The Claude Agent SDK does not reimplement Claude Code: your program starts the Claude Code binary as a child process, turns your options into its command-line flags, and answers its questions (permission checks, hooks, your own tools) as JSON lines on the same pipe. Everything else, the loop, the context, compaction, the built-in tools and the session file, stays in the child.
Fig. 1 replays run s1 (Haiku 4.5, our four tools, a hook and a permission callback) from its recorded wire, in seven stretches. Green dots are lines your process writes down stdin, purple ones are questions to your process coming up stdout, blue ones are conversation messages relayed up, orange ones are model calls over HTTPS.
--output-format stream-json --input-format stream-json plus one flag per option; the child alone talks to the Anthropic API. One session is one child process.initialize with the ids of its hook callbacks; Claude Code opens your in-process MCP server with three questions (initialize, initialized, tools/list); your answers and the prompt go down (5 lines), the init record comes up.hook_callback), which answers allow, so can_use_tool is never asked; tools/call list_files runs your function in your process; the PostToolUse hook runs; the result is relayed. Three questions, three answers, 14 ms.{} (no objection) and nothing else settles the call, so Claude Code asks your can_use_tool; you allow; tools/call run_tests returns two FAILs. Four questions, four answers.result: success after 5 model calls, $0.0215 at list prices. In all, 30 lines went down stdin and 53 came up stdout, of which 28 were questions to your process; section 1 counts them by kind and lets you read every line.You need: the agent loop itself (model call, tool call, tool result, repeat), taught from zero on Topic: agentic-harnesses (tab Loop lab); what the Claude Code process does with its tools, permission rules, hook events, memory files and headless runs, on Claude Code, taken apart; and, for in-process tools, what an MCP server is (MCP). This page owns the library: what your code controls, what it costs, and how it compares with writing the loop yourself or with the frameworks on Topic: agentic-frameworks.
control_request with a request id, answered by a control_response that echoes it.can_use_tool| Piece | What it is | Seen in run |
|---|---|---|
query(prompt, options) | Start one Claude Code process, send the prompt, iterate over the messages it streams back until a result message. | s1, s3, s5, s6 |
ClaudeSDKClient (Python) | Keep one process open across several turns; ask it things between turns (context usage, interrupt, rewind files). | s4, s9 |
ClaudeAgentOptions | 49 fields in Python 0.2.163, 69 in TypeScript 0.3.291; most become command-line flags of the child process. | Options lab |
@tool + create_sdk_mcp_server | Your Python functions as tools, served by an MCP server that lives inside your process. | s1, s2, s4, s6, s8 |
can_use_tool, hooks | Your functions in the permission decision and at fixed points (10 hook events in Python, 33 in TypeScript). | s1, s2 |
agents | Subagents defined in code, each with its own prompt, tools and model. | s5 |
resume, fork_session, rewind_files | Continue a saved conversation, branch it, or put edited files back. | s4, s9 |
output_format | A JSON schema the final answer must match, returned parsed. | s6 |
The running example, used by every run: the textstats repository with two planted bugs (tokenize drops apostrophes, top_words ignores ties), fixed by Haiku 4.5 unless stated; all runs recorded on 6 October 2026 and listed in the Recordings tab. Two lessons carry the page: defaults are not safe defaults (section 3), and "success" is not "done": our bare run ended with subtype: "success", six refused tool calls and both tests still failing.
The problem. Claude Code is a terminal program. To put its agent inside your own service (a support bot, a code-review job, a research agent) you either rebuild the loop, tools, permissions and context management yourself (Building a harness shows what that takes) or drive Claude Code from code. Anthropic shipped the second option as the Claude Code SDK and renamed it the Claude Agent SDK on 29 September 2025, because "the agent harness that powers Claude Code ... can power many other types of agents, too" (Anthropic, Thariq Shihipar, 29 Sep 2025) DOCS.
How it works. The Python wheel carries a whole Claude Code binary (_bundled/claude, 225,167,728 bytes on macOS arm64 for 0.2.163, which pins Claude Code 2.1.286); the TypeScript package pulls a platform package with its own binary (233,211,568 bytes, Claude Code 2.1.291 for SDK 0.3.291: the TypeScript version 0.3.N ships Claude Code 2.1.N) MEASURED. The SDK starts it with --output-format stream-json --verbose --input-format stream-json plus one flag per option you set, and sets CLAUDE_CODE_ENTRYPOINT=sdk-py and CLAUDE_AGENT_SDK_VERSION in its environment; from then on both sides write one JSON object per line. The docs: "One agent session maps to one subprocess" (Hosting the Agent SDK) DOCS.
Two kinds of lines share the pipe. Messages are the conversation: the system/init record, assistant messages, tool results and the final result. Control messages are the side channel: your process sends initialize (your hook callback ids and subagent definitions), interrupt, set_permission_mode and a few more; the Claude Code process sends can_use_tool, hook_callback and mcp_message (a JSON-RPC message for an MCP server inside your process) SOURCE. In run s1 the Claude Code process asked our process 28 questions in 15.8 seconds: 14 hook calls, 4 permission questions and 10 MCP messages (initialize, the initialized notification, the tool list, 7 tool calls) MEASURED.
The replay beside this text holds every line of s1 and of s3. Predict first: in s3 nobody registered a hook, a callback or a tool. After initialize, how many lines will your process send? Then switch to s3 and step through. The replay opens on s1's first permission question and does not play by itself: reading the lines is the point, and Fig. 1 already plays the run.
What follows. Your callbacks are in the critical path of every tool call: a slow can_use_tool or hook slows the agent, and an exception in one comes back to Claude Code as an error response. The model, the context window, compaction, the tool implementations of Read, Edit and Bash, and the session file all live in the child; your process sees them only as messages. So the answer to "how does the SDK do X" is almost always "Claude Code does X; the SDK passes a flag".
The Python transport looks for the bundled binary first, then claude on the PATH, then a few fixed install locations; cli_path overrides all of that (_internal/transport/subprocess_cli.py, 0.2.163) SOURCE. The docs say it plainly: "When your code calls query(), the SDK spawns a separate claude CLI process and talks to it over stdio" (hosting).
| Subtype | Direction | Meaning |
|---|---|---|
initialize | you to Claude Code | First line: hook callback ids per event and matcher, subagent definitions, skill filter. The answer lists commands, agents, the permission mode. |
mcp_message | Claude Code to you | A JSON-RPC message for an MCP server living in your process: initialize, tools/list, tools/call. |
hook_callback | Claude Code to you | Run hook hook_N with this input; your answer can allow, deny, rewrite or add context. |
can_use_tool | Claude Code to you | A tool call nothing else settled: allow (optionally with changed input) or deny with a message. |
interrupt, set_permission_mode, set_model, rewind_files, get_context_usage, MCP management | you to Claude Code | Control a running session (not in s1 or s3; get_context_usage and rewind_files are in s4 and s9). |
Left out of the replay: thinking-progress and session-state notices, rate-limit events, and from the initialize answer everything but the permission mode, the hook flag, the session state and the built-in agent names (it also carries the account, the model list and local paths); each body is shortened to 700 characters.
Source: types.py and _internal/query.py of claude-agent-sdk 0.2.163; we found this wire format described only in the SDK source, not in the documentation pages we read, so treat it as an implementation detail that may change between versions.
An infrastructure analogy from the old version of this page still helps: Claude Code is a managed runtime in which hooks are middleware, subagents are worker processes with private memory, MCP is the driver interface, permissions are the security policy and skills are lazy-loaded configuration.
Every line that crossed the pipe, captured by a stand-in for the binary that copies each line to a log before passing it on (src/code/wire.py), then redacted. s1: 83 lines; s3: 64 lines, only 2 of them from your process (the prompt and initialize), so every question Claude Code would have asked became a refusal. Times are seconds since the stand-in started (what was left out: the depth block below).
query() and ClaudeSDKClientquery() starts one Claude Code process, sends the prompt and yields messages until the result. The prompt is a string or an async iterator of user messages (streaming input), which the docs call "the preferred way": the string form lacks image attachments, queued messages, interruption and natural multi-turn conversation (streaming vs single message) DOCS. Our runs with a permission callback stream the prompt as a one-message iterator, as the docs' examples do. What comes back is the conversation plus a final ResultMessage carrying subtype, total_cost_usd, usage, model_usage and permission_denials (section 9 says how to read them).
The messages your loop receives (types.py, 0.2.163) SOURCE: SystemMessage (the init record with model, tools, permission mode and Claude Code version; also permission_denied and progress notices), AssistantMessage (one per content block, all blocks of one model call sharing a message_id), UserMessage (tool results), Task*Message (subagent started, progress, finished), RateLimitEvent, and the final ResultMessage with subtype, num_turns, total_cost_usd, usage, model_usage, permission_denials and structured_output. With include_partial_messages=True you also get the raw token stream.
query() is not stateless. Every call writes its conversation to ~/.claude/projects/<encoded working directory>/<session id>.jsonl (sessions) DOCS; our recordings left 15 session transcripts there (9 KB to 567 KB; the two largest came from the connector measurements of section 9), plus two subagent transcripts in a subfolder of run s5's session; we measured and deleted them MEASURED. In a container that file is lost on restart; on a shared host it is a data-retention question. TypeScript has persistSession: false; Python 0.2.163 has no such option (its extra_args can pass the command line's --no-session-persistence flag: not run here).
ClaudeSDKClient (Python only; TypeScript uses a streaming prompt and continue) keeps one Claude Code process open: client.query() sends the next turn, receive_response() reads until that turn's result, and between turns you can call get_context_usage(), interrupt(), set_permission_mode(), set_model() or rewind_files() SOURCE. Run s4 (section 7) used it for two turns, then resumed and forked the saved session. Interrupting a running turn is recorded on Building a harness: the SDK's interrupt() made Claude Code write a refused tool result and end with error_during_execution.
ClaudeAgentOptions has 49 fields in Python 0.2.163; TypeScript's Options has 69 (it adds, among others, persistSession, abortController, spawnClaudeCodeProcess, managedSettings and dialog hooks) SOURCE. Most become one flag of the child (model to --model, max_turns to --max-turns); subagents, skills and hook ids go in the initialize request instead. The Options lab rebuilds the mapping from _build_command() so you can see the exact command for any choice, checked against the commands our runs started. What matters is what you get when you set nothing:
subtype: "success" after 14 model calls, but 6 of its 16 tool calls were refused: 3 Bash calls ("This command requires approval", including the plain python3 tests/test_core.py) and all 3 edits ("Claude requested permissions to write to /work/textstats/core.py, but you haven't granted it yet."). Nobody was there to answer "ask", so ask became deny. Its final answer found both bugs and asked: "Please approve the file edits". Tests after: 2 failed. Cost: 247,863 input tokens processed, $0.0867 at list prices, against $0.0215 for run s1, which fixed both bugs MEASURED. subtype says the loop ended normally, not that the task was done: check permission_denials and run your own test.The four defaults to know by heart SOURCE DOCS:
system_prompt=None sends --system-prompt "". Since v0.1.0 "The SDK no longer uses Claude Code's system prompt by default"; ask for it with {"type": "preset", "preset": "claude_code"}, optionally with "append" (migration guide). It costs context: about 6,200 tokens on Haiku in the frameworks root's runs (7,612 against 1,388).tools=None adds no flag, so you get the default list; ours had 29 tools (Read, Edit, Write, Bash, WebFetch, WebSearch, Skill, the subagent tool and the task tools among them; Glob and Grep absent, as Claude Code, taken apart found on macOS) MEASURED. tools=[] removes them all.setting_sources=None reads user, project and local settings, "matching the CLI": your ~/.claude/settings.json, its hooks, CLAUDE.md files, skills and commands. Pass [] to isolate.strict_mcp_config=True, servers from .mcp.json, settings and plugins load, and with a claude.ai login so do the account's connectors, which the docs list among things "read regardless of settingSources" (Claude Code features in the SDK). Section 9 shows one call that cost 128,306 input tokens because of it.The fix is a decision about who answers "ask": a mode (acceptEdits approves file edits and simple file commands in the working directory; dontAsk turns every unresolved ask into a deny, which makes an allow-list exact), allow rules (allowed_tools=["Bash(python3 tests/test_core.py)"]), or your own can_use_tool. Section 5 shows the order in which these are consulted. A service-ready start passes setting_sources=[], strict_mcp_config=True, an explicit tool list and one of those answers (the Options lab's last preset).
| Group | Python options | Becomes |
|---|---|---|
| Model | model, fallback_model, thinking, effort, betas | --model, --fallback-model, --thinking, --effort, --betas |
| What the model sees | system_prompt, tools, mcp_servers, strict_mcp_config, agents, skills, plugins, setting_sources | --system-prompt or --append-system-prompt, --tools, --mcp-config, --strict-mcp-config, --setting-sources; agents and skills go in the initialize request |
| What it may do | permission_mode, allowed_tools, disallowed_tools, can_use_tool, hooks, sandbox, add_dirs, cwd | --permission-mode, --allowedTools, --disallowedTools, --permission-prompt-tool stdio, --settings, --add-dir |
| Limits | max_turns, max_budget_usd, task_budget | --max-turns, --max-budget-usd, --task-budget |
| Sessions | resume, continue_conversation, fork_session, session_id, resume_session_at, enable_file_checkpointing, session_store | --resume, --continue, --fork-session, ... |
| Output | output_format, include_partial_messages, include_hook_events | --json-schema, --include-partial-messages, --include-hook-events |
| Process | cli_path, env, extra_args, stderr, settings | which binary, its environment, any other flag |
History of the settings default: a short-lived v0.1.0 change to load nothing "was briefly changed ... and then reverted" (migration guide); Python 0.1.59 and earlier treated [] as "not given" DOCS.
Run s1 passes our four tools, a short system prompt, a hook and a callback; run s3 passes only isolation (setting_sources=[], strict_mcp_config=True) and a one-line system prompt in place of the empty default, so it gets Claude Code's 29 default tools, permission mode default and nobody to answer "ask". The first call grew from 1,390 tokens with our prompt and tools to 14,703 with the defaults; both runs ended "success" MEASURED.
A tool reaches the model from one of three places, and where it runs decides what it can touch and how it fails.
@tool("read_file", "Return the text of one file.", {"path": str})
async def read_file(args):
return {"content": [{"type": "text", "text": open(args["path"]).read()[:20000]}]}
repo = create_sdk_mcp_server("repo", tools=[list_files, read_file, edit_file, run_tests])
options = ClaudeAgentOptions(mcp_servers={"repo": repo}, tools=[], ...)
On the wire (run s1) MEASURED: before the first model call the Claude Code process opened our server with an MCP initialize (protocol version 2025-11-25, client name claude-code), sent initialized and asked for tools/list; the SDK had turned {"path": str} into {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}. Each tool call was then one tools/call round trip: 1 to 5 ms for the file tools, 26 and 36 ms for the two test runs (which start Python). No extra process, no port, no serialisation beyond JSON lines; the four definitions cost 258 tokens of context (section 7). In-process tools ask for permission like any other tool. The MCP protocol itself is taught on MCP.
(custom tools, MCP, tool search) DOCS: return is_error for a failure the model should see; annotations such as readOnlyHint let read-only tools run in parallel but "are metadata, not enforcement"; stdio and in-process servers may delay the first turn by up to MCP_TIMEOUT (30 s by default); tool search is on by default, because "50 tools can use 10-20K tokens" and selection "degrades with more than 30-50 tools loaded at once", and it is switched off when ANTHROPIC_BASE_URL points to a host that is not Anthropic's.
Built-in (tools=["Read", "Edit", "Bash"], or the default set): inside Claude Code, with its limits (the Read cap, the Bash output cap: see Claude Code, taken apart, section 2). In-process: your @tool functions wrapped by create_sdk_mcp_server("repo", tools=[...]) and passed in mcp_servers; each call comes to you as an mcp_message on the pipe, named mcp__repo__read_file. Outside MCP server: {"type": "stdio", "command": ...}, {"type": "http", "url": ...} or a project .mcp.json; a separate process or a remote service that Claude Code connects to itself.
Every tool call passes a permission check run by the Claude Code process, in a fixed order: (1) hooks, (2) deny rules ("even in bypassPermissions mode"), (3) ask rules (these go to your callback even in bypass mode), (4) the permission mode, (5) allow rules (including calls a tool approves on its own, such as reading a file in the working directory), (6) your can_use_tool callback; in dontAsk mode step 6 is skipped and the call is denied (configure permissions) DOCS.
Fig. 2 sends every recorded tool call through the six stages; the stage that settled each one is read from the recording (hook output, callback log, refusal text); stages before it were passed, stages after it never ran. Predict first: in s1 our hook allows the two read-only tools. How many of s1's 7 calls will reach the callback? Then try s2, where the callback says no once, and s3, where nobody answers.
can_use_tool (green: your code); stages 2 to 5 are Claude Code's deny rules, ask rules, permission mode and allow rules (none set here, mode default).list_files and both read_file calls stop at stage 1: our hook answers permissionDecision "allow" ("read-only tool"), so nothing after it runs and the callback never sees them.{}, no rule matches, mode default passes everything on) and our callback allows them.tests/, with the same hook and a callback that makes tests/ read-only.list_files and three read_file calls stop at stage 1.textstats/core.py.tests/test_core.py: the callback answers deny with its message, which goes back to the model as an error tool result.ls -la and find . -type f, and a skill pass at stage 5: a tool may approve a call on its own inside the working directory.python3 tests/test_core.py runs among them) and all three edits reach stage 6; with no callback, "ask" becomes deny, and each refusal goes back to the model.subtype: "success" with both tests failing.Two consequences. "Auto-approved tools never reach canUseTool", so a callback is not an audit log: log in a PreToolUse hook, which runs for every call. And a hook that returns allow still cannot override a deny rule; the SDK source adds that a PreToolUse hook returning allow "also skips" the callback, and that setting can_use_tool makes the SDK pass --permission-prompt-tool stdio so the questions come down the pipe SOURCE.
The callback returns allow (optionally with changed input) or deny with a message (signature in the depth block below). Run s2 asked for a fix and a new regression test in tests/, while our callback made tests/ read-only with the message "tests/ is read-only for this agent. Describe the test you would add in your final reply instead." The model received that sentence as an error tool result, did not try another route, and ended: "I was unable to edit the test file as it's read-only. However, I have successfully fixed the code." Tests passed and the test file was unchanged MEASURED. The callback may wait as long as you like (for a human on Slack, say); for very long waits the docs suggest a hook that returns defer so the process can exit and the session resume later (user input) DOCS.
Hooks as callbacks. hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[fn])]} registers fn; the SDK gives each function an id (hook_0, hook_1) in the initialize request and the Claude Code process calls it back with hook_callback SOURCE MEASURED. A PreToolUse callback can answer permissionDecision allow, deny, ask or defer, rewrite the input (updatedInput) or add context; PostToolUse can replace the tool's output. Several matchers on one event run concurrently, so do not rely on their order (docstring of hooks, 0.2.163). Python supports 10 events, TypeScript 33 (list in section 11); in Python, SessionStart and SessionEnd exist only as shell hooks in settings files, which also run if setting_sources loads them (hooks) DOCS. What each event means, and a hook that blocks, are on Claude Code, taken apart (section 4).
async def can_use_tool(tool_name, input, context) returns PermissionResultAllow(updated_input=..., updated_permissions=...) or PermissionResultDeny(message=..., interrupt=False); context carries the tool-use id, a suggested rule, the blocked path, a reason and a ready-made prompt sentence (title) for a human approval screen SOURCE.
A permission callback sees the tool's arguments, not what a command will do: python3 -c "..." passes any rule written about file paths. Run the agent where it cannot hurt you (the sandbox option for Bash, a container, a VM); the hosting docs compare sandbox-runtime, Docker, gVisor and Firecracker VMs (secure deployment) DOCS. Gate and sandbox design are taught on Agent security and Containers and isolation.
A subagent is a second agent loop with its own system prompt, tools, model and context window; the main agent starts one through the Agent tool (the init record still lists it as Task, an alias kept for compatibility) and receives only its final message (subagents) DOCS MEASURED. In the SDK you define them with agents={"test-runner": AgentDefinition(...)}: description (when to use it) and prompt are required; tools, model and maxTurns are the optional fields that matter most (full list below) SOURCE. The docs add: subagents run in the background by default; the parent passes only the Agent tool's prompt string, not its history; defaults allow 3 levels of nesting and 20 concurrent subagents, with no spend limit unless you set max_budget_usd DOCS.
What the lanes show. The subagent ran the allowed command, got the failures, then asked for more detail three times with variants (-v 2>&1, python3 -m pytest ..., a redirect to a file); each was refused because an allow rule matches the command it names, not its relatives. It hit its 4-turn cap with no report, and Claude Code told the main agent: "this agent stopped at its 4-turn limit before finishing ... Send the agent a message (SendMessage)". The main agent tried; SendMessage was "disabled for this session". It then read the files itself with one read-only shell command, made both edits, and delegated again; the second subagent ran one command and reported "0 failed". Each refusal is a wasted model call: when the action is known, a tool of your own (run_tests) beats a shell rule.
Counting subagents. Cost split by model in model_usage: Haiku $0.0228, Sonnet $0.0625, total $0.0852. The result's usage counted 33,906 input tokens, model_usage 65,602: usage leaves the subagent out, as the docs' table says ("Excluded. Counts only the top-level agent loop").
AgentDefinition field, and how subagent messages arriveOptional fields: tools, disallowedTools, model, skills, memory, mcpServers, initialPrompt, maxTurns, background, effort and permissionMode (Python keeps the camelCase spelling of the wire format). Subagent messages arrive in your stream with parent_tool_use_id set to the Agent call's id, plus task_started, task_progress and task_notification system messages; their text and thinking are forwarded only with forward_subagent_text=True SOURCE.
When several agents help and when they hurt is the subject of Multi-agent patterns, which cites this s5 run and measures lead-plus-subagents against one agent on a 48-module audit; it also notes from the agent teams docs that in -p and Agent SDK sessions Claude does not spawn teammates. Subagents as a context-isolation tool, with a measured window saving, are on Context engineering.
Every tool call of run s5 on its lane, at its recorded time (filled: ran; cross: refused by the permission check; hollow: the tool did not exist for this session; shaded: the subagent's lifetime): Sonnet 5.5 as the main agent, told to delegate every test run to a Haiku test-runner with only Bash, maxTurns=4, background=False; permission mode acceptEdits with the single allow rule Bash(python3 tests/test_core.py) MEASURED.
A session is the saved conversation of one Claude Code process: a JSONL file under ~/.claude/projects/<encoded cwd>/ (or $CLAUDE_CONFIG_DIR/projects/). The SDK reaches it four ways (sessions) DOCS: keep the process open (ClaudeSDKClient); continue_conversation=True (the most recent session in that directory, no id needed); resume="<id>"; or resume plus fork_session=True (a copy under a new id), optionally cut at a message with resume_session_at.
Fig. 3 is run s4 MEASURED (Haiku 4.5, our four tools): three processes on one saved history. The columns in front are the result message's total_cost_usd after each phase (reported), stacked as earlier spend in grey plus the part that phase added (own, the difference).
ClaudeSDKClient starts one Claude Code process and sends "run the tests, change nothing"; the transcript goes into session-1.jsonl as it happens. Reported cost $0.0123.get_context_usage() on the open process: 2,572 tokens in use, split into system prompt 56, MCP tools 258 (list_files 51, read_file 58, edit_file 96, run_tests 53) and messages 2,258, with autocompaction set for 167,000 of Haiku's 200,000; a long session compacts as Claude Code does (taught on Context engineering).resume="<id>" starts a new process that reads the whole file back and fixes the rest under the same session id. It reports $0.0409, because "A call that resumes a session also counts the session's earlier spend" (cost tracking) DOCS; its own part is $0.0162.resume plus fork_session=True reads the same history and writes a new file: same session id after resume, a new one after the fork. It answered from the full history ("Both failures have been fixed"), so the original session can continue separately. Reported $0.0424, own $0.0015.total_cost_usd and model_usage are running totals, across turns of one client and across later processes that resume the session, while usage covers only the last turn. Adding the four reported totals would give $0.1203, almost three times the real $0.0424.Helpers list, read, rename and tag sessions (list_sessions(), get_session_messages()), and a session_store mirrors every transcript line to storage you choose, so a fresh container can resume a session written by another (the "hybrid" hosting pattern, section 10).
File checkpointing is the undo button. With enable_file_checkpointing=True (and extra_args={"replay-user-messages": None} so user messages come back with their ids), Claude Code backs up each file before its built-in Write, Edit or NotebookEdit tools change it, and client.rewind_files(user_message_id) restores the files to that point. Bash changes and subagent edits are not tracked (file checkpointing) DOCS; by the same logic, edits made by your own in-process tools are not either (our reading of the docs, not run).
Run s9 MEASURED: tests before the agent "2 failed"; after the agent (Read, Edit and Bash, acceptEdits, one exact allow rule) "0 failed"; after rewind_files() to the prompt's checkpoint "2 failed" again, with one 457-byte backup written under ~/.claude/file-history/<session id>/. Rewinding restores files, not the conversation: the model still remembers its fix.
The same run shows Haiku making six refused attempts to test in other forms (python tests/test_core.py instead of python3, plus four inline test scripts), while python3 tests/test_core.py 2>&1 || true was allowed: Claude Code checks each part of a compound command separately, as its refusals say ("contains multiple operations. The following part requires approval"). The run cost $0.0773 against $0.0215 for s1.
output_format={"type": "json_schema", "schema": {...}} asks for a final answer that matches a JSON schema; the result message carries it parsed in structured_output. The SDK passes the schema as --json-schema, and Claude Code adds a tool named StructuredOutput whose input is the answer SOURCE MEASURED. The docs: the SDK "validates the output against it, re-prompting on mismatch", gives up with subtype error_max_structured_output_retries, checks schemas as JSON Schema draft-07, and before Claude Code 2.1.205 silently ignored an invalid schema (structured outputs) DOCS.
Run s6 (the textstats task with a schema of changes and a tests_passing flag) returned the object above MEASURED. The extra tool cost 181 tokens on the first call (1,571 against 1,390 in s1). How other libraries force structure (a hidden output tool in Pydantic AI, native JSON schema modes) is compared on Typed agent libraries, whose Claude runs use claude -p --json-schema: the same StructuredOutput route that output_format takes, so its comparison of a schema in the prompt against --json-schema is the one to read for this option.
Every result message carries total_cost_usd and, per model, model_usage (input, output, cache read and cache write tokens, and a cost). These "are client-side estimates, not authoritative billing data", computed "from a price table bundled at build time"; "Do not bill end users or trigger financial decisions from these fields" (cost tracking) DOCS. On a subscription, as here, nothing is billed per token: the figure is what the same tokens would cost at API list prices.
Rules for counting, each confirmed in our recordings MEASURED DOCS:
AssistantMessage objects, one per content block, all of a call sharing its message_id and its usage; count each id once ("Track which IDs you've already counted").usage is the last turn of the main agent only; total_cost_usd and model_usage include subagents (s5) and earlier turns and resumed sessions (s4). The cost of one turn of a long session is the difference of consecutive totals.model_usage contains a call the stream never shows. In every new session, model_usage exceeded the sum of streamed calls by one small Haiku call: 916 input tokens (930 in s2) and about 10 output tokens; not on resume or fork. Its purpose is not visible; a session-title request is our guess UNCONFIRMED.max_budget_usd and max_turns map to Claude Code's flags; both stop after the call that crosses them (measured on Claude Code, taken apart, section 11).total_cost_usd of each recorded run (s4: the last reported total, which includes all four phases). Every one reproduces exactly as model_usage tokens x list prices (Haiku 4.5 $1 input, $5 output, $0.10 cache read, $2 per million for 1-hour cache writes; Sonnet 5.5 $2, $10, $0.20, $4), with one twist: in s5 the subagent's cache writes match only at the 5-minute price ($1.25), the main thread's at the 1-hour price, as the Claude Code child also found.
With a claude.ai login, an SDK run that leaves strict_mcp_config off can be given the account's connected apps as MCP tools. We measured it with a one-word task ("Reply OK.", Haiku 4.5, tools=[], setting_sources=[], one turn), keeping only counts: no tool or server name was stored anywhere MEASURED.
Two lessons. The cost: one "OK" cost $0.257 at list prices instead of $0.0008, because 128,296 tokens of tool definitions were written to the 1-hour cache. And the non-determinism: the identical non-strict call loaded nothing in batch 1, 165 tools in batch 2, and 122 tools (with our own server present) a minute later; connectors connect while the session starts, so how many arrive before the first call varies. We did not find out more than that. With strict_mcp_config=True it was 0 extra servers every time (3 of 3). The frameworks root met the same pitfall in its first SDK run.
Input tokens of the single model call (fresh + cache write + cache read). Same machine, same account, 6 October 2026; batch 1 and batch 2 were minutes apart.
Authentication. The SDK reads an API key (ANTHROPIC_API_KEY) or a cloud provider switch: CLAUDE_CODE_USE_BEDROCK=1, CLAUDE_CODE_USE_VERTEX=1, CLAUDE_CODE_USE_FOUNDRY=1, CLAUDE_CODE_USE_ANTHROPIC_AWS=1 (Claude Platform on AWS) (overview) DOCS. Our recordings ran on a personal Claude subscription (the init record says apiKeySource: "none"), which is fine for personal experiments; a product is not: "Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Use the API key authentication methods described in the Quickstart instead." (same page) DOCS.
Hosting patterns. Because "One agent session maps to one subprocess" that "owns a shell, a working directory, and session files on disk", the hosting page lists four patterns (hosting) DOCS:
| Pattern | Shape | Fits |
|---|---|---|
| Ephemeral | A container per task, destroyed at the end | "bug investigation and fix, invoice and receipt extraction, document translation" |
| Long-running | Persistent containers, often several SDK processes each | email agents, chat bots, per-user site builders |
| Hybrid | Ephemeral containers that load the session from a SessionStore and write it back ("the store is required") | conversations that sit idle between turns |
| Multi-agent container | Several SDK processes in one container | agents that must collaborate closely |
Sizing starts at "1 GiB RAM, 5 GiB disk, and 1 CPU per agent"; a small container costs "roughly $0.05 per hour, while a single long agent session can spend dollars in tokens"; pin a session to one container by hashing its id; the subprocess needs outbound HTTPS to the API and "does not listen on the network". For several customers on one host the docs ask for setting_sources=[], CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, a separate CLAUDE_CONFIG_DIR and working directory per tenant, and per-tenant egress rules; "Do not rely on default query() options for multi-tenant isolation." Known gaps: no top-level session timeout, memory growth in long sessions, no per-subagent deadline DOCS.
Observability. "The SDK does not produce telemetry of its own": set CLAUDE_CODE_ENABLE_TELEMETRY=1 and OpenTelemetry exporters in the child's environment and Claude Code emits metrics, log events and (beta) spans named claude_code.interaction, claude_code.llm_request, claude_code.tool; the SDK passes the active trace context down so they join your trace (observability) DOCS. Two findings measured on LLM observability carry over because the SDK starts Claude Code itself: trace context joins through the environment, and the account's identity is on every span by default (details below).
A TRACEPARENT in the child's environment parents claude_code.interaction under the caller's span, Bash subprocesses inherit it, and user.email, user.id, user.account_uuid, user.account_id and organization.id are on every span by default (45 of 45), so filter them before traces leave your network MEASURED. The span tree is also recorded on the frameworks root's Production stack tab.
Python or TypeScript. Run s8 is run s1 rewritten in TypeScript (zod schemas, the same hook and callback) MEASURED: same fix, 6 model calls, $0.0247. Its first call was 1,566 tokens against 1,390 in Python, because the TypeScript package bundled the newer Claude Code (2.1.291 against 2.1.286): the context belongs to the binary, not to the language. Other differences: TypeScript has 33 hook events to Python's 10, persistSession, an AbortController, and 69 options; Python has ClaudeSDKClient; TypeScript's env replaces the child's environment while Python's merges into it (subagents) DOCS.
| You inherit (Claude Code does it) | You pay |
|---|---|
| The loop, compaction near the limit, the six-step permission order, subagents, sessions with resume, fork and file rewind, structured output with retries, built-in file and shell tools | A process per session: a 225 MB binary per install, "1 GiB RAM ... per agent" as a floor, a session file on disk |
| Claude Code's tuning (its tools, refusal messages, caching rules) as it improves with each release | Claude Code's context: the first call grew from 1,390 tokens to 14,703 with the default tools (section 3), and a version bump moved it by 176 tokens (s8) |
| Hooks and callbacks at every decision point | No control over the loop: you steer with options, hooks and callbacks; the wire between them is described only in the SDK source and may change with versions |
| Bedrock, Vertex, Foundry and Claude Platform on AWS by environment variable | Claude only: no other model provider |
Choose the Claude Agent SDK when the job is work on a computer (code, files, shell, research) and Claude is the model you want. Choose a typed loop (Typed agent libraries) when you need provider choice, a loop you own, or agents that are objects in your process; the same task in six frameworks with real runs is the root's Same agent, six ways tab. Claude Managed Agents (public beta since 8 April 2026) runs the same kind of agent in Anthropic's infrastructure: "the SDK runs in a process you operate, while Managed Agents runs in Anthropic's infrastructure. Most of the migration is mapping SDK configuration objects to their API-side equivalents" (migration) DOCS; its pricing, permission policies and the OpenAI Agents API are on the root's Production stack tab ("Hosted runtimes").
| Agent SDK (your process) | Managed Agents (Anthropic's) |
|---|---|
ClaudeAgentOptions on every run | An Agent created once, "persisted and versioned server-side" |
query() / ClaudeSDKClient | A session plus events streamed over SSE |
@tool in your process | Custom tools answered through agent.custom_tool_use / user.custom_tool_result events |
| Built-in tools on your filesystem | The agent toolset inside the session sandbox, against /workspace |
permission_mode, can_use_tool | Per-tool permission_policy (always_allow, always_ask, auto) and confirmation events |
Hooks, plan mode, output styles, slash commands, max_turns | "Features that move to your client" |
Pick the SDK over Managed Agents when the agent must run on your filesystem, network and audit trail, or you need hooks, plan mode and in-process tools.
The OpenAI Agents SDK is the closest library on the other side, and the gap is one of kind.
| Axis | Claude Agent SDK | OpenAI Agents SDK |
|---|---|---|
| What you get | A finished harness (Claude Code) in a child process, configured by options | Small primitives in your process: Agent, tool, handoff, guardrail, session, run loop |
| Loop | Claude Code's, not editable; you steer it with options, hooks and callbacks | A short Runner.run loop you can read end to end |
| Environment | Assumes a computer: files, shell, working directory | No environment: tools are whatever you register |
| Multi-agent | Subagents (hierarchical, isolated context) | Handoffs (control passes to another agent) and agents as tools |
| Guardrails | Permission order, callback, hooks, sandbox | Input and output guardrail functions with tripwires |
| Structured output | output_format (JSON schema, validated, retried) | output_type on the agent |
| Models | Claude, through Anthropic, Bedrock, Vertex, Foundry or Claude Platform on AWS | OpenAI by default; other providers through adapters such as LiteLLM |
| Tracing | Claude Code's OpenTelemetry, off until enabled | Built-in tracing, on by default |
| Hosted counterpart | Claude Managed Agents | The Agents API (public beta 10 Sep 2026) |
The OpenAI Agents SDK, Pydantic AI, smolagents and Google ADK are read from source on Typed agent libraries. Against LangGraph (LangChain and LangGraph): the SDK wins when the work needs a computer and Claude Code's loop is good enough, and you need neither your own control flow nor provider choice.
Versions and counts change monthly; they are gathered here instead of in the mechanisms above.
| Date or version | Fact |
|---|---|
| 28 Sep 2025 (UTC) | Python claude-agent-sdk 0.1.0, MIT licence for the Python wrapper per its PyPI classifier (PyPI) |
| 29 Sep 2025 | The Claude Code SDK renamed the Claude Agent SDK; TypeScript @anthropic-ai/claude-agent-sdk 0.1.0, its package saying "All rights reserved", use under Anthropic's legal agreements (npm) |
| SDK v0.1.0 | Claude Code's system prompt no longer the default; a change to load no settings by default was reverted |
| Python 0.1.59 and earlier | setting_sources=[] treated as "not given" |
| Claude Code 2.1.205 | Before it, an invalid output_format schema was silently ignored |
| 8 Apr 2026 | Claude Managed Agents public beta |
| 10 Sep 2026 | Managed Agents' auto permission policy; the OpenAI Agents API public beta; ant CLI v1.32.0 ant beta:sessions connect attaches a terminal to a live session |
| 6 Oct 2026 | Python 0.2.163 bundles Claude Code 2.1.286 (225,167,728 bytes, macOS arm64); TypeScript 0.3.291 ships Claude Code 2.1.291 (233,211,568 bytes); 49 Python options, 69 TypeScript |
| 6 Oct 2026 | Python hook events (10): PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStart, SubagentStop, PreCompact, Notification, PermissionRequest. TypeScript (33) adds, among others, SessionStart, SessionEnd, PostCompact and PermissionDenied |
The previous version of this page (Notion, last edited 22 Sep 2026); the fate of each claim is also in src/coverage.json.
| Old page said | Verdict | Where it stands now |
|---|---|---|
| Renamed from the Claude Code SDK "in late 2025" | holds | 29 September 2025; section 1 |
| Packages the entire Claude Code harness as a library | partly | It drives a bundled Claude Code binary as a child process over JSON lines; section 1 |
| Tool suite includes glob/grep | partly | Glob and Grep are not in the default set on macOS or Linux (our init records); Claude Code searches with Bash; section 3 |
| Python claude-agent-sdk, TypeScript @anthropic-ai/claude-agent-sdk | holds | 0.2.163 and 0.3.291 on 6 Oct 2026; section 11 |
| LangGraph gives primitives, the SDK a finished agent you configure | holds | Section 10 |
| Core bet: agents work best with a computer, a filesystem and a shell | holds | Blog: "give your agents a computer" |
| query() is stateless per call | wrong | Each call writes a session file and can be resumed; section 2 |
| ClaudeSDKClient (Python) or streaming sessions for multi-turn | holds | TypeScript has no client class; section 2 |
| Managed Agents "since September 2026" | wrong | Public beta since 8 April 2026; the auto permission policy came on 10 September 2026; section 11 |
| A beta command attaches a terminal to a live session | holds | ant CLI v1.32.0, ant beta:sessions connect (10 Sep 2026, verified on the harnesses pages) |
| OpenAI put the equivalent behind its Agents API the same day | holds | Agents API public beta 10 Sep 2026; section 11 |
| Custom tools in-process via @tool and an in-process MCP server, no subprocess hop | holds | Measured: 1 to 5 ms per call over the pipe; section 4 |
| Permissions: allowedTools, permissionMode, canUseTool as the SDK's permission prompt | partly | canUseTool sees only calls nothing earlier settled; six-step order; section 5 |
| MCP servers over stdio, HTTP or SSE | holds | Section 4 |
| Skills: only name and description in the prompt, body on demand | holds | Filesystem only; the skills option filters them; see Claude Code, taken apart |
| Subagents delegated "via a Task tool" | updated | The tool is Agent; Task is an alias still shown in the init record; section 6 |
| Hooks as callbacks on PreToolUse, PostToolUse, SessionStart, Stop | partly | Python callbacks cover 10 events and not SessionStart; TypeScript 33; section 5 |
| Sessions resume by id; compaction near the limit | holds | Section 7 |
| Structured output: "prompt-level; validate downstream" | wrong | output_format with a JSON schema, validated and retried; section 8 |
| Models: Claude via Bedrock and Vertex | updated | Also Foundry and Claude Platform on AWS; section 10 |
| Observability: hooks and OpenTelemetry export | holds | Telemetry is Claude Code's, off until enabled; section 10 |
| OpenAI Agents SDK: minimal primitives, Runner.run, handoffs, guardrails, output_type, LiteLLM, built-in traces, successor of Swarm | holds | Section 10 reference table; depth on Typed agent libraries |
| Docs link docs.claude.com/en/api/agent-sdk/overview | updated | Redirects to code.claude.com/docs/en/agent-sdk/overview |
| Best-practices link on anthropic.com/engineering | updated | Redirects to code.claude.com/docs/en/best-practices; see Further reading |
| 8 min read | updated | The page now carries the runs; its reading time is in the header |
sdk in the Claude Code process's MCP config; when the model calls the tool, Claude Code sends a control_request of subtype mcp_message carrying a JSON-RPC tools/call down stdout; the SDK runs your function and answers with a control_response on stdin. No socket, no extra process.permission_denials in the result, the init record's permissionMode and tool list, whether anything answers "ask" (a mode, allow rules or a callback), then the transcript.setting_sources=[], strict_mcp_config=True, auto memory off, a per-tenant CLAUDE_CONFIG_DIR, a sandbox or container, egress rules, and credentials injected by a proxy rather than given to the agent.Sources are linked where each fact is used: the Agent SDK documentation at code.claude.com (read 6 October 2026), the source of claude-agent-sdk 0.2.163 (Python) and @anthropic-ai/claude-agent-sdk 0.3.291 (TypeScript type definitions), and Anthropic's pricing page. Recordings: 8 runs plus 6 counting calls on 6 October 2026, Claude Haiku 4.5 unless stated (run s5: Sonnet 5.5 with a Haiku subagent), through the Python SDK with its bundled Claude Code 2.1.286 (run s8: TypeScript SDK, Claude Code 2.1.291), on a Claude subscription; costs are the SDK's own API-price estimates, each reproduced from token counts. Redacted copies, the scripts that made and checked them, and the old page (src/live.md, fate of each claim in src/coverage.json) are in this page's src/.
Pick options as you would write them in ClaudeAgentOptions. The lab shows the code, the exact command line the Python SDK 0.2.163 would start Claude Code with (rebuilt from _build_command() in its source), what goes into the initialize message instead, what will happen when the agent runs (each line marked with its evidence), and the nearest measured first-call context. Start from a recorded run: the lab then checks its rebuilt command against the command that run really started.
Evidence tags: SOURCE (claude-agent-sdk 0.2.163 code), DOCS (code.claude.com Agent SDK pages, read 6 Oct 2026), MEASURED (our runs on this page, the Claude Code child or the frameworks root). Token figures are first-call input tokens (fresh + cache write + cache read) on Haiku 4.5 unless the line says otherwise; another model or Claude Code version gives other numbers (the TypeScript run's newer Claude Code added 176 tokens). The TypeScript code uses the same options in camelCase.
initialize instead of flagsEight recorded runs on the running example (the textstats repository with two planted bugs: tokenize drops apostrophes, and top_words ignores ties), made on 6 October 2026 through the Python SDK 0.2.163 and its bundled Claude Code 2.1.286 (s8: the TypeScript SDK 0.3.291 with Claude Code 2.1.291), on a Claude subscription. Each started in a fresh copy of the repository; afterwards our script ran the tests itself and checked that the test file was unchanged. Redaction: paths become /work, ids short labels, the account and the machine's names are removed; model-written em-dashes were replaced by commas ( in all). Texts here are shortened; the full redacted copies are in src/recordings/.
Six one-turn calls ("Reply OK.", Haiku 4.5, no built-in tools, setting_sources=[]), only counts kept.
Any combination of options as code, command line and consequences; checked against five recorded commands. 15 min
All eight runs: transcripts, usage, the cost check, diffs, connector counts. 20 min
The root, a map: workflows against agents, the orchestration schools and libraries compared, when to use a framework at all. Tabs: Same agent, six ways (this SDK next to LangGraph, Pydantic AI, the OpenAI Agents SDK, smolagents and a plain loop); Orchestration lab; Production stack (gateways, tracing, evals, hosted runtimes). Reading 24 min, plus 2 closed; labs 18 to 21 min each.
Graphs, state, checkpointers and interrupts: the other way to get durable, resumable agents, against this SDK's session files and rewind. 34 min
Orchestrator-workers, handoffs, debate, measured with Claude Code subagents: when the subagents of section 6 pay. 32 min
Traces, OpenTelemetry GenAI conventions, Langfuse: where the bundled Claude Code's telemetry goes, TRACEPARENT and the identity attributes on every span. 34 min
Pydantic AI, the OpenAI Agents SDK, smolagents and Google ADK from source, and Claude's --json-schema route measured: the libraries this SDK is compared with. 25 min
LiteLLM, OpenRouter, budgets and fallbacks in front of model calls: the layer that sits between an agent and its providers. 37 min
The process this SDK starts: tools and their limits, permission rules, all hook events, memory files, skills, plan mode, headless runs. 43 min
The agent loop from zero (Loop lab), traces and caching (Trace and context lab), 23 harnesses compared. 21 min
Tool calling at the API level, edit formats, stop conditions, interrupts (with the SDK's interrupt recorded). 41 min
Window budgets, cache placement, compaction, subagents for isolation, and memory products (Mem0, Graphiti, Letta) against the session and memory files this SDK uses. 35 min
Permission gates, sandboxes, egress, prompt injection: what a callback cannot do. 35 min
Harnesses as RL environments and trajectory sources. 36 min
The protocol behind in-process and external tools. 37 min
Namespaces, seccomp, gVisor, microVMs: the sandboxes the hosting docs name. 51 min
The reason-act loop this lineage starts from. 21 min
Anthropic's docs: what the SDK is, the comparison with Claude Code, the Client SDK and Managed Agents, authentication rules. 15 min
The six-step order, modes, callbacks; hook events per language. 30 min
Session patterns, sizing, tenant isolation, sandbox choices, credential proxies. 35 min
What total_cost_usd, usage and modelUsage count, deduplication, caching. 10 min
Every option and message type. 40 min
The source: _internal/transport/subprocess_cli.py (the command line) and _internal/query.py (the control protocol) are short and worth reading. 45 min
Thariq Shihipar, 29 Sep 2025: the rename and the gather-context, take-action, verify-work loop. 14 min
The option-by-option mapping from the SDK to the hosted runtime. 15 min
Schluntz and Zhang, Dec 2024: workflows against agents, and when to use neither. 25 min
Most of it applies to SDK agents, since they run Claude Code. 30 min
The main comparison point: agents, handoffs, guardrails, sessions, tracing. 40 min