Claude Agent SDK: the Claude Code loop as a library

What the Python and TypeScript SDKs really are (your program starting the Claude Code binary and talking to it in JSON lines), the defaults that bite, permissions and hooks as your own functions, in-process tools, subagents, sessions, structured output, cost accounting and what a product on it costs, each shown in a real recorded run. Child of Topic: agentic-frameworks. claude-agent-sdk 0.2.163 (Python) and 0.3.291 (TypeScript), recorded and checked on 6 October 2026. Data as of October 2026. Reading: 29 min, plus 10 in closed details.

The SDK in one screen

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.

  1. Three processes. Your program (the Python SDK) starts the Claude Code binary with --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.
  2. Opening, 0.0 to 0.6 s. Your process sends 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.
  3. The model is called. Over HTTPS, not the pipe. Its thinking, text and first tool call come up the pipe as three lines, one per content block.
  4. A read: your hook settles it. Claude Code calls your PreToolUse hook (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.
  5. A test run: your callback decides. The hook answers {} (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.
  6. Five more calls, 4.1 to 13.5 s. Two reads settled by the hook, two edits and the final test run allowed by your callback: 18 questions and 18 answers in bursts between model calls, which are where the time goes.
  7. The result. 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 message
a side-channel line on the pipe: a control_request with a request id, answered by a control_response that echoes it.
SDK MCP server
an MCP server that lives inside your process; Claude Code reaches it over the pipe, not a socket.
can_use_tool
your function that decides a tool call nothing earlier settled.
Setting sources
which settings files (user, project, local) the child reads, with their hooks, CLAUDE.md files and skills.
Session
the saved conversation of one Claude Code process, a JSONL file on disk that can be resumed or forked.
PieceWhat it isSeen 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
ClaudeAgentOptions49 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_serverYour Python functions as tools, served by an MCP server that lives inside your process.s1, s2, s4, s6, s8
can_use_tool, hooksYour functions in the permission decision and at fixed points (10 hook events in Python, 33 in TypeScript).s1, s2
agentsSubagents defined in code, each with its own prompt, tools and model.s5
resume, fork_session, rewind_filesContinue a saved conversation, branch it, or put edited files back.s4, s9
output_formatA 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.

1. What the SDK is: your program starting Claude Code

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".

Predict: you run 50 agents at once with the SDK on one machine. How many Claude Code processes are running?
Fifty: one per session. (We did not check whether a subagent starts a further process; the session files show each subagent writing its own transcript inside the parent session's folder, section 6.) The hosting docs suggest planning "1 GiB RAM, 5 GiB disk, and 1 CPU per agent" as "a floor, not the ceiling" (hosting) DOCS. This is the main operational difference from a library such as Pydantic AI, where an agent is an object in your process.
Depth: how the binary is found, every control message, and the old page's analogy

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).

SubtypeDirectionMeaning
initializeyou to Claude CodeFirst line: hook callback ids per event and matcher, subagent definitions, skill filter. The answer lists commands, agents, the permission mode.
mcp_messageClaude Code to youA JSON-RPC message for an MCP server living in your process: initialize, tools/list, tools/call.
hook_callbackClaude Code to youRun hook hook_N with this input; your answer can allow, deny, rewrite or add context.
can_use_toolClaude Code to youA 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 managementyou to Claude CodeControl 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.

The same task twice: with callbacks the pipe is a conversation; with defaults it flows one way

sYour process (SDK)Claude Code

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).

2. Two ways in: query() and ClaudeSDKClient

query() 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).

Reference: every message class your loop receives

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.

3. Options, and the defaults that bite

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:

Predict, then open: what did s3's six refusals look like, and why did it still report success?
The run ended with 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: empty. 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: Claude Code's whole default set. 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.
  • Settings: everything on the machine. 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.
  • Outside MCP servers: allowed. Without 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).

Reference: the Python options grouped by what they control, and what each becomes
GroupPython optionsBecomes
Modelmodel, fallback_model, thinking, effort, betas--model, --fallback-model, --thinking, --effort, --betas
What the model seessystem_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 dopermission_mode, allowed_tools, disallowed_tools, can_use_tool, hooks, sandbox, add_dirs, cwd--permission-mode, --allowedTools, --disallowedTools, --permission-prompt-tool stdio, --settings, --add-dir
Limitsmax_turns, max_budget_usd, task_budget--max-turns, --max-budget-usd, --task-budget
Sessionsresume, continue_conversation, fork_session, session_id, resume_session_at, enable_file_checkpointing, session_store--resume, --continue, --fork-session, ...
Outputoutput_format, include_partial_messages, include_hook_events--json-schema, --include-partial-messages, --include-hook-events
Processcli_path, env, extra_args, stderr, settingswhich 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.

