Claude Agent SDK: Build Agents in Python and TypeScript
What is the Claude Agent SDK?
The Claude Agent SDK is Anthropic's library for Python and TypeScript that embeds Claude Code's agent loop, tools, permissions, hooks and sessions in your application. It starts the Claude Code binary as a child process on your machine and returns a stream of messages. In most cases you don't need to install Claude Code separately.
TL;DR
- -Packages as of November 29, 2026: claude-agent-sdk 0.2.189 (Python 3.10+, Alpha classifier) and @anthropic-ai/claude-agent-sdk 0.3.332 (Node 18.14+). Both ship Claude Code inside.
- -allowed_tools pre-approves calls and doesn't narrow the toolset. tools and disallowed_tools narrow it, dontAsk mode denies instead of prompting, and a PreToolUse hook with deny has the last word.
- -By default the SDK reads user, project and local settings. In the author's test a "Reply ok" request took 646 input tokens with tools=[] and setting_sources=[], and 16,356 with the default tools.
- -subtype=success doesn't mean the task is done: in the test a denied file write ended with success and is_error=False. Check permission_denials and the result itself.
- -The project CLAUDE.md didn't load for the author in the bundled CLI 2.1.332, although the docs promise it. The changelog gave no reason, so check loading after every update.
The Claude Agent SDK is Anthropic’s library for Python and TypeScript that embeds Claude Code’s agent loop, with its tools, permissions, hooks and sessions, in your application. The SDK starts the Claude Code binary as a child process and returns a stream of messages. Choose it when an agent needs files, commands and multi-step work. For a single model request, the Claude API is enough.
| Task | What to use | What you get |
|---|---|---|
| An agent inside your own application | Agent SDK | Claude Code’s loop and tools in your process |
| Terminal work, one-off tasks | Claude Code CLI | an interface, claude -p for scripts |
| A direct model call | Client SDK | you write the tool loop or use the beta runner |
| An agent on Anthropic’s side | Managed Agents | a cloud sandbox or your own, managed through an API |
The table condenses the comparison in the docs. For other languages they recommend running the CLI with -p and --output-format json.
This article covers how to install the SDK, build an agent, restrict it and avoid a surprising bill. The documentation and changelogs were checked on November 29, 2026. The author’s tests are from the same day: claude-agent-sdk 0.2.189, Python 3.13, bundled CLI 2.1.332, subscription login, Haiku 5.5, a folder with calc.py and CLAUDE.md, one run each unless stated otherwise. The author didn’t run TypeScript; everything about it comes from the documentation. The Python examples are simplified from the test scripts and checked for syntax and imports; dontAsk, ClaudeSDKClient and the subagent options in env weren’t run against a model. For building an agent from scratch, see the AI agent tutorial.
Install the Claude Agent SDK
# Python 3.10+
uv init && uv add claude-agent-sdk
# or: python3 -m venv .venv && source .venv/bin/activate && pip install claude-agent-sdk
# TypeScript, Node 18.14+
npm init -y && npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx
export ANTHROPIC_API_KEY=your-api-key
| Python | TypeScript | |
|---|---|---|
| Version on Nov 29, 2026 | 0.2.189 (Nov 25) | 0.3.332 (Nov 24) |
| Bundled Claude Code | 2.1.332 (measured) | 2.1.332 (npm metadata) |
| License in the registry | MIT | SEE LICENSE IN README.md |
| Required alongside | nothing | zod 4, @anthropic-ai/sdk, @modelcontextprotocol/sdk (peer) |
Version numbers differ between languages, so pin each one separately. The author’s Python environment took 397 MB because the CLI is inside. The earlier claude-code-sdk package was renamed, and ClaudeCodeOptions became ClaudeAgentOptions (migration guide).
Your first agent: query()
import asyncio
from claude_agent_sdk import (
AssistantMessage, ClaudeAgentOptions, ResultError,
ResultMessage, TextBlock, query,
)
OPTIONS = ClaudeAgentOptions(
model="haiku",
tools=["Read", "Glob", "Grep"],
allowed_tools=["Read", "Glob", "Grep"],
permission_mode="dontAsk",
setting_sources=[],
strict_mcp_config=True,
max_turns=10,
)
async def run(prompt: str) -> ResultMessage | None:
result = None
try:
async for m in query(prompt=prompt, options=OPTIONS):
if isinstance(m, AssistantMessage):
for block in m.content:
if isinstance(block, TextBlock):
print(block.text)
elif isinstance(m, ResultMessage):
result = m
except ResultError as e:
print("run failed:", e.subtype)
return result
Run it with asyncio.run(run("What does calc.py do?")). The same call in TypeScript:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const m of query({
prompt: "What does calc.py do?",
options: {
tools: ["Read", "Glob", "Grep"],
allowedTools: ["Read", "Glob", "Grep"],
permissionMode: "dontAsk",
settingSources: [],
strictMcpConfig: true,
},
})) {
if (m.type === "result") console.log(m.subtype, m.total_cost_usd);
}
A successful run isn’t a completed task
The author asked for a file to be created without granting permissions. The write was denied and there was no file, yet the result came back with subtype=success and is_error=False: the loop finished normally, and the model honestly reported the denial. Check three things: the subtype, the permission_denials list and the artifact itself (a file, a test, a database record).
On an error, a one-shot query() first yields a ResultMessage, then raises ResultError. In the test max_turns=1 produced error_max_turns and an exception. Without try the program crashes after it already has a useful result.
Conversations and sessions
| You need | Python | TypeScript |
|---|---|---|
| Several messages in one process | ClaudeSDKClient | streaming input to query() |
| Continue the folder’s latest session | continue_conversation=True | continue: true |
| Continue a specific one | resume=session_id | resume: sessionId |
| Branch from a session | resume=..., fork_session=True | forkSession: true |
from claude_agent_sdk import ClaudeSDKClient
async def dialog() -> None:
async with ClaudeSDKClient(options=OPTIONS) as client:
for prompt in ("List the functions in calc.py", "Which one fails on []?"):
await client.query(prompt)
async for m in client.receive_response():
if isinstance(m, ResultMessage):
print(m.result)
The Python reference asks you not to leave the message loop with break: it can cause asyncio cleanup issues. Take session_id from ResultMessage. In the test resume brought back a code word from the previous session.
According to the docs, a session is stored in ~/.claude/projects/<folder>/ on the machine where it was created. For another host, plug in a session_store or move the file. A fork copies the history, while working files stay shared.
Tools: built-in, custom, MCP
With default tools and setting_sources=[] the author’s session had 25 tools, with tools=[] none, with a custom server 26. Descriptions of loaded tools travel in every request, so the set affects both price and context:
| “Reply ok” request | Input tokens |
|---|---|
tools=[], setting_sources=[] | 646 |
| default tools | 16,356 |
You describe a custom tool as a function, and the server lives in your process:
import json
from claude_agent_sdk import create_sdk_mcp_server, tool
@tool("convert", "Convert USD to EUR", {"amount": float})
async def convert(args):
eur = round(args["amount"] * 0.92, 2)
return {"content": [{"type": "text", "text": json.dumps({"eur": eur})}]}
rates = create_sdk_mcp_server("rates", "1.0.0", [convert])
tool_options = ClaudeAgentOptions(
mcp_servers={"rates": rates},
allowed_tools=["mcp__rates__convert"],
setting_sources=[],
strict_mcp_config=True,
)
The name is built as mcp__server__tool. In the test the call was denied without allowed_tools and landed in permission_denials; with it the answer was 9.2. The model found the tool through ToolSearch. External servers use the same mcp_servers field; the protocol is covered in MCP servers explained.
The docs now describe the pattern mcp__rates__* as working; "*" and "mcp__*" in allowed_tools are ignored. The author didn’t run the patterns.
Permissions and hooks
Evaluation order
The documentation describes six steps: hooks, deny rules, ask rules, permission mode, allow rules, the can_use_tool callback. Each step can decide the call or pass it on.
| What you set | What it does | What it doesn’t do |
|---|---|---|
allowed_tools=["Read"] | approves calls in advance | doesn’t remove other tools, doesn’t limit bypassPermissions |
tools=[...] | sets the built-in toolset | doesn’t control MCP servers |
disallowed_tools=["Bash"] | removes the tool from the request | a Bash(rm *) rule doesn’t catch /bin/rm |
permission_mode="dontAsk" | denies where there would have been a prompt | doesn’t touch what needs no approval: reads in the folder, safe Bash commands, Agent |
can_use_tool | decides calls that reached the prompt stage | doesn’t see calls approved earlier |
PreToolUse hook | sees approved calls too, deny works even in bypassPermissions | allow doesn’t override deny rules |
The author’s tests confirm two rows: a hook with deny beat allowed_tools=["Bash"], and bypassPermissions together with disallowed_tools=["Bash"] didn’t run the command.
from claude_agent_sdk import (
HookMatcher, PermissionResultAllow, PermissionResultDeny,
)
async def deny_bash(data, tool_use_id, context):
return {"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Bash is disabled",
}}
async def guard(name, data, context):
if name == "Write" and not data.get("file_path", "").endswith(".md"):
return PermissionResultDeny(message="only .md files")
return PermissionResultAllow()
async def stream(text: str):
yield {"type": "user", "message": {"role": "user", "content": text}}
guarded = ClaudeAgentOptions(
can_use_tool=guard,
hooks={"PreToolUse": [
HookMatcher(matcher="Bash", hooks=[deny_bash], on_failure="block"),
]},
setting_sources=[],
)
# query(prompt=stream("Write notes.md"), options=guarded)
In Python can_use_tool needs a streaming prompt, and the docs add a hook that keeps the stream open. In the test the callback saw two Bash calls, and the denial on rm worked. The model had meanwhile merged creating and deleting the file into one command, so the file never appeared. Matching a command by substring is unreliable: for bans use the toolset and a sandbox.
Callback hooks live in your process. If a callback crashes, by default the call goes on as if no decision was made; on_failure="block" (since 0.2.177) turns the failure into a denial. Python has ten events, TypeScript has more, including SessionStart and InstructionsLoaded (table). Command hooks from settings.json are described in the Claude Code hooks guide. Permissions also protect against other people’s text in your data: see the article on prompt injection.
Isolation: what enters the session unasked
Settings: setting_sources
If the field isn’t set, the SDK reads what the CLI reads: user, project and local settings, CLAUDE.md files, skills, agents and commands. An empty list turns that off. The field’s description in package 0.2.189 recommends [] when the folder may not be yours: project settings can run hooks.
The author’s run with defaults brought up 63 tools, connected personal MCP servers, and answered an English question in Russian because the personal instructions say so. For a service on a server this is the worst kind of bug: the agent behaves differently on the developer’s machine than in production.
Connectors: strict_mcp_config
setting_sources=[] doesn’t close everything. The documentation lists sources that are read at any value: managed policies, ~/.claude.json, the project’s auto memory, and claude.ai connectors when you sign in through claude.ai. An empty mcp_servers doesn’t turn connectors off; for that there is strict_mcp_config=True, the disableClaudeAiConnectors setting and the variable ENABLE_CLAUDEAI_MCP_SERVERS=false.
In the author’s first series, connector tools got into the session in 2 runs out of 16: 157 and 209 tools. A “Reply ok” request cost $0.176 by the SDK’s estimate, against $0.0001 without them. In the second series (9 variants, 3 runs each) it never happened again, either with strict_mcp_config=True or without it. It looks like a startup race; the cause wasn’t established. So the author can’t call the flag a cure: it is documented, but the test didn’t confirm its effect. It’s safer to check the list at startup:
from claude_agent_sdk import SystemMessage
EXPECTED = {"Read", "Glob", "Grep"}
async def checked(prompt: str) -> None:
extra: set[str] = set()
async for m in query(prompt=prompt, options=OPTIONS):
if isinstance(m, SystemMessage) and m.subtype == "init":
extra = set(m.data["tools"]) - EXPECTED
if extra:
print("unexpected tools:", sorted(extra))
The check reports extras but doesn’t stop the run. If you need it to stop, use ClaudeSDKClient and its interrupt().
CLAUDE.md: the docs and the test disagree
According to the docs, setting_sources=["project"] loads CLAUDE.md from the working folder. The author’s file had one rule: end every answer with the word ZEBRA.
| Run | Instruction in context |
|---|---|
SDK, bundled CLI 2.1.332, ["project"] | no |
same with the claude_code preset | no |
| same with default sources | no |
SDK with cli_path to installed CLI 2.1.322 | yes |
claude -p 2.1.322 | yes |
The author read the Claude Code changelog from 2.1.323 to 2.1.332. Two entries concern delivering CLAUDE.md to the model: 2.1.332 fixes it being sent again after a move into a worktree, and 2.1.330 fixes link reference definitions being dropped from files with an HTML comment. Neither explains the gap. The file has no section for 2.1.324. The TypeScript SDK changelog for 0.3.323-0.3.332 doesn’t mention CLAUDE.md, the Python SDK changelog ends at 0.2.178, and GitHub releases 0.2.179-0.2.189 carry no description of changes. The cause wasn’t found. It may be a build bug or a quirk of the author’s environment: one machine, one model and one run each were tested.
In practice, check loading with a marker word after every SDK update. Per the reference, ClaudeSDKClient.get_context_usage() returns a memoryFiles list. If the rules are mandatory, pass the text explicitly. The author didn’t run this variant against a model:
from pathlib import Path
explicit = ClaudeAgentOptions(
setting_sources=[],
system_prompt={
"type": "preset",
"preset": "claude_code",
"append": Path("CLAUDE.md").read_text(encoding="utf-8"),
},
)
What to put in the file is covered in the CLAUDE.md guide. The preset here isn’t accidental: without system_prompt the SDK uses a minimal prompt which, according to the docs, omits Claude Code’s security and safety instructions.
Several tenants on one host
The docs warn that default query() options don’t provide multi-tenant isolation. Their recipe: a separate filesystem per tenant, setting_sources=[] and CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 in env. That doesn’t turn off an organization’s server-managed policies.
Subagents
from claude_agent_sdk import AgentDefinition
with_agent = ClaudeAgentOptions(
allowed_tools=["Agent", "Read"],
agents={"reader": AgentDefinition(
description="Reads files and summarizes them",
prompt="Read the file and summarize it in one sentence.",
tools=["Read"],
model="haiku",
)},
env={"CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH": "1"},
setting_sources=[],
)
In the test Agent and Read were called. From its parent a subagent receives only the prompt string, and the parent gets the final result back. The defaults are a depth of 3 levels and 20 concurrent subagents. AgentDefinition fields in Python are camelCase (disallowedTools, maxTurns). When a subagent pays off is covered in the article on Claude Code subagents.
Structured output
The field output_format={"type": "json_schema", "schema": {...}} asks for an answer that follows JSON Schema draft-07, and the result is in structured_output. The author got {'functions': ['mean'], 'handles_empty': False}, with a service call to StructuredOutput visible in the stream. If the model doesn’t fit the schema after retries, the subtype is error_max_structured_output_retries. A schema checks the shape; check the meaning yourself. For a comparison of modes, see the article on structured output.
Cost and limits
total_cost_usdis a client-side estimate from a built-in price table. The docs ask you not to bill users by it.usagecounts the main loop without subagents. For accounting usemodel_usage. In streaming mode the totals are cumulative, so you need the last result.max_turnsisn’t set by default. Without it a session can run for a long time.max_budget_usdis checked after a turn. In the test a $0.0005 limit gaveerror_max_budget_usdat an estimate of $0.0012: 2.4 times over. Set a hard ceiling in the Console.
The SDK turns prompt caching on by itself; how it works is covered in the article on prompt caching.
Hosting
Each agent is a separate process with state on disk. The documentation gives a starting estimate of 1 GiB of memory, 5 GiB of disk and 1 CPU and calls it a floor: memory grows with session length. A minimal container costs roughly $0.05 an hour, and tokens usually cost an order of magnitude more. Keep secrets outside: a proxy puts the key into the request, and the agent doesn’t see it (secure deployment). The author didn’t measure memory or load.
Subscription, API key and products for others
| Run | What is charged |
|---|---|
| SDK with a subscription login | plan limits |
| SDK with a key from an organization linked to Max, Ultra, or Team | monthly API credits, then purchased ones |
| SDK with an ordinary Console key | API balance |
Source: Help Center, updates dated October 7 and June 15, 2026; the math is in subscription or API. In a product for other people you can’t offer claude.ai login or its rate limits without Anthropic’s approval; the docs require an API key. Use of the SDK is governed by the Commercial Terms, except components with their own license. You can’t use the name “Claude Code” in your product, but “Powered by Claude” is allowed.
Where to start
- Pin the package version and write down the bundled CLI version.
- Start with read-only
tools,dontAsk,setting_sources=[]andstrict_mcp_config=True. - Compare the tool list in the init message with the expected one.
- Check
permission_denialsand the artifact, not justsubtype. - Set
max_turnsandmax_budget_usd, allowing for the overshoot. - Check that CLAUDE.md loads with a marker, or pass the text through
append. - Before production, move the agent into a container with a restricted network.