Changes on
58 changes detected
--- a/2026-w14.md
+++ b/2026-w14.md
@@ -49,7 +49,7 @@
}
}
-[MCP reference](</en/mcp#override-result-size-per-tool>)
+[MCP reference](</en/mcp#raise-the-limit-for-a-specific-tool>)
Plugin executables on PATHv2.1.91
Show diff (390 lines)
--- a/agent-loop.md
+++ b/agent-loop.md
@@ -0,0 +1,387 @@
+The Agent SDK lets you embed Claude Code’s autonomous agent loop in your own applications. The SDK is a standalone package that gives you programmatic control over tools, permissions, cost limits, and output. You don’t need the Claude Code CLI installed to use it. When you start an agent, the SDK runs the same [execution loop that powers Claude Code](</docs/en/how-claude-code-works#the-agentic-loop>): Claude evaluates your prompt, calls tools to take action, receives the results, and repeats until the task is complete. This page explains what happens inside that loop so you can build, debug, and optimize your agents effectively.
+
+##
+
+
+
+The loop at a glance
+
+Every agent session follows the same cycle:
+
+ 1. **Receive prompt.** Claude receives your prompt, along with the system prompt, tool definitions, and conversation history. The SDK yields a `SystemMessage` with subtype `"init"` containing session metadata.
+ 2. **Evaluate and respond.** Claude evaluates the current state and determines how to proceed. It may respond with text, request one or more tool calls, or both. The SDK yields an `AssistantMessage` containing the text and any tool call requests.
+ 3. **Execute tools.** The SDK runs each requested tool and collects the results. Each set of tool results feeds back to Claude for the next decision. You can use [hooks](</docs/en/agent-sdk/hooks>) to intercept, modify, or block tool calls before they run.
+ 4. **Repeat.** Steps 2 and 3 repeat as a cycle. Each full cycle is one turn. Claude continues calling tools and processing results until it produces a response with no tool calls.
+ 5. **Return result.** The SDK yields a final `AssistantMessage` with the text response (no tool calls), followed by a `ResultMessage` with the final text, token usage, cost, and session ID.
+
+A quick question (“what files are here?”) might take one or two turns of calling `Glob` and responding with the results. A complex task (“refactor the auth module and update the tests”) can chain dozens of tool calls across many turns, reading files, editing code, and running tests, with Claude adjusting its approach based on each result.
+
+##
+
+
+
+Turns and messages
+
+A turn is one round trip inside the loop: Claude produces output that includes tool calls, the SDK executes those tools, and the results feed back to Claude automatically. This happens without yielding control back to your code. Turns continue until Claude produces output with no tool calls, at which point the loop ends and the final result is delivered. Consider what a full session might look like for the prompt “Fix the failing tests in auth.ts”. First, the SDK sends your prompt to Claude and yields a `SystemMessage` with the session metadata. Then the loop begins:
+
+ 1. **Turn 1:** Claude calls `Bash` to run `npm test`. The SDK yields an `AssistantMessage` with the tool call, executes the command, then yields a `UserMessage` with the output (three failures).
+ 2. **Turn 2:** Claude calls `Read` on `auth.ts` and `auth.test.ts`. The SDK returns the file contents and yields an `AssistantMessage`.
+ 3. **Turn 3:** Claude calls `Edit` to fix `auth.ts`, then calls `Bash` to re-run `npm test`. All three tests pass. The SDK yields an `AssistantMessage`.
+ 4. **Final turn:** Claude produces a text-only response with no tool calls: “Fixed the auth bug, all three tests pass now.” The SDK yields a final `AssistantMessage` with this text, then a `ResultMessage` with the same text plus cost and usage.
+
+That was four turns: three with tool calls, one final text-only response. You can cap the loop with `max_turns` / `maxTurns`, which counts tool-use turns only. For example, `max_turns=2` in the loop above would have stopped before the edit step. You can also use `max_budget_usd` / `maxBudgetUsd` to cap turns based on a spend threshold. Without limits, the loop runs until Claude finishes on its own, which is fine for well-scoped tasks but can run long on open-ended prompts (“improve this codebase”). Setting a budget is a good default for production agents. See Turns and budget below for the option reference.
+
+##
+
+
+
+Message types
+
+As the loop runs, the SDK yields a stream of messages. Each message carries a type that tells you what stage of the loop it came from. The five core types are:
+
+ * **`SystemMessage`:** session lifecycle events. The `subtype` field distinguishes them: `"init"` is the first message (session metadata), and `"compact_boundary"` fires after compaction. In TypeScript, the compact boundary is its own [`SDKCompactBoundaryMessage`](</docs/en/agent-sdk/typescript#sdk-compact-boundary-message>) type rather than a subtype of `SDKSystemMessage`.
+ * **`AssistantMessage`:** emitted after each Claude response, including the final text-only one. Contains text content blocks and tool call blocks from that turn.
+ * **`UserMessage`:** emitted after each tool execution with the tool result content sent back to Claude. Also emitted for any user inputs you stream mid-loop.
+ * **`StreamEvent`:** only emitted when partial messages are enabled. Contains raw API streaming events (text deltas, tool input chunks). See [Stream responses](</docs/en/agent-sdk/streaming-output>).
+ * **`ResultMessage`:** the last message, always. Contains the final text result, token usage, cost, and session ID. Check the `subtype` field to determine whether the task succeeded or hit a limit. See Handle the result.
+
+These five types cover the full agent loop lifecycle in both SDKs. The TypeScript SDK also yields additional observability events (hook events, tool progress, rate limits, task notifications) that provide extra detail but are not required to drive the loop. See the [Python message types reference](</docs/en/agent-sdk/python#message-types>) and [TypeScript message types reference](</docs/en/agent-sdk/typescript#message-types>) for the complete lists.
+
+###
+
+
+
+Handle messages
+
+Which messages you handle depends on what you’re building:
+
+ * **Final results only:** handle `ResultMessage` to get the output, cost, and whether the task succeeded or hit a limit.
+ * **Progress updates:** handle `AssistantMessage` to see what Claude is doing each turn, including which tools it called.
+ * **Live streaming:** enable partial messages (`include_partial_messages` in Python, `includePartialMessages` in TypeScript) to get `StreamEvent` messages in real time. See [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>).
+
+How you check message types depends on the SDK:
+
+ * **Python:** check message types with `isinstance()` against classes imported from `claude_agent_sdk` (for example, `isinstance(message, ResultMessage)`).
+ * **TypeScript:** check the `type` string field (for example, `message.type === "result"`). `AssistantMessage` and `UserMessage` wrap the raw API message in a `.message` field, so content blocks are at `message.message.content`, not `message.content`.
+
+Example: Check message types and handle results
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, AssistantMessage, ResultMessage
+
+ async for message in query(prompt="Summarize this project"):
+ if isinstance(message, AssistantMessage):
+ print(f"Turn completed: {len(message.content)} content blocks")
+ if isinstance(message, ResultMessage):
+ if message.subtype == "success":
+ print(message.result)
+ else:
+ print(f"Stopped: {message.subtype}")
+
+##
+
+
+
+Tool execution
+
+Tools give your agent the ability to take action. Without tools, Claude can only respond with text. With tools, Claude can read files, run commands, search code, and interact with external services.
+
+###
+
+
+
+Built-in tools
+
+The SDK includes the same tools that power Claude Code:
+
+Category| Tools| What they do
+---|---|---
+**File operations**| `Read`, `Edit`, `Write`| Read, modify, and create files
+**Search**| `Glob`, `Grep`| Find files by pattern, search content with regex
+**Execution**| `Bash`| Run shell commands, scripts, git operations
+**Web**| `WebSearch`, `WebFetch`| Search the web, fetch and parse pages
+**Discovery**| `ToolSearch`| Dynamically find and load tools on-demand instead of preloading all of them
+**Orchestration**| `Agent`, `Skill`, `AskUserQuestion`, `TodoWrite`| Spawn subagents, invoke skills, ask the user, track tasks
+
+Beyond built-in tools, you can:
+
+ * **Connect external services** with [MCP servers](</docs/en/agent-sdk/mcp>) (databases, browsers, APIs)
+ * **Define custom tools** with [custom tool handlers](</docs/en/agent-sdk/custom-tools>)
+ * **Load project skills** via [setting sources](</docs/en/agent-sdk/claude-code-features>) for reusable workflows
+
+###
+
+
+
+Tool permissions
+
+Claude determines which tools to call based on the task, but you control whether those calls are allowed to execute. You can auto-approve specific tools, block others entirely, or require approval for everything. Three options work together to determine what runs:
+
+ * **`allowed_tools` / `allowedTools`** auto-approves listed tools. A read-only agent with `["Read", "Glob", "Grep"]` in its allowed tools list runs those tools without prompting. Tools not listed are still available but require permission.
+ * **`disallowed_tools` / `disallowedTools`** blocks listed tools, regardless of other settings. See [Permissions](</docs/en/agent-sdk/permissions>) for the order that rules are checked before a tool runs.
+ * **`permission_mode` / `permissionMode`** controls what happens to tools that aren’t covered by allow or deny rules. See Permission mode for available modes.
+
+You can also scope individual tools with rules like `"Bash(npm:*)"` to allow only specific commands. See [Permissions](</docs/en/agent-sdk/permissions>) for the full rule syntax. When a tool is denied, Claude receives a rejection message as the tool result and typically attempts a different approach or reports that it couldn’t proceed.
+
+###
+
+
+
+Parallel tool execution
+
+When Claude requests multiple tool calls in a single turn, both SDKs can run them concurrently or sequentially depending on the tool. Read-only tools (like `Read`, `Glob`, `Grep`, and MCP tools marked as read-only) can run concurrently. Tools that modify state (like `Edit`, `Write`, and `Bash`) run sequentially to avoid conflicts. Custom tools default to sequential execution. To enable parallel execution for a custom tool, mark it as read-only in its annotations: `readOnly` in [TypeScript](</docs/en/agent-sdk/typescript#tool>) or `readOnlyHint` in [Python](</docs/en/agent-sdk/python#tool>).
+
+##
+
+
+
+Control how the loop runs
+
+You can limit how many turns the loop takes, how much it costs, how deeply Claude reasons, and whether tools require approval before running. All of these are fields on [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claude-agent-options>) (Python) / [`Options`](</docs/en/agent-sdk/typescript#options>) (TypeScript).
+
+###
+
+
+
+Turns and budget
+
+Option| What it controls| Default
+---|---|---
+Max turns (`max_turns` / `maxTurns`)| Maximum tool-use round trips| No limit
+Max budget (`max_budget_usd` / `maxBudgetUsd`)| Maximum cost before stopping| No limit
+
+When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See Handle the result for how to check these subtypes and [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claude-agent-options>) / [`Options`](</docs/en/agent-sdk/typescript#options>) for syntax.
+
+###
+
+
+
+Effort level
+
+The `effort` option controls how much reasoning Claude applies. Lower effort levels use fewer tokens per turn and reduce cost. Not all models support the effort parameter. See [Effort](<https://platform.claude.com/docs/en/build-with-claude/effort>) for which models support it.
+
+Level| Behavior| Good for
+---|---|---
+`"low"`| Minimal reasoning, fast responses| File lookups, listing directories
+`"medium"`| Balanced reasoning| Routine edits, standard tasks
+`"high"`| Thorough analysis| Refactors, debugging
+`"max"`| Maximum reasoning depth| Multi-step problems requiring deep analysis
+
+If you don’t set `effort`, the Python SDK leaves the parameter unset and defers to the model’s default behavior. The TypeScript SDK defaults to `"high"`.
+
+`effort` trades latency and token cost for reasoning depth within each response. [Extended thinking](<https://platform.claude.com/docs/en/build-with-claude/extended-thinking>) is a separate feature that produces visible chain-of-thought blocks in the output. They are independent: you can set `effort: "low"` with extended thinking enabled, or `effort: "max"` without it.
+
+Use lower effort for agents doing simple, well-scoped tasks (like listing files or running a single grep) to reduce cost and latency. `effort` is set at the top-level `query()` options, not per-subagent.
+
+###
+
+
+
+Permission mode
+
+The permission mode option (`permission_mode` in Python, `permissionMode` in TypeScript) controls whether the agent asks for approval before using tools:
+
+Mode| Behavior
+---|---
+`"default"`| Tools not covered by allow rules trigger your approval callback; no callback means deny
+`"acceptEdits"`| Auto-approves file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.); other Bash commands follow default rules
+`"plan"`| No tool execution; Claude produces a plan for review
+`"dontAsk"`| Never prompts. Tools pre-approved by [permission rules](</docs/en/settings#permission-settings>) run, everything else is denied
+`"auto"` (TypeScript only)| Uses a model classifier to approve or deny each tool call. See [Auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) for availability and behavior
+`"bypassPermissions"`| Runs all allowed tools without asking. Cannot be used when running as root on Unix. Use only in isolated environments where the agent’s actions cannot affect systems you care about
+
+For interactive applications, use `"default"` with a tool approval callback to surface approval prompts. For autonomous agents on a dev machine, `"acceptEdits"` auto-approves file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.) while still gating other `Bash` commands behind allow rules. Reserve `"bypassPermissions"` for CI, containers, or other isolated environments. See [Permissions](</docs/en/agent-sdk/permissions>) for full details.
+
+###
+
+
+
+Model
+
+If you don’t set `model`, the SDK uses Claude Code’s default, which depends on your authentication method and subscription. Set it explicitly (for example, `model="claude-sonnet-4-6"`) to pin a specific model or to use a smaller model for faster, cheaper agents. See [models](<https://platform.claude.com/docs/en/about-claude/models>) for available IDs.
+
+##
+
+
+
+The context window
+
+The context window is the total amount of information available to Claude during a session. It does not reset between turns within a session. Everything accumulates: the system prompt, tool definitions, conversation history, tool inputs, and tool outputs. Content that stays the same across turns (system prompt, tool definitions, CLAUDE.md) is automatically [prompt cached](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching>), which reduces cost and latency for repeated prefixes.
+
+###
+
+
+
+What consumes context
+
+Here’s how each component affects context in the SDK:
+
+Source| When it loads| Impact
+---|---|---
+**System prompt**| Every request| Small fixed cost, always present
+**CLAUDE.md files**| Session start, when [`settingSources`](</docs/en/agent-sdk/claude-code-features>) is enabled| Full content in every request (but prompt-cached, so only the first request pays full cost)
+**Tool definitions**| Every request| Each tool adds its schema; use [MCP tool search](</docs/en/agent-sdk/mcp#mcp-tool-search>) to load tools on-demand instead of all at once
+**Conversation history**| Accumulates over turns| Grows with each turn: prompts, responses, tool inputs, tool outputs
+**Skill descriptions**| Session start (with setting sources enabled)| Short summaries; full content loads only when invoked
+
+Large tool outputs consume significant context. Reading a big file or running a command with verbose output can use thousands of tokens in a single turn. Context accumulates across turns, so longer sessions with many tool calls build up significantly more context than short ones.
+
+###
+
+
+
+Automatic compaction
+
+When the context window approaches its limit, the SDK automatically compacts the conversation: it summarizes older history to free space, keeping your most recent exchanges and key decisions intact. The SDK emits a message with `type: "system"` and `subtype: "compact_boundary"` in the stream when this happens (in Python this is a `SystemMessage`; in TypeScript it is a separate `SDKCompactBoundaryMessage` type). Compaction replaces older messages with a summary, so specific instructions from early in the conversation may not be preserved. Persistent rules belong in CLAUDE.md (loaded via [`settingSources`](</docs/en/agent-sdk/claude-code-features>)) rather than in the initial prompt, because CLAUDE.md content is re-injected on every request. You can customize compaction behavior in several ways:
+
+ * **Summarization instructions in CLAUDE.md:** The compactor reads your CLAUDE.md like any other context, so you can include a section telling it what to preserve when summarizing. The section header is free-form (not a magic string); the compactor matches on intent.
+ * **`PreCompact` hook:** Run custom logic before compaction occurs, for example to archive the full transcript. The hook receives a `trigger` field (`manual` or `auto`). See [hooks](</docs/en/agent-sdk/hooks>).
+ * **Manual compaction:** Send `/compact` as a prompt string to trigger compaction on demand. (Slash commands sent this way are SDK inputs, not CLI-only shortcuts. See [slash commands in the SDK](</docs/en/agent-sdk/slash-commands>).)
+
+Example: Summarization instructions in CLAUDE.md
+
+Add a section to your project’s CLAUDE.md telling the compactor what to preserve. The header name isn’t special; use any clear label.
+
+CLAUDE.md
+
+ # Summary instructions
+
+ When summarizing this conversation, always preserve:
+ - The current task objective and acceptance criteria
+ - File paths that have been read or modified
+ - Test results and error messages
+ - Decisions made and the reasoning behind them
+
+###
+
+
+
+Keep context efficient
+
+A few strategies for long-running agents:
+
+ * **Use subagents for subtasks.** Each subagent starts with a fresh conversation (no prior message history, though it does load its own system prompt and project-level context like CLAUDE.md). It does not see the parent’s turns, and only its final response returns to the parent as a tool result. The main agent’s context grows by that summary, not by the full subtask transcript. See [What subagents inherit](</docs/en/agent-sdk/subagents#what-subagents-inherit>) for details.
+ * **Be selective with tools.** Every tool definition takes context space. Use the `tools` field on [`AgentDefinition`](</docs/en/agent-sdk/subagents#agent-definition-configuration>) to scope subagents to the minimum set they need, and use [MCP tool search](</docs/en/agent-sdk/mcp#mcp-tool-search>) to load tools on demand instead of preloading all of them.
+ * **Watch MCP server costs.** Each MCP server adds all its tool schemas to every request. A few servers with many tools can consume significant context before the agent does any work. The `ToolSearch` tool can help by loading tools on-demand instead of preloading all of them. See [MCP tool search](</docs/en/agent-sdk/mcp#mcp-tool-search>) for configuration.
+ * **Use lower effort for routine tasks.** Set effort to `"low"` for agents that only need to read files or list directories. This reduces token usage and cost.
+
+For a detailed breakdown of per-feature context costs, see [Understand context costs](</docs/en/features-overview#understand-context-costs>).
+
+##
+
+
+
+Sessions and continuity
+
+Each interaction with the SDK creates or continues a session. Capture the session ID from `ResultMessage.session_id` (available in both SDKs) to resume later. The TypeScript SDK also exposes it as a direct field on the init `SystemMessage`; in Python it’s nested in `SystemMessage.data`. When you resume, the full context from previous turns is restored: files that were read, analysis that was performed, and actions that were taken. You can also fork a session to branch into a different approach without modifying the original. See [Session management](</docs/en/agent-sdk/sessions>) for the full guide on resume, continue, and fork patterns.
+
+In Python, `ClaudeSDKClient` handles session IDs automatically across multiple calls. See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claude-sdk-client>) for details.
+
+##
+
+
+
+Handle the result
+
+When the loop ends, the `ResultMessage` tells you what happened and gives you the output. The `subtype` field (available in both SDKs) is the primary way to check termination state.
+
+Result subtype| What happened| `result` field available?
+---|---|---
+`success`| Claude finished the task normally| Yes
+`error_max_turns`| Hit the `maxTurns` limit before finishing| No
+`error_max_budget_usd`| Hit the `maxBudgetUsd` limit before finishing| No
+`error_during_execution`| An error interrupted the loop (for example, an API failure or cancelled request)| No
+`error_max_structured_output_retries`| Structured output validation failed after the configured retry limit| No
+
+The `result` field (the final text output) is only present on the `success` variant, so always check the subtype before reading it. All result subtypes carry `total_cost_usd`, `usage`, `num_turns`, and `session_id` so you can track cost and resume even after errors. In Python, `total_cost_usd` and `usage` are typed as optional and may be `None` on some error paths, so guard before formatting them. See [Tracking costs and usage](</docs/en/agent-sdk/cost-tracking>) for details on interpreting the `usage` fields. The result also includes a `stop_reason` field (`string | null` in TypeScript, `str | None` in Python) indicating why the model stopped generating on its final turn. Common values are `end_turn` (model finished normally), `max_tokens` (hit the output token limit), and `refusal` (the model declined the request). On error result subtypes, `stop_reason` carries the value from the last assistant response before the loop ended. To detect refusals, check `stop_reason === "refusal"` (TypeScript) or `stop_reason == "refusal"` (Python). See [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdk-result-message>) (TypeScript) or [`ResultMessage`](</docs/en/agent-sdk/python#result-message>) (Python) for the full type.
+
+##
+
+
+
+Hooks
+
+[Hooks](</docs/en/agent-sdk/hooks>) are callbacks that fire at specific points in the loop: before a tool runs, after it returns, when the agent finishes, and so on. Some commonly used hooks are:
+
+Hook| When it fires| Common uses
+---|---|---
+`PreToolUse`| Before a tool executes| Validate inputs, block dangerous commands
+`PostToolUse`| After a tool returns| Audit outputs, trigger side effects
+`UserPromptSubmit`| When a prompt is sent| Inject additional context into prompts
+`Stop`| When the agent finishes| Validate the result, save session state
+`SubagentStart` / `SubagentStop`| When a subagent spawns or completes| Track and aggregate parallel task results
+`PreCompact`| Before context compaction| Archive full transcript before summarizing
+
+Hooks run in your application process, not inside the agent’s context window, so they don’t consume context. Hooks can also short-circuit the loop: a `PreToolUse` hook that rejects a tool call prevents it from executing, and Claude receives the rejection message instead. Both SDKs support all the events above. The TypeScript SDK includes additional events that Python does not yet support. See [Control execution with hooks](</docs/en/agent-sdk/hooks>) for the complete event list, per-SDK availability, and the full callback API.
+
+##
+
+
+
+Put it all together
+
+This example combines the key concepts from this page into a single agent that fixes failing tests. It configures the agent with allowed tools (auto-approved so the agent runs autonomously), project settings, and safety limits on turns and reasoning effort. As the loop runs, it captures the session ID for potential resumption, handles the final result, and prints the total cost.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ async def run_agent():
+ session_id = None
+
+ async for message in query(
+ prompt="Find and fix the bug causing test failures in the auth module",
+ options=ClaudeAgentOptions(
+ allowed_tools=[
+ "Read",
+ "Edit",
+ "Bash",
+ "Glob",
+ "Grep",
+ ], # Listing tools here auto-approves them (no prompting)
+ setting_sources=[
+ "project"
+ ], # Load CLAUDE.md, skills, hooks from current directory
+ max_turns=30, # Prevent runaway sessions
+ effort="high", # Thorough reasoning for complex debugging
+ ),
+ ):
+ # Handle the final result
+ if isinstance(message, ResultMessage):
+ session_id = message.session_id # Save for potential resumption
+
+ if message.subtype == "success":
+ print(f"Done: {message.result}")
+ elif message.subtype == "error_max_turns":
+ # Agent ran out of turns. Resume with a higher limit.
+ print(f"Hit turn limit. Resume session {session_id} to continue.")
+ elif message.subtype == "error_max_budget_usd":
+ print("Hit budget limit.")
+ else:
+ print(f"Stopped: {message.subtype}")
+ if message.total_cost_usd is not None:
+ print(f"Cost: ${message.total_cost_usd:.4f}")
+
+ asyncio.run(run_agent())
+
+##
+
+
+
+Next steps
+
+Now that you understand the loop, here’s where to go depending on what you’re building:
+
+ * **Haven’t run an agent yet?** Start with the [quickstart](</docs/en/agent-sdk/quickstart>) to get the SDK installed and see a full example running end to end.
+ * **Ready to hook into your project?** [Load CLAUDE.md, skills, and filesystem hooks](</docs/en/agent-sdk/claude-code-features>) so the agent follows your project conventions automatically.
+ * **Building an interactive UI?** Enable [streaming](</docs/en/agent-sdk/streaming-output>) to show live text and tool calls as the loop runs.
+ * **Need tighter control over what the agent can do?** Lock down tool access with [permissions](</docs/en/agent-sdk/permissions>), and use [hooks](</docs/en/agent-sdk/hooks>) to audit, block, or transform tool calls before they execute.
+ * **Running long or expensive tasks?** Offload isolated work to [subagents](</docs/en/agent-sdk/subagents>) to keep your main context lean.
+
+For the broader conceptual picture of the agentic loop (not SDK-specific), see [How Claude Code works](</docs/en/how-claude-code-works>).
--- a/authentication.md
+++ b/authentication.md
@@ -6,7 +6,7 @@
Log in to Claude Code
-After [installing Claude Code](</docs/en/setup#install-claude-code>), run `claude` in your terminal. On first launch, Claude Code opens a browser window for you to log in. If the browser doesn’t open automatically, press `c` to copy the login URL to your clipboard, then paste it into your browser. You can authenticate with any of these account types:
+After [installing Claude Code](</docs/en/setup#install-claude-code>), run `claude` in your terminal. On first launch, Claude Code opens a browser window for you to log in. If the browser doesn’t open automatically, press `c` to copy the login URL to your clipboard, then paste it into your browser. If your browser shows a login code instead of redirecting back after you sign in, paste it into the terminal at the `Paste code here if prompted` prompt. You can authenticate with any of these account types:
* **Claude Pro or Max subscription** : log in with your Claude.ai account. Subscribe at [claude.com/pricing](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=authentication_pro_max>).
* **Claude for Teams or Enterprise** : log in with the Claude.ai account your team admin invited you to.
--- a/changelog.md
+++ b/changelog.md
@@ -1,4 +1,65 @@
This page is generated from the [CHANGELOG.md on GitHub](<https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md>). Run `claude --version` to check your installed version.
+
+
+
+2.1.97
+
+April 8, 2026
+
+ * Added focus view toggle (`Ctrl+O`) in `NO_FLICKER` mode showing prompt, one-line tool summary with edit diffstats, and final response
+ * Added `refreshInterval` status line setting to re-run the status line command every N seconds
+ * Added `workspace.git_worktree` to the status line JSON input, set when the current directory is inside a linked git worktree
+ * Added `● N running` indicator in `/agents` next to agent types with live subagent instances
+ * Added syntax highlighting for Cedar policy files (`.cedar`, `.cedarpolicy`)
+ * Fixed `--dangerously-skip-permissions` being silently downgraded to accept-edits mode after approving a write to a protected path
+ * Fixed and hardened Bash tool permissions, tightening checks around env-var prefixes and network redirects, and reducing false prompts on common commands
+ * Fixed permission rules with names matching JavaScript prototype properties (e.g. `toString`) causing `settings.json` to be silently ignored
+ * Fixed managed-settings allow rules remaining active after an admin removed them until process restart
+ * Fixed `permissions.additionalDirectories` changes in settings not applying mid-session
+ * Fixed removing a directory from `settings.permissions.additionalDirectories` revoking access to the same directory passed via `--add-dir`
+ * Fixed MCP HTTP/SSE connections accumulating ~50 MB/hr of unreleased buffers when servers reconnect
+ * Fixed MCP OAuth `oauth.authServerMetadataUrl` not being honored on token refresh after restart, fixing ADFS and similar IdPs
+ * Fixed 429 retries burning all attempts in ~13 seconds when the server returns a small `Retry-After` — exponential backoff now applies as a minimum
+ * Fixed rate-limit upgrade options disappearing after context compaction
+ * Fixed several `/resume` picker issues: `--resume <name>` opening uneditable, Ctrl+A reload wiping search, empty list swallowing navigation, task-status text replacing conversation summary, and cross-project staleness
+ * Fixed file-edit diffs disappearing on `--resume` when the edited file was larger than 10KB
+ * Fixed `--resume` cache misses and lost mid-turn input from attachment messages not being saved to the transcript
+ * Fixed messages typed while Claude is working not being persisted to the transcript
+ * Fixed prompt-type `Stop`/`SubagentStop` hooks failing on long sessions, and hook evaluator API errors displaying “JSON validation failed” instead of the actual message
+ * Fixed subagents with worktree isolation or `cwd:` override leaking their working directory back to the parent session’s Bash tool
+ * Fixed compaction writing duplicate multi-MB subagent transcript files on prompt-too-long retries
+ * Fixed `claude plugin update` reporting “already at the latest version” for git-based marketplace plugins when the remote had newer commits
+ * Fixed slash command picker breaking when a plugin’s frontmatter `name` is a YAML boolean keyword
+ * Fixed copying wrapped URLs in `NO_FLICKER` mode inserting spaces at line breaks
+ * Fixed scroll rendering artifacts in `NO_FLICKER` mode when running inside zellij
+ * Fixed a crash in `NO_FLICKER` mode when hovering over MCP tool results
+ * Fixed a `NO_FLICKER` mode memory leak where API retries left stale streaming state
+ * Fixed slow mouse-wheel scrolling in `NO_FLICKER` mode on Windows Terminal
+ * Fixed custom status line not displaying in `NO_FLICKER` mode on terminals shorter than 24 rows
+ * Fixed Shift+Enter and Alt/Cmd+arrow shortcuts not working in Warp with `NO_FLICKER` mode
+ * Fixed Korean/Japanese/Unicode text becoming garbled when copied in no-flicker mode on Windows
+ * Fixed Bedrock SigV4 authentication failing when `AWS_BEARER_TOKEN_BEDROCK` or `ANTHROPIC_BEDROCK_BASE_URL` are set to empty strings (as GitHub Actions does for unset inputs)
+ * Improved Accept Edits mode to auto-approve filesystem commands prefixed with safe env vars or process wrappers (e.g. `LANG=C rm foo`, `timeout 5 mkdir out`)
+ * Improved auto mode and bypass-permissions mode to auto-approve sandbox network access prompts
+ * Improved sandbox: `sandbox.network.allowMachLookup` now takes effect on macOS
+ * Improved image handling: pasted and attached images are now compressed to the same token budget as images read via the Read tool
+ * Improved slash command and `@`-mention completion to trigger after CJK sentence punctuation, so Japanese/Chinese input no longer requires a space before `/` or `@`
+ * Improved Bridge sessions to show the local git repo, branch, and working directory on the claude.ai session card
+ * Improved footer layout: indicators (Focus, notifications) now stay on the mode-indicator row instead of wrapping below
+ * Improved context-low warning to show as a transient footer notification instead of a persistent row
+ * Improved markdown blockquotes to show a continuous left bar across wrapped lines
+ * Improved session transcript size by skipping empty hook entries and capping stored pre-edit file copies
+ * Improved transcript accuracy: per-block entries now carry the final token usage instead of the streaming placeholder
+ * Improved Bash tool OTEL tracing: subprocesses now inherit a W3C `TRACEPARENT` env var when tracing is enabled
+ * Updated `/claude-api` skill to cover Managed Agents alongside the Claude API
+
+
+
+2.1.96
+
+April 8, 2026
+
+ * Fixed Bedrock requests failing with `403 "Authorization header is missing"` when using `AWS_BEARER_TOKEN_BEDROCK` or `CLAUDE_CODE_SKIP_BEDROCK_AUTH` (regression in 2.1.94)
Show diff (202 lines)
--- a/claude-code-features.md
+++ b/claude-code-features.md
@@ -0,0 +1,199 @@
+The Agent SDK is built on the same foundation as Claude Code, which means your SDK agents have access to the same filesystem-based features: project instructions (`CLAUDE.md` and rules), skills, hooks, and more. By default, the SDK loads no filesystem settings. Your agent runs in isolation mode with only what you pass programmatically. To load CLAUDE.md, skills, or filesystem hooks, set `settingSources` to tell the SDK where to look. For a conceptual overview of what each feature does and when to use it, see [Extend Claude Code](</docs/en/features-overview>).
+
+##
+
+
+
+Enable Claude Code features with settingSources
+
+The setting sources option ([`setting_sources`](</docs/en/agent-sdk/python#claude-agent-options>) in Python, [`settingSources`](</docs/en/agent-sdk/typescript#setting-source>) in TypeScript) controls which filesystem-based settings the SDK loads. Without it, your agent won’t discover skills, `CLAUDE.md` files, or project-level hooks. This example loads both user-level and project-level settings by setting `settingSources` to `["user", "project"]`:
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
+
+ async for message in query(
+ prompt="Help me refactor the auth module",
+ options=ClaudeAgentOptions(
+ # "user" loads from ~/.claude/, "project" loads from ./.claude/ in cwd.
+ # Together they give the agent access to CLAUDE.md, skills, hooks, and
+ # permissions from both locations.
+ setting_sources=["user", "project"],
+ allowed_tools=["Read", "Edit", "Bash"],
+ ),
+ ):
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if hasattr(block, "text"):
+ print(block.text)
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(f"\nResult: {message.result}")
+
+Each source loads settings from a specific location, where `<cwd>` is the working directory you pass via the `cwd` option (or the process’s current directory if unset). For the full type definition, see [`SettingSource`](</docs/en/agent-sdk/typescript#setting-source>) (TypeScript) or [`SettingSource`](</docs/en/agent-sdk/python#setting-source>) (Python).
+
+Source| What it loads| Location
+---|---|---
+`"project"`| Project CLAUDE.md, `.claude/rules/*.md`, project skills, project hooks, project `settings.json`| `<cwd>/.claude/` and each parent directory up to the filesystem root (stopping when a `.claude/` is found or no more parents exist)
+`"user"`| User CLAUDE.md, `~/.claude/rules/*.md`, user skills, user settings| `~/.claude/`
+`"local"`| CLAUDE.local.md (gitignored), `.claude/settings.local.json`| `<cwd>/`
+
+To match the full Claude Code CLI behavior, use `["user", "project", "local"]`.
+
+The `cwd` option determines where the SDK looks for project settings. If neither `cwd` nor any of its parent directories contains a `.claude/` folder, project-level features won’t load. Auto memory (the `~/.claude/projects/<project>/memory/` directory that Claude Code uses to persist notes across interactive sessions) is a CLI-only feature and is never loaded by the SDK.
+
+##
+
+
+
+Project instructions (CLAUDE.md and rules)
+
+`CLAUDE.md` files and `.claude/rules/*.md` files give your agent persistent context about your project: coding conventions, build commands, architecture decisions, and instructions. When `settingSources` includes `"project"` (as in the example above), the SDK loads these files into context at session start. The agent then follows your project conventions without you repeating them in every prompt.
+
+###
+
+
+
+CLAUDE.md load locations
+
+Level| Location| When loaded
+---|---|---
+Project (root)| `<cwd>/CLAUDE.md` or `<cwd>/.claude/CLAUDE.md`| `settingSources` includes `"project"`
+Project rules| `<cwd>/.claude/rules/*.md`| `settingSources` includes `"project"`
+Project (parent dirs)| `CLAUDE.md` files in directories above `cwd`| `settingSources` includes `"project"`, loaded at session start
+Project (child dirs)| `CLAUDE.md` files in subdirectories of `cwd`| `settingSources` includes `"project"`, loaded on demand when the agent reads a file in that subtree
+Local (gitignored)| `<cwd>/CLAUDE.local.md`| `settingSources` includes `"local"`
+User| `~/.claude/CLAUDE.md`| `settingSources` includes `"user"`
+User rules| `~/.claude/rules/*.md`| `settingSources` includes `"user"`
+
+All levels are additive: if both project and user CLAUDE.md files exist, the agent sees both. There is no hard precedence rule between levels; if instructions conflict, the outcome depends on how Claude interprets them. Write non-conflicting rules, or state precedence explicitly in the more specific file (“These project instructions override any conflicting user-level defaults”).
+
+You can also inject context directly via `systemPrompt` without using CLAUDE.md files. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts>). Use CLAUDE.md when you want the same context shared between interactive Claude Code sessions and your SDK agents.
+
+For how to structure and organize CLAUDE.md content, see [Manage Claude’s memory](</docs/en/memory>).
+
+##
+
+
+
+Skills
+
+Skills are markdown files that give your agent specialized knowledge and invocable workflows. Unlike `CLAUDE.md` (which loads every session), skills load on demand. The agent receives skill descriptions at startup and loads the full content when relevant. To use skills in the SDK, set `settingSources` so the agent discovers skill files from the filesystem. The `Skill` tool is enabled by default when you don’t specify `allowedTools`. If you are using an `allowedTools` allowlist, include `"Skill"` explicitly.
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ # Skills in .claude/skills/ are discovered automatically
+ # when settingSources includes "project"
+ async for message in query(
+ prompt="Review this PR using our code review checklist",
+ options=ClaudeAgentOptions(
+ setting_sources=["user", "project"],
+ allowed_tools=["Skill", "Read", "Grep", "Glob"],
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+
+Skills must be created as filesystem artifacts (`.claude/skills/<name>/SKILL.md`). The SDK does not have a programmatic API for registering skills. See [Agent Skills in the SDK](</docs/en/agent-sdk/skills>) for full details.
+
+For more on creating and using skills, see [Agent Skills in the SDK](</docs/en/agent-sdk/skills>).
+
+##
+
+
+
+Hooks
+
+The SDK supports two ways to define hooks, and they run side by side:
+
+ * **Filesystem hooks:** shell commands defined in `settings.json`, loaded when `settingSources` includes the relevant source. These are the same hooks you’d configure for [interactive Claude Code sessions](</docs/en/hooks-guide>).
+ * **Programmatic hooks:** callback functions passed directly to `query()`. These run in your application process and can return structured decisions. See [Control execution with hooks](</docs/en/agent-sdk/hooks>).
+
+Both types execute during the same hook lifecycle. If you already have hooks in your project’s `.claude/settings.json` and you set `settingSources: ["project"]`, those hooks run automatically in the SDK with no extra configuration. Hook callbacks receive the tool input and return a decision dict. Returning `{}` (an empty dict) means allow the tool to proceed. Returning `{"decision": "block", "reason": "..."}` prevents execution and the reason is sent to Claude as the tool result. See the [hooks guide](</docs/en/agent-sdk/hooks>) for the full callback signature and return types.
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, ResultMessage
+
+ # PreToolUse hook callback. Positional args:
+ # input_data: HookInput dict with tool_name, tool_input, hook_event_name
+ # tool_use_id: str | None, the ID of the tool call being intercepted
+ # context: HookContext, carries session metadata
+ async def audit_bash(input_data, tool_use_id, context):
+ command = input_data.get("tool_input", {}).get("command", "")
+ if "rm -rf" in command:
+ return {"decision": "block", "reason": "Destructive command blocked"}
+ return {} # Empty dict: allow the tool to proceed
+
+ # Filesystem hooks from .claude/settings.json run automatically
+ # when settingSources loads them. You can also add programmatic hooks:
+ async for message in query(
+ prompt="Refactor the auth module",
+ options=ClaudeAgentOptions(
+ setting_sources=["project"], # Loads hooks from .claude/settings.json
+ hooks={
+ "PreToolUse": [
+ HookMatcher(matcher="Bash", hooks=[audit_bash]),
+ ]
+ },
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+
+###
+
+
+
+When to use which hook type
+
+Hook type| Best for
+---|---
+**Filesystem** (`settings.json`)| Sharing hooks between CLI and SDK sessions. Supports `"command"` (shell scripts), `"http"` (POST to an endpoint), `"prompt"` (LLM evaluates a prompt), and `"agent"` (spawns a verifier agent). These fire in the main agent and any subagents it spawns.
+**Programmatic** (callbacks in `query()`)| Application-specific logic; returning structured decisions; in-process integration. Scoped to the main session only.
+
+The TypeScript SDK supports additional hook events beyond Python, including `SessionStart`, `SessionEnd`, `TeammateIdle`, and `TaskCompleted`. See the [hooks guide](</docs/en/agent-sdk/hooks>) for the full event compatibility table.
+
+For full details on programmatic hooks, see [Control execution with hooks](</docs/en/agent-sdk/hooks>). For filesystem hook syntax, see [Hooks](</docs/en/hooks>).
+
+##
+
+
+
+Choose the right feature
+
+The Agent SDK gives you access to several ways to extend your agent’s behavior. If you’re unsure which to use, this table maps common goals to the right approach.
+
+You want to…| Use| SDK surface
+---|---|---
+Set project conventions your agent always follows| [CLAUDE.md](</docs/en/memory>)| `settingSources: ["project"]` loads it automatically
+Give the agent reference material it loads when relevant| [Skills](</docs/en/agent-sdk/skills>)| `settingSources` \+ `allowedTools: ["Skill"]`
+Run a reusable workflow (deploy, review, release)| [User-invocable skills](</docs/en/agent-sdk/skills>)| `settingSources` \+ `allowedTools: ["Skill"]`
+Delegate an isolated subtask to a fresh context (research, review)| [Subagents](</docs/en/agent-sdk/subagents>)| `agents` parameter + `allowedTools: ["Agent"]`
+Coordinate multiple Claude Code instances with shared task lists and direct inter-agent messaging| [Agent teams](</docs/en/agent-teams>)| Not directly configured via SDK options. Agent teams are a CLI feature where one session acts as the team lead, coordinating work across independent teammates
+Run deterministic logic on tool calls (audit, block, transform)| [Hooks](</docs/en/agent-sdk/hooks>)| `hooks` parameter with callbacks, or shell scripts loaded via `settingSources`
+Give Claude structured tool access to an external service| [MCP](</docs/en/agent-sdk/mcp>)| `mcpServers` parameter
+
+**Subagents versus agent teams:** Subagents are ephemeral and isolated: fresh conversation, one task, summary returned to parent. Agent teams coordinate multiple independent Claude Code instances that share a task list and message each other directly. Agent teams are a CLI feature. See [What subagents inherit](</docs/en/agent-sdk/subagents#what-subagents-inherit>) and the [agent teams comparison](</docs/en/agent-teams#compare-with-subagents>) for details.
+
+Every feature you enable adds to your agent’s context window. For per-feature costs and how these features layer together, see [Extend Claude Code](</docs/en/features-overview#understand-context-costs>).
+
+##
+
+
+
+Related resources
+
+ * [Extend Claude Code](</docs/en/features-overview>): Conceptual overview of all extension features, with comparison tables and context cost analysis
+ * [Skills in the SDK](</docs/en/agent-sdk/skills>): Full guide to using skills programmatically
+ * [Subagents](</docs/en/agent-sdk/subagents>): Define and invoke subagents for isolated subtasks
+ * [Hooks](</docs/en/agent-sdk/hooks>): Intercept and control agent behavior at key execution points
+ * [Permissions](</docs/en/agent-sdk/permissions>): Control tool access with modes, rules, and callbacks
+ * [System prompts](</docs/en/agent-sdk/modifying-system-prompts>): Inject context without CLAUDE.md files
Show diff (1239 lines)
--- a/claude-code-on-the-web.md
+++ b/claude-code-on-the-web.md
@@ -1,363 +1,179 @@
-Claude Code on the web is currently in research preview.
-
-##
-
-
-
-What is Claude Code on the web?
-
-Claude Code on the web lets developers kick off Claude Code from the Claude app. This is perfect for:
-
- * **Answering questions** : Ask about code architecture and how features are implemented
- * **Bug fixes and routine tasks** : Well-defined tasks that don’t require frequent steering
- * **Parallel work** : Tackle multiple bug fixes in parallel
- * **Repositories not on your local machine** : Work on code you don’t have checked out locally
- * **Backend changes** : Where Claude Code can write tests and then write code to pass those tests
-
-Claude Code is also available on the Claude app for [iOS](<https://apps.apple.com/us/app/claude-by-anthropic/id6473753684>) and [Android](<https://play.google.com/store/apps/details?id=com.anthropic.claude>) for kicking off tasks on the go and monitoring work in progress. You can kick off new tasks on the web from your terminal with `--remote`, or teleport web sessions back to your terminal to continue locally. To use the web interface while running Claude Code on your own machine instead of cloud infrastructure, see [Remote Control](</docs/en/remote-control>).
-
-##
-
-
-
-Who can use Claude Code on the web?
-
-Claude Code on the web is available in research preview to:
-
- * **Pro users**
- * **Max users**
- * **Team users**
- * **Enterprise users** with premium seats or Chat + Claude Code seats
-
-##
-
-
-
-Getting started
-
-Set up Claude Code on the web from the browser or from your terminal.
-
-###
-
-
-
-From the browser
-
- 1. Visit [claude.ai/code](<https://claude.ai/code>)
- 2. Connect your GitHub account
- 3. Install the Claude GitHub App in your repositories
- 4. Select your default environment
- 5. Submit your coding task
- 6. Review changes in diff view, iterate with comments, then create a pull request
-
-###
-
-
-
-From the terminal
-
-Run `/web-setup` inside Claude Code to connect GitHub using your local `gh` CLI credentials. The command syncs your `gh auth token` to Claude Code on the web, creates a default cloud environment, and opens claude.ai/code in your browser when it finishes. This path requires the `gh` CLI to be installed and authenticated with `gh auth login`. If `gh` is not available, `/web-setup` opens claude.ai/code so you can connect GitHub from the browser instead. Your `gh` credentials give Claude access to clone and push, so you can skip the GitHub App for basic sessions. Install the App later if you want Auto-fix, which uses the App to receive PR webhooks.
-
-Team and Enterprise admins can disable terminal setup with the Quick web setup toggle at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>).
-
-##
-
-
-
-How it works
-
-When you start a task on Claude Code on the web:
-
- 1. **Repository cloning** : Your repository is cloned to an Anthropic-managed virtual machine
- 2. **Environment setup** : Claude prepares a secure cloud environment with your code, then runs your setup script if configured
- 3. **Network configuration** : Internet access is configured based on your settings
- 4. **Task execution** : Claude analyzes code, makes changes, runs tests, and checks its work
- 5. **Completion** : You’re notified when finished and can create a PR with the changes
- 6. **Results** : Changes are pushed to a branch, ready for pull request creation
-
-##
-
-
-
-Review changes with diff view
-
-Diff view lets you see exactly what Claude changed before creating a pull request. Instead of clicking “Create PR” to review changes in GitHub, view the diff directly in the app and iterate with Claude until the changes are ready. When Claude makes changes to files, a diff stats indicator appears showing the number of lines added and removed (for example, `+12 -1`). Select this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right. From the diff view, you can:
-
- * Review changes file by file
- * Comment on specific changes to request modifications
- * Continue iterating with Claude based on what you see
-
-This lets you refine changes through multiple rounds of feedback without creating draft PRs or switching to GitHub.
-
-##
-
-
-
-Auto-fix pull requests
-
-Claude can watch a pull request and automatically respond to CI failures and review comments. Claude subscribes to GitHub activity on the PR, and when a check fails or a reviewer leaves a comment, Claude investigates and pushes a fix if one is clear.
-
-Auto-fix requires the Claude GitHub App to be installed on your repository. If you haven’t already, install it from the [GitHub App page](<https://github.com/apps/claude>) or when prompted during setup.
-
-There are a few ways to turn on auto-fix depending on where the PR came from and what device you’re using:
-
- * **PRs created in Claude Code on the web** : open the CI status bar and select **Auto-fix**
- * **From the mobile app** : tell Claude to auto-fix the PR, for example “watch this PR and fix any CI failures or review comments”
- * **Any existing PR** : paste the PR URL into a session and tell Claude to auto-fix it
-
-###
-
-
-
-How Claude responds to PR activity
-
-When auto-fix is active, Claude receives GitHub events for the PR including new review comments and CI check failures. For each event, Claude investigates and decides how to proceed:
-
- * **Clear fixes** : if Claude is confident in a fix and it doesn’t conflict with earlier instructions, Claude makes the change, pushes it, and explains what was done in the session
- * **Ambiguous requests** : if a reviewer’s comment could be interpreted multiple ways or involves something architecturally significant, Claude asks you before acting
- * **Duplicate or no-action events** : if an event is a duplicate or requires no change, Claude notes it in the session and moves on
-
-Claude may reply to review comment threads on GitHub as part of resolving them. These replies are posted using your GitHub account, so they appear under your username, but each reply is labeled as coming from Claude Code so reviewers know it was written by the agent and not by you directly.
-
-If your repository uses comment-triggered automation such as Atlantis, Terraform Cloud, or custom GitHub Actions that run on `issue_comment` events, be aware that Claude can reply on your behalf, which can trigger those workflows. Review your repository’s automation before enabling auto-fix, and consider disabling auto-fix for repositories where a PR comment can deploy infrastructure or run privileged operations.
-
-##
-
-
-
-Moving tasks between web and terminal
-
-You can start new tasks on the web from your terminal, or pull web sessions into your terminal to continue locally. Web sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude mobile app.
-
-Session handoff is one-way: you can pull web sessions into your terminal, but you can’t push an existing terminal session to the web. The `--remote` flag creates a _new_ web session for your current repository.
-
-###
-
-
-
-From terminal to web
-
-Start a web session from the command line with the `--remote` flag:
-
- claude --remote "Fix the authentication bug in src/auth/login.ts"
-
-This creates a new web session on claude.ai. The task runs in the cloud while you continue working locally. Use `/tasks` to check progress, or open the session on claude.ai or the Claude mobile app to interact directly. From there you can steer Claude, provide feedback, or answer questions just like any other conversation.
-
-####
-
-
-
-Tips for remote tasks
-
-**Plan locally, execute remotely** : For complex tasks, start Claude in plan mode to collaborate on the approach, then send work to the web:
-
- claude --permission-mode plan
-
-In plan mode, Claude can only read files and explore the codebase. Once you’re satisfied with the plan, start a remote session for autonomous execution:
-
- claude --remote "Execute the migration plan in docs/migration-plan.md"
-
-This pattern gives you control over the strategy while letting Claude execute autonomously in the cloud. **Plan in the cloud with ultraplan** : To draft and review the plan itself in a web session, use [ultraplan](</docs/en/ultraplan>). Claude generates the plan on Claude Code on the web while you keep working, then you comment on sections in your browser and choose to execute remotely or send the plan back to your terminal. **Run tasks in parallel** : Each `--remote` command creates its own web session that runs independently. You can kick off multiple tasks and they’ll all run simultaneously in separate sessions:
-
- claude --remote "Fix the flaky test in auth.spec.ts"
- claude --remote "Update the API documentation"
- claude --remote "Refactor the logger to use structured output"
-
-Monitor all sessions with `/tasks`. When a session completes, you can create a PR from the web interface or teleport the session to your terminal to continue working.
-
-###
-
-
-
-From web to terminal
-
-There are several ways to pull a web session into your terminal:
-
- * **Using`/teleport`**: From within Claude Code, run `/teleport` (or `/tp`) to see an interactive picker of your web sessions. If you have uncommitted changes, you’ll be prompted to stash them first.
- * **Using`--teleport`**: From the command line, run `claude --teleport` for an interactive session picker, or `claude --teleport <session-id>` to resume a specific session directly.
- * **From`/tasks`**: Run `/tasks` to see your background sessions, then press `t` to teleport into one
- * **From the web interface** : Click “Open in CLI” to copy a command you can paste into your terminal
-
-When you teleport a session, Claude verifies you’re in the correct repository, fetches and checks out the branch from the remote session, and loads the full conversation history into your terminal.
-
-####
-
-
-
-Requirements for teleporting
-
-Teleport checks these requirements before resuming a session. If any requirement isn’t met, you’ll see an error or be prompted to resolve the issue.
-
-Requirement| Details
+Claude Code on the web is in research preview for Pro, Max, and Team users, and for Enterprise users with premium seats or Chat + Claude Code seats.
+
+Claude Code on the web runs tasks on Anthropic-managed cloud infrastructure at [claude.ai/code](<https://claude.ai/code>). Sessions persist even if you close your browser, and you can monitor them from the Claude mobile app.
+
+New to Claude Code on the web? Start with [Get started](</docs/en/web-quickstart>) to connect your GitHub account and submit your first task.
+
+This page covers:
+
+ * GitHub authentication options: two ways to connect GitHub
+ * The cloud environment: what config carries over, what tools are installed, and how to configure environments
+ * Setup scripts and dependency management
+ * Network access: levels, proxies, and the default allowlist
+ * Move tasks between web and terminal with `--remote` and `--teleport`
+ * Work with sessions: reviewing, sharing, archiving, deleting
+ * Auto-fix pull requests: respond automatically to CI failures and review comments
+ * Security and isolation: how sessions are isolated
+ * Limitations: rate limits and platform restrictions
+
+##
+
+
+
+GitHub authentication options
+
+Cloud sessions need access to your GitHub repositories to clone code and push branches. You can grant access in two ways:
+
+Method| How it works| Best for
+---|---|---
+**GitHub App**| Install the Claude GitHub App on specific repositories during [web onboarding](</docs/en/web-quickstart>). Access is scoped per repository.| Teams that want explicit per-repo authorization
+**`/web-setup`**| Run `/web-setup` in your terminal to sync your local `gh` CLI token to your Claude account. Access matches whatever your `gh` token can see.| Individual developers who already use `gh`
+
+Either method works. [`/schedule`](</docs/en/web-scheduled-tasks>) checks for either form of access and prompts you to run `/web-setup` if neither is configured. See [Connect from your terminal](</docs/en/web-quickstart#connect-from-your-terminal>) for the `/web-setup` walkthrough. The GitHub App is required for Auto-fix, which uses the App to receive PR webhooks. If you connect with `/web-setup` and later want Auto-fix, install the App on those repositories. Team and Enterprise admins can disable `/web-setup` with the Quick web setup toggle at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>).
+
+Organizations with [Zero Data Retention](</docs/en/zero-data-retention>) enabled cannot use `/web-setup` or other cloud session features.
+
+##
+
+
+
+The cloud environment
+
+Each session runs in a fresh Anthropic-managed VM with your repository cloned. This section covers what’s available when a session starts and how to customize it.
+
+###
+
+
+
+What’s available in cloud sessions
+
+Cloud sessions start from a fresh clone of your repository. Anything committed to the repo is available. Anything you’ve installed or configured only on your own machine is not.
+
+| Available in cloud sessions| Why
+---|---|---
+Your repo’s `CLAUDE.md`| Yes| Part of the clone
+Your repo’s `.claude/settings.json` hooks| Yes| Part of the clone
+Your repo’s `.mcp.json` MCP servers| Yes| Part of the clone
+Your repo’s `.claude/rules/`| Yes| Part of the clone
+Your repo’s `.claude/skills/`, `.claude/agents/`, `.claude/commands/`| Yes| Part of the clone
+Plugins declared in `.claude/settings.json`| Yes| Installed at session start from the [marketplace](</docs/en/plugin-marketplaces>) you declared. Requires network access to reach the marketplace source
+Your user `~/.claude/CLAUDE.md`| No| Lives on your machine, not in the repo
+Plugins enabled only in your user settings| No| User-scoped `enabledPlugins` lives in `~/.claude/settings.json`. Declare them in the repo’s `.claude/settings.json` instead
+MCP servers you added with `claude mcp add`| No| Those write to your local user config, not the repo. Declare the server in [`.mcp.json`](</docs/en/mcp#project-scope>) instead
+Static API tokens and credentials| No| No dedicated secrets store exists yet. See below
+Interactive auth like AWS SSO| No| Not supported. SSO requires browser-based login that can’t run in a cloud session
+
+To make configuration available in cloud sessions, commit it to the repo. A dedicated secrets store is not yet available. Both environment variables and setup scripts are stored in the environment configuration, visible to anyone who can edit that environment. If you need secrets in a cloud session, add them as environment variables with that visibility in mind.
+
+###
+
+
+
+Installed tools
+
+Cloud sessions come with common language runtimes, build tools, and databases pre-installed. The table below summarizes what’s included by category.
+
+Category| Included
---|---
-Clean git state| Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed.
-Correct repository| You must run `--teleport` from a checkout of the same repository, not a fork.
-Branch available| The branch from the web session must have been pushed to the remote. Teleport automatically fetches and checks it out.
-Same account| You must be authenticated to the same Claude.ai account used in the web session.
-
-###
-
-
-
-Sharing sessions
-
-To share a session, toggle its visibility according to the account types below. After that, share the session link as-is. Recipients who open your shared session will see the latest state of the session upon load, but the recipient’s page will not update in real time.
-
-####
-
-
-
-Sharing from an Enterprise or Team account
-
-For Enterprise and Team accounts, the two visibility options are **Private** and **Team**. Team visibility makes the session visible to other members of your Claude.ai organization. Repository access verification is enabled by default, based on the GitHub account connected to the recipient’s account. Your account’s display name is visible to all recipients with access. [Claude in Slack](</docs/en/slack>) sessions are automatically shared with Team visibility.
-
-####
-
-
-
-Sharing from a Max or Pro account
-
-For Max and Pro accounts, the two visibility options are **Private** and **Public**. Public visibility makes the session visible to any user logged into claude.ai. Check your session for sensitive content before sharing. Sessions may contain code and credentials from private GitHub repositories. Repository access verification is not enabled by default. Enable repository access verification and/or withhold your name from your shared sessions by going to Settings > Claude Code > Sharing settings.
-
-##
-
-
-
-Schedule recurring tasks
-
-Run Claude on a recurring schedule to automate work like daily PR reviews, dependency audits, and CI failure analysis. See [Schedule tasks on the web](</docs/en/web-scheduled-tasks>) for the full guide.
-
-##
-
-
-
-Managing sessions
-
-###
-
-
-
-Archiving sessions
-
-You can archive sessions to keep your session list organized. Archived sessions are hidden from the default session list but can be viewed by filtering for archived sessions. To archive a session, hover over the session in the sidebar and click the archive icon.
-
-###
-
-
-
-Deleting sessions
-
-Deleting a session permanently removes the session and its data. This action cannot be undone. You can delete a session in two ways:
-
- * **From the sidebar** : Filter for archived sessions, then hover over the session you want to delete and click the delete icon
- * **From the session menu** : Open a session, click the dropdown next to the session title, and select **Delete**
-
-You will be asked to confirm before a session is deleted.
-
-##
-
-
-
-Cloud environment
-
-###
-
-
-
-Default image
-
-We build and maintain a universal image with common toolchains and language ecosystems pre-installed. This image includes:
-
- * Popular programming languages and runtimes
- * Common build tools and package managers
- * Testing frameworks and linters
-
-####
-
-
-
-Checking available tools
-
-To see what’s pre-installed in your environment, ask Claude Code to run:
-
- check-tools
-
-This command displays:
-
- * Programming languages and their versions
- * Available package managers
- * Installed development tools
-
-####
-
-
-
-Language-specific setups
-
-The universal image includes pre-configured environments for:
-
- * **Python** : Python 3.x with pip, poetry, and common scientific libraries
- * **Node.js** : Latest LTS versions with npm, yarn, pnpm, and bun
- * **Ruby** : Versions 3.1.6, 3.2.6, 3.3.6 (default: 3.3.6) with gem, bundler, and rbenv for version management
- * **PHP** : Version 8.4.14
- * **Java** : OpenJDK with Maven and Gradle
- * **Go** : Latest stable version with module support
- * **Rust** : Rust toolchain with cargo
- * **C++** : GCC and Clang compilers
-
-####
-
-
-
-Databases
-
-The universal image includes the following databases:
-
- * **PostgreSQL** : Version 16
- * **Redis** : Version 7.0
-
-###
-
-
-
-Environment configuration
-
-When you start a session in Claude Code on the web, here’s what happens under the hood:
-
- 1. **Environment preparation** : We clone your repository and run any configured setup script. The repo will be cloned with the default branch on your GitHub repo. If you would like to check out a specific branch, you can specify that in the prompt.
- 2. **Network configuration** : We configure internet access for the agent. Internet access is limited by default, but you can configure the environment to have no internet or full internet access based on your needs.
- 3. **Claude Code execution** : Claude Code runs to complete your task, writing code, running tests, and checking its work. You can guide and steer Claude throughout the session via the web interface. Claude respects context you’ve defined in your `CLAUDE.md`.
- 4. **Outcome** : When Claude completes its work, it will push the branch to remote. You will be able to create a PR for the branch.
-
-Claude operates entirely through the terminal and CLI tools available in the environment. It uses the pre-installed tools in the universal image and any additional tools you install through hooks or dependency management.
-
-**To add a new environment:** Select the current environment to open the environment selector, and then select “Add environment”. This will open a dialog where you can specify the environment name, network access level, environment variables, and a setup script. **To update an existing environment:** Select the current environment, to the right of the environment name, and select the settings button. This will open a dialog where you can update the environment name, network access, environment variables, and setup script. **To select your default environment from the terminal:** If you have multiple environments configured, run `/remote-env` to choose which one to use when starting web sessions from your terminal with `--remote`. With a single environment, this command shows your current configuration.
-
-Environment variables must be specified as key-value pairs, in [`.env` format](<https://www.dotenv.org/>). For example:
-
- API_KEY=your_api_key
- DEBUG=true
-
-###
+**Python**| Python 3.x with pip, poetry, uv, black, mypy, pytest, ruff
+**Node.js**| 20, 21, and 22 via nvm, with npm, yarn, pnpm, bun¹, eslint, prettier, chromedriver
+**Ruby**| 3.1, 3.2, 3.3 with gem, bundler, rbenv
+**PHP**| 8.4 with Composer
+**Java**| OpenJDK 21 with Maven and Gradle
+**Go**| latest stable with module support
+**Rust**| rustc and cargo
+**C/C++**| GCC, Clang, cmake, ninja, conan
+**Docker**| docker, dockerd, docker compose
+**Databases**| PostgreSQL 16, Redis 7.0
+**Utilities**| git, jq, yq, ripgrep, tmux, vim, nano
+
+¹ Bun is installed but has known proxy compatibility issues for package fetching. For exact versions, ask Claude to run `check-tools` in a cloud session. This command only exists in cloud sessions.
+
+###
+
+
+
+Work with GitHub issues and pull requests
+
+Cloud sessions include built-in GitHub tools that let Claude read issues, list pull requests, fetch diffs, and post comments without any setup. These tools authenticate through the GitHub proxy using whichever method you configured under GitHub authentication options, so your token never enters the container. The `gh` CLI is not pre-installed. If you need a `gh` command the built-in tools don’t cover, like `gh release` or `gh workflow run`, install and authenticate it yourself:
+
+1
+
+Install gh in your setup script
+
+Add `apt update && apt install -y gh` to your setup script.
+
+2
+
+Provide a token
+
+Add a `GH_TOKEN` environment variable to your environment settings with a GitHub personal access token. `gh` reads `GH_TOKEN` automatically, so no `gh auth login` step is needed.
+
+###
+
+
+
+Run tests, start services, and add packages
+
+Claude runs tests as part of working on a task. Ask for it in your prompt, like “fix the failing tests in `tests/`” or “run pytest after each change.” Test runners like pytest, jest, and cargo test work out of the box since they’re pre-installed. PostgreSQL and Redis are pre-installed but not running by default. Start each one in a setup script or ask Claude to start it during the session:
+
+ service postgresql start
+
+ service redis-server start
+
+Docker is available for running containerized services. Network access to pull images follows your environment’s access level. To add packages that aren’t pre-installed, use a setup script so they’re available at session start. You can also ask Claude to install packages during the session, but those installs don’t persist across sessions.
+
+###
+
+
+
+Resource limits
+
+Cloud sessions run with approximate resource ceilings that may change over time:
+
+ * 4 vCPUs
+ * 16 GB of RAM
+ * 30 GB of disk
+
+Tasks requiring significantly more memory, such as large build jobs or memory-intensive tests, may fail or be terminated. For workloads beyond these limits, use [Remote Control](</docs/en/remote-control>) to run Claude Code on your own hardware.
+
+###
+
+
+
+Configure your environment
+
+Environments control network access, environment variables, and the setup script that runs before a session starts. See Installed tools for what’s available without any configuration. You can manage environments from the web interface or the terminal:
+
+Action| How
+---|---
+Add an environment| Select the current environment to open the selector, then select **Add environment**. The dialog includes name, network access level, environment variables, and setup script.
+Edit an environment| Select the settings icon to the right of the environment name.
+Archive an environment| Open the environment for editing and select **Archive**. Archived environments are hidden from the selector but existing sessions keep running.
+Set the default for `--remote`| Run `/remote-env` in your terminal. If you have a single environment, this command shows your current configuration. `/remote-env` only selects the default; add, edit, and archive environments from the web interface.
+
+Environment variables use `.env` format with one `KEY=value` pair per line. Don’t wrap values in quotes, since quotes are stored as part of the value.
+
+ NODE_ENV=development
+ LOG_LEVEL=debug
+ DATABASE_URL=postgres://localhost:5432/myapp
+
+##
Setup scripts
-A setup script is a Bash script that runs when a new cloud session starts, before Claude Code launches. Use setup scripts to install dependencies, configure tools, or prepare anything the cloud environment needs that isn’t in the default image. Scripts run as root on Ubuntu 24.04, so `apt install` and most language package managers work.
-
-To check what’s already installed before adding it to your script, ask Claude to run `check-tools` in a cloud session.
-
-To add a setup script, open the environment settings dialog and enter your script in the **Setup script** field. This example installs the `gh` CLI, which isn’t in the default image:
+A setup script is a Bash script that runs when a new cloud session starts, before Claude Code launches. Use setup scripts to install dependencies, configure tools, or fetch anything the session needs that isn’t pre-installed. Scripts run as root on Ubuntu 24.04, so `apt install` and most language package managers work. To add a setup script, open the environment settings dialog and enter your script in the **Setup script** field. This example installs the `gh` CLI, which isn’t pre-installed:
#!/bin/bash
apt update && apt install -y gh
-Setup scripts run only when creating a new session. They are skipped when resuming an existing session. If the script exits non-zero, the session fails to start. Append `|| true` to non-critical commands to avoid blocking the session on a flaky install.
-
-Setup scripts that install packages need network access to reach registries. The default network access allows connections to common package registries including npm, PyPI, RubyGems, and crates.io. Scripts will fail to install packages if your environment has network access disabled.
-
-####
+Setup scripts run only when creating a new session. They are skipped when resuming an existing session. If the script exits non-zero, the session fails to start. Append `|| true` to non-critical commands to avoid blocking the session on an intermittent install failure.
+
+Setup scripts that install packages need network access to reach registries. The default **Trusted** network access allows connections to common package registries including npm, PyPI, RubyGems, and crates.io. Scripts will fail to install packages if your environment uses **None** network access.
+
+###
@@ -378,21 +194,15 @@
-Dependency management
-
-Custom environment images and snapshots are not yet supported. Use setup scripts to install packages when a session starts, or [SessionStart hooks](</docs/en/hooks#sessionstart>) for dependency installation that should also run in local environments. SessionStart hooks have known limitations. To configure automatic dependency installation with a setup script, open your environment settings and add a script:
-
- #!/bin/bash
- npm install
- pip install -r requirements.txt
-
-Alternatively, you can use SessionStart hooks in your repository’s `.claude/settings.json` file for dependency installation that should also run in local environments:
+Install dependencies with a SessionStart hook
+
+To install dependencies only in cloud sessions, add a SessionStart hook to your repo’s `.claude/settings.json`:
{
"hooks": {
"SessionStart": [
{
- "matcher": "startup",
+ "matcher": "startup|resume",
"hooks": [
{
"type": "command",
@@ -404,11 +214,10 @@
}
}
-Create the corresponding script at `scripts/install_pkgs.sh`:
+Create the script at `scripts/install_pkgs.sh` and make it executable with `chmod +x`. The `CLAUDE_CODE_REMOTE` environment variable is set to `true` in cloud sessions, so you can use it to skip local execution:
#!/bin/bash
- # Only run in remote environments
if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then
exit 0
fi
@@ -417,40 +226,55 @@
pip install -r requirements.txt
exit 0
-Make it executable: `chmod +x scripts/install_pkgs.sh`
-
-####
-
-
-
-Persist environment variables
-
-SessionStart hooks can persist environment variables for subsequent Bash commands by writing to the file specified in the `CLAUDE_ENV_FILE` environment variable. For details, see [SessionStart hooks](</docs/en/hooks#sessionstart>) in the hooks reference.
-
-####
-
-
-
-Dependency management limitations
-
- * **Hooks fire for all sessions** : SessionStart hooks run in both local and remote environments. There is no hook configuration to scope a hook to remote sessions only. To skip local execution, check the `CLAUDE_CODE_REMOTE` environment variable in your script as shown above.
- * **Requires network access** : Install commands need network access to reach package registries. If your environment is configured with “No internet” access, these hooks will fail. Use “Limited” (the default) or “Full” network access. The default allowlist includes common registries like npm, PyPI, RubyGems, and crates.io.
- * **Proxy compatibility** : All outbound traffic in remote environments passes through a security proxy. Some package managers do not work correctly with this proxy. Bun is a known example.
- * **Runs on every session start** : Hooks run each time a session starts or resumes, adding startup latency. Keep install scripts fast by checking whether dependencies are already present before reinstalling.
-
-##
-
-
-
-Network access and security
-
-###
-
-
-
-Network policy
-
-####
+SessionStart hooks have some limitations in cloud sessions:
+
+ * **No cloud-only scoping** : hooks run in both local and cloud sessions. To skip local execution, check the `CLAUDE_CODE_REMOTE` environment variable as shown above.
+ * **Requires network access** : install commands need to reach package registries. If your environment uses **None** network access, these hooks fail. The default allowlist under **Trusted** covers npm, PyPI, RubyGems, and crates.io.
+ * **Proxy compatibility** : all outbound traffic passes through a security proxy. Some package managers don’t work correctly with this proxy. Bun is a known example.
+ * **Adds startup latency** : hooks run each time a session starts or resumes. Keep install scripts fast by checking whether dependencies are already present before reinstalling.
+
+To persist environment variables for subsequent Bash commands, write to the file at `$CLAUDE_ENV_FILE`. See [SessionStart hooks](</docs/en/hooks#sessionstart>) for details. Custom environment images and snapshots are not yet supported.
+
+##
+
+
+
+Network access
+
+Network access controls outbound connections from the cloud environment. Each environment specifies one access level, and you can extend it with custom allowed domains. The default is **Trusted** , which allows package registries and other allowlisted domains.
+
+###
+
+
+
+Access levels
+
+Choose an access level when you create or edit an environment:
+
+Level| Outbound connections
+---|---
+**None**| No outbound network access
+**Trusted**| Allowlisted domains only: package registries, GitHub, cloud SDKs
+**Full**| Any domain
+**Custom**| Your own allowlist, optionally including the defaults
+
+GitHub operations use a separate proxy that is independent of this setting.
+
+###
+
+
+
+Allow specific domains
+
+To allow domains that aren’t in the Trusted list, select **Custom** in the environment’s network access settings. An **Allowed domains** field appears. Enter one domain per line:
+
+ api.example.com
+ *.internal.example.com
+ registry.example.com
+
+Use `*.` for wildcard subdomain matching. Check **Also include default list of common package managers** to keep the Trusted domains alongside your custom entries, or leave it unchecked to allow only what you list.
+
+###
@@ -458,11 +282,11 @@
For security, all GitHub operations go through a dedicated proxy service that transparently handles all git interactions. Inside the sandbox, the git client authenticates using a custom-built scoped credential. This proxy:
- * Manages GitHub authentication securely - the git client uses a scoped credential inside the sandbox, which the proxy verifies and translates to your actual GitHub authentication token
+ * Manages GitHub authentication securely: the git client uses a scoped credential inside the sandbox, which the proxy verifies and translates to your actual GitHub authentication token
* Restricts git push operations to the current working branch for safety
- * Enables seamless cloning, fetching, and PR operations while maintaining security boundaries
-
-####
+ * Enables cloning, fetching, and PR operations while maintaining security boundaries
+
+###
@@ -478,35 +302,20 @@
-Access levels
-
-By default, network access is limited to allowlisted domains. You can configure custom network access, including disabling network access.
-
-###
-
-
-
Default allowed domains
-When using “Limited” network access, the following domains are allowed by default:
-
-####
-
-
-
-Anthropic Services
+When using **Trusted** network access, the following domains are allowed by default. Domains marked with `*` indicate wildcard subdomain matching, so `*.gcr.io` allows any subdomain of `gcr.io`.
+
+Anthropic services
* api.anthropic.com
* statsig.anthropic.com
+ * docs.claude.com
* platform.claude.com
* code.claude.com
* claude.ai
-####
-
-
-
-Version Control
+Version control
* github.com
* [www.github.com](<http://www.github.com>)
@@ -515,6 +324,7 @@
* raw.githubusercontent.com
* pkg-npm.githubusercontent.com
* objects.githubusercontent.com
+ * release-assets.githubusercontent.com
* codeload.github.com
* avatars.githubusercontent.com
* camo.githubusercontent.com
@@ -526,11 +336,7 @@
* [www.bitbucket.org](<http://www.bitbucket.org>)
* api.bitbucket.org
-####
-
-
-
-Container Registries
+Container registries
* registry-1.docker.io
* auth.docker.io
@@ -546,11 +352,7 @@
* *.data.mcr.microsoft.com
* public.ecr.aws
-####
-
-
-
-Cloud Platforms
+Cloud platforms
* cloud.google.com
* accounts.google.com
@@ -580,11 +382,7 @@
* download.oracle.com
* yum.oracle.com
-####
-
-
-
-Package Managers - JavaScript/Node
+JavaScript and Node package managers
* registry.npmjs.org
* [www.npmjs.com](<http://www.npmjs.com>)
@@ -594,11 +392,7 @@
* yarnpkg.com
* registry.yarnpkg.com
-####
-
-
-
-Package Managers - Python
+Python package managers
* pypi.org
* [www.pypi.org](<http://www.pypi.org>)
@@ -609,11 +403,7 @@
* pypa.io
* [www.pypa.io](<http://www.pypa.io>)
-####
-
-
-
-Package Managers - Ruby
+Ruby package managers
* rubygems.org
* [www.rubygems.org](<http://www.rubygems.org>)
@@ -628,11 +418,7 @@
* rvm.io
* get.rvm.io
-####
-
-
-
-Package Managers - Rust
+Rust package managers
* crates.io
* [www.crates.io](<http://www.crates.io>)
@@ -642,11 +428,7 @@
* static.rust-lang.org
* [www.rust-lang.org](<http://www.rust-lang.org>)
-####
-
-
-
-Package Managers - Go
+Go package managers
* proxy.golang.org
* sum.golang.org
@@ -656,31 +438,24 @@
* goproxy.io
* pkg.go.dev
-####
-
-
-
-Package Managers - JVM
+JVM package managers
* maven.org
* repo.maven.org
* central.maven.org
* repo1.maven.org
+ * repo.maven.apache.org
* jcenter.bintray.com
* gradle.org
* [www.gradle.org](<http://www.gradle.org>)
* services.gradle.org
* plugins.gradle.org
- * kotlin.org
- * [www.kotlin.org](<http://www.kotlin.org>)
+ * kotlinlang.org
+ * [www.kotlinlang.org](<http://www.kotlinlang.org>)
* spring.io
* repo.spring.io
-####
-
-
-
-Package Managers - Other Languages
+Other package managers
* packagist.org (PHP Composer)
* [www.packagist.org](<http://www.packagist.org>)
@@ -706,11 +481,7 @@
* swift.org
* [www.swift.org](<http://www.swift.org>)
-####
-
-
-
-Linux Distributions
+Linux distributions
* archive.ubuntu.com
* security.ubuntu.com
@@ -720,12 +491,9 @@
* ppa.launchpad.net
* launchpad.net
* [www.launchpad.net](<http://www.launchpad.net>)
-
-####
-
-
-
-Development Tools & Platforms
+ * *.nixos.org
+
+Development tools and platforms
* dl.k8s.io (Kubernetes)
* pkgs.k8s.io
@@ -752,63 +520,256 @@
* download.eclipse.org
* nodejs.org (Node.js)
* [www.nodejs.org](<http://www.nodejs.org>)
-
-####
-
-
-
-Cloud Services & Monitoring
+ * developer.apple.com
+ * developer.android.com
+ * pkg.stainless.com
+ * binaries.prisma.sh
+
+Cloud services and monitoring
* statsig.com
* [www.statsig.com](<http://www.statsig.com>)
* api.statsig.com
* sentry.io
* *.sentry.io
+ * downloads.sentry-cdn.com
* http-intake.logs.datadoghq.com
* *.datadoghq.com
* *.datadoghq.eu
-
-####
-
-
-
-Content Delivery & Mirrors
+ * api.honeycomb.io
+
+Content delivery and mirrors
* sourceforge.net
* *.sourceforge.net
* packagecloud.io
* *.packagecloud.io
-
-####
-
-
-
-Schema & Configuration
+ * fonts.googleapis.com
+ * fonts.gstatic.com
+
+Schema and configuration
* json-schema.org
* [www.json-schema.org](<http://www.json-schema.org>)
* json.schemastore.org
* [www.schemastore.org](<http://www.schemastore.org>)
+Model Context Protocol
+
+ * *.modelcontextprotocol.io
+
+##
+
+
+
+Move tasks between web and terminal
+
+These workflows require the [Claude Code CLI](</docs/en/quickstart>) signed in to the same claude.ai account. You can start new cloud sessions from your terminal, or pull cloud sessions into your terminal to continue locally. Cloud sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude mobile app.
+
+From the CLI, session handoff is one-way: you can pull cloud sessions into your terminal with `--teleport`, but you can’t push an existing terminal session to the web. The `--remote` flag creates a new cloud session for your current repository. The [Desktop app](</docs/en/desktop#continue-in-another-surface>) provides a Continue in menu that can send a local session to the web.
+
+###
+
+
+
+From terminal to web
+
+Start a cloud session from the command line with the `--remote` flag:
+
+ claude --remote "Fix the authentication bug in src/auth/login.ts"
+
+This creates a new cloud session on claude.ai. The session clones your current directory’s GitHub remote at your current branch, so push first if you have local commits, since the VM clones from GitHub rather than your machine. `--remote` works with a single repository at a time. The task runs in the cloud while you continue working locally.
+
+`--remote` creates cloud sessions. `--remote-control` is unrelated: it exposes a local CLI session for monitoring from the web. See [Remote Control](</docs/en/remote-control>).
+
+Use `/tasks` in the Claude Code CLI to check progress, or open the session on claude.ai or the Claude mobile app to interact directly. From there you can steer Claude, provide feedback, or answer questions just like any other conversation.
+
####
-Model Context Protocol
-
- * *.modelcontextprotocol.io
-
-Domains marked with `*` indicate wildcard subdomain matching. For example, `*.gcr.io` allows access to any subdomain of `gcr.io`.
-
-###
-
-
-
-Security best practices for customized network access
-
- 1. **Principle of least privilege** : Only enable the minimum network access required
- 2. **Audit regularly** : Review allowed domains periodically
- 3. **Use HTTPS** : Always prefer HTTPS endpoints over HTTP
+Tips for cloud tasks
+
+**Plan locally, execute remotely** : for complex tasks, start Claude in plan mode to collaborate on the approach, then send work to the cloud:
+
+ claude --permission-mode plan
+
+In plan mode, Claude reads files, runs commands to explore, and proposes a plan without editing source code. Once you’re satisfied, save the plan to the repo, commit, and push so the cloud VM can clone it. Then start a cloud session for autonomous execution:
+
+ claude --remote "Execute the migration plan in docs/migration-plan.md"
+
+This pattern gives you control over the strategy while letting Claude execute autonomously in the cloud. **Plan in the cloud with ultraplan** : to draft and review the plan itself in a web session, use [ultraplan](</docs/en/ultraplan>). Claude generates the plan on Claude Code on the web while you keep working, then you comment on sections in your browser and choose to execute remotely or send the plan back to your terminal. **Run tasks in parallel** : each `--remote` command creates its own cloud session that runs independently. You can start multiple tasks and they’ll all run simultaneously in separate sessions:
+
+ claude --remote "Fix the flaky test in auth.spec.ts"
+ claude --remote "Update the API documentation"
+ claude --remote "Refactor the logger to use structured output"
+
+Monitor all sessions with `/tasks` in the Claude Code CLI. When a session completes, you can create a PR from the web interface or teleport the session to your terminal to continue working.
+
+####
+
+
+
+Send local repositories without GitHub
+
+When you run `claude --remote` from a repository that isn’t connected to GitHub, Claude Code bundles your local repository and uploads it directly to the cloud session. The bundle includes your full repository history across all branches, plus any uncommitted changes to tracked files. This fallback activates automatically when GitHub access isn’t available. To force it even when GitHub is connected, set `CCR_FORCE_BUNDLE=1`:
+
+ CCR_FORCE_BUNDLE=1 claude --remote "Run the test suite and fix any failures"
+
+Bundled repositories must meet these limits:
+
+ * The directory must be a git repository with at least one commit
+ * The bundled repository must be under 100 MB. Larger repositories fall back to bundling only the current branch, then to a single squashed snapshot of the working tree, and fail only if the snapshot is still too large
+ * Untracked files are not included; run `git add` on files you want the cloud session to see
+ * Sessions created from a bundle can’t push back to a remote unless you also have GitHub authentication configured
+
+###
+
+
+
+From web to terminal
+
+Pull a cloud session into your terminal using any of these:
+
+ * **Using`--teleport`**: from the command line, run `claude --teleport` for an interactive session picker, or `claude --teleport <session-id>` to resume a specific session directly. If you have uncommitted changes, you’ll be prompted to stash them first.
+ * **Using`/teleport`**: inside an existing CLI session, run `/teleport` (or `/tp`) to open the same session picker without restarting Claude Code.
+ * **From`/tasks`**: run `/tasks` to see your background sessions, then press `t` to teleport into one
+ * **From the web interface** : select **Open in CLI** to copy a command you can paste into your terminal
+
+When you teleport a session, Claude verifies you’re in the correct repository, fetches and checks out the branch from the cloud session, and loads the full conversation history into your terminal. `--teleport` is distinct from `--resume`. `--resume` reopens a conversation from this machine’s local history and doesn’t list cloud sessions; `--teleport` pulls a cloud session and its branch.
+
+####
+
+
+
+Teleport requirements
+
+Teleport checks these requirements before resuming a session. If any requirement isn’t met, you’ll see an error or be prompted to resolve the issue.
+
+Requirement| Details
+---|---
+Clean git state| Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed.
+Correct repository| You must run `--teleport` from a checkout of the same repository, not a fork.
+Branch available| The branch from the cloud session must have been pushed to the remote. Teleport automatically fetches and checks it out.
+Same account| You must be authenticated to the same claude.ai account used in the cloud session.
+
+####
+
+
+
+`--teleport` is unavailable
+
+Teleport requires claude.ai subscription authentication. If you’re authenticated via API key, Bedrock, Vertex AI, or Microsoft Foundry, run `/login` to sign in with your claude.ai account instead. If you’re already signed in via claude.ai and `--teleport` is still unavailable, your organization may have disabled cloud sessions.
+
+##
+
+
+
+Work with sessions
+
+Sessions appear in the sidebar at claude.ai/code. From there you can review changes, share with teammates, archive finished work, or delete sessions permanently.
+
+###
+
+
+
+Manage context
+
+Cloud sessions support [built-in commands](</docs/en/commands>) that produce text output. Commands that open an interactive terminal picker, like `/model` or `/config`, are not available. For context management specifically:
+
+Command| Works in cloud sessions| Notes
+---|---|---
+`/compact`| Yes| Summarizes the conversation to free up context. Accepts optional focus instructions like `/compact keep the test output`
+`/context`| Yes| Shows what’s currently in the context window
+`/clear`| No| Start a new session from the sidebar instead
+
+Auto-compaction runs automatically when the context window approaches capacity, the same as in the CLI. To trigger it earlier, set [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](</docs/en/env-vars>) in your environment variables. For example, `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70` compacts at 70% capacity instead of the default ~95%. To change the effective window size for compaction calculations, use [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>). [Subagents](</docs/en/sub-agents>) work the same way they do locally. Claude can spawn them with the Task tool to offload research or parallel work into a separate context window, keeping the main conversation lighter. Subagents defined in your repo’s `.claude/agents/` are picked up automatically. [Agent teams](</docs/en/agent-teams>) are off by default but can be enabled by adding `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` to your environment variables.
+
+###
+
+
+
+Review changes
+
+Each session shows a diff indicator with lines added and removed, like `+42 -18`. Select it to open the diff view, leave inline comments on specific lines, and send them to Claude with your next message. See [Review and iterate](</docs/en/web-quickstart#review-and-iterate>) for the full walkthrough including PR creation. To have Claude monitor the PR for CI failures and review comments automatically, see Auto-fix pull requests.
+
+###
+
+
+
+Share sessions
+
+To share a session, toggle its visibility according to the account types below. After that, share the session link as-is. Recipients see the latest state when they open the link, but their view doesn’t update in real time.
+
+####
+
+
+
+Share from an Enterprise or Team account
+
+For Enterprise and Team accounts, the two visibility options are **Private** and **Team**. Team visibility makes the session visible to other members of your claude.ai organization. Repository access verification is enabled by default, based on the GitHub account connected to the recipient’s account. Your account’s display name is visible to all recipients with access. [Claude in Slack](</docs/en/slack>) sessions are automatically shared with Team visibility.
+
+####
+
+
+
+Share from a Max or Pro account
+
+For Max and Pro accounts, the two visibility options are **Private** and **Public**. Public visibility makes the session visible to any user logged into claude.ai. Check your session for sensitive content before sharing. Sessions may contain code and credentials from private GitHub repositories. Repository access verification is not enabled by default. To require recipients to have repository access, or to hide your name from shared sessions, go to Settings > Claude Code > Sharing settings.
+
+###
+
+
+
+Archive sessions
+
+You can archive sessions to keep your session list organized. Archived sessions are hidden from the default session list but can be viewed by filtering for archived sessions. To archive a session, hover over the session in the sidebar and select the archive icon.
+
+###
+
+
+
+Delete sessions
+
+Deleting a session permanently removes the session and its data. This action cannot be undone. You can delete a session in two ways:
+
+ * **From the sidebar** : filter for archived sessions, then hover over the session you want to delete and select the delete icon
+ * **From the session menu** : open a session, select the dropdown next to the session title, and select **Delete**
+
+You will be asked to confirm before a session is deleted.
+
+##
+
+
+
+Auto-fix pull requests
+
+Claude can watch a pull request and automatically respond to CI failures and review comments. Claude subscribes to GitHub activity on the PR, and when a check fails or a reviewer leaves a comment, Claude investigates and pushes a fix if one is clear.
+
+Auto-fix requires the Claude GitHub App to be installed on your repository. If you haven’t already, install it from the [GitHub App page](<https://github.com/apps/claude>) or when prompted during [setup](</docs/en/web-quickstart#connect-github-and-create-an-environment>).
+
+There are a few ways to turn on auto-fix depending on where the PR came from and what device you’re using:
+
+ * **PRs created in Claude Code on the web** : open the CI status bar and select **Auto-fix**
+ * **From your terminal** : run [`/autofix-pr`](</docs/en/commands#built-in-commands>) while on the PR’s branch. Claude Code detects the open PR with `gh`, spawns a web session, and turns on auto-fix in one step
+ * **From the mobile app** : tell Claude to auto-fix the PR, for example “watch this PR and fix any CI failures or review comments”
+ * **Any existing PR** : paste the PR URL into a session and tell Claude to auto-fix it
+
+###
+
+
+
+How Claude responds to PR activity
+
+When auto-fix is active, Claude receives GitHub events for the PR including new review comments and CI check failures. For each event, Claude investigates and decides how to proceed:
+
+ * **Clear fixes** : if Claude is confident in a fix and it doesn’t conflict with earlier instructions, Claude makes the change, pushes it, and explains what was done in the session
+ * **Ambiguous requests** : if a reviewer’s comment could be interpreted multiple ways or involves something architecturally significant, Claude asks you before acting
+ * **Duplicate or no-action events** : if an event is a duplicate or requires no change, Claude notes it in the session and moves on
+
+Claude may reply to review comment threads on GitHub as part of resolving them. These replies are posted using your GitHub account, so they appear under your username, but each reply is labeled as coming from Claude Code so reviewers know it was written by the agent and not by you directly.
+
+If your repository uses comment-triggered automation such as Atlantis, Terraform Cloud, or custom GitHub Actions that run on `issue_comment` events, be aware that Claude can reply on your behalf, which can trigger those workflows. Review your repository’s automation before enabling auto-fix, and consider disabling auto-fix for repositories where a PR comment can deploy infrastructure or run privileged operations.
##
@@ -816,23 +777,12 @@
Security and isolation
-Claude Code on the web provides strong security guarantees:
-
- * **Isolated virtual machines** : Each session runs in an isolated, Anthropic-managed VM
- * **Network access controls** : Network access is limited by default, and can be disabled
-
-When running with network access disabled, Claude Code is allowed to communicate with the Anthropic API which may still allow data to exit the isolated Claude Code VM.
-
- * **Credential protection** : Sensitive credentials (such as git credentials or signing keys) are never inside the sandbox with Claude Code. Authentication is handled through a secure proxy using scoped credentials
- * **Secure analysis** : Code is analyzed and modified within isolated VMs before creating PRs
-
-##
-
-
-
-Pricing and rate limits
-
-Claude Code on the web shares rate limits with all other Claude and Claude Code usage within your account. Running multiple tasks in parallel will consume more rate limits proportionately.
+Each cloud session is separated from your machine and from other sessions through several layers:
+
+ * **Isolated virtual machines** : each session runs in an isolated, Anthropic-managed VM
+ * **Network access controls** : network access is limited by default, and can be disabled. When running with network access disabled, Claude Code can still communicate with the Anthropic API, which may allow data to exit the VM.
+ * **Credential protection** : sensitive credentials such as git credentials or signing keys are never inside the sandbox with Claude Code. Authentication is handled through a secure proxy using scoped credentials.
+ * **Secure analysis** : code is analyzed and modified within isolated VMs before creating PRs
##
@@ -840,17 +790,11 @@
Limitations
- * **Repository authentication** : You can only move sessions from web to local when you are authenticated to the same account
- * **Platform restrictions** : Claude Code on the web only works with code hosted in GitHub. Self-hosted [GitHub Enterprise Server](</docs/en/github-enterprise-server>) instances are supported for Team and Enterprise plans. GitLab and other non-GitHub repositories cannot be used with cloud sessions
-
-##
-
-
-
-Best practices
-
- 1. **Automate environment setup** : Use setup scripts to install dependencies and configure tools before Claude Code launches. For more advanced scenarios, configure [SessionStart hooks](</docs/en/hooks#sessionstart>).
- 2. **Document requirements** : Clearly specify dependencies and commands in your `CLAUDE.md` file. If you have an `AGENTS.md` file, you can source it in your `CLAUDE.md` using `@AGENTS.md` to maintain a single source of truth.
+Before relying on cloud sessions for a workflow, account for these constraints:
+
+ * **Rate limits** : Claude Code on the web shares rate limits with all other Claude and Claude Code usage within your account. Running multiple tasks in parallel consumes more rate limits proportionately. There is no separate compute charge for the cloud VM.
+ * **Repository authentication** : you can only move sessions from web to local when you are authenticated to the same account
+ * **Platform restrictions** : repository cloning and pull request creation require GitHub. Self-hosted [GitHub Enterprise Server](</docs/en/github-enterprise-server>) instances are supported for Team and Enterprise plans. GitLab, Bitbucket, and other non-GitHub repositories can be sent to cloud sessions as a local bundle, but the session can’t push results back to the remote
##
@@ -858,7 +802,8 @@
Related resources
- * [Hooks configuration](</docs/en/hooks>)
- * [Settings reference](</docs/en/settings>)
- * [Security](</docs/en/security>)
- * [Data usage](</docs/en/data-usage>)
+ * [Schedule tasks on the web](</docs/en/web-scheduled-tasks>): automate recurring work like daily PR reviews and dependency audits
+ * [Hooks configuration](</docs/en/hooks>): run scripts at session lifecycle events
+ * [Settings reference](</docs/en/settings>): all configuration options
+ * [Security](</docs/en/security>): isolation guarantees and data handling
+ * [Data usage](</docs/en/data-usage>): what Anthropic retains from cloud sessions
Show diff (106 lines)
--- a/claude-directory.md
+++ b/claude-directory.md
@@ -1,4 +1,4 @@
-Claude Code reads instructions, settings, skills, subagents, and memory from your project directory and from `~/.claude` in your home directory. Commit project files to git to share them with your team; files in `~/.claude` are personal configuration that applies across all your projects. Most users only edit `CLAUDE.md` and `settings.json`. The rest of the directory is optional: add skills, rules, or subagents as you need them. This page is an interactive explorer: click files in the tree to see what each one does, when it loads, and an example. For a quick reference, see the file reference table below.
+Claude Code reads instructions, settings, skills, subagents, and memory from your project directory and from `~/.claude` in your home directory. Commit project files to git to share them with your team; files in `~/.claude` are personal configuration that applies across all your projects. If you set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>), every `~/.claude` path on this page lives under that directory instead. Most users only edit `CLAUDE.md` and `settings.json`. The rest of the directory is optional: add skills, rules, or subagents as you need them. This page is an interactive explorer: click files in the tree to see what each one does, when it loads, and an example. For a quick reference, see the file reference table below.
##
@@ -6,7 +6,7 @@
What’s not shown
-The explorer covers files you author and edit. A few authored files live elsewhere:
+The explorer covers files you author and edit. A few related files live elsewhere:
File| Location| Purpose
---|---|---
@@ -78,23 +78,23 @@
Application data
-Beyond the config you author, `~/.claude` holds data Claude Code writes during sessions. These files are plaintext. Anything that passes through a tool (file contents, command output, pasted text) lands in a transcript on disk.
+Beyond the config you author, `~/.claude` holds data Claude Code writes during sessions. These files are plaintext. Anything that passes through a tool lands in a transcript on disk: file contents, command output, pasted text.
###
-Swept automatically
+Cleaned up automatically
-Files older than [`cleanupPeriodDays`](</docs/en/settings#available-settings>) (default 30) are deleted on the next startup.
+Files in the paths below are deleted on startup once they’re older than [`cleanupPeriodDays`](</docs/en/settings#available-settings>). The default is 30 days.
Path under `~/.claude/`| Contents
---|---
`projects/<project>/<session>.jsonl`| Full conversation transcript: every message, tool call, and tool result
`projects/<project>/<session>/tool-results/`| Large tool outputs spilled to separate files
`file-history/<session>/`| Pre-edit snapshots of files Claude changed, used for [checkpoint restore](</docs/en/checkpointing>)
-`plans/`| Plan files written during [plan mode](</docs/en/permission-modes#plan-mode>)
-`debug/`| Per-session debug logs
+`plans/`| Plan files written during [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>)
+`debug/`| Per-session debug logs, written only when you start with `--debug` or run `/debug`
`paste-cache/`, `image-cache/`| Contents of large pastes and attached images
`session-env/`| Per-session environment metadata
@@ -102,20 +102,18 @@
-Not swept
+Kept until you delete them
-These persist until you delete them.
+The following paths are not covered by automatic cleanup and persist indefinitely.
Path under `~/.claude/`| Contents
---|---
`history.jsonl`| Every prompt you’ve typed, with timestamp and project path. Used for up-arrow recall.
-`statsig/`| Feature-flag cache and a stable anonymous device ID
`stats-cache.json`| Aggregated token and cost counts shown by `/cost`
`backups/`| Timestamped copies of `~/.claude.json` taken before config migrations
-`downloads/`| Native binary downloads staged by the auto-updater
`todos/`| Legacy per-session task lists. No longer written by current versions; safe to delete.
-`shell-snapshots/` and `sockets/` are runtime files removed when the session exits cleanly.
+`shell-snapshots/` holds runtime files removed when the session exits cleanly. Other small cache and lock files appear depending on which features you use and are safe to delete.
###
@@ -123,10 +121,10 @@
Plaintext storage
-Transcripts and history are not encrypted at rest; OS file permissions are the only protection. If a tool reads a `.env` file or a command prints a credential, that value is written to `projects/<project>/<session>.jsonl`. To reduce exposure:
+Transcripts and history are not encrypted at rest. OS file permissions are the only protection. If a tool reads a `.env` file or a command prints a credential, that value is written to `projects/<project>/<session>.jsonl`. To reduce exposure:
* Lower `cleanupPeriodDays` to shorten how long transcripts are kept
- * For headless runs, pass `--no-session-persistence` with `-p`, or set `persistSession: false` in the SDK, to skip writing transcripts entirely. There is no interactive-mode equivalent.
+ * In non-interactive mode, pass `--no-session-persistence` alongside `-p` to skip writing transcripts entirely. In the Agent SDK, set `persistSession: false`. There is no interactive-mode equivalent.
* Use [permission rules](</docs/en/permissions>) to deny reads of credential files
###
@@ -135,16 +133,19 @@
Clear local data
-You can delete these at any time. You lose the listed capability for past sessions; new sessions are unaffected.
+You can delete any of the application-data paths above at any time. New sessions are unaffected. The table below shows what you lose for past sessions.
Delete| You lose
---|---
`~/.claude/projects/`| Resume, continue, and rewind for past sessions
`~/.claude/history.jsonl`| Up-arrow prompt recall
`~/.claude/file-history/`| Checkpoint restore for past sessions
-`~/.claude/debug/`, `paste-cache/`, `image-cache/`, `todos/`| Nothing user-facing
+`~/.claude/stats-cache.json`| Historical totals shown by `/cost`
+`~/.claude/backups/`| Rollback copies of `~/.claude.json` from past config migrations
+`~/.claude/debug/`, `~/.claude/plans/`, `~/.claude/paste-cache/`, `~/.claude/image-cache/`, `~/.claude/session-env/`| Nothing user-facing
+`~/.claude/todos/`| Nothing. Legacy directory not written by current versions.
-Don’t delete `~/.claude.json`, `settings.json`, or `plugins/`: those hold your auth, preferences, and installed plugins.
+Don’t delete `~/.claude.json`, `~/.claude/settings.json`, or `~/.claude/plugins/`: those hold your auth, preferences, and installed plugins.
##
--- a/cli-reference.md
+++ b/cli-reference.md
@@ -63,7 +63,7 @@
`--include-hook-events`| Include all hook lifecycle events in the output stream. Requires `--output-format stream-json`| `claude -p --output-format stream-json --include-hook-events "query"`
`--include-partial-messages`| Include partial streaming events in output. Requires `--print` and `--output-format stream-json`| `claude -p --output-format stream-json --include-partial-messages "query"`
`--input-format`| Specify input format for print mode (options: `text`, `stream-json`)| `claude -p --output-format json --input-format stream-json`
-`--json-schema`| Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](<https://platform.claude.com/docs/en/agent-sdk/structured-outputs>))| `claude -p --json-schema '{"type":"object","properties":{...}}' "query"`
+`--json-schema`| Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](</docs/en/agent-sdk/structured-outputs>))| `claude -p --json-schema '{"type":"object","properties":{...}}' "query"`
`--maintenance`| Run maintenance hooks and start interactive mode| `claude --maintenance`
`--max-budget-usd`| Maximum dollar amount to spend on API calls before stopping (print mode only)| `claude -p --max-budget-usd 5.00 "query"`
`--max-turns`| Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default| `claude -p --max-turns 3 "query"`
@@ -79,7 +79,7 @@
`--permission-mode`| Begin in a specified [permission mode](</docs/en/permission-modes>). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, or `bypassPermissions`. Overrides `defaultMode` from settings files| `claude --permission-mode plan`
`--permission-prompt-tool`| Specify an MCP tool to handle permission prompts in non-interactive mode| `claude -p --permission-prompt-tool mcp_auth_tool "query"`
`--plugin-dir`| Load plugins from a directory for this session only. Each flag takes one path. Repeat the flag for multiple directories: `--plugin-dir A --plugin-dir B`| `claude --plugin-dir ./my-plugins`
-`--print`, `-p`| Print response without interactive mode (see [Agent SDK documentation](<https://platform.claude.com/docs/en/agent-sdk/overview>) for programmatic usage details)| `claude -p "query"`
+`--print`, `-p`| Print response without interactive mode (see [Agent SDK documentation](</docs/en/agent-sdk/overview>) for programmatic usage details)| `claude -p "query"`
`--remote`| Create a new [web session](</docs/en/claude-code-on-the-web>) on claude.ai with the provided task description| `claude --remote "Fix the login bug"`
`--remote-control`, `--rc`| Start an interactive session with [Remote Control](</docs/en/remote-control#start-a-remote-control-session>) enabled so you can also control it from claude.ai or the Claude app. Optionally pass a name for the session| `claude --remote-control "My Project"`
`--remote-control-session-name-prefix <prefix>`| Prefix for auto-generated [Remote Control](</docs/en/remote-control>) session names when no explicit name is set. Defaults to your machine’s hostname, producing names like `myhost-graceful-unicorn`. Set `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` for the same effect| `claude remote-control --remote-control-session-name-prefix dev-box`
@@ -127,4 +127,4 @@
* [Quickstart guide](</docs/en/quickstart>) \- Getting started with Claude Code
* [Common workflows](</docs/en/common-workflows>) \- Advanced workflows and patterns
* [Settings](</docs/en/settings>) \- Configuration options
- * [Agent SDK documentation](<https://platform.claude.com/docs/en/agent-sdk/overview>) \- Programmatic usage and integrations
+ * [Agent SDK documentation](</docs/en/agent-sdk/overview>) \- Programmatic usage and integrations
--- a/commands.md
+++ b/commands.md
@@ -4,6 +4,7 @@
---|---
`/add-dir <path>`| Add a working directory for file access during the current session. Most `.claude/` configuration is [not discovered](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) from the added directory
`/agents`| Manage [agent](</docs/en/sub-agents>) configurations
+`/autofix-pr [prompt]`| Spawn a [Claude Code on the web](</docs/en/claude-code-on-the-web#auto-fix-pull-requests>) session that watches the current branch’s PR and pushes fixes when CI fails or reviewers leave comments. Detects the open PR from your checked-out branch with `gh pr view`; to watch a different PR, check out its branch first. By default the remote session is told to fix every CI failure and review comment; pass a prompt to give it different instructions, for example `/autofix-pr only fix lint and type errors`. Requires the `gh` CLI and access to [Claude Code on the web](</docs/en/claude-code-on-the-web#who-can-use-claude-code-on-the-web>)
`/btw <question>`| Ask a quick [side question](</docs/en/interactive-mode#side-questions-with-btw>) without adding to the conversation
`/chrome`| Configure [Claude in Chrome](</docs/en/chrome>) settings
`/clear`| Clear conversation history and free up context. Aliases: `/reset`, `/new`
@@ -47,7 +48,7 @@
`/release-notes`| View the changelog in an interactive version picker. Select a specific version to see its release notes, or choose to show all versions
`/reload-plugins`| Reload all active [plugins](</docs/en/plugins>) to apply pending changes without restarting. Reports counts for each reloaded component and flags any load errors
`/remote-control`| Make this session available for [remote control](</docs/en/remote-control>) from claude.ai. Alias: `/rc`
-`/remote-env`| Configure the default remote environment for [web sessions started with `--remote`](</docs/en/claude-code-on-the-web#environment-configuration>)
+`/remote-env`| Configure the default remote environment for [web sessions started with `--remote`](</docs/en/claude-code-on-the-web#configure-your-environment>)
`/rename [name]`| Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history
`/resume [session]`| Resume a conversation by ID or name, or open the session picker. Alias: `/continue`
`/review`| Deprecated. Install the [`code-review` plugin](<https://github.com/anthropics/claude-plugins-official/tree/main/plugins/code-review>) instead: `claude plugin install code-review@claude-plugins-official`
@@ -62,6 +63,7 @@
`/statusline`| Configure Claude Code’s [status line](</docs/en/statusline>). Describe what you want, or run without arguments to auto-configure from your shell prompt
`/stickers`| Order Claude Code stickers
`/tasks`| List and manage background tasks. Also available as `/bashes`
+`/teleport`| Pull a [Claude Code on the web](</docs/en/claude-code-on-the-web#from-web-to-terminal>) session into this terminal: opens a picker, then fetches the branch and conversation. Also available as `/tp`. Requires a claude.ai subscription
`/terminal-setup`| Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Alacritty, or Warp
`/theme`| Change the color theme. Includes light and dark variants, colorblind-accessible (daltonized) themes, and ANSI themes that use your terminal’s color palette
`/ultraplan <prompt>`| Draft a plan in an [ultraplan](</docs/en/ultraplan>) session, review it in your browser, then execute remotely or send it back to your terminal
@@ -69,6 +71,7 @@
`/usage`| Show plan usage limits and rate limit status
`/vim`| Removed in v2.1.92. To toggle between Vim and Normal editing modes, use `/config` → Editor mode
`/voice`| Toggle push-to-talk [voice dictation](</docs/en/voice-dictation>). Requires a Claude.ai account
+`/web-setup`| Connect your GitHub account to [Claude Code on the web](</docs/en/web-quickstart#connect-from-your-terminal>) using your local `gh` CLI credentials. `/schedule` prompts for this automatically if GitHub isn’t connected
##
Show diff (204 lines)
--- a/cost-tracking.md
+++ b/cost-tracking.md
@@ -0,0 +1,201 @@
+The Claude Agent SDK provides detailed token usage information for each interaction with Claude. This guide explains how to properly track costs and understand usage reporting, especially when dealing with parallel tool uses and multi-step conversations. For complete API documentation, see the [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) and [Python SDK reference](</docs/en/agent-sdk/python>).
+
+##
+
+
+
+Understand token usage
+
+The TypeScript and Python SDKs expose the same usage data with different field names:
+
+ * **TypeScript** provides per-step token breakdowns on each assistant message (`message.message.id`, `message.message.usage`), per-model cost via `modelUsage` on the result message, and a cumulative total on the result message.
+ * **Python** provides per-step token breakdowns on each assistant message (`message.usage`, `message.message_id`), per-model cost via `model_usage` on the result message, and the accumulated total on the result message (`total_cost_usd` and `usage` dict).
+
+Both SDKs use the same underlying cost model and expose the same granularity. The difference is in field naming and where per-step usage is nested. Cost tracking depends on understanding how the SDK scopes usage data:
+
+ * **`query()` call:** one invocation of the SDK’s `query()` function. A single call can involve multiple steps (Claude responds, uses tools, gets results, responds again). Each call produces one [`result`](</docs/en/agent-sdk/typescript#sdk-result-message>) message at the end.
+ * **Step:** a single request/response cycle within a `query()` call. Each step produces assistant messages with token usage.
+ * **Session:** a series of `query()` calls linked by a session ID (using the `resume` option). Each `query()` call within a session reports its own cost independently.
+
+The following diagram shows the message stream from a single `query()` call, with token usage reported at each step and the authoritative total at the end:
+
+1
+
+Each step produces assistant messages
+
+When Claude responds, it sends one or more assistant messages. In TypeScript, each assistant message contains a nested `BetaMessage` (accessed via `message.message`) with an `id` and a [`usage`](<https://platform.claude.com/docs/en/api/messages>) object with token counts (`input_tokens`, `output_tokens`). In Python, the `AssistantMessage` dataclass exposes the same data directly via `message.usage` and `message.message_id`. When Claude uses multiple tools in one turn, all messages in that turn share the same ID, so deduplicate by ID to avoid double-counting.
+
+2
+
+The result message provides the authoritative total
+
+When the `query()` call completes, the SDK emits a result message with `total_cost_usd` and cumulative `usage`. This is available in both TypeScript ([`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdk-result-message>)) and Python ([`ResultMessage`](</docs/en/agent-sdk/python#result-message>)). If you make multiple `query()` calls (for example, in a multi-turn session), each result only reflects the cost of that individual call. If you only need the total cost, you can ignore the per-step usage and read this single value.
+
+##
+
+
+
+Get the total cost of a query
+
+The result message ([TypeScript](</docs/en/agent-sdk/typescript#sdk-result-message>), [Python](</docs/en/agent-sdk/python#result-message>)) is the last message in every `query()` call. It includes `total_cost_usd`, the cumulative cost across all steps in that call. This works for both success and error results. If you use sessions to make multiple `query()` calls, each result only reflects the cost of that individual call. The following examples iterate over the message stream from a `query()` call and print the total cost when the `result` message arrives:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({ prompt: "Summarize this project" })) {
+ if (message.type === "result") {
+ console.log(`Total cost: $${message.total_cost_usd}`);
+ }
+ }
+
+##
+
+
+
+Track per-step and per-model usage
+
+The examples in this section use TypeScript field names. In Python, the equivalent fields are [`AssistantMessage.usage`](</docs/en/agent-sdk/python#assistant-message>) and `AssistantMessage.message_id` for per-step usage, and [`ResultMessage.model_usage`](</docs/en/agent-sdk/python#result-message>) for per-model breakdowns.
+
+###
+
+
+
+Track per-step usage
+
+Each assistant message contains a nested `BetaMessage` (accessed via `message.message`) with an `id` and `usage` object with token counts. When Claude uses tools in parallel, multiple messages share the same `id` with identical usage data. Track which IDs you’ve already counted and skip duplicates to avoid inflated totals.
+
+Parallel tool calls produce multiple assistant messages whose nested `BetaMessage` shares the same `id` and identical usage. Always deduplicate by ID to get accurate per-step token counts.
+
+The following example accumulates input and output tokens across all steps, counting each unique message ID only once:
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ const seenIds = new Set<string>();
+ let totalInputTokens = 0;
+ let totalOutputTokens = 0;
+
+ for await (const message of query({ prompt: "Summarize this project" })) {
+ if (message.type === "assistant") {
+ const msgId = message.message.id;
+
+ // Parallel tool calls share the same ID, only count once
+ if (!seenIds.has(msgId)) {
+ seenIds.add(msgId);
+ totalInputTokens += message.message.usage.input_tokens;
+ totalOutputTokens += message.message.usage.output_tokens;
+ }
+ }
+ }
+
+ console.log(`Steps: ${seenIds.size}`);
+ console.log(`Input tokens: ${totalInputTokens}`);
+ console.log(`Output tokens: ${totalOutputTokens}`);
+
+###
+
+
+
+Break down usage per model
+
+The result message includes [`modelUsage`](</docs/en/agent-sdk/typescript#model-usage>), a map of model name to per-model token counts and cost. This is useful when you run multiple models (for example, Haiku for subagents and Opus for the main agent) and want to see where tokens are going. The following example runs a query and prints the cost and token breakdown for each model used:
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({ prompt: "Summarize this project" })) {
+ if (message.type !== "result") continue;
+
+ for (const [modelName, usage] of Object.entries(message.modelUsage)) {
+ console.log(`${modelName}: $${usage.costUSD.toFixed(4)}`);
+ console.log(` Input tokens: ${usage.inputTokens}`);
+ console.log(` Output tokens: ${usage.outputTokens}`);
+ console.log(` Cache read: ${usage.cacheReadInputTokens}`);
+ console.log(` Cache creation: ${usage.cacheCreationInputTokens}`);
+ }
+ }
+
+##
+
+
+
+Accumulate costs across multiple calls
+
+Each `query()` call returns its own `total_cost_usd`. The SDK does not provide a session-level total, so if your application makes multiple `query()` calls (for example, in a multi-turn session or across different users), accumulate the totals yourself. The following examples run two `query()` calls sequentially, add each call’s `total_cost_usd` to a running total, and print both the per-call and combined cost:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Track cumulative cost across multiple query() calls
+ let totalSpend = 0;
+
+ const prompts = [
+ "Read the files in src/ and summarize the architecture",
+ "List all exported functions in src/auth.ts"
+ ];
+
+ for (const prompt of prompts) {
+ for await (const message of query({ prompt })) {
+ if (message.type === "result") {
+ totalSpend += message.total_cost_usd;
+ console.log(`This call: $${message.total_cost_usd}`);
+ }
+ }
+ }
+
+ console.log(`Total spend: $${totalSpend.toFixed(4)}`);
+
+##
+
+
+
+Handle errors, caching, and token discrepancies
+
+For accurate cost tracking, account for failed conversations, cache token pricing, and occasional reporting inconsistencies.
+
+###
+
+
+
+Resolve output token discrepancies
+
+In rare cases, you might observe different `output_tokens` values for messages with the same ID. When this occurs:
+
+ 1. **Use the highest value:** the final message in a group typically contains the accurate total.
+ 2. **Verify against total cost:** the `total_cost_usd` in the result message is authoritative.
+ 3. **Report inconsistencies:** file issues at the [Claude Code GitHub repository](<https://github.com/anthropics/claude-code/issues>).
+
+###
+
+
+
+Track costs on failed conversations
+
+Both success and error result messages include `usage` and `total_cost_usd`. If a conversation fails mid-way, you still consumed tokens up to the point of failure. Always read cost data from the result message regardless of its `subtype`.
+
+###
+
+
+
+Track cache tokens
+
+The Agent SDK automatically uses [prompt caching](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching>) to reduce costs on repeated content. You do not need to configure caching yourself. The usage object includes two additional fields for cache tracking:
+
+ * `cache_creation_input_tokens`: tokens used to create new cache entries (charged at a higher rate than standard input tokens).
+ * `cache_read_input_tokens`: tokens read from existing cache entries (charged at a reduced rate).
+
+Track these separately from `input_tokens` to understand caching savings. In TypeScript, these fields are typed on the [`Usage`](</docs/en/agent-sdk/typescript#usage>) object. In Python, they appear as keys in the [`ResultMessage.usage`](</docs/en/agent-sdk/python#result-message>) dict (for example, `message.usage.get("cache_read_input_tokens", 0)`).
+
+##
+
+
+
+Related documentation
+
+ * [TypeScript SDK Reference](</docs/en/agent-sdk/typescript>) \- Complete API documentation
+ * [SDK Overview](</docs/en/agent-sdk/overview>) \- Getting started with the SDK
+ * [SDK Permissions](</docs/en/agent-sdk/permissions>) \- Managing tool permissions
Show diff (545 lines)
--- a/custom-tools.md
+++ b/custom-tools.md
@@ -0,0 +1,542 @@
+Custom tools extend the Agent SDK by letting you define your own functions that Claude can call during a conversation. Using the SDK’s in-process MCP server, you can give Claude access to databases, external APIs, domain-specific logic, or any other capability your application needs. This guide covers how to define tools with input schemas and handlers, bundle them into an MCP server, pass them to `query`, and control which tools Claude can access. It also covers error handling, tool annotations, and returning non-text content like images.
+
+##
+
+
+
+Quick reference
+
+If you want to…| Do this
+---|---
+Define a tool| Use [`@tool`](</docs/en/agent-sdk/python#tool>) (Python) or [`tool()`](</docs/en/agent-sdk/typescript#tool>) (TypeScript) with a name, description, schema, and handler. See Create a custom tool.
+Register a tool with Claude| Wrap in `create_sdk_mcp_server` / `createSdkMcpServer` and pass to `mcpServers` in `query()`. See Call a custom tool.
+Pre-approve a tool| Add to your allowed tools. See Configure allowed tools.
+Remove a built-in tool from Claude’s context| Pass a `tools` array listing only the built-ins you want. See Configure allowed tools.
+Let Claude call tools in parallel| Set `readOnlyHint: true` on tools with no side effects. See Add tool annotations.
+Handle errors without stopping the loop| Return `isError: true` instead of throwing. See Handle errors.
+Return images or files| Use `image` or `resource` blocks in the content array. See Return images and resources.
+Scale to many tools| Use [tool search](</docs/en/agent-sdk/tool-search>) to load tools on demand.
+
+##
+
+
+
+Create a custom tool
+
+A tool is defined by four parts, passed as arguments to the [`tool()`](</docs/en/agent-sdk/typescript#tool>) helper in TypeScript or the [`@tool`](</docs/en/agent-sdk/python#tool>) decorator in Python:
+
+ * **Name:** a unique identifier Claude uses to call the tool.
+ * **Description:** what the tool does. Claude reads this to decide when to call it.
+ * **Input schema:** the arguments Claude must provide. In TypeScript this is always a [Zod schema](<https://zod.dev/>), and the handler’s `args` are typed from it automatically. In Python this is a dict mapping names to types, like `{"latitude": float}`, which the SDK converts to JSON Schema for you. The Python decorator also accepts a full [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) dict directly when you need enums, ranges, optional fields, or nested objects.
+ * **Handler:** the async function that runs when Claude calls the tool. It receives the validated arguments and must return an object with:
+ * `content` (required): an array of result blocks, each with a `type` of `"text"`, `"image"`, or `"resource"`. See Return images and resources for non-text blocks.
+ * `isError` (optional): set to `true` to signal a tool failure so Claude can react to it. See Handle errors.
+
+After defining a tool, wrap it in a server with [`createSdkMcpServer`](</docs/en/agent-sdk/typescript#create-sdk-mcp-server>) (TypeScript) or [`create_sdk_mcp_server`](</docs/en/agent-sdk/python#create-sdk-mcp-server>) (Python). The server runs in-process inside your application, not as a separate process.
+
+###
+
+
+
+Weather tool example
+
+This example defines a `get_temperature` tool and wraps it in an MCP server. It only sets up the tool; to pass it to `query` and run it, see Call a custom tool below.
+
+Python
+
+TypeScript
+
+ from typing import Any
+ import httpx
+ from claude_agent_sdk import tool, create_sdk_mcp_server
+
+ # Define a tool: name, description, input schema, handler
+ @tool(
+ "get_temperature",
+ "Get the current temperature at a location",
+ {"latitude": float, "longitude": float},
+ )
+ async def get_temperature(args: dict[str, Any]) -> dict[str, Any]:
+ async with httpx.AsyncClient() as client:
+ response = await client.get(
+ "https://api.open-meteo.com/v1/forecast",
+ params={
+ "latitude": args["latitude"],
+ "longitude": args["longitude"],
+ "current": "temperature_2m",
+ "temperature_unit": "fahrenheit",
+ },
+ )
+ data = response.json()
+
+ # Return a content array - Claude sees this as the tool result
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": f"Temperature: {data['current']['temperature_2m']}°F",
+ }
+ ]
+ }
+
+ # Wrap the tool in an in-process MCP server
+ weather_server = create_sdk_mcp_server(
+ name="weather",
+ version="1.0.0",
+ tools=[get_temperature],
+ )
+
+See the [`tool()`](</docs/en/agent-sdk/typescript#tool>) TypeScript reference or the [`@tool`](</docs/en/agent-sdk/python#tool>) Python reference for full parameter details, including JSON Schema input formats and return value structure.
+
+To make a parameter optional: in TypeScript, add `.default()` to the Zod field. In Python, the dict schema treats every key as required, so leave the parameter out of the schema, mention it in the description string, and read it with `args.get()` in the handler. The `get_precipitation_chance` tool below shows both patterns.
+
+###
+
+
+
+Call a custom tool
+
+Pass the MCP server you created to `query` via the `mcpServers` option. The key in `mcpServers` becomes the `{server_name}` segment in each tool’s fully qualified name: `mcp__{server_name}__{tool_name}`. List that name in `allowedTools` so the tool runs without a permission prompt. These snippets reuse the `weatherServer` from the example above to ask Claude what the weather is in a specific location.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ async def main():
+ options = ClaudeAgentOptions(
+ mcp_servers={"weather": weather_server},
+ allowed_tools=["mcp__weather__get_temperature"],
+ )
+
+ async for message in query(
+ prompt="What's the temperature in San Francisco?",
+ options=options,
+ ):
+ # ResultMessage is the final message after all tool calls complete
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+
+ asyncio.run(main())
+
+###
+
+
+
+Add more tools
+
+A server holds as many tools as you list in its `tools` array. With more than one tool on a server, you can list each one in `allowedTools` individually or use the wildcard `mcp__weather__*` to cover every tool the server exposes. The example below adds a second tool, `get_precipitation_chance`, to the `weatherServer` from the weather tool example and rebuilds it with both tools in the array.
+
+Python
+
+TypeScript
+
+ # Define a second tool for the same server
+ @tool(
+ "get_precipitation_chance",
+ "Get the hourly precipitation probability for a location. "
+ "Optionally pass 'hours' (1-24) to control how many hours to return.",
+ {"latitude": float, "longitude": float},
+ )
+ async def get_precipitation_chance(args: dict[str, Any]) -> dict[str, Any]:
+ # 'hours' isn't in the schema - read it with .get() to make it optional
+ hours = args.get("hours", 12)
+ async with httpx.AsyncClient() as client:
+ response = await client.get(
+ "https://api.open-meteo.com/v1/forecast",
+ params={
+ "latitude": args["latitude"],
+ "longitude": args["longitude"],
+ "hourly": "precipitation_probability",
+ "forecast_days": 1,
+ },
+ )
+ data = response.json()
+ chances = data["hourly"]["precipitation_probability"][:hours]
+
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": f"Next {hours} hours: {'%, '.join(map(str, chances))}%",
+ }
+ ]
+ }
+
+ # Rebuild the server with both tools in the array
+ weather_server = create_sdk_mcp_server(
+ name="weather",
+ version="1.0.0",
+ tools=[get_temperature, get_precipitation_chance],
+ )
+
+Every tool in this array consumes context window space on every turn. If you’re defining dozens of tools, see [tool search](</docs/en/agent-sdk/tool-search>) to load them on demand instead.
+
+###
+
+
+
+Add tool annotations
+
+[Tool annotations](<https://modelcontextprotocol.io/docs/concepts/tools#tool-annotations>) are optional metadata describing how a tool behaves. Pass them as the fifth argument to `tool()` helper in TypeScript or via the `annotations` keyword argument for the `@tool` decorator in Python. All hint fields are Booleans.
+
+Field| Default| Meaning
+---|---|---
+`readOnlyHint`| `false`| Tool does not modify its environment. Controls whether the tool can be called in parallel with other read-only tools.
+`destructiveHint`| `true`| Tool may perform destructive updates. Informational only.
+`idempotentHint`| `false`| Repeated calls with the same arguments have no additional effect. Informational only.
+`openWorldHint`| `true`| Tool reaches systems outside your process. Informational only.
+
+Annotations are metadata, not enforcement. A tool marked `readOnlyHint: true` can still write to disk if that’s what the handler does. Keep the annotation accurate to the handler. This example adds `readOnlyHint` to the `get_temperature` tool from the weather tool example.
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import tool, ToolAnnotations
+
+ @tool(
+ "get_temperature",
+ "Get the current temperature at a location",
+ {"latitude": float, "longitude": float},
+ annotations=ToolAnnotations(
+ readOnlyHint=True
+ ), # Lets Claude batch this with other read-only calls
+ )
+ async def get_temperature(args):
+ return {"content": [{"type": "text", "text": "..."}]}
+
+See `ToolAnnotations` in the [TypeScript](</docs/en/agent-sdk/typescript#tool-annotations>) or [Python](</docs/en/agent-sdk/python#tool-annotations>) reference.
+
+##
+
+
+
+Control tool access
+
+The weather tool example registered a server and listed tools in `allowedTools`. This section covers how tool names are constructed and how to scope access when you have multiple tools or want to restrict built-ins.
+
+###
+
+
+
+Tool name format
+
+When MCP tools are exposed to Claude, their names follow a specific format:
+
+ * Pattern: `mcp__{server_name}__{tool_name}`
+ * Example: A tool named `get_temperature` in server `weather` becomes `mcp__weather__get_temperature`
+
+###
+
+
+
+Configure allowed tools
+
+The `tools` option and the allowed/disallowed lists operate on separate layers. `tools` controls which built-in tools appear in Claude’s context. Allowed and disallowed tool lists control whether calls are approved or denied once Claude attempts them.
+
+Option| Layer| Effect
+---|---|---
+`tools: ["Read", "Grep"]`| Availability| Only the listed built-ins are in Claude’s context. Unlisted built-ins are removed. MCP tools are unaffected.
+`tools: []`| Availability| All built-ins are removed. Claude can only use your MCP tools.
+allowed tools| Permission| Listed tools run without a permission prompt. Unlisted tools remain available; calls go through the [permission flow](</docs/en/agent-sdk/permissions>).
+disallowed tools| Permission| Every call to a listed tool is denied. The tool stays in Claude’s context, so Claude may still attempt it before the call is rejected.
+
+To limit which built-ins Claude can use, prefer `tools` over disallowed tools. Omitting a tool from `tools` removes it from context so Claude never attempts it; listing it in `disallowedTools` (Python: `disallowed_tools`) blocks the call but leaves the tool visible, so Claude may waste a turn trying it. See [Configure permissions](</docs/en/agent-sdk/permissions>) for the full evaluation order.
+
+##
+
+
+
+Handle errors
+
+How your handler reports errors determines whether the agent loop continues or stops:
+
+What happens| Result
+---|---
+Handler throws an uncaught exception| Agent loop stops. Claude never sees the error, and the `query` call fails.
+Handler catches the error and returns `isError: true` (TS) / `"is_error": True` (Python)| Agent loop continues. Claude sees the error as data and can retry, try a different tool, or explain the failure.
+
+The example below catches two kinds of failures inside the handler instead of letting them throw. A non-200 HTTP status is caught from the response and returned as an error result. A network error or invalid JSON is caught by the surrounding `try/except` (Python) or `try/catch` (TypeScript) and also returned as an error result. In both cases the handler returns normally and the agent loop continues.
+
+Python
+
+TypeScript
+
+ import json
+ import httpx
+ from typing import Any
+
+ @tool(
+ "fetch_data",
+ "Fetch data from an API",
+ {"endpoint": str}, # Simple schema
+ )
+ async def fetch_data(args: dict[str, Any]) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient() as client:
+ response = await client.get(args["endpoint"])
+ if response.status_code != 200:
+ # Return the failure as a tool result so Claude can react to it.
+ # is_error marks this as a failed call rather than odd-looking data.
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": f"API error: {response.status_code} {response.reason_phrase}",
+ }
+ ],
+ "is_error": True,
+ }
+
+ data = response.json()
+ return {"content": [{"type": "text", "text": json.dumps(data, indent=2)}]}
+ except Exception as e:
+ # Catching here keeps the agent loop alive. An uncaught exception
+ # would end the whole query() call.
+ return {
+ "content": [{"type": "text", "text": f"Failed to fetch data: {str(e)}"}],
+ "is_error": True,
+ }
+
+##
+
+
+
+Return images and resources
+
+The `content` array in a tool result accepts `text`, `image`, and `resource` blocks. You can mix them in the same response.
+
+###
+
+
+
+Images
+
+An image block carries the image bytes inline, encoded as base64. There is no URL field. To return an image that lives at a URL, fetch it in the handler, read the response bytes, and base64-encode them before returning. The result is processed as visual input.
+
+Field| Type| Notes
+---|---|---
+`type`| `"image"`|
+`data`| `string`| Base64-encoded bytes. Raw base64 only, no `data:image/...;base64,` prefix
+`mimeType`| `string`| Required. For example `image/png`, `image/jpeg`, `image/webp`, `image/gif`
+
+Python
+
+TypeScript
+
+ import base64
+ import httpx
+
+ # Define a tool that fetches an image from a URL and returns it to Claude
+ @tool("fetch_image", "Fetch an image from a URL and return it to Claude", {"url": str})
+ async def fetch_image(args):
+ async with httpx.AsyncClient() as client: # Fetch the image bytes
+ response = await client.get(args["url"])
+
+ return {
+ "content": [
+ {
+ "type": "image",
+ "data": base64.b64encode(response.content).decode(
+ "ascii"
+ ), # Base64-encode the raw bytes
+ "mimeType": response.headers.get(
+ "content-type", "image/png"
+ ), # Read MIME type from the response
+ }
+ ]
+ }
+
+###
+
+
+
+Resources
+
+A resource block embeds a piece of content identified by a URI. The URI is a label for Claude to reference; the actual content rides in the block’s `text` or `blob` field. Use this when your tool produces something that makes sense to address by name later, such as a generated file or a record from an external system.
+
+Field| Type| Notes
+---|---|---
+`type`| `"resource"`|
+`resource.uri`| `string`| Identifier for the content. Any URI scheme
+`resource.text`| `string`| The content, if it’s text. Provide this or `blob`, not both
+`resource.blob`| `string`| The content base64-encoded, if it’s binary
+`resource.mimeType`| `string`| Optional
+
+This example shows a resource block returned from inside a tool handler. The URI `file:///tmp/report.md` is a label that Claude can reference later; the SDK does not read from that path.
+
+TypeScript
+
+Python
+
+ return {
+ content: [
+ {
+ type: "resource",
+ resource: {
+ uri: "file:///tmp/report.md", // Label for Claude to reference, not a path the SDK reads
+ mimeType: "text/markdown",
+ text: "# Report\n..." // The actual content, inline
+ }
+ }
+ ]
+ };
+
+These block shapes come from the MCP `CallToolResult` type. See the [MCP specification](<https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result>) for the full definition.
+
+##
+
+
+
+Example: unit converter
+
+This tool converts values between units of length, temperature, and weight. A user can ask “convert 100 kilometers to miles” or “what is 72°F in Celsius,” and Claude picks the right unit type and units from the request. It demonstrates two patterns:
+
+ * **Enum schemas:** `unit_type` is constrained to a fixed set of values. In TypeScript, use `z.enum()`. In Python, the dict schema doesn’t support enums, so the full JSON Schema dict is required.
+ * **Unsupported input handling:** when a conversion pair isn’t found, the handler returns `isError: true` so Claude can tell the user what went wrong rather than treating a failure as a normal result.
+
+Python
+
+TypeScript
+
+ from typing import Any
+ from claude_agent_sdk import tool, create_sdk_mcp_server
+
+ # z.enum() in TypeScript becomes an "enum" constraint in JSON Schema.
+ # The dict schema has no equivalent, so full JSON Schema is required.
+ @tool(
+ "convert_units",
+ "Convert a value from one unit to another",
+ {
+ "type": "object",
+ "properties": {
+ "unit_type": {
+ "type": "string",
+ "enum": ["length", "temperature", "weight"],
+ "description": "Category of unit",
+ },
+ "from_unit": {
+ "type": "string",
+ "description": "Unit to convert from, e.g. kilometers, fahrenheit, pounds",
+ },
+ "to_unit": {"type": "string", "description": "Unit to convert to"},
+ "value": {"type": "number", "description": "Value to convert"},
+ },
+ "required": ["unit_type", "from_unit", "to_unit", "value"],
+ },
+ )
+ async def convert_units(args: dict[str, Any]) -> dict[str, Any]:
+ conversions = {
+ "length": {
+ "kilometers_to_miles": lambda v: v * 0.621371,
+ "miles_to_kilometers": lambda v: v * 1.60934,
+ "meters_to_feet": lambda v: v * 3.28084,
+ "feet_to_meters": lambda v: v * 0.3048,
+ },
+ "temperature": {
+ "celsius_to_fahrenheit": lambda v: (v * 9) / 5 + 32,
+ "fahrenheit_to_celsius": lambda v: (v - 32) * 5 / 9,
+ "celsius_to_kelvin": lambda v: v + 273.15,
+ "kelvin_to_celsius": lambda v: v - 273.15,
+ },
+ "weight": {
+ "kilograms_to_pounds": lambda v: v * 2.20462,
+ "pounds_to_kilograms": lambda v: v * 0.453592,
+ "grams_to_ounces": lambda v: v * 0.035274,
+ "ounces_to_grams": lambda v: v * 28.3495,
+ },
+ }
+
+ key = f"{args['from_unit']}_to_{args['to_unit']}"
+ fn = conversions.get(args["unit_type"], {}).get(key)
+
+ if not fn:
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": f"Unsupported conversion: {args['from_unit']} to {args['to_unit']}",
+ }
+ ],
+ "is_error": True,
+ }
+
+ result = fn(args["value"])
+ return {
+ "content": [
+ {
+ "type": "text",
+ "text": f"{args['value']} {args['from_unit']} = {result:.4f} {args['to_unit']}",
+ }
+ ]
+ }
+
+ converter_server = create_sdk_mcp_server(
+ name="converter",
+ version="1.0.0",
+ tools=[convert_units],
+ )
+
+Once the server is defined, pass it to `query` the same way as the weather example. This example sends three different prompts in a loop to show the same tool handling different unit types. For each response, it inspects `AssistantMessage` objects (which contain the tool calls Claude made during that turn) and prints each `ToolUseBlock` before printing the final `ResultMessage` text. This lets you see when Claude is using the tool versus answering from its own knowledge.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import (
+ query,
+ ClaudeAgentOptions,
+ ResultMessage,
+ AssistantMessage,
+ ToolUseBlock,
+ )
+
+ async def main():
+ options = ClaudeAgentOptions(
+ mcp_servers={"converter": converter_server},
+ allowed_tools=["mcp__converter__convert_units"],
+ )
+
+ prompts = [
+ "Convert 100 kilometers to miles.",
+ "What is 72°F in Celsius?",
+ "How many pounds is 5 kilograms?",
+ ]
+
+ for prompt in prompts:
+ async for message in query(prompt=prompt, options=options):
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, ToolUseBlock):
+ print(f"[tool call] {block.name}({block.input})")
+ elif isinstance(message, ResultMessage) and message.subtype == "success":
+ print(f"Q: {prompt}\nA: {message.result}\n")
+
+ asyncio.run(main())
+
+##
+
+
+
+Next steps
+
+Custom tools wrap async functions in a standard interface. You can mix the patterns on this page in the same server: a single server can hold a database tool, an API gateway tool, and an image renderer alongside each other. From here:
+
+ * If your server grows to dozens of tools, see [tool search](</docs/en/agent-sdk/tool-search>) to defer loading them until Claude needs them.
+ * To connect to external MCP servers (filesystem, GitHub, Slack) instead of building your own, see [Connect MCP servers](</docs/en/agent-sdk/mcp>).
+ * To control which tools run automatically versus requiring approval, see [Configure permissions](</docs/en/agent-sdk/permissions>).
+
+##
+
+
+
+Related documentation
+
+ * [TypeScript SDK Reference](</docs/en/agent-sdk/typescript>)
+ * [Python SDK Reference](</docs/en/agent-sdk/python>)
+ * [MCP Documentation](<https://modelcontextprotocol.io>)
+ * [SDK Overview](</docs/en/agent-sdk/overview>)
--- a/data-usage.md
+++ b/data-usage.md
@@ -52,9 +52,9 @@
* Standard: 30-day retention period
* [Zero data retention](</docs/en/zero-data-retention>): available for Claude Code on Claude for Enterprise. ZDR is enabled on a per-organization basis; each new organization must have ZDR enabled separately by your account team
- * Local caching: Claude Code clients store session transcripts locally in plaintext under `~/.claude/projects/` for 30 days by default (configurable via `cleanupPeriodDays`) to enable session resumption. See [application data](</docs/en/claude-directory#application-data>) for what’s stored and how to clear it.
+ * Local caching: Claude Code clients store session transcripts locally in plaintext under `~/.claude/projects/` for 30 days by default to enable session resumption. Adjust the period with `cleanupPeriodDays`. See [application data](</docs/en/claude-directory#application-data>) for what’s stored and how to clear it.
-You can delete individual Claude Code on the web sessions at any time. Deleting a session permanently removes the session’s event data. For instructions on how to delete sessions, see [Managing sessions](</docs/en/claude-code-on-the-web#managing-sessions>). Learn more about data retention practices in our [Privacy Center](<https://privacy.anthropic.com/>). For full details, please review our [Commercial Terms of Service](<https://www.anthropic.com/legal/commercial-terms>) (for Team, Enterprise, and API users) or [Consumer Terms](<https://www.anthropic.com/legal/consumer-terms>) (for Free, Pro, and Max users) and [Privacy Policy](<https://www.anthropic.com/legal/privacy>).
+You can delete individual Claude Code on the web sessions at any time. Deleting a session permanently removes the session’s event data. For instructions on how to delete sessions, see [Delete sessions](</docs/en/claude-code-on-the-web#delete-sessions>). Learn more about data retention practices in our [Privacy Center](<https://privacy.anthropic.com/>). For full details, please review our [Commercial Terms of Service](<https://www.anthropic.com/legal/commercial-terms>) (for Team, Enterprise, and API users) or [Consumer Terms](<https://www.anthropic.com/legal/consumer-terms>) (for Free, Pro, and Max users) and [Privacy Policy](<https://www.anthropic.com/legal/privacy>).
##
--- a/desktop.md
+++ b/desktop.md
@@ -67,8 +67,8 @@
Mode| Settings key| Behavior
---|---|---
**Ask permissions**| `default`| Claude asks before editing files or running commands. You see a diff and can accept or reject each change. Recommended for new users.
-**Auto accept edits**| `acceptEdits`| Claude auto-accepts file edits but still asks before running terminal commands. Use this when you trust file changes and want faster iteration.
-**Plan mode**| `plan`| Claude analyzes your code and creates a plan without modifying files or running commands. Good for complex tasks where you want to review the approach first.
+**Auto accept edits**| `acceptEdits`| Claude auto-accepts file edits and common filesystem commands like `mkdir`, `touch`, and `mv`, but still asks before running other terminal commands. Use this when you trust file changes and want faster iteration.
+**Plan mode**| `plan`| Claude reads files and runs commands to explore, then proposes a plan without editing your source code. Good for complex tasks where you want to review the approach first.
**Auto**| `auto`| Claude executes all actions with background safety checks that verify alignment with your request. Reduces permission prompts while maintaining oversight. Currently a research preview. Available on Team, Enterprise, and API plans. Requires Claude Sonnet 4.6 or Opus 4.6. Enable in your Settings → Claude Code.
**Bypass permissions**| `bypassPermissions`| Claude runs without any permission prompts, equivalent to `--dangerously-skip-permissions` in the CLI. Enable in your Settings → Claude Code under “Allow bypass permissions mode”. Only use this in sandboxed containers or VMs. Enterprise admins can disable this option.
@@ -341,7 +341,7 @@
`runtimeArgs`| string[]| Arguments passed to `runtimeExecutable`, such as `["run", "dev"]`
`port`| number| The port your server listens on. Defaults to 3000
`cwd`| string| Working directory relative to your project root. Defaults to the project root. Use `${workspaceFolder}` to reference the project root explicitly
-`env`| object| Additional environment variables as key-value pairs, such as `{ "NODE_ENV": "development" }`. Don’t put secrets here since this file is committed to your repo. Secrets set in your shell profile are inherited automatically.
+`env`| object| Additional environment variables as key-value pairs, such as `{ "NODE_ENV": "development" }`. Don’t put secrets here since this file is committed to your repo. To pass secrets to your dev server, set them in the local environment editor instead.
`autoPort`| boolean| How to handle port conflicts. See below
`program`| string| A script to run with `node`. See when to use `program` vs `runtimeExecutable`
`args`| string[]| Arguments passed to `program`. Only used when `program` is set
@@ -449,7 +449,7 @@
Local sessions
-Local sessions inherit environment variables from your shell. If you need additional variables, set them in your shell profile, such as `~/.zshrc` or `~/.bashrc`, and restart the desktop app. See [environment variables](</docs/en/env-vars>) for the full list of supported variables. [Extended thinking](</docs/en/common-workflows#use-extended-thinking-thinking-mode>) is enabled by default, which improves performance on complex reasoning tasks but uses additional tokens. To disable thinking entirely, set `MAX_THINKING_TOKENS=0` in your shell profile. On Opus, `MAX_THINKING_TOKENS` is ignored except for `0` because adaptive reasoning controls thinking depth instead.
+The desktop app does not always inherit your full shell environment. On macOS, when you launch the app from the Dock or Finder, it reads your shell profile, such as `~/.zshrc` or `~/.bashrc`, to extract `PATH` and a fixed set of Claude Code variables, but other variables you export there are not picked up. On Windows, the app inherits user and system environment variables but does not read PowerShell profiles. To set environment variables for local sessions and dev servers on any platform, open the environment dropdown in the prompt box, hover over **Local** , and click the gear icon to open the local environment editor. Variables you save here are stored encrypted on your machine and apply to every local session and preview server you start. You can also add variables to the `env` key in your `~/.claude/settings.json` file, though these reach Claude sessions only and not dev servers. See [environment variables](</docs/en/env-vars>) for the full list of supported variables. [Extended thinking](</docs/en/common-workflows#use-extended-thinking-thinking-mode>) is enabled by default, which improves performance on complex reasoning tasks but uses additional tokens. To disable thinking entirely, set `MAX_THINKING_TOKENS` to `0` in the local environment editor. On Opus 4.6 and Sonnet 4.6, any other `MAX_THINKING_TOKENS` value is ignored because adaptive reasoning controls thinking depth instead. To use a fixed thinking budget on these models, also set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` to `1`.
###
@@ -457,7 +457,7 @@
Remote sessions
-Remote sessions continue in the background even if you close the app. Usage counts toward your [subscription plan limits](</docs/en/costs>) with no separate compute charges. You can create custom cloud environments with different network access levels and environment variables. Select the environment dropdown when starting a remote session and choose **Add environment**. See [cloud environments](</docs/en/claude-code-on-the-web#cloud-environment>) for details on configuring network access and environment variables.
+Remote sessions continue in the background even if you close the app. Usage counts toward your [subscription plan limits](</docs/en/costs>) with no separate compute charges. You can create custom cloud environments with different network access levels and environment variables. Select the environment dropdown when starting a remote session and choose **Add environment**. See [the cloud environment](</docs/en/claude-code-on-the-web#the-cloud-environment>) for details on configuring network access and environment variables.
###
@@ -580,7 +580,7 @@
`--verbose`| Not available. Check system logs: Console.app on macOS, Event Viewer → Windows Logs → Application on Windows
`--print`, `--output-format`| Not available. Desktop is interactive only.
`ANTHROPIC_MODEL` env var| Model dropdown next to the send button
-`MAX_THINKING_TOKENS` env var| Set in shell profile; applies to local sessions. See environment configuration.
+`MAX_THINKING_TOKENS` env var| Set in the local environment editor. See environment configuration.
###
--- a/devcontainer.md
+++ b/devcontainer.md
@@ -25,6 +25,8 @@
2. Clone the [Claude Code reference implementation](<https://github.com/anthropics/claude-code/tree/main/.devcontainer>) repository
3. Open the repository in VS Code
4. When prompted, click “Reopen in Container” (or use Command Palette: Cmd+Shift+P → “Dev Containers: Reopen in Container”)
+
+Once the container finishes building, open a terminal in VS Code with `Ctrl+`` and run `claude` to authenticate and start your first session. The container has Claude Code preinstalled, so you can begin working immediately. Your project files are mounted into the container, and any code Claude writes appears in your local repository.
##
--- a/env-vars.md
+++ b/env-vars.md
@@ -37,6 +37,7 @@
`BASH_DEFAULT_TIMEOUT_MS`| Default timeout for long-running bash commands (default: 120000, or 2 minutes)
`BASH_MAX_OUTPUT_LENGTH`| Maximum number of characters in bash outputs before they are middle-truncated
`BASH_MAX_TIMEOUT_MS`| Maximum timeout the model can set for long-running bash commands (default: 600000, or 10 minutes)
+`CCR_FORCE_BUNDLE`| Set to `1` to force [`claude --remote`](</docs/en/claude-code-on-the-web#send-local-repositories-without-github>) to bundle and upload your local repository even when GitHub access is available
`CLAUDECODE`| Set to `1` in shell environments Claude Code spawns (Bash tool, tmux sessions). Not set in [hooks](</docs/en/hooks>) or [status line](</docs/en/statusline>) commands. Use to detect when a script is running inside a shell spawned by Claude Code
`CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS`| Set to `1` to disable all built-in [subagent](</docs/en/sub-agents>) types such as Explore and Plan. Only applies in non-interactive mode (the `-p` flag). Useful for SDK users who want a blank slate
`CLAUDE_AGENT_SDK_MCP_NO_PREFIX`| Set to `1` to skip the `mcp__<server>__` prefix on tool names from SDK-created MCP servers. Tools use their original names. SDK usage only
@@ -158,7 +159,7 @@
`HTTP_PROXY`| Specify HTTP proxy server for network connections
`HTTPS_PROXY`| Specify HTTPS proxy server for network connections
`IS_DEMO`| Set to `1` to enable demo mode: hides your email and organization name from the header and `/status` output, and skips onboarding. Useful when streaming or recording a session
-`MAX_MCP_OUTPUT_TOKENS`| Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens (default: 25000)
+`MAX_MCP_OUTPUT_TOKENS`| Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens. Tools that declare [`anthropic/maxResultSizeChars`](</docs/en/mcp#raise-the-limit-for-a-specific-tool>) use that character limit for text content instead, but image content from those tools is still subject to this variable (default: 25000)
`MAX_STRUCTURED_OUTPUT_RETRIES`| Number of times to retry when the model’s response fails validation against the [`--json-schema`](</docs/en/cli-reference#cli-flags>) in non-interactive mode (the `-p` flag). Defaults to 5
`MAX_THINKING_TOKENS`| Override the [extended thinking](<https://platform.claude.com/docs/en/build-with-claude/extended-thinking>) token budget. The ceiling is the model’s [max output tokens](<https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison>) minus one. Set to `0` to disable thinking entirely. On models with adaptive reasoning (Opus 4.6, Sonnet 4.6), the budget is ignored unless adaptive reasoning is disabled via `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING`
`MCP_CLIENT_SECRET`| OAuth client secret for MCP servers that require [pre-configured credentials](</docs/en/mcp#use-pre-configured-oauth-credentials>). Avoids the interactive prompt when adding a server with `--client-secret`
--- a/fast-mode.md
+++ b/fast-mode.md
@@ -130,7 +130,7 @@
Handle rate limits
-Fast mode has separate rate limits from standard Opus 4.6. When you hit the fast mode rate limit or run out of extra usage credits:
+Fast mode has separate rate limits from standard Opus 4.6. When you hit the fast mode rate limit or run out of extra usage:
1. Fast mode automatically falls back to standard Opus 4.6
2. The `↯` icon turns gray to indicate cooldown
Show diff (488 lines)
--- a/file-checkpointing.md
+++ b/file-checkpointing.md
@@ -0,0 +1,485 @@
+File checkpointing tracks file modifications made through the Write, Edit, and NotebookEdit tools during an agent session, allowing you to rewind files to any previous state. Want to try it out? Jump to the interactive example. With checkpointing, you can:
+
+ * **Undo unwanted changes** by restoring files to a known good state
+ * **Explore alternatives** by restoring to a checkpoint and trying a different approach
+ * **Recover from errors** when the agent makes incorrect modifications
+
+Only changes made through the Write, Edit, and NotebookEdit tools are tracked. Changes made through Bash commands (like `echo > file.txt` or `sed -i`) are not captured by the checkpoint system.
+
+##
+
+
+
+How checkpointing works
+
+When you enable file checkpointing, the SDK creates backups of files before modifying them through the Write, Edit, or NotebookEdit tools. User messages in the response stream include a checkpoint UUID that you can use as a restore point. Checkpoint works with these built-in tools that the agent uses to modify files:
+
+Tool| Description
+---|---
+Write| Creates a new file or overwrites an existing file with new content
+Edit| Makes targeted edits to specific parts of an existing file
+NotebookEdit| Modifies cells in Jupyter notebooks (`.ipynb` files)
+
+File rewinding restores files on disk to a previous state. It does not rewind the conversation itself. The conversation history and context remain intact after calling `rewindFiles()` (TypeScript) or `rewind_files()` (Python).
+
+The checkpoint system tracks:
+
+ * Files created during the session
+ * Files modified during the session
+ * The original content of modified files
+
+When you rewind to a checkpoint, created files are deleted and modified files are restored to their content at that point.
+
+##
+
+
+
+Implement checkpointing
+
+To use file checkpointing, enable it in your options, capture checkpoint UUIDs from the response stream, then call `rewindFiles()` (TypeScript) or `rewind_files()` (Python) when you need to restore. The following example shows the complete flow: enable checkpointing, capture the checkpoint UUID and session ID from the response stream, then resume the session later to rewind files. Each step is explained in detail below.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ UserMessage,
+ ResultMessage,
+ )
+
+ async def main():
+ # Step 1: Enable checkpointing
+ options = ClaudeAgentOptions(
+ enable_file_checkpointing=True,
+ permission_mode="acceptEdits", # Auto-accept file edits without prompting
+ extra_args={
+ "replay-user-messages": None
+ }, # Required to receive checkpoint UUIDs in the response stream
+ )
+
+ checkpoint_id = None
+ session_id = None
+
+ # Run the query and capture checkpoint UUID and session ID
+ async with ClaudeSDKClient(options) as client:
+ await client.query("Refactor the authentication module")
+
+ # Step 2: Capture checkpoint UUID from the first user message
+ async for message in client.receive_response():
+ if isinstance(message, UserMessage) and message.uuid and not checkpoint_id:
+ checkpoint_id = message.uuid
+ if isinstance(message, ResultMessage) and not session_id:
+ session_id = message.session_id
+
+ # Step 3: Later, rewind by resuming the session with an empty prompt
+ if checkpoint_id and session_id:
+ async with ClaudeSDKClient(
+ ClaudeAgentOptions(enable_file_checkpointing=True, resume=session_id)
+ ) as client:
+ await client.query("") # Empty prompt to open the connection
+ async for message in client.receive_response():
+ await client.rewind_files(checkpoint_id)
+ break
+ print(f"Rewound to checkpoint: {checkpoint_id}")
+
+ asyncio.run(main())
+
+1
+
+Enable checkpointing
+
+Configure your SDK options to enable checkpointing and receive checkpoint UUIDs:
+
+Option| Python| TypeScript| Description
+---|---|---|---
+Enable checkpointing| `enable_file_checkpointing=True`| `enableFileCheckpointing: true`| Tracks file changes for rewinding
+Receive checkpoint UUIDs| `extra_args={"replay-user-messages": None}`| `extraArgs: { 'replay-user-messages': null }`| Required to get user message UUIDs in the stream
+
+Python
+
+TypeScript
+
+ options = ClaudeAgentOptions(
+ enable_file_checkpointing=True,
+ permission_mode="acceptEdits",
+ extra_args={"replay-user-messages": None},
+ )
+
+ async with ClaudeSDKClient(options) as client:
+ await client.query("Refactor the authentication module")
+
+2
+
+Capture checkpoint UUID and session ID
+
+With the `replay-user-messages` option set (shown above), each user message in the response stream has a UUID that serves as a checkpoint.For most use cases, capture the first user message UUID (`message.uuid`); rewinding to it restores all files to their original state. To store multiple checkpoints and rewind to intermediate states, see Multiple restore points.Capturing the session ID (`message.session_id`) is optional; you only need it if you want to rewind later, after the stream completes. If you’re calling `rewindFiles()` immediately while still processing messages (as the example in Checkpoint before risky operations does), you can skip capturing the session ID.
+
+Python
+
+TypeScript
+
+ checkpoint_id = None
+ session_id = None
+
+ async for message in client.receive_response():
+ # Update checkpoint on each user message (keeps the latest)
+ if isinstance(message, UserMessage) and message.uuid:
+ checkpoint_id = message.uuid
+ # Capture session ID from the result message
+ if isinstance(message, ResultMessage):
+ session_id = message.session_id
+
+3
+
+Rewind files
+
+To rewind after the stream completes, resume the session with an empty prompt and call `rewind_files()` (Python) or `rewindFiles()` (TypeScript) with your checkpoint UUID. You can also rewind during the stream; see Checkpoint before risky operations for that pattern.
+
+Python
+
+TypeScript
+
+ async with ClaudeSDKClient(
+ ClaudeAgentOptions(enable_file_checkpointing=True, resume=session_id)
+ ) as client:
+ await client.query("") # Empty prompt to open the connection
+ async for message in client.receive_response():
+ await client.rewind_files(checkpoint_id)
+ break
+
+If you capture the session ID and checkpoint ID, you can also rewind from the CLI:
+
+ claude -p --resume <session-id> --rewind-files <checkpoint-uuid>
+
+##
+
+
+
+Common patterns
+
+These patterns show different ways to capture and use checkpoint UUIDs depending on your use case.
+
+###
+
+
+
+Checkpoint before risky operations
+
+This pattern keeps only the most recent checkpoint UUID, updating it before each agent turn. If something goes wrong during processing, you can immediately rewind to the last safe state and break out of the loop.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, UserMessage
+
+ async def main():
+ options = ClaudeAgentOptions(
+ enable_file_checkpointing=True,
+ permission_mode="acceptEdits",
+ extra_args={"replay-user-messages": None},
+ )
+
+ safe_checkpoint = None
+
+ async with ClaudeSDKClient(options) as client:
+ await client.query("Refactor the authentication module")
+
+ async for message in client.receive_response():
+ # Update checkpoint before each agent turn starts
+ # This overwrites the previous checkpoint. Only keep the latest
+ if isinstance(message, UserMessage) and message.uuid:
+ safe_checkpoint = message.uuid
+
+ # Decide when to revert based on your own logic
+ # For example: error detection, validation failure, or user input
+ if your_revert_condition and safe_checkpoint:
+ await client.rewind_files(safe_checkpoint)
+ # Exit the loop after rewinding, files are restored
+ break
+
+ asyncio.run(main())
+
+###
+
+
+
+Multiple restore points
+
+If Claude makes changes across multiple turns, you might want to rewind to a specific point rather than all the way back. For example, if Claude refactors a file in turn one and adds tests in turn two, you might want to keep the refactor but undo the tests. This pattern stores all checkpoint UUIDs in an array with metadata. After the session completes, you can rewind to any previous checkpoint:
+
+Python
+
+TypeScript
+
+ import asyncio
+ from dataclasses import dataclass
+ from datetime import datetime
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ UserMessage,
+ ResultMessage,
+ )
+
+ # Store checkpoint metadata for better tracking
+ @dataclass
+ class Checkpoint:
+ id: str
+ description: str
+ timestamp: datetime
+
+ async def main():
+ options = ClaudeAgentOptions(
+ enable_file_checkpointing=True,
+ permission_mode="acceptEdits",
+ extra_args={"replay-user-messages": None},
+ )
+
+ checkpoints = []
+ session_id = None
+
+ async with ClaudeSDKClient(options) as client:
+ await client.query("Refactor the authentication module")
+
+ async for message in client.receive_response():
+ if isinstance(message, UserMessage) and message.uuid:
+ checkpoints.append(
+ Checkpoint(
+ id=message.uuid,
+ description=f"After turn {len(checkpoints) + 1}",
+ timestamp=datetime.now(),
+ )
+ )
+ if isinstance(message, ResultMessage) and not session_id:
+ session_id = message.session_id
+
+ # Later: rewind to any checkpoint by resuming the session
+ if checkpoints and session_id:
+ target = checkpoints[0] # Pick any checkpoint
+ async with ClaudeSDKClient(
+ ClaudeAgentOptions(enable_file_checkpointing=True, resume=session_id)
+ ) as client:
+ await client.query("") # Empty prompt to open the connection
+ async for message in client.receive_response():
+ await client.rewind_files(target.id)
+ break
+ print(f"Rewound to: {target.description}")
+
+ asyncio.run(main())
+
+##
+
+
+
+Try it out
+
+This complete example creates a small utility file, has the agent add documentation comments, shows you the changes, then asks if you want to rewind. Before you begin, make sure you have the [Claude Agent SDK installed](</docs/en/agent-sdk/quickstart>).
+
+1
+
+Create a test file
+
+Create a new file called `utils.py` (Python) or `utils.ts` (TypeScript) and paste the following code:
+
+utils.py
+
+utils.ts
+
+ def add(a, b):
+ return a + b
+
+ def subtract(a, b):
+ return a - b
+
+ def multiply(a, b):
+ return a * b
+
+ def divide(a, b):
+ if b == 0:
+ raise ValueError("Cannot divide by zero")
+ return a / b
+
+2
+
+Run the interactive example
+
+Create a new file called `try_checkpointing.py` (Python) or `try_checkpointing.ts` (TypeScript) in the same directory as your utility file, and paste the following code.This script asks Claude to add doc comments to your utility file, then gives you the option to rewind and restore the original.
+
+try_checkpointing.py
+
+try_checkpointing.ts
+
+ import asyncio
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ UserMessage,
+ ResultMessage,
+ )
+
+ async def main():
+ # Configure the SDK with checkpointing enabled
+ # - enable_file_checkpointing: Track file changes for rewinding
+ # - permission_mode: Auto-accept file edits without prompting
+ # - extra_args: Required to receive user message UUIDs in the stream
+ options = ClaudeAgentOptions(
+ enable_file_checkpointing=True,
+ permission_mode="acceptEdits",
+ extra_args={"replay-user-messages": None},
+ )
+
+ checkpoint_id = None # Store the user message UUID for rewinding
+ session_id = None # Store the session ID for resuming
+
+ print("Running agent to add doc comments to utils.py...\n")
+
+ # Run the agent and capture checkpoint data from the response stream
+ async with ClaudeSDKClient(options) as client:
+ await client.query("Add doc comments to utils.py")
+
+ async for message in client.receive_response():
+ # Capture the first user message UUID - this is our restore point
+ if isinstance(message, UserMessage) and message.uuid and not checkpoint_id:
+ checkpoint_id = message.uuid
+ # Capture the session ID so we can resume later
+ if isinstance(message, ResultMessage):
+ session_id = message.session_id
+
+ print("Done! Open utils.py to see the added doc comments.\n")
+
+ # Ask the user if they want to rewind the changes
+ if checkpoint_id and session_id:
+ response = input("Rewind to remove the doc comments? (y/n): ")
+
+ if response.lower() == "y":
+ # Resume the session with an empty prompt, then rewind
+ async with ClaudeSDKClient(
+ ClaudeAgentOptions(enable_file_checkpointing=True, resume=session_id)
+ ) as client:
+ await client.query("") # Empty prompt opens the connection
+ async for message in client.receive_response():
+ await client.rewind_files(checkpoint_id) # Restore files
+ break
+
+ print(
+ "\n✓ File restored! Open utils.py to verify the doc comments are gone."
+ )
+ else:
+ print("\nKept the modified file.")
+
+ asyncio.run(main())
+
+This example demonstrates the complete checkpointing workflow:
+
+ 1. **Enable checkpointing** : configure the SDK with `enable_file_checkpointing=True` and `permission_mode="acceptEdits"` to auto-approve file edits
+ 2. **Capture checkpoint data** : as the agent runs, store the first user message UUID (your restore point) and the session ID
+ 3. **Prompt for rewind** : after the agent finishes, check your utility file to see the doc comments, then decide if you want to undo the changes
+ 4. **Resume and rewind** : if yes, resume the session with an empty prompt and call `rewind_files()` to restore the original file
+
+3
+
+Run the example
+
+Run the script from the same directory as your utility file.
+
+Open your utility file (`utils.py` or `utils.ts`) in your IDE or editor before running the script. You’ll see the file update in real-time as the agent adds doc comments, then revert back to the original when you choose to rewind.
+
+ * Python
+
+ * TypeScript
+
+ python try_checkpointing.py
+
+ npx tsx try_checkpointing.ts
+
+You’ll see the agent add doc comments, then a prompt asking if you want to rewind. If you choose yes, the file is restored to its original state.
+
+##
+
+
+
+Limitations
+
+File checkpointing has the following limitations:
+
+Limitation| Description
+---|---
+Write/Edit/NotebookEdit tools only| Changes made through Bash commands are not tracked
+Same session| Checkpoints are tied to the session that created them
+File content only| Creating, moving, or deleting directories is not undone by rewinding
+Local files| Remote or network files are not tracked
+
+##
+
+
+
+Troubleshooting
+
+###
+
+
+
+Checkpointing options not recognized
+
+If `enableFileCheckpointing` or `rewindFiles()` isn’t available, you may be on an older SDK version. **Solution** : Update to the latest SDK version:
+
+ * **Python** : `pip install --upgrade claude-agent-sdk`
+ * **TypeScript** : `npm install @anthropic-ai/claude-agent-sdk@latest`
+
+###
+
+
+
+User messages don’t have UUIDs
+
+If `message.uuid` is `undefined` or missing, you’re not receiving checkpoint UUIDs. **Cause** : The `replay-user-messages` option isn’t set. **Solution** : Add `extra_args={"replay-user-messages": None}` (Python) or `extraArgs: { 'replay-user-messages': null }` (TypeScript) to your options.
+
+###
+
+
+
+”No file checkpoint found for message” error
+
+This error occurs when the checkpoint data doesn’t exist for the specified user message UUID. **Common causes** :
+
+ * File checkpointing was not enabled on the original session (`enable_file_checkpointing` or `enableFileCheckpointing` was not set to `true`)
+ * The session wasn’t properly completed before attempting to resume and rewind
+
+**Solution** : Ensure `enable_file_checkpointing=True` (Python) or `enableFileCheckpointing: true` (TypeScript) was set on the original session, then use the pattern shown in the examples: capture the first user message UUID, complete the session fully, then resume with an empty prompt and call `rewindFiles()` once.
+
+###
+
+
+
+”ProcessTransport is not ready for writing” error
+
+This error occurs when you call `rewindFiles()` or `rewind_files()` after you’ve finished iterating through the response. The connection to the CLI process closes when the loop completes. **Solution** : Resume the session with an empty prompt, then call rewind on the new query:
+
+Python
+
+TypeScript
+
+ # Resume session with empty prompt, then rewind
+ async with ClaudeSDKClient(
+ ClaudeAgentOptions(enable_file_checkpointing=True, resume=session_id)
+ ) as client:
+ await client.query("")
+ async for message in client.receive_response():
+ await client.rewind_files(checkpoint_id)
+ break
+
+##
+
+
+
+Next steps
+
+ * **[Sessions](</docs/en/agent-sdk/sessions>)** : learn how to resume sessions, which is required for rewinding after the stream completes. Covers session IDs, resuming conversations, and session forking.
+ * **[Permissions](</docs/en/agent-sdk/permissions>)** : configure which tools Claude can use and how file modifications are approved. Useful if you want more control over when edits happen.
+ * **[TypeScript SDK reference](</docs/en/agent-sdk/typescript>)** : complete API reference including all options for `query()` and the `rewindFiles()` method.
+ * **[Python SDK reference](</docs/en/agent-sdk/python>)** : complete API reference including all options for `ClaudeAgentOptions` and the `rewind_files()` method.
--- a/fullscreen.md
+++ b/fullscreen.md
@@ -28,7 +28,7 @@
Before| Now| Details
---|---|---
-`Cmd+f` or tmux search to find text| `Ctrl+o` then `/` to search, or `Ctrl+o` then `[` to write the conversation to native scrollback so `Cmd+f` works again| Search and review the conversation
+`Cmd+f` or tmux search to find text| `Ctrl+o` once for transcript mode (then `/` to search or `[` to write to scrollback), or `Ctrl+o` twice for focus view (last prompt + tool summary + response)| Search and review the conversation
Terminal’s native click-and-drag to select and copy| In-app selection, copies automatically on mouse release| Use the mouse
`Cmd`-click to open a URL| Click the URL| Use the mouse
@@ -85,7 +85,7 @@
Search and review the conversation
-Press `Ctrl+o` to enter transcript mode. With fullscreen rendering active, transcript mode gains `less`-style navigation and search:
+In fullscreen rendering, `Ctrl+o` cycles through three states: normal prompt, transcript mode, and focus view. Press it once to enter transcript mode, press it again to return to a focus view showing just your last prompt, a one-line summary of tool calls with edit diffstats, and the final response. Press it a third time to return to the normal prompt screen. Transcript mode gains `less`-style navigation and search:
Key| Action
---|---
@@ -95,14 +95,15 @@
`g` / `G` or `Home` / `End`| Jump to top or bottom
`Ctrl+u` / `Ctrl+d`| Scroll half a page
`Ctrl+b` / `Ctrl+f` or `Space` / `b`| Scroll a full page
-`Esc`, `q`, or `Ctrl+o`| Exit transcript mode
+`Ctrl+o`| Advance to focus view
+`Esc` or `q`| Exit transcript mode and return to the prompt
Your terminal’s `Cmd+f` and tmux search don’t see the conversation because it lives in the alternate screen buffer, not the native scrollback. To hand the content back to your terminal, press `Ctrl+o` to enter transcript mode first, then:
* **`[`** : writes the full conversation into your terminal’s native scrollback buffer, with all tool output expanded. The conversation is now ordinary text in your terminal, so `Cmd+f`, tmux copy mode, and any other native tool can search or select it. Long sessions may pause for a moment while this happens. This lasts until you exit transcript mode with `Esc` or `q`, which returns you to fullscreen rendering. The next `Ctrl+o` starts fresh.
* **`v`** : writes the conversation to a temporary file and opens it in `$VISUAL` or `$EDITOR`.
-Press `Esc`, `q`, or `Ctrl+o` to return to the prompt.
+Press `Esc` or `q` to return to the prompt.
##
--- a/github-actions.md
+++ b/github-actions.md
@@ -1,6 +1,6 @@
Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project’s standards. For automatic reviews posted on every PR without a trigger, see [GitHub Code Review](</docs/en/code-review>).
-Claude Code GitHub Actions is built on top of the [Claude Agent SDK](<https://platform.claude.com/docs/en/agent-sdk/overview>), which enables programmatic integration of Claude Code into your applications. You can use the SDK to build custom automation workflows beyond GitHub Actions.
+Claude Code GitHub Actions is built on top of the [Claude Agent SDK](</docs/en/agent-sdk/overview>), which enables programmatic integration of Claude Code into your applications. You can use the SDK to build custom automation workflows beyond GitHub Actions.
**Claude Opus 4.6 is now available.** Claude Code GitHub Actions default to Sonnet. To use Opus 4.6, configure the model parameter to use `claude-opus-4-6`.
--- a/github-enterprise-server.md
+++ b/github-enterprise-server.md
@@ -14,7 +14,7 @@
---|---|---
Claude Code on the web| ✅ Supported| Admin connects the GHES instance once; developers use `claude --remote` or [claude.ai/code](<https://claude.ai/code>) as usual
Code Review| ✅ Supported| Same automated PR reviews as github.com
-Teleport sessions| ✅ Supported| Move sessions between web and terminal with `/teleport`
+Teleport sessions| ✅ Supported| Move sessions between web and terminal with `--teleport`
Plugin marketplaces| ✅ Supported| Use full git URLs instead of `owner/repo` shorthand
Contribution metrics| ✅ Supported| Delivered via webhooks to the [analytics dashboard](</docs/en/analytics>)
GitHub Actions| ✅ Supported| Requires manual workflow setup; `/install-github-app` is github.com only
@@ -117,7 +117,7 @@
Teleport sessions to your terminal
-Pull a web session into your local terminal with `/teleport` or `claude --teleport`. Teleport verifies you’re in a checkout of the same GHES repository before fetching the branch and loading the session history. See [teleport requirements](</docs/en/claude-code-on-the-web#requirements-for-teleporting>) for details.
+Pull a web session into your local terminal with `claude --teleport`. Teleport verifies you’re in a checkout of the same GHES repository before fetching the branch and loading the session history. See [teleport requirements](</docs/en/claude-code-on-the-web#teleport-requirements>) for details.
##
--- a/gitlab-ci-cd.md
+++ b/gitlab-ci-cd.md
@@ -1,6 +1,6 @@
Claude Code for GitLab CI/CD is currently in beta. Features and functionality may evolve as we refine the experience.This integration is maintained by GitLab. For support, see the following [GitLab issue](<https://gitlab.com/gitlab-org/gitlab/-/issues/573776>).
-This integration is built on top of the [Claude Code CLI and Agent SDK](<https://platform.claude.com/docs/en/agent-sdk/overview>), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.
+This integration is built on top of the [Claude Code CLI and Agent SDK](</docs/en/agent-sdk/overview>), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.
##
--- a/headless.md
+++ b/headless.md
@@ -1,4 +1,4 @@
-The [Agent SDK](<https://platform.claude.com/docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](<https://platform.claude.com/docs/en/agent-sdk/python>) and [TypeScript](<https://platform.claude.com/docs/en/agent-sdk/typescript>) packages for full programmatic control.
+The [Agent SDK](</docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](</docs/en/agent-sdk/python>) and [TypeScript](</docs/en/agent-sdk/typescript>) packages for full programmatic control.
The CLI was previously called “headless mode.” The `-p` flag and all CLI options work the same way.
@@ -6,7 +6,7 @@
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
-This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](<https://platform.claude.com/docs/en/agent-sdk/overview>).
+This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](</docs/en/agent-sdk/overview>).
##
@@ -118,7 +118,7 @@
`uuid`| string| unique event identifier
`session_id`| string| session the event belongs to
-For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](<https://platform.claude.com/docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation.
+For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation.
###
@@ -131,7 +131,7 @@
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"
-To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules, which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting, but shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted:
+To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules, which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted:
claude -p "Apply the lint fixes" --permission-mode acceptEdits
@@ -190,7 +190,7 @@
Next steps
- * [Agent SDK quickstart](<https://platform.claude.com/docs/en/agent-sdk/quickstart>): build your first agent with Python or TypeScript
+ * [Agent SDK quickstart](</docs/en/agent-sdk/quickstart>): build your first agent with Python or TypeScript
* [CLI reference](</docs/en/cli-reference>): all CLI flags and options
* [GitHub Actions](</docs/en/github-actions>): use the Agent SDK in GitHub workflows
* [GitLab CI/CD](</docs/en/gitlab-ci-cd>): use the Agent SDK in GitLab pipelines
Show diff (186 lines)
--- a/hosting.md
+++ b/hosting.md
@@ -0,0 +1,183 @@
+The Claude Agent SDK differs from traditional stateless LLM APIs in that it maintains conversational state and executes commands in a persistent environment. This guide covers the architecture, hosting considerations, and best practices for deploying SDK-based agents in production.
+
+For security hardening beyond basic sandboxing (including network controls, credential management, and isolation options), see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>).
+
+##
+
+
+
+Hosting Requirements
+
+###
+
+
+
+Container-Based Sandboxing
+
+For security and isolation, the SDK should run inside a sandboxed container environment. This provides process isolation, resource limits, network control, and ephemeral filesystems. The SDK also supports [programmatic sandbox configuration](</docs/en/agent-sdk/typescript#sandbox-settings>) for command execution.
+
+###
+
+
+
+System Requirements
+
+Each SDK instance requires:
+
+ * **Runtime dependencies**
+ * Python 3.10+ (for Python SDK) or Node.js 18+ (for TypeScript SDK)
+ * Node.js (required by the bundled Claude Code CLI that the SDK spawns; both SDK packages include it, so no separate install is needed)
+ * **Resource allocation**
+ * Recommended: 1GiB RAM, 5GiB of disk, and 1 CPU (vary this based on your task as needed)
+ * **Network access**
+ * Outbound HTTPS to `api.anthropic.com`
+ * Optional: Access to MCP servers or external tools
+
+##
+
+
+
+Understanding the SDK Architecture
+
+Unlike stateless API calls, the Claude Agent SDK operates as a **long-running process** that:
+
+ * **Executes commands** in a persistent shell environment
+ * **Manages file operations** within a working directory
+ * **Handles tool execution** with context from previous interactions
+
+##
+
+
+
+Sandbox Provider Options
+
+Several providers specialize in secure container environments for AI code execution:
+
+ * **[Modal Sandbox](<https://modal.com/docs/guide/sandbox>)** \- [demo implementation](<https://modal.com/docs/examples/claude-slack-gif-creator>)
+ * **[Cloudflare Sandboxes](<https://github.com/cloudflare/sandbox-sdk>)**
+ * **[Daytona](<https://www.daytona.io/>)**
+ * **[E2B](<https://e2b.dev/>)**
+ * **[Fly Machines](<https://fly.io/docs/machines/>)**
+ * **[Vercel Sandbox](<https://vercel.com/docs/functions/sandbox>)**
+
+For self-hosted options (Docker, gVisor, Firecracker) and detailed isolation configuration, see [Isolation Technologies](</docs/en/agent-sdk/secure-deployment#isolation-technologies>).
+
+##
+
+
+
+Production Deployment Patterns
+
+###
+
+
+
+Pattern 1: Ephemeral Sessions
+
+Create a new container for each user task, then destroy it when complete. Best for one-off tasks, the user may still interact with the AI while the task is completing, but once completed the container is destroyed. **Examples:**
+
+ * Bug Investigation & Fix: Debug and resolve a specific issue with relevant context
+ * Invoice Processing: Extract and structure data from receipts/invoices for accounting systems
+ * Translation Tasks: Translate documents or content batches between languages
+ * Image/Video Processing: Apply transformations, optimizations, or extract metadata from media files
+
+###
+
+
+
+Pattern 2: Long-Running Sessions
+
+Maintain persistent container instances for long running tasks. Often times running _multiple_ Claude Agent processes inside of the container based on demand. Best for proactive agents that take action without the users input, agents that serve content or agents that process high amounts of messages. **Examples:**
+
+ * Email Agent: Monitors incoming emails and autonomously triages, responds, or takes actions based on content
+ * Site Builder: Hosts custom websites per user with live editing capabilities served through container ports
+ * High-Frequency Chat Bots: Handles continuous message streams from platforms like Slack where rapid response times are critical
+
+###
+
+
+
+Pattern 3: Hybrid Sessions
+
+Ephemeral containers that are hydrated with history and state, possibly from a database or from the SDK’s session resumption features. Best for containers with intermittent interaction from the user that kicks off work and spins down when the work is completed but can be continued. **Examples:**
+
+ * Personal Project Manager: Helps manage ongoing projects with intermittent check-ins, maintains context of tasks, decisions, and progress
+ * Deep Research: Conducts multi-hour research tasks, saves findings and resumes investigation when user returns
+ * Customer Support Agent: Handles support tickets that span multiple interactions, loads ticket history and customer context
+
+###
+
+
+
+Pattern 4: Single Containers
+
+Run multiple Claude Agent SDK processes in one global container. Best for agents that must collaborate closely together. This is likely the least popular pattern because you will have to prevent agents from overwriting each other. **Examples:**
+
+ * **Simulations** : Agents that interact with each other in simulations such as video games.
+
+##
+
+
+
+FAQ
+
+###
+
+
+
+How do I communicate with my sandboxes?
+
+When hosting in containers, expose ports to communicate with your SDK instances. Your application can expose HTTP/WebSocket endpoints for external clients while the SDK runs internally within the container.
+
+###
+
+
+
+What is the cost of hosting a container?
+
+The dominant cost of serving agents is the tokens; containers vary based on what you provision, but a minimum cost is roughly 5 cents per hour running.
+
+###
+
+
+
+When should I shut down idle containers vs. keeping them warm?
+
+This is likely provider dependent, different sandbox providers will let you set different criteria for idle timeouts after which a sandbox might spin down. You will want to tune this timeout based on how frequent you think user response might be.
+
+###
+
+
+
+How often should I update the Claude Code CLI?
+
+The Claude Code CLI is versioned with semver, so any breaking changes will be versioned.
+
+###
+
+
+
+How do I monitor container health and agent performance?
+
+Since containers are just servers the same logging infrastructure you use for the backend will work for containers.
+
+###
+
+
+
+How long can an agent session run before timing out?
+
+An agent session will not timeout, but consider setting a ‘maxTurns’ property to prevent Claude from getting stuck in a loop.
+
+##
+
+
+
+Next Steps
+
+ * [Secure Deployment](</docs/en/agent-sdk/secure-deployment>) \- Network controls, credential management, and isolation hardening
+ * [TypeScript SDK - Sandbox Settings](</docs/en/agent-sdk/typescript#sandbox-settings>) \- Configure sandbox programmatically
+ * [Sessions Guide](</docs/en/agent-sdk/sessions>) \- Learn about session management
+ * [Permissions](</docs/en/agent-sdk/permissions>) \- Configure tool permissions
+ * [Cost Tracking](</docs/en/agent-sdk/cost-tracking>) \- Monitor API usage
+ * [MCP Integration](</docs/en/agent-sdk/mcp>) \- Extend with custom tools
--- a/how-claude-code-works.md
+++ b/how-claude-code-works.md
@@ -132,7 +132,7 @@
When context fills up
-Claude Code manages context automatically as you approach the limit. It clears older tool outputs first, then summarizes the conversation if needed. Your requests and key code snippets are preserved; detailed instructions from early in the conversation may be lost. Put persistent rules in CLAUDE.md rather than relying on conversation history. To control what’s preserved during compaction, add a “Compact Instructions” section to CLAUDE.md or run `/compact` with a focus (like `/compact focus on the API changes`). Run `/context` to see what’s using space. MCP tool definitions are deferred by default and loaded on demand via [tool search](</docs/en/mcp#scale-with-mcp-tool-search>), so only tool names consume context until Claude uses a specific tool. Run `/mcp` to check per-server costs.
+Claude Code manages context automatically as you approach the limit. It clears older tool outputs first, then summarizes the conversation if needed. Your requests and key code snippets are preserved; detailed instructions from early in the conversation may be lost. Put persistent rules in CLAUDE.md rather than relying on conversation history. To control what’s preserved during compaction, add a “Compact Instructions” section to CLAUDE.md or run `/compact` with a focus (like `/compact focus on the API changes`). If a single file or tool output is so large that context refills immediately after each summary, Claude Code stops auto-compacting after a few attempts and shows an error instead of looping. See [Auto-compaction stops with a thrashing error](</docs/en/troubleshooting#auto-compaction-stops-with-a-thrashing-error>) for recovery steps. Run `/context` to see what’s using space. MCP tool definitions are deferred by default and loaded on demand via [tool search](</docs/en/mcp#scale-with-mcp-tool-search>), so only tool names consume context until Claude uses a specific tool. Run `/mcp` to check per-server costs.
####
@@ -167,7 +167,7 @@
Press `Shift+Tab` to cycle through permission modes:
* **Default** : Claude asks before file edits and shell commands
- * **Auto-accept edits** : Claude edits files without asking, still asks for commands
+ * **Auto-accept edits** : Claude edits files and runs common filesystem commands like `mkdir` and `mv` without asking, still asks for other commands
* **Plan mode** : Claude uses read-only tools only, creating a plan you can approve before execution
* **Auto mode** : Claude evaluates all actions with background safety checks. Currently a research preview
--- a/interactive-mode.md
+++ b/interactive-mode.md
@@ -25,7 +25,7 @@
`Ctrl+D`| Exit Claude Code session| EOF signal
`Ctrl+G` or `Ctrl+X Ctrl+E`| Open in default text editor| Edit your prompt or custom response in your default text editor. `Ctrl+X Ctrl+E` is the readline-native binding
`Ctrl+L`| Clear prompt input| Clears typed text, keeps conversation history
-`Ctrl+O`| Toggle verbose output| Shows detailed tool usage and execution. Also expands MCP read and search calls, which collapse to a single line like “Queried slack” by default
+`Ctrl+O`| Toggle transcript viewer| Shows detailed tool usage and execution. Also expands MCP read and search calls, which collapse to a single line like “Queried slack” by default. In [fullscreen rendering](</docs/en/fullscreen>), cycles through three states: normal prompt, transcript mode, and focus view (last prompt + tool summary + response)
`Ctrl+R`| Reverse search command history| Search through previous commands interactively
`Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows)| Paste image from clipboard| Inserts an `[Image #N]` chip at the cursor so you can reference it positionally in your prompt
`Ctrl+B`| Background running tasks| Backgrounds bash commands and agents. Tmux users press twice
--- a/legal-and-compliance.md
+++ b/legal-and-compliance.md
@@ -60,7 +60,7 @@
Claude Code authenticates with Anthropic’s servers using OAuth tokens or API keys. These authentication methods serve different purposes:
* **OAuth authentication** is intended exclusively for purchasers of Claude Free, Pro, Max, Team, and Enterprise subscription plans and is designed to support ordinary use of Claude Code and other native Anthropic applications. More information about how users can authenticate with OAuth tokens can be found in [Logging in to your Claude account](<https://support.claude.com/en/articles/13189465-logging-in-to-your-claude-account>).
- * **Developers** building products or services that interact with Claude’s capabilities, including those using the [Agent SDK](<https://platform.claude.com/docs/en/agent-sdk/overview>), should use API key authentication through [Claude Console](<https://platform.claude.com/>) or a supported cloud provider. Anthropic does not permit third-party developers to offer Claude.ai login or to route requests through Free, Pro, or Max plan credentials on behalf of their users.
+ * **Developers** building products or services that interact with Claude’s capabilities, including those using the [Agent SDK](</docs/en/agent-sdk/overview>), should use API key authentication through [Claude Console](<https://platform.claude.com/>) or a supported cloud provider. Anthropic does not permit third-party developers to offer Claude.ai login or to route requests through Free, Pro, or Max plan credentials on behalf of their users.
Anthropic reserves the right to take measures to enforce these restrictions and may do so without prior notice. For questions about permitted authentication methods for your use case, please [contact sales](<https://www.anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=legal_compliance_contact_sales>).
Show diff (115 lines)
--- a/mcp.md
+++ b/mcp.md
@@ -212,7 +212,13 @@
MCP installation scopes
-MCP servers can be configured at three different scope levels, each serving distinct purposes for managing server accessibility and sharing. Understanding these scopes helps you determine the best way to configure servers for your specific needs.
+MCP servers can be configured at three scopes. The scope you choose controls which projects the server loads in and whether the configuration is shared with your team.
+
+Scope| Loads in| Shared with team| Stored in
+---|---|---|---
+Local| Current project only| No| `~/.claude.json`
+Project| Current project only| Yes, via version control| `.mcp.json` in project root
+User| All your projects| No| `~/.claude.json`
###
@@ -220,7 +226,7 @@
Local scope
-Local-scoped servers represent the default configuration level and are stored in `~/.claude.json` under your project’s path. These servers remain private to you and are only accessible when working within the current project directory. This scope is ideal for personal development servers, experimental configurations, or servers containing sensitive credentials that shouldn’t be shared.
+Local scope is the default. A local-scoped server loads only in the project where you added it and stays private to you. Claude Code stores it in `~/.claude.json` under that project’s path, so the same server won’t appear in your other projects. Use local scope for personal development servers, experimental configurations, or servers with credentials you don’t want in version control.
The term “local scope” for MCP servers differs from general local settings. MCP local-scoped servers are stored in `~/.claude.json` (your home directory), while general local settings use `.claude/settings.local.json` (in the project directory). See [Settings](</docs/en/settings#settings-files>) for details on settings file locations.
@@ -229,6 +235,21 @@
# Explicitly specify local scope
claude mcp add --transport http stripe --scope local https://mcp.stripe.com
+
+The command writes the server into the entry for your current project inside `~/.claude.json`. The example below shows the result when you run it from `/path/to/your/project`:
+
+ {
+ "projects": {
+ "/path/to/your/project": {
+ "mcpServers": {
+ "stripe": {
+ "type": "http",
+ "url": "https://mcp.stripe.com"
+ }
+ }
+ }
+ }
+ }
###
@@ -265,24 +286,6 @@
# Add a user server
claude mcp add --transport http hubspot --scope user https://mcp.hubspot.com/anthropic
-
-###
-
-
-
-Choosing the right scope
-
-Select your scope based on:
-
- * **Local scope** : Personal servers, experimental configurations, or sensitive credentials specific to one project
- * **Project scope** : Team-shared servers, project-specific tools, or services required for collaboration
- * **User scope** : Personal utilities needed across multiple projects, development tools, or frequently used services
-
-**Where are MCP servers stored?**
-
- * **User and local scope** : `~/.claude.json` (in the `mcpServers` field or under project paths)
- * **Project scope** : `.mcp.json` in your project root (checked into source control)
- * **Managed** : `managed-mcp.json` in system directories (see Managed MCP configuration)
###
@@ -734,8 +737,9 @@
When MCP tools produce large outputs, Claude Code helps manage the token usage to prevent overwhelming your conversation context:
* **Output warning threshold** : Claude Code displays a warning when any MCP tool output exceeds 10,000 tokens
- * **Configurable limit** : You can adjust the maximum allowed MCP output tokens using the `MAX_MCP_OUTPUT_TOKENS` environment variable
- * **Default limit** : The default maximum is 25,000 tokens
+ * **Configurable limit** : you can adjust the maximum allowed MCP output tokens using the `MAX_MCP_OUTPUT_TOKENS` environment variable
+ * **Default limit** : the default maximum is 25,000 tokens
+ * **Scope** : the environment variable applies to tools that don’t declare their own limit. Tools that set `anthropic/maxResultSizeChars` use that value instead for text content, regardless of what `MAX_MCP_OUTPUT_TOKENS` is set to. Tools that return image data are still subject to `MAX_MCP_OUTPUT_TOKENS`
To increase the limit for tools that produce large outputs:
@@ -752,7 +756,7 @@
-Override result size per tool
+Raise the limit for a specific tool
If you’re building an MCP server, you can allow individual tools to return results larger than the default persist-to-disk threshold by setting `_meta["anthropic/maxResultSizeChars"]` in the tool’s `tools/list` response entry. Claude Code raises that tool’s threshold to the annotated value, up to a hard ceiling of 500,000 characters. This is useful for tools that return inherently large but necessary outputs, such as database schemas or full file trees. Without the annotation, results that exceed the default threshold are persisted to disk and replaced with a file reference in the conversation.
@@ -760,13 +764,13 @@
"name": "get_schema",
"description": "Returns the full database schema",
"_meta": {
- "anthropic/maxResultSizeChars": 500000
- }
- }
-
-The annotation raises the per-tool persist threshold but does not bypass the global `MAX_MCP_OUTPUT_TOKENS` limit, which defaults to 25,000 tokens or roughly 100,000 characters. To return results larger than that, users must also raise `MAX_MCP_OUTPUT_TOKENS`.
-
-If you frequently encounter output warnings with specific MCP servers you don’t control, consider increasing the `MAX_MCP_OUTPUT_TOKENS` limit. You can also ask the server author to add the `anthropic/maxResultSizeChars` annotation or to paginate their responses.
+ "anthropic/maxResultSizeChars": 200000
+ }
+ }
+
+The annotation applies independently of `MAX_MCP_OUTPUT_TOKENS` for text content, so users don’t need to raise the environment variable for tools that declare it. Tools that return image data are still subject to the token limit.
+
+If you frequently encounter output warnings with specific MCP servers you don’t control, consider increasing the `MAX_MCP_OUTPUT_TOKENS` limit. You can also ask the server author to add the `anthropic/maxResultSizeChars` annotation or to paginate their responses. The annotation has no effect on tools that return image content; for those, raising `MAX_MCP_OUTPUT_TOKENS` is the only option.
##
Show diff (256 lines)
--- a/migration-guide.md
+++ b/migration-guide.md
@@ -0,0 +1,253 @@
+##
+
+
+
+Overview
+
+The Claude Code SDK has been renamed to the **Claude Agent SDK** and its documentation has been reorganized. This change reflects the SDK’s broader capabilities for building AI agents beyond just coding tasks.
+
+##
+
+
+
+What’s Changed
+
+Aspect| Old| New
+---|---|---
+**Package Name (TS/JS)**| `@anthropic-ai/claude-code`| `@anthropic-ai/claude-agent-sdk`
+**Python Package**| `claude-code-sdk`| `claude-agent-sdk`
+**Documentation Location**| Claude Code docs| API Guide → Agent SDK section
+
+**Documentation Changes:** The Agent SDK documentation has moved from the Claude Code docs to the API Guide under a dedicated [Agent SDK](</docs/en/agent-sdk/overview>) section. The Claude Code docs now focus on the CLI tool and automation features.
+
+##
+
+
+
+Migration Steps
+
+###
+
+
+
+For TypeScript/JavaScript Projects
+
+**1\. Uninstall the old package:**
+
+ npm uninstall @anthropic-ai/claude-code
+
+**2\. Install the new package:**
+
+ npm install @anthropic-ai/claude-agent-sdk
+
+**3\. Update your imports:** Change all imports from `@anthropic-ai/claude-code` to `@anthropic-ai/claude-agent-sdk`:
+
+ // Before
+ import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-code";
+
+ // After
+ import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
+
+**4\. Update package.json dependencies:** If you have the package listed in your `package.json`, update it: Before:
+
+ {
+ "dependencies": {
+ "@anthropic-ai/claude-code": "^0.0.42"
+ }
+ }
+
+After:
+
+ {
+ "dependencies": {
+ "@anthropic-ai/claude-agent-sdk": "^0.2.0"
+ }
+ }
+
+That’s it! No other code changes are required.
+
+###
+
+
+
+For Python Projects
+
+**1\. Uninstall the old package:**
+
+ pip uninstall claude-code-sdk
+
+**2\. Install the new package:**
+
+ pip install claude-agent-sdk
+
+**3\. Update your imports:** Change all imports from `claude_code_sdk` to `claude_agent_sdk`:
+
+ # Before
+ from claude_code_sdk import query, ClaudeCodeOptions
+
+ # After
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+**4\. Update type names:** Change `ClaudeCodeOptions` to `ClaudeAgentOptions`:
+
+ # Before
+ from claude_code_sdk import query, ClaudeCodeOptions
+
+ options = ClaudeCodeOptions(model="claude-opus-4-6")
+
+ # After
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ options = ClaudeAgentOptions(model="claude-opus-4-6")
+
+**5\. Reviewbreaking changes** Make any code changes needed to complete the migration.
+
+##
+
+
+
+Breaking changes
+
+To improve isolation and explicit configuration, Claude Agent SDK v0.1.0 introduces breaking changes for users migrating from Claude Code SDK. Review this section carefully before migrating.
+
+###
+
+
+
+Python: ClaudeCodeOptions renamed to ClaudeAgentOptions
+
+**What changed:** The Python SDK type `ClaudeCodeOptions` has been renamed to `ClaudeAgentOptions`. **Migration:**
+
+ # BEFORE (claude-code-sdk)
+ from claude_code_sdk import query, ClaudeCodeOptions
+
+ options = ClaudeCodeOptions(model="claude-opus-4-6", permission_mode="acceptEdits")
+
+ # AFTER (claude-agent-sdk)
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ options = ClaudeAgentOptions(model="claude-opus-4-6", permission_mode="acceptEdits")
+
+**Why this changed:** The type name now matches the “Claude Agent SDK” branding and provides consistency across the SDK’s naming conventions.
+
+###
+
+
+
+System prompt no longer default
+
+**What changed:** The SDK no longer uses Claude Code’s system prompt by default. **Migration:**
+
+TypeScript
+
+Python
+
+ // BEFORE (v0.0.x) - Used Claude Code's system prompt by default
+ const result = query({ prompt: "Hello" });
+
+ // AFTER (v0.1.0) - Uses minimal system prompt by default
+ // To get the old behavior, explicitly request Claude Code's preset:
+ const result = query({
+ prompt: "Hello",
+ options: {
+ systemPrompt: { type: "preset", preset: "claude_code" }
+ }
+ });
+
+ // Or use a custom system prompt:
+ const result = query({
+ prompt: "Hello",
+ options: {
+ systemPrompt: "You are a helpful coding assistant"
+ }
+ });
+
+**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code’s CLI-focused instructions.
+
+###
+
+
+
+Settings Sources No Longer Loaded by Default
+
+**What changed:** The SDK no longer reads from filesystem settings (CLAUDE.md, settings.json, slash commands, etc.) by default. **Migration:**
+
+TypeScript
+
+Python
+
+ // BEFORE (v0.0.x) - Loaded all settings automatically
+ const result = query({ prompt: "Hello" });
+ // Would read from:
+ // - ~/.claude/settings.json (user)
+ // - .claude/settings.json (project)
+ // - .claude/settings.local.json (local)
+ // - CLAUDE.md files
+ // - Custom slash commands
+
+ // AFTER (v0.1.0) - No settings loaded by default
+ // To get the old behavior:
+ const result = query({
+ prompt: "Hello",
+ options: {
+ settingSources: ["user", "project", "local"]
+ }
+ });
+
+ // Or load only specific sources:
+ const result = query({
+ prompt: "Hello",
+ options: {
+ settingSources: ["project"] // Only project settings
+ }
+ });
+
+**Why this changed:** Ensures SDK applications have predictable behavior independent of local filesystem configurations. This is especially important for:
+
+ * **CI/CD environments** \- Consistent behavior without local customizations
+ * **Deployed applications** \- No dependency on filesystem settings
+ * **Testing** \- Isolated test environments
+ * **Multi-tenant systems** \- Prevent settings leakage between users
+
+**Backward compatibility:** If your application relied on filesystem settings (custom slash commands, CLAUDE.md instructions, etc.), add `settingSources: ['user', 'project', 'local']` to your options.
+
+##
+
+
+
+Why the Rename?
+
+The Claude Code SDK was originally designed for coding tasks, but it has evolved into a powerful framework for building all types of AI agents. The new name “Claude Agent SDK” better reflects its capabilities:
+
+ * Building business agents (legal assistants, finance advisors, customer support)
+ * Creating specialized coding agents (SRE bots, security reviewers, code review agents)
+ * Developing custom agents for any domain with tool use, MCP integration, and more
+
+##
+
+
+
+Getting Help
+
+If you encounter any issues during migration: **For TypeScript/JavaScript:**
+
+ 1. Check that all imports are updated to use `@anthropic-ai/claude-agent-sdk`
+ 2. Verify your package.json has the new package name
+ 3. Run `npm install` to ensure dependencies are updated
+
+**For Python:**
+
+ 1. Check that all imports are updated to use `claude_agent_sdk`
+ 2. Verify your requirements.txt or pyproject.toml has the new package name
+ 3. Run `pip install claude-agent-sdk` to ensure the package is installed
+
+##
+
+
+
+Next Steps
+
+ * Explore the [Agent SDK Overview](</docs/en/agent-sdk/overview>) to learn about available features
+ * Check out the [TypeScript SDK Reference](</docs/en/agent-sdk/typescript>) for detailed API documentation
+ * Review the [Python SDK Reference](</docs/en/agent-sdk/python>) for Python-specific documentation
+ * Learn about [Custom Tools](</docs/en/agent-sdk/custom-tools>) and [MCP Integration](</docs/en/agent-sdk/mcp>)
Show diff (420 lines)
--- a/modifying-system-prompts.md
+++ b/modifying-system-prompts.md
@@ -0,0 +1,417 @@
+System prompts define Claude’s behavior, capabilities, and response style. The Claude Agent SDK provides three ways to customize system prompts: using output styles (persistent, file-based configurations), appending to Claude Code’s prompt, or using a fully custom prompt.
+
+##
+
+
+
+Understanding system prompts
+
+A system prompt is the initial instruction set that shapes how Claude behaves throughout a conversation.
+
+**Default behavior:** The Agent SDK uses a **minimal system prompt** by default. It contains only essential tool instructions but omits Claude Code’s coding guidelines, response style, and project context. To include the full Claude Code system prompt, specify `systemPrompt: { type: "preset", preset: "claude_code" }` in TypeScript or `system_prompt={"type": "preset", "preset": "claude_code"}` in Python.
+
+Claude Code’s system prompt includes:
+
+ * Tool usage instructions and available tools
+ * Code style and formatting guidelines
+ * Response tone and verbosity settings
+ * Security and safety instructions
+ * Context about the current working directory and environment
+
+##
+
+
+
+Methods of modification
+
+###
+
+
+
+Method 1: CLAUDE.md files (project-level instructions)
+
+CLAUDE.md files provide project-specific context and instructions that are automatically read by the Agent SDK when it runs in a directory. They serve as persistent “memory” for your project.
+
+####
+
+
+
+How CLAUDE.md works with the SDK
+
+**Location and discovery:**
+
+ * **Project-level:** `CLAUDE.md` or `.claude/CLAUDE.md` in your working directory
+ * **User-level:** `~/.claude/CLAUDE.md` for global instructions across all projects
+
+**IMPORTANT:** The SDK only reads CLAUDE.md files when you explicitly configure `settingSources` (TypeScript) or `setting_sources` (Python):
+
+ * Include `'project'` to load project-level CLAUDE.md
+ * Include `'user'` to load user-level CLAUDE.md (`~/.claude/CLAUDE.md`)
+
+The `claude_code` system prompt preset does NOT automatically load CLAUDE.md - you must also specify setting sources. **Content format:** CLAUDE.md files use plain markdown and can contain:
+
+ * Coding guidelines and standards
+ * Project-specific context
+ * Common commands or workflows
+ * API conventions
+ * Testing requirements
+
+####
+
+
+
+Example CLAUDE.md
+
+ # Project Guidelines
+
+ ## Code Style
+
+ - Use TypeScript strict mode
+ - Prefer functional components in React
+ - Always include JSDoc comments for public APIs
+
+ ## Testing
+
+ - Run `npm test` before committing
+ - Maintain >80% code coverage
+ - Use jest for unit tests, playwright for E2E
+
+ ## Commands
+
+ - Build: `npm run build`
+ - Dev server: `npm run dev`
+ - Type check: `npm run typecheck`
+
+####
+
+
+
+Using CLAUDE.md with the SDK
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // IMPORTANT: You must specify settingSources to load CLAUDE.md
+ // The claude_code preset alone does NOT load CLAUDE.md files
+ const messages = [];
+
+ for await (const message of query({
+ prompt: "Add a new React component for user profiles",
+ options: {
+ systemPrompt: {
+ type: "preset",
+ preset: "claude_code" // Use Claude Code's system prompt
+ },
+ settingSources: ["project"] // Required to load CLAUDE.md from project
+ }
+ })) {
+ messages.push(message);
+ }
+
+ // Now Claude has access to your project guidelines from CLAUDE.md
+
+####
+
+
+
+When to use CLAUDE.md
+
+**Best for:**
+
+ * **Team-shared context** \- Guidelines everyone should follow
+ * **Project conventions** \- Coding standards, file structure, naming patterns
+ * **Common commands** \- Build, test, deploy commands specific to your project
+ * **Long-term memory** \- Context that should persist across all sessions
+ * **Version-controlled instructions** \- Commit to git so the team stays in sync
+
+**Key characteristics:**
+
+ * ✅ Persistent across all sessions in a project
+ * ✅ Shared with team via git
+ * ✅ Automatic discovery (no code changes needed)
+ * ⚠️ Requires loading settings via `settingSources`
+
+###
+
+
+
+Method 2: Output styles (persistent configurations)
+
+Output styles are saved configurations that modify Claude’s system prompt. They’re stored as markdown files and can be reused across sessions and projects.
+
+####
+
+
+
+Creating an output style
+
+TypeScript
+
+Python
+
+ import { writeFile, mkdir } from "fs/promises";
+ import { join } from "path";
+ import { homedir } from "os";
+
+ async function createOutputStyle(name: string, description: string, prompt: string) {
+ // User-level: ~/.claude/output-styles
+ // Project-level: .claude/output-styles
+ const outputStylesDir = join(homedir(), ".claude", "output-styles");
+
+ await mkdir(outputStylesDir, { recursive: true });
+
+ const content = `---
+ name: ${name}
+ description: ${description}
+ ---
+
+ ${prompt}`;
+
+ const filePath = join(outputStylesDir, `${name.toLowerCase().replace(/\s+/g, "-")}.md`);
+ await writeFile(filePath, content, "utf-8");
+ }
+
+ // Example: Create a code review specialist
+ await createOutputStyle(
+ "Code Reviewer",
+ "Thorough code review assistant",
+ `You are an expert code reviewer.
+
+ For every code submission:
+ 1. Check for bugs and security issues
+ 2. Evaluate performance
+ 3. Suggest improvements
+ 4. Rate code quality (1-10)`
+ );
+
+####
+
+
+
+Using output styles
+
+Once created, activate output styles via:
+
+ * **CLI** : `/output-style [style-name]`
+ * **Settings** : `.claude/settings.local.json`
+ * **Create new** : `/output-style:new [description]`
+
+**Note for SDK users:** Output styles are loaded when you include `settingSources: ['user']` or `settingSources: ['project']` (TypeScript) / `setting_sources=["user"]` or `setting_sources=["project"]` (Python) in your options.
+
+###
+
+
+
+Method 3: Using `systemPrompt` with append
+
+You can use the Claude Code preset with an `append` property to add your custom instructions while preserving all built-in functionality.
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ const messages = [];
+
+ for await (const message of query({
+ prompt: "Help me write a Python function to calculate fibonacci numbers",
+ options: {
+ systemPrompt: {
+ type: "preset",
+ preset: "claude_code",
+ append: "Always include detailed docstrings and type hints in Python code."
+ }
+ }
+ })) {
+ messages.push(message);
+ if (message.type === "assistant") {
+ console.log(message.message.content);
+ }
+ }
+
+###
+
+
+
+Method 4: Custom system prompts
+
+You can provide a custom string as `systemPrompt` to replace the default entirely with your own instructions.
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ const customPrompt = `You are a Python coding specialist.
+ Follow these guidelines:
+ - Write clean, well-documented code
+ - Use type hints for all functions
+ - Include comprehensive docstrings
+ - Prefer functional programming patterns when appropriate
+ - Always explain your code choices`;
+
+ const messages = [];
+
+ for await (const message of query({
+ prompt: "Create a data processing pipeline",
+ options: {
+ systemPrompt: customPrompt
+ }
+ })) {
+ messages.push(message);
+ if (message.type === "assistant") {
+ console.log(message.message.content);
+ }
+ }
+
+##
+
+
+
+Comparison of all four approaches
+
+Feature| CLAUDE.md| Output Styles| `systemPrompt` with append| Custom `systemPrompt`
+---|---|---|---|---
+**Persistence**| Per-project file| Saved as files| Session only| Session only
+**Reusability**| Per-project| Across projects| Code duplication| Code duplication
+**Management**| On filesystem| CLI + files| In code| In code
+**Default tools**| Preserved| Preserved| Preserved| Lost (unless included)
+**Built-in safety**| Maintained| Maintained| Maintained| Must be added
+**Environment context**| Automatic| Automatic| Automatic| Must be provided
+**Customization level**| Additions only| Replace default| Additions only| Complete control
+**Version control**| With project| Yes| With code| With code
+**Scope**| Project-specific| User or project| Code session| Code session
+
+**Note:** “With append” means using `systemPrompt: { type: "preset", preset: "claude_code", append: "..." }` in TypeScript or `system_prompt={"type": "preset", "preset": "claude_code", "append": "..."}` in Python.
+
+##
+
+
+
+Use cases and best practices
+
+###
+
+
+
+When to use CLAUDE.md
+
+**Best for:**
+
+ * Project-specific coding standards and conventions
+ * Documenting project structure and architecture
+ * Listing common commands (build, test, deploy)
+ * Team-shared context that should be version controlled
+ * Instructions that apply to all SDK usage in a project
+
+**Examples:**
+
+ * “All API endpoints should use async/await patterns”
+ * “Run `npm run lint:fix` before committing”
+ * “Database migrations are in the `migrations/` directory”
+
+**Important:** To load CLAUDE.md files, you must explicitly set `settingSources: ['project']` (TypeScript) or `setting_sources=["project"]` (Python). The `claude_code` system prompt preset does NOT automatically load CLAUDE.md without this setting.
+
+###
+
+
+
+When to use output styles
+
+**Best for:**
+
+ * Persistent behavior changes across sessions
+ * Team-shared configurations
+ * Specialized assistants (code reviewer, data scientist, DevOps)
+ * Complex prompt modifications that need versioning
+
+**Examples:**
+
+ * Creating a dedicated SQL optimization assistant
+ * Building a security-focused code reviewer
+ * Developing a teaching assistant with specific pedagogy
+
+###
+
+
+
+When to use `systemPrompt` with append
+
+**Best for:**
+
+ * Adding specific coding standards or preferences
+ * Customizing output formatting
+ * Adding domain-specific knowledge
+ * Modifying response verbosity
+ * Enhancing Claude Code’s default behavior without losing tool instructions
+
+###
+
+
+
+When to use custom `systemPrompt`
+
+**Best for:**
+
+ * Complete control over Claude’s behavior
+ * Specialized single-session tasks
+ * Testing new prompt strategies
+ * Situations where default tools aren’t needed
+ * Building specialized agents with unique behavior
+
+##
+
+
+
+Combining approaches
+
+You can combine these methods for maximum flexibility:
+
+###
+
+
+
+Example: Output style with session-specific additions
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Assuming "Code Reviewer" output style is active (via /output-style)
+ // Add session-specific focus areas
+ const messages = [];
+
+ for await (const message of query({
+ prompt: "Review this authentication module",
+ options: {
+ systemPrompt: {
+ type: "preset",
+ preset: "claude_code",
+ append: `
+ For this review, prioritize:
+ - OAuth 2.0 compliance
+ - Token storage security
+ - Session management
+ `
+ }
+ }
+ })) {
+ messages.push(message);
+ }
+
+##
+
+
+
+See also
+
+ * [Output styles](</docs/en/output-styles>) \- Complete output styles documentation
+ * [TypeScript SDK guide](</docs/en/agent-sdk/typescript>) \- Complete SDK usage guide
+ * [Configuration guide](</docs/en/settings>) \- General configuration options
--- a/monitoring-usage.md
+++ b/monitoring-usage.md
@@ -120,7 +120,7 @@
`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces`
`OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000`
-Spans redact user prompt text and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1` and `OTEL_LOG_TOOL_CONTENT=1` to include them.
+Spans redact user prompt text and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1` and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs.
###
Show diff (158 lines)
--- a/observability.md
+++ b/observability.md
@@ -0,0 +1,155 @@
+When you run agents in production, you need visibility into what they did:
+
+ * which tools they called
+ * how long each model request took
+ * how many tokens were spent
+ * where failures occurred
+
+The Agent SDK can export this data as OpenTelemetry traces, metrics, and log events to any backend that accepts the OpenTelemetry Protocol (OTLP), such as Honeycomb, Datadog, Grafana, Langfuse, or a self-hosted collector. This guide explains how the SDK emits telemetry, how to configure the export, and how to tag and filter the data once it reaches your backend. To read token usage and cost directly from the SDK response stream instead of exporting to a backend, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>).
+
+##
+
+
+
+How telemetry flows from the SDK
+
+The Agent SDK runs the Claude Code CLI as a child process and communicates with it over a local pipe. The CLI has OpenTelemetry instrumentation built in: it records spans around each model request and tool execution, emits metrics for token and cost counters, and emits structured log events for prompts and tool results. The SDK does not produce telemetry of its own. Instead, it passes configuration through to the CLI process, and the CLI exports directly to your collector. Configuration is passed as environment variables. By default, the child process inherits your application’s environment, so you can configure telemetry in either of two places:
+
+ * **Process environment:** set the variables in your shell, container, or orchestrator before your application starts. Every `query()` call picks them up automatically with no code change. This is the recommended approach for production deployments.
+ * **Per-call options:** set the variables in `ClaudeAgentOptions.env` (Python) or `options.env` (TypeScript). Use this when different agents in the same process need different telemetry settings. In Python, `env` is merged on top of the inherited environment. In TypeScript, `env` replaces the inherited environment entirely, so include `...process.env` in the object you pass.
+
+The CLI exports three independent OpenTelemetry signals. Each has its own enable switch and its own exporter, so you can turn on only the ones you need.
+
+Signal| What it contains| Enable with
+---|---|---
+Metrics| Counters for tokens, cost, sessions, lines of code, and tool decisions| `OTEL_METRICS_EXPORTER`
+Log events| Structured records for each prompt, API request, API error, and tool result| `OTEL_LOGS_EXPORTER`
+Traces| Spans for each interaction, model request, tool call, and hook (beta)| `OTEL_TRACES_EXPORTER` plus `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`
+
+For the complete list of metric names, event names, and attributes, see the Claude Code [Monitoring](</docs/en/monitoring-usage>) reference. The Agent SDK emits the same data because it runs the same CLI. Span names are listed in Read agent traces below.
+
+##
+
+
+
+Enable telemetry export
+
+Telemetry is off until you set `CLAUDE_CODE_ENABLE_TELEMETRY=1` and choose at least one exporter. The most common configuration sends all three signals over OTLP HTTP to a collector. The following example sets the variables in a dictionary and passes them through `options.env`. The agent runs a single task, and the CLI exports spans, metrics, and events to the collector at `collector.example.com` while the loop consumes the response stream:
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ OTEL_ENV = {
+ "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
+ # Required for traces, which are in beta. Metrics and log events do not need this.
+ "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA": "1",
+ # Choose an exporter per signal. Use otlp for the SDK; see the Note below.
+ "OTEL_TRACES_EXPORTER": "otlp",
+ "OTEL_METRICS_EXPORTER": "otlp",
+ "OTEL_LOGS_EXPORTER": "otlp",
+ # Standard OTLP transport configuration.
+ "OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf",
+ "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.example.com:4318",
+ "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer your-token",
+ }
+
+ async def main():
+ options = ClaudeAgentOptions(env=OTEL_ENV)
+ async for message in query(
+ prompt="List the files in this directory", options=options
+ ):
+ print(message)
+
+ asyncio.run(main())
+
+Because the child process inherits your application’s environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely.
+
+The `console` exporter writes telemetry to standard output, which the SDK uses as its message channel. Do not set `console` as an exporter value when running through the SDK. To inspect telemetry locally, point `OTEL_EXPORTER_OTLP_ENDPOINT` at a local collector or an all-in-one Jaeger container instead.
+
+###
+
+
+
+Flush telemetry from short-lived calls
+
+The CLI batches telemetry and exports on an interval. It flushes any pending data when the process exits cleanly, so a `query()` call that completes normally does not lose spans. However, if your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces that window. By default, metrics export every 60 seconds and traces and logs export every 5 seconds. The following example shortens all three intervals so that data reaches the collector while a short task is still running:
+
+Python
+
+TypeScript
+
+ OTEL_ENV = {
+ # ... exporter configuration from the previous example ...
+ "OTEL_METRIC_EXPORT_INTERVAL": "1000",
+ "OTEL_LOGS_EXPORT_INTERVAL": "1000",
+ "OTEL_TRACES_EXPORT_INTERVAL": "1000",
+ }
+
+##
+
+
+
+Read agent traces
+
+Traces give you the most detailed view of an agent run. With `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` set, each step of the agent loop becomes a span you can inspect in your tracing backend:
+
+ * **`claude_code.interaction`:** wraps a single turn of the agent loop, from receiving a prompt to producing a response.
+ * **`claude_code.llm_request`:** wraps each call to the Claude API, with model name, latency, and token counts as attributes.
+ * **`claude_code.tool`:** wraps each tool invocation, with child spans for the permission wait (`claude_code.tool.blocked_on_user`) and the execution itself (`claude_code.tool.execution`).
+ * **`claude_code.hook`:** wraps each [hook](</docs/en/agent-sdk/hooks>) execution.
+
+Every span carries a `session.id` attribute. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline.
+
+Tracing is in beta. Span names and attributes may change between releases. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the trace exporter configuration variables.
+
+##
+
+
+
+Tag telemetry from your agent
+
+By default, the CLI reports `service.name` as `claude-code`. If you run several agents, or run the SDK alongside other services that export to the same collector, override the service name and add resource attributes so you can filter by agent in your backend. The following example renames the service and attaches deployment metadata. These values are applied as OpenTelemetry resource attributes on every span, metric, and event the agent emits:
+
+Python
+
+TypeScript
+
+ options = ClaudeAgentOptions(
+ env={
+ # ... exporter configuration ...
+ "OTEL_SERVICE_NAME": "support-triage-agent",
+ "OTEL_RESOURCE_ATTRIBUTES": "service.version=1.4.0,deployment.environment=production",
+ },
+ )
+
+##
+
+
+
+Control sensitive data in exports
+
+Telemetry is structural by default. Token counts, durations, model names, and tool names are always recorded, but the content your agent reads and writes is not. Three opt-in variables add content to the exported data:
+
+Variable| Adds
+---|---
+`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
+`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments (file paths, shell commands, search patterns) on `claude_code.tool_result` events
+`OTEL_LOG_TOOL_CONTENT=1`| Full tool input and output bodies as span events on `claude_code.tool`, truncated at 60 KB. Requires tracing to be enabled
+
+Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](</docs/en/monitoring-usage#security-and-privacy>) in the Monitoring reference for the full list of attributes and redaction behavior.
+
+##
+
+
+
+Related documentation
+
+These guides cover adjacent topics for monitoring and deploying agents:
+
+ * [Track cost and usage](</docs/en/agent-sdk/cost-tracking>): read token and cost data from the message stream without an external backend.
+ * [Hosting the Agent SDK](</docs/en/agent-sdk/hosting>): deploy agents in containers where you can set OpenTelemetry variables at the environment level.
+ * [Monitoring](</docs/en/monitoring-usage>): the complete reference for every environment variable, metric, and event the CLI emits.
--- a/overview.md
+++ b/overview.md
@@ -70,11 +70,11 @@
* [macOS](<https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs>) (Intel and Apple Silicon)
* [Windows](<https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs>) (x64)
- * [Windows ARM64](<https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs>) (remote sessions only)
+ * [Windows ARM64](<https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs>)
After installing, launch Claude, sign in, and click the **Code** tab to start coding. A [paid subscription](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=overview_desktop_pricing>) is required.[Learn more about the desktop app →](</docs/en/desktop-quickstart>)
-Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they’re done, work on repos you don’t have locally, or run multiple tasks in parallel. Available on desktop browsers and the Claude iOS app.Start coding at [claude.ai/code](<https://claude.ai/code>).[Get started on the web →](</docs/en/claude-code-on-the-web#getting-started>)
+Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they’re done, work on repos you don’t have locally, or run multiple tasks in parallel. Available on desktop browsers and the Claude iOS app.Start coding at [claude.ai/code](<https://claude.ai/code>).[Get started on the web →](</docs/en/web-quickstart>)
A plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with interactive diff viewing and selection context sharing.Install the [Claude Code plugin](<https://plugins.jetbrains.com/plugin/27310-claude-code-beta->) from the JetBrains Marketplace and restart your IDE.[Get started with JetBrains →](</docs/en/jetbrains>)
@@ -114,7 +114,7 @@
Run agent teams and build custom agents
-Spawn [multiple Claude Code agents](</docs/en/sub-agents>) that work on different parts of a task simultaneously. A lead agent coordinates the work, assigns subtasks, and merges results.For fully custom workflows, the [Agent SDK](<https://platform.claude.com/docs/en/agent-sdk/overview>) lets you build your own agents powered by Claude Code’s tools and capabilities, with full control over orchestration, tool access, and permissions.
+Spawn [multiple Claude Code agents](</docs/en/sub-agents>) that work on different parts of a task simultaneously. A lead agent coordinates the work, assigns subtasks, and merges results.For fully custom workflows, the [Agent SDK](</docs/en/agent-sdk/overview>) lets you build your own agents powered by Claude Code’s tools and capabilities, with full control over orchestration, tool access, and permissions.
Pipe, script, and automate with the CLI
@@ -167,7 +167,7 @@
Get automatic code review on every PR| [GitHub Code Review](</docs/en/code-review>)
Route bug reports from Slack to pull requests| [Slack](</docs/en/slack>)
Debug live web applications| [Chrome](</docs/en/chrome>)
-Build custom agents for your own workflows| [Agent SDK](<https://platform.claude.com/docs/en/agent-sdk/overview>)
+Build custom agents for your own workflows| [Agent SDK](</docs/en/agent-sdk/overview>)
##
--- a/permission-modes.md
+++ b/permission-modes.md
@@ -11,7 +11,7 @@
Mode| What runs without asking| Best for
---|---|---
`default`| Reads only| Getting started, sensitive work
-`acceptEdits`| Reads and file edits| Iterating on code you’re reviewing
+`acceptEdits`| Reads, file edits, and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.)| Iterating on code you’re reviewing
`plan`| Reads only| Exploring a codebase before changing it
`auto`| Everything, with background safety checks| Long tasks, reducing prompt fatigue
`dontAsk`| Only pre-approved tools| Locked-down CI and scripts
@@ -88,7 +88,7 @@
Auto-approve file edits with acceptEdits mode
-`acceptEdits` mode lets Claude create and edit files in your working directory without prompting. Writes to protected paths and all non-edit actions still prompt the same as default mode. The status bar shows `⏵⏵ accept edits on` while this mode is active. Use `acceptEdits` when you want to review changes in your editor or via `git diff` after the fact rather than approving each edit inline. Press `Shift+Tab` once from default mode to enter it, or start with it directly:
+`acceptEdits` mode lets Claude create and edit files in your working directory without prompting. The status bar shows `⏵⏵ accept edits on` while this mode is active. In addition to file edits, `acceptEdits` mode auto-approves common filesystem Bash commands: `mkdir`, `touch`, `rm`, `rmdir`, `mv`, `cp`, and `sed`. Like file edits, these are auto-approved only for paths inside your working directory or `additionalDirectories`. Paths outside that scope, writes to protected paths, and all other Bash commands still prompt. Use `acceptEdits` when you want to review changes in your editor or via `git diff` after the fact rather than approving each edit inline. Press `Shift+Tab` once from default mode to enter it, or start with it directly:
claude --permission-mode acceptEdits
@@ -159,6 +159,7 @@
* Reading `.env` and sending credentials to their matching API
* Read-only HTTP requests
* Pushing to the branch you started on or one Claude created
+ * Sandbox network access requests
Run `claude auto-mode defaults` to see the full rule lists. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure the auto mode classifier](</docs/en/permissions#configure-the-auto-mode-classifier>).
--- a/permissions.md
+++ b/permissions.md
@@ -39,7 +39,7 @@
Mode| Description
---|---
`default`| Standard behavior: prompts for permission on first use of each tool
-`acceptEdits`| Automatically accepts file edit permissions for the session, except writes to protected directories
+`acceptEdits`| Automatically accepts file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.) for paths in the working directory or `additionalDirectories`
`plan`| Plan Mode: Claude can analyze but not modify files or execute commands
`auto`| Auto-approves tool calls with background safety checks that verify actions align with your request. Currently a research preview
`dontAsk`| Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules
--- a/platforms.md
+++ b/platforms.md
@@ -15,8 +15,9 @@
[VS Code](</docs/en/vs-code>)| Working inside VS Code without switching to a terminal| Inline diffs, integrated terminal, file context
[JetBrains](</docs/en/jetbrains>)| Working inside IntelliJ, PyCharm, WebStorm, or other JetBrains IDEs| Diff viewer, selection sharing, terminal session
[Web](</docs/en/claude-code-on-the-web>)| Long-running tasks that don’t need much steering, or work that should continue when you’re offline| Anthropic-managed cloud, continues after you disconnect
+Mobile| Starting and monitoring tasks while away from your computer| Cloud sessions from the Claude app for iOS and Android, [Remote Control](</docs/en/remote-control>) for local sessions, [Dispatch](</docs/en/desktop#sessions-from-dispatch>) to Desktop on Pro and Max
-The CLI is the most complete surface for terminal-native work: scripting, third-party providers, and the Agent SDK are CLI-only. Desktop and the IDE extensions trade some CLI-only features for visual review and tighter editor integration. The web runs in Anthropic’s cloud, so tasks keep going after you disconnect. You can mix surfaces on the same project. Configuration, project memory, and MCP servers are shared across the local surfaces.
+The CLI is the most complete surface for terminal-native work: scripting, third-party providers, and the Agent SDK are CLI-only. Desktop and the IDE extensions trade some CLI-only features for visual review and tighter editor integration. The web runs in Anthropic’s cloud, so tasks keep going after you disconnect. Mobile is a thin client into those same cloud sessions or into a local session via Remote Control, and can send tasks to Desktop with Dispatch. You can mix surfaces on the same project. Configuration, project memory, and MCP servers are shared across the local surfaces.
##
@@ -71,6 +72,7 @@
* [VS Code](</docs/en/vs-code>): the Claude Code extension inside your editor
* [JetBrains](</docs/en/jetbrains>): the extension for IntelliJ, PyCharm, and other JetBrains IDEs
* [Claude Code on the web](</docs/en/claude-code-on-the-web>): cloud sessions that keep running when you disconnect
+ * Mobile: the Claude app for [iOS](<https://apps.apple.com/us/app/claude-by-anthropic/id6473753684>) and [Android](<https://play.google.com/store/apps/details?id=com.anthropic.claude>) for starting and monitoring tasks while away from your computer
###
Show diff (3419 lines)
--- a/python.md
+++ b/python.md
@@ -0,0 +1,3416 @@
+##
+
+
+
+Installation
+
+ pip install claude-agent-sdk
+
+##
+
+
+
+Choosing between `query()` and `ClaudeSDKClient`
+
+The Python SDK provides two ways to interact with Claude Code:
+
+###
+
+
+
+Quick comparison
+
+Feature| `query()`| `ClaudeSDKClient`
+---|---|---
+**Session**| Creates new session each time| Reuses same session
+**Conversation**| Single exchange| Multiple exchanges in same context
+**Connection**| Managed automatically| Manual control
+**Streaming Input**| ✅ Supported| ✅ Supported
+**Interrupts**| ❌ Not supported| ✅ Supported
+**Hooks**| ✅ Supported| ✅ Supported
+**Custom Tools**| ✅ Supported| ✅ Supported
+**Continue Chat**| ❌ New session each time| ✅ Maintains conversation
+**Use Case**| One-off tasks| Continuous conversations
+
+###
+
+
+
+When to use `query()` (new session each time)
+
+**Best for:**
+
+ * One-off questions where you don’t need conversation history
+ * Independent tasks that don’t require context from previous exchanges
+ * Simple automation scripts
+ * When you want a fresh start each time
+
+###
+
+
+
+When to use `ClaudeSDKClient` (continuous conversation)
+
+**Best for:**
+
+ * **Continuing conversations** \- When you need Claude to remember context
+ * **Follow-up questions** \- Building on previous responses
+ * **Interactive applications** \- Chat interfaces, REPLs
+ * **Response-driven logic** \- When next action depends on Claude’s response
+ * **Session control** \- Managing conversation lifecycle explicitly
+
+##
+
+
+
+Functions
+
+###
+
+
+
+`query()`
+
+Creates a new session for each interaction with Claude Code. Returns an async iterator that yields messages as they arrive. Each call to `query()` starts fresh with no memory of previous interactions.
+
+ async def query(
+ *,
+ prompt: str | AsyncIterable[dict[str, Any]],
+ options: ClaudeAgentOptions | None = None,
+ transport: Transport | None = None
+ ) -> AsyncIterator[Message]
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Description
+---|---|---
+`prompt`| `str | AsyncIterable[dict]`| The input prompt as a string or async iterable for streaming mode
+`options`| `ClaudeAgentOptions | None`| Optional configuration object (defaults to `ClaudeAgentOptions()` if None)
+`transport`| `Transport | None`| Optional custom transport for communicating with the CLI process
+
+####
+
+
+
+Returns
+
+Returns an `AsyncIterator[Message]` that yields messages from the conversation.
+
+####
+
+
+
+Example - With options
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async def main():
+ options = ClaudeAgentOptions(
+ system_prompt="You are an expert Python developer",
+ permission_mode="acceptEdits",
+ cwd="/home/user/project",
+ )
+
+ async for message in query(prompt="Create a Python web server", options=options):
+ print(message)
+
+ asyncio.run(main())
+
+###
+
+
+
+`tool()`
+
+Decorator for defining MCP tools with type safety.
+
+ def tool(
+ name: str,
+ description: str,
+ input_schema: type | dict[str, Any],
+ annotations: ToolAnnotations | None = None
+ ) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Description
+---|---|---
+`name`| `str`| Unique identifier for the tool
+`description`| `str`| Human-readable description of what the tool does
+`input_schema`| `type | dict[str, Any]`| Schema defining the tool’s input parameters (see below)
+`annotations`| `ToolAnnotations`` | None`| Optional MCP tool annotations providing behavioral hints to clients
+
+####
+
+
+
+Input schema options
+
+ 1. **Simple type mapping** (recommended):
+
+ {"text": str, "count": int, "enabled": bool}
+
+ 2. **JSON Schema format** (for complex validation):
+
+ {
+ "type": "object",
+ "properties": {
+ "text": {"type": "string"},
+ "count": {"type": "integer", "minimum": 0},
+ },
+ "required": ["text"],
+ }
+
+####
+
+
+
+Returns
+
+A decorator function that wraps the tool implementation and returns an `SdkMcpTool` instance.
+
+####
+
+
+
+Example
+
+ from claude_agent_sdk import tool
+ from typing import Any
+
+ @tool("greet", "Greet a user", {"name": str})
+ async def greet(args: dict[str, Any]) -> dict[str, Any]:
+ return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}
+
+####
+
+
+
+`ToolAnnotations`
+
+Re-exported from `mcp.types` (also available as `from claude_agent_sdk import ToolAnnotations`). All fields are optional hints; clients should not rely on them for security decisions.
+
+Field| Type| Default| Description
+---|---|---|---
+`title`| `str | None`| `None`| Human-readable title for the tool
+`readOnlyHint`| `bool | None`| `False`| If `True`, the tool does not modify its environment
+`destructiveHint`| `bool | None`| `True`| If `True`, the tool may perform destructive updates (only meaningful when `readOnlyHint` is `False`)
+`idempotentHint`| `bool | None`| `False`| If `True`, repeated calls with the same arguments have no additional effect (only meaningful when `readOnlyHint` is `False`)
+`openWorldHint`| `bool | None`| `True`| If `True`, the tool interacts with external entities (for example, web search). If `False`, the tool’s domain is closed (for example, a memory tool)
+
+ from claude_agent_sdk import tool, ToolAnnotations
+ from typing import Any
+
+ @tool(
+ "search",
+ "Search the web",
+ {"query": str},
+ annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True),
+ )
+ async def search(args: dict[str, Any]) -> dict[str, Any]:
+ return {"content": [{"type": "text", "text": f"Results for: {args['query']}"}]}
+
+###
+
+
+
+`create_sdk_mcp_server()`
+
+Create an in-process MCP server that runs within your Python application.
+
+ def create_sdk_mcp_server(
+ name: str,
+ version: str = "1.0.0",
+ tools: list[SdkMcpTool[Any]] | None = None
+ ) -> McpSdkServerConfig
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`name`| `str`| -| Unique identifier for the server
+`version`| `str`| `"1.0.0"`| Server version string
+`tools`| `list[SdkMcpTool[Any]] | None`| `None`| List of tool functions created with `@tool` decorator
+
+####
+
+
+
+Returns
+
+Returns an `McpSdkServerConfig` object that can be passed to `ClaudeAgentOptions.mcp_servers`.
+
+####
+
+
+
+Example
+
+ from claude_agent_sdk import tool, create_sdk_mcp_server
+
+ @tool("add", "Add two numbers", {"a": float, "b": float})
+ async def add(args):
+ return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}
+
+ @tool("multiply", "Multiply two numbers", {"a": float, "b": float})
+ async def multiply(args):
+ return {"content": [{"type": "text", "text": f"Product: {args['a'] * args['b']}"}]}
+
+ calculator = create_sdk_mcp_server(
+ name="calculator",
+ version="2.0.0",
+ tools=[add, multiply], # Pass decorated functions
+ )
+
+ # Use with Claude
+ options = ClaudeAgentOptions(
+ mcp_servers={"calc": calculator},
+ allowed_tools=["mcp__calc__add", "mcp__calc__multiply"],
+ )
+
+###
+
+
+
+`list_sessions()`
+
+Lists past sessions with metadata. Filter by project directory or list sessions across all projects. Synchronous; returns immediately.
+
+ def list_sessions(
+ directory: str | None = None,
+ limit: int | None = None,
+ include_worktrees: bool = True
+ ) -> list[SDKSessionInfo]
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`directory`| `str | None`| `None`| Directory to list sessions for. When omitted, returns sessions across all projects
+`limit`| `int | None`| `None`| Maximum number of sessions to return
+`include_worktrees`| `bool`| `True`| When `directory` is inside a git repository, include sessions from all worktree paths
+
+####
+
+
+
+Return type: `SDKSessionInfo`
+
+Property| Type| Description
+---|---|---
+`session_id`| `str`| Unique session identifier
+`summary`| `str`| Display title: custom title, auto-generated summary, or first prompt
+`last_modified`| `int`| Last modified time in milliseconds since epoch
+`file_size`| `int | None`| Session file size in bytes (`None` for remote storage backends)
+`custom_title`| `str | None`| User-set session title
+`first_prompt`| `str | None`| First meaningful user prompt in the session
+`git_branch`| `str | None`| Git branch at the end of the session
+`cwd`| `str | None`| Working directory for the session
+`tag`| `str | None`| User-set session tag (see `tag_session()`)
+`created_at`| `int | None`| Session creation time in milliseconds since epoch
+
+####
+
+
+
+Example
+
+Print the 10 most recent sessions for a project. Results are sorted by `last_modified` descending, so the first item is the newest. Omit `directory` to search across all projects.
+
+ from claude_agent_sdk import list_sessions
+
+ for session in list_sessions(directory="/path/to/project", limit=10):
+ print(f"{session.summary} ({session.session_id})")
+
+###
+
+
+
+`get_session_messages()`
+
+Retrieves messages from a past session. Synchronous; returns immediately.
+
+ def get_session_messages(
+ session_id: str,
+ directory: str | None = None,
+ limit: int | None = None,
+ offset: int = 0
+ ) -> list[SessionMessage]
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`session_id`| `str`| required| The session ID to retrieve messages for
+`directory`| `str | None`| `None`| Project directory to look in. When omitted, searches all projects
+`limit`| `int | None`| `None`| Maximum number of messages to return
+`offset`| `int`| `0`| Number of messages to skip from the start
+
+####
+
+
+
+Return type: `SessionMessage`
+
+Property| Type| Description
+---|---|---
+`type`| `Literal["user", "assistant"]`| Message role
+`uuid`| `str`| Unique message identifier
+`session_id`| `str`| Session identifier
+`message`| `Any`| Raw message content
+`parent_tool_use_id`| `None`| Reserved for future use
+
+####
+
+
+
+Example
+
+ from claude_agent_sdk import list_sessions, get_session_messages
+
+ sessions = list_sessions(limit=1)
+ if sessions:
+ messages = get_session_messages(sessions[0].session_id)
+ for msg in messages:
+ print(f"[{msg.type}] {msg.uuid}")
+
+###
+
+
+
+`get_session_info()`
+
+Reads metadata for a single session by ID without scanning the full project directory. Synchronous; returns immediately.
+
+ def get_session_info(
+ session_id: str,
+ directory: str | None = None,
+ ) -> SDKSessionInfo | None
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`session_id`| `str`| required| UUID of the session to look up
+`directory`| `str | None`| `None`| Project directory path. When omitted, searches all project directories
+
+Returns `SDKSessionInfo`, or `None` if the session is not found.
+
+####
+
+
+
+Example
+
+Look up a single session’s metadata without scanning the project directory. Useful when you already have a session ID from a previous run.
+
+ from claude_agent_sdk import get_session_info
+
+ info = get_session_info("550e8400-e29b-41d4-a716-446655440000")
+ if info:
+ print(f"{info.summary} (branch: {info.git_branch}, tag: {info.tag})")
+
+###
+
+
+
+`rename_session()`
+
+Renames a session by appending a custom-title entry. Repeated calls are safe; the most recent title wins. Synchronous.
+
+ def rename_session(
+ session_id: str,
+ title: str,
+ directory: str | None = None,
+ ) -> None
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`session_id`| `str`| required| UUID of the session to rename
+`title`| `str`| required| New title. Must be non-empty after stripping whitespace
+`directory`| `str | None`| `None`| Project directory path. When omitted, searches all project directories
+
+Raises `ValueError` if `session_id` is not a valid UUID or `title` is empty; `FileNotFoundError` if the session cannot be found.
+
+####
+
+
+
+Example
+
+Rename the most recent session so it’s easier to find later. The new title appears in `SDKSessionInfo.custom_title` on subsequent reads.
+
+ from claude_agent_sdk import list_sessions, rename_session
+
+ sessions = list_sessions(directory="/path/to/project", limit=1)
+ if sessions:
+ rename_session(sessions[0].session_id, "Refactor auth module")
+
+###
+
+
+
+`tag_session()`
+
+Tags a session. Pass `None` to clear the tag. Repeated calls are safe; the most recent tag wins. Synchronous.
+
+ def tag_session(
+ session_id: str,
+ tag: str | None,
+ directory: str | None = None,
+ ) -> None
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`session_id`| `str`| required| UUID of the session to tag
+`tag`| `str | None`| required| Tag string, or `None` to clear. Unicode-sanitized before storing
+`directory`| `str | None`| `None`| Project directory path. When omitted, searches all project directories
+
+Raises `ValueError` if `session_id` is not a valid UUID or `tag` is empty after sanitization; `FileNotFoundError` if the session cannot be found.
+
+####
+
+
+
+Example
+
+Tag a session, then filter by that tag on a later read. Pass `None` to clear an existing tag.
+
+ from claude_agent_sdk import list_sessions, tag_session
+
+ # Tag a session
+ tag_session("550e8400-e29b-41d4-a716-446655440000", "needs-review")
+
+ # Later: find all sessions with that tag
+ for session in list_sessions(directory="/path/to/project"):
+ if session.tag == "needs-review":
+ print(session.summary)
+
+##
+
+
+
+Classes
+
+###
+
+
+
+`ClaudeSDKClient`
+
+**Maintains a conversation session across multiple exchanges.** This is the Python equivalent of how the TypeScript SDK’s `query()` function works internally - it creates a client object that can continue conversations.
+
+####
+
+
+
+Key Features
+
+ * **Session continuity** : Maintains conversation context across multiple `query()` calls
+ * **Same conversation** : The session retains previous messages
+ * **Interrupt support** : Can stop execution mid-task
+ * **Explicit lifecycle** : You control when the session starts and ends
+ * **Response-driven flow** : Can react to responses and send follow-ups
+ * **Custom tools and hooks** : Supports custom tools (created with `@tool` decorator) and hooks
+
+ class ClaudeSDKClient:
+ def __init__(self, options: ClaudeAgentOptions | None = None, transport: Transport | None = None)
+ async def connect(self, prompt: str | AsyncIterable[dict] | None = None) -> None
+ async def query(self, prompt: str | AsyncIterable[dict], session_id: str = "default") -> None
+ async def receive_messages(self) -> AsyncIterator[Message]
+ async def receive_response(self) -> AsyncIterator[Message]
+ async def interrupt(self) -> None
+ async def set_permission_mode(self, mode: str) -> None
+ async def set_model(self, model: str | None = None) -> None
+ async def rewind_files(self, user_message_id: str) -> None
+ async def get_mcp_status(self) -> McpStatusResponse
+ async def reconnect_mcp_server(self, server_name: str) -> None
+ async def toggle_mcp_server(self, server_name: str, enabled: bool) -> None
+ async def stop_task(self, task_id: str) -> None
+ async def get_server_info(self) -> dict[str, Any] | None
+ async def disconnect(self) -> None
+
+####
+
+
+
+Methods
+
+Method| Description
+---|---
+`__init__(options)`| Initialize the client with optional configuration
+`connect(prompt)`| Connect to Claude with an optional initial prompt or message stream
+`query(prompt, session_id)`| Send a new request in streaming mode
+`receive_messages()`| Receive all messages from Claude as an async iterator
+`receive_response()`| Receive messages until and including a ResultMessage
+`interrupt()`| Send interrupt signal (only works in streaming mode)
+`set_permission_mode(mode)`| Change the permission mode for the current session
+`set_model(model)`| Change the model for the current session. Pass `None` to reset to default
+`rewind_files(user_message_id)`| Restore files to their state at the specified user message. Requires `enable_file_checkpointing=True`. See [File checkpointing](</docs/en/agent-sdk/file-checkpointing>)
+`get_mcp_status()`| Get the status of all configured MCP servers. Returns `McpStatusResponse`
+`reconnect_mcp_server(server_name)`| Retry connecting to an MCP server that failed or was disconnected
+`toggle_mcp_server(server_name, enabled)`| Enable or disable an MCP server mid-session. Disabling removes its tools
+`stop_task(task_id)`| Stop a running background task. A `TaskNotificationMessage` with status `"stopped"` follows in the message stream
+`get_server_info()`| Get server information including session ID and capabilities
+`disconnect()`| Disconnect from Claude
+
+####
+
+
+
+Context Manager Support
+
+The client can be used as an async context manager for automatic connection management:
+
+ async with ClaudeSDKClient() as client:
+ await client.query("Hello Claude")
+ async for message in client.receive_response():
+ print(message)
+
+> **Important:** When iterating over messages, avoid using `break` to exit early as this can cause asyncio cleanup issues. Instead, let the iteration complete naturally or use flags to track when you’ve found what you need.
+
+####
+
+
+
+Example - Continuing a conversation
+
+ import asyncio
+ from claude_agent_sdk import ClaudeSDKClient, AssistantMessage, TextBlock, ResultMessage
+
+ async def main():
+ async with ClaudeSDKClient() as client:
+ # First question
+ await client.query("What's the capital of France?")
+
+ # Process response
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(f"Claude: {block.text}")
+
+ # Follow-up question - the session retains the previous context
+ await client.query("What's the population of that city?")
+
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(f"Claude: {block.text}")
+
+ # Another follow-up - still in the same conversation
+ await client.query("What are some famous landmarks there?")
+
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(f"Claude: {block.text}")
+
+ asyncio.run(main())
+
+####
+
+
+
+Example - Streaming input with ClaudeSDKClient
+
+ import asyncio
+ from claude_agent_sdk import ClaudeSDKClient
+
+ async def message_stream():
+ """Generate messages dynamically."""
+ yield {
+ "type": "user",
+ "message": {"role": "user", "content": "Analyze the following data:"},
+ }
+ await asyncio.sleep(0.5)
+ yield {
+ "type": "user",
+ "message": {"role": "user", "content": "Temperature: 25°C, Humidity: 60%"},
+ }
+ await asyncio.sleep(0.5)
+ yield {
+ "type": "user",
+ "message": {"role": "user", "content": "What patterns do you see?"},
+ }
+
+ async def main():
+ async with ClaudeSDKClient() as client:
+ # Stream input to Claude
+ await client.query(message_stream())
+
+ # Process response
+ async for message in client.receive_response():
+ print(message)
+
+ # Follow-up in same session
+ await client.query("Should we be concerned about these readings?")
+
+ async for message in client.receive_response():
+ print(message)
+
+ asyncio.run(main())
+
+####
+
+
+
+Example - Using interrupts
+
+ import asyncio
+ from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, ResultMessage
+
+ async def interruptible_task():
+ options = ClaudeAgentOptions(allowed_tools=["Bash"], permission_mode="acceptEdits")
+
+ async with ClaudeSDKClient(options=options) as client:
+ # Start a long-running task
+ await client.query("Count from 1 to 100 slowly, using the bash sleep command")
+
+ # Let it run for a bit
+ await asyncio.sleep(2)
+
+ # Interrupt the task
+ await client.interrupt()
+ print("Task interrupted!")
+
+ # Drain the interrupted task's messages (including its ResultMessage)
+ async for message in client.receive_response():
+ if isinstance(message, ResultMessage):
+ print(f"Interrupted task finished with subtype={message.subtype!r}")
+ # subtype is "error_during_execution" for interrupted tasks
+
+ # Send a new command
+ await client.query("Just say hello instead")
+
+ # Now receive the new response
+ async for message in client.receive_response():
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(f"New result: {message.result}")
+
+ asyncio.run(interruptible_task())
+
+**Buffer behavior after interrupt:** `interrupt()` sends a stop signal but does not clear the message buffer. Messages already produced by the interrupted task, including its `ResultMessage` (with `subtype="error_during_execution"`), remain in the stream. You must drain them with `receive_response()` before reading the response to a new query. If you send a new query immediately after `interrupt()` and call `receive_response()` only once, you’ll receive the interrupted task’s messages, not the new query’s response.
+
+####
+
+
+
+Example - Advanced permission control
+
+ from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
+ from claude_agent_sdk.types import (
+ PermissionResultAllow,
+ PermissionResultDeny,
+ ToolPermissionContext,
+ )
+
+ async def custom_permission_handler(
+ tool_name: str, input_data: dict, context: ToolPermissionContext
+ ) -> PermissionResultAllow | PermissionResultDeny:
+ """Custom logic for tool permissions."""
+
+ # Block writes to system directories
+ if tool_name == "Write" and input_data.get("file_path", "").startswith("/system/"):
+ return PermissionResultDeny(
+ message="System directory write not allowed", interrupt=True
+ )
+
+ # Redirect sensitive file operations
+ if tool_name in ["Write", "Edit"] and "config" in input_data.get("file_path", ""):
+ safe_path = f"./sandbox/{input_data['file_path']}"
+ return PermissionResultAllow(
+ updated_input={**input_data, "file_path": safe_path}
+ )
+
+ # Allow everything else
+ return PermissionResultAllow(updated_input=input_data)
+
+ async def main():
+ options = ClaudeAgentOptions(
+ can_use_tool=custom_permission_handler, allowed_tools=["Read", "Write", "Edit"]
+ )
+
+ async with ClaudeSDKClient(options=options) as client:
+ await client.query("Update the system config file")
+
+ async for message in client.receive_response():
+ # Will use sandbox path instead
+ print(message)
+
+ asyncio.run(main())
+
+##
+
+
+
+Types
+
+**`@dataclass` vs `TypedDict`:** This SDK uses two kinds of types. Classes decorated with `@dataclass` (such as `ResultMessage`, `AgentDefinition`, `TextBlock`) are object instances at runtime and support attribute access: `msg.result`. Classes defined with `TypedDict` (such as `ThinkingConfigEnabled`, `McpStdioServerConfig`, `SyncHookJSONOutput`) are **plain dicts at runtime** and require key access: `config["budget_tokens"]`, not `config.budget_tokens`. The `ClassName(field=value)` call syntax works for both, but only dataclasses produce objects with attributes.
+
+###
+
+
+
+`SdkMcpTool`
+
+Definition for an SDK MCP tool created with the `@tool` decorator.
+
+ @dataclass
+ class SdkMcpTool(Generic[T]):
+ name: str
+ description: str
+ input_schema: type[T] | dict[str, Any]
+ handler: Callable[[T], Awaitable[dict[str, Any]]]
+ annotations: ToolAnnotations | None = None
+
+Property| Type| Description
+---|---|---
+`name`| `str`| Unique identifier for the tool
+`description`| `str`| Human-readable description
+`input_schema`| `type[T] | dict[str, Any]`| Schema for input validation
+`handler`| `Callable[[T], Awaitable[dict[str, Any]]]`| Async function that handles tool execution
+`annotations`| `ToolAnnotations | None`| Optional MCP tool annotations (e.g., `readOnlyHint`, `destructiveHint`, `openWorldHint`). From `mcp.types`
+
+###
+
+
+
+`Transport`
+
+Abstract base class for custom transport implementations. Use this to communicate with the Claude process over a custom channel (for example, a remote connection instead of a local subprocess).
+
+This is a low-level internal API. The interface may change in future releases. Custom implementations must be updated to match any interface changes.
+
+ from abc import ABC, abstractmethod
+ from collections.abc import AsyncIterator
+ from typing import Any
+
+ class Transport(ABC):
+ @abstractmethod
+ async def connect(self) -> None: ...
+
+ @abstractmethod
+ async def write(self, data: str) -> None: ...
+
+ @abstractmethod
+ def read_messages(self) -> AsyncIterator[dict[str, Any]]: ...
+
+ @abstractmethod
+ async def close(self) -> None: ...
+
+ @abstractmethod
+ def is_ready(self) -> bool: ...
+
+ @abstractmethod
+ async def end_input(self) -> None: ...
+
+Method| Description
+---|---
+`connect()`| Connect the transport and prepare for communication
+`write(data)`| Write raw data (JSON + newline) to the transport
+`read_messages()`| Async iterator that yields parsed JSON messages
+`close()`| Close the connection and clean up resources
+`is_ready()`| Returns `True` if the transport can send and receive
+`end_input()`| Close the input stream (for example, close stdin for subprocess transports)
+
+Import: `from claude_agent_sdk import Transport`
+
+###
+
+
+
+`ClaudeAgentOptions`
+
+Configuration dataclass for Claude Code queries.
+
+ @dataclass
+ class ClaudeAgentOptions:
+ tools: list[str] | ToolsPreset | None = None
+ allowed_tools: list[str] = field(default_factory=list)
+ system_prompt: str | SystemPromptPreset | None = None
+ mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
+ permission_mode: PermissionMode | None = None
+ continue_conversation: bool = False
+ resume: str | None = None
+ max_turns: int | None = None
+ max_budget_usd: float | None = None
+ disallowed_tools: list[str] = field(default_factory=list)
+ model: str | None = None
+ fallback_model: str | None = None
+ betas: list[SdkBeta] = field(default_factory=list)
+ output_format: dict[str, Any] | None = None
+ permission_prompt_tool_name: str | None = None
+ cwd: str | Path | None = None
+ cli_path: str | Path | None = None
+ settings: str | None = None
+ add_dirs: list[str | Path] = field(default_factory=list)
+ env: dict[str, str] = field(default_factory=dict)
+ extra_args: dict[str, str | None] = field(default_factory=dict)
+ max_buffer_size: int | None = None
+ debug_stderr: Any = sys.stderr # Deprecated
+ stderr: Callable[[str], None] | None = None
+ can_use_tool: CanUseTool | None = None
+ hooks: dict[HookEvent, list[HookMatcher]] | None = None
+ user: str | None = None
+ include_partial_messages: bool = False
+ fork_session: bool = False
+ agents: dict[str, AgentDefinition] | None = None
+ setting_sources: list[SettingSource] | None = None
+ sandbox: SandboxSettings | None = None
+ plugins: list[SdkPluginConfig] = field(default_factory=list)
+ max_thinking_tokens: int | None = None # Deprecated: use thinking instead
+ thinking: ThinkingConfig | None = None
+ effort: Literal["low", "medium", "high", "max"] | None = None
+ enable_file_checkpointing: bool = False
+
+Property| Type| Default| Description
+---|---|---|---
+`tools`| `list[str] | ToolsPreset | None`| `None`| Tools configuration. Use `{"type": "preset", "preset": "claude_code"}` for Claude Code’s default tools
+`allowed_tools`| `list[str]`| `[]`| Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permission_mode` and `can_use_tool`. Use `disallowed_tools` to block tools. See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
+`system_prompt`| `str | SystemPromptPreset | None`| `None`| System prompt configuration. Pass a string for custom prompt, or use `{"type": "preset", "preset": "claude_code"}` for Claude Code’s system prompt. Add `"append"` to extend the preset
+`mcp_servers`| `dict[str, McpServerConfig] | str | Path`| `{}`| MCP server configurations or path to config file
+`permission_mode`| `PermissionMode | None`| `None`| Permission mode for tool usage
+`continue_conversation`| `bool`| `False`| Continue the most recent conversation
+`resume`| `str | None`| `None`| Session ID to resume
+`max_turns`| `int | None`| `None`| Maximum agentic turns (tool-use round trips)
+`max_budget_usd`| `float | None`| `None`| Maximum budget in USD for the session
+`disallowed_tools`| `list[str]`| `[]`| Tools to always deny. Deny rules are checked first and override `allowed_tools` and `permission_mode` (including `bypassPermissions`)
+`enable_file_checkpointing`| `bool`| `False`| Enable file change tracking for rewinding. See [File checkpointing](</docs/en/agent-sdk/file-checkpointing>)
+`model`| `str | None`| `None`| Claude model to use
+`fallback_model`| `str | None`| `None`| Fallback model to use if the primary model fails
+`betas`| `list[SdkBeta]`| `[]`| Beta features to enable. See `SdkBeta` for available options
+`output_format`| `dict[str, Any] | None`| `None`| Output format for structured responses (e.g., `{"type": "json_schema", "schema": {...}}`). See [Structured outputs](</docs/en/agent-sdk/structured-outputs>) for details
+`permission_prompt_tool_name`| `str | None`| `None`| MCP tool name for permission prompts
+`cwd`| `str | Path | None`| `None`| Current working directory
+`cli_path`| `str | Path | None`| `None`| Custom path to the Claude Code CLI executable
+`settings`| `str | None`| `None`| Path to settings file
+`add_dirs`| `list[str | Path]`| `[]`| Additional directories Claude can access
+`env`| `dict[str, str]`| `{}`| Environment variables
+`extra_args`| `dict[str, str | None]`| `{}`| Additional CLI arguments to pass directly to the CLI
+`max_buffer_size`| `int | None`| `None`| Maximum bytes when buffering CLI stdout
+`debug_stderr`| `Any`| `sys.stderr`| _Deprecated_ \- File-like object for debug output. Use `stderr` callback instead
+`stderr`| `Callable[[str], None] | None`| `None`| Callback function for stderr output from CLI
+`can_use_tool`| `CanUseTool` ` | None`| `None`| Tool permission callback function. See Permission types for details
+`hooks`| `dict[HookEvent, list[HookMatcher]] | None`| `None`| Hook configurations for intercepting events
+`user`| `str | None`| `None`| User identifier
+`include_partial_messages`| `bool`| `False`| Include partial message streaming events. When enabled, `StreamEvent` messages are yielded
+`fork_session`| `bool`| `False`| When resuming with `resume`, fork to a new session ID instead of continuing the original session
+`agents`| `dict[str, AgentDefinition] | None`| `None`| Programmatically defined subagents
+`plugins`| `list[SdkPluginConfig]`| `[]`| Load custom plugins from local paths. See [Plugins](</docs/en/agent-sdk/plugins>) for details
+`sandbox`| `SandboxSettings` ` | None`| `None`| Configure sandbox behavior programmatically. See Sandbox settings for details
+`setting_sources`| `list[SettingSource] | None`| `None` (no settings)| Control which filesystem settings to load. When omitted, no settings are loaded. **Note:** Must include `"project"` to load CLAUDE.md files
+`max_thinking_tokens`| `int | None`| `None`| _Deprecated_ \- Maximum tokens for thinking blocks. Use `thinking` instead
+`thinking`| `ThinkingConfig` ` | None`| `None`| Controls extended thinking behavior. Takes precedence over `max_thinking_tokens`
+`effort`| `Literal["low", "medium", "high", "max"] | None`| `None`| Effort level for thinking depth
+
+###
+
+
+
+`OutputFormat`
+
+Configuration for structured output validation. Pass this as a `dict` to the `output_format` field on `ClaudeAgentOptions`:
+
+ # Expected dict shape for output_format
+ {
+ "type": "json_schema",
+ "schema": {...}, # Your JSON Schema definition
+ }
+
+Field| Required| Description
+---|---|---
+`type`| Yes| Must be `"json_schema"` for JSON Schema validation
+`schema`| Yes| JSON Schema definition for output validation
+
+###
+
+
+
+`SystemPromptPreset`
+
+Configuration for using Claude Code’s preset system prompt with optional additions.
+
+ class SystemPromptPreset(TypedDict):
+ type: Literal["preset"]
+ preset: Literal["claude_code"]
+ append: NotRequired[str]
+
+Field| Required| Description
+---|---|---
+`type`| Yes| Must be `"preset"` to use a preset system prompt
+`preset`| Yes| Must be `"claude_code"` to use Claude Code’s system prompt
+`append`| No| Additional instructions to append to the preset system prompt
+
+###
+
+
+
+`SettingSource`
+
+Controls which filesystem-based configuration sources the SDK loads settings from.
+
+ SettingSource = Literal["user", "project", "local"]
+
+Value| Description| Location
+---|---|---
+`"user"`| Global user settings| `~/.claude/settings.json`
+`"project"`| Shared project settings (version controlled)| `.claude/settings.json`
+`"local"`| Local project settings (gitignored)| `.claude/settings.local.json`
+
+####
+
+
+
+Default behavior
+
+When `setting_sources` is **omitted** or **`None`** , the SDK does **not** load any filesystem settings. This provides isolation for SDK applications.
+
+####
+
+
+
+Why use setting_sources
+
+**Load all filesystem settings (legacy behavior):**
+
+ # Load all settings like SDK v0.0.x did
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async for message in query(
+ prompt="Analyze this code",
+ options=ClaudeAgentOptions(
+ setting_sources=["user", "project", "local"] # Load all settings
+ ),
+ ):
+ print(message)
+
+**Load only specific setting sources:**
+
+ # Load only project settings, ignore user and local
+ async for message in query(
+ prompt="Run CI checks",
+ options=ClaudeAgentOptions(
+ setting_sources=["project"] # Only .claude/settings.json
+ ),
+ ):
+ print(message)
+
+**Testing and CI environments:**
+
+ # Ensure consistent behavior in CI by excluding local settings
+ async for message in query(
+ prompt="Run tests",
+ options=ClaudeAgentOptions(
+ setting_sources=["project"], # Only team-shared settings
+ permission_mode="bypassPermissions",
+ ),
+ ):
+ print(message)
+
+**SDK-only applications:**
+
+ # Define everything programmatically (default behavior)
+ # No filesystem dependencies - setting_sources defaults to None
+ async for message in query(
+ prompt="Review this PR",
+ options=ClaudeAgentOptions(
+ # setting_sources=None is the default, no need to specify
+ agents={...},
+ mcp_servers={...},
+ allowed_tools=["Read", "Grep", "Glob"],
+ ),
+ ):
+ print(message)
+
+**Loading CLAUDE.md project instructions:**
+
+ # Load project settings to include CLAUDE.md files
+ async for message in query(
+ prompt="Add a new feature following project conventions",
+ options=ClaudeAgentOptions(
+ system_prompt={
+ "type": "preset",
+ "preset": "claude_code", # Use Claude Code's system prompt
+ },
+ setting_sources=["project"], # Required to load CLAUDE.md from project
+ allowed_tools=["Read", "Write", "Edit"],
+ ),
+ ):
+ print(message)
+
+####
+
+
+
+Settings precedence
+
+When multiple sources are loaded, settings are merged with this precedence (highest to lowest):
+
+ 1. Local settings (`.claude/settings.local.json`)
+ 2. Project settings (`.claude/settings.json`)
+ 3. User settings (`~/.claude/settings.json`)
+
+Programmatic options (like `agents`, `allowed_tools`) always override filesystem settings.
+
+###
+
+
+
+`AgentDefinition`
+
+Configuration for a subagent defined programmatically.
+
+ @dataclass
+ class AgentDefinition:
+ description: str
+ prompt: str
+ tools: list[str] | None = None
+ model: Literal["sonnet", "opus", "haiku", "inherit"] | None = None
+ skills: list[str] | None = None
+ memory: Literal["user", "project", "local"] | None = None
+ mcpServers: list[str | dict[str, Any]] | None = None
+
+Field| Required| Description
+---|---|---
+`description`| Yes| Natural language description of when to use this agent
+`prompt`| Yes| The agent’s system prompt
+`tools`| No| Array of allowed tool names. If omitted, inherits all tools
+`model`| No| Model override for this agent. If omitted, uses the main model
+`skills`| No| List of skill names available to this agent
+`memory`| No| Memory source for this agent: `"user"`, `"project"`, or `"local"`
+`mcpServers`| No| MCP servers available to this agent. Each entry is a server name or an inline `{name: config}` dict
+
+###
+
+
+
+`PermissionMode`
+
+Permission modes for controlling tool execution.
+
+ PermissionMode = Literal[
+ "default", # Standard permission behavior
+ "acceptEdits", # Auto-accept file edits
+ "plan", # Planning mode - no execution
+ "dontAsk", # Deny anything not pre-approved instead of prompting
+ "bypassPermissions", # Bypass all permission checks (use with caution)
+ ]
+
+###
+
+
+
+`CanUseTool`
+
+Type alias for tool permission callback functions.
+
+ CanUseTool = Callable[
+ [str, dict[str, Any], ToolPermissionContext], Awaitable[PermissionResult]
+ ]
+
+The callback receives:
+
+ * `tool_name`: Name of the tool being called
+ * `input_data`: The tool’s input parameters
+ * `context`: A `ToolPermissionContext` with additional information
+
+Returns a `PermissionResult` (either `PermissionResultAllow` or `PermissionResultDeny`).
+
+###
+
+
+
+`ToolPermissionContext`
+
+Context information passed to tool permission callbacks.
+
+ @dataclass
+ class ToolPermissionContext:
+ signal: Any | None = None # Future: abort signal support
+ suggestions: list[PermissionUpdate] = field(default_factory=list)
+
+Field| Type| Description
+---|---|---
+`signal`| `Any | None`| Reserved for future abort signal support
+`suggestions`| `list[PermissionUpdate]`| Permission update suggestions from the CLI
+
+###
+
+
+
+`PermissionResult`
+
+Union type for permission callback results.
+
+ PermissionResult = PermissionResultAllow | PermissionResultDeny
+
+###
+
+
+
+`PermissionResultAllow`
+
+Result indicating the tool call should be allowed.
+
+ @dataclass
+ class PermissionResultAllow:
+ behavior: Literal["allow"] = "allow"
+ updated_input: dict[str, Any] | None = None
+ updated_permissions: list[PermissionUpdate] | None = None
+
+Field| Type| Default| Description
+---|---|---|---
+`behavior`| `Literal["allow"]`| `"allow"`| Must be “allow”
+`updated_input`| `dict[str, Any] | None`| `None`| Modified input to use instead of original
+`updated_permissions`| `list[PermissionUpdate] | None`| `None`| Permission updates to apply
+
+###
+
+
+
+`PermissionResultDeny`
+
+Result indicating the tool call should be denied.
+
+ @dataclass
+ class PermissionResultDeny:
+ behavior: Literal["deny"] = "deny"
+ message: str = ""
+ interrupt: bool = False
+
+Field| Type| Default| Description
+---|---|---|---
+`behavior`| `Literal["deny"]`| `"deny"`| Must be “deny”
+`message`| `str`| `""`| Message explaining why the tool was denied
+`interrupt`| `bool`| `False`| Whether to interrupt the current execution
+
+###
+
+
+
+`PermissionUpdate`
+
+Configuration for updating permissions programmatically.
+
+ @dataclass
+ class PermissionUpdate:
+ type: Literal[
+ "addRules",
+ "replaceRules",
+ "removeRules",
+ "setMode",
+ "addDirectories",
+ "removeDirectories",
+ ]
+ rules: list[PermissionRuleValue] | None = None
+ behavior: Literal["allow", "deny", "ask"] | None = None
+ mode: PermissionMode | None = None
+ directories: list[str] | None = None
+ destination: (
+ Literal["userSettings", "projectSettings", "localSettings", "session"] | None
+ ) = None
+
+Field| Type| Description
+---|---|---
+`type`| `Literal[...]`| The type of permission update operation
+`rules`| `list[PermissionRuleValue] | None`| Rules for add/replace/remove operations
+`behavior`| `Literal["allow", "deny", "ask"] | None`| Behavior for rule-based operations
+`mode`| `PermissionMode | None`| Mode for setMode operation
+`directories`| `list[str] | None`| Directories for add/remove directory operations
+`destination`| `Literal[...] | None`| Where to apply the permission update
+
+###
+
+
+
+`PermissionRuleValue`
+
+A rule to add, replace, or remove in a permission update.
+
+ @dataclass
+ class PermissionRuleValue:
+ tool_name: str
+ rule_content: str | None = None
+
+###
+
+
+
+`ToolsPreset`
+
+Preset tools configuration for using Claude Code’s default tool set.
+
+ class ToolsPreset(TypedDict):
+ type: Literal["preset"]
+ preset: Literal["claude_code"]
+
+###
+
+
+
+`ThinkingConfig`
+
+Controls extended thinking behavior. A union of three configurations:
+
+ class ThinkingConfigAdaptive(TypedDict):
+ type: Literal["adaptive"]
+
+ class ThinkingConfigEnabled(TypedDict):
+ type: Literal["enabled"]
+ budget_tokens: int
+
+ class ThinkingConfigDisabled(TypedDict):
+ type: Literal["disabled"]
+
+ ThinkingConfig = ThinkingConfigAdaptive | ThinkingConfigEnabled | ThinkingConfigDisabled
+
+Variant| Fields| Description
+---|---|---
+`adaptive`| `type`| Claude adaptively decides when to think
+`enabled`| `type`, `budget_tokens`| Enable thinking with a specific token budget
+`disabled`| `type`| Disable thinking
+
+Because these are `TypedDict` classes, they’re plain dicts at runtime. Either construct them as dict literals or call the class like a constructor; both produce a `dict`. Access fields with `config["budget_tokens"]`, not `config.budget_tokens`:
+
+ from claude_agent_sdk import ClaudeAgentOptions, ThinkingConfigEnabled
+
+ # Option 1: dict literal (recommended, no import needed)
+ options = ClaudeAgentOptions(thinking={"type": "enabled", "budget_tokens": 20000})
+
+ # Option 2: constructor-style (returns a plain dict)
+ config = ThinkingConfigEnabled(type="enabled", budget_tokens=20000)
+ print(config["budget_tokens"]) # 20000
+ # config.budget_tokens would raise AttributeError
+
+###
+
+
+
+`SdkBeta`
+
+Literal type for SDK beta features.
+
+ SdkBeta = Literal["context-1m-2025-08-07"]
+
+Use with the `betas` field in `ClaudeAgentOptions` to enable beta features.
+
+The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this header with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Sonnet 4.6 or Claude Opus 4.6](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
+
+###
+
+
+
+`McpSdkServerConfig`
+
+Configuration for SDK MCP servers created with `create_sdk_mcp_server()`.
+
+ class McpSdkServerConfig(TypedDict):
+ type: Literal["sdk"]
+ name: str
+ instance: Any # MCP Server instance
+
+###
+
+
+
+`McpServerConfig`
+
+Union type for MCP server configurations.
+
+ McpServerConfig = (
+ McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig
+ )
+
+####
+
+
+
+`McpStdioServerConfig`
+
+ class McpStdioServerConfig(TypedDict):
+ type: NotRequired[Literal["stdio"]] # Optional for backwards compatibility
+ command: str
+ args: NotRequired[list[str]]
+ env: NotRequired[dict[str, str]]
+
+####
+
+
+
+`McpSSEServerConfig`
+
+ class McpSSEServerConfig(TypedDict):
+ type: Literal["sse"]
+ url: str
+ headers: NotRequired[dict[str, str]]
+
+####
+
+
+
+`McpHttpServerConfig`
+
+ class McpHttpServerConfig(TypedDict):
+ type: Literal["http"]
+ url: str
+ headers: NotRequired[dict[str, str]]
+
+###
+
+
+
+`McpServerStatusConfig`
+
+The configuration of an MCP server as reported by `get_mcp_status()`. This is the union of all `McpServerConfig` transport variants plus an output-only `claudeai-proxy` variant for servers proxied through claude.ai.
+
+ McpServerStatusConfig = (
+ McpStdioServerConfig
+ | McpSSEServerConfig
+ | McpHttpServerConfig
+ | McpSdkServerConfigStatus
+ | McpClaudeAIProxyServerConfig
+ )
+
+`McpSdkServerConfigStatus` is the serializable form of `McpSdkServerConfig` with only `type` (`"sdk"`) and `name` (`str`) fields; the in-process `instance` is omitted. `McpClaudeAIProxyServerConfig` has `type` (`"claudeai-proxy"`), `url` (`str`), and `id` (`str`) fields.
+
+###
+
+
+
+`McpStatusResponse`
+
+Response from `ClaudeSDKClient.get_mcp_status()`. Wraps the list of server statuses under the `mcpServers` key.
+
+ class McpStatusResponse(TypedDict):
+ mcpServers: list[McpServerStatus]
+
+###
+
+
+
+`McpServerStatus`
+
+Status of a connected MCP server, contained in `McpStatusResponse`.
+
+ class McpServerStatus(TypedDict):
+ name: str
+ status: McpServerConnectionStatus # "connected" | "failed" | "needs-auth" | "pending" | "disabled"
+ serverInfo: NotRequired[McpServerInfo]
+ error: NotRequired[str]
+ config: NotRequired[McpServerStatusConfig]
+ scope: NotRequired[str]
+ tools: NotRequired[list[McpToolInfo]]
+
+Field| Type| Description
+---|---|---
+`name`| `str`| Server name
+`status`| `str`| One of `"connected"`, `"failed"`, `"needs-auth"`, `"pending"`, or `"disabled"`
+`serverInfo`| `dict` (optional)| Server name and version (`{"name": str, "version": str}`)
+`error`| `str` (optional)| Error message if the server failed to connect
+`config`| `McpServerStatusConfig` (optional)| Server configuration. Same shape as `McpServerConfig` (stdio, SSE, HTTP, or SDK), plus a `claudeai-proxy` variant for servers connected through claude.ai
+`scope`| `str` (optional)| Configuration scope
+`tools`| `list` (optional)| Tools provided by this server, each with `name`, `description`, and `annotations` fields
+
+###
+
+
+
+`SdkPluginConfig`
+
+Configuration for loading plugins in the SDK.
+
+ class SdkPluginConfig(TypedDict):
+ type: Literal["local"]
+ path: str
+
+Field| Type| Description
+---|---|---
+`type`| `Literal["local"]`| Must be `"local"` (only local plugins currently supported)
+`path`| `str`| Absolute or relative path to the plugin directory
+
+**Example:**
+
+ plugins = [
+ {"type": "local", "path": "./my-plugin"},
+ {"type": "local", "path": "/absolute/path/to/plugin"},
+ ]
+
+For complete information on creating and using plugins, see [Plugins](</docs/en/agent-sdk/plugins>).
+
+##
+
+
+
+Message Types
+
+###
+
+
+
+`Message`
+
+Union type of all possible messages.
+
+ Message = (
+ UserMessage
+ | AssistantMessage
+ | SystemMessage
+ | ResultMessage
+ | StreamEvent
+ | RateLimitEvent
+ )
+
+###
+
+
+
+`UserMessage`
+
+User input message.
+
+ @dataclass
+ class UserMessage:
+ content: str | list[ContentBlock]
+ uuid: str | None = None
+ parent_tool_use_id: str | None = None
+ tool_use_result: dict[str, Any] | None = None
+
+Field| Type| Description
+---|---|---
+`content`| `str | list[ContentBlock]`| Message content as text or content blocks
+`uuid`| `str | None`| Unique message identifier
+`parent_tool_use_id`| `str | None`| Tool use ID if this message is a tool result response
+`tool_use_result`| `dict[str, Any] | None`| Tool result data if applicable
+
+###
+
+
+
+`AssistantMessage`
+
+Assistant response message with content blocks.
+
+ @dataclass
+ class AssistantMessage:
+ content: list[ContentBlock]
+ model: str
+ parent_tool_use_id: str | None = None
+ error: AssistantMessageError | None = None
+ usage: dict[str, Any] | None = None
+ message_id: str | None = None
+
+Field| Type| Description
+---|---|---
+`content`| `list[ContentBlock]`| List of content blocks in the response
+`model`| `str`| Model that generated the response
+`parent_tool_use_id`| `str | None`| Tool use ID if this is a nested response
+`error`| `AssistantMessageError` ` | None`| Error type if the response encountered an error
+`usage`| `dict[str, Any] | None`| Per-message token usage (same keys as `ResultMessage.usage`)
+`message_id`| `str | None`| API message ID. Multiple messages from one turn share the same ID
+
+###
+
+
+
+`AssistantMessageError`
+
+Possible error types for assistant messages.
+
+ AssistantMessageError = Literal[
+ "authentication_failed",
+ "billing_error",
+ "rate_limit",
+ "invalid_request",
+ "server_error",
+ "max_output_tokens",
+ "unknown",
+ ]
+
+###
+
+
+
+`SystemMessage`
+
+System message with metadata.
+
+ @dataclass
+ class SystemMessage:
+ subtype: str
+ data: dict[str, Any]
+
+###
+
+
+
+`ResultMessage`
+
+Final result message with cost and usage information.
+
+ @dataclass
+ class ResultMessage:
+ subtype: str
+ duration_ms: int
+ duration_api_ms: int
+ is_error: bool
+ num_turns: int
+ session_id: str
+ total_cost_usd: float | None = None
+ usage: dict[str, Any] | None = None
+ result: str | None = None
+ stop_reason: str | None = None
+ structured_output: Any = None
+ model_usage: dict[str, Any] | None = None
+
+The `usage` dict contains the following keys when present:
+
+Key| Type| Description
+---|---|---
+`input_tokens`| `int`| Total input tokens consumed.
+`output_tokens`| `int`| Total output tokens generated.
+`cache_creation_input_tokens`| `int`| Tokens used to create new cache entries.
+`cache_read_input_tokens`| `int`| Tokens read from existing cache entries.
+
+The `model_usage` dict maps model names to per-model usage. The inner dict keys use camelCase because the value is passed through unmodified from the underlying CLI process, matching the TypeScript [`ModelUsage`](</docs/en/agent-sdk/typescript#model-usage>) type:
+
+Key| Type| Description
+---|---|---
+`inputTokens`| `int`| Input tokens for this model.
+`outputTokens`| `int`| Output tokens for this model.
+`cacheReadInputTokens`| `int`| Cache read tokens for this model.
+`cacheCreationInputTokens`| `int`| Cache creation tokens for this model.
+`webSearchRequests`| `int`| Web search requests made by this model.
+`costUSD`| `float`| Cost in USD for this model.
+`contextWindow`| `int`| Context window size for this model.
+`maxOutputTokens`| `int`| Maximum output token limit for this model.
+
+###
+
+
+
+`StreamEvent`
+
+Stream event for partial message updates during streaming. Only received when `include_partial_messages=True` in `ClaudeAgentOptions`. Import via `from claude_agent_sdk.types import StreamEvent`.
+
+ @dataclass
+ class StreamEvent:
+ uuid: str
+ session_id: str
+ event: dict[str, Any] # The raw Claude API stream event
+ parent_tool_use_id: str | None = None
+
+Field| Type| Description
+---|---|---
+`uuid`| `str`| Unique identifier for this event
+`session_id`| `str`| Session identifier
+`event`| `dict[str, Any]`| The raw Claude API stream event data
+`parent_tool_use_id`| `str | None`| Parent tool use ID if this event is from a subagent
+
+###
+
+
+
+`RateLimitEvent`
+
+Emitted when rate limit status changes (for example, from `"allowed"` to `"allowed_warning"`). Use this to warn users before they hit a hard limit, or to back off when status is `"rejected"`.
+
+ @dataclass
+ class RateLimitEvent:
+ rate_limit_info: RateLimitInfo
+ uuid: str
+ session_id: str
+
+Field| Type| Description
+---|---|---
+`rate_limit_info`| `RateLimitInfo`| Current rate limit state
+`uuid`| `str`| Unique event identifier
+`session_id`| `str`| Session identifier
+
+###
+
+
+
+`RateLimitInfo`
+
+Rate limit state carried by `RateLimitEvent`.
+
+ RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]
+ RateLimitType = Literal[
+ "five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet", "overage"
+ ]
+
+ @dataclass
+ class RateLimitInfo:
+ status: RateLimitStatus
+ resets_at: int | None = None
+ rate_limit_type: RateLimitType | None = None
+ utilization: float | None = None
+ overage_status: RateLimitStatus | None = None
+ overage_resets_at: int | None = None
+ overage_disabled_reason: str | None = None
+ raw: dict[str, Any] = field(default_factory=dict)
+
+Field| Type| Description
+---|---|---
+`status`| `RateLimitStatus`| Current status. `"allowed_warning"` means approaching the limit; `"rejected"` means the limit was hit
+`resets_at`| `int | None`| Unix timestamp when the rate limit window resets
+`rate_limit_type`| `RateLimitType | None`| Which rate limit window applies
+`utilization`| `float | None`| Fraction of the rate limit consumed (0.0 to 1.0)
+`overage_status`| `RateLimitStatus | None`| Status of pay-as-you-go overage usage, if applicable
+`overage_resets_at`| `int | None`| Unix timestamp when the overage window resets
+`overage_disabled_reason`| `str | None`| Why overage is unavailable, if status is `"rejected"`
+`raw`| `dict[str, Any]`| Full raw dict from the CLI, including fields not modeled above
+
+###
+
+
+
+`TaskStartedMessage`
+
+Emitted when a background task starts. A background task is anything tracked outside the main turn: a backgrounded Bash command, a subagent spawned via the Agent tool, or a remote agent. The `task_type` field tells you which. This naming is unrelated to the `Task`-to-`Agent` tool rename.
+
+ @dataclass
+ class TaskStartedMessage(SystemMessage):
+ task_id: str
+ description: str
+ uuid: str
+ session_id: str
+ tool_use_id: str | None = None
+ task_type: str | None = None
+
+Field| Type| Description
+---|---|---
+`task_id`| `str`| Unique identifier for the task
+`description`| `str`| Description of the task
+`uuid`| `str`| Unique message identifier
+`session_id`| `str`| Session identifier
+`tool_use_id`| `str | None`| Associated tool use ID
+`task_type`| `str | None`| Which kind of background task: `"local_bash"`, `"local_agent"`, `"remote_agent"`
+
+###
+
+
+
+`TaskUsage`
+
+Token and timing data for a background task.
+
+ class TaskUsage(TypedDict):
+ total_tokens: int
+ tool_uses: int
+ duration_ms: int
+
+###
+
+
+
+`TaskProgressMessage`
+
+Emitted periodically with progress updates for a running background task.
+
+ @dataclass
+ class TaskProgressMessage(SystemMessage):
+ task_id: str
+ description: str
+ usage: TaskUsage
+ uuid: str
+ session_id: str
+ tool_use_id: str | None = None
+ last_tool_name: str | None = None
+
+Field| Type| Description
+---|---|---
+`task_id`| `str`| Unique identifier for the task
+`description`| `str`| Current status description
+`usage`| `TaskUsage`| Token usage for this task so far
+`uuid`| `str`| Unique message identifier
+`session_id`| `str`| Session identifier
+`tool_use_id`| `str | None`| Associated tool use ID
+`last_tool_name`| `str | None`| Name of the last tool the task used
+
+###
+
+
+
+`TaskNotificationMessage`
+
+Emitted when a task completes, fails, or is stopped.
+
+ @dataclass
+ class TaskNotificationMessage(SystemMessage):
+ task_id: str
+ status: TaskNotificationStatus # "completed" | "failed" | "stopped"
+ output_file: str
+ summary: str
+ uuid: str
+ session_id: str
+ tool_use_id: str | None = None
+ usage: TaskUsage | None = None
+
+Field| Type| Description
+---|---|---
+`task_id`| `str`| Unique identifier for the task
+`status`| `TaskNotificationStatus`| One of `"completed"`, `"failed"`, or `"stopped"`
+`output_file`| `str`| Path to the task output file
+`summary`| `str`| Summary of the task result
+`uuid`| `str`| Unique message identifier
+`session_id`| `str`| Session identifier
+`tool_use_id`| `str | None`| Associated tool use ID
+`usage`| `TaskUsage | None`| Final token usage for the task
+
+##
+
+
+
+Content Block Types
+
+###
+
+
+
+`ContentBlock`
+
+Union type of all content blocks.
+
+ ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
+
+###
+
+
+
+`TextBlock`
+
+Text content block.
+
+ @dataclass
+ class TextBlock:
+ text: str
+
+###
+
+
+
+`ThinkingBlock`
+
+Thinking content block (for models with thinking capability).
+
+ @dataclass
+ class ThinkingBlock:
+ thinking: str
+ signature: str
+
+###
+
+
+
+`ToolUseBlock`
+
+Tool use request block.
+
+ @dataclass
+ class ToolUseBlock:
+ id: str
+ name: str
+ input: dict[str, Any]
+
+###
+
+
+
+`ToolResultBlock`
+
+Tool execution result block.
+
+ @dataclass
+ class ToolResultBlock:
+ tool_use_id: str
+ content: str | list[dict[str, Any]] | None = None
+ is_error: bool | None = None
+
+##
+
+
+
+Error Types
+
+###
+
+
+
+`ClaudeSDKError`
+
+Base exception class for all SDK errors.
+
+ class ClaudeSDKError(Exception):
+ """Base error for Claude SDK."""
+
+###
+
+
+
+`CLINotFoundError`
+
+Raised when Claude Code CLI is not installed or not found.
+
+ class CLINotFoundError(CLIConnectionError):
+ def __init__(
+ self, message: str = "Claude Code not found", cli_path: str | None = None
+ ):
+ """
+ Args:
+ message: Error message (default: "Claude Code not found")
+ cli_path: Optional path to the CLI that was not found
+ """
+
+###
+
+
+
+`CLIConnectionError`
+
+Raised when connection to Claude Code fails.
+
+ class CLIConnectionError(ClaudeSDKError):
+ """Failed to connect to Claude Code."""
+
+###
+
+
+
+`ProcessError`
+
+Raised when the Claude Code process fails.
+
+ class ProcessError(ClaudeSDKError):
+ def __init__(
+ self, message: str, exit_code: int | None = None, stderr: str | None = None
+ ):
+ self.exit_code = exit_code
+ self.stderr = stderr
+
+###
+
+
+
+`CLIJSONDecodeError`
+
+Raised when JSON parsing fails.
+
+ class CLIJSONDecodeError(ClaudeSDKError):
+ def __init__(self, line: str, original_error: Exception):
+ """
+ Args:
+ line: The line that failed to parse
+ original_error: The original JSON decode exception
+ """
+ self.line = line
+ self.original_error = original_error
+
+##
+
+
+
+Hook Types
+
+For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](</docs/en/agent-sdk/hooks>).
+
+###
+
+
+
+`HookEvent`
+
+Supported hook event types.
+
+ HookEvent = Literal[
+ "PreToolUse", # Called before tool execution
+ "PostToolUse", # Called after tool execution
+ "PostToolUseFailure", # Called when a tool execution fails
+ "UserPromptSubmit", # Called when user submits a prompt
+ "Stop", # Called when stopping execution
+ "SubagentStop", # Called when a subagent stops
+ "PreCompact", # Called before message compaction
+ "Notification", # Called for notification events
+ "SubagentStart", # Called when a subagent starts
+ "PermissionRequest", # Called when a permission decision is needed
+ ]
+
+The TypeScript SDK supports additional hook events not yet available in Python: `SessionStart`, `SessionEnd`, `Setup`, `TeammateIdle`, `TaskCompleted`, `ConfigChange`, `WorktreeCreate`, and `WorktreeRemove`.
+
+###
+
+
+
+`HookCallback`
+
+Type definition for hook callback functions.
+
+ HookCallback = Callable[[HookInput, str | None, HookContext], Awaitable[HookJSONOutput]]
+
+Parameters:
+
+ * `input`: Strongly-typed hook input with discriminated unions based on `hook_event_name` (see `HookInput`)
+ * `tool_use_id`: Optional tool use identifier (for tool-related hooks)
+ * `context`: Hook context with additional information
+
+Returns a `HookJSONOutput` that may contain:
+
+ * `decision`: `"block"` to block the action
+ * `systemMessage`: System message to add to the transcript
+ * `hookSpecificOutput`: Hook-specific output data
+
+###
+
+
+
+`HookContext`
+
+Context information passed to hook callbacks.
+
+ class HookContext(TypedDict):
+ signal: Any | None # Future: abort signal support
+
+###
+
+
+
+`HookMatcher`
+
+Configuration for matching hooks to specific events or tools.
+
+ @dataclass
+ class HookMatcher:
+ matcher: str | None = (
+ None # Tool name or pattern to match (e.g., "Bash", "Write|Edit")
+ )
+ hooks: list[HookCallback] = field(
+ default_factory=list
+ ) # List of callbacks to execute
+ timeout: float | None = (
+ None # Timeout in seconds for all hooks in this matcher (default: 60)
+ )
+
+###
+
+
+
+`HookInput`
+
+Union type of all hook input types. The actual type depends on the `hook_event_name` field.
+
+ HookInput = (
+ PreToolUseHookInput
+ | PostToolUseHookInput
+ | PostToolUseFailureHookInput
+ | UserPromptSubmitHookInput
+ | StopHookInput
+ | SubagentStopHookInput
+ | PreCompactHookInput
+ | NotificationHookInput
+ | SubagentStartHookInput
+ | PermissionRequestHookInput
+ )
+
+###
+
+
+
+`BaseHookInput`
+
+Base fields present in all hook input types.
+
+ class BaseHookInput(TypedDict):
+ session_id: str
+ transcript_path: str
+ cwd: str
+ permission_mode: NotRequired[str]
+
+Field| Type| Description
+---|---|---
+`session_id`| `str`| Current session identifier
+`transcript_path`| `str`| Path to the session transcript file
+`cwd`| `str`| Current working directory
+`permission_mode`| `str` (optional)| Current permission mode
+
+###
+
+
+
+`PreToolUseHookInput`
+
+Input data for `PreToolUse` hook events.
+
+ class PreToolUseHookInput(BaseHookInput):
+ hook_event_name: Literal["PreToolUse"]
+ tool_name: str
+ tool_input: dict[str, Any]
+ tool_use_id: str
+ agent_id: NotRequired[str]
+ agent_type: NotRequired[str]
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["PreToolUse"]`| Always “PreToolUse”
+`tool_name`| `str`| Name of the tool about to be executed
+`tool_input`| `dict[str, Any]`| Input parameters for the tool
+`tool_use_id`| `str`| Unique identifier for this tool use
+`agent_id`| `str` (optional)| Subagent identifier, present when the hook fires inside a subagent
+`agent_type`| `str` (optional)| Subagent type, present when the hook fires inside a subagent
+
+###
+
+
+
+`PostToolUseHookInput`
+
+Input data for `PostToolUse` hook events.
+
+ class PostToolUseHookInput(BaseHookInput):
+ hook_event_name: Literal["PostToolUse"]
+ tool_name: str
+ tool_input: dict[str, Any]
+ tool_response: Any
+ tool_use_id: str
+ agent_id: NotRequired[str]
+ agent_type: NotRequired[str]
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["PostToolUse"]`| Always “PostToolUse”
+`tool_name`| `str`| Name of the tool that was executed
+`tool_input`| `dict[str, Any]`| Input parameters that were used
+`tool_response`| `Any`| Response from the tool execution
+`tool_use_id`| `str`| Unique identifier for this tool use
+`agent_id`| `str` (optional)| Subagent identifier, present when the hook fires inside a subagent
+`agent_type`| `str` (optional)| Subagent type, present when the hook fires inside a subagent
+
+###
+
+
+
+`PostToolUseFailureHookInput`
+
+Input data for `PostToolUseFailure` hook events. Called when a tool execution fails.
+
+ class PostToolUseFailureHookInput(BaseHookInput):
+ hook_event_name: Literal["PostToolUseFailure"]
+ tool_name: str
+ tool_input: dict[str, Any]
+ tool_use_id: str
+ error: str
+ is_interrupt: NotRequired[bool]
+ agent_id: NotRequired[str]
+ agent_type: NotRequired[str]
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["PostToolUseFailure"]`| Always “PostToolUseFailure”
+`tool_name`| `str`| Name of the tool that failed
+`tool_input`| `dict[str, Any]`| Input parameters that were used
+`tool_use_id`| `str`| Unique identifier for this tool use
+`error`| `str`| Error message from the failed execution
+`is_interrupt`| `bool` (optional)| Whether the failure was caused by an interrupt
+`agent_id`| `str` (optional)| Subagent identifier, present when the hook fires inside a subagent
+`agent_type`| `str` (optional)| Subagent type, present when the hook fires inside a subagent
+
+###
+
+
+
+`UserPromptSubmitHookInput`
+
+Input data for `UserPromptSubmit` hook events.
+
+ class UserPromptSubmitHookInput(BaseHookInput):
+ hook_event_name: Literal["UserPromptSubmit"]
+ prompt: str
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["UserPromptSubmit"]`| Always “UserPromptSubmit”
+`prompt`| `str`| The user’s submitted prompt
+
+###
+
+
+
+`StopHookInput`
+
+Input data for `Stop` hook events.
+
+ class StopHookInput(BaseHookInput):
+ hook_event_name: Literal["Stop"]
+ stop_hook_active: bool
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["Stop"]`| Always “Stop”
+`stop_hook_active`| `bool`| Whether the stop hook is active
+
+###
+
+
+
+`SubagentStopHookInput`
+
+Input data for `SubagentStop` hook events.
+
+ class SubagentStopHookInput(BaseHookInput):
+ hook_event_name: Literal["SubagentStop"]
+ stop_hook_active: bool
+ agent_id: str
+ agent_transcript_path: str
+ agent_type: str
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["SubagentStop"]`| Always “SubagentStop”
+`stop_hook_active`| `bool`| Whether the stop hook is active
+`agent_id`| `str`| Unique identifier for the subagent
+`agent_transcript_path`| `str`| Path to the subagent’s transcript file
+`agent_type`| `str`| Type of the subagent
+
+###
+
+
+
+`PreCompactHookInput`
+
+Input data for `PreCompact` hook events.
+
+ class PreCompactHookInput(BaseHookInput):
+ hook_event_name: Literal["PreCompact"]
+ trigger: Literal["manual", "auto"]
+ custom_instructions: str | None
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["PreCompact"]`| Always “PreCompact”
+`trigger`| `Literal["manual", "auto"]`| What triggered the compaction
+`custom_instructions`| `str | None`| Custom instructions for compaction
+
+###
+
+
+
+`NotificationHookInput`
+
+Input data for `Notification` hook events.
+
+ class NotificationHookInput(BaseHookInput):
+ hook_event_name: Literal["Notification"]
+ message: str
+ title: NotRequired[str]
+ notification_type: str
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["Notification"]`| Always “Notification”
+`message`| `str`| Notification message content
+`title`| `str` (optional)| Notification title
+`notification_type`| `str`| Type of notification
+
+###
+
+
+
+`SubagentStartHookInput`
+
+Input data for `SubagentStart` hook events.
+
+ class SubagentStartHookInput(BaseHookInput):
+ hook_event_name: Literal["SubagentStart"]
+ agent_id: str
+ agent_type: str
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["SubagentStart"]`| Always “SubagentStart”
+`agent_id`| `str`| Unique identifier for the subagent
+`agent_type`| `str`| Type of the subagent
+
+###
+
+
+
+`PermissionRequestHookInput`
+
+Input data for `PermissionRequest` hook events. Allows hooks to handle permission decisions programmatically.
+
+ class PermissionRequestHookInput(BaseHookInput):
+ hook_event_name: Literal["PermissionRequest"]
+ tool_name: str
+ tool_input: dict[str, Any]
+ permission_suggestions: NotRequired[list[Any]]
+
+Field| Type| Description
+---|---|---
+`hook_event_name`| `Literal["PermissionRequest"]`| Always “PermissionRequest”
+`tool_name`| `str`| Name of the tool requesting permission
+`tool_input`| `dict[str, Any]`| Input parameters for the tool
+`permission_suggestions`| `list[Any]` (optional)| Suggested permission updates from the CLI
+
+###
+
+
+
+`HookJSONOutput`
+
+Union type for hook callback return values.
+
+ HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput
+
+####
+
+
+
+`SyncHookJSONOutput`
+
+Synchronous hook output with control and decision fields.
+
+ class SyncHookJSONOutput(TypedDict):
+ # Control fields
+ continue_: NotRequired[bool] # Whether to proceed (default: True)
+ suppressOutput: NotRequired[bool] # Hide stdout from transcript
+ stopReason: NotRequired[str] # Message when continue is False
+
+ # Decision fields
+ decision: NotRequired[Literal["block"]]
+ systemMessage: NotRequired[str] # Warning message for user
+ reason: NotRequired[str] # Feedback for Claude
+
+ # Hook-specific output
+ hookSpecificOutput: NotRequired[HookSpecificOutput]
+
+Use `continue_` (with underscore) in Python code. It is automatically converted to `continue` when sent to the CLI.
+
+####
+
+
+
+`HookSpecificOutput`
+
+A `TypedDict` containing the hook event name and event-specific fields. The shape depends on the `hookEventName` value. For full details on available fields per hook event, see [Control execution with hooks](</docs/en/agent-sdk/hooks#outputs>). A discriminated union of event-specific output types. The `hookEventName` field determines which fields are valid.
+
+ class PreToolUseHookSpecificOutput(TypedDict):
+ hookEventName: Literal["PreToolUse"]
+ permissionDecision: NotRequired[Literal["allow", "deny", "ask"]]
+ permissionDecisionReason: NotRequired[str]
+ updatedInput: NotRequired[dict[str, Any]]
+ additionalContext: NotRequired[str]
+
+ class PostToolUseHookSpecificOutput(TypedDict):
+ hookEventName: Literal["PostToolUse"]
+ additionalContext: NotRequired[str]
+ updatedMCPToolOutput: NotRequired[Any]
+
+ class PostToolUseFailureHookSpecificOutput(TypedDict):
+ hookEventName: Literal["PostToolUseFailure"]
+ additionalContext: NotRequired[str]
+
+ class UserPromptSubmitHookSpecificOutput(TypedDict):
+ hookEventName: Literal["UserPromptSubmit"]
+ additionalContext: NotRequired[str]
+
+ class NotificationHookSpecificOutput(TypedDict):
+ hookEventName: Literal["Notification"]
+ additionalContext: NotRequired[str]
+
+ class SubagentStartHookSpecificOutput(TypedDict):
+ hookEventName: Literal["SubagentStart"]
+ additionalContext: NotRequired[str]
+
+ class PermissionRequestHookSpecificOutput(TypedDict):
+ hookEventName: Literal["PermissionRequest"]
+ decision: dict[str, Any]
+
+ HookSpecificOutput = (
+ PreToolUseHookSpecificOutput
+ | PostToolUseHookSpecificOutput
+ | PostToolUseFailureHookSpecificOutput
+ | UserPromptSubmitHookSpecificOutput
+ | NotificationHookSpecificOutput
+ | SubagentStartHookSpecificOutput
+ | PermissionRequestHookSpecificOutput
+ )
+
+####
+
+
+
+`AsyncHookJSONOutput`
+
+Async hook output that defers hook execution.
+
+ class AsyncHookJSONOutput(TypedDict):
+ async_: Literal[True] # Set to True to defer execution
+ asyncTimeout: NotRequired[int] # Timeout in milliseconds
+
+Use `async_` (with underscore) in Python code. It is automatically converted to `async` when sent to the CLI.
+
+###
+
+
+
+Hook Usage Example
+
+This example registers two hooks: one that blocks dangerous bash commands like `rm -rf /`, and another that logs all tool usage for auditing. The security hook only runs on Bash commands (via the `matcher`), while the logging hook runs on all tools.
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext
+ from typing import Any
+
+ async def validate_bash_command(
+ input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
+ ) -> dict[str, Any]:
+ """Validate and potentially block dangerous bash commands."""
+ if input_data["tool_name"] == "Bash":
+ command = input_data["tool_input"].get("command", "")
+ if "rm -rf /" in command:
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": "Dangerous command blocked",
+ }
+ }
+ return {}
+
+ async def log_tool_use(
+ input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
+ ) -> dict[str, Any]:
+ """Log all tool usage for auditing."""
+ print(f"Tool used: {input_data.get('tool_name')}")
+ return {}
+
+ options = ClaudeAgentOptions(
+ hooks={
+ "PreToolUse": [
+ HookMatcher(
+ matcher="Bash", hooks=[validate_bash_command], timeout=120
+ ), # 2 min for validation
+ HookMatcher(
+ hooks=[log_tool_use]
+ ), # Applies to all tools (default 60s timeout)
+ ],
+ "PostToolUse": [HookMatcher(hooks=[log_tool_use])],
+ }
+ )
+
+ async for message in query(prompt="Analyze this codebase", options=options):
+ print(message)
+
+##
+
+
+
+Tool Input/Output Types
+
+Documentation of input/output schemas for all built-in Claude Code tools. While the Python SDK doesn’t export these as types, they represent the structure of tool inputs and outputs in messages.
+
+###
+
+
+
+Agent
+
+**Tool name:** `Agent` (previously `Task`, which is still accepted as an alias) **Input:**
+
+ {
+ "description": str, # A short (3-5 word) description of the task
+ "prompt": str, # The task for the agent to perform
+ "subagent_type": str, # The type of specialized agent to use
+ }
+
+**Output:**
+
+ {
+ "result": str, # Final result from the subagent
+ "usage": dict | None, # Token usage statistics
+ "total_cost_usd": float | None, # Total cost in USD
+ "duration_ms": int | None, # Execution duration in milliseconds
+ }
+
+###
+
+
+
+AskUserQuestion
+
+**Tool name:** `AskUserQuestion` Asks the user clarifying questions during execution. See [Handle approvals and user input](</docs/en/agent-sdk/user-input#handle-clarifying-questions>) for usage details. **Input:**
+
+ {
+ "questions": [ # Questions to ask the user (1-4 questions)
+ {
+ "question": str, # The complete question to ask the user
+ "header": str, # Very short label displayed as a chip/tag (max 12 chars)
+ "options": [ # The available choices (2-4 options)
+ {
+ "label": str, # Display text for this option (1-5 words)
+ "description": str, # Explanation of what this option means
+ }
+ ],
+ "multiSelect": bool, # Set to true to allow multiple selections
+ }
+ ],
+ "answers": dict | None, # User answers populated by the permission system
+ }
+
+**Output:**
+
+ {
+ "questions": [ # The questions that were asked
+ {
+ "question": str,
+ "header": str,
+ "options": [{"label": str, "description": str}],
+ "multiSelect": bool,
+ }
+ ],
+ "answers": dict[str, str], # Maps question text to answer string
+ # Multi-select answers are comma-separated
+ }
+
+###
+
+
+
+Bash
+
+**Tool name:** `Bash` **Input:**
+
+ {
+ "command": str, # The command to execute
+ "timeout": int | None, # Optional timeout in milliseconds (max 600000)
+ "description": str | None, # Clear, concise description (5-10 words)
+ "run_in_background": bool | None, # Set to true to run in background
+ }
+
+**Output:**
+
+ {
+ "output": str, # Combined stdout and stderr output
+ "exitCode": int, # Exit code of the command
+ "killed": bool | None, # Whether command was killed due to timeout
+ "shellId": str | None, # Shell ID for background processes
+ }
+
+###
+
+
+
+Edit
+
+**Tool name:** `Edit` **Input:**
+
+ {
+ "file_path": str, # The absolute path to the file to modify
+ "old_string": str, # The text to replace
+ "new_string": str, # The text to replace it with
+ "replace_all": bool | None, # Replace all occurrences (default False)
+ }
+
+**Output:**
+
+ {
+ "message": str, # Confirmation message
+ "replacements": int, # Number of replacements made
+ "file_path": str, # File path that was edited
+ }
+
+###
+
+
+
+Read
+
+**Tool name:** `Read` **Input:**
+
+ {
+ "file_path": str, # The absolute path to the file to read
+ "offset": int | None, # The line number to start reading from
+ "limit": int | None, # The number of lines to read
+ }
+
+**Output (Text files):**
+
+ {
+ "content": str, # File contents with line numbers
+ "total_lines": int, # Total number of lines in file
+ "lines_returned": int, # Lines actually returned
+ }
+
+**Output (Images):**
+
+ {
+ "image": str, # Base64 encoded image data
+ "mime_type": str, # Image MIME type
+ "file_size": int, # File size in bytes
+ }
+
+###
+
+
+
+Write
+
+**Tool name:** `Write` **Input:**
+
+ {
+ "file_path": str, # The absolute path to the file to write
+ "content": str, # The content to write to the file
+ }
+
+**Output:**
+
+ {
+ "message": str, # Success message
+ "bytes_written": int, # Number of bytes written
+ "file_path": str, # File path that was written
+ }
+
+###
+
+
+
+Glob
+
+**Tool name:** `Glob` **Input:**
+
+ {
+ "pattern": str, # The glob pattern to match files against
+ "path": str | None, # The directory to search in (defaults to cwd)
+ }
+
+**Output:**
+
+ {
+ "matches": list[str], # Array of matching file paths
+ "count": int, # Number of matches found
+ "search_path": str, # Search directory used
+ }
+
+###
+
+
+
+Grep
+
+**Tool name:** `Grep` **Input:**
+
+ {
+ "pattern": str, # The regular expression pattern
+ "path": str | None, # File or directory to search in
+ "glob": str | None, # Glob pattern to filter files
+ "type": str | None, # File type to search
+ "output_mode": str | None, # "content", "files_with_matches", or "count"
+ "-i": bool | None, # Case insensitive search
+ "-n": bool | None, # Show line numbers
+ "-B": int | None, # Lines to show before each match
+ "-A": int | None, # Lines to show after each match
+ "-C": int | None, # Lines to show before and after
+ "head_limit": int | None, # Limit output to first N lines/entries
+ "multiline": bool | None, # Enable multiline mode
+ }
+
+**Output (content mode):**
+
+ {
+ "matches": [
+ {
+ "file": str,
+ "line_number": int | None,
+ "line": str,
+ "before_context": list[str] | None,
+ "after_context": list[str] | None,
+ }
+ ],
+ "total_matches": int,
+ }
+
+**Output (files_with_matches mode):**
+
+ {
+ "files": list[str], # Files containing matches
+ "count": int, # Number of files with matches
+ }
+
+###
+
+
+
+NotebookEdit
+
+**Tool name:** `NotebookEdit` **Input:**
+
+ {
+ "notebook_path": str, # Absolute path to the Jupyter notebook
+ "cell_id": str | None, # The ID of the cell to edit
+ "new_source": str, # The new source for the cell
+ "cell_type": "code" | "markdown" | None, # The type of the cell
+ "edit_mode": "replace" | "insert" | "delete" | None, # Edit operation type
+ }
+
+**Output:**
+
+ {
+ "message": str, # Success message
+ "edit_type": "replaced" | "inserted" | "deleted", # Type of edit performed
+ "cell_id": str | None, # Cell ID that was affected
+ "total_cells": int, # Total cells in notebook after edit
+ }
+
+###
+
+
+
+WebFetch
+
+**Tool name:** `WebFetch` **Input:**
+
+ {
+ "url": str, # The URL to fetch content from
+ "prompt": str, # The prompt to run on the fetched content
+ }
+
+**Output:**
+
+ {
+ "response": str, # AI model's response to the prompt
+ "url": str, # URL that was fetched
+ "final_url": str | None, # Final URL after redirects
+ "status_code": int | None, # HTTP status code
+ }
+
+###
+
+
+
+WebSearch
+
+**Tool name:** `WebSearch` **Input:**
+
+ {
+ "query": str, # The search query to use
+ "allowed_domains": list[str] | None, # Only include results from these domains
+ "blocked_domains": list[str] | None, # Never include results from these domains
+ }
+
+**Output:**
+
+ {
+ "results": [{"title": str, "url": str, "snippet": str, "metadata": dict | None}],
+ "total_results": int,
+ "query": str,
+ }
+
+###
+
+
+
+TodoWrite
+
+**Tool name:** `TodoWrite` **Input:**
+
+ {
+ "todos": [
+ {
+ "content": str, # The task description
+ "status": "pending" | "in_progress" | "completed", # Task status
+ "activeForm": str, # Active form of the description
+ }
+ ]
+ }
+
+**Output:**
+
+ {
+ "message": str, # Success message
+ "stats": {"total": int, "pending": int, "in_progress": int, "completed": int},
+ }
+
+###
+
+
+
+BashOutput
+
+**Tool name:** `BashOutput` **Input:**
+
+ {
+ "bash_id": str, # The ID of the background shell
+ "filter": str | None, # Optional regex to filter output lines
+ }
+
+**Output:**
+
+ {
+ "output": str, # New output since last check
+ "status": "running" | "completed" | "failed", # Current shell status
+ "exitCode": int | None, # Exit code when completed
+ }
+
+###
+
+
+
+KillBash
+
+**Tool name:** `KillBash` **Input:**
+
+ {
+ "shell_id": str # The ID of the background shell to kill
+ }
+
+**Output:**
+
+ {
+ "message": str, # Success message
+ "shell_id": str, # ID of the killed shell
+ }
+
+###
+
+
+
+ExitPlanMode
+
+**Tool name:** `ExitPlanMode` **Input:**
+
+ {
+ "plan": str # The plan to run by the user for approval
+ }
+
+**Output:**
+
+ {
+ "message": str, # Confirmation message
+ "approved": bool | None, # Whether user approved the plan
+ }
+
+###
+
+
+
+ListMcpResources
+
+**Tool name:** `ListMcpResources` **Input:**
+
+ {
+ "server": str | None # Optional server name to filter resources by
+ }
+
+**Output:**
+
+ {
+ "resources": [
+ {
+ "uri": str,
+ "name": str,
+ "description": str | None,
+ "mimeType": str | None,
+ "server": str,
+ }
+ ],
+ "total": int,
+ }
+
+###
+
+
+
+ReadMcpResource
+
+**Tool name:** `ReadMcpResource` **Input:**
+
+ {
+ "server": str, # The MCP server name
+ "uri": str, # The resource URI to read
+ }
+
+**Output:**
+
+ {
+ "contents": [
+ {"uri": str, "mimeType": str | None, "text": str | None, "blob": str | None}
+ ],
+ "server": str,
+ }
+
+##
+
+
+
+Advanced Features with ClaudeSDKClient
+
+###
+
+
+
+Building a Continuous Conversation Interface
+
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ AssistantMessage,
+ TextBlock,
+ )
+ import asyncio
+
+ class ConversationSession:
+ """Maintains a single conversation session with Claude."""
+
+ def __init__(self, options: ClaudeAgentOptions | None = None):
+ self.client = ClaudeSDKClient(options)
+ self.turn_count = 0
+
+ async def start(self):
+ await self.client.connect()
+ print("Starting conversation session. Claude will remember context.")
+ print(
+ "Commands: 'exit' to quit, 'interrupt' to stop current task, 'new' for new session"
+ )
+
+ while True:
+ user_input = input(f"\n[Turn {self.turn_count + 1}] You: ")
+
+ if user_input.lower() == "exit":
+ break
+ elif user_input.lower() == "interrupt":
+ await self.client.interrupt()
+ print("Task interrupted!")
+ continue
+ elif user_input.lower() == "new":
+ # Disconnect and reconnect for a fresh session
+ await self.client.disconnect()
+ await self.client.connect()
+ self.turn_count = 0
+ print("Started new conversation session (previous context cleared)")
+ continue
+
+ # Send message - the session retains all previous messages
+ await self.client.query(user_input)
+ self.turn_count += 1
+
+ # Process response
+ print(f"[Turn {self.turn_count}] Claude: ", end="")
+ async for message in self.client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(block.text, end="")
+ print() # New line after response
+
+ await self.client.disconnect()
+ print(f"Conversation ended after {self.turn_count} turns.")
+
+ async def main():
+ options = ClaudeAgentOptions(
+ allowed_tools=["Read", "Write", "Bash"], permission_mode="acceptEdits"
+ )
+ session = ConversationSession(options)
+ await session.start()
+
+ # Example conversation:
+ # Turn 1 - You: "Create a file called hello.py"
+ # Turn 1 - Claude: "I'll create a hello.py file for you..."
+ # Turn 2 - You: "What's in that file?"
+ # Turn 2 - Claude: "The hello.py file I just created contains..." (remembers!)
+ # Turn 3 - You: "Add a main function to it"
+ # Turn 3 - Claude: "I'll add a main function to hello.py..." (knows which file!)
+
+ asyncio.run(main())
+
+###
+
+
+
+Using Hooks for Behavior Modification
+
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ HookMatcher,
+ HookContext,
+ )
+ import asyncio
+ from typing import Any
+
+ async def pre_tool_logger(
+ input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
+ ) -> dict[str, Any]:
+ """Log all tool usage before execution."""
+ tool_name = input_data.get("tool_name", "unknown")
+ print(f"[PRE-TOOL] About to use: {tool_name}")
+
+ # You can modify or block the tool execution here
+ if tool_name == "Bash" and "rm -rf" in str(input_data.get("tool_input", {})):
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": "Dangerous command blocked",
+ }
+ }
+ return {}
+
+ async def post_tool_logger(
+ input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
+ ) -> dict[str, Any]:
+ """Log results after tool execution."""
+ tool_name = input_data.get("tool_name", "unknown")
+ print(f"[POST-TOOL] Completed: {tool_name}")
+ return {}
+
+ async def user_prompt_modifier(
+ input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
+ ) -> dict[str, Any]:
+ """Add context to user prompts."""
+ original_prompt = input_data.get("prompt", "")
+
+ # Add a timestamp as additional context for Claude to see
+ from datetime import datetime
+
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "UserPromptSubmit",
+ "additionalContext": f"[Submitted at {timestamp}] Original prompt: {original_prompt}",
+ }
+ }
+
+ async def main():
+ options = ClaudeAgentOptions(
+ hooks={
+ "PreToolUse": [
+ HookMatcher(hooks=[pre_tool_logger]),
+ HookMatcher(matcher="Bash", hooks=[pre_tool_logger]),
+ ],
+ "PostToolUse": [HookMatcher(hooks=[post_tool_logger])],
+ "UserPromptSubmit": [HookMatcher(hooks=[user_prompt_modifier])],
+ },
+ allowed_tools=["Read", "Write", "Bash"],
+ )
+
+ async with ClaudeSDKClient(options=options) as client:
+ await client.query("List files in current directory")
+
+ async for message in client.receive_response():
+ # Hooks will automatically log tool usage
+ pass
+
+ asyncio.run(main())
+
+###
+
+
+
+Real-time Progress Monitoring
+
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ AssistantMessage,
+ ToolUseBlock,
+ ToolResultBlock,
+ TextBlock,
+ )
+ import asyncio
+
+ async def monitor_progress():
+ options = ClaudeAgentOptions(
+ allowed_tools=["Write", "Bash"], permission_mode="acceptEdits"
+ )
+
+ async with ClaudeSDKClient(options=options) as client:
+ await client.query("Create 5 Python files with different sorting algorithms")
+
+ # Monitor progress in real-time
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, ToolUseBlock):
+ if block.name == "Write":
+ file_path = block.input.get("file_path", "")
+ print(f"Creating: {file_path}")
+ elif isinstance(block, ToolResultBlock):
+ print("Completed tool execution")
+ elif isinstance(block, TextBlock):
+ print(f"Claude says: {block.text[:100]}...")
+
+ print("Task completed!")
+
+ asyncio.run(monitor_progress())
+
+##
+
+
+
+Example Usage
+
+###
+
+
+
+Basic file operations (using query)
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock
+ import asyncio
+
+ async def create_project():
+ options = ClaudeAgentOptions(
+ allowed_tools=["Read", "Write", "Bash"],
+ permission_mode="acceptEdits",
+ cwd="/home/user/project",
+ )
+
+ async for message in query(
+ prompt="Create a Python project structure with setup.py", options=options
+ ):
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, ToolUseBlock):
+ print(f"Using tool: {block.name}")
+
+ asyncio.run(create_project())
+
+###
+
+
+
+Error handling
+
+ from claude_agent_sdk import query, CLINotFoundError, ProcessError, CLIJSONDecodeError
+
+ try:
+ async for message in query(prompt="Hello"):
+ print(message)
+ except CLINotFoundError:
+ print(
+ "Claude Code CLI not found. Try reinstalling: pip install --force-reinstall claude-agent-sdk"
+ )
+ except ProcessError as e:
+ print(f"Process failed with exit code: {e.exit_code}")
+ except CLIJSONDecodeError as e:
+ print(f"Failed to parse response: {e}")
+
+###
+
+
+
+Streaming mode with client
+
+ from claude_agent_sdk import ClaudeSDKClient
+ import asyncio
+
+ async def interactive_session():
+ async with ClaudeSDKClient() as client:
+ # Send initial message
+ await client.query("What's the weather like?")
+
+ # Process responses
+ async for msg in client.receive_response():
+ print(msg)
+
+ # Send follow-up
+ await client.query("Tell me more about that")
+
+ # Process follow-up response
+ async for msg in client.receive_response():
+ print(msg)
+
+ asyncio.run(interactive_session())
+
+###
+
+
+
+Using custom tools with ClaudeSDKClient
+
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ tool,
+ create_sdk_mcp_server,
+ AssistantMessage,
+ TextBlock,
+ )
+ import asyncio
+ from typing import Any
+
+ # Define custom tools with @tool decorator
+ @tool("calculate", "Perform mathematical calculations", {"expression": str})
+ async def calculate(args: dict[str, Any]) -> dict[str, Any]:
+ try:
+ result = eval(args["expression"], {"__builtins__": {}})
+ return {"content": [{"type": "text", "text": f"Result: {result}"}]}
+ except Exception as e:
+ return {
+ "content": [{"type": "text", "text": f"Error: {str(e)}"}],
+ "is_error": True,
+ }
+
+ @tool("get_time", "Get current time", {})
+ async def get_time(args: dict[str, Any]) -> dict[str, Any]:
+ from datetime import datetime
+
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ return {"content": [{"type": "text", "text": f"Current time: {current_time}"}]}
+
+ async def main():
+ # Create SDK MCP server with custom tools
+ my_server = create_sdk_mcp_server(
+ name="utilities", version="1.0.0", tools=[calculate, get_time]
+ )
+
+ # Configure options with the server
+ options = ClaudeAgentOptions(
+ mcp_servers={"utils": my_server},
+ allowed_tools=["mcp__utils__calculate", "mcp__utils__get_time"],
+ )
+
+ # Use ClaudeSDKClient for interactive tool usage
+ async with ClaudeSDKClient(options=options) as client:
+ await client.query("What's 123 * 456?")
+
+ # Process calculation response
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(f"Calculation: {block.text}")
+
+ # Follow up with time query
+ await client.query("What time is it now?")
+
+ async for message in client.receive_response():
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(f"Time: {block.text}")
+
+ asyncio.run(main())
+
+##
+
+
+
+Sandbox Configuration
+
+###
+
+
+
+`SandboxSettings`
+
+Configuration for sandbox behavior. Use this to enable command sandboxing and configure network restrictions programmatically.
+
+ class SandboxSettings(TypedDict, total=False):
+ enabled: bool
+ autoAllowBashIfSandboxed: bool
+ excludedCommands: list[str]
+ allowUnsandboxedCommands: bool
+ network: SandboxNetworkConfig
+ ignoreViolations: SandboxIgnoreViolations
+ enableWeakerNestedSandbox: bool
+
+Property| Type| Default| Description
+---|---|---|---
+`enabled`| `bool`| `False`| Enable sandbox mode for command execution
+`autoAllowBashIfSandboxed`| `bool`| `True`| Auto-approve bash commands when sandbox is enabled
+`excludedCommands`| `list[str]`| `[]`| Commands that always bypass sandbox restrictions (e.g., `["docker"]`). These run unsandboxed automatically without model involvement
+`allowUnsandboxedCommands`| `bool`| `True`| Allow the model to request running commands outside the sandbox. When `True`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the permissions system
+`network`| `SandboxNetworkConfig`| `None`| Network-specific sandbox configuration
+`ignoreViolations`| `SandboxIgnoreViolations`| `None`| Configure which sandbox violations to ignore
+`enableWeakerNestedSandbox`| `bool`| `False`| Enable a weaker nested sandbox for compatibility
+
+**Filesystem and network access restrictions** are NOT configured via sandbox settings. Instead, they are derived from [permission rules](</docs/en/settings#permission-settings>):
+
+ * **Filesystem read restrictions** : Read deny rules
+ * **Filesystem write restrictions** : Edit allow/deny rules
+ * **Network restrictions** : WebFetch allow/deny rules
+
+Use sandbox settings for command execution sandboxing, and permission rules for filesystem and network access control.
+
+####
+
+
+
+Example usage
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings
+
+ sandbox_settings: SandboxSettings = {
+ "enabled": True,
+ "autoAllowBashIfSandboxed": True,
+ "network": {"allowLocalBinding": True},
+ }
+
+ async for message in query(
+ prompt="Build and test my project",
+ options=ClaudeAgentOptions(sandbox=sandbox_settings),
+ ):
+ print(message)
+
+**Unix socket security** : The `allowUnixSockets` option can grant access to powerful system services. For example, allowing `/var/run/docker.sock` effectively grants full host system access through the Docker API, bypassing sandbox isolation. Only allow Unix sockets that are strictly necessary and understand the security implications of each.
+
+###
+
+
+
+`SandboxNetworkConfig`
+
+Network-specific configuration for sandbox mode.
+
+ class SandboxNetworkConfig(TypedDict, total=False):
+ allowLocalBinding: bool
+ allowUnixSockets: list[str]
+ allowAllUnixSockets: bool
+ httpProxyPort: int
+ socksProxyPort: int
+
+Property| Type| Default| Description
+---|---|---|---
+`allowLocalBinding`| `bool`| `False`| Allow processes to bind to local ports (e.g., for dev servers)
+`allowUnixSockets`| `list[str]`| `[]`| Unix socket paths that processes can access (e.g., Docker socket)
+`allowAllUnixSockets`| `bool`| `False`| Allow access to all Unix sockets
+`httpProxyPort`| `int`| `None`| HTTP proxy port for network requests
+`socksProxyPort`| `int`| `None`| SOCKS proxy port for network requests
+
+###
+
+
+
+`SandboxIgnoreViolations`
+
+Configuration for ignoring specific sandbox violations.
+
+ class SandboxIgnoreViolations(TypedDict, total=False):
+ file: list[str]
+ network: list[str]
+
+Property| Type| Default| Description
+---|---|---|---
+`file`| `list[str]`| `[]`| File path patterns to ignore violations for
+`network`| `list[str]`| `[]`| Network patterns to ignore violations for
+
+###
+
+
+
+Permissions Fallback for Unsandboxed Commands
+
+When `allowUnsandboxedCommands` is enabled, the model can request to run commands outside the sandbox by setting `dangerouslyDisableSandbox: True` in the tool input. These requests fall back to the existing permissions system, meaning your `can_use_tool` handler will be invoked, allowing you to implement custom authorization logic.
+
+**`excludedCommands` vs `allowUnsandboxedCommands`:**
+
+ * `excludedCommands`: A static list of commands that always bypass the sandbox automatically (e.g., `["docker"]`). The model has no control over this.
+ * `allowUnsandboxedCommands`: Lets the model decide at runtime whether to request unsandboxed execution by setting `dangerouslyDisableSandbox: True` in the tool input.
+
+ from claude_agent_sdk import (
+ query,
+ ClaudeAgentOptions,
+ HookMatcher,
+ PermissionResultAllow,
+ PermissionResultDeny,
+ ToolPermissionContext,
+ )
+
+ async def can_use_tool(
+ tool: str, input: dict, context: ToolPermissionContext
+ ) -> PermissionResultAllow | PermissionResultDeny:
+ # Check if the model is requesting to bypass the sandbox
+ if tool == "Bash" and input.get("dangerouslyDisableSandbox"):
+ # The model is requesting to run this command outside the sandbox
+ print(f"Unsandboxed command requested: {input.get('command')}")
+
+ if is_command_authorized(input.get("command")):
+ return PermissionResultAllow()
+ return PermissionResultDeny(
+ message="Command not authorized for unsandboxed execution"
+ )
+ return PermissionResultAllow()
+
+ # Required: dummy hook keeps the stream open for can_use_tool
+ async def dummy_hook(input_data, tool_use_id, context):
+ return {"continue_": True}
+
+ async def prompt_stream():
+ yield {
+ "type": "user",
+ "message": {"role": "user", "content": "Deploy my application"},
+ }
+
+ async def main():
+ async for message in query(
+ prompt=prompt_stream(),
+ options=ClaudeAgentOptions(
+ sandbox={
+ "enabled": True,
+ "allowUnsandboxedCommands": True, # Model can request unsandboxed execution
+ },
+ permission_mode="default",
+ can_use_tool=can_use_tool,
+ hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]},
+ ),
+ ):
+ print(message)
+
+This pattern enables you to:
+
+ * **Audit model requests** : Log when the model requests unsandboxed execution
+ * **Implement allowlists** : Only permit specific commands to run unsandboxed
+ * **Add approval workflows** : Require explicit authorization for privileged operations
+
+Commands running with `dangerouslyDisableSandbox: True` have full system access. Ensure your `can_use_tool` handler validates these requests carefully.If `permission_mode` is set to `bypassPermissions` and `allow_unsandboxed_commands` is enabled, the model can autonomously execute commands outside the sandbox without any approval prompts. This combination effectively allows the model to escape sandbox isolation silently.
+
+##
+
+
+
+See also
+
+ * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts
+ * [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) \- TypeScript SDK documentation
+ * [CLI reference](</docs/en/cli-reference>) \- Command-line interface
+ * [Common workflows](</docs/en/common-workflows>) \- Step-by-step guides
Show diff (366 lines)
--- a/secure-deployment.md
+++ b/secure-deployment.md
@@ -0,0 +1,363 @@
+Claude Code and the Agent SDK are powerful tools that can execute code, access files, and interact with external services on your behalf. Like any tool with these capabilities, deploying them thoughtfully ensures you get the benefits while maintaining appropriate controls. Unlike traditional software that follows predetermined code paths, these tools generate their actions dynamically based on context and goals. This flexibility is what makes them useful, but it also means their behavior can be influenced by the content they process: files, webpages, or user input. This is sometimes called prompt injection. For example, if a repository’s README contains unusual instructions, Claude Code might incorporate those into its actions in ways the operator didn’t anticipate. This guide covers practical ways to reduce this risk. The good news is that securing an agent deployment doesn’t require exotic infrastructure. The same principles that apply to running any semi-trusted code apply here: isolation, least privilege, and defense in depth. Claude Code includes several security features that help with common concerns, and this guide walks through these along with additional hardening options for those who need them. Not every deployment needs maximum security. A developer running Claude Code on their laptop has different requirements than a company processing customer data in a multi-tenant environment. This guide presents options ranging from Claude Code’s built-in security features to hardened production architectures, so you can choose what fits your situation.
+
+##
+
+
+
+Threat model
+
+Agents can take unintended actions due to prompt injection (instructions embedded in content they process) or model error. Claude models are designed to resist this, and as analyzed in the [model card](<https://www.anthropic.com/claude-opus-4-6-system-card>), Claude Opus 4.6 is the most robust frontier model available. Defense in depth is still good practice though. For example, if an agent processes a malicious file that instructs it to send customer data to an external server, network controls can block that request entirely.
+
+##
+
+
+
+Built-in security features
+
+Claude Code includes several security features that address common concerns. See the [security documentation](</docs/en/security>) for full details.
+
+ * **Permissions system** : Every tool and bash command can be configured to allow, block, or prompt the user for approval. Use glob patterns to create rules like “allow all npm commands” or “block any command with sudo”. Organizations can set policies that apply across all users. See [permissions](</docs/en/permissions>).
+ * **Static analysis** : Before executing bash commands, Claude Code runs static analysis to identify potentially risky operations. Commands that modify system files or access sensitive directories are flagged and require explicit user approval.
+ * **Web search summarization** : Search results are summarized rather than passing raw content directly into the context, reducing the risk of prompt injection from malicious web content.
+ * **Sandbox mode** : Bash commands can run in a sandboxed environment that restricts filesystem and network access. See the [sandboxing documentation](</docs/en/sandboxing>) for details.
+
+##
+
+
+
+Security principles
+
+For deployments that require additional hardening beyond Claude Code’s defaults, these principles guide the available options.
+
+###
+
+
+
+Security boundaries
+
+A security boundary separates components with different trust levels. For high-security deployments, you can place sensitive resources (like credentials) outside the boundary containing the agent. If something goes wrong in the agent’s environment, resources outside that boundary remain protected. For example, rather than giving an agent direct access to an API key, you could run a proxy outside the agent’s environment that injects the key into requests. The agent can make API calls, but it never sees the credential itself. This pattern is useful for multi-tenant deployments or when processing untrusted content.
+
+###
+
+
+
+Least privilege
+
+When needed, you can restrict the agent to only the capabilities required for its specific task:
+
+Resource| Restriction options
+---|---
+Filesystem| Mount only needed directories, prefer read-only
+Network| Restrict to specific endpoints via proxy
+Credentials| Inject via proxy rather than exposing directly
+System capabilities| Drop Linux capabilities in containers
+
+###
+
+
+
+Defense in depth
+
+For high-security environments, layering multiple controls provides additional protection. Options include:
+
+ * Container isolation
+ * Network restrictions
+ * Filesystem controls
+ * Request validation at a proxy
+
+The right combination depends on your threat model and operational requirements.
+
+##
+
+
+
+Isolation technologies
+
+Different isolation technologies offer different tradeoffs between security strength, performance, and operational complexity.
+
+In all of these configurations, Claude Code (or your Agent SDK application) runs inside the isolation boundary (the sandbox, container, or VM). The security controls described below restrict what the agent can access from within that boundary.
+
+Technology| Isolation strength| Performance overhead| Complexity
+---|---|---|---
+Sandbox runtime| Good (secure defaults)| Very low| Low
+Containers (Docker)| Setup dependent| Low| Medium
+gVisor| Excellent (with correct setup)| Medium/High| Medium
+VMs (Firecracker, QEMU)| Excellent (with correct setup)| High| Medium/High
+
+###
+
+
+
+Sandbox runtime
+
+For lightweight isolation without containers, [sandbox-runtime](<https://github.com/anthropic-experimental/sandbox-runtime>) enforces filesystem and network restrictions at the OS level. The main advantage is simplicity: no Docker configuration, container images, or networking setup required. The proxy and filesystem restrictions are built in. You provide a settings file specifying allowed domains and paths. **How it works:**
+
+ * **Filesystem** : Uses OS primitives (`bubblewrap` on Linux, `sandbox-exec` on macOS) to restrict read/write access to configured paths
+ * **Network** : Removes network namespace (Linux) or uses Seatbelt profiles (macOS) to route network traffic through a built-in proxy
+ * **Configuration** : JSON-based allowlists for domains and filesystem paths
+
+**Setup:**
+
+ npm install @anthropic-ai/sandbox-runtime
+
+Then create a configuration file specifying allowed paths and domains. **Security considerations:**
+
+ 1. **Same-host kernel** : Unlike VMs, sandboxed processes share the host kernel. A kernel vulnerability could theoretically enable escape. For some threat models this is acceptable, but if you need kernel-level isolation, use gVisor or a separate VM.
+ 2. **No TLS inspection** : The proxy allowlists domains but doesn’t inspect encrypted traffic. If the agent has permissive credentials for an allowed domain, ensure it isn’t possible to use that domain to trigger other network requests or to exfiltrate data.
+
+For many single-developer and CI/CD use cases, sandbox-runtime raises the bar significantly with minimal setup. The sections below cover containers and VMs for deployments requiring stronger isolation.
+
+###
+
+
+
+Containers
+
+Containers provide isolation through Linux namespaces. Each container has its own view of the filesystem, process tree, and network stack, while sharing the host kernel. A security-hardened container configuration might look like this:
+
+ docker run \
+ --cap-drop ALL \
+ --security-opt no-new-privileges \
+ --security-opt seccomp=/path/to/seccomp-profile.json \
+ --read-only \
+ --tmpfs /tmp:rw,noexec,nosuid,size=100m \
+ --tmpfs /home/agent:rw,noexec,nosuid,size=500m \
+ --network none \
+ --memory 2g \
+ --cpus 2 \
+ --pids-limit 100 \
+ --user 1000:1000 \
+ -v /path/to/code:/workspace:ro \
+ -v /var/run/proxy.sock:/var/run/proxy.sock:ro \
+ agent-image
+
+Here’s what each option does:
+
+Option| Purpose
+---|---
+`--cap-drop ALL`| Removes Linux capabilities like `NET_ADMIN` and `SYS_ADMIN` that could enable privilege escalation
+`--security-opt no-new-privileges`| Prevents processes from gaining privileges through setuid binaries
+`--security-opt seccomp=...`| Restricts available syscalls; Docker’s default blocks ~44, custom profiles can block more
+`--read-only`| Makes the container’s root filesystem immutable, preventing the agent from persisting changes
+`--tmpfs /tmp:...`| Provides a writable temporary directory that’s cleared when the container stops
+`--network none`| Removes all network interfaces; the agent communicates through the mounted Unix socket below
+`--memory 2g`| Limits memory usage to prevent resource exhaustion
+`--pids-limit 100`| Limits process count to prevent fork bombs
+`--user 1000:1000`| Runs as a non-root user
+`-v ...:/workspace:ro`| Mounts code read-only so the agent can analyze but not modify it. **Avoid mounting sensitive host directories like`~/.ssh`, `~/.aws`, or `~/.config`**
+`-v .../proxy.sock:...`| Mounts a Unix socket connected to a proxy running outside the container (see below)
+
+**Unix socket architecture:** With `--network none`, the container has no network interfaces at all. The only way for the agent to reach the outside world is through the mounted Unix socket, which connects to a proxy running on the host. This proxy can enforce domain allowlists, inject credentials, and log all traffic. This is the same architecture used by [sandbox-runtime](<https://github.com/anthropic-experimental/sandbox-runtime>). Even if the agent is compromised via prompt injection, it cannot exfiltrate data to arbitrary servers. It can only communicate through the proxy, which controls what domains are reachable. For more details, see the [Claude Code sandboxing blog post](<https://www.anthropic.com/engineering/claude-code-sandboxing>). **Additional hardening options:**
+
+Option| Purpose
+---|---
+`--userns-remap`| Maps container root to unprivileged host user; requires daemon configuration but limits damage from container escape
+`--ipc private`| Isolates inter-process communication to prevent cross-container attacks
+
+###
+
+
+
+gVisor
+
+Standard containers share the host kernel: when code inside a container makes a system call, it goes directly to the same kernel that runs the host. This means a kernel vulnerability could allow container escape. gVisor addresses this by intercepting system calls in userspace before they reach the host kernel, implementing its own compatibility layer that handles most syscalls without involving the real kernel. If an agent runs malicious code (perhaps due to prompt injection), that code runs in the container and could attempt kernel exploits. With gVisor, the attack surface is much smaller: the malicious code would need to exploit gVisor’s userspace implementation first and would have limited access to the real kernel. To use gVisor with Docker, install the `runsc` runtime and configure the daemon:
+
+ // /etc/docker/daemon.json
+ {
+ "runtimes": {
+ "runsc": {
+ "path": "/usr/local/bin/runsc"
+ }
+ }
+ }
+
+Then run containers with:
+
+ docker run --runtime=runsc agent-image
+
+**Performance considerations:**
+
+Workload| Overhead
+---|---
+CPU-bound computation| ~0% (no syscall interception)
+Simple syscalls| ~2× slower
+File I/O intensive| Up to 10-200× slower for heavy open/close patterns
+
+For multi-tenant environments or when processing untrusted content, the additional isolation is often worth the overhead.
+
+###
+
+
+
+Virtual machines
+
+VMs provide hardware-level isolation through CPU virtualization extensions. Each VM runs its own kernel, creating a strong boundary. A vulnerability in the guest kernel doesn’t directly compromise the host. However, VMs aren’t automatically “more secure” than alternatives like gVisor. VM security depends heavily on the hypervisor and device emulation code. Firecracker is designed for lightweight microVM isolation. It can boot VMs in under 125ms with less than 5 MiB memory overhead, stripping away unnecessary device emulation to reduce attack surface. With this approach, the agent VM has no external network interface. Instead, it communicates through `vsock` (virtual sockets). All traffic routes through vsock to a proxy on the host, which enforces allowlists and injects credentials before forwarding requests.
+
+###
+
+
+
+Cloud deployments
+
+For cloud deployments, you can combine any of the above isolation technologies with cloud-native network controls:
+
+ 1. Run agent containers in a private subnet with no internet gateway
+ 2. Configure cloud firewall rules (AWS Security Groups, GCP VPC firewall) to block all egress except to your proxy
+ 3. Run a proxy (such as [Envoy](<https://www.envoyproxy.io/>) with its `credential_injector` filter) that validates requests, enforces domain allowlists, injects credentials, and forwards to external APIs
+ 4. Assign minimal IAM permissions to the agent’s service account, routing sensitive access through the proxy where possible
+ 5. Log all traffic at the proxy for audit purposes
+
+##
+
+
+
+Credential management
+
+Agents often need credentials to call APIs, access repositories, or interact with cloud services. The challenge is providing this access without exposing the credentials themselves.
+
+###
+
+
+
+The proxy pattern
+
+The recommended approach is to run a proxy outside the agent’s security boundary that injects credentials into outgoing requests. The agent sends requests without credentials, the proxy adds them, and forwards the request to its destination. This pattern has several benefits:
+
+ 1. The agent never sees the actual credentials
+ 2. The proxy can enforce an allowlist of permitted endpoints
+ 3. The proxy can log all requests for auditing
+ 4. Credentials are stored in one secure location rather than distributed to each agent
+
+###
+
+
+
+Configuring Claude Code to use a proxy
+
+Claude Code supports two methods for routing sampling requests through a proxy: **Option 1: ANTHROPIC_BASE_URL (simple but only for sampling API requests)**
+
+ export ANTHROPIC_BASE_URL="http://localhost:8080"
+
+This tells Claude Code and the Agent SDK to send sampling requests to your proxy instead of the Claude API directly. Your proxy receives plaintext HTTP requests, can inspect and modify them (including injecting credentials), then forwards to the real API. **Option 2: HTTP_PROXY / HTTPS_PROXY (system-wide)**
+
+ export HTTP_PROXY="http://localhost:8080"
+ export HTTPS_PROXY="http://localhost:8080"
+
+Claude Code and the Agent SDK respect these standard environment variables, routing all HTTP traffic through the proxy. For HTTPS, the proxy creates an encrypted CONNECT tunnel: it cannot see or modify request contents without TLS interception.
+
+###
+
+
+
+Implementing a proxy
+
+You can build your own proxy or use an existing one:
+
+ * [Envoy Proxy](<https://www.envoyproxy.io/>): production-grade proxy with `credential_injector` filter for adding auth headers
+ * [mitmproxy](<https://mitmproxy.org/>): TLS-terminating proxy for inspecting and modifying HTTPS traffic
+ * [Squid](<http://www.squid-cache.org/>): caching proxy with access control lists
+ * [LiteLLM](<https://github.com/BerriAI/litellm>): LLM gateway with credential injection and rate limiting
+
+###
+
+
+
+Credentials for other services
+
+Beyond sampling from the Claude API, agents often need authenticated access to other services, such as git repositories, databases, and internal APIs. There are two main approaches:
+
+####
+
+
+
+Custom tools
+
+Provide access through an MCP server or custom tool that routes requests to a service running outside the agent’s security boundary. The agent calls the tool, but the actual authenticated request happens outside. The tool calls to a proxy which injects the credentials. For example, a git MCP server could accept commands from the agent but forward them to a git proxy running on the host, which adds authentication before contacting the remote repository. The agent never sees the credentials. Advantages:
+
+ * **No TLS interception** : The external service makes authenticated requests directly
+ * **Credentials stay outside** : The agent only sees the tool interface, not the underlying credentials
+
+####
+
+
+
+Traffic forwarding
+
+For Claude API calls, `ANTHROPIC_BASE_URL` lets you route requests to a proxy that can inspect and modify them in plaintext. But for other HTTPS services (GitHub, npm registries, internal APIs), the traffic is often encrypted end-to-end. Even if you route it through a proxy via `HTTP_PROXY`, the proxy only sees an opaque TLS tunnel and can’t inject credentials. To modify HTTPS traffic to arbitrary services, without using a custom tool, you need a TLS-terminating proxy that decrypts traffic, inspects or modifies it, then re-encrypts it before forwarding. This requires:
+
+ 1. Running the proxy outside the agent’s container
+ 2. Installing the proxy’s CA certificate in the agent’s trust store (so the agent trusts the proxy’s certificates)
+ 3. Configuring `HTTP_PROXY`/`HTTPS_PROXY` to route traffic through the proxy
+
+This approach handles any HTTP-based service without writing custom tools, but adds complexity around certificate management. Note that not all programs respect `HTTP_PROXY`/`HTTPS_PROXY`. Most tools (curl, pip, npm, git) do, but some may bypass these variables and connect directly. For example, Node.js `fetch()` ignores these variables by default; in Node 24+ you can set `NODE_USE_ENV_PROXY=1` to enable support. For comprehensive coverage, you can use [proxychains](<https://github.com/haad/proxychains>) to intercept network calls, or configure iptables to redirect outbound traffic to a transparent proxy.
+
+A **transparent proxy** intercepts traffic at the network level, so the client doesn’t need to be configured to use it. Regular proxies require clients to explicitly connect and speak HTTP CONNECT or SOCKS. Transparent proxies (like Squid or mitmproxy in transparent mode) can handle raw redirected TCP connections.
+
+Both approaches still require the TLS-terminating proxy and trusted CA certificate. They just ensure traffic actually reaches the proxy.
+
+##
+
+
+
+Filesystem configuration
+
+Filesystem controls determine what files the agent can read and write.
+
+###
+
+
+
+Read-only code mounting
+
+When the agent needs to analyze code but not modify it, mount the directory read-only:
+
+ docker run -v /path/to/code:/workspace:ro agent-image
+
+Even read-only access to a code directory can expose credentials. Common files to exclude or sanitize before mounting:
+
+File| Risk
+---|---
+`.env`, `.env.local`| API keys, database passwords, secrets
+`~/.git-credentials`| Git passwords/tokens in plaintext
+`~/.aws/credentials`| AWS access keys
+`~/.config/gcloud/application_default_credentials.json`| Google Cloud ADC tokens
+`~/.azure/`| Azure CLI credentials
+`~/.docker/config.json`| Docker registry auth tokens
+`~/.kube/config`| Kubernetes cluster credentials
+`.npmrc`, `.pypirc`| Package registry tokens
+`*-service-account.json`| GCP service account keys
+`*.pem`, `*.key`| Private keys
+
+Consider copying only the source files needed, or using `.dockerignore`-style filtering.
+
+###
+
+
+
+Writable locations
+
+If the agent needs to write files, you have a few options depending on whether you want changes to persist: For ephemeral workspaces in containers, use `tmpfs` mounts that exist only in memory and are cleared when the container stops:
+
+ docker run \
+ --read-only \
+ --tmpfs /tmp:rw,noexec,nosuid,size=100m \
+ --tmpfs /workspace:rw,noexec,size=500m \
+ agent-image
+
+If you want to review changes before persisting them, an overlay filesystem lets the agent write without modifying underlying files. Changes are stored in a separate layer you can inspect, apply, or discard. For fully persistent output, mount a dedicated volume but keep it separate from sensitive directories.
+
+##
+
+
+
+Further reading
+
+ * [Claude Code security documentation](</docs/en/security>)
+ * [Hosting the Agent SDK](</docs/en/agent-sdk/hosting>)
+ * [Handling permissions](</docs/en/agent-sdk/permissions>)
+ * [Sandbox runtime](<https://github.com/anthropic-experimental/sandbox-runtime>)
+ * [The Lethal Trifecta for AI Agents](<https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/>)
+ * [OWASP Top 10 for LLM Applications](<https://owasp.org/www-project-top-10-for-large-language-model-applications/>)
+ * [Docker Security Best Practices](<https://docs.docker.com/engine/security/>)
+ * [gVisor Documentation](<https://gvisor.dev/docs/>)
+ * [Firecracker Documentation](<https://firecracker-microvm.github.io/>)
Show diff (271 lines)
--- a/sessions.md
+++ b/sessions.md
@@ -0,0 +1,268 @@
+A session is the conversation history the SDK accumulates while your agent works. It contains your prompt, every tool call the agent made, every tool result, and every response. The SDK writes it to disk automatically so you can return to it later. Returning to a session means the agent has full context from before: files it already read, analysis it already performed, decisions it already made. You can ask a follow-up question, recover from an interruption, or branch off to try a different approach.
+
+Sessions persist the **conversation** , not the filesystem. To snapshot and revert file changes the agent made, use [file checkpointing](</docs/en/agent-sdk/file-checkpointing>).
+
+This guide covers how to pick the right approach for your app, the SDK interfaces that track sessions automatically, how to capture session IDs and use `resume` and `fork` manually, and what to know about resuming sessions across hosts.
+
+##
+
+
+
+Choose an approach
+
+How much session handling you need depends on your application’s shape. Session management comes into play when you send multiple prompts that should share context. Within a single `query()` call, the agent already takes as many turns as it needs, and permission prompts and `AskUserQuestion` are [handled in-loop](</docs/en/agent-sdk/user-input>) (they don’t end the call).
+
+What you’re building| What to use
+---|---
+One-shot task: single prompt, no follow-up| Nothing extra. One `query()` call handles it.
+Multi-turn chat in one process| `ClaudeSDKClient` (Python) or `continue: true` (TypeScript). The SDK tracks the session for you with no ID handling.
+Pick up where you left off after a process restart| `continue_conversation=True` (Python) / `continue: true` (TypeScript). Resumes the most recent session in the directory, no ID needed.
+Resume a specific past session (not the most recent)| Capture the session ID and pass it to `resume`.
+Try an alternative approach without losing the original| Fork the session.
+Stateless task, don’t want anything written to disk (TypeScript only)| Set [`persistSession: false`](</docs/en/agent-sdk/typescript#options>). The session exists only in memory for the duration of the call. Python always persists to disk.
+
+###
+
+
+
+Continue, resume, and fork
+
+Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claude-agent-options>) in Python, [`Options`](</docs/en/agent-sdk/typescript#options>) in TypeScript). **Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session:
+
+ * **Continue** finds the most recent session in the current directory. You don’t track anything. Works well when your app runs one conversation at a time.
+ * **Resume** takes a specific session ID. You track the ID. Required when you have multiple sessions (for example, one per user in a multi-user app) or want to return to one that isn’t the most recent.
+
+**Fork** is different: it creates a new session that starts with a copy of the original’s history. The original stays unchanged. Use fork to try a different direction while keeping the option to go back.
+
+##
+
+
+
+Automatic session management
+
+Both SDKs offer an interface that tracks session state for you across calls, so you don’t pass IDs around manually. Use these for multi-turn conversations within a single process.
+
+###
+
+
+
+Python: `ClaudeSDKClient`
+
+[`ClaudeSDKClient`](</docs/en/agent-sdk/python#claude-sdk-client>) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](</docs/en/agent-sdk/python#claude-sdk-client>) to iterate over the messages for the current query. The client must be used as an async context manager. This example runs two queries against the same `client`. The first asks the agent to analyze a module; the second asks it to refactor that module. Because both calls go through the same client instance, the second query has full context from the first without any explicit `resume` or session ID:
+
+Python
+
+ import asyncio
+ from claude_agent_sdk import (
+ ClaudeSDKClient,
+ ClaudeAgentOptions,
+ AssistantMessage,
+ ResultMessage,
+ TextBlock,
+ )
+
+ def print_response(message):
+ """Print only the human-readable parts of a message."""
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(block.text)
+ elif isinstance(message, ResultMessage):
+ cost = (
+ f"${message.total_cost_usd:.4f}"
+ if message.total_cost_usd is not None
+ else "N/A"
+ )
+ print(f"[done: {message.subtype}, cost: {cost}]")
+
+ async def main():
+ options = ClaudeAgentOptions(
+ allowed_tools=["Read", "Edit", "Glob", "Grep"],
+ )
+
+ async with ClaudeSDKClient(options=options) as client:
+ # First query: client captures the session ID internally
+ await client.query("Analyze the auth module")
+ async for message in client.receive_response():
+ print_response(message)
+
+ # Second query: automatically continues the same session
+ await client.query("Now refactor it to use JWT")
+ async for message in client.receive_response():
+ print_response(message)
+
+ asyncio.run(main())
+
+See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claude-sdk-client>) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function.
+
+###
+
+
+
+TypeScript: `continue: true`
+
+The stable TypeScript SDK (the `query()` function used throughout these docs, sometimes called V1) doesn’t have a session-holding client object like Python’s `ClaudeSDKClient`. Instead, pass `continue: true` on each subsequent `query()` call and the SDK picks up the most recent session in the current directory. No ID tracking required. This example makes two separate `query()` calls. The first creates a fresh session; the second sets `continue: true`, which tells the SDK to find and resume the most recent session on disk. The agent has full context from the first call:
+
+TypeScript
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // First query: creates a new session
+ for await (const message of query({
+ prompt: "Analyze the auth module",
+ options: { allowedTools: ["Read", "Glob", "Grep"] }
+ })) {
+ if (message.type === "result" && message.subtype === "success") {
+ console.log(message.result);
+ }
+ }
+
+ // Second query: continue: true resumes the most recent session
+ for await (const message of query({
+ prompt: "Now refactor it to use JWT",
+ options: {
+ continue: true,
+ allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"]
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success") {
+ console.log(message.result);
+ }
+ }
+
+There’s also a [V2 preview](</docs/en/agent-sdk/typescript-v2-preview>) of the TypeScript SDK that provides `createSession()` with a `send` / `stream` pattern, closer to Python’s `ClaudeSDKClient` in feel. V2 is unstable and its APIs may change; the rest of this documentation uses the stable V1 `query()` function.
+
+##
+
+
+
+Use session options with `query()`
+
+###
+
+
+
+Capture the session ID
+
+Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](</docs/en/agent-sdk/python#result-message>) in Python, [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdk-result-message>) in TypeScript), which is present on every result regardless of success or error. In TypeScript the ID is also available earlier as a direct field on the init `SystemMessage`; in Python it’s nested inside `SystemMessage.data`.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ async def main():
+ session_id = None
+
+ async for message in query(
+ prompt="Analyze the auth module and suggest improvements",
+ options=ClaudeAgentOptions(
+ allowed_tools=["Read", "Glob", "Grep"],
+ ),
+ ):
+ if isinstance(message, ResultMessage):
+ session_id = message.session_id
+ if message.subtype == "success":
+ print(message.result)
+
+ print(f"Session ID: {session_id}")
+ return session_id
+
+ session_id = asyncio.run(main())
+
+###
+
+
+
+Resume by ID
+
+Pass a session ID to `resume` to return to that specific session. The agent picks up with full context from wherever the session left off. Common reasons to resume:
+
+ * **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files.
+ * **Recover from a limit.** The first run ended with `error_max_turns` or `error_max_budget_usd` (see [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>)); resume with a higher limit.
+ * **Restart your process.** You captured the ID before shutdown and want to restore the conversation.
+
+This example resumes the session from Capture the session ID with a follow-up prompt. Because you’re resuming, the agent already has the prior analysis in context:
+
+Python
+
+TypeScript
+
+ # Earlier session analyzed the code; now build on that analysis
+ async for message in query(
+ prompt="Now implement the refactoring you suggested",
+ options=ClaudeAgentOptions(
+ resume=session_id,
+ allowed_tools=["Read", "Edit", "Write", "Glob", "Grep"],
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+
+If a `resume` call returns a fresh session instead of the expected history, the most common cause is a mismatched `cwd`. Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, where `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-` (so `/Users/me/proj` becomes `-Users-me-proj`). If your resume call runs from a different directory, the SDK looks in the wrong place. The session file also needs to exist on the current machine.
+
+###
+
+
+
+Fork to explore alternatives
+
+Forking creates a new session that starts with a copy of the original’s history but diverges from that point. The fork gets its own session ID; the original’s ID and history stay unchanged. You end up with two independent sessions you can resume separately.
+
+Forking branches the conversation history, not the filesystem. If a forked agent edits files, those changes are real and visible to any session working in the same directory. To branch and revert file changes, use [file checkpointing](</docs/en/agent-sdk/file-checkpointing>).
+
+This example builds on Capture the session ID: you’ve already analyzed an auth module in `session_id` and want to explore OAuth2 without losing the JWT-focused thread. The first block forks the session and captures the fork’s ID (`forked_id`); the second block resumes the original `session_id` to continue down the JWT path. You now have two session IDs pointing at two separate histories:
+
+Python
+
+TypeScript
+
+ # Fork: branch from session_id into a new session
+ forked_id = None
+ async for message in query(
+ prompt="Instead of JWT, implement OAuth2 for the auth module",
+ options=ClaudeAgentOptions(
+ resume=session_id,
+ fork_session=True,
+ ),
+ ):
+ if isinstance(message, ResultMessage):
+ forked_id = message.session_id # The fork's ID, distinct from session_id
+ if message.subtype == "success":
+ print(message.result)
+
+ print(f"Forked session: {forked_id}")
+
+ # Original session is untouched; resuming it continues the JWT thread
+ async for message in query(
+ prompt="Continue with the JWT approach",
+ options=ClaudeAgentOptions(resume=session_id),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+
+##
+
+
+
+Resume across hosts
+
+Session files are local to the machine that created them. To resume a session on a different host (CI workers, ephemeral containers, serverless), you have two options:
+
+ * **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it to the same path on the new host before calling `resume`. The `cwd` must match.
+ * **Don’t rely on session resume.** Capture the results you need (analysis output, decisions, file diffs) as application state and pass them into a fresh session’s prompt. This is often more robust than shipping transcript files around.
+
+Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](</docs/en/agent-sdk/typescript#list-sessions>) and [`getSessionMessages()`](</docs/en/agent-sdk/typescript#get-session-messages>) in TypeScript, [`list_sessions()`](</docs/en/agent-sdk/python#list-sessions>) and [`get_session_messages()`](</docs/en/agent-sdk/python#get-session-messages>) in Python. Use them to build custom session pickers, cleanup logic, or transcript viewers. Both SDKs also expose functions for looking up and mutating individual sessions: [`get_session_info()`](</docs/en/agent-sdk/python#get-session-info>), [`rename_session()`](</docs/en/agent-sdk/python#rename-session>), and [`tag_session()`](</docs/en/agent-sdk/python#tag-session>) in Python, and [`getSessionInfo()`](</docs/en/agent-sdk/typescript#get-session-info>), [`renameSession()`](</docs/en/agent-sdk/typescript#rename-session>), and [`tagSession()`](</docs/en/agent-sdk/typescript#tag-session>) in TypeScript. Use them to organize sessions by tag or give them human-readable titles.
+
+##
+
+
+
+Related resources
+
+ * [How the agent loop works](</docs/en/agent-sdk/agent-loop>): Understand turns, messages, and context accumulation within a session
+ * [File checkpointing](</docs/en/agent-sdk/file-checkpointing>): Track and revert file changes across sessions
+ * [Python `ClaudeAgentOptions`](</docs/en/agent-sdk/python#claude-agent-options>): Full session option reference for Python
+ * [TypeScript `Options`](</docs/en/agent-sdk/typescript#options>): Full session option reference for TypeScript
--- a/settings.md
+++ b/settings.md
@@ -177,7 +177,7 @@
`awsCredentialExport`| Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](</docs/en/amazon-bedrock#advanced-credential-configuration>))| `/bin/generate_aws_grant.sh`
`blockedMarketplaces`| (Managed settings only) Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [Managed marketplace restrictions](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>)| `[{ "source": "github", "repo": "untrusted/plugins" }]`
`channelsEnabled`| (Managed settings only) Allow [channels](</docs/en/channels>) for Team and Enterprise users. Unset or `false` blocks channel message delivery regardless of what users pass to `--channels`| `true`
-`cleanupPeriodDays`| Sessions inactive for longer than this period are deleted at startup (default: 30 days, minimum 1). Setting to `0` is rejected with a validation error. Also controls the age cutoff for automatic removal of [orphaned subagent worktrees](</docs/en/common-workflows#worktree-cleanup>) at startup. To disable transcript writes entirely in non-interactive mode (`-p`), use the `--no-session-persistence` flag or the `persistSession: false` SDK option; there is no interactive-mode equivalent.| `20`
+`cleanupPeriodDays`| Session files older than this period are deleted at startup (default: 30 days, minimum 1). Setting to `0` is rejected with a validation error. Also controls the age cutoff for automatic removal of [orphaned subagent worktrees](</docs/en/common-workflows#worktree-cleanup>) at startup. To disable transcript writes entirely in non-interactive mode (`-p`), use the `--no-session-persistence` flag or the `persistSession: false` SDK option; there is no interactive-mode equivalent.| `20`
`companyAnnouncements`| Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random.| `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]`
`defaultShell`| Default shell for input-box `!` commands. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` routes interactive `!` commands through PowerShell on Windows. Requires `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. See [PowerShell tool](</docs/en/tools-reference#powershell-tool>)| `"powershell"`
`deniedMcpServers`| When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](</docs/en/mcp#managed-mcp-configuration>)| `[{ "serverName": "filesystem" }]`
@@ -308,6 +308,7 @@
`network.allowUnixSockets`| Unix socket paths accessible in sandbox (for SSH agents, etc.)| `["~/.ssh/agent-socket"]`
`network.allowAllUnixSockets`| Allow all Unix socket connections in sandbox. Default: false| `true`
`network.allowLocalBinding`| Allow binding to localhost ports (macOS only). Default: false| `true`
+`network.allowMachLookup`| Additional XPC/Mach service names the sandbox may look up (macOS only). Supports a single trailing `*` for prefix matching. Needed for tools that communicate via XPC such as the iOS Simulator or Playwright.| `["com.apple.coresimulator.*"]`
`network.allowedDomains`| Array of domains to allow for outbound network traffic. Supports wildcards (e.g., `*.example.com`).| `["github.com", "*.npmjs.org"]`
`network.allowManagedDomainsOnly`| (Managed settings only) Only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Domains from user, project, and local settings are ignored. Non-allowed domains are blocked automatically without prompting the user. Denied domains are still respected from all sources. Default: false| `true`
`network.httpProxyPort`| HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy.| `8080`
--- a/setup.md
+++ b/setup.md
@@ -14,7 +14,7 @@
* Ubuntu 20.04+
* Debian 10+
* Alpine Linux 3.19+
- * **Hardware** : 4 GB+ RAM
+ * **Hardware** : 4 GB+ RAM, x64 or ARM64 processor
* **Network** : internet connection required. See [network configuration](</docs/en/network-config#network-access-requirements>).
* **Shell** : Bash, Zsh, PowerShell, or CMD. On Windows, [Git for Windows](<https://git-scm.com/downloads/win>) is required.
* **Location** : [Anthropic supported countries](<https://www.anthropic.com/supported-countries>)
--- a/skills.md
+++ b/skills.md
@@ -15,7 +15,7 @@
Skill| Purpose
---|---
`/batch <instruction>`| Orchestrate large-scale changes across a codebase in parallel. Researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once approved, spawns one background agent per unit in an isolated [git worktree](</docs/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees>). Each agent implements its unit, runs tests, and opens a pull request. Requires a git repository. Example: `/batch migrate src/ from Solid to React`
-`/claude-api`| Load Claude API reference material for your project’s language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL) and Agent SDK reference for Python and TypeScript. Covers tool use, streaming, batches, structured outputs, and common pitfalls. Also activates automatically when your code imports `anthropic`, `@anthropic-ai/sdk`, or `claude_agent_sdk`
+`/claude-api`| Load Claude API reference material for your project’s language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL). Covers tool use, streaming, batches, structured outputs, Managed Agents, and common pitfalls. Also activates automatically when your code imports `anthropic` or `@anthropic-ai/sdk`
`/debug [description]`| Enable debug logging for the current session and troubleshoot issues by reading the session debug log. Debug logging is off by default unless you started with `claude --debug`, so running `/debug` mid-session starts capturing logs from that point forward. Optionally describe the issue to focus the analysis
`/loop [interval] <prompt>`| Run a prompt repeatedly on an interval while the session stays open. Useful for polling a deployment, babysitting a PR, or periodically re-running another skill. Example: `/loop 5m check if the deploy finished`. See [Run prompts on a schedule](</docs/en/scheduled-tasks>)
`/simplify [focus]`| Review your recently changed files for code reuse, quality, and efficiency issues, then fix them. Spawns three review agents in parallel, aggregates their findings, and applies fixes. Pass text to focus on specific concerns: `/simplify focus on memory efficiency`
@@ -216,7 +216,7 @@
`${CLAUDE_SESSION_ID}`| The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions.
`${CLAUDE_SKILL_DIR}`| The directory containing the skill’s `SKILL.md` file. For plugin skills, this is the skill’s subdirectory within the plugin, not the plugin root. Use this in bash injection commands to reference scripts or files bundled with the skill, regardless of the current working directory.
-**Example using substitutions:**
+Indexed arguments use shell-style quoting, so wrap multi-word values in quotes to pass them as a single argument. For example, `/my-skill "hello world" second` makes `$0` expand to `hello world` and `$1` to `second`. The `$ARGUMENTS` placeholder always expands to the full argument string as typed. **Example using substitutions:**
---
name: session-logger
@@ -291,15 +291,26 @@
-Restrict tool access
-
-Use the `allowed-tools` field to limit which tools Claude can use when a skill is active. This skill creates a read-only mode where Claude can explore files but not modify them:
-
- ---
- name: safe-reader
- description: Read files without making changes
- allowed-tools: Read Grep Glob
- ---
+Skill content lifecycle
+
+When you or Claude invoke a skill, the rendered `SKILL.md` content enters the conversation as a single message and stays there for the rest of the session. Claude Code does not re-read the skill file on later turns, so write guidance that should apply throughout a task as standing instructions rather than one-time steps. [Auto-compaction](</docs/en/how-claude-code-works#when-context-fills-up>) preserves invoked skills. When the conversation is summarized to free context, Claude Code re-attaches the most recent invocation of each skill after the summary (truncated if the skill is very large). If you invoke the same skill more than once, only the latest copy is carried forward through compaction. If a skill seems to stop influencing behavior after the first response, the skill content is still present. The model is choosing other tools or approaches. Strengthen the skill’s `description` and instructions so the model keeps preferring it, or use [hooks](</docs/en/hooks>) to enforce behavior deterministically.
+
+###
+
+
+
+Pre-approve tools for a skill
+
+The `allowed-tools` field grants permission for the listed tools while the skill is active, so Claude can use them without prompting you for approval. It does not restrict which tools are available: every tool remains callable, and your [permission settings](</docs/en/permissions>) still govern tools that are not listed. This skill lets Claude run git commands without per-use approval whenever you invoke it:
+
+ ---
+ name: commit
+ description: Stage and commit the current changes
+ disable-model-invocation: true
+ allowed-tools: Bash(git add *) Bash(git commit *) Bash(git status *)
+ ---
+
+To block a skill from using certain tools, add deny rules in your [permission settings](</docs/en/permissions>) instead.
###
--- a/slack.md
+++ b/slack.md
@@ -21,7 +21,7 @@
Requirement| Details
---|---
-Claude Plan| Pro, Max, Team, or Enterprise with Claude Code access (premium seats)
+Claude Plan| Pro, Max, Team, or Enterprise with Claude Code access (premium seats or Chat + Claude Code seats)
Claude Code on the web| Access to [Claude Code on the web](</docs/en/claude-code-on-the-web>) must be enabled
GitHub Account| Connected to Claude Code on the web with at least one repository authenticated
Slack Authentication| Your Slack account linked to your Claude account via the Claude app
@@ -204,7 +204,7 @@
What’s accessible where
-**In Slack** : You’ll see status updates, completion summaries, and action buttons. The full transcript is preserved and always accessible. **On the web** : The complete Claude Code session with full conversation history, all code changes, file operations, and the ability to continue the session or create pull requests. For Enterprise and Team accounts, sessions created from Claude in Slack are automatically visible to the organization. See [Claude Code on the Web sharing](</docs/en/claude-code-on-the-web#sharing-sessions>) for more details.
+**In Slack** : You’ll see status updates, completion summaries, and action buttons. The full transcript is preserved and always accessible. **On the web** : The complete Claude Code session with full conversation history, all code changes, file operations, and the ability to continue the session or create pull requests. For Enterprise and Team accounts, sessions created from Claude in Slack are automatically visible to the organization. See [Claude Code on the Web sharing](</docs/en/claude-code-on-the-web#share-sessions>) for more details.
##
Show diff (404 lines)
--- a/slash-commands.md
+++ b/slash-commands.md
@@ -0,0 +1,401 @@
+Slash commands provide a way to control Claude Code sessions with special commands that start with `/`. These commands can be sent through the SDK to perform actions like clearing conversation history, compacting messages, or getting help.
+
+##
+
+
+
+Discovering Available Slash Commands
+
+The Claude Agent SDK provides information about available slash commands in the system initialization message. Access this information when your session starts:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Hello Claude",
+ options: { maxTurns: 1 }
+ })) {
+ if (message.type === "system" && message.subtype === "init") {
+ console.log("Available slash commands:", message.slash_commands);
+ // Example output: ["/compact", "/clear", "/help"]
+ }
+ }
+
+##
+
+
+
+Sending Slash Commands
+
+Send slash commands by including them in your prompt string, just like regular text:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Send a slash command
+ for await (const message of query({
+ prompt: "/compact",
+ options: { maxTurns: 1 }
+ })) {
+ if (message.type === "result") {
+ console.log("Command executed:", message.result);
+ }
+ }
+
+##
+
+
+
+Common Slash Commands
+
+###
+
+
+
+`/compact` \- Compact Conversation History
+
+The `/compact` command reduces the size of your conversation history by summarizing older messages while preserving important context:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "/compact",
+ options: { maxTurns: 1 }
+ })) {
+ if (message.type === "system" && message.subtype === "compact_boundary") {
+ console.log("Compaction completed");
+ console.log("Pre-compaction tokens:", message.compact_metadata.pre_tokens);
+ console.log("Trigger:", message.compact_metadata.trigger);
+ }
+ }
+
+###
+
+
+
+`/clear` \- Clear Conversation
+
+The `/clear` command starts a fresh conversation by clearing all previous history:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Clear conversation and start fresh
+ for await (const message of query({
+ prompt: "/clear",
+ options: { maxTurns: 1 }
+ })) {
+ if (message.type === "system" && message.subtype === "init") {
+ console.log("Conversation cleared, new session started");
+ console.log("Session ID:", message.session_id);
+ }
+ }
+
+##
+
+
+
+Creating Custom Slash Commands
+
+In addition to using built-in slash commands, you can create your own custom commands that are available through the SDK. Custom commands are defined as markdown files in specific directories, similar to how subagents are configured.
+
+The `.claude/commands/` directory is the legacy format. The recommended format is `.claude/skills/<name>/SKILL.md`, which supports the same slash-command invocation (`/name`) plus autonomous invocation by Claude. See [Skills](</docs/en/agent-sdk/skills>) for the current format. The CLI continues to support both formats, and the examples below remain accurate for `.claude/commands/`.
+
+###
+
+
+
+File Locations
+
+Custom slash commands are stored in designated directories based on their scope:
+
+ * **Project commands** : `.claude/commands/` \- Available only in the current project (legacy; prefer `.claude/skills/`)
+ * **Personal commands** : `~/.claude/commands/` \- Available across all your projects (legacy; prefer `~/.claude/skills/`)
+
+###
+
+
+
+File Format
+
+Each custom command is a markdown file where:
+
+ * The filename (without `.md` extension) becomes the command name
+ * The file content defines what the command does
+ * Optional YAML frontmatter provides configuration
+
+####
+
+
+
+Basic Example
+
+Create `.claude/commands/refactor.md`:
+
+ Refactor the selected code to improve readability and maintainability.
+ Focus on clean code principles and best practices.
+
+This creates the `/refactor` command that you can use through the SDK.
+
+####
+
+
+
+With Frontmatter
+
+Create `.claude/commands/security-check.md`:
+
+ ---
+ allowed-tools: Read, Grep, Glob
+ description: Run security vulnerability scan
+ model: claude-opus-4-6
+ ---
+
+ Analyze the codebase for security vulnerabilities including:
+ - SQL injection risks
+ - XSS vulnerabilities
+ - Exposed credentials
+ - Insecure configurations
+
+###
+
+
+
+Using Custom Commands in the SDK
+
+Once defined in the filesystem, custom commands are automatically available through the SDK:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Use a custom command
+ for await (const message of query({
+ prompt: "/refactor src/auth/login.ts",
+ options: { maxTurns: 3 }
+ })) {
+ if (message.type === "assistant") {
+ console.log("Refactoring suggestions:", message.message);
+ }
+ }
+
+ // Custom commands appear in the slash_commands list
+ for await (const message of query({
+ prompt: "Hello",
+ options: { maxTurns: 1 }
+ })) {
+ if (message.type === "system" && message.subtype === "init") {
+ // Will include both built-in and custom commands
+ console.log("Available commands:", message.slash_commands);
+ // Example: ["/compact", "/clear", "/help", "/refactor", "/security-check"]
+ }
+ }
+
+###
+
+
+
+Advanced Features
+
+####
+
+
+
+Arguments and Placeholders
+
+Custom commands support dynamic arguments using placeholders: Create `.claude/commands/fix-issue.md`:
+
+ ---
+ argument-hint: [issue-number] [priority]
+ description: Fix a GitHub issue
+ ---
+
+ Fix issue #$1 with priority $2.
+ Check the issue description and implement the necessary changes.
+
+Use in SDK:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Pass arguments to custom command
+ for await (const message of query({
+ prompt: "/fix-issue 123 high",
+ options: { maxTurns: 5 }
+ })) {
+ // Command will process with $1="123" and $2="high"
+ if (message.type === "result") {
+ console.log("Issue fixed:", message.result);
+ }
+ }
+
+####
+
+
+
+Bash Command Execution
+
+Custom commands can execute bash commands and include their output: Create `.claude/commands/git-commit.md`:
+
+ ---
+ allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
+ description: Create a git commit
+ ---
+
+ ## Context
+
+ - Current status: !`git status`
+ - Current diff: !`git diff HEAD`
+
+ ## Task
+
+ Create a git commit with appropriate message based on the changes.
+
+####
+
+
+
+File References
+
+Include file contents using the `@` prefix: Create `.claude/commands/review-config.md`:
+
+ ---
+ description: Review configuration files
+ ---
+
+ Review the following configuration files for issues:
+ - Package config: @package.json
+ - TypeScript config: @tsconfig.json
+ - Environment config: @.env
+
+ Check for security issues, outdated dependencies, and misconfigurations.
+
+###
+
+
+
+Organization with Namespacing
+
+Organize commands in subdirectories for better structure:
+
+ .claude/commands/
+ ├── frontend/
+ │ ├── component.md # Creates /component (project:frontend)
+ │ └── style-check.md # Creates /style-check (project:frontend)
+ ├── backend/
+ │ ├── api-test.md # Creates /api-test (project:backend)
+ │ └── db-migrate.md # Creates /db-migrate (project:backend)
+ └── review.md # Creates /review (project)
+
+The subdirectory appears in the command description but doesn’t affect the command name itself.
+
+###
+
+
+
+Practical Examples
+
+####
+
+
+
+Code Review Command
+
+Create `.claude/commands/code-review.md`:
+
+ ---
+ allowed-tools: Read, Grep, Glob, Bash(git diff:*)
+ description: Comprehensive code review
+ ---
+
+ ## Changed Files
+ !`git diff --name-only HEAD~1`
+
+ ## Detailed Changes
+ !`git diff HEAD~1`
+
+ ## Review Checklist
+
+ Review the above changes for:
+ 1. Code quality and readability
+ 2. Security vulnerabilities
+ 3. Performance implications
+ 4. Test coverage
+ 5. Documentation completeness
+
+ Provide specific, actionable feedback organized by priority.
+
+####
+
+
+
+Test Runner Command
+
+Create `.claude/commands/test.md`:
+
+ ---
+ allowed-tools: Bash, Read, Edit
+ argument-hint: [test-pattern]
+ description: Run tests with optional pattern
+ ---
+
+ Run tests matching pattern: $ARGUMENTS
+
+ 1. Detect the test framework (Jest, pytest, etc.)
+ 2. Run tests with the provided pattern
+ 3. If tests fail, analyze and fix them
+ 4. Re-run to verify fixes
+
+Use these commands through the SDK:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Run code review
+ for await (const message of query({
+ prompt: "/code-review",
+ options: { maxTurns: 3 }
+ })) {
+ // Process review feedback
+ }
+
+ // Run specific tests
+ for await (const message of query({
+ prompt: "/test auth",
+ options: { maxTurns: 5 }
+ })) {
+ // Handle test results
+ }
+
+##
+
+
+
+See Also
+
+ * [Slash Commands](</docs/en/skills>) \- Complete slash command documentation
+ * [Subagents in the SDK](</docs/en/agent-sdk/subagents>) \- Similar filesystem-based configuration for subagents
+ * [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) \- Complete API documentation
+ * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts
+ * [CLI reference](</docs/en/cli-reference>) \- Command-line interface
--- a/statusline.md
+++ b/statusline.md
@@ -52,7 +52,7 @@
}
}
-The optional `padding` field adds extra horizontal spacing (in characters) to the status line content. Defaults to `0`. This padding is in addition to the interface’s built-in spacing, so it controls relative indentation rather than absolute distance from the terminal edge.
+The optional `padding` field adds extra horizontal spacing (in characters) to the status line content. Defaults to `0`. This padding is in addition to the interface’s built-in spacing, so it controls relative indentation rather than absolute distance from the terminal edge. The optional `refreshInterval` field re-runs your command every N seconds in addition to the event-driven updates. The minimum is `1`. Set this when your status line shows time-based data such as a clock, or when background subagents change git state while the main session is idle. Leave it unset to run only on events.
###
@@ -122,7 +122,7 @@
How status lines work
-Claude Code runs your script and pipes JSON session data to it via stdin. Your script reads the JSON, extracts what it needs, and prints text to stdout. Claude Code displays whatever your script prints. **When it updates** Your script runs after each new assistant message, when the permission mode changes, or when vim mode toggles. Updates are debounced at 300ms, meaning rapid changes batch together and your script runs once things settle. If a new update triggers while your script is still running, the in-flight execution is cancelled. If you edit your script, the changes won’t appear until your next interaction with Claude Code triggers an update. **What your script can output**
+Claude Code runs your script and pipes JSON session data to it via stdin. Your script reads the JSON, extracts what it needs, and prints text to stdout. Claude Code displays whatever your script prints. **When it updates** Your script runs after each new assistant message, when the permission mode changes, or when vim mode toggles. Updates are debounced at 300ms, meaning rapid changes batch together and your script runs once things settle. If a new update triggers while your script is still running, the in-flight execution is cancelled. If you edit your script, the changes won’t appear until your next interaction with Claude Code triggers an update. These triggers can go quiet when the main session is idle, for example while a coordinator waits on background subagents. To keep time-based or externally-sourced segments current during idle periods, set `refreshInterval` to also re-run the command on a fixed timer. **What your script can output**
* **Multiple lines** : each `echo` or `print` statement displays as a separate row. See the multi-line example.
* **Colors** : use [ANSI escape codes](<https://en.wikipedia.org/wiki/ANSI_escape_code#Colors>) like `\033[32m` for green (terminal must support them). See the git status example.
@@ -144,6 +144,7 @@
`cwd`, `workspace.current_dir`| Current working directory. Both fields contain the same value; `workspace.current_dir` is preferred for consistency with `workspace.project_dir`.
`workspace.project_dir`| Directory where Claude Code was launched, which may differ from `cwd` if the working directory changes during a session
`workspace.added_dirs`| Additional directories added via `/add-dir` or `--add-dir`. Empty array if none have been added
+`workspace.git_worktree`| Git worktree name when the current directory is inside a linked worktree created with `git worktree add`. Absent in the main working tree. Populated for any git worktree, unlike `worktree.*` which applies only to `--worktree` sessions
`cost.total_cost_usd`| Total session cost in USD
`cost.total_duration_ms`| Total wall-clock time since the session started, in milliseconds
`cost.total_api_duration_ms`| Total time spent waiting for API responses in milliseconds
@@ -185,7 +186,8 @@
"workspace": {
"current_dir": "/current/working/directory",
"project_dir": "/original/project/directory",
- "added_dirs": []
+ "added_dirs": [],
+ "git_worktree": "feature-xyz"
},
"version": "2.1.90",
"output_style": {
@@ -240,6 +242,7 @@
**Fields that may be absent** (not present in JSON):
* `session_name`: appears only when a custom name has been set with `--name` or `/rename`
+ * `workspace.git_worktree`: appears only when the current directory is inside a linked git worktree
* `vim`: appears only when vim mode is enabled
* `agent`: appears only when running with the `--agent` flag or agent settings configured
* `worktree`: appears only during `--worktree` sessions. When present, `branch` and `original_branch` may also be absent for hook-based worktrees
@@ -499,7 +502,7 @@
Cache expensive operations
-Your status line script runs frequently during active sessions. Commands like `git status` or `git diff` can be slow, especially in large repositories. This example caches git information to a temp file and only refreshes it every 5 seconds. Use a stable, fixed filename for the cache file like `/tmp/statusline-git-cache`. Each status line invocation runs as a new process, so process-based identifiers like `$$`, `os.getpid()`, or `process.pid` produce a different value every time and the cache is never reused. Each script checks if the cache file is missing or older than 5 seconds before running git commands:
+Your status line script runs frequently during active sessions. Commands like `git status` or `git diff` can be slow, especially in large repositories. This example caches git information to a temp file and only refreshes it every 5 seconds. The cache filename needs to be stable across status line invocations within a session, but unique across sessions so concurrent sessions in different repositories don’t read each other’s cached git state. Process-based identifiers like `$$`, `os.getpid()`, or `process.pid` change on every invocation and defeat the cache. Use the `session_id` from the JSON input instead: it’s stable for the lifetime of a session and unique per session. Each script checks if the cache file is missing or older than 5 seconds before running git commands:
Bash
@@ -512,8 +515,9 @@
MODEL=$(echo "$input" | jq -r '.model.display_name')
DIR=$(echo "$input" | jq -r '.workspace.current_dir')
-
- CACHE_FILE="/tmp/statusline-git-cache"
+ SESSION_ID=$(echo "$input" | jq -r '.session_id')
+
+ CACHE_FILE="/tmp/statusline-git-cache-$SESSION_ID"
CACHE_MAX_AGE=5 # seconds
cache_is_stale() {
@@ -579,7 +583,7 @@
Tips
- * **Test with mock input** : `echo '{"model":{"display_name":"Opus"},"context_window":{"used_percentage":25}}' | ./statusline.sh`
+ * **Test with mock input** : `echo '{"model":{"display_name":"Opus"},"workspace":{"current_dir":"/home/user/project"},"context_window":{"used_percentage":25},"session_id":"test-session-abc"}' | ./statusline.sh`
* **Keep output short** : the status bar has limited width, so long output may get truncated or wrap awkwardly
* **Cache slow operations** : your script runs frequently during active sessions, so commands like `git status` can cause lag. See the caching example for how to handle this.
@@ -616,6 +620,14 @@
* Verify your terminal supports OSC 8 hyperlinks (iTerm2, Kitty, WezTerm)
* Terminal.app does not support clickable links
+ * If link text appears but isn’t clickable, Claude Code may not have detected hyperlink support in your terminal. This commonly affects Windows Terminal and other emulators not in the auto-detection list. Set the `FORCE_HYPERLINK` environment variable to override detection before launching Claude Code:
+
+ FORCE_HYPERLINK=1 claude
+
+In PowerShell, set the variable in the current session first:
+
+ $env:FORCE_HYPERLINK = "1"; claude
+
* SSH and tmux sessions may strip OSC sequences depending on configuration
* If escape sequences appear as literal text like `\e]8;;`, use `printf '%b'` instead of `echo -e` for more reliable escape handling
Show diff (277 lines)
--- a/streaming-output.md
+++ b/streaming-output.md
@@ -0,0 +1,274 @@
+By default, the Agent SDK yields complete `AssistantMessage` objects after Claude finishes generating each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming by setting `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options.
+
+This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>).
+
+##
+
+
+
+Enable streaming output
+
+To enable streaming, set `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options. This causes the SDK to yield `StreamEvent` messages containing raw API events as they arrive, in addition to the usual `AssistantMessage` and `ResultMessage`. Your code then needs to:
+
+ 1. Check each message’s type to distinguish `StreamEvent` from other message types
+ 2. For `StreamEvent`, extract the `event` field and check its `type`
+ 3. Look for `content_block_delta` events where `delta.type` is `text_delta`, which contain the actual text chunks
+
+The example below enables streaming and prints text chunks as they arrive. Notice the nested type checks: first for `StreamEvent`, then for `content_block_delta`, then for `text_delta`:
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions
+ from claude_agent_sdk.types import StreamEvent
+ import asyncio
+
+ async def stream_response():
+ options = ClaudeAgentOptions(
+ include_partial_messages=True,
+ allowed_tools=["Bash", "Read"],
+ )
+
+ async for message in query(prompt="List the files in my project", options=options):
+ if isinstance(message, StreamEvent):
+ event = message.event
+ if event.get("type") == "content_block_delta":
+ delta = event.get("delta", {})
+ if delta.get("type") == "text_delta":
+ print(delta.get("text", ""), end="", flush=True)
+
+ asyncio.run(stream_response())
+
+##
+
+
+
+StreamEvent reference
+
+When partial messages are enabled, you receive raw Claude API streaming events wrapped in an object. The type has different names in each SDK:
+
+ * **Python** : `StreamEvent` (import from `claude_agent_sdk.types`)
+ * **TypeScript** : `SDKPartialAssistantMessage` with `type: 'stream_event'`
+
+Both contain raw Claude API events, not accumulated text. You need to extract and accumulate text deltas yourself. Here’s the structure of each type:
+
+Python
+
+TypeScript
+
+ @dataclass
+ class StreamEvent:
+ uuid: str # Unique identifier for this event
+ session_id: str # Session identifier
+ event: dict[str, Any] # The raw Claude API stream event
+ parent_tool_use_id: str | None # Parent tool ID if from a subagent
+
+The `event` field contains the raw streaming event from the [Claude API](<https://platform.claude.com/docs/en/build-with-claude/streaming#event-types>). Common event types include:
+
+Event Type| Description
+---|---
+`message_start`| Start of a new message
+`content_block_start`| Start of a new content block (text or tool use)
+`content_block_delta`| Incremental update to content
+`content_block_stop`| End of a content block
+`message_delta`| Message-level updates (stop reason, usage)
+`message_stop`| End of the message
+
+##
+
+
+
+Message flow
+
+With partial messages enabled, you receive messages in this order:
+
+ StreamEvent (message_start)
+ StreamEvent (content_block_start) - text block
+ StreamEvent (content_block_delta) - text chunks...
+ StreamEvent (content_block_stop)
+ StreamEvent (content_block_start) - tool_use block
+ StreamEvent (content_block_delta) - tool input chunks...
+ StreamEvent (content_block_stop)
+ StreamEvent (message_delta)
+ StreamEvent (message_stop)
+ AssistantMessage - complete message with all content
+ ... tool executes ...
+ ... more streaming events for next turn ...
+ ResultMessage - final result
+
+Without partial messages enabled (`include_partial_messages` in Python, `includePartialMessages` in TypeScript), you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete responses), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python).
+
+##
+
+
+
+Stream text responses
+
+To display text as it’s generated, look for `content_block_delta` events where `delta.type` is `text_delta`. These contain the incremental text chunks. The example below prints each chunk as it arrives:
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions
+ from claude_agent_sdk.types import StreamEvent
+ import asyncio
+
+ async def stream_text():
+ options = ClaudeAgentOptions(include_partial_messages=True)
+
+ async for message in query(prompt="Explain how databases work", options=options):
+ if isinstance(message, StreamEvent):
+ event = message.event
+ if event.get("type") == "content_block_delta":
+ delta = event.get("delta", {})
+ if delta.get("type") == "text_delta":
+ # Print each text chunk as it arrives
+ print(delta.get("text", ""), end="", flush=True)
+
+ print() # Final newline
+
+ asyncio.run(stream_text())
+
+##
+
+
+
+Stream tool calls
+
+Tool calls also stream incrementally. You can track when tools start, receive their input as it’s generated, and see when they complete. The example below tracks the current tool being called and accumulates the JSON input as it streams in. It uses three event types:
+
+ * `content_block_start`: tool begins
+ * `content_block_delta` with `input_json_delta`: input chunks arrive
+ * `content_block_stop`: tool call complete
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions
+ from claude_agent_sdk.types import StreamEvent
+ import asyncio
+
+ async def stream_tool_calls():
+ options = ClaudeAgentOptions(
+ include_partial_messages=True,
+ allowed_tools=["Read", "Bash"],
+ )
+
+ # Track the current tool and accumulate its input JSON
+ current_tool = None
+ tool_input = ""
+
+ async for message in query(prompt="Read the README.md file", options=options):
+ if isinstance(message, StreamEvent):
+ event = message.event
+ event_type = event.get("type")
+
+ if event_type == "content_block_start":
+ # New tool call is starting
+ content_block = event.get("content_block", {})
+ if content_block.get("type") == "tool_use":
+ current_tool = content_block.get("name")
+ tool_input = ""
+ print(f"Starting tool: {current_tool}")
+
+ elif event_type == "content_block_delta":
+ delta = event.get("delta", {})
+ if delta.get("type") == "input_json_delta":
+ # Accumulate JSON input as it streams in
+ chunk = delta.get("partial_json", "")
+ tool_input += chunk
+ print(f" Input chunk: {chunk}")
+
+ elif event_type == "content_block_stop":
+ # Tool call complete - show final input
+ if current_tool:
+ print(f"Tool {current_tool} called with: {tool_input}")
+ current_tool = None
+
+ asyncio.run(stream_tool_calls())
+
+##
+
+
+
+Build a streaming UI
+
+This example combines text and tool streaming into a cohesive UI. It tracks whether the agent is currently executing a tool (using an `in_tool` flag) to show status indicators like `[Using Read...]` while tools run. Text streams normally when not in a tool, and tool completion triggers a “done” message. This pattern is useful for chat interfaces that need to show progress during multi-step agent tasks.
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+ from claude_agent_sdk.types import StreamEvent
+ import asyncio
+ import sys
+
+ async def streaming_ui():
+ options = ClaudeAgentOptions(
+ include_partial_messages=True,
+ allowed_tools=["Read", "Bash", "Grep"],
+ )
+
+ # Track whether we're currently in a tool call
+ in_tool = False
+
+ async for message in query(
+ prompt="Find all TODO comments in the codebase", options=options
+ ):
+ if isinstance(message, StreamEvent):
+ event = message.event
+ event_type = event.get("type")
+
+ if event_type == "content_block_start":
+ content_block = event.get("content_block", {})
+ if content_block.get("type") == "tool_use":
+ # Tool call is starting - show status indicator
+ tool_name = content_block.get("name")
+ print(f"\n[Using {tool_name}...]", end="", flush=True)
+ in_tool = True
+
+ elif event_type == "content_block_delta":
+ delta = event.get("delta", {})
+ # Only stream text when not executing a tool
+ if delta.get("type") == "text_delta" and not in_tool:
+ sys.stdout.write(delta.get("text", ""))
+ sys.stdout.flush()
+
+ elif event_type == "content_block_stop":
+ if in_tool:
+ # Tool call finished
+ print(" done", flush=True)
+ in_tool = False
+
+ elif isinstance(message, ResultMessage):
+ # Agent finished all work
+ print(f"\n\n--- Complete ---")
+
+ asyncio.run(streaming_ui())
+
+##
+
+
+
+Known limitations
+
+Some SDK features are incompatible with streaming:
+
+ * **Extended thinking** : when you explicitly set `max_thinking_tokens` (Python) or `maxThinkingTokens` (TypeScript), `StreamEvent` messages are not emitted. You’ll only receive complete messages after each turn. Note that thinking is disabled by default in the SDK, so streaming works unless you enable it.
+ * **Structured output** : the JSON result appears only in the final `ResultMessage.structured_output`, not as streaming deltas. See [structured outputs](</docs/en/agent-sdk/structured-outputs>) for details.
+
+##
+
+
+
+Next steps
+
+Now that you can stream text and tool calls in real-time, explore these related topics:
+
+ * [Interactive vs one-shot queries](</docs/en/agent-sdk/streaming-vs-single-mode>): choose between input modes for your use case
+ * [Structured outputs](</docs/en/agent-sdk/structured-outputs>): get typed JSON responses from the agent
+ * [Permissions](</docs/en/agent-sdk/permissions>): control which tools the agent can use
Show diff (193 lines)
--- a/streaming-vs-single-mode.md
+++ b/streaming-vs-single-mode.md
@@ -0,0 +1,190 @@
+##
+
+
+
+Overview
+
+The Claude Agent SDK supports two distinct input modes for interacting with agents:
+
+ * **Streaming Input Mode** (Default & Recommended) - A persistent, interactive session
+ * **Single Message Input** \- One-shot queries that use session state and resuming
+
+This guide explains the differences, benefits, and use cases for each mode to help you choose the right approach for your application.
+
+##
+
+
+
+Streaming Input Mode (Recommended)
+
+Streaming input mode is the **preferred** way to use the Claude Agent SDK. It provides full access to the agent’s capabilities and enables rich, interactive experiences. It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.
+
+###
+
+
+
+How It Works
+
+###
+
+
+
+Benefits
+
+## Image Uploads
+
+Attach images directly to messages for visual analysis and understanding
+
+## Queued Messages
+
+Send multiple messages that process sequentially, with ability to interrupt
+
+## Tool Integration
+
+Full access to all tools and custom MCP servers during the session
+
+## Hooks Support
+
+Use lifecycle hooks to customize behavior at various points
+
+## Real-time Feedback
+
+See responses as they’re generated, not just final results
+
+## Context Persistence
+
+Maintain conversation context across multiple turns naturally
+
+###
+
+
+
+Implementation Example
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+ import { readFile } from "fs/promises";
+
+ async function* generateMessages() {
+ // First message
+ yield {
+ type: "user" as const,
+ message: {
+ role: "user" as const,
+ content: "Analyze this codebase for security issues"
+ }
+ };
+
+ // Wait for conditions or user input
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ // Follow-up with image
+ yield {
+ type: "user" as const,
+ message: {
+ role: "user" as const,
+ content: [
+ {
+ type: "text",
+ text: "Review this architecture diagram"
+ },
+ {
+ type: "image",
+ source: {
+ type: "base64",
+ media_type: "image/png",
+ data: await readFile("diagram.png", "base64")
+ }
+ }
+ ]
+ }
+ };
+ }
+
+ // Process streaming responses
+ for await (const message of query({
+ prompt: generateMessages(),
+ options: {
+ maxTurns: 10,
+ allowedTools: ["Read", "Grep"]
+ }
+ })) {
+ if (message.type === "result") {
+ console.log(message.result);
+ }
+ }
+
+##
+
+
+
+Single Message Input
+
+Single message input is simpler but more limited.
+
+###
+
+
+
+When to Use Single Message Input
+
+Use single message input when:
+
+ * You need a one-shot response
+ * You do not need image attachments, hooks, etc.
+ * You need to operate in a stateless environment, such as a lambda function
+
+###
+
+
+
+Limitations
+
+Single message input mode does **not** support:
+
+ * Direct image attachments in messages
+ * Dynamic message queueing
+ * Real-time interruption
+ * Hook integration
+ * Natural multi-turn conversations
+
+###
+
+
+
+Implementation Example
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Simple one-shot query
+ for await (const message of query({
+ prompt: "Explain the authentication flow",
+ options: {
+ maxTurns: 1,
+ allowedTools: ["Read", "Grep"]
+ }
+ })) {
+ if (message.type === "result") {
+ console.log(message.result);
+ }
+ }
+
+ // Continue conversation with session management
+ for await (const message of query({
+ prompt: "Now explain the authorization process",
+ options: {
+ continue: true,
+ maxTurns: 1
+ }
+ })) {
+ if (message.type === "result") {
+ console.log(message.result);
+ }
+ }
Show diff (276 lines)
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -0,0 +1,273 @@
+Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK guarantees the output matches it. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly-typed objects back.
+
+##
+
+
+
+Why structured outputs?
+
+Agents return free-form text by default, which works for chat but not when you need to use the output programmatically. Structured outputs give you typed data you can pass directly to your application logic, database, or UI components. Consider a recipe app where an agent searches the web and brings back recipes. Without structured outputs, you get free-form text that you’d need to parse yourself. With structured outputs, you define the shape you want and get typed data you can use directly in your app.
+
+Without structured outputs
+
+ Here's a classic chocolate chip cookie recipe!
+
+ **Chocolate Chip Cookies**
+ Prep time: 15 minutes | Cook time: 10 minutes
+
+ Ingredients:
+ - 2 1/4 cups all-purpose flour
+ - 1 cup butter, softened
+ ...
+
+To use this in your app, you’d need to parse out the title, convert “15 minutes” to a number, separate ingredients from instructions, and handle inconsistent formatting across responses.
+
+With structured outputs
+
+ {
+ "name": "Chocolate Chip Cookies",
+ "prep_time_minutes": 15,
+ "cook_time_minutes": 10,
+ "ingredients": [
+ { "item": "all-purpose flour", "amount": 2.25, "unit": "cups" },
+ { "item": "butter, softened", "amount": 1, "unit": "cup" }
+ // ...
+ ],
+ "steps": ["Preheat oven to 375°F", "Cream butter and sugar" /* ... */]
+ }
+
+Typed data you can use directly in your UI.
+
+##
+
+
+
+Quick start
+
+To use structured outputs, define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) describing the shape of data you want, then pass it to `query()` via the `outputFormat` option (TypeScript) or `output_format` option (Python). When the agent finishes, the result message includes a `structured_output` field with validated data matching your schema. The example below asks the agent to research Anthropic and return the company name, year founded, and headquarters as structured output.
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Define the shape of data you want back
+ const schema = {
+ type: "object",
+ properties: {
+ company_name: { type: "string" },
+ founded_year: { type: "number" },
+ headquarters: { type: "string" }
+ },
+ required: ["company_name"]
+ };
+
+ for await (const message of query({
+ prompt: "Research Anthropic and provide key company information",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: schema
+ }
+ }
+ })) {
+ // The result message contains structured_output with validated data
+ if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ console.log(message.structured_output);
+ // { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }
+ }
+ }
+
+##
+
+
+
+Type-safe schemas with Zod and Pydantic
+
+Instead of writing JSON Schema by hand, you can use [Zod](<https://zod.dev/>) (TypeScript) or [Pydantic](<https://docs.pydantic.dev/latest/>) (Python) to define your schema. These libraries generate the JSON Schema for you and let you parse the response into a fully-typed object you can use throughout your codebase with autocomplete and type checking. The example below defines a schema for a feature implementation plan with a summary, list of steps (each with complexity level), and potential risks. The agent plans the feature and returns a typed `FeaturePlan` object. You can then access properties like `plan.summary` and iterate over `plan.steps` with full type safety.
+
+TypeScript
+
+Python
+
+ import { z } from "zod";
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Define schema with Zod
+ const FeaturePlan = z.object({
+ feature_name: z.string(),
+ summary: z.string(),
+ steps: z.array(
+ z.object({
+ step_number: z.number(),
+ description: z.string(),
+ estimated_complexity: z.enum(["low", "medium", "high"])
+ })
+ ),
+ risks: z.array(z.string())
+ });
+
+ type FeaturePlan = z.infer<typeof FeaturePlan>;
+
+ // Convert to JSON Schema
+ const schema = z.toJSONSchema(FeaturePlan);
+
+ // Use in query
+ for await (const message of query({
+ prompt:
+ "Plan how to add dark mode support to a React app. Break it into implementation steps.",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: schema
+ }
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ // Validate and get fully typed result
+ const parsed = FeaturePlan.safeParse(message.structured_output);
+ if (parsed.success) {
+ const plan: FeaturePlan = parsed.data;
+ console.log(`Feature: ${plan.feature_name}`);
+ console.log(`Summary: ${plan.summary}`);
+ plan.steps.forEach((step) => {
+ console.log(`${step.step_number}. [${step.estimated_complexity}] ${step.description}`);
+ });
+ }
+ }
+ }
+
+**Benefits:**
+
+ * Full type inference (TypeScript) and type hints (Python)
+ * Runtime validation with `safeParse()` or `model_validate()`
+ * Better error messages
+ * Composable, reusable schemas
+
+##
+
+
+
+Output format configuration
+
+The `outputFormat` (TypeScript) or `output_format` (Python) option accepts an object with:
+
+ * `type`: Set to `"json_schema"` for structured outputs
+ * `schema`: A [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) object defining your output structure. You can generate this from a Zod schema with `z.toJSONSchema()` or a Pydantic model with `.model_json_schema()`
+
+The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), `enum`, `const`, `required`, nested objects, and `$ref` definitions. For the full list of supported features and limitations, see [JSON Schema limitations](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations>).
+
+##
+
+
+
+Example: TODO tracking agent
+
+This example demonstrates how structured outputs work with multi-step tool use. The agent needs to find TODO comments in the codebase, then look up git blame information for each one. It autonomously decides which tools to use (Grep to search, Bash to run git commands) and combines the results into a single structured response. The schema includes optional fields (`author` and `date`) since git blame information might not be available for all files. The agent fills in what it can find and omits the rest.
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Define structure for TODO extraction
+ const todoSchema = {
+ type: "object",
+ properties: {
+ todos: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ text: { type: "string" },
+ file: { type: "string" },
+ line: { type: "number" },
+ author: { type: "string" },
+ date: { type: "string" }
+ },
+ required: ["text", "file", "line"]
+ }
+ },
+ total_count: { type: "number" }
+ },
+ required: ["todos", "total_count"]
+ };
+
+ // Agent uses Grep to find TODOs, Bash to get git blame info
+ for await (const message of query({
+ prompt: "Find all TODO comments in this codebase and identify who added them",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: todoSchema
+ }
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ const data = message.structured_output as { total_count: number; todos: Array<{ file: string; line: number; text: string; author?: string; date?: string }> };
+ console.log(`Found ${data.total_count} TODOs`);
+ data.todos.forEach((todo) => {
+ console.log(`${todo.file}:${todo.line} - ${todo.text}`);
+ if (todo.author) {
+ console.log(` Added by ${todo.author} on ${todo.date}`);
+ }
+ });
+ }
+ }
+
+##
+
+
+
+Error handling
+
+Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. When an error occurs, the result message has a `subtype` indicating what went wrong:
+
+Subtype| Meaning
+---|---
+`success`| Output was generated and validated successfully
+`error_max_structured_output_retries`| Agent couldn’t produce valid output after multiple attempts
+
+The example below checks the `subtype` field to determine whether the output was generated successfully or if you need to handle a failure:
+
+TypeScript
+
+Python
+
+ for await (const msg of query({
+ prompt: "Extract contact info from the document",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: contactSchema
+ }
+ }
+ })) {
+ if (msg.type === "result") {
+ if (msg.subtype === "success" && msg.structured_output) {
+ // Use the validated output
+ console.log(msg.structured_output);
+ } else if (msg.subtype === "error_max_structured_output_retries") {
+ // Handle the failure - retry with simpler prompt, fall back to unstructured, etc.
+ console.error("Could not produce valid output");
+ }
+ }
+ }
+
+**Tips for avoiding errors:**
+
+ * **Keep schemas focused.** Deeply nested schemas with many required fields are harder to satisfy. Start simple and add complexity as needed.
+ * **Match schema to task.** If the task might not have all the information your schema requires, make those fields optional.
+ * **Use clear prompts.** Ambiguous prompts make it harder for the agent to know what output to produce.
+
+##
+
+
+
+Related resources
+
+ * [JSON Schema documentation](<https://json-schema.org/>): learn JSON Schema syntax for defining complex schemas with nested objects, arrays, enums, and validation constraints
+ * [API Structured Outputs](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs>): use structured outputs with the Claude API directly for single-turn requests without tool use
+ * [Custom tools](</docs/en/agent-sdk/custom-tools>): give your agent custom tools to call during execution before returning structured output
--- a/sub-agents.md
+++ b/sub-agents.md
@@ -349,7 +349,7 @@
Mode| Behavior
---|---
`default`| Standard permission checking with prompts
-`acceptEdits`| Auto-accept file edits except in protected directories
+`acceptEdits`| Auto-accept file edits and common filesystem commands for paths in the working directory or `additionalDirectories`
`auto`| [Auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>): a background classifier reviews commands and protected-directory writes
`dontAsk`| Auto-deny permission prompts (explicitly allowed tools still work)
`bypassPermissions`| Skip permission prompts
Show diff (453 lines)
--- a/subagents.md
+++ b/subagents.md
@@ -0,0 +1,450 @@
+Subagents are separate agent instances that your main agent can spawn to handle focused subtasks. Use subagents to isolate context for focused subtasks, run multiple analyses in parallel, and apply specialized instructions without bloating the main agent’s prompt. This guide explains how to define and use subagents in the SDK using the `agents` parameter.
+
+##
+
+
+
+Overview
+
+You can create subagents in three ways:
+
+ * **Programmatically** : use the `agents` parameter in your `query()` options ([TypeScript](</docs/en/agent-sdk/typescript#agent-definition>), [Python](</docs/en/agent-sdk/python#agent-definition>))
+ * **Filesystem-based** : define agents as markdown files in `.claude/agents/` directories (see [defining subagents as files](</docs/en/sub-agents>))
+ * **Built-in general-purpose** : Claude can invoke the built-in `general-purpose` subagent at any time via the Agent tool without you defining anything
+
+This guide focuses on the programmatic approach, which is recommended for SDK applications. When you define subagents, Claude determines whether to invoke them based on each subagent’s `description` field. Write clear descriptions that explain when the subagent should be used, and Claude will automatically delegate appropriate tasks. You can also explicitly request a subagent by name in your prompt (for example, “Use the code-reviewer agent to…”).
+
+##
+
+
+
+Benefits of using subagents
+
+###
+
+
+
+Context isolation
+
+Each subagent runs in its own fresh conversation. Intermediate tool calls and results stay inside the subagent; only its final message returns to the parent. See What subagents inherit for exactly what’s in the subagent’s context. **Example:** a `research-assistant` subagent can explore dozens of files without any of that content accumulating in the main conversation. The parent receives a concise summary, not every file the subagent read.
+
+###
+
+
+
+Parallelization
+
+Multiple subagents can run concurrently, dramatically speeding up complex workflows. **Example:** during a code review, you can run `style-checker`, `security-scanner`, and `test-coverage` subagents simultaneously, reducing review time from minutes to seconds.
+
+###
+
+
+
+Specialized instructions and knowledge
+
+Each subagent can have tailored system prompts with specific expertise, best practices, and constraints. **Example:** a `database-migration` subagent can have detailed knowledge about SQL best practices, rollback strategies, and data integrity checks that would be unnecessary noise in the main agent’s instructions.
+
+###
+
+
+
+Tool restrictions
+
+Subagents can be limited to specific tools, reducing the risk of unintended actions. **Example:** a `doc-reviewer` subagent might only have access to Read and Grep tools, ensuring it can analyze but never accidentally modify your documentation files.
+
+##
+
+
+
+Creating subagents
+
+###
+
+
+
+Programmatic definition (recommended)
+
+Define subagents directly in your code using the `agents` parameter. This example creates two subagents: a code reviewer with read-only access and a test runner that can execute commands. The `Agent` tool must be included in `allowedTools` since Claude invokes subagents through the Agent tool.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
+
+ async def main():
+ async for message in query(
+ prompt="Review the authentication module for security issues",
+ options=ClaudeAgentOptions(
+ # Agent tool is required for subagent invocation
+ allowed_tools=["Read", "Grep", "Glob", "Agent"],
+ agents={
+ "code-reviewer": AgentDefinition(
+ # description tells Claude when to use this subagent
+ description="Expert code review specialist. Use for quality, security, and maintainability reviews.",
+ # prompt defines the subagent's behavior and expertise
+ prompt="""You are a code review specialist with expertise in security, performance, and best practices.
+
+ When reviewing code:
+ - Identify security vulnerabilities
+ - Check for performance issues
+ - Verify adherence to coding standards
+ - Suggest specific improvements
+
+ Be thorough but concise in your feedback.""",
+ # tools restricts what the subagent can do (read-only here)
+ tools=["Read", "Grep", "Glob"],
+ # model overrides the default model for this subagent
+ model="sonnet",
+ ),
+ "test-runner": AgentDefinition(
+ description="Runs and analyzes test suites. Use for test execution and coverage analysis.",
+ prompt="""You are a test execution specialist. Run tests and provide clear analysis of results.
+
+ Focus on:
+ - Running test commands
+ - Analyzing test output
+ - Identifying failing tests
+ - Suggesting fixes for failures""",
+ # Bash access lets this subagent run test commands
+ tools=["Bash", "Read", "Grep"],
+ ),
+ },
+ ),
+ ):
+ if hasattr(message, "result"):
+ print(message.result)
+
+ asyncio.run(main())
+
+###
+
+
+
+AgentDefinition configuration
+
+Field| Type| Required| Description
+---|---|---|---
+`description`| `string`| Yes| Natural language description of when to use this agent
+`prompt`| `string`| Yes| The agent’s system prompt defining its role and behavior
+`tools`| `string[]`| No| Array of allowed tool names. If omitted, inherits all tools
+`model`| `'sonnet' | 'opus' | 'haiku' | 'inherit'`| No| Model override for this agent. Defaults to main model if omitted
+`skills`| `string[]`| No| List of skill names available to this agent
+`memory`| `'user' | 'project' | 'local'`| No| Memory source for this agent (Python only)
+`mcpServers`| `(string | object)[]`| No| MCP servers available to this agent, by name or inline config
+
+Subagents cannot spawn their own subagents. Don’t include `Agent` in a subagent’s `tools` array.
+
+###
+
+
+
+Filesystem-based definition (alternative)
+
+You can also define subagents as markdown files in `.claude/agents/` directories. See the [Claude Code subagents documentation](</docs/en/sub-agents>) for details on this approach. Programmatically defined agents take precedence over filesystem-based agents with the same name.
+
+Even without defining custom subagents, Claude can spawn the built-in `general-purpose` subagent when `Agent` is in your `allowedTools`. This is useful for delegating research or exploration tasks without creating specialized agents.
+
+##
+
+
+
+What subagents inherit
+
+A subagent’s context window starts fresh (no parent conversation) but isn’t empty. The only channel from parent to subagent is the Agent tool’s prompt string, so include any file paths, error messages, or decisions the subagent needs directly in that prompt.
+
+The subagent receives| The subagent does not receive
+---|---
+Its own system prompt (`AgentDefinition.prompt`) and the Agent tool’s prompt| The parent’s conversation history or tool results
+Project CLAUDE.md (loaded via `settingSources`)| Skills (unless listed in `AgentDefinition.skills`)
+Tool definitions (inherited from parent, or the subset in `tools`)| The parent’s system prompt
+
+The parent receives the subagent’s final message verbatim as the Agent tool result, but may summarize it in its own response. To preserve subagent output verbatim in the user-facing response, include an instruction to do so in the prompt or `systemPrompt` option you pass to the **main** `query()` call.
+
+##
+
+
+
+Invoking subagents
+
+###
+
+
+
+Automatic invocation
+
+Claude automatically decides when to invoke subagents based on the task and each subagent’s `description`. For example, if you define a `performance-optimizer` subagent with the description “Performance optimization specialist for query tuning”, Claude will invoke it when your prompt mentions optimizing queries. Write clear, specific descriptions so Claude can match tasks to the right subagent.
+
+###
+
+
+
+Explicit invocation
+
+To guarantee Claude uses a specific subagent, mention it by name in your prompt:
+
+ "Use the code-reviewer agent to check the authentication module"
+
+This bypasses automatic matching and directly invokes the named subagent.
+
+###
+
+
+
+Dynamic agent configuration
+
+You can create agent definitions dynamically based on runtime conditions. This example creates a security reviewer with different strictness levels, using a more powerful model for strict reviews.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
+
+ # Factory function that returns an AgentDefinition
+ # This pattern lets you customize agents based on runtime conditions
+ def create_security_agent(security_level: str) -> AgentDefinition:
+ is_strict = security_level == "strict"
+ return AgentDefinition(
+ description="Security code reviewer",
+ # Customize the prompt based on strictness level
+ prompt=f"You are a {'strict' if is_strict else 'balanced'} security reviewer...",
+ tools=["Read", "Grep", "Glob"],
+ # Key insight: use a more capable model for high-stakes reviews
+ model="opus" if is_strict else "sonnet",
+ )
+
+ async def main():
+ # The agent is created at query time, so each request can use different settings
+ async for message in query(
+ prompt="Review this PR for security issues",
+ options=ClaudeAgentOptions(
+ allowed_tools=["Read", "Grep", "Glob", "Agent"],
+ agents={
+ # Call the factory with your desired configuration
+ "security-reviewer": create_security_agent("strict")
+ },
+ ),
+ ):
+ if hasattr(message, "result"):
+ print(message.result)
+
+ asyncio.run(main())
+
+##
+
+
+
+Detecting subagent invocation
+
+Subagents are invoked via the Agent tool. To detect when a subagent is invoked, check for `tool_use` blocks where `name` is `"Agent"`. Messages from within a subagent’s context include a `parent_tool_use_id` field.
+
+The tool name was renamed from `"Task"` to `"Agent"` in Claude Code v2.1.63. Current SDK releases emit `"Agent"` in `tool_use` blocks but still use `"Task"` in the `system:init` tools list and in `result.permission_denials[].tool_name`. Checking both values in `block.name` ensures compatibility across SDK versions.
+
+This example iterates through streamed messages, logging when a subagent is invoked and when subsequent messages originate from within that subagent’s execution context.
+
+The message structure differs between SDKs. In Python, content blocks are accessed directly via `message.content`. In TypeScript, `SDKAssistantMessage` wraps the Claude API message, so content is accessed via `message.message.content`.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
+
+ async def main():
+ async for message in query(
+ prompt="Use the code-reviewer agent to review this codebase",
+ options=ClaudeAgentOptions(
+ allowed_tools=["Read", "Glob", "Grep", "Agent"],
+ agents={
+ "code-reviewer": AgentDefinition(
+ description="Expert code reviewer.",
+ prompt="Analyze code quality and suggest improvements.",
+ tools=["Read", "Glob", "Grep"],
+ )
+ },
+ ),
+ ):
+ # Check for subagent invocation. Match both names: older SDK
+ # versions emitted "Task", current versions emit "Agent".
+ if hasattr(message, "content") and message.content:
+ for block in message.content:
+ if getattr(block, "type", None) == "tool_use" and block.name in (
+ "Task",
+ "Agent",
+ ):
+ print(f"Subagent invoked: {block.input.get('subagent_type')}")
+
+ # Check if this message is from within a subagent's context
+ if hasattr(message, "parent_tool_use_id") and message.parent_tool_use_id:
+ print(" (running inside subagent)")
+
+ if hasattr(message, "result"):
+ print(message.result)
+
+ asyncio.run(main())
+
+##
+
+
+
+Resuming subagents
+
+Subagents can be resumed to continue where they left off. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, Claude receives its agent ID in the Agent tool result. To resume a subagent programmatically:
+
+ 1. **Capture the session ID** : Extract `session_id` from messages during the first query
+ 2. **Extract the agent ID** : Parse `agentId` from the message content
+ 3. **Resume the session** : Pass `resume: sessionId` in the second query’s options, and include the agent ID in your prompt
+
+You must resume the same session to access the subagent’s transcript. Each `query()` call starts a new session by default, so pass `resume: sessionId` to continue in the same session.If you’re using a custom agent (not a built-in one), you also need to pass the same agent definition in the `agents` parameter for both queries.
+
+The example below demonstrates this flow: the first query runs a subagent and captures the session ID and agent ID, then the second query resumes the session to ask a follow-up question that requires context from the first analysis.
+
+TypeScript
+
+Python
+
+ import { query, type SDKMessage } from "@anthropic-ai/claude-agent-sdk";
+
+ // Helper to extract agentId from message content
+ // Stringify to avoid traversing different block types (TextBlock, ToolResultBlock, etc.)
+ function extractAgentId(message: SDKMessage): string | undefined {
+ if (!("message" in message)) return undefined;
+ // Stringify the content so we can search it without traversing nested blocks
+ const content = JSON.stringify(message.message.content);
+ const match = content.match(/agentId:\s*([a-f0-9-]+)/);
+ return match?.[1];
+ }
+
+ let agentId: string | undefined;
+ let sessionId: string | undefined;
+
+ // First invocation - use the Explore agent to find API endpoints
+ for await (const message of query({
+ prompt: "Use the Explore agent to find all API endpoints in this codebase",
+ options: { allowedTools: ["Read", "Grep", "Glob", "Agent"] }
+ })) {
+ // Capture session_id from ResultMessage (needed to resume this session)
+ if ("session_id" in message) sessionId = message.session_id;
+ // Search message content for the agentId (appears in Agent tool results)
+ const extractedId = extractAgentId(message);
+ if (extractedId) agentId = extractedId;
+ // Print the final result
+ if ("result" in message) console.log(message.result);
+ }
+
+ // Second invocation - resume and ask follow-up
+ if (agentId && sessionId) {
+ for await (const message of query({
+ prompt: `Resume agent ${agentId} and list the top 3 most complex endpoints`,
+ options: { allowedTools: ["Read", "Grep", "Glob", "Agent"], resume: sessionId }
+ })) {
+ if ("result" in message) console.log(message.result);
+ }
+ }
+
+Subagent transcripts persist independently of the main conversation:
+
+ * **Main conversation compaction** : When the main conversation compacts, subagent transcripts are unaffected. They’re stored in separate files.
+ * **Session persistence** : Subagent transcripts persist within their session. You can resume a subagent after restarting Claude Code by resuming the same session.
+ * **Automatic cleanup** : Transcripts are cleaned up based on the `cleanupPeriodDays` setting (default: 30 days).
+
+##
+
+
+
+Tool restrictions
+
+Subagents can have restricted tool access via the `tools` field:
+
+ * **Omit the field** : agent inherits all available tools (default)
+ * **Specify tools** : agent can only use listed tools
+
+This example creates a read-only analysis agent that can examine code but cannot modify files or run commands.
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
+
+ async def main():
+ async for message in query(
+ prompt="Analyze the architecture of this codebase",
+ options=ClaudeAgentOptions(
+ allowed_tools=["Read", "Grep", "Glob", "Agent"],
+ agents={
+ "code-analyzer": AgentDefinition(
+ description="Static code analysis and architecture review",
+ prompt="""You are a code architecture analyst. Analyze code structure,
+ identify patterns, and suggest improvements without making changes.""",
+ # Read-only tools: no Edit, Write, or Bash access
+ tools=["Read", "Grep", "Glob"],
+ )
+ },
+ ),
+ ):
+ if hasattr(message, "result"):
+ print(message.result)
+
+ asyncio.run(main())
+
+###
+
+
+
+Common tool combinations
+
+Use case| Tools| Description
+---|---|---
+Read-only analysis| `Read`, `Grep`, `Glob`| Can examine code but not modify or execute
+Test execution| `Bash`, `Read`, `Grep`| Can run commands and analyze output
+Code modification| `Read`, `Edit`, `Write`, `Grep`, `Glob`| Full read/write access without command execution
+Full access| All tools| Inherits all tools from parent (omit `tools` field)
+
+##
+
+
+
+Troubleshooting
+
+###
+
+
+
+Claude not delegating to subagents
+
+If Claude completes tasks directly instead of delegating to your subagent:
+
+ 1. **Include the Agent tool** : subagents are invoked via the Agent tool, so it must be in `allowedTools`
+ 2. **Use explicit prompting** : mention the subagent by name in your prompt (for example, “Use the code-reviewer agent to…”)
+ 3. **Write a clear description** : explain exactly when the subagent should be used so Claude can match tasks appropriately
+
+###
+
+
+
+Filesystem-based agents not loading
+
+Agents defined in `.claude/agents/` are loaded at startup only. If you create a new agent file while Claude Code is running, restart the session to load it.
+
+###
+
+
+
+Windows: long prompt failures
+
+On Windows, subagents with very long prompts may fail due to command line length limits (8191 chars). Keep prompts concise or use filesystem-based agents for complex instructions.
+
+##
+
+
+
+Related documentation
+
+ * [Claude Code subagents](</docs/en/sub-agents>): comprehensive subagent documentation including filesystem-based definitions
+ * [SDK overview](</docs/en/agent-sdk/overview>): getting started with the Claude Agent SDK
Show diff (134 lines)
--- a/todo-tracking.md
+++ b/todo-tracking.md
@@ -0,0 +1,131 @@
+Todo tracking provides a structured way to manage tasks and display progress to users. The Claude Agent SDK includes built-in todo functionality that helps organize complex workflows and keep users informed about task progression.
+
+###
+
+
+
+Todo Lifecycle
+
+Todos follow a predictable lifecycle:
+
+ 1. **Created** as `pending` when tasks are identified
+ 2. **Activated** to `in_progress` when work begins
+ 3. **Completed** when the task finishes successfully
+ 4. **Removed** when all tasks in a group are completed
+
+###
+
+
+
+When Todos Are Used
+
+The SDK automatically creates todos for:
+
+ * **Complex multi-step tasks** requiring 3 or more distinct actions
+ * **User-provided task lists** when multiple items are mentioned
+ * **Non-trivial operations** that benefit from progress tracking
+ * **Explicit requests** when users ask for todo organization
+
+##
+
+
+
+Examples
+
+###
+
+
+
+Monitoring Todo Changes
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Optimize my React app performance and track progress with todos",
+ options: { maxTurns: 15 }
+ })) {
+ // Todo updates are reflected in the message stream
+ if (message.type === "assistant") {
+ for (const block of message.message.content) {
+ if (block.type === "tool_use" && block.name === "TodoWrite") {
+ const todos = block.input.todos;
+
+ console.log("Todo Status Update:");
+ todos.forEach((todo, index) => {
+ const status =
+ todo.status === "completed" ? "✅" : todo.status === "in_progress" ? "🔧" : "❌";
+ console.log(`${index + 1}. ${status} ${todo.content}`);
+ });
+ }
+ }
+ }
+ }
+
+###
+
+
+
+Real-time Progress Display
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ class TodoTracker {
+ private todos: any[] = [];
+
+ displayProgress() {
+ if (this.todos.length === 0) return;
+
+ const completed = this.todos.filter((t) => t.status === "completed").length;
+ const inProgress = this.todos.filter((t) => t.status === "in_progress").length;
+ const total = this.todos.length;
+
+ console.log(`\nProgress: ${completed}/${total} completed`);
+ console.log(`Currently working on: ${inProgress} task(s)\n`);
+
+ this.todos.forEach((todo, index) => {
+ const icon =
+ todo.status === "completed" ? "✅" : todo.status === "in_progress" ? "🔧" : "❌";
+ const text = todo.status === "in_progress" ? todo.activeForm : todo.content;
+ console.log(`${index + 1}. ${icon} ${text}`);
+ });
+ }
+
+ async trackQuery(prompt: string) {
+ for await (const message of query({
+ prompt,
+ options: { maxTurns: 20 }
+ })) {
+ if (message.type === "assistant") {
+ for (const block of message.message.content) {
+ if (block.type === "tool_use" && block.name === "TodoWrite") {
+ this.todos = block.input.todos;
+ this.displayProgress();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Usage
+ const tracker = new TodoTracker();
+ await tracker.trackQuery("Build a complete authentication system with todos");
+
+##
+
+
+
+Related Documentation
+
+ * [TypeScript SDK Reference](</docs/en/agent-sdk/typescript>)
+ * [Python SDK Reference](</docs/en/agent-sdk/python>)
+ * [Streaming vs Single Mode](</docs/en/agent-sdk/streaming-vs-single-mode>)
+ * [Custom Tools](</docs/en/agent-sdk/custom-tools>)
--- a/tool-search.md
+++ b/tool-search.md
@@ -0,0 +1,95 @@
+Tool search enables your agent to work with hundreds or thousands of tools by dynamically discovering and loading them on demand. Instead of loading all tool definitions into the context window upfront, the agent searches your tool catalog and loads only the tools it needs. This approach solves two challenges as tool libraries scale:
+
+ * **Context efficiency:** Tool definitions can consume large portions of the context window (50 tools can use 10-20K tokens), leaving less room for actual work.
+ * **Tool selection accuracy:** Tool selection accuracy degrades with more than 30-50 tools loaded at once.
+
+Tool search is enabled by default. This page covers how it works, how to configure it, and how to optimize tool discovery.
+
+##
+
+
+
+How tool search works
+
+When tool search is active, tool definitions are withheld from the context window. The agent receives a summary of available tools and searches for relevant ones when the task requires a capability not already loaded. The 3-5 most relevant tools are loaded into context, where they stay available for subsequent turns. If the conversation is long enough that the SDK compacts earlier messages to free space, previously discovered tools may be removed, and the agent searches again as needed. Tool search adds one extra round-trip the first time Claude discovers a tool (the search step), but for large tool sets this is offset by smaller context on every turn. With fewer than ~10 tools, loading everything upfront is typically faster. For details on the underlying API mechanism, see [Tool search in the API](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool>).
+
+Tool search requires Claude Sonnet 4 or later, or Claude Opus 4 or later. Haiku models do not support tool search.
+
+##
+
+
+
+Configure tool search
+
+By default, tool search is always on. You can change this with the `ENABLE_TOOL_SEARCH` environment variable:
+
+Value| Behavior
+---|---
+(unset)| Tool search is always on. Tool definitions are never loaded into context. This is the default.
+`true`| Same as unset.
+`auto`| Checks the combined token count of all tool definitions against the model’s context window. If they exceed 10%, tool search activates. If they’re under 10%, all tools are loaded into context normally.
+`auto:N`| Same as `auto` with a custom percentage. `auto:5` activates when tool definitions exceed 5% of the context window. Lower values activate sooner.
+`false`| Tool search is off. All tool definitions are loaded into context on every turn.
+
+Tool search applies to all registered tools, whether they come from remote MCP servers or [custom SDK MCP servers](</docs/en/agent-sdk/custom-tools>). When using `auto`, the threshold is based on the combined size of all tool definitions across all servers. Set the value in the `env` option on `query()`. This example connects to a remote MCP server that exposes many tools, pre-approves all of them with a wildcard, and uses `auto:5` so tool search activates when their definitions exceed 5% of the context window:
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Find and run the appropriate database query",
+ options: {
+ mcpServers: {
+ "enterprise-tools": {
+ // Connect to a remote MCP server
+ type: "http",
+ url: "https://tools.example.com/mcp"
+ }
+ },
+ allowedTools: ["mcp__enterprise-tools__*"], // Wildcard pre-approves all tools from this server
+ env: {
+ ENABLE_TOOL_SEARCH: "auto:5" // Activate tool search when tools exceed 5% of context
+ }
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success") {
+ console.log(message.result);
+ }
+ }
+
+Setting `ENABLE_TOOL_SEARCH` to `"false"` disables tool search and loads all tool definitions into context on every turn. This removes the search round-trip, which can be faster when the tool set is small (fewer than ~10 tools) and the definitions fit comfortably in the context window.
+
+##
+
+
+
+Optimize tool discovery
+
+The search mechanism matches queries against tool names and descriptions. Names like `search_slack_messages` surface for a wider range of requests than `query_slack`. Descriptions with specific keywords (“Search Slack messages by keyword, channel, or date range”) match more queries than generic ones (“Query Slack”). You can also add a system prompt section listing available tool categories. This gives the agent context about what kinds of tools are available to search for:
+
+ You can search for tools to interact with Slack, GitHub, and Jira.
+
+##
+
+
+
+Limits
+
+ * **Maximum tools:** 10,000 tools in your catalog
+ * **Search results:** Returns 3-5 most relevant tools per search
+ * **Model support:** Claude Sonnet 4 and later, Claude Opus 4 and later (no Haiku)
+
+##
+
+
+
+Related documentation
+
+ * [Tool search in the API](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool>): Full API documentation for tool search, including custom implementations
+ * [Connect MCP servers](</docs/en/agent-sdk/mcp>): Connect to external tools via MCP servers
+ * [Custom tools](</docs/en/agent-sdk/custom-tools>): Build your own tools with SDK MCP servers
+ * [TypeScript SDK reference](</docs/en/agent-sdk/typescript>): Full API reference
+ * [Python SDK reference](</docs/en/agent-sdk/python>): Full API reference
--- a/troubleshooting.md
+++ b/troubleshooting.md
@@ -271,6 +271,11 @@
export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem
Ask your IT team for the certificate file if you don’t have it. You can also try on a direct connection to confirm the proxy is the cause.
+ 4. **On Windows, bypass certificate revocation checks** if you see `CRYPT_E_REVOCATION_OFFLINE (0x80092013)`. This means curl reached the server but your network blocks the certificate revocation lookup, which is common behind corporate firewalls. Add `--ssl-revoke-best-effort` to the install command:
+
+ curl --ssl-revoke-best-effort -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
+
+Alternatively, install with `winget install Anthropic.ClaudeCode`, which avoids curl entirely.
###
@@ -676,6 +681,19 @@
1. Use `/compact` regularly to reduce context size
2. Close and restart Claude Code between major tasks
3. Consider adding large build directories to your `.gitignore` file
+
+###
+
+
+
+Auto-compaction stops with a thrashing error
+
+If you see `Autocompact is thrashing: the context refilled to the limit...`, automatic compaction succeeded but a file or tool output immediately refilled the context window several times in a row. Claude Code stops retrying to avoid wasting API calls on a loop that isn’t making progress. To recover:
+
+ 1. Ask Claude to read the oversized file in smaller chunks, such as a specific line range or function, instead of the whole file
+ 2. Run `/compact` with a focus that drops the large output, for example `/compact keep only the plan and the diff`
+ 3. Move the large-file work to a [subagent](</docs/en/sub-agents>) so it runs in a separate context window
+ 4. Run `/clear` if the earlier conversation is no longer needed
###
Show diff (3145 lines)
--- a/typescript.md
+++ b/typescript.md
@@ -0,0 +1,3142 @@
+**Try the new V2 interface (preview):** A simplified interface with `send()` and `stream()` patterns is now available, making multi-turn conversations easier. [Learn more about the TypeScript V2 preview](</docs/en/agent-sdk/typescript-v2-preview>)
+
+##
+
+
+
+Installation
+
+ npm install @anthropic-ai/claude-agent-sdk
+
+##
+
+
+
+Functions
+
+###
+
+
+
+`query()`
+
+The primary function for interacting with Claude Code. Creates an async generator that streams messages as they arrive.
+
+ function query({
+ prompt,
+ options
+ }: {
+ prompt: string | AsyncIterable<SDKUserMessage>;
+ options?: Options;
+ }): Query;
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Description
+---|---|---
+`prompt`| `string | AsyncIterable<``SDKUserMessage``>`| The input prompt as a string or async iterable for streaming mode
+`options`| `Options`| Optional configuration object (see Options type below)
+
+####
+
+
+
+Returns
+
+Returns a `Query` object that extends `AsyncGenerator<``SDKMessage``, void>` with additional methods.
+
+###
+
+
+
+`tool()`
+
+Creates a type-safe MCP tool definition for use with SDK MCP servers.
+
+ function tool<Schema extends AnyZodRawShape>(
+ name: string,
+ description: string,
+ inputSchema: Schema,
+ handler: (args: InferShape<Schema>, extra: unknown) => Promise<CallToolResult>,
+ extras?: { annotations?: ToolAnnotations }
+ ): SdkMcpToolDefinition<Schema>;
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Description
+---|---|---
+`name`| `string`| The name of the tool
+`description`| `string`| A description of what the tool does
+`inputSchema`| `Schema extends AnyZodRawShape`| Zod schema defining the tool’s input parameters (supports both Zod 3 and Zod 4)
+`handler`| `(args, extra) => Promise<``CallToolResult``>`| Async function that executes the tool logic
+`extras`| `{ annotations?: ``ToolAnnotations`` }`| Optional MCP tool annotations providing behavioral hints to clients
+
+####
+
+
+
+`ToolAnnotations`
+
+Re-exported from `@modelcontextprotocol/sdk/types.js`. All fields are optional hints; clients should not rely on them for security decisions.
+
+Field| Type| Default| Description
+---|---|---|---
+`title`| `string`| `undefined`| Human-readable title for the tool
+`readOnlyHint`| `boolean`| `false`| If `true`, the tool does not modify its environment
+`destructiveHint`| `boolean`| `true`| If `true`, the tool may perform destructive updates (only meaningful when `readOnlyHint` is `false`)
+`idempotentHint`| `boolean`| `false`| If `true`, repeated calls with the same arguments have no additional effect (only meaningful when `readOnlyHint` is `false`)
+`openWorldHint`| `boolean`| `true`| If `true`, the tool interacts with external entities (for example, web search). If `false`, the tool’s domain is closed (for example, a memory tool)
+
+ import { tool } from "@anthropic-ai/claude-agent-sdk";
+ import { z } from "zod";
+
+ const searchTool = tool(
+ "search",
+ "Search the web",
+ { query: z.string() },
+ async ({ query }) => {
+ return { content: [{ type: "text", text: `Results for: ${query}` }] };
+ },
+ { annotations: { readOnlyHint: true, openWorldHint: true } }
+ );
+
+###
+
+
+
+`createSdkMcpServer()`
+
+Creates an MCP server instance that runs in the same process as your application.
+
+ function createSdkMcpServer(options: {
+ name: string;
+ version?: string;
+ tools?: Array<SdkMcpToolDefinition<any>>;
+ }): McpSdkServerConfigWithInstance;
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Description
+---|---|---
+`options.name`| `string`| The name of the MCP server
+`options.version`| `string`| Optional version string
+`options.tools`| `Array<SdkMcpToolDefinition>`| Array of tool definitions created with `tool()`
+
+###
+
+
+
+`listSessions()`
+
+Discovers and lists past sessions with light metadata. Filter by project directory or list sessions across all projects.
+
+ function listSessions(options?: ListSessionsOptions): Promise<SDKSessionInfo[]>;
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`options.dir`| `string`| `undefined`| Directory to list sessions for. When omitted, returns sessions across all projects
+`options.limit`| `number`| `undefined`| Maximum number of sessions to return
+`options.includeWorktrees`| `boolean`| `true`| When `dir` is inside a git repository, include sessions from all worktree paths
+
+####
+
+
+
+Return type: `SDKSessionInfo`
+
+Property| Type| Description
+---|---|---
+`sessionId`| `string`| Unique session identifier (UUID)
+`summary`| `string`| Display title: custom title, auto-generated summary, or first prompt
+`lastModified`| `number`| Last modified time in milliseconds since epoch
+`fileSize`| `number | undefined`| Session file size in bytes. Only populated for local JSONL storage
+`customTitle`| `string | undefined`| User-set session title (via `/rename`)
+`firstPrompt`| `string | undefined`| First meaningful user prompt in the session
+`gitBranch`| `string | undefined`| Git branch at the end of the session
+`cwd`| `string | undefined`| Working directory for the session
+`tag`| `string | undefined`| User-set session tag (see `tagSession()`)
+`createdAt`| `number | undefined`| Creation time in milliseconds since epoch, from the first entry’s timestamp
+
+####
+
+
+
+Example
+
+Print the 10 most recent sessions for a project. Results are sorted by `lastModified` descending, so the first item is the newest. Omit `dir` to search across all projects.
+
+ import { listSessions } from "@anthropic-ai/claude-agent-sdk";
+
+ const sessions = await listSessions({ dir: "/path/to/project", limit: 10 });
+
+ for (const session of sessions) {
+ console.log(`${session.summary} (${session.sessionId})`);
+ }
+
+###
+
+
+
+`getSessionMessages()`
+
+Reads user and assistant messages from a past session transcript.
+
+ function getSessionMessages(
+ sessionId: string,
+ options?: GetSessionMessagesOptions
+ ): Promise<SessionMessage[]>;
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`sessionId`| `string`| required| Session UUID to read (see `listSessions()`)
+`options.dir`| `string`| `undefined`| Project directory to find the session in. When omitted, searches all projects
+`options.limit`| `number`| `undefined`| Maximum number of messages to return
+`options.offset`| `number`| `undefined`| Number of messages to skip from the start
+
+####
+
+
+
+Return type: `SessionMessage`
+
+Property| Type| Description
+---|---|---
+`type`| `"user" | "assistant"`| Message role
+`uuid`| `string`| Unique message identifier
+`session_id`| `string`| Session this message belongs to
+`message`| `unknown`| Raw message payload from the transcript
+`parent_tool_use_id`| `null`| Reserved
+
+####
+
+
+
+Example
+
+ import { listSessions, getSessionMessages } from "@anthropic-ai/claude-agent-sdk";
+
+ const [latest] = await listSessions({ dir: "/path/to/project", limit: 1 });
+
+ if (latest) {
+ const messages = await getSessionMessages(latest.sessionId, {
+ dir: "/path/to/project",
+ limit: 20
+ });
+
+ for (const msg of messages) {
+ console.log(`[${msg.type}] ${msg.uuid}`);
+ }
+ }
+
+###
+
+
+
+`getSessionInfo()`
+
+Reads metadata for a single session by ID without scanning the full project directory.
+
+ function getSessionInfo(
+ sessionId: string,
+ options?: GetSessionInfoOptions
+ ): Promise<SDKSessionInfo | undefined>;
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`sessionId`| `string`| required| UUID of the session to look up
+`options.dir`| `string`| `undefined`| Project directory path. When omitted, searches all project directories
+
+Returns `SDKSessionInfo`, or `undefined` if the session is not found.
+
+###
+
+
+
+`renameSession()`
+
+Renames a session by appending a custom-title entry. Repeated calls are safe; the most recent title wins.
+
+ function renameSession(
+ sessionId: string,
+ title: string,
+ options?: SessionMutationOptions
+ ): Promise<void>;
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`sessionId`| `string`| required| UUID of the session to rename
+`title`| `string`| required| New title. Must be non-empty after trimming whitespace
+`options.dir`| `string`| `undefined`| Project directory path. When omitted, searches all project directories
+
+###
+
+
+
+`tagSession()`
+
+Tags a session. Pass `null` to clear the tag. Repeated calls are safe; the most recent tag wins.
+
+ function tagSession(
+ sessionId: string,
+ tag: string | null,
+ options?: SessionMutationOptions
+ ): Promise<void>;
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`sessionId`| `string`| required| UUID of the session to tag
+`tag`| `string | null`| required| Tag string, or `null` to clear
+`options.dir`| `string`| `undefined`| Project directory path. When omitted, searches all project directories
+
+##
+
+
+
+Types
+
+###
+
+
+
+`Options`
+
+Configuration object for the `query()` function.
+
+Property| Type| Default| Description
+---|---|---|---
+`abortController`| `AbortController`| `new AbortController()`| Controller for cancelling operations
+`additionalDirectories`| `string[]`| `[]`| Additional directories Claude can access
+`agent`| `string`| `undefined`| Agent name for the main thread. The agent must be defined in the `agents` option or in settings
+`agents`| `Record<string, [`AgentDefinition`](#agent-definition)>`| `undefined`| Programmatically define subagents
+`allowDangerouslySkipPermissions`| `boolean`| `false`| Enable bypassing permissions. Required when using `permissionMode: 'bypassPermissions'`
+`allowedTools`| `string[]`| `[]`| Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permissionMode` and `canUseTool`. Use `disallowedTools` to block tools. See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
+`betas`| `SdkBeta``[]`| `[]`| Enable beta features
+`canUseTool`| `CanUseTool`| `undefined`| Custom permission function for tool usage
+`continue`| `boolean`| `false`| Continue the most recent conversation
+`cwd`| `string`| `process.cwd()`| Current working directory
+`debug`| `boolean`| `false`| Enable debug mode for the Claude Code process
+`debugFile`| `string`| `undefined`| Write debug logs to a specific file path. Implicitly enables debug mode
+`disallowedTools`| `string[]`| `[]`| Tools to always deny. Deny rules are checked first and override `allowedTools` and `permissionMode` (including `bypassPermissions`)
+`effort`| `'low' | 'medium' | 'high' | 'max'`| `'high'`| Controls how much effort Claude puts into its response. Works with adaptive thinking to guide thinking depth
+`enableFileCheckpointing`| `boolean`| `false`| Enable file change tracking for rewinding. See [File checkpointing](</docs/en/agent-sdk/file-checkpointing>)
+`env`| `Record<string, string | undefined>`| `process.env`| Environment variables. Set `CLAUDE_AGENT_SDK_CLIENT_APP` to identify your app in the User-Agent header
+`executable`| `'bun' | 'deno' | 'node'`| Auto-detected| JavaScript runtime to use
+`executableArgs`| `string[]`| `[]`| Arguments to pass to the executable
+`extraArgs`| `Record<string, string | null>`| `{}`| Additional arguments
+`fallbackModel`| `string`| `undefined`| Model to use if primary fails
+`forkSession`| `boolean`| `false`| When resuming with `resume`, fork to a new session ID instead of continuing the original session
+`hooks`| `Partial<Record<``HookEvent``, ``HookCallbackMatcher``[]>>`| `{}`| Hook callbacks for events
+`includePartialMessages`| `boolean`| `false`| Include partial message events
+`maxBudgetUsd`| `number`| `undefined`| Maximum budget in USD for the query
+`maxThinkingTokens`| `number`| `undefined`| _Deprecated:_ Use `thinking` instead. Maximum tokens for thinking process
+`maxTurns`| `number`| `undefined`| Maximum agentic turns (tool-use round trips)
+`mcpServers`| `Record<string, [`McpServerConfig`](#mcp-server-config)>`| `{}`| MCP server configurations
+`model`| `string`| Default from CLI| Claude model to use
+`outputFormat`| `{ type: 'json_schema', schema: JSONSchema }`| `undefined`| Define output format for agent results. See [Structured outputs](</docs/en/agent-sdk/structured-outputs>) for details
+`pathToClaudeCodeExecutable`| `string`| Uses built-in executable| Path to Claude Code executable
+`permissionMode`| `PermissionMode`| `'default'`| Permission mode for the session
+`permissionPromptToolName`| `string`| `undefined`| MCP tool name for permission prompts
+`persistSession`| `boolean`| `true`| When `false`, disables session persistence to disk. Sessions cannot be resumed later
+`plugins`| `SdkPluginConfig``[]`| `[]`| Load custom plugins from local paths. See [Plugins](</docs/en/agent-sdk/plugins>) for details
+`promptSuggestions`| `boolean`| `false`| Enable prompt suggestions. Emits a `prompt_suggestion` message after each turn with a predicted next user prompt
+`resume`| `string`| `undefined`| Session ID to resume
+`resumeSessionAt`| `string`| `undefined`| Resume session at a specific message UUID
+`sandbox`| `SandboxSettings`| `undefined`| Configure sandbox behavior programmatically. See Sandbox settings for details
+`sessionId`| `string`| Auto-generated| Use a specific UUID for the session instead of auto-generating one
+`settingSources`| `SettingSource``[]`| `[]` (no settings)| Control which filesystem settings to load. When omitted, no settings are loaded. **Note:** Must include `'project'` to load CLAUDE.md files
+`spawnClaudeCodeProcess`| `(options: SpawnOptions) => SpawnedProcess`| `undefined`| Custom function to spawn the Claude Code process. Use to run Claude Code in VMs, containers, or remote environments
+`stderr`| `(data: string) => void`| `undefined`| Callback for stderr output
+`strictMcpConfig`| `boolean`| `false`| Enforce strict MCP validation
+`systemPrompt`| `string | { type: 'preset'; preset: 'claude_code'; append?: string }`| `undefined` (minimal prompt)| System prompt configuration. Pass a string for custom prompt, or `{ type: 'preset', preset: 'claude_code' }` to use Claude Code’s system prompt. When using the preset object form, add `append` to extend the system prompt with additional instructions
+`thinking`| `ThinkingConfig`| `{ type: 'adaptive' }` for supported models| Controls Claude’s thinking/reasoning behavior. See `ThinkingConfig` for options
+`toolConfig`| `ToolConfig`| `undefined`| Configuration for built-in tool behavior. See `ToolConfig` for details
+`tools`| `string[] | { type: 'preset'; preset: 'claude_code' }`| `undefined`| Tool configuration. Pass an array of tool names or use the preset to get Claude Code’s default tools
+
+###
+
+
+
+`Query` object
+
+Interface returned by the `query()` function.
+
+ interface Query extends AsyncGenerator<SDKMessage, void> {
+ interrupt(): Promise<void>;
+ rewindFiles(
+ userMessageId: string,
+ options?: { dryRun?: boolean }
+ ): Promise<RewindFilesResult>;
+ setPermissionMode(mode: PermissionMode): Promise<void>;
+ setModel(model?: string): Promise<void>;
+ setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;
+ initializationResult(): Promise<SDKControlInitializeResponse>;
+ supportedCommands(): Promise<SlashCommand[]>;
+ supportedModels(): Promise<ModelInfo[]>;
+ supportedAgents(): Promise<AgentInfo[]>;
+ mcpServerStatus(): Promise<McpServerStatus[]>;
+ accountInfo(): Promise<AccountInfo>;
+ reconnectMcpServer(serverName: string): Promise<void>;
+ toggleMcpServer(serverName: string, enabled: boolean): Promise<void>;
+ setMcpServers(servers: Record<string, McpServerConfig>): Promise<McpSetServersResult>;
+ streamInput(stream: AsyncIterable<SDKUserMessage>): Promise<void>;
+ stopTask(taskId: string): Promise<void>;
+ close(): void;
+ }
+
+####
+
+
+
+Methods
+
+Method| Description
+---|---
+`interrupt()`| Interrupts the query (only available in streaming input mode)
+`rewindFiles(userMessageId, options?)`| Restores files to their state at the specified user message. Pass `{ dryRun: true }` to preview changes. Requires `enableFileCheckpointing: true`. See [File checkpointing](</docs/en/agent-sdk/file-checkpointing>)
+`setPermissionMode()`| Changes the permission mode (only available in streaming input mode)
+`setModel()`| Changes the model (only available in streaming input mode)
+`setMaxThinkingTokens()`| _Deprecated:_ Use the `thinking` option instead. Changes the maximum thinking tokens
+`initializationResult()`| Returns the full initialization result including supported commands, models, account info, and output style configuration
+`supportedCommands()`| Returns available slash commands
+`supportedModels()`| Returns available models with display info
+`supportedAgents()`| Returns available subagents as `AgentInfo``[]`
+`mcpServerStatus()`| Returns status of connected MCP servers
+`accountInfo()`| Returns account information
+`reconnectMcpServer(serverName)`| Reconnect an MCP server by name
+`toggleMcpServer(serverName, enabled)`| Enable or disable an MCP server by name
+`setMcpServers(servers)`| Dynamically replace the set of MCP servers for this session. Returns info about which servers were added, removed, and any errors
+`streamInput(stream)`| Stream input messages to the query for multi-turn conversations
+`stopTask(taskId)`| Stop a running background task by ID
+`close()`| Close the query and terminate the underlying process. Forcefully ends the query and cleans up all resources
+
+###
+
+
+
+`SDKControlInitializeResponse`
+
+Return type of `initializationResult()`. Contains session initialization data.
+
+ type SDKControlInitializeResponse = {
+ commands: SlashCommand[];
+ agents: AgentInfo[];
+ output_style: string;
+ available_output_styles: string[];
+ models: ModelInfo[];
+ account: AccountInfo;
+ fast_mode_state?: "off" | "cooldown" | "on";
+ };
+
+###
+
+
+
+`AgentDefinition`
+
+Configuration for a subagent defined programmatically.
+
+ type AgentDefinition = {
+ description: string;
+ tools?: string[];
+ disallowedTools?: string[];
+ prompt: string;
+ model?: "sonnet" | "opus" | "haiku" | "inherit";
+ mcpServers?: AgentMcpServerSpec[];
+ skills?: string[];
+ maxTurns?: number;
+ criticalSystemReminder_EXPERIMENTAL?: string;
+ };
+
+Field| Required| Description
+---|---|---
+`description`| Yes| Natural language description of when to use this agent
+`tools`| No| Array of allowed tool names. If omitted, inherits all tools from parent
+`disallowedTools`| No| Array of tool names to explicitly disallow for this agent
+`prompt`| Yes| The agent’s system prompt
+`model`| No| Model override for this agent. If omitted or `'inherit'`, uses the main model
+`mcpServers`| No| MCP server specifications for this agent
+`skills`| No| Array of skill names to preload into the agent context
+`maxTurns`| No| Maximum number of agentic turns (API round-trips) before stopping
+`criticalSystemReminder_EXPERIMENTAL`| No| Experimental: Critical reminder added to the system prompt
+
+###
+
+
+
+`AgentMcpServerSpec`
+
+Specifies MCP servers available to a subagent. Can be a server name (string referencing a server from the parent’s `mcpServers` config) or an inline server configuration record mapping server names to configs.
+
+ type AgentMcpServerSpec = string | Record<string, McpServerConfigForProcessTransport>;
+
+Where `McpServerConfigForProcessTransport` is `McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig`.
+
+###
+
+
+
+`SettingSource`
+
+Controls which filesystem-based configuration sources the SDK loads settings from.
+
+ type SettingSource = "user" | "project" | "local";
+
+Value| Description| Location
+---|---|---
+`'user'`| Global user settings| `~/.claude/settings.json`
+`'project'`| Shared project settings (version controlled)| `.claude/settings.json`
+`'local'`| Local project settings (gitignored)| `.claude/settings.local.json`
+
+####
+
+
+
+Default behavior
+
+When `settingSources` is **omitted** or **undefined** , the SDK does **not** load any filesystem settings. This provides isolation for SDK applications.
+
+####
+
+
+
+Why use settingSources
+
+**Load all filesystem settings (legacy behavior):**
+
+ // Load all settings like SDK v0.0.x did
+ const result = query({
+ prompt: "Analyze this code",
+ options: {
+ settingSources: ["user", "project", "local"] // Load all settings
+ }
+ });
+
+**Load only specific setting sources:**
+
+ // Load only project settings, ignore user and local
+ const result = query({
+ prompt: "Run CI checks",
+ options: {
+ settingSources: ["project"] // Only .claude/settings.json
+ }
+ });
+
+**Testing and CI environments:**
+
+ // Ensure consistent behavior in CI by excluding local settings
+ const result = query({
+ prompt: "Run tests",
+ options: {
+ settingSources: ["project"], // Only team-shared settings
+ permissionMode: "bypassPermissions"
+ }
+ });
+
+**SDK-only applications:**
+
+ // Define everything programmatically (default behavior)
+ // No filesystem dependencies - settingSources defaults to []
+ const result = query({
+ prompt: "Review this PR",
+ options: {
+ // settingSources: [] is the default, no need to specify
+ agents: {
+ /* ... */
+ },
+ mcpServers: {
+ /* ... */
+ },
+ allowedTools: ["Read", "Grep", "Glob"]
+ }
+ });
+
+**Loading CLAUDE.md project instructions:**
+
+ // Load project settings to include CLAUDE.md files
+ const result = query({
+ prompt: "Add a new feature following project conventions",
+ options: {
+ systemPrompt: {
+ type: "preset",
+ preset: "claude_code" // Required to use CLAUDE.md
+ },
+ settingSources: ["project"], // Loads CLAUDE.md from project directory
+ allowedTools: ["Read", "Write", "Edit"]
+ }
+ });
+
+####
+
+
+
+Settings precedence
+
+When multiple sources are loaded, settings are merged with this precedence (highest to lowest):
+
+ 1. Local settings (`.claude/settings.local.json`)
+ 2. Project settings (`.claude/settings.json`)
+ 3. User settings (`~/.claude/settings.json`)
+
+Programmatic options (like `agents`, `allowedTools`) always override filesystem settings.
+
+###
+
+
+
+`PermissionMode`
+
+ type PermissionMode =
+ | "default" // Standard permission behavior
+ | "acceptEdits" // Auto-accept file edits
+ | "bypassPermissions" // Bypass all permission checks
+ | "plan" // Planning mode - no execution
+ | "dontAsk" // Don't prompt for permissions, deny if not pre-approved
+ | "auto"; // Use a model classifier to approve or deny each tool call
+
+###
+
+
+
+`CanUseTool`
+
+Custom permission function type for controlling tool usage.
+
+ type CanUseTool = (
+ toolName: string,
+ input: Record<string, unknown>,
+ options: {
+ signal: AbortSignal;
+ suggestions?: PermissionUpdate[];
+ blockedPath?: string;
+ decisionReason?: string;
+ toolUseID: string;
+ agentID?: string;
+ }
+ ) => Promise<PermissionResult>;
+
+Option| Type| Description
+---|---|---
+`signal`| `AbortSignal`| Signaled if the operation should be aborted
+`suggestions`| `PermissionUpdate``[]`| Suggested permission updates so the user is not prompted again for this tool
+`blockedPath`| `string`| The file path that triggered the permission request, if applicable
+`decisionReason`| `string`| Explains why this permission request was triggered
+`toolUseID`| `string`| Unique identifier for this specific tool call within the assistant message
+`agentID`| `string`| If running within a sub-agent, the sub-agent’s ID
+
+###
+
+
+
+`PermissionResult`
+
+Result of a permission check.
+
+ type PermissionResult =
+ | {
+ behavior: "allow";
+ updatedInput?: Record<string, unknown>;
+ updatedPermissions?: PermissionUpdate[];
+ toolUseID?: string;
+ }
+ | {
+ behavior: "deny";
+ message: string;
+ interrupt?: boolean;
+ toolUseID?: string;
+ };
+
+###
+
+
+
+`ToolConfig`
+
+Configuration for built-in tool behavior.
+
+ type ToolConfig = {
+ askUserQuestion?: {
+ previewFormat?: "markdown" | "html";
+ };
+ };
+
+Field| Type| Description
+---|---|---
+`askUserQuestion.previewFormat`| `'markdown' | 'html'`| Opts into the `preview` field on [`AskUserQuestion`](</docs/en/agent-sdk/user-input#question-format>) options and sets its content format. When unset, Claude does not emit previews
+
+###
+
+
+
+`McpServerConfig`
+
+Configuration for MCP servers.
+
+ type McpServerConfig =
+ | McpStdioServerConfig
+ | McpSSEServerConfig
+ | McpHttpServerConfig
+ | McpSdkServerConfigWithInstance;
+
+####
+
+
+
+`McpStdioServerConfig`
+
+ type McpStdioServerConfig = {
+ type?: "stdio";
+ command: string;
+ args?: string[];
+ env?: Record<string, string>;
+ };
+
+####
+
+
+
+`McpSSEServerConfig`
+
+ type McpSSEServerConfig = {
+ type: "sse";
+ url: string;
+ headers?: Record<string, string>;
+ };
+
+####
+
+
+
+`McpHttpServerConfig`
+
+ type McpHttpServerConfig = {
+ type: "http";
+ url: string;
+ headers?: Record<string, string>;
+ };
+
+####
+
+
+
+`McpSdkServerConfigWithInstance`
+
+ type McpSdkServerConfigWithInstance = {
+ type: "sdk";
+ name: string;
+ instance: McpServer;
+ };
+
+####
+
+
+
+`McpClaudeAIProxyServerConfig`
+
+ type McpClaudeAIProxyServerConfig = {
+ type: "claudeai-proxy";
+ url: string;
+ id: string;
+ };
+
+###
+
+
+
+`SdkPluginConfig`
+
+Configuration for loading plugins in the SDK.
+
+ type SdkPluginConfig = {
+ type: "local";
+ path: string;
+ };
+
+Field| Type| Description
+---|---|---
+`type`| `'local'`| Must be `'local'` (only local plugins currently supported)
+`path`| `string`| Absolute or relative path to the plugin directory
+
+**Example:**
+
+ plugins: [
+ { type: "local", path: "./my-plugin" },
+ { type: "local", path: "/absolute/path/to/plugin" }
+ ];
+
+For complete information on creating and using plugins, see [Plugins](</docs/en/agent-sdk/plugins>).
+
+##
+
+
+
+Message Types
+
+###
+
+
+
+`SDKMessage`
+
+Union type of all possible messages returned by the query.
+
+ type SDKMessage =
+ | SDKAssistantMessage
+ | SDKUserMessage
+ | SDKUserMessageReplay
+ | SDKResultMessage
+ | SDKSystemMessage
+ | SDKPartialAssistantMessage
+ | SDKCompactBoundaryMessage
+ | SDKStatusMessage
+ | SDKLocalCommandOutputMessage
+ | SDKHookStartedMessage
+ | SDKHookProgressMessage
+ | SDKHookResponseMessage
+ | SDKToolProgressMessage
+ | SDKAuthStatusMessage
+ | SDKTaskNotificationMessage
+ | SDKTaskStartedMessage
+ | SDKTaskProgressMessage
+ | SDKFilesPersistedEvent
+ | SDKToolUseSummaryMessage
+ | SDKRateLimitEvent
+ | SDKPromptSuggestionMessage;
+
+###
+
+
+
+`SDKAssistantMessage`
+
+Assistant response message.
+
+ type SDKAssistantMessage = {
+ type: "assistant";
+ uuid: UUID;
+ session_id: string;
+ message: BetaMessage; // From Anthropic SDK
+ parent_tool_use_id: string | null;
+ error?: SDKAssistantMessageError;
+ };
+
+The `message` field is a [`BetaMessage`](<https://platform.claude.com/docs/en/api/messages/create>) from the Anthropic SDK. It includes fields like `id`, `content`, `model`, `stop_reason`, and `usage`. `SDKAssistantMessageError` is one of: `'authentication_failed'`, `'billing_error'`, `'rate_limit'`, `'invalid_request'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`.
+
+###
+
+
+
+`SDKUserMessage`
+
+User input message.
+
+ type SDKUserMessage = {
+ type: "user";
+ uuid?: UUID;
+ session_id: string;
+ message: MessageParam; // From Anthropic SDK
+ parent_tool_use_id: string | null;
+ isSynthetic?: boolean;
+ tool_use_result?: unknown;
+ };
+
+###
+
+
+
+`SDKUserMessageReplay`
+
+Replayed user message with required UUID.
+
+ type SDKUserMessageReplay = {
+ type: "user";
+ uuid: UUID;
+ session_id: string;
+ message: MessageParam;
+ parent_tool_use_id: string | null;
+ isSynthetic?: boolean;
+ tool_use_result?: unknown;
+ isReplay: true;
+ };
+
+###
+
+
+
+`SDKResultMessage`
+
+Final result message.
+
+ type SDKResultMessage =
+ | {
+ type: "result";
+ subtype: "success";
+ uuid: UUID;
+ session_id: string;
+ duration_ms: number;
+ duration_api_ms: number;
+ is_error: boolean;
+ num_turns: number;
+ result: string;
+ stop_reason: string | null;
+ total_cost_usd: number;
+ usage: NonNullableUsage;
+ modelUsage: { [modelName: string]: ModelUsage };
+ permission_denials: SDKPermissionDenial[];
+ structured_output?: unknown;
+ }
+ | {
+ type: "result";
+ subtype:
+ | "error_max_turns"
+ | "error_during_execution"
+ | "error_max_budget_usd"
+ | "error_max_structured_output_retries";
+ uuid: UUID;
+ session_id: string;
+ duration_ms: number;
+ duration_api_ms: number;
+ is_error: boolean;
+ num_turns: number;
+ stop_reason: string | null;
+ total_cost_usd: number;
+ usage: NonNullableUsage;
+ modelUsage: { [modelName: string]: ModelUsage };
+ permission_denials: SDKPermissionDenial[];
+ errors: string[];
+ };
+
+###
+
+
+
+`SDKSystemMessage`
+
+System initialization message.
+
+ type SDKSystemMessage = {
+ type: "system";
+ subtype: "init";
+ uuid: UUID;
+ session_id: string;
+ agents?: string[];
+ apiKeySource: ApiKeySource;
+ betas?: string[];
+ claude_code_version: string;
+ cwd: string;
+ tools: string[];
+ mcp_servers: {
+ name: string;
+ status: string;
+ }[];
+ model: string;
+ permissionMode: PermissionMode;
+ slash_commands: string[];
+ output_style: string;
+ skills: string[];
+ plugins: { name: string; path: string }[];
+ };
+
+###
+
+
+
+`SDKPartialAssistantMessage`
+
+Streaming partial message (only when `includePartialMessages` is true).
+
+ type SDKPartialAssistantMessage = {
+ type: "stream_event";
+ event: BetaRawMessageStreamEvent; // From Anthropic SDK
+ parent_tool_use_id: string | null;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKCompactBoundaryMessage`
+
+Message indicating a conversation compaction boundary.
+
+ type SDKCompactBoundaryMessage = {
+ type: "system";
+ subtype: "compact_boundary";
+ uuid: UUID;
+ session_id: string;
+ compact_metadata: {
+ trigger: "manual" | "auto";
+ pre_tokens: number;
+ };
+ };
+
+###
+
+
+
+`SDKPermissionDenial`
+
+Information about a denied tool use.
+
+ type SDKPermissionDenial = {
+ tool_name: string;
+ tool_use_id: string;
+ tool_input: Record<string, unknown>;
+ };
+
+##
+
+
+
+Hook Types
+
+For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](</docs/en/agent-sdk/hooks>).
+
+###
+
+
+
+`HookEvent`
+
+Available hook events.
+
+ type HookEvent =
+ | "PreToolUse"
+ | "PostToolUse"
+ | "PostToolUseFailure"
+ | "Notification"
+ | "UserPromptSubmit"
+ | "SessionStart"
+ | "SessionEnd"
+ | "Stop"
+ | "SubagentStart"
+ | "SubagentStop"
+ | "PreCompact"
+ | "PermissionRequest"
+ | "Setup"
+ | "TeammateIdle"
+ | "TaskCompleted"
+ | "ConfigChange"
+ | "WorktreeCreate"
+ | "WorktreeRemove";
+
+###
+
+
+
+`HookCallback`
+
+Hook callback function type.
+
+ type HookCallback = (
+ input: HookInput, // Union of all hook input types
+ toolUseID: string | undefined,
+ options: { signal: AbortSignal }
+ ) => Promise<HookJSONOutput>;
+
+###
+
+
+
+`HookCallbackMatcher`
+
+Hook configuration with optional matcher.
+
+ interface HookCallbackMatcher {
+ matcher?: string;
+ hooks: HookCallback[];
+ timeout?: number; // Timeout in seconds for all hooks in this matcher
+ }
+
+###
+
+
+
+`HookInput`
+
+Union type of all hook input types.
+
+ type HookInput =
+ | PreToolUseHookInput
+ | PostToolUseHookInput
+ | PostToolUseFailureHookInput
+ | NotificationHookInput
+ | UserPromptSubmitHookInput
+ | SessionStartHookInput
+ | SessionEndHookInput
+ | StopHookInput
+ | SubagentStartHookInput
+ | SubagentStopHookInput
+ | PreCompactHookInput
+ | PermissionRequestHookInput
+ | SetupHookInput
+ | TeammateIdleHookInput
+ | TaskCompletedHookInput
+ | ConfigChangeHookInput
+ | WorktreeCreateHookInput
+ | WorktreeRemoveHookInput;
+
+###
+
+
+
+`BaseHookInput`
+
+Base interface that all hook input types extend.
+
+ type BaseHookInput = {
+ session_id: string;
+ transcript_path: string;
+ cwd: string;
+ permission_mode?: string;
+ agent_id?: string;
+ agent_type?: string;
+ };
+
+####
+
+
+
+`PreToolUseHookInput`
+
+ type PreToolUseHookInput = BaseHookInput & {
+ hook_event_name: "PreToolUse";
+ tool_name: string;
+ tool_input: unknown;
+ tool_use_id: string;
+ };
+
+####
+
+
+
+`PostToolUseHookInput`
+
+ type PostToolUseHookInput = BaseHookInput & {
+ hook_event_name: "PostToolUse";
+ tool_name: string;
+ tool_input: unknown;
+ tool_response: unknown;
+ tool_use_id: string;
+ };
+
+####
+
+
+
+`PostToolUseFailureHookInput`
+
+ type PostToolUseFailureHookInput = BaseHookInput & {
+ hook_event_name: "PostToolUseFailure";
+ tool_name: string;
+ tool_input: unknown;
+ tool_use_id: string;
+ error: string;
+ is_interrupt?: boolean;
+ };
+
+####
+
+
+
+`NotificationHookInput`
+
+ type NotificationHookInput = BaseHookInput & {
+ hook_event_name: "Notification";
+ message: string;
+ title?: string;
+ notification_type: string;
+ };
+
+####
+
+
+
+`UserPromptSubmitHookInput`
+
+ type UserPromptSubmitHookInput = BaseHookInput & {
+ hook_event_name: "UserPromptSubmit";
+ prompt: string;
+ };
+
+####
+
+
+
+`SessionStartHookInput`
+
+ type SessionStartHookInput = BaseHookInput & {
+ hook_event_name: "SessionStart";
+ source: "startup" | "resume" | "clear" | "compact";
+ agent_type?: string;
+ model?: string;
+ };
+
+####
+
+
+
+`SessionEndHookInput`
+
+ type SessionEndHookInput = BaseHookInput & {
+ hook_event_name: "SessionEnd";
+ reason: ExitReason; // String from EXIT_REASONS array
+ };
+
+####
+
+
+
+`StopHookInput`
+
+ type StopHookInput = BaseHookInput & {
+ hook_event_name: "Stop";
+ stop_hook_active: boolean;
+ last_assistant_message?: string;
+ };
+
+####
+
+
+
+`SubagentStartHookInput`
+
+ type SubagentStartHookInput = BaseHookInput & {
+ hook_event_name: "SubagentStart";
+ agent_id: string;
+ agent_type: string;
+ };
+
+####
+
+
+
+`SubagentStopHookInput`
+
+ type SubagentStopHookInput = BaseHookInput & {
+ hook_event_name: "SubagentStop";
+ stop_hook_active: boolean;
+ agent_id: string;
+ agent_transcript_path: string;
+ agent_type: string;
+ last_assistant_message?: string;
+ };
+
+####
+
+
+
+`PreCompactHookInput`
+
+ type PreCompactHookInput = BaseHookInput & {
+ hook_event_name: "PreCompact";
+ trigger: "manual" | "auto";
+ custom_instructions: string | null;
+ };
+
+####
+
+
+
+`PermissionRequestHookInput`
+
+ type PermissionRequestHookInput = BaseHookInput & {
+ hook_event_name: "PermissionRequest";
+ tool_name: string;
+ tool_input: unknown;
+ permission_suggestions?: PermissionUpdate[];
+ };
+
+####
+
+
+
+`SetupHookInput`
+
+ type SetupHookInput = BaseHookInput & {
+ hook_event_name: "Setup";
+ trigger: "init" | "maintenance";
+ };
+
+####
+
+
+
+`TeammateIdleHookInput`
+
+ type TeammateIdleHookInput = BaseHookInput & {
+ hook_event_name: "TeammateIdle";
+ teammate_name: string;
+ team_name: string;
+ };
+
+####
+
+
+
+`TaskCompletedHookInput`
+
+ type TaskCompletedHookInput = BaseHookInput & {
+ hook_event_name: "TaskCompleted";
+ task_id: string;
+ task_subject: string;
+ task_description?: string;
+ teammate_name?: string;
+ team_name?: string;
+ };
+
+####
+
+
+
+`ConfigChangeHookInput`
+
+ type ConfigChangeHookInput = BaseHookInput & {
+ hook_event_name: "ConfigChange";
+ source:
+ | "user_settings"
+ | "project_settings"
+ | "local_settings"
+ | "policy_settings"
+ | "skills";
+ file_path?: string;
+ };
+
+####
+
+
+
+`WorktreeCreateHookInput`
+
+ type WorktreeCreateHookInput = BaseHookInput & {
+ hook_event_name: "WorktreeCreate";
+ name: string;
+ };
+
+####
+
+
+
+`WorktreeRemoveHookInput`
+
+ type WorktreeRemoveHookInput = BaseHookInput & {
+ hook_event_name: "WorktreeRemove";
+ worktree_path: string;
+ };
+
+###
+
+
+
+`HookJSONOutput`
+
+Hook return value.
+
+ type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;
+
+####
+
+
+
+`AsyncHookJSONOutput`
+
+ type AsyncHookJSONOutput = {
+ async: true;
+ asyncTimeout?: number;
+ };
+
+####
+
+
+
+`SyncHookJSONOutput`
+
+ type SyncHookJSONOutput = {
+ continue?: boolean;
+ suppressOutput?: boolean;
+ stopReason?: string;
+ decision?: "approve" | "block";
+ systemMessage?: string;
+ reason?: string;
+ hookSpecificOutput?:
+ | {
+ hookEventName: "PreToolUse";
+ permissionDecision?: "allow" | "deny" | "ask";
+ permissionDecisionReason?: string;
+ updatedInput?: Record<string, unknown>;
+ additionalContext?: string;
+ }
+ | {
+ hookEventName: "UserPromptSubmit";
+ additionalContext?: string;
+ }
+ | {
+ hookEventName: "SessionStart";
+ additionalContext?: string;
+ }
+ | {
+ hookEventName: "Setup";
+ additionalContext?: string;
+ }
+ | {
+ hookEventName: "SubagentStart";
+ additionalContext?: string;
+ }
+ | {
+ hookEventName: "PostToolUse";
+ additionalContext?: string;
+ updatedMCPToolOutput?: unknown;
+ }
+ | {
+ hookEventName: "PostToolUseFailure";
+ additionalContext?: string;
+ }
+ | {
+ hookEventName: "Notification";
+ additionalContext?: string;
+ }
+ | {
+ hookEventName: "PermissionRequest";
+ decision:
+ | {
+ behavior: "allow";
+ updatedInput?: Record<string, unknown>;
+ updatedPermissions?: PermissionUpdate[];
+ }
+ | {
+ behavior: "deny";
+ message?: string;
+ interrupt?: boolean;
+ };
+ };
+ };
+
+##
+
+
+
+Tool Input Types
+
+Documentation of input schemas for all built-in Claude Code tools. These types are exported from `@anthropic-ai/claude-agent-sdk` and can be used for type-safe tool interactions.
+
+###
+
+
+
+`ToolInputSchemas`
+
+Union of all tool input types, exported from `@anthropic-ai/claude-agent-sdk`.
+
+ type ToolInputSchemas =
+ | AgentInput
+ | AskUserQuestionInput
+ | BashInput
+ | TaskOutputInput
+ | ConfigInput
+ | EnterWorktreeInput
+ | ExitPlanModeInput
+ | FileEditInput
+ | FileReadInput
+ | FileWriteInput
+ | GlobInput
+ | GrepInput
+ | ListMcpResourcesInput
+ | McpInput
+ | NotebookEditInput
+ | ReadMcpResourceInput
+ | SubscribeMcpResourceInput
+ | SubscribePollingInput
+ | TaskStopInput
+ | TodoWriteInput
+ | UnsubscribeMcpResourceInput
+ | UnsubscribePollingInput
+ | WebFetchInput
+ | WebSearchInput;
+
+###
+
+
+
+Agent
+
+**Tool name:** `Agent` (previously `Task`, which is still accepted as an alias)
+
+ type AgentInput = {
+ description: string;
+ prompt: string;
+ subagent_type: string;
+ model?: "sonnet" | "opus" | "haiku";
+ resume?: string;
+ run_in_background?: boolean;
+ max_turns?: number;
+ name?: string;
+ team_name?: string;
+ mode?: "acceptEdits" | "bypassPermissions" | "default" | "dontAsk" | "plan";
+ isolation?: "worktree";
+ };
+
+Launches a new agent to handle complex, multi-step tasks autonomously.
+
+###
+
+
+
+AskUserQuestion
+
+**Tool name:** `AskUserQuestion`
+
+ type AskUserQuestionInput = {
+ questions: Array<{
+ question: string;
+ header: string;
+ options: Array<{ label: string; description: string; preview?: string }>;
+ multiSelect: boolean;
+ }>;
+ };
+
+Asks the user clarifying questions during execution. See [Handle approvals and user input](</docs/en/agent-sdk/user-input#handle-clarifying-questions>) for usage details.
+
+###
+
+
+
+Bash
+
+**Tool name:** `Bash`
+
+ type BashInput = {
+ command: string;
+ timeout?: number;
+ description?: string;
+ run_in_background?: boolean;
+ dangerouslyDisableSandbox?: boolean;
+ };
+
+Executes bash commands in a persistent shell session with optional timeout and background execution.
+
+###
+
+
+
+TaskOutput
+
+**Tool name:** `TaskOutput`
+
+ type TaskOutputInput = {
+ task_id: string;
+ block: boolean;
+ timeout: number;
+ };
+
+Retrieves output from a running or completed background task.
+
+###
+
+
+
+Edit
+
+**Tool name:** `Edit`
+
+ type FileEditInput = {
+ file_path: string;
+ old_string: string;
+ new_string: string;
+ replace_all?: boolean;
+ };
+
+Performs exact string replacements in files.
+
+###
+
+
+
+Read
+
+**Tool name:** `Read`
+
+ type FileReadInput = {
+ file_path: string;
+ offset?: number;
+ limit?: number;
+ pages?: string;
+ };
+
+Reads files from the local filesystem, including text, images, PDFs, and Jupyter notebooks. Use `pages` for PDF page ranges (for example, `"1-5"`).
+
+###
+
+
+
+Write
+
+**Tool name:** `Write`
+
+ type FileWriteInput = {
+ file_path: string;
+ content: string;
+ };
+
+Writes a file to the local filesystem, overwriting if it exists.
+
+###
+
+
+
+Glob
+
+**Tool name:** `Glob`
+
+ type GlobInput = {
+ pattern: string;
+ path?: string;
+ };
+
+Fast file pattern matching that works with any codebase size.
+
+###
+
+
+
+Grep
+
+**Tool name:** `Grep`
+
+ type GrepInput = {
+ pattern: string;
+ path?: string;
+ glob?: string;
+ type?: string;
+ output_mode?: "content" | "files_with_matches" | "count";
+ "-i"?: boolean;
+ "-n"?: boolean;
+ "-B"?: number;
+ "-A"?: number;
+ "-C"?: number;
+ context?: number;
+ head_limit?: number;
+ offset?: number;
+ multiline?: boolean;
+ };
+
+Powerful search tool built on ripgrep with regex support.
+
+###
+
+
+
+TaskStop
+
+**Tool name:** `TaskStop`
+
+ type TaskStopInput = {
+ task_id?: string;
+ shell_id?: string; // Deprecated: use task_id
+ };
+
+Stops a running background task or shell by ID.
+
+###
+
+
+
+NotebookEdit
+
+**Tool name:** `NotebookEdit`
+
+ type NotebookEditInput = {
+ notebook_path: string;
+ cell_id?: string;
+ new_source: string;
+ cell_type?: "code" | "markdown";
+ edit_mode?: "replace" | "insert" | "delete";
+ };
+
+Edits cells in Jupyter notebook files.
+
+###
+
+
+
+WebFetch
+
+**Tool name:** `WebFetch`
+
+ type WebFetchInput = {
+ url: string;
+ prompt: string;
+ };
+
+Fetches content from a URL and processes it with an AI model.
+
+###
+
+
+
+WebSearch
+
+**Tool name:** `WebSearch`
+
+ type WebSearchInput = {
+ query: string;
+ allowed_domains?: string[];
+ blocked_domains?: string[];
+ };
+
+Searches the web and returns formatted results.
+
+###
+
+
+
+TodoWrite
+
+**Tool name:** `TodoWrite`
+
+ type TodoWriteInput = {
+ todos: Array<{
+ content: string;
+ status: "pending" | "in_progress" | "completed";
+ activeForm: string;
+ }>;
+ };
+
+Creates and manages a structured task list for tracking progress.
+
+###
+
+
+
+ExitPlanMode
+
+**Tool name:** `ExitPlanMode`
+
+ type ExitPlanModeInput = {
+ allowedPrompts?: Array<{
+ tool: "Bash";
+ prompt: string;
+ }>;
+ };
+
+Exits planning mode. Optionally specifies prompt-based permissions needed to implement the plan.
+
+###
+
+
+
+ListMcpResources
+
+**Tool name:** `ListMcpResources`
+
+ type ListMcpResourcesInput = {
+ server?: string;
+ };
+
+Lists available MCP resources from connected servers.
+
+###
+
+
+
+ReadMcpResource
+
+**Tool name:** `ReadMcpResource`
+
+ type ReadMcpResourceInput = {
+ server: string;
+ uri: string;
+ };
+
+Reads a specific MCP resource from a server.
+
+###
+
+
+
+Config
+
+**Tool name:** `Config`
+
+ type ConfigInput = {
+ setting: string;
+ value?: string | boolean | number;
+ };
+
+Gets or sets a configuration value.
+
+###
+
+
+
+EnterWorktree
+
+**Tool name:** `EnterWorktree`
+
+ type EnterWorktreeInput = {
+ name?: string;
+ };
+
+Creates and enters a temporary git worktree for isolated work.
+
+##
+
+
+
+Tool Output Types
+
+Documentation of output schemas for all built-in Claude Code tools. These types are exported from `@anthropic-ai/claude-agent-sdk` and represent the actual response data returned by each tool.
+
+###
+
+
+
+`ToolOutputSchemas`
+
+Union of all tool output types.
+
+ type ToolOutputSchemas =
+ | AgentOutput
+ | AskUserQuestionOutput
+ | BashOutput
+ | ConfigOutput
+ | EnterWorktreeOutput
+ | ExitPlanModeOutput
+ | FileEditOutput
+ | FileReadOutput
+ | FileWriteOutput
+ | GlobOutput
+ | GrepOutput
+ | ListMcpResourcesOutput
+ | NotebookEditOutput
+ | ReadMcpResourceOutput
+ | TaskStopOutput
+ | TodoWriteOutput
+ | WebFetchOutput
+ | WebSearchOutput;
+
+###
+
+
+
+Agent
+
+**Tool name:** `Agent` (previously `Task`, which is still accepted as an alias)
+
+ type AgentOutput =
+ | {
+ status: "completed";
+ agentId: string;
+ content: Array<{ type: "text"; text: string }>;
+ totalToolUseCount: number;
+ totalDurationMs: number;
+ totalTokens: number;
+ usage: {
+ input_tokens: number;
+ output_tokens: number;
+ cache_creation_input_tokens: number | null;
+ cache_read_input_tokens: number | null;
+ server_tool_use: {
+ web_search_requests: number;
+ web_fetch_requests: number;
+ } | null;
+ service_tier: ("standard" | "priority" | "batch") | null;
+ cache_creation: {
+ ephemeral_1h_input_tokens: number;
+ ephemeral_5m_input_tokens: number;
+ } | null;
+ };
+ prompt: string;
+ }
+ | {
+ status: "async_launched";
+ agentId: string;
+ description: string;
+ prompt: string;
+ outputFile: string;
+ canReadOutputFile?: boolean;
+ }
+ | {
+ status: "sub_agent_entered";
+ description: string;
+ message: string;
+ };
+
+Returns the result from the subagent. Discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"sub_agent_entered"` for interactive subagents.
+
+###
+
+
+
+AskUserQuestion
+
+**Tool name:** `AskUserQuestion`
+
+ type AskUserQuestionOutput = {
+ questions: Array<{
+ question: string;
+ header: string;
+ options: Array<{ label: string; description: string; preview?: string }>;
+ multiSelect: boolean;
+ }>;
+ answers: Record<string, string>;
+ };
+
+Returns the questions asked and the user’s answers.
+
+###
+
+
+
+Bash
+
+**Tool name:** `Bash`
+
+ type BashOutput = {
+ stdout: string;
+ stderr: string;
+ rawOutputPath?: string;
+ interrupted: boolean;
+ isImage?: boolean;
+ backgroundTaskId?: string;
+ backgroundedByUser?: boolean;
+ dangerouslyDisableSandbox?: boolean;
+ returnCodeInterpretation?: string;
+ structuredContent?: unknown[];
+ persistedOutputPath?: string;
+ persistedOutputSize?: number;
+ };
+
+Returns command output with stdout/stderr split. Background commands include a `backgroundTaskId`.
+
+###
+
+
+
+Edit
+
+**Tool name:** `Edit`
+
+ type FileEditOutput = {
+ filePath: string;
+ oldString: string;
+ newString: string;
+ originalFile: string;
+ structuredPatch: Array<{
+ oldStart: number;
+ oldLines: number;
+ newStart: number;
+ newLines: number;
+ lines: string[];
+ }>;
+ userModified: boolean;
+ replaceAll: boolean;
+ gitDiff?: {
+ filename: string;
+ status: "modified" | "added";
+ additions: number;
+ deletions: number;
+ changes: number;
+ patch: string;
+ };
+ };
+
+Returns the structured diff of the edit operation.
+
+###
+
+
+
+Read
+
+**Tool name:** `Read`
+
+ type FileReadOutput =
+ | {
+ type: "text";
+ file: {
+ filePath: string;
+ content: string;
+ numLines: number;
+ startLine: number;
+ totalLines: number;
+ };
+ }
+ | {
+ type: "image";
+ file: {
+ base64: string;
+ type: "image/jpeg" | "image/png" | "image/gif" | "image/webp";
+ originalSize: number;
+ dimensions?: {
+ originalWidth?: number;
+ originalHeight?: number;
+ displayWidth?: number;
+ displayHeight?: number;
+ };
+ };
+ }
+ | {
+ type: "notebook";
+ file: {
+ filePath: string;
+ cells: unknown[];
+ };
+ }
+ | {
+ type: "pdf";
+ file: {
+ filePath: string;
+ base64: string;
+ originalSize: number;
+ };
+ }
+ | {
+ type: "parts";
+ file: {
+ filePath: string;
+ originalSize: number;
+ count: number;
+ outputDir: string;
+ };
+ };
+
+Returns file contents in a format appropriate to the file type. Discriminated on the `type` field.
+
+###
+
+
+
+Write
+
+**Tool name:** `Write`
+
+ type FileWriteOutput = {
+ type: "create" | "update";
+ filePath: string;
+ content: string;
+ structuredPatch: Array<{
+ oldStart: number;
+ oldLines: number;
+ newStart: number;
+ newLines: number;
+ lines: string[];
+ }>;
+ originalFile: string | null;
+ gitDiff?: {
+ filename: string;
+ status: "modified" | "added";
+ additions: number;
+ deletions: number;
+ changes: number;
+ patch: string;
+ };
+ };
+
+Returns the write result with structured diff information.
+
+###
+
+
+
+Glob
+
+**Tool name:** `Glob`
+
+ type GlobOutput = {
+ durationMs: number;
+ numFiles: number;
+ filenames: string[];
+ truncated: boolean;
+ };
+
+Returns file paths matching the glob pattern, sorted by modification time.
+
+###
+
+
+
+Grep
+
+**Tool name:** `Grep`
+
+ type GrepOutput = {
+ mode?: "content" | "files_with_matches" | "count";
+ numFiles: number;
+ filenames: string[];
+ content?: string;
+ numLines?: number;
+ numMatches?: number;
+ appliedLimit?: number;
+ appliedOffset?: number;
+ };
+
+Returns search results. The shape varies by `mode`: file list, content with matches, or match counts.
+
+###
+
+
+
+TaskStop
+
+**Tool name:** `TaskStop`
+
+ type TaskStopOutput = {
+ message: string;
+ task_id: string;
+ task_type: string;
+ command?: string;
+ };
+
+Returns confirmation after stopping the background task.
+
+###
+
+
+
+NotebookEdit
+
+**Tool name:** `NotebookEdit`
+
+ type NotebookEditOutput = {
+ new_source: string;
+ cell_id?: string;
+ cell_type: "code" | "markdown";
+ language: string;
+ edit_mode: string;
+ error?: string;
+ notebook_path: string;
+ original_file: string;
+ updated_file: string;
+ };
+
+Returns the result of the notebook edit with original and updated file contents.
+
+###
+
+
+
+WebFetch
+
+**Tool name:** `WebFetch`
+
+ type WebFetchOutput = {
+ bytes: number;
+ code: number;
+ codeText: string;
+ result: string;
+ durationMs: number;
+ url: string;
+ };
+
+Returns the fetched content with HTTP status and metadata.
+
+###
+
+
+
+WebSearch
+
+**Tool name:** `WebSearch`
+
+ type WebSearchOutput = {
+ query: string;
+ results: Array<
+ | {
+ tool_use_id: string;
+ content: Array<{ title: string; url: string }>;
+ }
+ | string
+ >;
+ durationSeconds: number;
+ };
+
+Returns search results from the web.
+
+###
+
+
+
+TodoWrite
+
+**Tool name:** `TodoWrite`
+
+ type TodoWriteOutput = {
+ oldTodos: Array<{
+ content: string;
+ status: "pending" | "in_progress" | "completed";
+ activeForm: string;
+ }>;
+ newTodos: Array<{
+ content: string;
+ status: "pending" | "in_progress" | "completed";
+ activeForm: string;
+ }>;
+ };
+
+Returns the previous and updated task lists.
+
+###
+
+
+
+ExitPlanMode
+
+**Tool name:** `ExitPlanMode`
+
+ type ExitPlanModeOutput = {
+ plan: string | null;
+ isAgent: boolean;
+ filePath?: string;
+ hasTaskTool?: boolean;
+ awaitingLeaderApproval?: boolean;
+ requestId?: string;
+ };
+
+Returns the plan state after exiting plan mode.
+
+###
+
+
+
+ListMcpResources
+
+**Tool name:** `ListMcpResources`
+
+ type ListMcpResourcesOutput = Array<{
+ uri: string;
+ name: string;
+ mimeType?: string;
+ description?: string;
+ server: string;
+ }>;
+
+Returns an array of available MCP resources.
+
+###
+
+
+
+ReadMcpResource
+
+**Tool name:** `ReadMcpResource`
+
+ type ReadMcpResourceOutput = {
+ contents: Array<{
+ uri: string;
+ mimeType?: string;
+ text?: string;
+ }>;
+ };
+
+Returns the contents of the requested MCP resource.
+
+###
+
+
+
+Config
+
+**Tool name:** `Config`
+
+ type ConfigOutput = {
+ success: boolean;
+ operation?: "get" | "set";
+ setting?: string;
+ value?: unknown;
+ previousValue?: unknown;
+ newValue?: unknown;
+ error?: string;
+ };
+
+Returns the result of a configuration get or set operation.
+
+###
+
+
+
+EnterWorktree
+
+**Tool name:** `EnterWorktree`
+
+ type EnterWorktreeOutput = {
+ worktreePath: string;
+ worktreeBranch?: string;
+ message: string;
+ };
+
+Returns information about the created git worktree.
+
+##
+
+
+
+Permission Types
+
+###
+
+
+
+`PermissionUpdate`
+
+Operations for updating permissions.
+
+ type PermissionUpdate =
+ | {
+ type: "addRules";
+ rules: PermissionRuleValue[];
+ behavior: PermissionBehavior;
+ destination: PermissionUpdateDestination;
+ }
+ | {
+ type: "replaceRules";
+ rules: PermissionRuleValue[];
+ behavior: PermissionBehavior;
+ destination: PermissionUpdateDestination;
+ }
+ | {
+ type: "removeRules";
+ rules: PermissionRuleValue[];
+ behavior: PermissionBehavior;
+ destination: PermissionUpdateDestination;
+ }
+ | {
+ type: "setMode";
+ mode: PermissionMode;
+ destination: PermissionUpdateDestination;
+ }
+ | {
+ type: "addDirectories";
+ directories: string[];
+ destination: PermissionUpdateDestination;
+ }
+ | {
+ type: "removeDirectories";
+ directories: string[];
+ destination: PermissionUpdateDestination;
+ };
+
+###
+
+
+
+`PermissionBehavior`
+
+ type PermissionBehavior = "allow" | "deny" | "ask";
+
+###
+
+
+
+`PermissionUpdateDestination`
+
+ type PermissionUpdateDestination =
+ | "userSettings" // Global user settings
+ | "projectSettings" // Per-directory project settings
+ | "localSettings" // Gitignored local settings
+ | "session" // Current session only
+ | "cliArg"; // CLI argument
+
+###
+
+
+
+`PermissionRuleValue`
+
+ type PermissionRuleValue = {
+ toolName: string;
+ ruleContent?: string;
+ };
+
+##
+
+
+
+Other Types
+
+###
+
+
+
+`ApiKeySource`
+
+ type ApiKeySource = "user" | "project" | "org" | "temporary" | "oauth";
+
+###
+
+
+
+`SdkBeta`
+
+Available beta features that can be enabled via the `betas` option. See [Beta headers](<https://platform.claude.com/docs/en/api/beta-headers>) for more information.
+
+ type SdkBeta = "context-1m-2025-08-07";
+
+The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this value with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Sonnet 4.6 or Claude Opus 4.6](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
+
+###
+
+
+
+`SlashCommand`
+
+Information about an available slash command.
+
+ type SlashCommand = {
+ name: string;
+ description: string;
+ argumentHint: string;
+ };
+
+###
+
+
+
+`ModelInfo`
+
+Information about an available model.
+
+ type ModelInfo = {
+ value: string;
+ displayName: string;
+ description: string;
+ supportsEffort?: boolean;
+ supportedEffortLevels?: ("low" | "medium" | "high" | "max")[];
+ supportsAdaptiveThinking?: boolean;
+ supportsFastMode?: boolean;
+ };
+
+###
+
+
+
+`AgentInfo`
+
+Information about an available subagent that can be invoked via the Agent tool.
+
+ type AgentInfo = {
+ name: string;
+ description: string;
+ model?: string;
+ };
+
+Field| Type| Description
+---|---|---
+`name`| `string`| Agent type identifier (e.g., `"Explore"`, `"general-purpose"`)
+`description`| `string`| Description of when to use this agent
+`model`| `string | undefined`| Model alias this agent uses. If omitted, inherits the parent’s model
+
+###
+
+
+
+`McpServerStatus`
+
+Status of a connected MCP server.
+
+ type McpServerStatus = {
+ name: string;
+ status: "connected" | "failed" | "needs-auth" | "pending" | "disabled";
+ serverInfo?: {
+ name: string;
+ version: string;
+ };
+ error?: string;
+ config?: McpServerStatusConfig;
+ scope?: string;
+ tools?: {
+ name: string;
+ description?: string;
+ annotations?: {
+ readOnly?: boolean;
+ destructive?: boolean;
+ openWorld?: boolean;
+ };
+ }[];
+ };
+
+###
+
+
+
+`McpServerStatusConfig`
+
+The configuration of an MCP server as reported by `mcpServerStatus()`. This is the union of all MCP server transport types.
+
+ type McpServerStatusConfig =
+ | McpStdioServerConfig
+ | McpSSEServerConfig
+ | McpHttpServerConfig
+ | McpSdkServerConfig
+ | McpClaudeAIProxyServerConfig;
+
+See `McpServerConfig` for details on each transport type.
+
+###
+
+
+
+`AccountInfo`
+
+Account information for the authenticated user.
+
+ type AccountInfo = {
+ email?: string;
+ organization?: string;
+ subscriptionType?: string;
+ tokenSource?: string;
+ apiKeySource?: string;
+ };
+
+###
+
+
+
+`ModelUsage`
+
+Per-model usage statistics returned in result messages.
+
+ type ModelUsage = {
+ inputTokens: number;
+ outputTokens: number;
+ cacheReadInputTokens: number;
+ cacheCreationInputTokens: number;
+ webSearchRequests: number;
+ costUSD: number;
+ contextWindow: number;
+ maxOutputTokens: number;
+ };
+
+###
+
+
+
+`ConfigScope`
+
+ type ConfigScope = "local" | "user" | "project";
+
+###
+
+
+
+`NonNullableUsage`
+
+A version of `Usage` with all nullable fields made non-nullable.
+
+ type NonNullableUsage = {
+ [K in keyof Usage]: NonNullable<Usage[K]>;
+ };
+
+###
+
+
+
+`Usage`
+
+Token usage statistics (from `@anthropic-ai/sdk`).
+
+ type Usage = {
+ input_tokens: number | null;
+ output_tokens: number | null;
+ cache_creation_input_tokens?: number | null;
+ cache_read_input_tokens?: number | null;
+ };
+
+###
+
+
+
+`CallToolResult`
+
+MCP tool result type (from `@modelcontextprotocol/sdk/types.js`).
+
+ type CallToolResult = {
+ content: Array<{
+ type: "text" | "image" | "resource";
+ // Additional fields vary by type
+ }>;
+ isError?: boolean;
+ };
+
+###
+
+
+
+`ThinkingConfig`
+
+Controls Claude’s thinking/reasoning behavior. Takes precedence over the deprecated `maxThinkingTokens`.
+
+ type ThinkingConfig =
+ | { type: "adaptive" } // The model determines when and how much to reason (Opus 4.6+)
+ | { type: "enabled"; budgetTokens?: number } // Fixed thinking token budget
+ | { type: "disabled" }; // No extended thinking
+
+###
+
+
+
+`SpawnedProcess`
+
+Interface for custom process spawning (used with `spawnClaudeCodeProcess` option). `ChildProcess` already satisfies this interface.
+
+ interface SpawnedProcess {
+ stdin: Writable;
+ stdout: Readable;
+ readonly killed: boolean;
+ readonly exitCode: number | null;
+ kill(signal: NodeJS.Signals): boolean;
+ on(
+ event: "exit",
+ listener: (code: number | null, signal: NodeJS.Signals | null) => void
+ ): void;
+ on(event: "error", listener: (error: Error) => void): void;
+ once(
+ event: "exit",
+ listener: (code: number | null, signal: NodeJS.Signals | null) => void
+ ): void;
+ once(event: "error", listener: (error: Error) => void): void;
+ off(
+ event: "exit",
+ listener: (code: number | null, signal: NodeJS.Signals | null) => void
+ ): void;
+ off(event: "error", listener: (error: Error) => void): void;
+ }
+
+###
+
+
+
+`SpawnOptions`
+
+Options passed to the custom spawn function.
+
+ interface SpawnOptions {
+ command: string;
+ args: string[];
+ cwd?: string;
+ env: Record<string, string | undefined>;
+ signal: AbortSignal;
+ }
+
+###
+
+
+
+`McpSetServersResult`
+
+Result of a `setMcpServers()` operation.
+
+ type McpSetServersResult = {
+ added: string[];
+ removed: string[];
+ errors: Record<string, string>;
+ };
+
+###
+
+
+
+`RewindFilesResult`
+
+Result of a `rewindFiles()` operation.
+
+ type RewindFilesResult = {
+ canRewind: boolean;
+ error?: string;
+ filesChanged?: string[];
+ insertions?: number;
+ deletions?: number;
+ };
+
+###
+
+
+
+`SDKStatusMessage`
+
+Status update message (e.g., compacting).
+
+ type SDKStatusMessage = {
+ type: "system";
+ subtype: "status";
+ status: "compacting" | null;
+ permissionMode?: PermissionMode;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKTaskNotificationMessage`
+
+Notification when a background task completes, fails, or is stopped.
+
+ type SDKTaskNotificationMessage = {
+ type: "system";
+ subtype: "task_notification";
+ task_id: string;
+ tool_use_id?: string;
+ status: "completed" | "failed" | "stopped";
+ output_file: string;
+ summary: string;
+ usage?: {
+ total_tokens: number;
+ tool_uses: number;
+ duration_ms: number;
+ };
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKToolUseSummaryMessage`
+
+Summary of tool usage in a conversation.
+
+ type SDKToolUseSummaryMessage = {
+ type: "tool_use_summary";
+ summary: string;
+ preceding_tool_use_ids: string[];
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKHookStartedMessage`
+
+Emitted when a hook begins executing.
+
+ type SDKHookStartedMessage = {
+ type: "system";
+ subtype: "hook_started";
+ hook_id: string;
+ hook_name: string;
+ hook_event: string;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKHookProgressMessage`
+
+Emitted while a hook is running, with stdout/stderr output.
+
+ type SDKHookProgressMessage = {
+ type: "system";
+ subtype: "hook_progress";
+ hook_id: string;
+ hook_name: string;
+ hook_event: string;
+ stdout: string;
+ stderr: string;
+ output: string;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKHookResponseMessage`
+
+Emitted when a hook finishes executing.
+
+ type SDKHookResponseMessage = {
+ type: "system";
+ subtype: "hook_response";
+ hook_id: string;
+ hook_name: string;
+ hook_event: string;
+ output: string;
+ stdout: string;
+ stderr: string;
+ exit_code?: number;
+ outcome: "success" | "error" | "cancelled";
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKToolProgressMessage`
+
+Emitted periodically while a tool is executing to indicate progress.
+
+ type SDKToolProgressMessage = {
+ type: "tool_progress";
+ tool_use_id: string;
+ tool_name: string;
+ parent_tool_use_id: string | null;
+ elapsed_time_seconds: number;
+ task_id?: string;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKAuthStatusMessage`
+
+Emitted during authentication flows.
+
+ type SDKAuthStatusMessage = {
+ type: "auth_status";
+ isAuthenticating: boolean;
+ output: string[];
+ error?: string;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKTaskStartedMessage`
+
+Emitted when a background task begins.
+
+ type SDKTaskStartedMessage = {
+ type: "system";
+ subtype: "task_started";
+ task_id: string;
+ tool_use_id?: string;
+ description: string;
+ task_type?: string;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKTaskProgressMessage`
+
+Emitted periodically while a background task is running.
+
+ type SDKTaskProgressMessage = {
+ type: "system";
+ subtype: "task_progress";
+ task_id: string;
+ tool_use_id?: string;
+ description: string;
+ usage: {
+ total_tokens: number;
+ tool_uses: number;
+ duration_ms: number;
+ };
+ last_tool_name?: string;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKFilesPersistedEvent`
+
+Emitted when file checkpoints are persisted to disk.
+
+ type SDKFilesPersistedEvent = {
+ type: "system";
+ subtype: "files_persisted";
+ files: { filename: string; file_id: string }[];
+ failed: { filename: string; error: string }[];
+ processed_at: string;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKRateLimitEvent`
+
+Emitted when the session encounters a rate limit.
+
+ type SDKRateLimitEvent = {
+ type: "rate_limit_event";
+ rate_limit_info: {
+ status: "allowed" | "allowed_warning" | "rejected";
+ resetsAt?: number;
+ utilization?: number;
+ };
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKLocalCommandOutputMessage`
+
+Output from a local slash command (for example, `/voice` or `/cost`). Displayed as assistant-style text in the transcript.
+
+ type SDKLocalCommandOutputMessage = {
+ type: "system";
+ subtype: "local_command_output";
+ content: string;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`SDKPromptSuggestionMessage`
+
+Emitted after each turn when `promptSuggestions` is enabled. Contains a predicted next user prompt.
+
+ type SDKPromptSuggestionMessage = {
+ type: "prompt_suggestion";
+ suggestion: string;
+ uuid: UUID;
+ session_id: string;
+ };
+
+###
+
+
+
+`AbortError`
+
+Custom error class for abort operations.
+
+ class AbortError extends Error {}
+
+##
+
+
+
+Sandbox Configuration
+
+###
+
+
+
+`SandboxSettings`
+
+Configuration for sandbox behavior. Use this to enable command sandboxing and configure network restrictions programmatically.
+
+ type SandboxSettings = {
+ enabled?: boolean;
+ autoAllowBashIfSandboxed?: boolean;
+ excludedCommands?: string[];
+ allowUnsandboxedCommands?: boolean;
+ network?: SandboxNetworkConfig;
+ filesystem?: SandboxFilesystemConfig;
+ ignoreViolations?: Record<string, string[]>;
+ enableWeakerNestedSandbox?: boolean;
+ ripgrep?: { command: string; args?: string[] };
+ };
+
+Property| Type| Default| Description
+---|---|---|---
+`enabled`| `boolean`| `false`| Enable sandbox mode for command execution
+`autoAllowBashIfSandboxed`| `boolean`| `true`| Auto-approve bash commands when sandbox is enabled
+`excludedCommands`| `string[]`| `[]`| Commands that always bypass sandbox restrictions (e.g., `['docker']`). These run unsandboxed automatically without model involvement
+`allowUnsandboxedCommands`| `boolean`| `true`| Allow the model to request running commands outside the sandbox. When `true`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the permissions system
+`network`| `SandboxNetworkConfig`| `undefined`| Network-specific sandbox configuration
+`filesystem`| `SandboxFilesystemConfig`| `undefined`| Filesystem-specific sandbox configuration for read/write restrictions
+`ignoreViolations`| `Record<string, string[]>`| `undefined`| Map of violation categories to patterns to ignore (e.g., `{ file: ['/tmp/*'], network: ['localhost'] }`)
+`enableWeakerNestedSandbox`| `boolean`| `false`| Enable a weaker nested sandbox for compatibility
+`ripgrep`| `{ command: string; args?: string[] }`| `undefined`| Custom ripgrep binary configuration for sandbox environments
+
+####
+
+
+
+Example usage
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Build and test my project",
+ options: {
+ sandbox: {
+ enabled: true,
+ autoAllowBashIfSandboxed: true,
+ network: {
+ allowLocalBinding: true
+ }
+ }
+ }
+ })) {
+ if ("result" in message) console.log(message.result);
+ }
+
+**Unix socket security:** The `allowUnixSockets` option can grant access to powerful system services. For example, allowing `/var/run/docker.sock` effectively grants full host system access through the Docker API, bypassing sandbox isolation. Only allow Unix sockets that are strictly necessary and understand the security implications of each.
+
+###
+
+
+
+`SandboxNetworkConfig`
+
+Network-specific configuration for sandbox mode.
+
+ type SandboxNetworkConfig = {
+ allowedDomains?: string[];
+ allowManagedDomainsOnly?: boolean;
+ allowLocalBinding?: boolean;
+ allowUnixSockets?: string[];
+ allowAllUnixSockets?: boolean;
+ httpProxyPort?: number;
+ socksProxyPort?: number;
+ };
+
+Property| Type| Default| Description
+---|---|---|---
+`allowedDomains`| `string[]`| `[]`| Domain names that sandboxed processes can access
+`allowManagedDomainsOnly`| `boolean`| `false`| Restrict network access to only the domains in `allowedDomains`
+`allowLocalBinding`| `boolean`| `false`| Allow processes to bind to local ports (e.g., for dev servers)
+`allowUnixSockets`| `string[]`| `[]`| Unix socket paths that processes can access (e.g., Docker socket)
+`allowAllUnixSockets`| `boolean`| `false`| Allow access to all Unix sockets
+`httpProxyPort`| `number`| `undefined`| HTTP proxy port for network requests
+`socksProxyPort`| `number`| `undefined`| SOCKS proxy port for network requests
+
+###
+
+
+
+`SandboxFilesystemConfig`
+
+Filesystem-specific configuration for sandbox mode.
+
+ type SandboxFilesystemConfig = {
+ allowWrite?: string[];
+ denyWrite?: string[];
+ denyRead?: string[];
+ };
+
+Property| Type| Default| Description
+---|---|---|---
+`allowWrite`| `string[]`| `[]`| File path patterns to allow write access to
+`denyWrite`| `string[]`| `[]`| File path patterns to deny write access to
+`denyRead`| `string[]`| `[]`| File path patterns to deny read access to
+
+###
+
+
+
+Permissions Fallback for Unsandboxed Commands
+
+When `allowUnsandboxedCommands` is enabled, the model can request to run commands outside the sandbox by setting `dangerouslyDisableSandbox: true` in the tool input. These requests fall back to the existing permissions system, meaning your `canUseTool` handler is invoked, allowing you to implement custom authorization logic.
+
+**`excludedCommands` vs `allowUnsandboxedCommands`:**
+
+ * `excludedCommands`: A static list of commands that always bypass the sandbox automatically (e.g., `['docker']`). The model has no control over this.
+ * `allowUnsandboxedCommands`: Lets the model decide at runtime whether to request unsandboxed execution by setting `dangerouslyDisableSandbox: true` in the tool input.
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Deploy my application",
+ options: {
+ sandbox: {
+ enabled: true,
+ allowUnsandboxedCommands: true // Model can request unsandboxed execution
+ },
+ permissionMode: "default",
+ canUseTool: async (tool, input) => {
+ // Check if the model is requesting to bypass the sandbox
+ if (tool === "Bash" && input.dangerouslyDisableSandbox) {
+ // The model is requesting to run this command outside the sandbox
+ console.log(`Unsandboxed command requested: ${input.command}`);
+
+ if (isCommandAuthorized(input.command)) {
+ return { behavior: "allow" as const, updatedInput: input };
+ }
+ return {
+ behavior: "deny" as const,
+ message: "Command not authorized for unsandboxed execution"
+ };
+ }
+ return { behavior: "allow" as const, updatedInput: input };
+ }
+ }
+ })) {
+ if ("result" in message) console.log(message.result);
+ }
+
+This pattern enables you to:
+
+ * **Audit model requests:** Log when the model requests unsandboxed execution
+ * **Implement allowlists:** Only permit specific commands to run unsandboxed
+ * **Add approval workflows:** Require explicit authorization for privileged operations
+
+Commands running with `dangerouslyDisableSandbox: true` have full system access. Ensure your `canUseTool` handler validates these requests carefully.If `permissionMode` is set to `bypassPermissions` and `allowUnsandboxedCommands` is enabled, the model can autonomously execute commands outside the sandbox without any approval prompts. This combination effectively allows the model to escape sandbox isolation silently.
+
+##
+
+
+
+See also
+
+ * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts
+ * [Python SDK reference](</docs/en/agent-sdk/python>) \- Python SDK documentation
+ * [CLI reference](</docs/en/cli-reference>) \- Command-line interface
+ * [Common workflows](</docs/en/common-workflows>) \- Step-by-step guides
Show diff (283 lines)
--- a/typescript-v2-preview.md
+++ b/typescript-v2-preview.md
@@ -0,0 +1,280 @@
+The V2 interface is an **unstable preview**. APIs may change based on feedback before becoming stable. Some features like session forking are only available in the [V1 SDK](</docs/en/agent-sdk/typescript>).
+
+The V2 Claude Agent TypeScript SDK removes the need for async generators and yield coordination. This makes multi-turn conversations simpler, instead of managing generator state across turns, each turn is a separate `send()`/`stream()` cycle. The API surface reduces to three concepts:
+
+ * `createSession()` / `resumeSession()`: Start or continue a conversation
+ * `session.send()`: Send a message
+ * `session.stream()`: Get the response
+
+##
+
+
+
+Installation
+
+The V2 interface is included in the existing SDK package:
+
+ npm install @anthropic-ai/claude-agent-sdk
+
+##
+
+
+
+Quick start
+
+###
+
+
+
+One-shot prompt
+
+For simple single-turn queries where you don’t need to maintain a session, use `unstable_v2_prompt()`. This example sends a math question and logs the answer:
+
+ import { unstable_v2_prompt } from "@anthropic-ai/claude-agent-sdk";
+
+ const result = await unstable_v2_prompt("What is 2 + 2?", {
+ model: "claude-opus-4-6"
+ });
+ if (result.subtype === "success") {
+ console.log(result.result);
+ }
+
+###
+
+
+
+Basic session
+
+For interactions beyond a single prompt, create a session. V2 separates sending and streaming into distinct steps:
+
+ * `send()` dispatches your message
+ * `stream()` streams back the response
+
+This explicit separation makes it easier to add logic between turns (like processing responses before sending follow-ups). The example below creates a session, sends “Hello!” to Claude, and prints the text response. It uses [`await using`](<https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management>) (TypeScript 5.2+) to automatically close the session when the block exits. You can also call `session.close()` manually.
+
+ import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";
+
+ await using session = unstable_v2_createSession({
+ model: "claude-opus-4-6"
+ });
+
+ await session.send("Hello!");
+ for await (const msg of session.stream()) {
+ // Filter for assistant messages to get human-readable output
+ if (msg.type === "assistant") {
+ const text = msg.message.content
+ .filter((block) => block.type === "text")
+ .map((block) => block.text)
+ .join("");
+ console.log(text);
+ }
+ }
+
+###
+
+
+
+Multi-turn conversation
+
+Sessions persist context across multiple exchanges. To continue a conversation, call `send()` again on the same session. Claude remembers the previous turns. This example asks a math question, then asks a follow-up that references the previous answer:
+
+ import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";
+
+ await using session = unstable_v2_createSession({
+ model: "claude-opus-4-6"
+ });
+
+ // Turn 1
+ await session.send("What is 5 + 3?");
+ for await (const msg of session.stream()) {
+ // Filter for assistant messages to get human-readable output
+ if (msg.type === "assistant") {
+ const text = msg.message.content
+ .filter((block) => block.type === "text")
+ .map((block) => block.text)
+ .join("");
+ console.log(text);
+ }
+ }
+
+ // Turn 2
+ await session.send("Multiply that by 2");
+ for await (const msg of session.stream()) {
+ if (msg.type === "assistant") {
+ const text = msg.message.content
+ .filter((block) => block.type === "text")
+ .map((block) => block.text)
+ .join("");
+ console.log(text);
+ }
+ }
+
+###
+
+
+
+Session resume
+
+If you have a session ID from a previous interaction, you can resume it later. This is useful for long-running workflows or when you need to persist conversations across application restarts. This example creates a session, stores its ID, closes it, then resumes the conversation:
+
+ import {
+ unstable_v2_createSession,
+ unstable_v2_resumeSession,
+ type SDKMessage
+ } from "@anthropic-ai/claude-agent-sdk";
+
+ // Helper to extract text from assistant messages
+ function getAssistantText(msg: SDKMessage): string | null {
+ if (msg.type !== "assistant") return null;
+ return msg.message.content
+ .filter((block) => block.type === "text")
+ .map((block) => block.text)
+ .join("");
+ }
+
+ // Create initial session and have a conversation
+ const session = unstable_v2_createSession({
+ model: "claude-opus-4-6"
+ });
+
+ await session.send("Remember this number: 42");
+
+ // Get the session ID from any received message
+ let sessionId: string | undefined;
+ for await (const msg of session.stream()) {
+ sessionId = msg.session_id;
+ const text = getAssistantText(msg);
+ if (text) console.log("Initial response:", text);
+ }
+
+ console.log("Session ID:", sessionId);
+ session.close();
+
+ // Later: resume the session using the stored ID
+ await using resumedSession = unstable_v2_resumeSession(sessionId!, {
+ model: "claude-opus-4-6"
+ });
+
+ await resumedSession.send("What number did I ask you to remember?");
+ for await (const msg of resumedSession.stream()) {
+ const text = getAssistantText(msg);
+ if (text) console.log("Resumed response:", text);
+ }
+
+###
+
+
+
+Cleanup
+
+Sessions can be closed manually or automatically using [`await using`](<https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management>), a TypeScript 5.2+ feature for automatic resource cleanup. If you’re using an older TypeScript version or encounter compatibility issues, use manual cleanup instead. **Automatic cleanup (TypeScript 5.2+):**
+
+ import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";
+
+ await using session = unstable_v2_createSession({
+ model: "claude-opus-4-6"
+ });
+ // Session closes automatically when the block exits
+
+**Manual cleanup:**
+
+ import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";
+
+ const session = unstable_v2_createSession({
+ model: "claude-opus-4-6"
+ });
+ // ... use the session ...
+ session.close();
+
+##
+
+
+
+API reference
+
+###
+
+
+
+`unstable_v2_createSession()`
+
+Creates a new session for multi-turn conversations.
+
+ function unstable_v2_createSession(options: {
+ model: string;
+ // Additional options supported
+ }): SDKSession;
+
+###
+
+
+
+`unstable_v2_resumeSession()`
+
+Resumes an existing session by ID.
+
+ function unstable_v2_resumeSession(
+ sessionId: string,
+ options: {
+ model: string;
+ // Additional options supported
+ }
+ ): SDKSession;
+
+###
+
+
+
+`unstable_v2_prompt()`
+
+One-shot convenience function for single-turn queries.
+
+ function unstable_v2_prompt(
+ prompt: string,
+ options: {
+ model: string;
+ // Additional options supported
+ }
+ ): Promise<SDKResultMessage>;
+
+###
+
+
+
+SDKSession interface
+
+ interface SDKSession {
+ readonly sessionId: string;
+ send(message: string | SDKUserMessage): Promise<void>;
+ stream(): AsyncGenerator<SDKMessage, void>;
+ close(): void;
+ }
+
+##
+
+
+
+Feature availability
+
+Not all V1 features are available in V2 yet. The following require using the [V1 SDK](</docs/en/agent-sdk/typescript>):
+
+ * Session forking (`forkSession` option)
+ * Some advanced streaming input patterns
+
+##
+
+
+
+Feedback
+
+Share your feedback on the V2 interface before it becomes stable. Report issues and suggestions through [GitHub Issues](<https://github.com/anthropics/claude-code/issues>).
+
+##
+
+
+
+See also
+
+ * [TypeScript SDK reference (V1)](</docs/en/agent-sdk/typescript>) \- Full V1 SDK documentation
+ * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts
+ * [V2 examples on GitHub](<https://github.com/anthropics/claude-agent-sdk-demos/tree/main/hello-world-v2>) \- Working code examples
--- a/ultraplan.md
+++ b/ultraplan.md
@@ -6,7 +6,7 @@
* **Hands-off drafting** : the plan is generated remotely, so your terminal stays free for other work
* **Flexible execution** : approve the plan to run on the web and open a pull request, or send it back to your terminal
-Ultraplan requires a [Claude Code on the web](</docs/en/claude-code-on-the-web#who-can-use-claude-code-on-the-web>) account and a GitHub repository. Because it runs on Anthropic’s cloud infrastructure, it is not available when using Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry. The cloud session runs in your account’s default [cloud environment](</docs/en/claude-code-on-the-web#cloud-environment>).
+Ultraplan requires a [Claude Code on the web](</docs/en/claude-code-on-the-web>) account and a GitHub repository. Because it runs on Anthropic’s cloud infrastructure, it is not available when using Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry. The cloud session runs in your account’s default [cloud environment](</docs/en/claude-code-on-the-web#the-cloud-environment>).
##
@@ -62,7 +62,7 @@
Execute on the web
-Select **Approve Claude’s plan and start coding** in your browser to have Claude implement it in the same Claude Code on the web session. Your terminal shows a confirmation, the status indicator clears, and the work continues in the cloud. When the implementation finishes, [review the diff](</docs/en/claude-code-on-the-web#review-changes-with-diff-view>) and create a pull request from the web interface.
+Select **Approve Claude’s plan and start coding** in your browser to have Claude implement it in the same Claude Code on the web session. Your terminal shows a confirmation, the status indicator clears, and the work continues in the cloud. When the implementation finishes, [review the diff](</docs/en/claude-code-on-the-web#review-changes>) and create a pull request from the web interface.
###
Show diff (595 lines)
--- a/user-input.md
+++ b/user-input.md
@@ -0,0 +1,592 @@
+While working on a task, Claude sometimes needs to check in with users. It might need permission before deleting files, or need to ask which database to use for a new project. Your application needs to surface these requests to users so Claude can continue with their input. Claude requests user input in two situations: when it needs **permission to use a tool** (like deleting files or running commands), and when it has **clarifying questions** (via the `AskUserQuestion` tool). Both trigger your `canUseTool` callback, which pauses execution until you return a response. This is different from normal conversation turns where Claude finishes and waits for your next message. For clarifying questions, Claude generates the questions and options. Your role is to present them to users and return their selections. You can’t add your own questions to this flow; if you need to ask users something yourself, do that separately in your application logic. This guide shows you how to detect each type of request and respond appropriately.
+
+##
+
+
+
+Detect when Claude needs input
+
+Pass a `canUseTool` callback in your query options. The callback fires whenever Claude needs user input, receiving the tool name and input as arguments:
+
+Python
+
+TypeScript
+
+ async def handle_tool_request(tool_name, input_data, context):
+ # Prompt user and return allow or deny
+ ...
+
+ options = ClaudeAgentOptions(can_use_tool=handle_tool_request)
+
+The callback fires in two cases:
+
+ 1. **Tool needs approval** : Claude wants to use a tool that isn’t auto-approved by [permission rules](</docs/en/agent-sdk/permissions>) or modes. Check `tool_name` for the tool (e.g., `"Bash"`, `"Write"`).
+ 2. **Claude asks a question** : Claude calls the `AskUserQuestion` tool. Check if `tool_name == "AskUserQuestion"` to handle it differently. If you specify a `tools` array, include `AskUserQuestion` for this to work. See Handle clarifying questions for details.
+
+To automatically allow or deny tools without prompting users, use [hooks](</docs/en/agent-sdk/hooks>) instead. Hooks execute before `canUseTool` and can allow, deny, or modify requests based on your own logic. You can also use the [`PermissionRequest` hook](</docs/en/agent-sdk/hooks#available-hooks>) to send external notifications (Slack, email, push) when Claude is waiting for approval.
+
+##
+
+
+
+Handle tool approval requests
+
+Once you’ve passed a `canUseTool` callback in your query options, it fires when Claude wants to use a tool that isn’t auto-approved. Your callback receives three arguments:
+
+Argument| Description
+---|---
+`toolName`| The name of the tool Claude wants to use (e.g., `"Bash"`, `"Write"`, `"Edit"`)
+`input`| The parameters Claude is passing to the tool. Contents vary by tool.
+`options` (TS) / `context` (Python)| Additional context including optional `suggestions` (proposed `PermissionUpdate` entries to avoid re-prompting) and a cancellation signal. In TypeScript, `signal` is an `AbortSignal`; in Python, the signal field is reserved for future use. See [`ToolPermissionContext`](</docs/en/agent-sdk/python#tool-permission-context>) for Python.
+
+The `input` object contains tool-specific parameters. Common examples:
+
+Tool| Input fields
+---|---
+`Bash`| `command`, `description`, `timeout`
+`Write`| `file_path`, `content`
+`Edit`| `file_path`, `old_string`, `new_string`
+`Read`| `file_path`, `offset`, `limit`
+
+See the SDK reference for complete input schemas: [Python](</docs/en/agent-sdk/python#tool-input-output-types>) | [TypeScript](</docs/en/agent-sdk/typescript#tool-input-types>). You can display this information to the user so they can decide whether to allow or reject the action, then return the appropriate response. The following example asks Claude to create and delete a test file. When Claude attempts each operation, the callback prints the tool request to the terminal and prompts for y/n approval.
+
+Python
+
+TypeScript
+
+ import asyncio
+
+ from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
+ from claude_agent_sdk.types import (
+ HookMatcher,
+ PermissionResultAllow,
+ PermissionResultDeny,
+ ToolPermissionContext,
+ )
+
+ async def can_use_tool(
+ tool_name: str, input_data: dict, context: ToolPermissionContext
+ ) -> PermissionResultAllow | PermissionResultDeny:
+ # Display the tool request
+ print(f"\nTool: {tool_name}")
+ if tool_name == "Bash":
+ print(f"Command: {input_data.get('command')}")
+ if input_data.get("description"):
+ print(f"Description: {input_data.get('description')}")
+ else:
+ print(f"Input: {input_data}")
+
+ # Get user approval
+ response = input("Allow this action? (y/n): ")
+
+ # Return allow or deny based on user's response
+ if response.lower() == "y":
+ # Allow: tool executes with the original (or modified) input
+ return PermissionResultAllow(updated_input=input_data)
+ else:
+ # Deny: tool doesn't execute, Claude sees the message
+ return PermissionResultDeny(message="User denied this action")
+
+ # Required workaround: dummy hook keeps the stream open for can_use_tool
+ async def dummy_hook(input_data, tool_use_id, context):
+ return {"continue_": True}
+
+ async def prompt_stream():
+ yield {
+ "type": "user",
+ "message": {
+ "role": "user",
+ "content": "Create a test file in /tmp and then delete it",
+ },
+ }
+
+ async def main():
+ async for message in query(
+ prompt=prompt_stream(),
+ options=ClaudeAgentOptions(
+ can_use_tool=can_use_tool,
+ hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]},
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+
+ asyncio.run(main())
+
+In Python, `can_use_tool` requires [streaming mode](</docs/en/agent-sdk/streaming-vs-single-mode>) and a `PreToolUse` hook that returns `{"continue_": True}` to keep the stream open. Without this hook, the stream closes before the permission callback can be invoked.
+
+This example uses a `y/n` flow where any input other than `y` is treated as a denial. In practice, you might build a richer UI that lets users modify the request, provide feedback, or redirect Claude entirely. See Respond to tool requests for all the ways you can respond.
+
+###
+
+
+
+Respond to tool requests
+
+Your callback returns one of two response types:
+
+Response| Python| TypeScript
+---|---|---
+**Allow**| `PermissionResultAllow(updated_input=...)`| `{ behavior: "allow", updatedInput }`
+**Deny**| `PermissionResultDeny(message=...)`| `{ behavior: "deny", message }`
+
+When allowing, pass the tool input (original or modified). When denying, provide a message explaining why. Claude sees this message and may adjust its approach.
+
+Python
+
+TypeScript
+
+ from claude_agent_sdk.types import PermissionResultAllow, PermissionResultDeny
+
+ # Allow the tool to execute
+ return PermissionResultAllow(updated_input=input_data)
+
+ # Block the tool
+ return PermissionResultDeny(message="User rejected this action")
+
+Beyond allowing or denying, you can modify the tool’s input or provide context that helps Claude adjust its approach:
+
+ * **Approve** : let the tool execute as Claude requested
+ * **Approve with changes** : modify the input before execution (e.g., sanitize paths, add constraints)
+ * **Reject** : block the tool and tell Claude why
+ * **Suggest alternative** : block but guide Claude toward what the user wants instead
+ * **Redirect entirely** : use [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>) to send Claude a completely new instruction
+
+ * Approve
+
+ * Approve with changes
+
+ * Reject
+
+ * Suggest alternative
+
+ * Redirect entirely
+
+The user approves the action as-is. Pass through the `input` from your callback unchanged and the tool executes exactly as Claude requested.
+
+Python
+
+TypeScript
+
+ async def can_use_tool(tool_name, input_data, context):
+ print(f"Claude wants to use {tool_name}")
+ approved = await ask_user("Allow this action?")
+
+ if approved:
+ return PermissionResultAllow(updated_input=input_data)
+ return PermissionResultDeny(message="User declined")
+
+The user approves but wants to modify the request first. You can change the input before the tool executes. Claude sees the result but isn’t told you changed anything. Useful for sanitizing parameters, adding constraints, or scoping access.
+
+Python
+
+TypeScript
+
+ async def can_use_tool(tool_name, input_data, context):
+ if tool_name == "Bash":
+ # User approved, but scope all commands to sandbox
+ sandboxed_input = {**input_data}
+ sandboxed_input["command"] = input_data["command"].replace(
+ "/tmp", "/tmp/sandbox"
+ )
+ return PermissionResultAllow(updated_input=sandboxed_input)
+ return PermissionResultAllow(updated_input=input_data)
+
+The user doesn’t want this action to happen. Block the tool and provide a message explaining why. Claude sees this message and may try a different approach.
+
+Python
+
+TypeScript
+
+ async def can_use_tool(tool_name, input_data, context):
+ approved = await ask_user(f"Allow {tool_name}?")
+
+ if not approved:
+ return PermissionResultDeny(message="User rejected this action")
+ return PermissionResultAllow(updated_input=input_data)
+
+The user doesn’t want this specific action, but has a different idea. Block the tool and include guidance in your message. Claude will read this and decide how to proceed based on your feedback.
+
+Python
+
+TypeScript
+
+ async def can_use_tool(tool_name, input_data, context):
+ if tool_name == "Bash" and "rm" in input_data.get("command", ""):
+ # User doesn't want to delete, suggest archiving instead
+ return PermissionResultDeny(
+ message="User doesn't want to delete files. They asked if you could compress them into an archive instead."
+ )
+ return PermissionResultAllow(updated_input=input_data)
+
+For a complete change of direction (not just a nudge), use [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>) to send Claude a new instruction directly. This bypasses the current tool request and gives Claude entirely new instructions to follow.
+
+##
+
+
+
+Handle clarifying questions
+
+When Claude needs more direction on a task with multiple valid approaches, it calls the `AskUserQuestion` tool. This triggers your `canUseTool` callback with `toolName` set to `AskUserQuestion`. The input contains Claude’s questions as multiple-choice options, which you display to the user and return their selections.
+
+Clarifying questions are especially common in [`plan` mode](</docs/en/agent-sdk/permissions#plan-mode-plan>), where Claude explores the codebase and asks questions before proposing a plan. This makes plan mode ideal for interactive workflows where you want Claude to gather requirements before making changes.
+
+The following steps show how to handle clarifying questions:
+
+1
+
+Pass a canUseTool callback
+
+Pass a `canUseTool` callback in your query options. By default, `AskUserQuestion` is available. If you specify a `tools` array to restrict Claude’s capabilities (for example, a read-only agent with only `Read`, `Glob`, and `Grep`), include `AskUserQuestion` in that array. Otherwise, Claude won’t be able to ask clarifying questions:
+
+Python
+
+TypeScript
+
+ async for message in query(
+ prompt="Analyze this codebase",
+ options=ClaudeAgentOptions(
+ # Include AskUserQuestion in your tools list
+ tools=["Read", "Glob", "Grep", "AskUserQuestion"],
+ can_use_tool=can_use_tool,
+ ),
+ ):
+ print(message)
+
+2
+
+Detect AskUserQuestion
+
+In your callback, check if `toolName` equals `AskUserQuestion` to handle it differently from other tools:
+
+Python
+
+TypeScript
+
+ async def can_use_tool(tool_name: str, input_data: dict, context):
+ if tool_name == "AskUserQuestion":
+ # Your implementation to collect answers from the user
+ return await handle_clarifying_questions(input_data)
+ # Handle other tools normally
+ return await prompt_for_approval(tool_name, input_data)
+
+3
+
+Parse the question input
+
+The input contains Claude’s questions in a `questions` array. Each question has a `question` (the text to display), `options` (the choices), and `multiSelect` (whether multiple selections are allowed):
+
+ {
+ "questions": [
+ {
+ "question": "How should I format the output?",
+ "header": "Format",
+ "options": [
+ { "label": "Summary", "description": "Brief overview" },
+ { "label": "Detailed", "description": "Full explanation" }
+ ],
+ "multiSelect": false
+ },
+ {
+ "question": "Which sections should I include?",
+ "header": "Sections",
+ "options": [
+ { "label": "Introduction", "description": "Opening context" },
+ { "label": "Conclusion", "description": "Final summary" }
+ ],
+ "multiSelect": true
+ }
+ ]
+ }
+
+See Question format for full field descriptions.
+
+4
+
+Collect answers from the user
+
+Present the questions to the user and collect their selections. How you do this depends on your application: a terminal prompt, a web form, a mobile dialog, etc.
+
+5
+
+Return answers to Claude
+
+Build the `answers` object as a record where each key is the `question` text and each value is the selected option’s `label`:
+
+From the question object| Use as
+---|---
+`question` field (e.g., `"How should I format the output?"`)| Key
+Selected option’s `label` field (e.g., `"Summary"`)| Value
+
+For multi-select questions, join multiple labels with `", "`. If you support free-text input, use the user’s custom text as the value.
+
+Python
+
+TypeScript
+
+ return PermissionResultAllow(
+ updated_input={
+ "questions": input_data.get("questions", []),
+ "answers": {
+ "How should I format the output?": "Summary",
+ "Which sections should I include?": "Introduction, Conclusion",
+ },
+ }
+ )
+
+###
+
+
+
+Question format
+
+The input contains Claude’s generated questions in a `questions` array. Each question has these fields:
+
+Field| Description
+---|---
+`question`| The full question text to display
+`header`| Short label for the question (max 12 characters)
+`options`| Array of 2-4 choices, each with `label` and `description`. TypeScript: optionally `preview` (see below)
+`multiSelect`| If `true`, users can select multiple options
+
+The structure your callback receives:
+
+ {
+ "questions": [
+ {
+ "question": "How should I format the output?",
+ "header": "Format",
+ "options": [
+ { "label": "Summary", "description": "Brief overview of key points" },
+ { "label": "Detailed", "description": "Full explanation with examples" }
+ ],
+ "multiSelect": false
+ }
+ ]
+ }
+
+####
+
+
+
+Option previews (TypeScript)
+
+`toolConfig.askUserQuestion.previewFormat` adds a `preview` field to each option so your app can show a visual mockup alongside the label. Without this setting, Claude does not generate previews and the field is absent.
+
+`previewFormat`| `preview` contains
+---|---
+unset (default)| Field is absent. Claude does not generate previews.
+`"markdown"`| ASCII art and fenced code blocks
+`"html"`| A styled `<div>` fragment (the SDK rejects `<script>`, `<style>`, and `<!DOCTYPE>` before your callback runs)
+
+The format applies to all questions in the session. Claude includes `preview` on options where a visual comparison helps (layout choices, color schemes) and omits it where one wouldn’t (yes/no confirmations, text-only choices). Check for `undefined` before rendering.
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ for await (const message of query({
+ prompt: "Help me choose a card layout",
+ options: {
+ toolConfig: {
+ askUserQuestion: { previewFormat: "html" }
+ },
+ canUseTool: async (toolName, input) => {
+ // input.questions[].options[].preview is an HTML string or undefined
+ return { behavior: "allow", updatedInput: input };
+ }
+ }
+ })) {
+ // ...
+ }
+
+An option with an HTML preview:
+
+ {
+ "label": "Compact",
+ "description": "Title and metric value only",
+ "preview": "<div style=\"padding:12px;border:1px solid #ddd;border-radius:8px\"><div style=\"font-size:12px;color:#666\">Active users</div><div style=\"font-size:28px;font-weight:600\">1,284</div></div>"
+ }
+
+###
+
+
+
+Response format
+
+Return an `answers` object mapping each question’s `question` field to the selected option’s `label`:
+
+Field| Description
+---|---
+`questions`| Pass through the original questions array (required for tool processing)
+`answers`| Object where keys are question text and values are selected labels
+
+For multi-select questions, join multiple labels with `", "`. For free-text input, use the user’s custom text directly.
+
+ {
+ "questions": [
+ // ...
+ ],
+ "answers": {
+ "How should I format the output?": "Summary",
+ "Which sections should I include?": "Introduction, Conclusion"
+ }
+ }
+
+####
+
+
+
+Support free-text input
+
+Claude’s predefined options won’t always cover what users want. To let users type their own answer:
+
+ * Display an additional “Other” choice after Claude’s options that accepts text input
+ * Use the user’s custom text as the answer value (not the word “Other”)
+
+See the complete example below for a full implementation.
+
+###
+
+
+
+Complete example
+
+Claude asks clarifying questions when it needs user input to proceed. For example, when asked to help decide on a tech stack for a mobile app, Claude might ask about cross-platform vs native, backend preferences, or target platforms. These questions help Claude make decisions that match the user’s preferences rather than guessing. This example handles those questions in a terminal application. Here’s what happens at each step:
+
+ 1. **Route the request** : The `canUseTool` callback checks if the tool name is `"AskUserQuestion"` and routes to a dedicated handler
+ 2. **Display questions** : The handler loops through the `questions` array and prints each question with numbered options
+ 3. **Collect input** : The user can enter a number to select an option, or type free text directly (e.g., “jquery”, “i don’t know”)
+ 4. **Map answers** : The code checks if input is numeric (uses the option’s label) or free text (uses the text directly)
+ 5. **Return to Claude** : The response includes both the original `questions` array and the `answers` mapping
+
+Python
+
+TypeScript
+
+ import asyncio
+
+ from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
+ from claude_agent_sdk.types import HookMatcher, PermissionResultAllow
+
+ def parse_response(response: str, options: list) -> str:
+ """Parse user input as option number(s) or free text."""
+ try:
+ indices = [int(s.strip()) - 1 for s in response.split(",")]
+ labels = [options[i]["label"] for i in indices if 0 <= i < len(options)]
+ return ", ".join(labels) if labels else response
+ except ValueError:
+ return response
+
+ async def handle_ask_user_question(input_data: dict) -> PermissionResultAllow:
+ """Display Claude's questions and collect user answers."""
+ answers = {}
+
+ for q in input_data.get("questions", []):
+ print(f"\n{q['header']}: {q['question']}")
+
+ options = q["options"]
+ for i, opt in enumerate(options):
+ print(f" {i + 1}. {opt['label']} - {opt['description']}")
+ if q.get("multiSelect"):
+ print(" (Enter numbers separated by commas, or type your own answer)")
+ else:
+ print(" (Enter a number, or type your own answer)")
+
+ response = input("Your choice: ").strip()
+ answers[q["question"]] = parse_response(response, options)
+
+ return PermissionResultAllow(
+ updated_input={
+ "questions": input_data.get("questions", []),
+ "answers": answers,
+ }
+ )
+
+ async def can_use_tool(
+ tool_name: str, input_data: dict, context
+ ) -> PermissionResultAllow:
+ # Route AskUserQuestion to our question handler
+ if tool_name == "AskUserQuestion":
+ return await handle_ask_user_question(input_data)
+ # Auto-approve other tools for this example
+ return PermissionResultAllow(updated_input=input_data)
+
+ async def prompt_stream():
+ yield {
+ "type": "user",
+ "message": {
+ "role": "user",
+ "content": "Help me decide on the tech stack for a new mobile app",
+ },
+ }
+
+ # Required workaround: dummy hook keeps the stream open for can_use_tool
+ async def dummy_hook(input_data, tool_use_id, context):
+ return {"continue_": True}
+
+ async def main():
+ async for message in query(
+ prompt=prompt_stream(),
+ options=ClaudeAgentOptions(
+ can_use_tool=can_use_tool,
+ hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]},
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.subtype == "success":
+ print(message.result)
+
+ asyncio.run(main())
+
+##
+
+
+
+Limitations
+
+ * **Subagents** : `AskUserQuestion` is not currently available in subagents spawned via the Agent tool
+ * **Question limits** : each `AskUserQuestion` call supports 1-4 questions with 2-4 options each
+
+##
+
+
+
+Other ways to get user input
+
+The `canUseTool` callback and `AskUserQuestion` tool cover most approval and clarification scenarios, but the SDK offers other ways to get input from users:
+
+###
+
+
+
+Streaming input
+
+Use [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>) when you need to:
+
+ * **Interrupt the agent mid-task** : send a cancel signal or change direction while Claude is working
+ * **Provide additional context** : add information Claude needs without waiting for it to ask
+ * **Build chat interfaces** : let users send follow-up messages during long-running operations
+
+Streaming input is ideal for conversational UIs where users interact with the agent throughout execution, not just at approval checkpoints.
+
+###
+
+
+
+Custom tools
+
+Use [custom tools](</docs/en/agent-sdk/custom-tools>) when you need to:
+
+ * **Collect structured input** : build forms, wizards, or multi-step workflows that go beyond `AskUserQuestion`’s multiple-choice format
+ * **Integrate external approval systems** : connect to existing ticketing, workflow, or approval platforms
+ * **Implement domain-specific interactions** : create tools tailored to your application’s needs, like code review interfaces or deployment checklists
+
+Custom tools give you full control over the interaction, but require more implementation work than using the built-in `canUseTool` callback.
+
+##
+
+
+
+Related resources
+
+ * [Configure permissions](</docs/en/agent-sdk/permissions>): set up permission modes and rules
+ * [Control execution with hooks](</docs/en/agent-sdk/hooks>): run custom code at key points in the agent lifecycle
+ * [TypeScript SDK reference](</docs/en/agent-sdk/typescript#can-use-tool>): full canUseTool API documentation
Show diff (260 lines)
--- a/web-quickstart.md
+++ b/web-quickstart.md
@@ -0,0 +1,257 @@
+Claude Code on the web is in research preview for Pro, Max, and Team users, and for Enterprise users with premium seats or Chat + Claude Code seats.
+
+Claude Code on the web runs on Anthropic-managed cloud infrastructure instead of your machine. Submit tasks from [claude.ai/code](<https://claude.ai/code>) in your browser or the Claude mobile app. You’ll need a GitHub repository to get started. Claude clones it into an isolated virtual machine, makes changes, and pushes a branch for you to review. Sessions persist across devices, so a task you start on your laptop is ready to review from your phone later. Claude Code on the web works well for:
+
+ * **Parallel tasks** : run several independent tasks at once, each in its own session and branch, without managing multiple worktrees
+ * **Repos you don’t have locally** : Claude clones the repo fresh every session, so you don’t need it checked out
+ * **Tasks that don’t need frequent steering** : submit a well-defined task, do something else, and review the result when Claude is done
+ * **Code questions and exploration** : understand a codebase or trace how a feature is implemented without a local checkout
+
+For work that needs your local config, tools, or environment, running Claude Code locally or using [Remote Control](</docs/en/remote-control>) is a better fit.
+
+##
+
+
+
+How sessions run
+
+When you submit a task:
+
+ 1. **Clone and prepare** : your repository is cloned to an Anthropic-managed VM, and your [setup script](</docs/en/claude-code-on-the-web#setup-scripts>) runs if configured.
+ 2. **Configure network** : internet access is set based on your environment’s [access level](</docs/en/claude-code-on-the-web#access-levels>).
+ 3. **Work** : Claude analyzes code, makes changes, runs tests, and checks its work. You can watch and steer throughout, or step away and come back when it’s done.
+ 4. **Push the branch** : when Claude reaches a stopping point, it pushes its branch to GitHub. You review the diff, leave inline comments, create a PR, or send another message to keep going.
+
+The session doesn’t close when the branch is pushed. PR creation and further edits all happen within the same conversation.
+
+##
+
+
+
+Compare ways to run Claude Code
+
+Claude Code behaves the same everywhere. What changes is where code executes and whether your local config is available. The Desktop app offers both local and cloud sessions, so its answers below depend on which you choose:
+
+| On the web| Remote Control| Terminal CLI| Desktop app
+---|---|---|---|---
+**Code runs on**| Anthropic cloud VM| Your machine| Your machine| Your machine or cloud VM
+**You chat from**| claude.ai or mobile app| claude.ai or mobile app| Your terminal| The Desktop UI
+**Uses your local config**| No, repo only| Yes| Yes| Yes for local, no for cloud
+**Requires GitHub**| Yes, or [bundle a local repo](</docs/en/claude-code-on-the-web#send-local-repositories-without-github>) via `--remote`| No| No| Only for cloud sessions
+**Keeps running if you disconnect**| Yes| While terminal stays open| No| Depends on session type
+**[Permission modes](</docs/en/permission-modes>)**| Auto accept edits, Plan| Ask, Auto accept edits, Plan| All modes| Depends on session type
+**Network access**| Configurable per environment| Your machine’s network| Your machine’s network| Depends on session type
+
+See the [terminal quickstart](</docs/en/quickstart>), [Desktop app](</docs/en/desktop>), or [Remote Control](</docs/en/remote-control>) docs to set those up.
+
+##
+
+
+
+Connect GitHub and create an environment
+
+Setup is a one-time process. If you already use the GitHub CLI, you can do this from your terminal instead of the browser.
+
+1
+
+Visit claude.ai/code
+
+Go to [claude.ai/code](<https://claude.ai/code>) and sign in with your Anthropic account.
+
+2
+
+Install the Claude GitHub App
+
+After signing in, claude.ai/code prompts you to connect GitHub. Follow the prompt to install the Claude GitHub App and grant it access to your repositories. Cloud sessions work with existing GitHub repositories, so to start a new project, [create an empty repository on GitHub](<https://github.com/new>) first.
+
+3
+
+Create your environment
+
+After connecting GitHub, you’ll be prompted to create a cloud environment. The environment controls what network access Claude has during sessions and what runs when a new session is created. See [Installed tools](</docs/en/claude-code-on-the-web#installed-tools>) for what’s available without any configuration.The form has these fields:
+
+ * **Name** : a display label. Useful when you have multiple environments for different projects or access levels.
+ * **Network access** : controls what the session can reach on the internet. The default, `Trusted`, allows connections to [common package registries](</docs/en/claude-code-on-the-web#default-allowed-domains>) like npm, PyPI, and RubyGems while blocking general internet access.
+ * **Environment variables** : optional variables available in every session, in `.env` format. Don’t wrap values in quotes, since quotes are stored as part of the value. These are visible to anyone who can edit this environment.
+ * **Setup script** : an optional Bash script that runs before Claude Code launches when a new session is created. Use it to install system tools the cloud VM doesn’t include, like `apt install -y gh`, or to start services your project needs. See [Setup scripts](</docs/en/claude-code-on-the-web#setup-scripts>) for examples and debugging tips.
+
+For a first project, leave the defaults and click **Create environment**. You can [edit it later or create additional environments](</docs/en/claude-code-on-the-web#configure-your-environment>) for different projects.
+
+###
+
+
+
+Connect from your terminal
+
+If you already use the GitHub CLI (`gh`), you can set up Claude Code on the web without opening a browser. This requires the [Claude Code CLI](</docs/en/quickstart>). `/web-setup` reads your local `gh` token, links it to your Claude account, and creates a default cloud environment if you don’t have one.
+
+Organizations with [Zero Data Retention](</docs/en/zero-data-retention>) enabled cannot use `/web-setup` or other cloud session features. If the GitHub CLI isn’t installed or authenticated, `/web-setup` opens the browser onboarding flow instead.
+
+1
+
+Authenticate with the GitHub CLI
+
+In your shell, authenticate the GitHub CLI if you haven’t already:
+
+ gh auth login
+
+2
+
+Sign in to Claude
+
+In the Claude Code CLI, run `/login` to sign in with your claude.ai account. Skip this step if you’re already signed in.
+
+3
+
+Run /web-setup
+
+In the Claude Code CLI, run:
+
+ /web-setup
+
+This syncs your `gh` token to your Claude account. If you don’t have a cloud environment yet, `/web-setup` creates one with Trusted network access and no setup script. You can [edit the environment or add variables](</docs/en/claude-code-on-the-web#configure-your-environment>) afterward. Once `/web-setup` completes, you can start cloud sessions from your terminal with [`--remote`](</docs/en/claude-code-on-the-web#from-terminal-to-web>) or set up recurring tasks with [`/schedule`](</docs/en/web-scheduled-tasks>).
+
+##
+
+
+
+Start a task
+
+With GitHub connected and an environment created, you’re ready to submit tasks.
+
+1
+
+Select a repository and branch
+
+From [claude.ai/code](<https://claude.ai/code>) or the Code tab in the Claude mobile app, click the repository selector below the input box and choose a repository for Claude to work in. Each repository shows a branch selector. Change it to start Claude from a feature branch instead of the default. You can add multiple repositories to work across them in one session.
+
+2
+
+Choose a permission mode
+
+The mode dropdown next to the input defaults to **Auto accept edits** , where Claude makes changes and pushes a branch without stopping for approval. Switch to **Plan mode** if you want Claude to propose an approach and wait for your go-ahead before editing files. Cloud sessions don’t offer Ask permissions, Auto mode, or Bypass permissions. See [Permission modes](</docs/en/permission-modes>) for the full list.
+
+3
+
+Describe the task and submit
+
+Type a description of what you want and press Enter. Be specific:
+
+ * Name the file or function: “Add a README with setup instructions” or “Fix the failing auth test in `tests/test_auth.py`” is better than “fix tests”
+ * Paste error output if you have it
+ * Describe the expected behavior, not just the symptom
+
+Claude clones the repositories, runs your setup script if configured, and starts working. Each task gets its own session and its own branch, so you don’t need to wait for one to finish before starting another.
+
+##
+
+
+
+Review and iterate
+
+When Claude finishes, review the changes, leave feedback on specific lines, and keep going until the diff looks right.
+
+1
+
+Open the diff view
+
+A diff indicator shows lines added and removed across the session, for example `+42 -18`. Select it to open the diff view, with a file list on the left and changes on the right.
+
+2
+
+Leave inline comments
+
+Select any line in the diff, type your feedback, and press Enter. Comments queue up until you send your next message, then they’re bundled with it. Claude sees “at `src/auth.ts:47`, don’t catch the error here” alongside your main instruction, so you don’t have to describe where the problem is.
+
+3
+
+Create a pull request
+
+When the diff looks right, select **Create PR** at the top of the diff view. You can open it as a full PR, a draft, or jump to GitHub’s compose page with a generated title and description.
+
+4
+
+Keep iterating after the PR
+
+The session stays live after the PR is created. Paste CI failure output or reviewer comments into the chat and ask Claude to address them. To have Claude monitor the PR automatically, see [Auto-fix pull requests](</docs/en/claude-code-on-the-web#auto-fix-pull-requests>).
+
+##
+
+
+
+Troubleshoot setup
+
+###
+
+
+
+No repositories appear after connecting GitHub
+
+The Claude GitHub App needs explicit access to each repository you want to use. On github.com, open **Settings → Applications → Claude → Configure** and verify your repo is listed under **Repository access**. Private repositories need the same authorization as public ones.
+
+###
+
+
+
+The page only shows a GitHub login button
+
+Cloud sessions require a connected GitHub account. Connect via the browser flow above, or run `/web-setup` from your terminal if you use the GitHub CLI. If you’d rather not connect GitHub at all, see [Remote Control](</docs/en/remote-control>) to run Claude Code on your own machine and monitor it from the web.
+
+###
+
+
+
+”Not available for the selected organization”
+
+Enterprise organizations may need an admin to enable Claude Code on the web. Contact your Anthropic account team.
+
+###
+
+
+
+`/web-setup` returns “Unknown command”
+
+`/web-setup` runs inside the Claude Code CLI, not your shell. Launch `claude` first, then type `/web-setup` at the prompt. If you typed it inside Claude Code and still see the error, your CLI is older than v2.1.80 or you’re authenticated with an API key or third-party provider instead of a claude.ai subscription. Run `claude update`, then `/login` to sign in with your claude.ai account.
+
+###
+
+
+
+”No cloud environment available” when using `--remote`
+
+You haven’t created a cloud environment yet. Run `/web-setup` in the Claude Code CLI to create one, or visit [claude.ai/code](<https://claude.ai/code>) and follow the **Create your environment** step above.
+
+###
+
+
+
+Setup script failed
+
+The setup script exited with a non-zero status, which blocks the session from starting. Common causes:
+
+ * A package install failed because the registry isn’t in your [network access level](</docs/en/claude-code-on-the-web#access-levels>). `Trusted` covers most package managers; `None` blocks them all.
+ * The script references a file or path that doesn’t exist in a fresh clone.
+ * A command that works locally needs a different invocation on Ubuntu.
+
+To debug, add `set -x` at the top of the script to see which command failed. For non-critical commands, append `|| true` so they don’t block session start.
+
+###
+
+
+
+Session keeps running after closing the tab
+
+This is by design. Closing the tab or navigating away doesn’t stop the session. It continues running in the background until Claude finishes the current task, then idles. From the sidebar, you can [archive a session](</docs/en/claude-code-on-the-web#archive-sessions>) to hide it from your list, or [delete it](</docs/en/claude-code-on-the-web#delete-sessions>) to remove it permanently.
+
+##
+
+
+
+Next steps
+
+Now that you can submit and review tasks, these pages cover what comes next: starting cloud sessions from your terminal, scheduling recurring work, and giving Claude standing instructions.
+
+ * [Use Claude Code on the web](</docs/en/claude-code-on-the-web>): the full reference, including teleporting sessions to your terminal, setup scripts, environment variables, and network config
+ * [Schedule tasks on the web](</docs/en/web-scheduled-tasks>): automate recurring work like daily PR reviews and dependency audits
+ * [CLAUDE.md](</docs/en/memory>): give Claude persistent instructions and context that load at the start of every session
+ * Install the Claude mobile app for [iOS](<https://apps.apple.com/us/app/claude-by-anthropic/id6473753684>) or [Android](<https://play.google.com/store/apps/details?id=com.anthropic.claude>) to monitor sessions from your phone. From the Claude Code CLI, `/mobile` shows a QR code.
--- a/web-scheduled-tasks.md
+++ b/web-scheduled-tasks.md
@@ -65,13 +65,13 @@
Select an environment
-Select a [cloud environment](</docs/en/claude-code-on-the-web#cloud-environment>) for the task. Environments control what the cloud session has access to:
+Select a [cloud environment](</docs/en/claude-code-on-the-web#the-cloud-environment>) for the task. Environments control what the cloud session has access to:
* **Network access** : set the level of internet access available during each run
* **Environment variables** : provide API keys, tokens, or other secrets Claude can use
* **Setup script** : run install commands before each session starts, like installing dependencies or configuring tools
-A **Default** environment is available out of the box. To use a custom environment, [create one](</docs/en/claude-code-on-the-web#cloud-environment>) before creating the task.
+A **Default** environment is available out of the box. To use a custom environment, [create one](</docs/en/claude-code-on-the-web#the-cloud-environment>) before creating the task.
5
@@ -116,7 +116,7 @@
Repositories and branch permissions
-Each repository you add is cloned on every run. Claude starts from the repository’s default branch unless your prompt specifies otherwise. By default, Claude can only push to branches prefixed with `claude/`. This prevents scheduled tasks from accidentally modifying protected or long-lived branches. To remove this restriction for a specific repository, enable **Allow unrestricted branch pushes** for that repository when creating or editing the task.
+Scheduled tasks need GitHub access to clone repositories. When you create a task from the CLI with `/schedule`, Claude checks whether your account has GitHub connected and prompts you to run `/web-setup` if it doesn’t. See [GitHub authentication options](</docs/en/claude-code-on-the-web#github-authentication-options>) for the two ways to grant access. Each repository you add is cloned on every run. Claude starts from the repository’s default branch unless your prompt specifies otherwise. By default, Claude can only push to branches prefixed with `claude/`. This prevents scheduled tasks from accidentally modifying protected or long-lived branches. To remove this restriction for a specific repository, enable **Allow unrestricted branch pushes** for that repository when creating or editing the task.
###
@@ -132,7 +132,7 @@
Environments
-Each task runs in a [cloud environment](</docs/en/claude-code-on-the-web#cloud-environment>) that controls network access, environment variables, and setup scripts. Configure environments before creating a task to give Claude access to APIs, install dependencies, or restrict network scope. See [cloud environment](</docs/en/claude-code-on-the-web#cloud-environment>) for the full setup guide.
+Each task runs in a [cloud environment](</docs/en/claude-code-on-the-web#the-cloud-environment>) that controls network access, environment variables, and setup scripts. Configure environments before creating a task to give Claude access to APIs, install dependencies, or restrict network scope. See [cloud environment](</docs/en/claude-code-on-the-web#the-cloud-environment>) for the full setup guide.
##
@@ -173,6 +173,6 @@
* [Desktop scheduled tasks](</docs/en/desktop-scheduled-tasks>): schedule tasks that run on your machine with access to local files. The Desktop app’s **Schedule** page shows both local and remote tasks in the same grid.
* [`/loop` and CLI scheduled tasks](</docs/en/scheduled-tasks>): lightweight scheduling within a CLI session
- * [Cloud environment](</docs/en/claude-code-on-the-web#cloud-environment>): configure the runtime environment for cloud tasks
+ * [Cloud environment](</docs/en/claude-code-on-the-web#the-cloud-environment>): configure the runtime environment for cloud tasks
* [MCP connectors](</docs/en/mcp>): connect external services like Slack, Linear, and Google Drive
* [GitHub Actions](</docs/en/github-actions>): run Claude in your CI pipeline on repo events