Same task, same model: options set on purpose against the defaults

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.

4. Tools: built-in, in your process, or an outside MCP server

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.

Depth: errors, annotations, start-up delay and tool search, from the docs

(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.

Where each kind of tool runs, and the name the model sees

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.

5. Permissions and hooks: your code in the decision

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.

  1. Seven calls, six stages. Run s1's model made 7 tool calls. Stage 1 is our PreToolUse hook and stage 6 our 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).
  2. The hook settles the reads. 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.
  3. Everything else reaches the callback. Both test runs and both edits pass stages 1 to 5 (the hook answers {}, no rule matches, mode default passes everything on) and our callback allows them.
  4. The tally. 3 calls settled by the hook, 4 allowed by the callback, none refused: the callback saw only 4 of the 7 calls.

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).

Depth: the callback's signature and context

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.

Callbacks are policy, not a sandbox

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.

6. Subagents defined in code

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").

Reference: every AgentDefinition field, and how subagent messages arrive

Optional 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.

Run s5: the first delegation stalls on refused commands, the second reports in one call

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.

7. Sessions: resume, fork, and putting files back

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).

  1. Turn 1, process 1. 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.
  2. Between turns: the context report. 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).
  3. Turn 2, same process. "Fix the first failure": it remembered turn 1 without our code sending any history, because the history lives in the Claude Code process. Reported $0.0247, of which this turn added $0.0124.
  4. Resume: process 2. Process 1 has exited; 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.
  5. Fork: process 3. 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.
  6. Take differences, never sums. 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.

Depth: s9's refused test commands, and compound commands

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.

8. Structured output: a schema, enforced by a tool

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.

9. Cost and usage: what the numbers mean

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:

  • One model call arrives as several messages. Run s1 made 5 model calls but streamed 15 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").
  • Per-message output counts are placeholders (1 to 3 tokens in s1); read output tokens from the result (1,563 in s1).
  • 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.
  • Caching follows Claude Code's rules. Haiku 4.5 caches only prompts of at least 4,096 tokens, so s1 (1,390-token first call) had no cache traffic at all, while s3 (14,703) read 226,443 cached tokens. Subscription runs write 1-hour cache entries (2x input price); with an API key the default is 5 minutes (cost tracking). How the prefix is placed is taught on Context engineering.
  • Limits: 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).

The defaults run (s3) cost four times the tuned run (s1) and still failed

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.

The connector pitfall, counted

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.

The same "Reply OK." call: 434 input tokens strict, up to 128,306 not strict

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.

10. Building a product on it, and what it costs against your own loop

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:

PatternShapeFits
EphemeralA container per task, destroyed at the end"bug investigation and fix, invoice and receipt extraction, document translation"
Long-runningPersistent containers, often several SDK processes eachemail agents, chat bots, per-user site builders
HybridEphemeral containers that load the session from a SessionStore and write it back ("the store is required")conversations that sit idle between turns
Multi-agent containerSeveral SDK processes in one containeragents 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).

Depth: trace context and identity attributes, measured for Claude Code 2.1.291

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.

What you inherit, and what you pay, against writing the loop yourself

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 toolsA 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 releaseClaude 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 pointNo 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 variableClaude 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").

Reference: the SDK against Managed Agents, option by option
Agent SDK (your process)Managed Agents (Anthropic's)
ClaudeAgentOptions on every runAn Agent created once, "persisted and versioned server-side"
query() / ClaudeSDKClientA session plus events streamed over SSE
@tool in your processCustom tools answered through agent.custom_tool_use / user.custom_tool_result events
Built-in tools on your filesystemThe agent toolset inside the session sandbox, against /workspace
permission_mode, can_use_toolPer-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.

Reference: the SDK against the OpenAI Agents SDK (the old page's table, corrected)

The OpenAI Agents SDK is the closest library on the other side, and the gap is one of kind.

AxisClaude Agent SDKOpenAI Agents SDK
What you getA finished harness (Claude Code) in a child process, configured by optionsSmall primitives in your process: Agent, tool, handoff, guardrail, session, run loop
LoopClaude Code's, not editable; you steer it with options, hooks and callbacksA short Runner.run loop you can read end to end
EnvironmentAssumes a computer: files, shell, working directoryNo environment: tools are whatever you register
Multi-agentSubagents (hierarchical, isolated context)Handoffs (control passes to another agent) and agents as tools
GuardrailsPermission order, callback, hooks, sandboxInput and output guardrail functions with tripwires
Structured outputoutput_format (JSON schema, validated, retried)output_type on the agent
ModelsClaude, through Anthropic, Bedrock, Vertex, Foundry or Claude Platform on AWSOpenAI by default; other providers through adapters such as LiteLLM
TracingClaude Code's OpenTelemetry, off until enabledBuilt-in tracing, on by default
Hosted counterpartClaude Managed AgentsThe 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.

11. Dated facts

Versions and counts change monthly; they are gathered here instead of in the mechanisms above.

Versions, dates and counts (9 rows, read 6 October 2026 unless dated otherwise)
Date or versionFact
28 Sep 2025 (UTC)Python claude-agent-sdk 0.1.0, MIT licence for the Python wrapper per its PyPI classifier (PyPI)
29 Sep 2025The 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.0Claude Code's system prompt no longer the default; a change to load no settings by default was reverted
Python 0.1.59 and earliersetting_sources=[] treated as "not given"
Claude Code 2.1.205Before it, an invalid output_format schema was silently ignored
8 Apr 2026Claude Managed Agents public beta
10 Sep 2026Managed 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 2026Python 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 2026Python hook events (10): PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStart, SubagentStop, PreCompact, Notification, PermissionRequest. TypeScript (33) adds, among others, SessionStart, SessionEnd, PostCompact and PermissionDenied

Depth

The old page, claim by claim (25 claims checked against the docs, the 0.2.163 source and our runs)

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 saidVerdictWhere it stands now
Renamed from the Claude Code SDK "in late 2025"holds29 September 2025; section 1
Packages the entire Claude Code harness as a librarypartlyIt drives a bundled Claude Code binary as a child process over JSON lines; section 1
Tool suite includes glob/greppartlyGlob 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-sdkholds0.2.163 and 0.3.291 on 6 Oct 2026; section 11
LangGraph gives primitives, the SDK a finished agent you configureholdsSection 10
Core bet: agents work best with a computer, a filesystem and a shellholdsBlog: "give your agents a computer"
query() is stateless per callwrongEach call writes a session file and can be resumed; section 2
ClaudeSDKClient (Python) or streaming sessions for multi-turnholdsTypeScript has no client class; section 2
Managed Agents "since September 2026"wrongPublic 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 sessionholdsant 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 dayholdsAgents API public beta 10 Sep 2026; section 11
Custom tools in-process via @tool and an in-process MCP server, no subprocess hopholdsMeasured: 1 to 5 ms per call over the pipe; section 4
Permissions: allowedTools, permissionMode, canUseTool as the SDK's permission promptpartlycanUseTool sees only calls nothing earlier settled; six-step order; section 5
MCP servers over stdio, HTTP or SSEholdsSection 4
Skills: only name and description in the prompt, body on demandholdsFilesystem only; the skills option filters them; see Claude Code, taken apart
Subagents delegated "via a Task tool"updatedThe tool is Agent; Task is an alias still shown in the init record; section 6
Hooks as callbacks on PreToolUse, PostToolUse, SessionStart, StoppartlyPython callbacks cover 10 events and not SessionStart; TypeScript 33; section 5
Sessions resume by id; compaction near the limitholdsSection 7
Structured output: "prompt-level; validate downstream"wrongoutput_format with a JSON schema, validated and retried; section 8
Models: Claude via Bedrock and VertexupdatedAlso Foundry and Claude Platform on AWS; section 10
Observability: hooks and OpenTelemetry exportholdsTelemetry 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 SwarmholdsSection 10 reference table; depth on Typed agent libraries
Docs link docs.claude.com/en/api/agent-sdk/overviewupdatedRedirects to code.claude.com/docs/en/agent-sdk/overview
Best-practices link on anthropic.com/engineeringupdatedRedirects to code.claude.com/docs/en/best-practices; see Further reading
8 min readupdatedThe page now carries the runs; its reading time is in the header
Interview rehearsal: three design questions
How does the Claude Agent SDK call your Python tool if the agent runs in another process?
The SDK registers an MCP server of type 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.
An agent built with the SDK reports success but did nothing. What do you check?
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.
How do you isolate tenants?
One process and working directory per session, 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/.