Agent SDK reference - Python
--- a/python.md
+++ b/python.md
@@ -1009,12 +1009,12 @@
---|---|---
`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 every [tool available to subagents](</docs/en/sub-agents#available-tools>)
+`tools`| No| Array of tool names available to this agent. If omitted, inherits every [tool available to subagents](</docs/en/sub-agents#available-tools>)
`disallowedTools`| No| Array of tool names to remove from the agent’s tool set. MCP server-level patterns are also accepted: `mcp__server` or `mcp__server__*` removes every tool from that server, and `mcp__*` removes every MCP tool from any server
`model`| No| Model override for this agent. Accepts an alias such as `"sonnet"`, `"opus"`, `"haiku"`, or `"inherit"`, or a full model ID. When you omit it, Claude Code picks the model in the [subagent model order](</docs/en/sub-agents#choose-a-model>)
`skills`| No| List of skill names to preload into the agent’s context at startup. Unlisted skills remain invocable through the Skill tool
`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
+`mcpServers`| No| MCP servers to add to any that this agent inherits. Each entry is a server name or an inline `{name: config}` dict
`initialPrompt`| No| Auto-submitted as the first user turn when this agent runs as the main thread agent
`maxTurns`| No| Maximum number of agentic turns before the agent stops
`background`| No| Run this agent as a non-blocking background task when invoked
--- a/python.md
+++ b/python.md
@@ -792,7 +792,7 @@
`stderr`| `Callable[[str], None] | None`| `None`| Callback function for stderr output from CLI
`can_use_tool`| `CanUseTool` ` | None`| `None`| Tool permission callback, invoked only when the [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) falls through to a prompt. Not invoked for calls auto-approved by `allowed_tools`, allow rules, or `permission_mode`. An allow rule doesn’t pre-approve the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). See `CanUseTool` for details
`hooks`| `dict[HookEvent, list[HookMatcher]] | None`| `None`| Hook configurations for intercepting events
-`user`| `str | None`| `None`| On POSIX platforms, the OS user account the Claude Code subprocess runs as. Claude Code keeps the parent process’s environment, including `HOME`, and runs in `cwd`
+`user`| `str | None`| `None`| On POSIX platforms, the OS user account the Claude Code subprocess runs as. Claude Code keeps the parent process’s groups and environment, including `HOME`, and runs in `cwd`
`include_partial_messages`| `bool`| `False`| Include partial message streaming events. When enabled, `StreamEvent` messages are yielded
`include_hook_events`| `bool`| `False`| Include hook lifecycle events in the message stream as `HookEventMessage` objects
`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. Without this option, Claude Code omits the text and thinking blocks of a subagent that runs in the [foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>). For nested subagents, skills with `context: fork`, and the Claude Code version each needs, see [Follow subagent messages](</docs/en/headless#follow-subagent-messages>). Requires Python Agent SDK 0.2.140 or later
@@ -2550,7 +2550,7 @@
"firstPage": int | None, # Optional document page number of the first extracted page
}
-**Output (type:`"file_unchanged"`):**
+**Output (type:`"file_unchanged"`), before Claude Code v2.1.317:**
{
"type": "file_unchanged", # The file is unchanged since Claude last read it in this session, so the content isn't repeated
--- a/python.md
+++ b/python.md
@@ -2432,6 +2432,7 @@
"taskId": str, # ID of the background monitor task
"timeoutMs": int, # The watch's effective deadline in milliseconds
"persistent": bool | None, # False: every watch has a deadline
+ "keptInSandboxByCheck": bool | None,
}
### Edit
--- a/python.md
+++ b/python.md
@@ -828,7 +828,7 @@
)
* [`API_TIMEOUT_MS`](</docs/en/env-vars>): how long each request attempt can wait for response headers, in milliseconds. It doesn’t limit how long a streaming response runs after the headers arrive. Default `600000`. Applies to the main loop and all subagents.
- * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window. For unattended runs that need to wait through longer outages, set [`CLAUDE_CODE_RETRY_WATCHDOG=1`](</docs/en/errors#tune-retry-behavior>): it retries transient capacity errors indefinitely and, on Claude Code v2.1.199 or later, raises the default for other transient errors to `300` and removes the cap on this variable.
+ * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window. For unattended runs that need to wait through longer outages, set [`CLAUDE_CODE_RETRY_WATCHDOG=1`](</docs/en/errors#tune-retry-behavior>) to keep retrying transient capacity errors. With `CLAUDE_CODE_RETRY_WATCHDOG` set on v2.1.199 or later, the cap doesn’t apply, and the default for other transient errors is `300`.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents. While the stream watchdog is on, the default is `CLAUDE_STREAM_IDLE_TIMEOUT_MS` plus 5 minutes, which comes to `600000` unless you raise that variable. With the stream watchdog off, the default is `600000`. Before v2.1.257, the default was always `600000`. The timer resets on each stream event. On a stall, Claude Code aborts the subagent and reports the stall to the parent. For a background subagent, it also marks the task failed and attaches any partial result.
* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: stream watchdog that aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed. While the watchdog waits out a response that a gateway behind `ANTHROPIC_BASE_URL` holds open with keep-alive pings, a host that sets `include_partial_messages` keeps receiving `ping` `StreamEvent` messages. Read those frames as liveness rather than timing the session out on silence. Before v2.1.257, the frames stopped 5 minutes after the last real stream event.
--- a/python.md
+++ b/python.md
@@ -2327,7 +2327,7 @@
"resolvedModel": str | None, # Model in use at the backgrounding transition
"modelsUsed": list[str] | None, # Models used before backgrounding, in order, with consecutive repeats collapsed
"prompt": str, # The prompt the agent runs
- "outputFile": str, # File path where the agent's output is written
+ "outputFile": str, # Path to the task output file
"canReadOutputFile": bool | None, # Whether the output file can be read directly
}
--- a/python.md
+++ b/python.md
@@ -2701,7 +2701,7 @@
"bytes": int, # Size of the fetched content in bytes
"code": int, # HTTP response code
"codeText": str, # HTTP response code text
- "result": str, # Processed result from applying the prompt to the content
+ "result": str, # Answer to the prompt, or page text
"durationMs": int, # Time to fetch and process the content, in milliseconds
"url": str, # URL that was fetched
}
--- a/python.md
+++ b/python.md
@@ -804,7 +804,7 @@
`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` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. With `skills` set and this field unset, only user and project sources load. Set `setting_sources` explicitly to keep local settings. Endpoint-managed policy loads regardless; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). For inputs read regardless of this option, see [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
-`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. Pass exact names only. The SDK rejects malformed and wildcard-form names with a `ValueError` before starting the Claude Code process; this check requires Python Agent SDK 0.2.129 or later. When set, the SDK adds the Skill tool to `allowed_tools` automatically. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
+`skills`| `list[str] | Literal["all"] | None`| `None`| Limits the main agent’s skills. Pass `"all"` to enable every discovered skill, or a list of skill names. Pass exact names only. The SDK rejects malformed and wildcard-form names with a `ValueError` before starting the Claude Code process; this check requires Python Agent SDK 0.2.129 or later. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
`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`| `EffortLevel` ` | None`| `None`| Effort level for thinking depth. See [adjust the effort level](</docs/en/model-config#adjust-effort-level>)
@@ -983,7 +983,7 @@
2. Project settings (`.claude/settings.json`)
3. User settings (`~/.claude/settings.json`)
-Programmatic options such as `agents`, `allowed_tools`, and `settings` override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options.
+Permission rules you pass in `allowed_tools` or `settings` [add to](</docs/en/settings#lists-merge-instead-of-overriding>) these files’ rules. For most single values, Claude Code takes the one in `settings` over these files. Managed policy settings take precedence over most programmatic options.
### `AgentDefinition`
@@ -1031,7 +1031,7 @@
"default", # Standard permission behavior
"acceptEdits", # Auto-accept file edits
"plan", # Planning mode - Claude explores and plans
- "dontAsk", # Deny anything not pre-approved instead of prompting
+ "dontAsk", # Deny calls that would otherwise prompt
"bypassPermissions", # Bypass permission checks; explicit ask rules still prompt (use with caution)
"auto", # A model classifier reviews actions such as shell commands and network requests
]
@@ -2268,7 +2268,7 @@
Launches a new agent to handle complex, multi-step tasks autonomously. When Claude leaves `run_in_background` out of an `Agent` call, by default your main agent doesn’t wait for the new agent and a subagent waits:
* **From your main agent** : the new agent runs in the background, and the result has `status: "async_launched"`. To make your main agent wait for the new agent instead, see [Choose whether Claude waits for subagents](</docs/en/agent-sdk/subagents#choose-whether-claude-waits-for-subagents>).
- * **From one of your subagents** : the calling subagent [waits for the new agent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>). The new agent runs in the background instead when its definition sets `background` to `True`, or when you [turn fork mode off](</docs/en/sub-agents#turn-fork-mode-on-or-off>) by setting `CLAUDE_CODE_FORK_SUBAGENT` to `0`.
+ * **From one of your subagents** : the calling subagent [waits for the new agent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>). The new agent runs in the background instead when its definition sets `background` to `True`.
Before Python SDK v0.2.169, agents that your subagents started also ran in the background by default. That release is the first to bundle Claude Code v2.1.302 or later. **Output (status:`"completed"`):**
@@ -2285,7 +2285,7 @@
],
"resolvedModel": str | None, # Model the subagent started on
"modelsUsed": list[str] | None, # Models used in order, with consecutive repeats collapsed
- "totalToolUseCount": int, # Number of tool calls the agent made
+ "totalToolUseCount": int, # Number of tool calls the agent made, excluding SubagentHandback calls
"totalDurationMs": int, # Execution duration in milliseconds
"totalTokens": int, # Token count from the final API request, not the whole run
"usage": { # Token usage statistics
--- a/python.md
+++ b/python.md
@@ -2653,9 +2653,10 @@
"totalLines": int | None, # Optional total before head_limit and offset, in content mode
"appliedLimit": int | None, # Present when head_limit truncated the result
"appliedOffset": int | None, # Present when an offset was applied
- }
-
-Grep returns this dict shape in each output mode. Which optional keys are present depends on `output_mode`. `totalFiles` requires Claude Code v2.1.208 or later. `totalLines` requires Claude Code v2.1.210 or later.
+ "timedOut": bool | None, # True when the search ran out of time, so results may be incomplete
+ }
+
+Grep returns this dict shape in each output mode. Which optional keys are present depends on `output_mode`. `totalFiles` requires Claude Code v2.1.208 or later. `totalLines` requires Claude Code v2.1.210 or later. `timedOut` requires Claude Code v2.1.317 or later.
### NotebookEdit
--- a/python.md
+++ b/python.md
@@ -1508,7 +1508,9 @@
* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.
* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.
* `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are `interrupt()` and a permission callback returning `PermissionResultDeny` with `interrupt=True`. `None` on CLI versions that predate the field, on results from local commands such as `/voice` or `/usage`, which bypass the query loop, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK’s [`SDKResultMessage.terminal_reason`](</docs/en/agent-sdk/typescript#sdkresultmessage>), which lists the full set of values.
- * `origin`: origin of the user message that triggered this turn. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), check this to tell the result of your own prompt, where `origin` is `None` or `{"kind": "human"}`, from the result of an injected turn such as a background-task notification. Requires Python Agent SDK 0.2.137 or later.
+ * `origin`: origin of the user message that triggered this turn. Requires Python Agent SDK 0.2.137 or later. Don’t suppress a result on `kind` alone. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), check `origin` to see whether your own prompt started the turn:
+ * **Your own prompt** : `origin` is `None` or `{"kind": "human"}`
+ * **A background-task notification** : `origin["kind"]` is `"task-notification"`. That turn’s result can also hold Claude’s answer to a message you sent while the turn ran tools.
When several background tasks finish close together, Claude Code can answer their notifications in one turn rather than one turn each. You still receive one `ResultMessage` per notification, in order, each with an `origin` whose `kind` is `"task-notification"`. All but the last have `num_turns` set to `0` and an empty `result`, and the last one carries the turn that answers them all. The `usage` dict covers the main agent loop only and excludes subagent and other nested or auxiliary model calls. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), the values are per-turn. Prefer `model_usage` for token and cost accounting. The `usage` dict contains the following keys when present:
--- a/python.md
+++ b/python.md
@@ -2121,7 +2121,7 @@
class SyncHookJSONOutput(TypedDict):
# Control fields
continue_: NotRequired[bool] # Whether to proceed (default: True)
- suppressOutput: NotRequired[bool] # Hide stdout from transcript
+ suppressOutput: NotRequired[bool] # Has no effect
stopReason: NotRequired[str] # Message when continue is False
# Decision fields
--- a/python.md
+++ b/python.md
@@ -767,7 +767,7 @@
`allowed_tools`| `list[str]`| `[]`| Tools to auto-approve without prompting, apart from reads from [network paths](</docs/en/permissions#network-paths>). This does not restrict Claude to only these tools. If you name one of the [task-tracking tools](</docs/en/agent-sdk/todo-tracking#model-availability>) here, Claude Code also opts the session in. Other 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 | SystemPromptCustom | SystemPromptFile | None`| `None`| System prompt configuration. Pass a string for a custom prompt, `{"type": "preset", "preset": "claude_code"}` for Claude Code’s system prompt with optional `"append"`, `{"type": "custom", "prompt": "..."}` for a custom prompt that can also set `"snapshot"`, or `{"type": "file", "path": "..."}` to load a large prompt from disk. See `SystemPromptPreset`, `SystemPromptCustom`, and `SystemPromptFile`
`mcp_servers`| `dict[str, McpServerConfig] | str | Path`| `{}`| MCP server configurations or path to config file
-`strict_mcp_config`| `bool`| `False`| When `True`, use only the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, plugin-provided MCP servers, and [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>). Maps to the CLI `--strict-mcp-config` flag
+`strict_mcp_config`| `bool`| `False`| When `True`, use the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, plugin-provided MCP servers, and [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>). Maps to the CLI `--strict-mcp-config` flag
`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
@@ -787,7 +787,7 @@
`add_dirs`| `list[str | Path]`| `[]`| Additional directories Claude can access. The SDK passes each entry to Claude Code as `--add-dir`, so with the `project` setting source Claude Code also [loads the directory’s skills, commands, and subagents](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>)
`env`| `dict[str, str]`| `{}`| Environment variables merged on top of the inherited process environment. See [Environment variables](</docs/en/env-vars>) for variables the underlying CLI reads, and Handle slow or stalled API responses for timeout-related variables. Set `CLAUDE_AGENT_SDK_CLIENT_APP` to identify your app in the User-Agent header
`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
+`max_buffer_size`| `int | None`| `None`| Longest single message the SDK accepts from the CLI, in characters. `None` uses 1,048,576. A longer message raises `CLIJSONDecodeError`
`debug_stderr`| `Any`| `sys.stderr`| _Deprecated_ \- The SDK ignores this value. Use the `stderr` callback for CLI stderr output
`stderr`| `Callable[[str], None] | None`| `None`| Callback function for stderr output from CLI
`can_use_tool`| `CanUseTool` ` | None`| `None`| Tool permission callback, invoked only when the [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) falls through to a prompt. Not invoked for calls auto-approved by `allowed_tools`, allow rules, or `permission_mode`. An allow rule doesn’t pre-approve the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). See `CanUseTool` for details
@@ -1088,7 +1088,7 @@
Field| Type| Description
---|---|---
`signal`| `Any | None`| Reserved for future abort signal support
-`suggestions`| `list[PermissionUpdate]`| Permission update suggestions from the CLI. Bash prompts include a suggestion with the `localSettings` destination, so returning it in `updated_permissions` writes the rule to `.claude/settings.local.json` and persists across sessions.
+`suggestions`| `list[PermissionUpdate]`| Permission update suggestions from the CLI. Bash prompts can include a suggestion with the `localSettings` destination, so returning it in `updated_permissions` writes the rule to `.claude/settings.local.json` and persists across sessions.
`tool_use_id`| `str | None`| Identifier of the specific tool call this prompt is for. Always populated when delivered to `can_use_tool`
`agent_id`| `str | None`| Sub-agent ID when the call originates from a subagent; `None` for the main agent
`blocked_path`| `str | None`| File path that triggered the permission request, when applicable. For example, when a Bash command tries to access a path outside allowed directories
@@ -1501,8 +1501,8 @@
* `is_error`: `True` when the conversation ended in an error state. Always `True` on the `error_*` subtypes. On `subtype="success"` it is `True` in three cases. Check `stop_reason` to tell them apart:
* `"refusal"`: the model declined to respond. Read the refusal text in `result`, or in the preceding `AssistantMessage` when `result` is empty.
* `"tool_deferred_unavailable"`: the [deferred tool](</docs/en/hooks#defer-a-tool-call-for-later>) was no longer available when you resumed the session, for example because its MCP server wasn’t connected. In the two cases below, a prompt you send after resuming counts the same as one passed with the resume:
- * No prompt: the call is still pending. Make the tool available and resume again without a prompt, and the call runs first.
- * A prompt: Claude Code answers it without the tool’s result, and the deferred call is gone. Send a new prompt if you still need the tool called.
+ * No prompt: by default, the call is still pending. Make the tool available and resume again without a prompt, and the call runs first.
+ * A prompt: by default, the prompt doesn’t reach Claude and the call is still pending. To continue without the tool, [drop the call](</docs/en/hooks#resume-when-a-deferred-tool-is-unavailable>).
* Any other value: the turn ended on an error that Claude Code reported in place of a model response, such as an API error. Read `terminal_reason` for the cause, `result` for the message, and `api_error_status` for the HTTP status when the API returned one.
* `api_error_status`: the HTTP status code of the terminating API error. `None` when the turn ended without one. Populated only on `subtype="success"`.
* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.
@@ -1814,7 +1814,7 @@
### `CLIJSONDecodeError`
-Raised when JSON parsing fails.
+Raised when JSON parsing fails, or when one message from the CLI is longer than `max_buffer_size`. To raise the limit and pick up the stopped work, see [Large tool calls and results](</docs/en/agent-sdk/troubleshooting#large-tool-calls-and-results>).
class CLIJSONDecodeError(ClaudeSDKError):
def __init__(self, line: str, original_error: Exception):
@@ -2193,7 +2193,7 @@
### 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. With its [`Bash` matcher](</docs/en/agent-sdk/hooks#matchers>), the security hook runs on Bash tool calls. The logging hook has no matcher, so it runs on every tool call.
+This example registers two hooks: one that blocks dangerous Bash commands like `rm -rf /`, and another that logs all tool usage for auditing. With its [`Bash` matcher](</docs/en/agent-sdk/hooks#matchers>), the security hook runs on Bash tool calls. The logging hook has no matcher, so it matches every tool.
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext
@@ -3068,14 +3068,14 @@
Property| Type| Default| Description
---|---|---|---
`enabled`| `bool`| `False`| Enable sandbox mode for command execution
-`autoAllowBashIfSandboxed`| `bool`| `True`| Auto-approve bash commands when sandbox is enabled
+[`autoAllowBashIfSandboxed`](</docs/en/settings-reference#sandbox-autoallowbashifsandboxed>)| `bool`| `False`| Auto-approve Bash commands when sandbox is enabled. The `False` default requires Python SDK v0.2.182 or later
`excludedCommands`| `list[str]`| `[]`| Commands that bypass sandbox restrictions, such as `["docker *"]`. These run unsandboxed automatically without model involvement; [`sandbox.excludedCommands`](</docs/en/settings-reference#sandbox-excludedcommands>) covers when an entry applies
`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
-The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. By default, when `enabled` is `True` but the sandbox can’t start, commands run unsandboxed with a warning on stderr. This default differs from the TypeScript SDK, where `failIfUnavailable` defaults to `true`.Set `"failIfUnavailable": True` in your sandbox settings to stop instead. The SDK forwards `failIfUnavailable` to Claude Code along with the declared `SandboxSettings` fields. `query()` then reports a `ResultMessage` with `subtype="error_during_execution"` and the reason in `errors`. Because this is a single-shot `query()` call, the SDK raises after yielding that error result, so wrap the loop in a try block to continue past it. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the error contract.
+The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. By default, when `enabled` is `True` but the sandbox can’t start, commands run unsandboxed with a warning on stderr. This default differs from the TypeScript SDK, where `failIfUnavailable` defaults to `true`.Set `"failIfUnavailable": True` in your sandbox settings to stop instead. With `failIfUnavailable` set, `query()` raises a `ResultError` when the sandbox can’t start, so wrap your `async for` loop in a `try` block. The reason is in the exception’s `errors` list. The SDK forwards `failIfUnavailable` to Claude Code along with the declared `SandboxSettings` fields.
To keep sandboxed commands from writing to a file, list its absolute path under [`denyWrite`](</docs/en/settings-reference#sandbox-filesystem-denywrite>) in your sandbox settings, such as `"filesystem": {"denyWrite": ["/home/user/project/.env"]}`. The SDK forwards `filesystem` to Claude Code along with the declared `SandboxSettings` fields. Once the sandbox starts, it blocks writes to each absolute path you listed.
@@ -3100,8 +3100,8 @@
):
print(message)
except Exception as error:
- # A single-shot query() raises after yielding an error result,
- # such as when failIfUnavailable is set and the sandbox can't start.
+ # query() raises, for example, when failIfUnavailable is set
+ # and the sandbox can't start.
print(f"Session ended with an error: {error}")
asyncio.run(main())
Show diff (2069 lines)
--- a/python.md
+++ b/python.md
@@ -1,8 +1,4 @@
-##
-
-
-
-Installation
+## Installation
Install the package into a virtual environment. On recent Debian, Ubuntu, and Homebrew Python installs, running `pip install` against system Python fails with `error: externally-managed-environment`.
@@ -12,11 +8,7 @@
For uv, Windows PowerShell, and API key setup, see [Setup in the Agent SDK quickstart](</docs/en/agent-sdk/quickstart#setup>).
-##
-
-
-
-Choosing between `query()` and `ClaudeSDKClient`
+## Choosing between `query()` and `ClaudeSDKClient`
The Python SDK provides two ways to interact with Claude Code:
@@ -34,19 +26,11 @@
Use `ClaudeSDKClient` for interactive applications such as chat interfaces, or when the next action depends on Claude’s response.
-##
-
-
-
-Functions
+## Functions
Signature blocks and bare `async for` / `async with` fragments on this page are illustrative. To run them, wrap the body in `async def main(): ...` and call `asyncio.run(main())`.
-###
-
-
-
-`query()`
+### `query()`
Creates a new session for each interaction with Claude Code by default. Returns an async iterator that yields messages as they arrive. Each call to `query()` starts fresh with no memory of previous interactions unless you pass `continue_conversation=True` or `resume` in `ClaudeAgentOptions`. See [Sessions](</docs/en/agent-sdk/sessions>).
@@ -57,11 +41,7 @@
transport: Transport | None = None
) -> AsyncIterator[Message]
-####
-
-
-
-Parameters
+#### Parameters
Parameter| Type| Description
---|---|---
@@ -69,19 +49,11 @@
`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
Returns an `AsyncIterator[Message]` that yields messages from the conversation.
-####
-
-
-
-Example - With options
+#### Example - With options
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
@@ -97,11 +69,7 @@
asyncio.run(main())
-###
-
-
-
-`tool()`
+### `tool()`
Decorator for defining MCP tools with type safety.
@@ -112,11 +80,7 @@
annotations: ToolAnnotations | None = None
) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]
-####
-
-
-
-Parameters
+#### Parameters
Parameter| Type| Description
---|---|---
@@ -125,11 +89,7 @@
`input_schema`| `type | dict[str, Any]`| Schema defining the tool’s input parameters. See Input schema options
`annotations`| `ToolAnnotations`` | None`| Optional MCP tool annotations providing behavioral hints to clients
-####
-
-
-
-Input schema options
+#### Input schema options
1. **Simple type mapping** (recommended):
@@ -164,19 +124,11 @@
In the simple mapping and TypedDict forms, wrap a type in `Annotated[type, "description"]` to set the field’s description.
-####
-
-
-
-Returns
+#### Returns
A decorator function that wraps the tool implementation and returns an `SdkMcpTool` instance.
-####
-
-
-
-Example
+#### Example
from claude_agent_sdk import tool
from typing import Any
@@ -185,11 +137,7 @@
async def greet(args: dict[str, Any]) -> dict[str, Any]:
return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}
-####
-
-
-
-`ToolAnnotations`
+#### `ToolAnnotations`
Behavioral hints for a tool, passed as the `annotations` argument of `tool()`. `ToolAnnotations` extends the MCP SDK’s `mcp.types.ToolAnnotations` with a `maxResultSizeChars` field, and you can write each hint in camelCase or snake_case: `ToolAnnotations(readOnlyHint=True)` and `ToolAnnotations(read_only_hint=True)` are equivalent. To read a hint back from the object, use the spelling your installed `mcp` package declares: `.readOnlyHint` on `mcp` 1.x and `.read_only_hint` on 2.x, while `.maxResultSizeChars` works on both. You can also pass a plain `mcp.types.ToolAnnotations` wherever the SDK accepts annotations. The snake_case names and the typed `maxResultSizeChars` field require Python Agent SDK 0.2.140 or later. Versions 0.1.31 through 0.2.139 re-export `mcp.types.ToolAnnotations` unchanged. On versions 0.1.55 through 0.2.139 you can still pass `maxResultSizeChars` as a keyword argument: the MCP class accepts extra fields, and the SDK forwards the value to Claude Code. All fields are optional. Clients shouldn’t rely on the hints for security decisions.
@@ -214,11 +162,7 @@
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_sdk_mcp_server()`
Create an in-process MCP server that runs within your Python application.
@@ -228,11 +172,7 @@
tools: list[SdkMcpTool[Any]] | None = None
) -> McpSdkServerConfig
-####
-
-
-
-Parameters
+#### Parameters
Parameter| Type| Default| Description
---|---|---|---
@@ -240,19 +180,11 @@
`version`| `str`| `"1.0.0"`| Server version string
`tools`| `list[SdkMcpTool[Any]] | None`| `None`| List of tool functions created with `@tool` decorator
-####
-
-
-
-Returns
+#### Returns
Returns an `McpSdkServerConfig` object that can be passed to `ClaudeAgentOptions.mcp_servers`.
-####
-
-
-
-Example
+#### Example
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions
@@ -276,11 +208,7 @@
allowed_tools=["mcp__calc__add", "mcp__calc__multiply"],
)
-###
-
-
-
-`list_sessions()`
+### `list_sessions()`
Lists past sessions with metadata. Filter by project directory or list sessions across all projects. Synchronous; returns immediately.
@@ -291,11 +219,7 @@
include_worktrees: bool = True
) -> list[SDKSessionInfo]
-####
-
-
-
-Parameters
+#### Parameters
Parameter| Type| Default| Description
---|---|---|---
@@ -304,11 +228,7 @@
`offset`| `int`| `0`| Number of sessions to skip from the start of the sorted results. Use with `limit` for pagination
`include_worktrees`| `bool`| `True`| When `directory` is inside a git repository, include sessions from all worktree paths
-####
-
-
-
-Return type: `SDKSessionInfo`
+#### Return type: `SDKSessionInfo`
Property| Type| Description
---|---|---
@@ -323,11 +243,7 @@
`tag`| `str | None`| User-set session tag (see `tag_session()`)
`created_at`| `int | None`| Session creation time in milliseconds since epoch
-####
-
-
-
-Example
+#### 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.
@@ -336,11 +252,7 @@
for session in list_sessions(directory="/path/to/project", limit=10):
print(f"{session.summary} ({session.session_id})")
-###
-
-
-
-`get_session_messages()`
+### `get_session_messages()`
Retrieves messages from a past session. Synchronous; returns immediately.
@@ -351,11 +263,7 @@
offset: int = 0
) -> list[SessionMessage]
-####
-
-
-
-Parameters
+#### Parameters
Parameter| Type| Default| Description
---|---|---|---
@@ -364,11 +272,7 @@
`limit`| `int | None`| `None`| Maximum number of messages to return
`offset`| `int`| `0`| Number of messages to skip from the start
-####
-
-
-
-Return type: `SessionMessage`
+#### Return type: `SessionMessage`
Property| Type| Description
---|---|---
@@ -379,11 +283,7 @@
`parent_tool_use_id`| `str | None`| For subagent messages, the id of the spawning `Agent` tool-use block. `None` for main-session messages and older sessions
`parent_agent_id`| `str | None`| For messages from a [nested subagent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), the agent id of the parent subagent. `None` for main-session messages, top-level subagent messages, and older sessions. Requires Python Agent SDK 0.2.140 or later
-####
-
-
-
-Example
+#### Example
from claude_agent_sdk import list_sessions, get_session_messages
@@ -393,11 +293,7 @@
for msg in messages:
print(f"[{msg.type}] {msg.uuid}")
-###
-
-
-
-`get_session_info()`
+### `get_session_info()`
Reads metadata for a single session by ID without scanning the full project directory. Synchronous; returns immediately.
@@ -406,11 +302,7 @@
directory: str | None = None,
) -> SDKSessionInfo | None
-####
-
-
-
-Parameters
+#### Parameters
Parameter| Type| Default| Description
---|---|---|---
@@ -419,11 +311,7 @@
Returns `SDKSessionInfo`, or `None` if the session is not found.
-####
-
-
-
-Example
+#### 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.
@@ -433,11 +321,7 @@
if info:
print(f"{info.summary} (branch: {info.git_branch}, tag: {info.tag})")
-###
-
-
-
-`rename_session()`
+### `rename_session()`
Renames a session by appending a custom-title entry. Repeated calls are safe; the most recent title wins. Synchronous.
@@ -447,11 +331,7 @@
directory: str | None = None,
) -> None
-####
-
-
-
-Parameters
+#### Parameters
Parameter| Type| Default| Description
---|---|---|---
@@ -461,11 +341,7 @@
Raises `ValueError` if `session_id` is not a valid UUID or `title` is empty; `FileNotFoundError` if the session cannot be found.
-####
-
-
-
-Example
+#### Example
Rename the most recent session so it’s easier to find later. The new title appears in `SDKSessionInfo.custom_title` on subsequent reads.
@@ -475,11 +351,7 @@
if sessions:
rename_session(sessions[0].session_id, "Refactor auth module")
-###
-
-
-
-`tag_session()`
+### `tag_session()`
Tags a session. Pass `None` to clear the tag. Repeated calls are safe; the most recent tag wins. Synchronous.
@@ -489,11 +361,7 @@
directory: str | None = None,
) -> None
-####
-
-
-
-Parameters
+#### Parameters
Parameter| Type| Default| Description
---|---|---|---
@@ -503,11 +371,7 @@
Raises `ValueError` if `session_id` is not a valid UUID or `tag` is empty after sanitization; `FileNotFoundError` if the session cannot be found.
-####
-
-
-
-Example
+#### Example
Tag a session, then filter by that tag on a later read. Pass `None` to clear an existing tag.
@@ -523,11 +387,7 @@
if session.tag == "needs-review":
print(session.summary)
-###
-
-
-
-`fork_session()`
+### `fork_session()`
Copies a session’s transcript into a new session so you can take the conversation in another direction while the original stays unchanged. To branch from an earlier point in the conversation, pass `up_to_message_id`. Synchronous.
@@ -538,11 +398,7 @@
title: str | None = None,
) -> ForkSessionResult
-####
-
-
-
-Parameters
+#### Parameters
Parameter| Type| Default| Description
---|---|---|---
@@ -557,11 +413,7 @@
* `ValueError`: the session has no messages, or `up_to_message_id` matches no message in the transcript
* `FileNotFoundError`: the session cannot be found
-####
-
-
-
-Example
+#### Example
Fork the most recent session under a new title, then resume the fork. The original session keeps its own history.
@@ -572,17 +424,9 @@
forked = fork_session(sessions[0].session_id, title="Try the OAuth approach")
print(forked.session_id) # pass as ClaudeAgentOptions(resume=...) to continue the fork
-##
-
-
-
-Classes
-
-###
-
-
-
-`ClaudeSDKClient`
+## 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. See the comparison with `query()`.
@@ -604,11 +448,7 @@
async def get_server_info(self) -> dict[str, Any] | None
async def disconnect(self) -> None
-####
-
-
-
-Methods
+#### Methods
Method| Description
---|---
@@ -629,11 +469,7 @@
`get_server_info()`| Get the server’s initialization info, including available commands and output styles
`disconnect()`| Disconnect from Claude
-####
-
-
-
-Context Manager Support
+#### Context Manager Support
The client can be used as an async context manager for automatic connection management:
@@ -650,11 +486,7 @@
> **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
+#### Example - Continuing a conversation
import asyncio
from claude_agent_sdk import ClaudeSDKClient, AssistantMessage, TextBlock, ResultMessage
@@ -691,11 +523,7 @@
asyncio.run(main())
-####
-
-
-
-Example - Streaming input with ClaudeSDKClient
+#### Example - Streaming input with ClaudeSDKClient
`query()` also accepts an async iterable of user message dicts, so you can assemble the prompt at send time or include content blocks such as images. Claude Code starts responding to the first yielded message as soon as it arrives, without waiting for the iterable to finish, and `receive_response()` stops at the `ResultMessage` that ends that response. Put everything Claude should read before answering into one message, as this generator does, and pair each `query()` call with its own `receive_response()` loop.
@@ -731,11 +559,7 @@
asyncio.run(main())
-####
-
-
-
-Example - Using interrupts
+#### Example - Using interrupts
import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, ResultMessage
@@ -773,11 +597,7 @@
**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`, 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
+#### Example - Advanced permission control
import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
@@ -821,19 +641,11 @@
asyncio.run(main())
-##
-
-
-
-Types
+## 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`
+### `SdkMcpTool`
Definition for an SDK MCP tool created with the `@tool` decorator.
@@ -853,11 +665,7 @@
`handler`| `Callable[[T], Awaitable[dict[str, Any]]]`| Async function that handles tool execution
`annotations`| `ToolAnnotations`` | None`| Optional tool annotations (for example `readOnlyHint`, `destructiveHint`, `openWorldHint`, `maxResultSizeChars`)
-###
-
-
-
-`Transport`
+### `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).
@@ -897,11 +705,7 @@
Import: `from claude_agent_sdk import Transport`
-###
-
-
-
-`ClaudeAgentOptions`
+### `ClaudeAgentOptions`
Configuration dataclass for Claude Code queries.
@@ -1009,11 +813,7 @@
`load_timeout_ms`| `int`| `60000`| Per-call timeout for `session_store.load()` and `list_subkeys()` during resume materialization, in milliseconds
`task_budget`| `TaskBudget | None`| `None`| API-side token budget. Sent as `output_config.task_budget` with the `task-budgets-2026-03-13` beta header. Pass `{"total": <int>}`.
-####
-
-
-
-Handle slow or stalled API responses
+#### Handle slow or stalled API responses
The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through `ClaudeAgentOptions.env`:
@@ -1032,11 +832,7 @@
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents. While the stream watchdog is on, the default is `CLAUDE_STREAM_IDLE_TIMEOUT_MS` plus 5 minutes, which comes to `600000` unless you raise that variable. With the stream watchdog off, the default is `600000`. Before v2.1.257, the default was always `600000`. The timer resets on each stream event. On a stall, Claude Code aborts the subagent and reports the stall to the parent. For a background subagent, it also marks the task failed and attaches any partial result.
* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: stream watchdog that aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed. While the watchdog waits out a response that a gateway behind `ANTHROPIC_BASE_URL` holds open with keep-alive pings, a host that sets `include_partial_messages` keeps receiving `ping` `StreamEvent` messages. Read those frames as liveness rather than timing the session out on silence. Before v2.1.257, the frames stopped 5 minutes after the last real stream event.
-###
-
-
-
-`OutputFormat`
+### `OutputFormat`
Configuration for structured output validation. Pass this as a `dict` to the `output_format` field on `ClaudeAgentOptions`:
@@ -1051,11 +847,7 @@
`type`| Yes| Must be `"json_schema"` for JSON Schema validation
`schema`| Yes| JSON Schema definition for output validation
-###
-
-
-
-`SystemPromptPreset`
+### `SystemPromptPreset`
Configuration for using Claude Code’s preset system prompt with optional additions.
@@ -1074,11 +866,7 @@
`exclude_dynamic_sections`| No| Move per-user context, such as the auto memory location, from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>)
`snapshot`| No| Set to `False` to rebuild the system prompt on every request instead of [reusing the prompt the session recorded on its first request](</docs/en/agent-sdk/modifying-system-prompts#change-the-prompt-of-an-existing-session>). Requires `claude-agent-sdk` v0.2.153 or later
-###
-
-
-
-`SystemPromptCustom`
+### `SystemPromptCustom`
A custom system prompt in object form, equivalent to passing a string as `system_prompt`, that can also set `snapshot`. Requires `claude-agent-sdk` v0.2.153 or later.
@@ -1093,11 +881,7 @@
`prompt`| Yes| The system prompt text. Passed to the CLI as a command-line argument, so the command-line length limits apply
`snapshot`| No| Same as `SystemPromptPreset.snapshot`, applied to `prompt`
-###
-
-
-
-`SystemPromptFile`
+### `SystemPromptFile`
Configuration for loading a custom system prompt from a file instead of passing it as a string. The SDK maps this to the CLI [`--system-prompt-file`](</docs/en/cli-reference#system-prompt-flags>) flag. Use the file form when the prompt is large: the SDK passes a string `system_prompt` on the CLI subprocess argv, which is subject to OS command-line length limits before the SDK sends any API request. On Linux a single argument longer than roughly 128 KB fails at process spawn with `Argument list too long`. On Windows the whole command line is capped at roughly 32 KB, so the string form fails at a lower threshold.
@@ -1110,11 +894,7 @@
`type`| Yes| Must be `"file"` to load the prompt from disk
`path`| Yes| Path to a file containing the system prompt
-###
-
-
-
-`SettingSource`
+### `SettingSource`
Controls which filesystem-based configuration sources the SDK loads settings from.
@@ -1126,19 +906,11 @@
`"project"`| Shared project settings (version controlled)| `.claude/settings.json`
`"local"`| Local project settings, gitignored when Claude Code saves a setting to it| `.claude/settings.local.json`
-####
-
-
-
-Default behavior
+#### Default behavior
When `setting_sources` is omitted or `None` and `skills` is not set, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. With `skills` set, the `setting_sources` row describes the current default. Endpoint-managed policy is loaded in all cases; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). For more information, see [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>).
-####
-
-
-
-Why use setting_sources
+#### Why use setting_sources
**Disable filesystem settings:**
@@ -1203,11 +975,7 @@
To load CLAUDE.md project instructions, include `"project"` in `setting_sources`. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#claude-md-files-for-project-level-instructions>) for how CLAUDE.md loading interacts with the system prompt options.
-####
-
-
-
-Settings precedence
+#### Settings precedence
When multiple sources are loaded, settings are merged with this precedence (highest to lowest):
@@ -1217,11 +985,7 @@
Programmatic options such as `agents`, `allowed_tools`, and `settings` override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options.
-###
-
-
-
-`AgentDefinition`
+### `AgentDefinition`
Configuration for a subagent defined programmatically.
@@ -1259,11 +1023,7 @@
`AgentDefinition` field names use camelCase, such as `disallowedTools`, `permissionMode`, and `maxTurns`. These names map directly to the wire format shared with the TypeScript SDK. This differs from `ClaudeAgentOptions`, which uses Python snake_case for the equivalent top-level fields such as `disallowed_tools` and `permission_mode`. Because `AgentDefinition` is a dataclass, passing a snake_case keyword raises a `TypeError` at construction time.
-###
-
-
-
-`PermissionMode`
+### `PermissionMode`
Permission modes for controlling tool execution.
@@ -1276,11 +1036,7 @@
"auto", # A model classifier reviews actions such as shell commands and network requests
]
-###
-
-
-
-`EffortLevel`
+### `EffortLevel`
Effort levels for guiding thinking depth.
@@ -1292,11 +1048,7 @@
"max", # Maximum effort
]
-###
-
-
-
-`CanUseTool`
+### `CanUseTool`
Type alias for tool permission callback functions.
@@ -1317,11 +1069,7 @@
To check those calls, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>), which runs for them too. An allow rule doesn’t pre-approve the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>); see [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) for which of them reach the callback and what happens in `dontAsk` and `auto` mode.
-###
-
-
-
-`ToolPermissionContext`
+### `ToolPermissionContext`
Context information passed to tool permission callbacks.
@@ -1349,21 +1097,13 @@
`display_name`| `str | None`| Short noun phrase for the tool action, such as `Read file`, suitable for button labels
`description`| `str | None`| Human-readable subtitle for the permission UI
-###
-
-
-
-`PermissionResult`
+### `PermissionResult`
Union type for permission callback results.
PermissionResult = PermissionResultAllow | PermissionResultDeny
-###
-
-
-
-`PermissionResultAllow`
+### `PermissionResultAllow`
Result indicating the tool call should be allowed.
@@ -1381,11 +1121,7 @@
If you return `PermissionResultAllow` with more than 4,096 items in `updated_permissions`, Claude Code treats the result as invalid and denies the tool call. Each `PermissionUpdate` counts as one item, and so does each entry in its `rules` or `directories` list. The denial message ends with `updatedPermissions may hold at most 4096 updates, rules and directories in all.` To avoid the denial, return 4,096 items or fewer.
-###
-
-
-
-`PermissionResultDeny`
+### `PermissionResultDeny`
Result indicating the tool call should be denied.
@@ -1401,11 +1137,7 @@
`message`| `str`| `""`| Message explaining why the tool was denied
`interrupt`| `bool`| `False`| Whether to interrupt the current execution
-###
-
-
-
-`PermissionUpdate`
+### `PermissionUpdate`
Configuration for updating permissions programmatically.
@@ -1436,11 +1168,7 @@
`directories`| `list[str] | None`| Directories for add/remove directory operations
`destination`| `Literal[...] | None`| Where to apply the permission update
-###
-
-
-
-`PermissionRuleValue`
+### `PermissionRuleValue`
A rule to add, replace, or remove in a permission update.
@@ -1449,11 +1177,7 @@
tool_name: str
rule_content: str | None = None
-###
-
-
-
-`ToolsPreset`
+### `ToolsPreset`
Preset tools configuration for using Claude Code’s default tool set.
@@ -1461,11 +1185,7 @@
type: Literal["preset"]
preset: Literal["claude_code"]
-###
-
-
-
-`ThinkingConfig`
+### `ThinkingConfig`
Controls extended thinking behavior. A union of three configurations:
@@ -1503,11 +1223,7 @@
print(config["budget_tokens"]) # 20000
# config.budget_tokens would raise AttributeError
-###
-
-
-
-`TaskBudget`
+### `TaskBudget`
API-side task budget in tokens, used with the `task_budget` field in `ClaudeAgentOptions`.
@@ -1520,11 +1236,7 @@
Because this is a `TypedDict`, pass it as a plain dict, such as `ClaudeAgentOptions(task_budget={"total": 50000})`.
-###
-
-
-
-`SdkBeta`
+### `SdkBeta`
Literal type for SDK beta features.
@@ -1534,11 +1246,7 @@
On the Claude API, the `context-1m-2025-08-07` beta is retired for Claude Sonnet 4.5 and Claude Sonnet 4. If you still pass it with either model, requests that exceed the standard 200K-token context window return an error, so remove it from `betas`. To run a session with a 1M-token context window, set `model` to a model that [runs with the 1M window by default](</docs/en/model-config#extended-context>), such as `claude-sonnet-5-5` or `claude-opus-5-5`. For a model that reaches 1M only through its `[1m]` variant, append the suffix to the model ID, as in `claude-opus-4-6[1m]`.
-###
-
-
-
-`McpSdkServerConfig`
+### `McpSdkServerConfig`
Configuration for SDK MCP servers created with `create_sdk_mcp_server()`.
@@ -1547,11 +1255,7 @@
name: str
instance: Any # MCP Server instance
-###
-
-
-
-`McpServerConfig`
+### `McpServerConfig`
Union type for MCP server configurations.
@@ -1559,11 +1263,7 @@
McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig
)
-####
-
-
-
-`McpStdioServerConfig`
+#### `McpStdioServerConfig`
class McpStdioServerConfig(TypedDict):
type: NotRequired[Literal["stdio"]] # Optional for backwards compatibility
@@ -1571,33 +1271,21 @@
args: NotRequired[list[str]]
env: NotRequired[dict[str, str]]
-####
-
-
-
-`McpSSEServerConfig`
+#### `McpSSEServerConfig`
class McpSSEServerConfig(TypedDict):
type: Literal["sse"]
url: str
headers: NotRequired[dict[str, str]]
-####
-
-
-
-`McpHttpServerConfig`
+#### `McpHttpServerConfig`
class McpHttpServerConfig(TypedDict):
type: Literal["http"]
url: str
headers: NotRequired[dict[str, str]]
-###
-
-
-
-`McpServerStatusConfig`
+### `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.
@@ -1611,22 +1299,14 @@
`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`
+### `McpStatusResponse`
Response from `ClaudeSDKClient.get_mcp_status()`. Wraps the list of server statuses under the `mcpServers` key.
class McpStatusResponse(TypedDict):
mcpServers: list[McpServerStatus]
-###
-
-
-
-`McpServerStatus`
+### `McpServerStatus`
Status of a connected MCP server, contained in `McpStatusResponse`.
@@ -1649,11 +1329,7 @@
`scope`| `str` (optional)| Configuration scope
`tools`| `list` (optional)| Tools provided by this server, each with `name`, `description`, and `annotations` fields
-###
-
-
-
-`ContextUsageResponse`
+### `ContextUsageResponse`
Response from `ClaudeSDKClient.get_context_usage()`. The response includes the payload Claude Code renders for the `/context` command in an interactive session. Alongside the token counts, that payload carries display fields such as `color` and `gridRows` that Claude Code uses to draw the `/context` usage grid. Claude Code builds this payload by sending several requests to the [token-counting](<https://platform.claude.com/docs/en/build-with-claude/token-counting>) API. These requests don’t appear in the message stream, so cost tracking that reads the stream won’t see them. On the Anthropic API, token counting isn’t billed.
@@ -1680,11 +1356,7 @@
Each `ContextUsageCategory` entry carries `name`, `tokens`, `color`, and an optional `isDeferred` flag. `totalTokens` is the session’s current context usage, and `maxTokens` is the window that usage is measured against. That window is the model’s context window, or the lower auto-compaction window when one applies, and `rawMaxTokens` carries the same value as `maxTokens`. `apiUsage` holds the usage from the latest API response, not a running total for the session. Claude Code leaves the optional `deferredBuiltinTools`, `systemTools`, and `systemPromptSections` keys unset, so expect them to be absent even though the type declares them.
-###
-
-
-
-`SdkPluginConfig`
+### `SdkPluginConfig`
Configuration for loading plugins in the SDK.
@@ -1706,17 +1378,9 @@
For complete information on creating and using plugins, see [Plugins](</docs/en/agent-sdk/plugins>).
-##
-
-
-
-Message Types
-
-###
-
-
-
-`Message`
+## Message Types
+
+### `Message`
Union type of all possible messages.
@@ -1730,11 +1394,7 @@
| ConversationResetMessage
)
-###
-
-
-
-`UserMessage`
+### `UserMessage`
User input message.
@@ -1756,11 +1416,7 @@
The SDK passes `tool_use_result` through from the CLI unmodified. For a tool on an external MCP server whose result contains `resource_link` blocks, the dict has a `resourceLinks` key holding a list of dicts with the keys of the TypeScript [`SDKMcpResourceLink`](</docs/en/agent-sdk/typescript#sdkmcpresourcelink>) type. Claude receives each link as a line of text in the tool result. To render the files the server returned, read `resourceLinks` instead of parsing that text. The `resourceLinks` key requires Python Agent SDK 0.2.150 or later and Claude Code v2.1.257 or later; the CLI bundled with that SDK version satisfies the Claude Code requirement. The CLI omits the key when the result has no links and on results from subagents. The CLI keeps at most 50 links per result and stops adding links once the list reaches 64 KiB of serialized JSON. A tool you define in-process with `tool()` never produces the key, because the SDK flattens its `resource_link` blocks to text before the CLI sees the result.
-###
-
-
-
-`AssistantMessage`
+### `AssistantMessage`
Assistant response message with content blocks.
@@ -1788,11 +1444,7 @@
`session_id`| `str | None`| ID of the session this message belongs to
`uuid`| `str | None`| Unique message identifier within the session transcript
-###
-
-
-
-`AssistantMessageError`
+### `AssistantMessageError`
Possible error types for assistant messages.
@@ -1807,11 +1459,7 @@
The underlying CLI process can emit error types this Literal doesn’t list, such as `max_output_tokens`. The SDK passes the value through unmodified, so treat strings outside this list the way you treat `unknown`. The TypeScript [`SDKAssistantMessageError`](</docs/en/agent-sdk/typescript#sdkassistantmessage>) type lists the full set of values the CLI can emit.
-###
-
-
-
-`SystemMessage`
+### `SystemMessage`
System message with metadata.
@@ -1822,11 +1470,7 @@
Subtypes that have no dataclass of their own arrive as `SystemMessage`. To follow the session between turns, set [`CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS=1`](</docs/en/env-vars#variables>) and read `message.data["state"]` on each message whose `subtype` is `session_state_changed`. [`SDKSessionStateChangedMessage`](</docs/en/agent-sdk/typescript#sdksessionstatechangedmessage>) lists the states it can carry. Iterate with `receive_messages()` to read them: `receive_response()` stops at the `ResultMessage`, and a `session_state_changed` message can follow that result.
-###
-
-
-
-`ResultMessage`
+### `ResultMessage`
Final result message with cost and usage information.
@@ -1892,11 +1536,7 @@
`provider`| `str`| API provider that served this model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`. Not always present.
`costBasis`| `str`| Price table that priced this model’s latest request: `list` for list price, `managed` for a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table, or `unknown` when neither matched the model ID. Not always present, and not declared on the TypedDict, so read it with `.get()`. Requires Claude Code v2.1.246 or later.
-###
-
-
-
-`StreamEvent`
+### `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`.
@@ -1914,11 +1554,7 @@
`event`| `dict[str, Any]`| The raw Claude API stream event data
`parent_tool_use_id`| `str | None`| Always `None`. Stream events are emitted for the main session only. For subagent attribution, use complete messages such as `AssistantMessage`
-###
-
-
-
-`RateLimitEvent`
+### `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"`.
@@ -1934,11 +1570,7 @@
`uuid`| `str`| Unique event identifier
`session_id`| `str`| Session identifier
-###
-
-
-
-`RateLimitInfo`
+### `RateLimitInfo`
Rate limit state carried by `RateLimitEvent`.
@@ -1969,11 +1601,7 @@
`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
-###
-
-
-
-`ConversationResetMessage`
+### `ConversationResetMessage`
Emitted when the conversation is replaced without ending the connection, such as after `/clear`. See [Track costs in streaming input mode](</docs/en/agent-sdk/cost-tracking#track-costs-in-streaming-input-mode>) for how a reset affects the running totals on later `ResultMessage` objects. Requires Python Agent SDK 0.2.137 or later.
@@ -1989,11 +1617,7 @@
`uuid`| `str`| Unique message identifier
`session_id`| `str`| ID of the session that was reset. Messages after the reset carry a new `session_id`
-###
-
-
-
-`TaskStartedMessage`
+### `TaskStartedMessage`
Emitted when a background task starts. A background task is anything tracked outside the main turn, such as a backgrounded Bash command, a Monitor watch, a subagent spawned via the Agent tool, or a remote agent. This naming is unrelated to the `Task`-to-`Agent` tool rename.
@@ -2015,11 +1639,7 @@
`tool_use_id`| `str | None`| Associated tool use ID
`task_type`| `str | None`| Which kind of background task, such as `"local_bash"` for background Bash and Monitor watches, `"local_agent"` for subagents, `"mcp_task"` for [background MCP tool calls](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), or `"remote_agent"`
-###
-
-
-
-`TaskUsage`
+### `TaskUsage`
Token and timing data for a background task.
@@ -2028,11 +1648,7 @@
tool_uses: int
duration_ms: int
-###
-
-
-
-`TaskProgressMessage`
+### `TaskProgressMessage`
Emitted periodically with progress updates for a running background task.
@@ -2056,11 +1672,7 @@
`tool_use_id`| `str | None`| Associated tool use ID
`last_tool_name`| `str | None`| Name of the last tool the task used
-###
-
-
-
-`TaskNotificationMessage`
+### `TaskNotificationMessage`
Emitted when a background task completes, fails, or is stopped. Background tasks include `run_in_background` Bash commands, Monitor watches, and background subagents.
@@ -2088,17 +1700,9 @@
When the CLI [moves a long MCP tool call to the background](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), the tool result for that call holds only a placeholder and the call’s real result arrives in this message. On a `"completed"` notification for such a call, the CLI adds a `resource_links` key listing the files the tool returned by reference, with the same entries and limits as the `resourceLinks` key on `UserMessage.tool_use_result`. The `resource_links` key requires Python Agent SDK 0.2.150 or later and Claude Code v2.1.257 or later; the CLI bundled with that SDK version satisfies the Claude Code requirement. The dataclass has no field for `resource_links`. Read it from the `data` dict the message inherits from `SystemMessage`: `message.data.get("resource_links")`. Match the notification to the call with `tool_use_id`. The CLI omits the key when the result had no links and on notifications for tasks that aren’t MCP tool calls.
-##
-
-
-
-Content Block Types
-
-###
-
-
-
-`ContentBlock`
+## Content Block Types
+
+### `ContentBlock`
Union type of all content blocks.
@@ -2111,11 +1715,7 @@
| ServerToolResultBlock
)
-###
-
-
-
-`TextBlock`
+### `TextBlock`
Text content block.
@@ -2123,11 +1723,7 @@
class TextBlock:
text: str
-###
-
-
-
-`ThinkingBlock`
+### `ThinkingBlock`
Thinking content block (for models with thinking capability).
@@ -2136,11 +1732,7 @@
thinking: str
signature: str
-###
-
-
-
-`ToolUseBlock`
+### `ToolUseBlock`
Tool use request block.
@@ -2150,11 +1742,7 @@
name: str
input: dict[str, Any]
-###
-
-
-
-`ToolResultBlock`
+### `ToolResultBlock`
Tool execution result block.
@@ -2164,19 +1752,11 @@
content: str | list[dict[str, Any]] | None = None
is_error: bool | None = None
-##
-
-
-
-Error Types
+## Error Types
The types below define what your code catches. For entries keyed to the error messages these types raise, with the cause and fix for each, see [Troubleshooting](</docs/en/agent-sdk/troubleshooting>).
-###
-
-
-
-`ClaudeSDKError`
+### `ClaudeSDKError`
Base exception class for all SDK errors.
@@ -2185,11 +1765,7 @@
When a single-shot `query()` ends with an error result, for example a turn-limit error, the SDK raises a `ResultError`.
-###
-
-
-
-`CLINotFoundError`
+### `CLINotFoundError`
Raised when Claude Code CLI is not installed or not found.
@@ -2203,22 +1779,14 @@
cli_path: Optional path to the CLI that was not found
"""
-###
-
-
-
-`CLIConnectionError`
+### `CLIConnectionError`
Raised when connection to Claude Code fails.
class CLIConnectionError(ClaudeSDKError):
"""Failed to connect to Claude Code."""
-###
-
-
-
-`ProcessError`
+### `ProcessError`
Raised when the Claude Code process fails.
@@ -2229,11 +1797,7 @@
self.exit_code = exit_code
self.stderr = stderr
-###
-
-
-
-`ResultError`
+### `ResultError`
Raised when the Claude Code process exits because the run ended with an error result message, such as a turn-limit error or an API error. `ResultError` subclasses `ProcessError`, so an existing `except ProcessError` handler also catches it. Its attributes carry the fields of that result message, so you can branch on why the run failed without parsing the message text. Requires Python Agent SDK 0.2.140 or later.
@@ -2248,11 +1812,7 @@
To tell failures apart, check `data["stop_reason"]` first, then `terminal_reason`, then `subtype`. A declined response has `stop_reason` `"refusal"`, usually with `subtype` `"success"`; its `terminal_reason` doesn’t single it out and can read `"completed"` or `"api_error"`. A failed final request has `subtype` `"success"` and its cause in `terminal_reason`, such as `"api_error"` for an API error. When the run hits a limit you set, such as `max_turns` or `max_budget_usd`, you get an `error_*` subtype.
-###
-
-
-
-`CLIJSONDecodeError`
+### `CLIJSONDecodeError`
Raised when JSON parsing fails.
@@ -2266,19 +1826,11 @@
self.line = line
self.original_error = original_error
-##
-
-
-
-Hook Types
+## Hook Types
For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](</docs/en/agent-sdk/hooks>).
-###
-
-
-
-`HookEvent`
+### `HookEvent`
Supported hook event types.
@@ -2297,11 +1849,7 @@
The TypeScript SDK supports additional hook events not yet available in Python. See the [hook availability table](</docs/en/agent-sdk/hooks#available-hooks>) for per-SDK support.
-###
-
-
-
-`HookCallback`
+### `HookCallback`
Type definition for hook callback functions.
@@ -2315,22 +1863,14 @@
Returns a `HookJSONOutput`.
-###
-
-
-
-`HookContext`
+### `HookContext`
Context information passed to hook callbacks.
class HookContext(TypedDict):
signal: Any | None # Future: abort signal support
-###
-
-
-
-`HookMatcher`
+### `HookMatcher`
Configuration for matching hooks to specific events or tools.
@@ -2352,11 +1892,7 @@
To decide what `on_failure` covers, see [Block the action when a callback fails](</docs/en/agent-sdk/hooks#block-the-action-when-a-callback-fails>).
-###
-
-
-
-`HookInput`
+### `HookInput`
Union type of all hook input types. The actual type depends on the `hook_event_name` field.
@@ -2373,11 +1909,7 @@
| PermissionRequestHookInput
)
-###
-
-
-
-`BaseHookInput`
+### `BaseHookInput`
Base fields present in all hook input types.
@@ -2394,11 +1926,7 @@
`cwd`| `str`| Current working directory
`permission_mode`| `str` (optional)| Current permission mode
-###
-
-
-
-`PreToolUseHookInput`
+### `PreToolUseHookInput`
Input data for `PreToolUse` hook events.
@@ -2419,11 +1947,7 @@
`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`
+### `PostToolUseHookInput`
Input data for `PostToolUse` hook events.
@@ -2446,11 +1970,7 @@
`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`
+### `PostToolUseFailureHookInput`
Input data for `PostToolUseFailure` hook events. Called when a tool execution fails.
@@ -2475,11 +1995,7 @@
`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`
+### `UserPromptSubmitHookInput`
Input data for `UserPromptSubmit` hook events.
@@ -2492,11 +2008,7 @@
`hook_event_name`| `Literal["UserPromptSubmit"]`| Always “UserPromptSubmit”
`prompt`| `str`| The submitted prompt
-###
-
-
-
-`StopHookInput`
+### `StopHookInput`
Input data for `Stop` hook events.
@@ -2509,11 +2021,7 @@
`hook_event_name`| `Literal["Stop"]`| Always “Stop”
`stop_hook_active`| `bool`| Whether the stop hook is active
-###
-
-
-
-`SubagentStopHookInput`
+### `SubagentStopHookInput`
Input data for `SubagentStop` hook events.
@@ -2532,11 +2040,7 @@
`agent_transcript_path`| `str`| Path to the subagent’s transcript file
`agent_type`| `str`| Type of the subagent
-###
-
-
-
-`PreCompactHookInput`
+### `PreCompactHookInput`
Input data for `PreCompact` hook events.
@@ -2551,11 +2055,7 @@
`trigger`| `Literal["manual", "auto"]`| What triggered the compaction
`custom_instructions`| `str | None`| Custom instructions for compaction
-###
-
-
-
-`NotificationHookInput`
+### `NotificationHookInput`
Input data for `Notification` hook events.
@@ -2572,11 +2072,7 @@
`title`| `str` (optional)| Notification title
`notification_type`| `str`| Type of notification
-###
-
-
-
-`SubagentStartHookInput`
+### `SubagentStartHookInput`
Input data for `SubagentStart` hook events.
@@ -2591,11 +2087,7 @@
`agent_id`| `str`| Unique identifier for the subagent
`agent_type`| `str`| Type of the subagent
-###
-
-
-
-`PermissionRequestHookInput`
+### `PermissionRequestHookInput`
Input data for `PermissionRequest` hook events. Allows hooks to handle permission decisions programmatically.
@@ -2616,21 +2108,13 @@
`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
-###
-
-
-
-`HookJSONOutput`
+### `HookJSONOutput`
Union type for hook callback return values.
HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput
-####
-
-
-
-`SyncHookJSONOutput`
+#### `SyncHookJSONOutput`
Synchronous hook output with control and decision fields.
@@ -2650,11 +2134,7 @@
Use `continue_` (with underscore) in Python code. It is automatically converted to `continue` when sent to the CLI.
-####
-
-
-
-`HookSpecificOutput`
+#### `HookSpecificOutput`
A discriminated union of event-specific `TypedDict` output types. The `hookEventName` field determines which fields are valid. For full details on available fields per hook event, see [Control execution with hooks](</docs/en/agent-sdk/hooks#outputs>).
@@ -2701,11 +2181,7 @@
| PermissionRequestHookSpecificOutput
)
-####
-
-
-
-`AsyncHookJSONOutput`
+#### `AsyncHookJSONOutput`
Async hook output that defers hook execution.
@@ -2715,11 +2191,7 @@
Use `async_` (with underscore) in Python code. It is automatically converted to `async` when sent to the CLI.
-###
-
-
-
-Hook Usage Example
+### 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. With its [`Bash` matcher](</docs/en/agent-sdk/hooks#matchers>), the security hook runs on Bash tool calls. The logging hook has no matcher, so it runs on every tool call.
@@ -2770,19 +2242,11 @@
asyncio.run(main())
-##
-
-
-
-Tool Input/Output Types
+## Tool Input/Output Types
Documentation of input/output schemas for 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. Each output shown is the value you read from `UserMessage.tool_use_result` for that tool. Key names appear exactly as Claude Code emits them. A key annotated `| None` with a “present when” or “optional” comment is omitted when it doesn’t apply.
-###
-
-
-
-Agent
+### Agent
**Tool name:** `Agent`. The previous name `Task` is still accepted as an alias when this tool is available to the session. The `tools` list in the init `SystemMessage` reports this tool as `Task` for backward compatibility. **Input:**
@@ -2878,11 +2342,7 @@
Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a cloud session, where `sessionUrl` links to that session and `taskId` identifies it. If Claude Code [kept the subagent’s isolated worktree](</docs/en/worktrees#isolate-subagents-with-worktrees>), `worktreePath` on the `completed` variant is where to find it, and `worktreeBranch` is its branch when Claude Code created the worktree with git. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On the `async_launched` variant, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The `modelsUsed` field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later. Claude Code fills `usage` and `totalTokens` from the subagent’s final API request, not from the whole run. When present, `thinking_tokens` under `output_tokens_details` in `usage` is the number of that request’s output tokens that were thinking tokens. The `output_tokens_details` key requires Python SDK v0.2.136 or later, which bundles Claude Code v2.1.228. The `fallback_credit` key requires Python SDK v0.2.162 or later, which bundles Claude Code v2.1.285.
-###
-
-
-
-AskUserQuestion
+### 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:**
@@ -2932,11 +2392,7 @@
"afkTimeoutMs": int | None, # Set when the dialog auto-resolved after this many milliseconds of user inactivity; absent when the user answered
}
-###
-
-
-
-Bash
+### Bash
**Tool name:** `Bash` For what sets the foreground ceiling, see [Timeout and output limits](</docs/en/tools-reference#timeout-and-output-limits>). For the background time limit, see [Time limit for background commands](</docs/en/tools-reference#time-limit-for-background-commands>). **Input:**
@@ -2957,11 +2413,7 @@
"backgroundTaskId": str | None, # ID of the background task if command is running in background
}
-###
-
-
-
-Monitor
+### Monitor
**Tool name:** `Monitor` Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. The `ws` source requires Claude Code v2.1.195 or later. When Monitor runs a command, it follows the same permission rules as Bash. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for WebSocket permissions, behavior, and provider availability. **Input:**
@@ -2980,11 +2432,7 @@
"persistent": bool | None, # False: every watch has a deadline
}
-###
-
-
-
-Edit
+### Edit
**Tool name:** `Edit` **Input:**
@@ -3024,11 +2472,7 @@
} | None,
}
-###
-
-
-
-Read
+### Read
**Tool name:** `Read` **Input:**
@@ -3113,11 +2557,7 @@
"source": "seeded" | None, # Present when the earlier copy came from a CLAUDE.md or memory file loaded at startup rather than a Read call
}
-###
-
-
-
-Write
+### Write
**Tool name:** `Write` **Input:**
@@ -3154,11 +2594,7 @@
"userModified": bool | None, # Optional; whether the user edited the proposed content before accepting it
}
-###
-
-
-
-Glob
+### Glob
**Tool name:** `Glob` **Input:**
@@ -3180,11 +2616,7 @@
`totalMatches` and `countIsComplete` require Claude Code v2.1.191 or later.
-###
-
-
-
-Grep
+### Grep
**Tool name:** `Grep` **Input:**
@@ -3223,11 +2655,7 @@
Grep returns this dict shape in each output mode. Which optional keys are present depends on `output_mode`. `totalFiles` requires Claude Code v2.1.208 or later. `totalLines` requires Claude Code v2.1.210 or later.
-###
-
-
-
-NotebookEdit
+### NotebookEdit
**Tool name:** `NotebookEdit` **Input:**
@@ -3254,11 +2682,7 @@
"updated_file": str, # Notebook content after the edit
}
-###
-
-
-
-WebFetch
+### WebFetch
**Tool name:** `WebFetch` **Input:**
@@ -3279,11 +2703,7 @@
"url": str, # URL that was fetched
}
-###
-
-
-
-WebSearch
+### WebSearch
**Tool name:** `WebSearch` **Input:**
@@ -3301,11 +2721,7 @@
"durationSeconds": float, # Search duration in seconds
}
-###
-
-
-
-TodoWrite
+### TodoWrite
**Tool name:** `TodoWrite`
@@ -3317,7 +2733,7 @@
* `TaskUpdate`
* `TaskList`
-Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`.This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in.
+Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`. This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in.
**Input:**
@@ -3350,11 +2766,7 @@
],
}
-###
-
-
-
-TaskCreate
+### TaskCreate
**Tool name:** `TaskCreate` **Input:**
@@ -3371,11 +2783,7 @@
"task": {"id": str, "subject": str}, # Created task with assigned ID
}
-###
-
-
-
-TaskUpdate
+### TaskUpdate
**Tool name:** `TaskUpdate` **Input:**
@@ -3401,11 +2809,7 @@
"statusChange": {"from": str, "to": str} | None,
}
-###
-
-
-
-TaskGet
+### TaskGet
**Tool name:** `TaskGet` **Input:**
@@ -3426,11 +2830,7 @@
} | None, # None when the ID is not found
}
-###
-
-
-
-TaskList
+### TaskList
**Tool name:** `TaskList` **Input:**
@@ -3450,19 +2850,11 @@
],
}
-###
-
-
-
-TaskOutput
+### TaskOutput
Removed in Claude Code v2.1.277. Previously retrieved output from a running or completed background task, with `BashOutput` accepted as an alias; Claude reads a background task’s output file with `Read` instead. A `disallowed_tools` entry or a deny rule that still names either name is ignored without a warning.
-###
-
-
-
-TaskStop
+### TaskStop
**Tool name:** `TaskStop`. You can still use the previous names `KillShell` and `KillBash` in permission rules, in hook matchers, and in the `tools`, `allowed_tools`, and `disallowed_tools` options. **Input:**
@@ -3480,11 +2872,7 @@
"command": str | None, # The command or description of the stopped task
}
-###
-
-
-
-ExitPlanMode
+### ExitPlanMode
**Tool name:** `ExitPlanMode` **Input:**
@@ -3504,11 +2892,7 @@
"requestId": str | None, # Optional ID of that approval request
}
-###
-
-
-
-ListMcpResources
+### ListMcpResources
**Tool name:** `ListMcpResourcesTool` **Input:**
@@ -3528,11 +2912,7 @@
}
]
-###
-
-
-
-ReadMcpResource
+### ReadMcpResource
**Tool name:** `ReadMcpResourceTool` **Input:**
@@ -3555,11 +2935,7 @@
"error": str | None, # Present when the server couldn't read the resource
}
-##
-
-
-
-Build a continuous conversation interface
+## Build a continuous conversation interface
The following example keeps one `ClaudeSDKClient` connected across turns, so Claude remembers earlier messages. Type `new` to disconnect and reconnect for a fresh session, or `exit` to end the conversation.
@@ -3635,11 +3011,7 @@
asyncio.run(main())
-##
-
-
-
-Error handling
+## Error handling
The following example wraps a `query()` call in handlers for four of the error types the SDK raises. This example catches `ResultError`, which requires Python Agent SDK 0.2.140 or later.
@@ -3678,17 +3050,9 @@
asyncio.run(main())
-##
-
-
-
-Sandbox Configuration
-
-###
-
-
-
-`SandboxSettings`
+## Sandbox Configuration
+
+### `SandboxSettings`
Configuration for sandbox behavior. Use this to enable command sandboxing and configure network restrictions programmatically.
@@ -3715,11 +3079,7 @@
To keep sandboxed commands from writing to a file, list its absolute path under [`denyWrite`](</docs/en/settings-reference#sandbox-filesystem-denywrite>) in your sandbox settings, such as `"filesystem": {"denyWrite": ["/home/user/project/.env"]}`. The SDK forwards `filesystem` to Claude Code along with the declared `SandboxSettings` fields. Once the sandbox starts, it blocks writes to each absolute path you listed.
-####
-
-
-
-Example usage
+#### Example usage
import asyncio
@@ -3748,11 +3108,7 @@
**Unix socket security** : The `allowUnixSockets` option can grant access to system services that reach outside the sandbox. 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`
+### `SandboxNetworkConfig`
Network-specific configuration for sandbox mode. These settings apply to sandboxed Bash commands when `enabled` is `True` in the parent `SandboxSettings`. They do not restrict the WebFetch tool, which uses [permission rules](</docs/en/permissions#webfetch>) instead.
@@ -3781,21 +3137,13 @@
The built-in sandbox proxy enforces the network allowlist based on the requested hostname. By default, the proxy doesn’t terminate or inspect TLS traffic, so techniques such as [domain fronting](<https://en.wikipedia.org/wiki/Domain_fronting>) can potentially bypass the allowlist. See [Sandboxing security limitations](</docs/en/sandboxing#security-limitations>) for details and [Secure deployment](</docs/en/agent-sdk/secure-deployment#traffic-forwarding>) for configuring a TLS-terminating proxy.
-###
-
-
-
-`SandboxIgnoreViolations`
+### `SandboxIgnoreViolations`
Violations to leave out of the sandbox’s violation report. Each key matches part of a command, or `*` for every command, and each value lists text to match in a violation line: `{"*": ["/etc/hosts"]}` hides violations that mention `/etc/hosts`. A matching access is still blocked. See [`sandbox.ignoreViolations`](</docs/en/settings-reference#sandbox-ignoreviolations>).
SandboxIgnoreViolations = dict[str, list[str]]
-###
-
-
-
-Permissions Fallback for Unsandboxed Commands
+### 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 is invoked, allowing you to implement custom authorization logic. Your `excludedCommands` entries instead take a call out of the sandbox with no model involvement; [`sandbox.excludedCommands`](</docs/en/settings-reference#sandbox-excludedcommands>) covers when an entry applies. The following example logs each unsandboxed request and denies it unless your own authorization logic allows it:
@@ -3857,11 +3205,7 @@
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 `allowUnsandboxedCommands` is enabled, the model can autonomously execute commands outside the sandbox without approval prompts, apart from the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). This combination effectively allows the model to escape sandbox isolation silently.
-##
-
-
-
-See also
+## See also
* [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts
* [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) \- TypeScript SDK documentation
--- a/python.md
+++ b/python.md
@@ -1489,7 +1489,7 @@
---|---|---
`adaptive`| `type`, `display`| Claude adaptively decides when to think
`enabled`| `type`, `budget_tokens`, `display`| Enable thinking with a specific token budget
-`disabled`| `type`| Disable thinking
+`disabled`| `type`| Turn thinking off [where the model and provider allow it](</docs/en/model-config#where-you-cant-turn-thinking-off>)
The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. On providers such as Amazon Bedrock and Google Cloud’s Agent Platform, Claude Code doesn’t pass `display` for earlier models it recognizes. Those are Opus 4.6, Sonnet 4.6, Haiku 4.5, and earlier models, which use their default. 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`:
@@ -1995,7 +1995,7 @@
`TaskStartedMessage`
-Emitted when a background task starts. A background task is anything tracked outside the main turn: a backgrounded Bash command, a Monitor watch, 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.
+Emitted when a background task starts. A background task is anything tracked outside the main turn, such as a backgrounded Bash command, a Monitor watch, a subagent spawned via the Agent tool, or a remote agent. This naming is unrelated to the `Task`-to-`Agent` tool rename.
@dataclass
class TaskStartedMessage(SystemMessage):
@@ -2013,7 +2013,7 @@
`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"` for background Bash and Monitor watches, `"local_agent"`, or `"remote_agent"`
+`task_type`| `str | None`| Which kind of background task, such as `"local_bash"` for background Bash and Monitor watches, `"local_agent"` for subagents, `"mcp_task"` for [background MCP tool calls](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), or `"remote_agent"`
###
--- a/python.md
+++ b/python.md
@@ -2963,7 +2963,7 @@
Monitor
-**Tool name:** `Monitor` Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. When Monitor runs a command, it follows the same permission rules as Bash; a WebSocket watch prompts for approval separately. The `ws` source requires Claude Code v2.1.195 or later. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for behavior and provider availability. **Input:**
+**Tool name:** `Monitor` Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. The `ws` source requires Claude Code v2.1.195 or later. When Monitor runs a command, it follows the same permission rules as Bash. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for WebSocket permissions, behavior, and provider availability. **Input:**
{
"command": str | None, # Shell script; each stdout line is an event, exit ends the watch
--- a/python.md
+++ b/python.md
@@ -1491,7 +1491,7 @@
`enabled`| `type`, `budget_tokens`, `display`| Enable thinking with a specific token budget
`disabled`| `type`| Disable thinking
-The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. Claude Code doesn’t pass your `display` value to some providers, such as Amazon Bedrock and Google Cloud’s Agent Platform. On those providers, Opus 4.7 and later return empty `ThinkingBlock` outputs even when you set `display` to `"summarized"`. 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`:
+The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. On providers such as Amazon Bedrock and Google Cloud’s Agent Platform, Claude Code doesn’t pass `display` for earlier models it recognizes. Those are Opus 4.6, Sonnet 4.6, Haiku 4.5, and earlier models, which use their default. 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
--- a/python.md
+++ b/python.md
@@ -2721,7 +2721,7 @@
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.
+This example registers two hooks: one that blocks dangerous Bash commands like `rm -rf /`, and another that logs all tool usage for auditing. With its [`Bash` matcher](</docs/en/agent-sdk/hooks#matchers>), the security hook runs on Bash tool calls. The logging hook has no matcher, so it runs on every tool call.
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext
@@ -3787,16 +3787,9 @@
`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
+Violations to leave out of the sandbox’s violation report. Each key matches part of a command, or `*` for every command, and each value lists text to match in a violation line: `{"*": ["/etc/hosts"]}` hides violations that mention `/etc/hosts`. A matching access is still blocked. See [`sandbox.ignoreViolations`](</docs/en/settings-reference#sandbox-ignoreviolations>).
+
+ SandboxIgnoreViolations = dict[str, list[str]]
###
--- a/python.md
+++ b/python.md
@@ -1270,7 +1270,7 @@
PermissionMode = Literal[
"default", # Standard permission behavior
"acceptEdits", # Auto-accept file edits
- "plan", # Planning mode - explore without editing
+ "plan", # Planning mode - Claude explores and plans
"dontAsk", # Deny anything not pre-approved instead of prompting
"bypassPermissions", # Bypass permission checks; explicit ask rules still prompt (use with caution)
"auto", # A model classifier reviews actions such as shell commands and network requests
@@ -1310,7 +1310,12 @@
* `input_data`: The tool’s input parameters
* `context`: A `ToolPermissionContext` with additional information
-Returns a `PermissionResult` (either `PermissionResultAllow` or `PermissionResultDeny`). The callback is the SDK replacement for the interactive permission prompt: it’s invoked only when the [permission evaluation flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) resolves to a prompt. Tool calls already approved by an `allowed_tools` entry, a settings allow rule, or the permission mode, such as `acceptEdits` or `bypassPermissions`, never invoke it. To gate every tool call, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>) instead. An allow rule doesn’t pre-approve the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>); see [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) for which of them reach the callback and what happens in `dontAsk` and `auto` mode.
+Returns a `PermissionResult` (either `PermissionResultAllow` or `PermissionResultDeny`). The callback replaces the interactive permission prompt. The SDK calls `can_use_tool` when the [permission evaluation flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) resolves to a prompt. Calls approved in either of these ways run without calling `can_use_tool`:
+
+ * A call that an `allowed_tools` entry or a settings allow rule approves
+ * A call the permission mode approves, such as a file edit in `acceptEdits` mode
+
+To check those calls, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>), which runs for them too. An allow rule doesn’t pre-approve the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>); see [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) for which of them reach the callback and what happens in `dontAsk` and `auto` mode.
###
@@ -3774,7 +3779,7 @@
`httpProxyPort`| `int`| `None`| HTTP proxy port for network requests
`socksProxyPort`| `int`| `None`| SOCKS proxy port for network requests
-The built-in sandbox proxy enforces the network allowlist based on the requested hostname and does not terminate or inspect TLS traffic, so techniques such as [domain fronting](<https://en.wikipedia.org/wiki/Domain_fronting>) can potentially bypass it. See [Sandboxing security limitations](</docs/en/sandboxing#security-limitations>) for details and [Secure deployment](</docs/en/agent-sdk/secure-deployment#traffic-forwarding>) for configuring a TLS-terminating proxy.
+The built-in sandbox proxy enforces the network allowlist based on the requested hostname. By default, the proxy doesn’t terminate or inspect TLS traffic, so techniques such as [domain fronting](<https://en.wikipedia.org/wiki/Domain_fronting>) can potentially bypass the allowlist. See [Sandboxing security limitations](</docs/en/sandboxing#security-limitations>) for details and [Secure deployment](</docs/en/agent-sdk/secure-deployment#traffic-forwarding>) for configuring a TLS-terminating proxy.
###
--- a/python.md
+++ b/python.md
@@ -2341,6 +2341,11 @@
None # Timeout in seconds. When omitted, the per-event default applies:
# 600 for most events, 30 for UserPromptSubmit
)
+ on_failure: Literal["continue", "block"] | None = (
+ None # "block" blocks the action when a callback fails
+ )
+
+To decide what `on_failure` covers, see [Block the action when a callback fails](</docs/en/agent-sdk/hooks#block-the-action-when-a-callback-fails>).
###
--- a/python.md
+++ b/python.md
@@ -3454,7 +3454,7 @@
TaskStop
-**Tool name:** `TaskStop`. The previous names `KillShell` and `KillBash` are still accepted as aliases. **Input:**
+**Tool name:** `TaskStop`. You can still use the previous names `KillShell` and `KillBash` in permission rules, in hook matchers, and in the `tools`, `allowed_tools`, and `disallowed_tools` options. **Input:**
{
"task_id": str | None, # The ID of the background task to stop
--- a/python.md
+++ b/python.md
@@ -1374,6 +1374,8 @@
`updated_input`| `dict[str, Any] | None`| `None`| Modified input to use instead of original
`updated_permissions`| `list[PermissionUpdate] | None`| `None`| Permission updates to apply
+If you return `PermissionResultAllow` with more than 4,096 items in `updated_permissions`, Claude Code treats the result as invalid and denies the tool call. Each `PermissionUpdate` counts as one item, and so does each entry in its `rules` or `directories` list. The denial message ends with `updatedPermissions may hold at most 4096 updates, rules and directories in all.` To avoid the denial, return 4,096 items or fewer.
+
###
--- a/python.md
+++ b/python.md
@@ -968,7 +968,7 @@
`continue_conversation`| `bool`| `False`| Continue the most recent conversation
`resume`| `str | None`| `None`| Session ID to resume
`session_id`| `str | None`| `None`| Use a specific session ID instead of an auto-generated one. Must be a valid UUID. Can’t be combined with `continue_conversation` or `resume` unless `fork_session` is also set
-`max_turns`| `int | None`| `None`| Maximum agentic turns (tool-use round trips)
+`max_turns`| `int | None`| `None`| Maximum agentic [turns](</docs/en/agent-sdk/agent-loop#turns-and-messages>)
`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. The estimate can pass this value, so [leave headroom](</docs/en/agent-sdk/agent-loop#budget-headroom>). Counts only the call’s own spend; totals restored from a resumed session don’t count. For accuracy caveats and reset behavior, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>)
`disallowed_tools`| `list[str]`| `[]`| Tools to deny. A bare name such as `"Bash"` removes the tool from Claude’s context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`, for the command [as written](</docs/en/permissions#bash-rule-limits>). See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
`enable_file_checkpointing`| `bool`| `False`| Enable file change tracking for rewinding. See [File checkpointing](</docs/en/agent-sdk/file-checkpointing>)
@@ -2772,7 +2772,7 @@
Agent
-**Tool name:** `Agent`. The previous name `Task` is still accepted as an alias, and the `tools` list in the init `SystemMessage` reports this tool as `Task` for backward compatibility. **Input:**
+**Tool name:** `Agent`. The previous name `Task` is still accepted as an alias when this tool is available to the session. The `tools` list in the init `SystemMessage` reports this tool as `Task` for backward compatibility. **Input:**
{
"description": str, # A short (3-5 word) description of the task
@@ -3761,7 +3761,7 @@
`deniedDomains`| `list[str]`| `[]`| Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains`
`allowManagedDomainsOnly`| `bool`| `False`| Managed-settings only: when set in managed settings, ignore `allowedDomains` and `WebFetch(domain:...)` allow rules from non-managed settings sources. Has no effect when set via SDK options
`allowUnixSockets`| `list[str]`| `[]`| macOS only: Unix socket paths that processes can access, such as the Docker socket. Ignored on Linux
-`allowAllUnixSockets`| `bool`| `False`| Allow access to all Unix sockets
+`allowAllUnixSockets`| `bool`| `False`| Allow access to all Unix sockets, and on Linux to VM sockets (`AF_VSOCK`)
`allowLocalBinding`| `bool`| `False`| Allow processes to bind to local ports (for example, for dev servers)
`allowMachLookup`| `list[str]`| `[]`| macOS only: XPC/Mach service names to allow. Supports a trailing wildcard
`httpProxyPort`| `int`| `None`| HTTP proxy port for network requests
--- a/python.md
+++ b/python.md
@@ -2780,14 +2780,19 @@
"subagent_type": str | None, # The type of specialized agent to use
"model": "sonnet" | "opus" | "haiku" | "fable" | None, # Model override for this agent
"effort": "low" | "medium" | "high" | "xhigh" | "max" | None, # Reasoning effort for this agent
- "run_in_background": bool | None, # Agents run in the background by default; set to False to run synchronously
+ "run_in_background": bool | None, # Default when omitted: your main agent's call runs the new agent in the background, and a subagent's call waits for it
"name": str | None, # Name for the spawned agent
"team_name": str | None, # Deprecated; ignored
"mode": "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan" | None, # Deprecated; ignored. The subagent inheritance rules decide a subagent's permission mode
"isolation": "worktree" | "remote" | None, # Isolation mode for the agent's changes
}
-Launches a new agent to handle complex, multi-step tasks autonomously. **Output (status:`"completed"`):**
+Launches a new agent to handle complex, multi-step tasks autonomously. When Claude leaves `run_in_background` out of an `Agent` call, by default your main agent doesn’t wait for the new agent and a subagent waits:
+
+ * **From your main agent** : the new agent runs in the background, and the result has `status: "async_launched"`. To make your main agent wait for the new agent instead, see [Choose whether Claude waits for subagents](</docs/en/agent-sdk/subagents#choose-whether-claude-waits-for-subagents>).
+ * **From one of your subagents** : the calling subagent [waits for the new agent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>). The new agent runs in the background instead when its definition sets `background` to `True`, or when you [turn fork mode off](</docs/en/sub-agents#turn-fork-mode-on-or-off>) by setting `CLAUDE_CODE_FORK_SUBAGENT` to `0`.
+
+Before Python SDK v0.2.169, agents that your subagents started also ran in the background by default. That release is the first to bundle Claude Code v2.1.302 or later. **Output (status:`"completed"`):**
{
"status": "completed",
--- a/python.md
+++ b/python.md
@@ -622,7 +622,7 @@
`set_model(model)`| Change the model for the current session. Pass `None` to reset to [Claude Code’s default model](</docs/en/model-config>). A session in `auto` mode [changes to `default` mode](</docs/en/agent-sdk/permissions#auto-mode-auto>) if the new model doesn’t support auto mode
`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`
-`get_context_usage()`| Get a breakdown of context window usage by category, skill, and tool. The same data `/context` shows in an interactive session. Returns `ContextUsageResponse`. To compute the breakdown, Claude Code makes several token-counting API requests that don’t appear in the message stream; see how these requests are handled
+`get_context_usage()`| Get a breakdown of context window usage by category, skill, and tool. Includes the data `/context` shows in an interactive session. Returns `ContextUsageResponse`. To compute the breakdown, Claude Code makes several token-counting API requests that don’t appear in the message stream; see how these requests are handled
`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 a stdio, SSE, or HTTP server removes its tools
`stop_task(task_id)`| Stop a running background task. A `TaskNotificationMessage` with status `"stopped"` follows in the message stream
@@ -1648,7 +1648,7 @@
`ContextUsageResponse`
-Response from `ClaudeSDKClient.get_context_usage()`. This is the same payload Claude Code renders for the `/context` command in an interactive session, so alongside the token counts it carries display fields such as `color` and `gridRows` that Claude Code uses to draw the `/context` usage grid. Claude Code builds this payload by sending several requests to the [token-counting](<https://platform.claude.com/docs/en/build-with-claude/token-counting>) API. These requests don’t appear in the message stream, so cost tracking that reads the stream won’t see them. On the Anthropic API, token counting isn’t billed.
+Response from `ClaudeSDKClient.get_context_usage()`. The response includes the payload Claude Code renders for the `/context` command in an interactive session. Alongside the token counts, that payload carries display fields such as `color` and `gridRows` that Claude Code uses to draw the `/context` usage grid. Claude Code builds this payload by sending several requests to the [token-counting](<https://platform.claude.com/docs/en/build-with-claude/token-counting>) API. These requests don’t appear in the message stream, so cost tracking that reads the stream won’t see them. On the Anthropic API, token counting isn’t billed.
class ContextUsageResponse(TypedDict):
categories: list[ContextUsageCategory]
@@ -1847,7 +1847,12 @@
The `subtype` field determines which other fields are populated. It is one of `"success"`, `"error_during_execution"`, `"error_max_turns"`, `"error_max_budget_usd"`, or `"error_max_structured_output_retries"`. The Python dataclass flattens all variants into one shape, so fields that don’t apply to the returned subtype are `None`. Several fields carry diagnostic detail about how the conversation ended:
- * `is_error`: `True` when the conversation ended in an error state. Always `True` on the `error_*` subtypes. On `subtype="success"` it is `True` when the final model request failed, meaning the agent loop completed but the last API call returned an error.
+ * `is_error`: `True` when the conversation ended in an error state. Always `True` on the `error_*` subtypes. On `subtype="success"` it is `True` in three cases. Check `stop_reason` to tell them apart:
+ * `"refusal"`: the model declined to respond. Read the refusal text in `result`, or in the preceding `AssistantMessage` when `result` is empty.
+ * `"tool_deferred_unavailable"`: the [deferred tool](</docs/en/hooks#defer-a-tool-call-for-later>) was no longer available when you resumed the session, for example because its MCP server wasn’t connected. In the two cases below, a prompt you send after resuming counts the same as one passed with the resume:
+ * No prompt: the call is still pending. Make the tool available and resume again without a prompt, and the call runs first.
+ * A prompt: Claude Code answers it without the tool’s result, and the deferred call is gone. Send a new prompt if you still need the tool called.
+ * Any other value: the turn ended on an error that Claude Code reported in place of a model response, such as an API error. Read `terminal_reason` for the cause, `result` for the message, and `api_error_status` for the HTTP status when the API returned one.
* `api_error_status`: the HTTP status code of the terminating API error. `None` when the turn ended without one. Populated only on `subtype="success"`.
* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.
* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.
@@ -2230,11 +2235,11 @@
errors: list[str] # an empty list when the result message reported none
result: str | None
api_error_status: int | None
- terminal_reason: str | None # "max_turns", "api_error", ...; check this before subtype
+ terminal_reason: str | None # "max_turns", "api_error", ...; check after data["stop_reason"], before subtype
session_id: str | None
data: dict[str, Any] # the raw result message payload
-To tell failures apart, check `terminal_reason` before `subtype`. When the final request fails, such as on an API error, Claude Code reports `subtype` `"success"` with the cause in `terminal_reason`, for example `"api_error"`; when a limit you set ends the run, such as `max_turns` or `max_budget_usd`, it reports an `error_*` subtype.
+To tell failures apart, check `data["stop_reason"]` first, then `terminal_reason`, then `subtype`. A declined response has `stop_reason` `"refusal"`, usually with `subtype` `"success"`; its `terminal_reason` doesn’t single it out and can read `"completed"` or `"api_error"`. A failed final request has `subtype` `"success"` and its cause in `terminal_reason`, such as `"api_error"` for an API error. When the run hits a limit you set, such as `max_turns` or `max_budget_usd`, you get an `error_*` subtype.
###
@@ -3640,10 +3645,12 @@
"Claude Code CLI not found. Try reinstalling: pip install --force-reinstall claude-agent-sdk"
)
# Catch ResultError before ProcessError, which it subclasses. Its message
- # carries the error text. A failed final request, such as an API error,
- # arrives with subtype "success", so branch on terminal_reason first.
+ # carries the error text. A refusal and a failed final request both usually
+ # arrive with subtype "success", so check stop_reason, then terminal_reason.
except ResultError as e:
- if e.terminal_reason == "api_error":
+ if e.data.get("stop_reason") == "refusal":
+ print(f"Model declined to respond: {e}")
+ elif e.terminal_reason == "api_error":
print(f"API request failed: {e}")
else:
print(f"Query ended with an error result ({e.terminal_reason or e.subtype}): {e}")
--- a/python.md
+++ b/python.md
@@ -1027,7 +1027,7 @@
},
)
- * `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
+ * [`API_TIMEOUT_MS`](</docs/en/env-vars>): how long each request attempt can wait for response headers, in milliseconds. It doesn’t limit how long a streaming response runs after the headers arrive. Default `600000`. Applies to the main loop and all subagents.
* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window. For unattended runs that need to wait through longer outages, set [`CLAUDE_CODE_RETRY_WATCHDOG=1`](</docs/en/errors#tune-retry-behavior>): it retries transient capacity errors indefinitely and, on Claude Code v2.1.199 or later, raises the default for other transient errors to `300` and removes the cap on this variable.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents. While the stream watchdog is on, the default is `CLAUDE_STREAM_IDLE_TIMEOUT_MS` plus 5 minutes, which comes to `600000` unless you raise that variable. With the stream watchdog off, the default is `600000`. Before v2.1.257, the default was always `600000`. The timer resets on each stream event. On a stall, Claude Code aborts the subagent and reports the stall to the parent. For a background subagent, it also marks the task failed and attaches any partial result.
* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: stream watchdog that aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed. While the watchdog waits out a response that a gateway behind `ANTHROPIC_BASE_URL` holds open with keep-alive pings, a host that sets `include_partial_messages` keeps receiving `ping` `StreamEvent` messages. Read those frames as liveness rather than timing the session out on silence. Before v2.1.257, the frames stopped 5 minutes after the last real stream event.
--- a/python.md
+++ b/python.md
@@ -619,7 +619,7 @@
`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 [Claude Code’s default model](</docs/en/model-config>)
+`set_model(model)`| Change the model for the current session. Pass `None` to reset to [Claude Code’s default model](</docs/en/model-config>). A session in `auto` mode [changes to `default` mode](</docs/en/agent-sdk/permissions#auto-mode-auto>) if the new model doesn’t support auto mode
`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`
`get_context_usage()`| Get a breakdown of context window usage by category, skill, and tool. The same data `/context` shows in an interactive session. Returns `ContextUsageResponse`. To compute the breakdown, Claude Code makes several token-counting API requests that don’t appear in the message stream; see how these requests are handled
@@ -3687,7 +3687,9 @@
`ignoreViolations`| `SandboxIgnoreViolations`| `None`| Configure which sandbox violations to ignore
`enableWeakerNestedSandbox`| `bool`| `False`| Enable a weaker nested sandbox for compatibility
-The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. By default, when `enabled` is `True` but the sandbox can’t start, commands run unsandboxed with a warning on stderr. This default differs from the TypeScript SDK, where `failIfUnavailable` defaults to `true`.Set `"failIfUnavailable": True` in your sandbox settings to stop instead. The key isn’t declared on `SandboxSettings` yet, but the SDK forwards it to Claude Code, which honors it. `query()` then reports a `ResultMessage` with `subtype="error_during_execution"` and the reason in `errors`. Because this is a single-shot `query()` call, the SDK raises after yielding that error result, so wrap the loop in a try block to continue past it. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the error contract.
+The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. By default, when `enabled` is `True` but the sandbox can’t start, commands run unsandboxed with a warning on stderr. This default differs from the TypeScript SDK, where `failIfUnavailable` defaults to `true`.Set `"failIfUnavailable": True` in your sandbox settings to stop instead. The SDK forwards `failIfUnavailable` to Claude Code along with the declared `SandboxSettings` fields. `query()` then reports a `ResultMessage` with `subtype="error_during_execution"` and the reason in `errors`. Because this is a single-shot `query()` call, the SDK raises after yielding that error result, so wrap the loop in a try block to continue past it. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the error contract.
+
+To keep sandboxed commands from writing to a file, list its absolute path under [`denyWrite`](</docs/en/settings-reference#sandbox-filesystem-denywrite>) in your sandbox settings, such as `"filesystem": {"denyWrite": ["/home/user/project/.env"]}`. The SDK forwards `filesystem` to Claude Code along with the declared `SandboxSettings` fields. Once the sandbox starts, it blocks writes to each absolute path you listed.
####
--- a/python.md
+++ b/python.md
@@ -3287,7 +3287,7 @@
**Tool name:** `TodoWrite`
-The following tools are available by default only on Claude 3.x models, Opus 4 through 4.7, Sonnet 4 through 4.6, and Haiku 4.5. On every other model, including model IDs Claude Code doesn’t recognize, they aren’t available unless you opt in:
+The following tools are available by default only on Claude Opus 4.7, Claude Sonnet 4.6, Claude Haiku 4.5, and earlier models. On every other model, including model IDs Claude Code doesn’t recognize, they aren’t available unless you opt in:
* `TodoWrite`
* `TaskCreate`
--- a/python.md
+++ b/python.md
@@ -522,6 +522,55 @@
for session in list_sessions(directory="/path/to/project"):
if session.tag == "needs-review":
print(session.summary)
+
+###
+
+
+
+`fork_session()`
+
+Copies a session’s transcript into a new session so you can take the conversation in another direction while the original stays unchanged. To branch from an earlier point in the conversation, pass `up_to_message_id`. Synchronous.
+
+ def fork_session(
+ session_id: str,
+ directory: str | None = None,
+ up_to_message_id: str | None = None,
+ title: str | None = None,
+ ) -> ForkSessionResult
+
+####
+
+
+
+Parameters
+
+Parameter| Type| Default| Description
+---|---|---|---
+`session_id`| `str`| required| UUID of the session to fork
+`directory`| `str | None`| `None`| Project directory path. When omitted, searches all project directories
+`up_to_message_id`| `str | None`| `None`| Copy the transcript up to and including the message with this UUID, such as a `uuid` from `get_session_messages()`. When omitted, copies the whole transcript
+`title`| `str | None`| `None`| Title for the fork. When omitted, the SDK derives one from the original session, followed by `(fork)`
+
+Returns a `ForkSessionResult` whose `session_id` is the new session’s UUID. Pass it as `resume` to continue the fork. The fork doesn’t include the original session’s [file checkpoints](</docs/en/agent-sdk/file-checkpointing>), so you can’t rewind it to a checkpoint captured before the fork. `fork_session()` raises:
+
+ * `ValueError`: `session_id` or `up_to_message_id` is not a valid UUID
+ * `ValueError`: the session has no messages, or `up_to_message_id` matches no message in the transcript
+ * `FileNotFoundError`: the session cannot be found
+
+####
+
+
+
+Example
+
+Fork the most recent session under a new title, then resume the fork. The original session keeps its own history.
+
+ from claude_agent_sdk import fork_session, list_sessions
+
+ sessions = list_sessions(directory="/path/to/project", limit=1)
+ if sessions:
+ forked = fork_session(sessions[0].session_id, title="Try the OAuth approach")
+ print(forked.session_id) # pass as ClaudeAgentOptions(resume=...) to continue the fork
##
@@ -911,7 +960,7 @@
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. If you name one of the [task-tracking tools](</docs/en/agent-sdk/todo-tracking#model-availability>) here, Claude Code also opts the session in. Other 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>)
+`allowed_tools`| `list[str]`| `[]`| Tools to auto-approve without prompting, apart from reads from [network paths](</docs/en/permissions#network-paths>). This does not restrict Claude to only these tools. If you name one of the [task-tracking tools](</docs/en/agent-sdk/todo-tracking#model-availability>) here, Claude Code also opts the session in. Other 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 | SystemPromptCustom | SystemPromptFile | None`| `None`| System prompt configuration. Pass a string for a custom prompt, `{"type": "preset", "preset": "claude_code"}` for Claude Code’s system prompt with optional `"append"`, `{"type": "custom", "prompt": "..."}` for a custom prompt that can also set `"snapshot"`, or `{"type": "file", "path": "..."}` to load a large prompt from disk. See `SystemPromptPreset`, `SystemPromptCustom`, and `SystemPromptFile`
`mcp_servers`| `dict[str, McpServerConfig] | str | Path`| `{}`| MCP server configurations or path to config file
`strict_mcp_config`| `bool`| `False`| When `True`, use only the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, plugin-provided MCP servers, and [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>). Maps to the CLI `--strict-mcp-config` flag
@@ -1805,7 +1854,7 @@
* `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are `interrupt()` and a permission callback returning `PermissionResultDeny` with `interrupt=True`. `None` on CLI versions that predate the field, on results from local commands such as `/voice` or `/usage`, which bypass the query loop, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK’s [`SDKResultMessage.terminal_reason`](</docs/en/agent-sdk/typescript#sdkresultmessage>), which lists the full set of values.
* `origin`: origin of the user message that triggered this turn. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), check this to tell the result of your own prompt, where `origin` is `None` or `{"kind": "human"}`, from the result of an injected turn such as a background-task notification. Requires Python Agent SDK 0.2.137 or later.
-The `usage` dict covers the main agent loop only and excludes subagent and other nested or auxiliary model calls. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), the values are per-turn. Prefer `model_usage` for token and cost accounting. The `usage` dict contains the following keys when present:
+When several background tasks finish close together, Claude Code can answer their notifications in one turn rather than one turn each. You still receive one `ResultMessage` per notification, in order, each with an `origin` whose `kind` is `"task-notification"`. All but the last have `num_turns` set to `0` and an empty `result`, and the last one carries the turn that answers them all. The `usage` dict covers the main agent loop only and excludes subagent and other nested or auxiliary model calls. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), the values are per-turn. Prefer `model_usage` for token and cost accounting. The `usage` dict contains the following keys when present:
Key| Type| Description
---|---|---
--- a/python.md
+++ b/python.md
@@ -920,7 +920,7 @@
`resume`| `str | None`| `None`| Session ID to resume
`session_id`| `str | None`| `None`| Use a specific session ID instead of an auto-generated one. Must be a valid UUID. Can’t be combined with `continue_conversation` or `resume` unless `fork_session` is also set
`max_turns`| `int | None`| `None`| Maximum agentic turns (tool-use round trips)
-`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. Counts only the call’s own spend; totals restored from a resumed session don’t count. For accuracy caveats and reset behavior, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>)
+`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. The estimate can pass this value, so [leave headroom](</docs/en/agent-sdk/agent-loop#budget-headroom>). Counts only the call’s own spend; totals restored from a resumed session don’t count. For accuracy caveats and reset behavior, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>)
`disallowed_tools`| `list[str]`| `[]`| Tools to deny. A bare name such as `"Bash"` removes the tool from Claude’s context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`, for the command [as written](</docs/en/permissions#bash-rule-limits>). See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
`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 alias or full model name. See [accepted values and provider-specific IDs](</docs/en/model-config#available-models>)
@@ -979,7 +979,7 @@
)
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
- * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set [`CLAUDE_CODE_RETRY_WATCHDOG=1`](</docs/en/errors#tune-retry-behavior>): it retries transient capacity errors indefinitely and, on Claude Code v2.1.199 or later, raises the default for other transient errors to `300` and removes the cap on this variable.
+ * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window. For unattended runs that need to wait through longer outages, set [`CLAUDE_CODE_RETRY_WATCHDOG=1`](</docs/en/errors#tune-retry-behavior>): it retries transient capacity errors indefinitely and, on Claude Code v2.1.199 or later, raises the default for other transient errors to `300` and removes the cap on this variable.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents. While the stream watchdog is on, the default is `CLAUDE_STREAM_IDLE_TIMEOUT_MS` plus 5 minutes, which comes to `600000` unless you raise that variable. With the stream watchdog off, the default is `600000`. Before v2.1.257, the default was always `600000`. The timer resets on each stream event. On a stall, Claude Code aborts the subagent and reports the stall to the parent. For a background subagent, it also marks the task failed and attaches any partial result.
* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: stream watchdog that aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed. While the watchdog waits out a response that a gateway behind `ANTHROPIC_BASE_URL` holds open with keep-alive pings, a host that sets `include_partial_messages` keeps receiving `ping` `StreamEvent` messages. Read those frames as liveness rather than timing the session out on silence. Before v2.1.257, the frames stopped 5 minutes after the last real stream event.
@@ -3194,6 +3194,7 @@
{
"url": str, # The URL to fetch content from
"prompt": str, # The prompt to run on the fetched content
+ "offset": int | None, # Number of characters to skip from the start of the page. Requires Python Agent SDK 0.2.164 or later
}
**Output:**
--- a/python.md
+++ b/python.md
@@ -942,7 +942,7 @@
`user`| `str | None`| `None`| On POSIX platforms, the OS user account the Claude Code subprocess runs as. Claude Code keeps the parent process’s environment, including `HOME`, and runs in `cwd`
`include_partial_messages`| `bool`| `False`| Include partial message streaming events. When enabled, `StreamEvent` messages are yielded
`include_hook_events`| `bool`| `False`| Include hook lifecycle events in the message stream as `HookEventMessage` objects
-`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. Without this option, Claude Code emits subagent `tool_use` and `tool_result` blocks but not text or thinking. Requires Python Agent SDK 0.2.140 or later
+`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. Without this option, Claude Code omits the text and thinking blocks of a subagent that runs in the [foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>). For nested subagents, skills with `context: fork`, and the Claude Code version each needs, see [Follow subagent messages](</docs/en/headless#follow-subagent-messages>). Requires Python Agent SDK 0.2.140 or later
`verbatim_prompts`| `bool`| `False`| Deliver every prompt as written. The SDK sends each user message with `client_composed` set to `True`. See [`client_composed`](</docs/en/agent-sdk/typescript#sdkusermessage>) for what Claude Code skips on those messages. Use this option when your prompt text includes content the end user didn’t type. For per-turn control, leave it off and set `"client_composed": True` on individual streamed messages instead. While the option is on, the SDK overwrites any `client_composed` value you set. Requires Python Agent SDK 0.2.158 or later and Claude Code v2.1.248 or later; the CLI bundled with those SDK versions satisfies the Claude Code requirement
`fork_session`| `bool`| `False`| When resuming with `resume`, fork to a new session ID instead of continuing the original session
`resume_session_at`| `str | None`| `None`| When resuming, load the conversation only up to and including the message with this UUID. Use with `resume`, and usually `fork_session`, to branch from an earlier point. Requires Python Agent SDK 0.2.137 or later
@@ -1435,7 +1435,7 @@
`enabled`| `type`, `budget_tokens`, `display`| Enable thinking with a specific token budget
`disabled`| `type`| Disable thinking
-The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. Claude Code leaves `display` out of requests to some providers, such as Amazon Bedrock and Google Cloud’s Agent Platform. On those providers, Opus 4.7 and later return empty `ThinkingBlock` outputs even when you set `display` to `"summarized"`. 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`:
+The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. Claude Code doesn’t pass your `display` value to some providers, such as Amazon Bedrock and Google Cloud’s Agent Platform. On those providers, Opus 4.7 and later return empty `ThinkingBlock` outputs even when you set `display` to `"summarized"`. 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
@@ -2725,6 +2725,7 @@
"prompt": str, # The task for the agent to perform
"subagent_type": str | None, # The type of specialized agent to use
"model": "sonnet" | "opus" | "haiku" | "fable" | None, # Model override for this agent
+ "effort": "low" | "medium" | "high" | "xhigh" | "max" | None, # Reasoning effort for this agent
"run_in_background": bool | None, # Agents run in the background by default; set to False to run synchronously
"name": str | None, # Name for the spawned agent
"team_name": str | None, # Deprecated; ignored
--- a/python.md
+++ b/python.md
@@ -191,7 +191,7 @@
`ToolAnnotations`
-Behavioral hints for a tool, passed as the `annotations` argument of `tool()`. `ToolAnnotations` extends the MCP SDK’s `mcp.types.ToolAnnotations` with a `maxResultSizeChars` field, and you can write each hint in camelCase or snake_case: `ToolAnnotations(readOnlyHint=True)` and `ToolAnnotations(read_only_hint=True)` are equivalent. You can also pass a plain `mcp.types.ToolAnnotations` wherever the SDK accepts annotations. The snake_case names and the typed `maxResultSizeChars` field require Python Agent SDK 0.2.140 or later. Versions 0.1.31 through 0.2.139 re-export `mcp.types.ToolAnnotations` unchanged. On versions 0.1.55 through 0.2.139 you can still pass `maxResultSizeChars` as a keyword argument: the MCP class accepts extra fields, and the SDK forwards the value to Claude Code. All fields are optional. Clients shouldn’t rely on the hints for security decisions.
+Behavioral hints for a tool, passed as the `annotations` argument of `tool()`. `ToolAnnotations` extends the MCP SDK’s `mcp.types.ToolAnnotations` with a `maxResultSizeChars` field, and you can write each hint in camelCase or snake_case: `ToolAnnotations(readOnlyHint=True)` and `ToolAnnotations(read_only_hint=True)` are equivalent. To read a hint back from the object, use the spelling your installed `mcp` package declares: `.readOnlyHint` on `mcp` 1.x and `.read_only_hint` on 2.x, while `.maxResultSizeChars` works on both. You can also pass a plain `mcp.types.ToolAnnotations` wherever the SDK accepts annotations. The snake_case names and the typed `maxResultSizeChars` field require Python Agent SDK 0.2.140 or later. Versions 0.1.31 through 0.2.139 re-export `mcp.types.ToolAnnotations` unchanged. On versions 0.1.55 through 0.2.139 you can still pass `maxResultSizeChars` as a keyword argument: the MCP class accepts extra fields, and the SDK forwards the value to Claude Code. All fields are optional. Clients shouldn’t rely on the hints for security decisions.
Field| Type| Default| Description
---|---|---|---
@@ -1435,7 +1435,7 @@
`enabled`| `type`, `budget_tokens`, `display`| Enable thinking with a specific token budget
`disabled`| `type`| Disable thinking
-The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. Claude Code doesn’t send `display` to Amazon Bedrock or Google Cloud’s Agent Platform, so on those providers Opus 4.7 and later return empty `ThinkingBlock` outputs even when you set `display` to `"summarized"`. 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`:
+The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. Claude Code leaves `display` out of requests to some providers, such as Amazon Bedrock and Google Cloud’s Agent Platform. On those providers, Opus 4.7 and later return empty `ThinkingBlock` outputs even when you set `display` to `"summarized"`. 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
@@ -1829,6 +1829,7 @@
`maxOutputTokens`| `int`| Maximum output token limit for this model.
`canonicalModel`| `str`| Canonical model ID used for the pricing lookup. May differ from the raw model string the entry is keyed by, such as a provider-specific ID or alias. Not always present.
`provider`| `str`| API provider that served this model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`. Not always present.
+`costBasis`| `str`| Price table that priced this model’s latest request: `list` for list price, `managed` for a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table, or `unknown` when neither matched the model ID. Not always present, and not declared on the TypedDict, so read it with `.get()`. Requires Claude Code v2.1.246 or later.
###
@@ -2121,7 +2122,7 @@
class ClaudeSDKError(Exception):
"""Base error for Claude SDK."""
-When a single-shot `query()` ends with an error result, for example a turn-limit error, the SDK raises a `ResultError` after yielding the final result message. Python Agent SDK versions before 0.2.140 raised a plain `Exception` that wasn’t a `ClaudeSDKError` subclass.
+When a single-shot `query()` ends with an error result, for example a turn-limit error, the SDK raises a `ResultError`.
###
@@ -2173,7 +2174,7 @@
`ResultError`
-Raised after the final `ResultMessage` when the Claude Code process exits because the run ended with an error result, such as a turn-limit error or an API error. `ResultError` subclasses `ProcessError`, so an existing `except ProcessError` handler also catches it. Its attributes carry the fields of that result message, so you can branch on why the run failed without parsing the message text. Requires Python Agent SDK 0.2.140 or later.
+Raised when the Claude Code process exits because the run ended with an error result message, such as a turn-limit error or an API error. `ResultError` subclasses `ProcessError`, so an existing `except ProcessError` handler also catches it. Its attributes carry the fields of that result message, so you can branch on why the run failed without parsing the message text. Requires Python Agent SDK 0.2.140 or later.
class ResultError(ProcessError):
subtype: str | None # "error_max_turns", "error_during_execution", ...; "success" when the run ended on a failed request
@@ -2602,7 +2603,7 @@
hookEventName: Literal["PostToolUse"]
additionalContext: NotRequired[str]
updatedToolOutput: NotRequired[Any]
- updatedMCPToolOutput: NotRequired[Any] # Deprecated: use updatedToolOutput, which works for all tools
+ updatedMCPToolOutput: NotRequired[Any] # MCP tools only. Prefer updatedToolOutput, which works for all tools
class PostToolUseFailureHookSpecificOutput(TypedDict):
hookEventName: Literal["PostToolUseFailure"]
@@ -2709,7 +2710,7 @@
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. Each output shown is the value you read from `UserMessage.tool_use_result` for that tool. Key names appear exactly as Claude Code emits them. A key annotated `| None` with a “present when” or “optional” comment is omitted when it doesn’t apply.
+Documentation of input/output schemas for 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. Each output shown is the value you read from `UserMessage.tool_use_result` for that tool. Key names appear exactly as Claude Code emits them. A key annotated `| None` with a “present when” or “optional” comment is omitted when it doesn’t apply.
###
--- a/python.md
+++ b/python.md
@@ -145,6 +145,24 @@
},
"required": ["text"],
}
+
+ 3. **TypedDict class** : a typed schema whose `NotRequired` keys are left out of `required`.
+ * **Python 3.11 and later** : import `TypedDict` and `NotRequired` from `typing`.
+ * **Python 3.10** : `typing` has no `NotRequired`. Import `TypedDict` and `NotRequired` from `typing_extensions`, which the SDK installs on Python 3.10.
+
+ from typing import Annotated, Any, NotRequired, TypedDict
+ from claude_agent_sdk import tool
+
+ class ForecastArgs(TypedDict):
+ latitude: Annotated[float, "Latitude coordinate"]
+ hours: NotRequired[Annotated[int, "How many hours of forecast to return"]]
+
+ @tool("get_forecast", "Get the hourly forecast for a location", ForecastArgs)
+ async def get_forecast(args: dict[str, Any]) -> dict[str, Any]:
+ hours = args.get("hours", 12)
+ return {"content": [{"type": "text", "text": f"{hours}-hour forecast for {args['latitude']}"}]}
+
+In the simple mapping and TypedDict forms, wrap a type in `Annotated[type, "description"]` to set the field’s description.
####
@@ -1746,6 +1764,8 @@
subtype: str
data: dict[str, Any]
+Subtypes that have no dataclass of their own arrive as `SystemMessage`. To follow the session between turns, set [`CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS=1`](</docs/en/env-vars#variables>) and read `message.data["state"]` on each message whose `subtype` is `session_state_changed`. [`SDKSessionStateChangedMessage`](</docs/en/agent-sdk/typescript#sdksessionstatechangedmessage>) lists the states it can carry. Iterate with `receive_messages()` to read them: `receive_response()` stops at the `ResultMessage`, and a `session_state_changed` message can follow that result.
+
###
@@ -2227,7 +2247,7 @@
Parameters:
- * `input`: Strongly-typed hook input with discriminated unions based on `hook_event_name` (see `HookInput`)
+ * `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
--- a/python.md
+++ b/python.md
@@ -2741,6 +2741,7 @@
"speed": str | None,
"iterations": Any | None,
"output_tokens_details": {"thinking_tokens": int | None} | None,
+ "fallback_credit": Any | None,
},
"toolStats": { # Aggregate tool activity for the run
"readCount": int,
@@ -2782,7 +2783,7 @@
"outputFile": str, # File path where the agent's output is written
}
-Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a cloud session, where `sessionUrl` links to that session and `taskId` identifies it. If Claude Code [kept the subagent’s isolated worktree](</docs/en/worktrees#isolate-subagents-with-worktrees>), `worktreePath` on the `completed` variant is where to find it, and `worktreeBranch` is its branch when Claude Code created the worktree with git. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On the `async_launched` variant, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The `modelsUsed` field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later. Claude Code fills `usage` and `totalTokens` from the subagent’s final API request, not from the whole run. When present, `thinking_tokens` under `output_tokens_details` in `usage` is the number of that request’s output tokens that were thinking tokens. The `output_tokens_details` key requires Python SDK v0.2.136 or later, which bundles Claude Code v2.1.228.
+Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a cloud session, where `sessionUrl` links to that session and `taskId` identifies it. If Claude Code [kept the subagent’s isolated worktree](</docs/en/worktrees#isolate-subagents-with-worktrees>), `worktreePath` on the `completed` variant is where to find it, and `worktreeBranch` is its branch when Claude Code created the worktree with git. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On the `async_launched` variant, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The `modelsUsed` field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later. Claude Code fills `usage` and `totalTokens` from the subagent’s final API request, not from the whole run. When present, `thinking_tokens` under `output_tokens_details` in `usage` is the number of that request’s output tokens that were thinking tokens. The `output_tokens_details` key requires Python SDK v0.2.136 or later, which bundles Claude Code v2.1.228. The `fallback_credit` key requires Python SDK v0.2.162 or later, which bundles Claude Code v2.1.285.
###
--- a/python.md
+++ b/python.md
@@ -2204,7 +2204,7 @@
"PreToolUse", # Called before tool execution
"PostToolUse", # Called after tool execution
"PostToolUseFailure", # Called when a tool execution fails
- "UserPromptSubmit", # Called when user submits a prompt
+ "UserPromptSubmit", # Called when a prompt is submitted
"Stop", # Called when stopping execution
"SubagentStop", # Called when a subagent stops
"PreCompact", # Called before message compaction
@@ -2403,7 +2403,7 @@
Field| Type| Description
---|---|---
`hook_event_name`| `Literal["UserPromptSubmit"]`| Always “UserPromptSubmit”
-`prompt`| `str`| The user’s submitted prompt
+`prompt`| `str`| The submitted prompt
###
--- a/python.md
+++ b/python.md
@@ -530,6 +530,7 @@
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 get_context_usage(self) -> ContextUsageResponse
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
@@ -554,6 +555,7 @@
`set_model(model)`| Change the model for the current session. Pass `None` to reset to [Claude Code’s default model](</docs/en/model-config>)
`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`
+`get_context_usage()`| Get a breakdown of context window usage by category, skill, and tool. The same data `/context` shows in an interactive session. Returns `ContextUsageResponse`. To compute the breakdown, Claude Code makes several token-counting API requests that don’t appear in the message stream; see how these requests are handled
`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 a stdio, SSE, or HTTP server removes its tools
`stop_task(task_id)`| Stop a running background task. A `TaskNotificationMessage` with status `"stopped"` follows in the message stream
@@ -1456,7 +1458,7 @@
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 Opus 5.5, Claude Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
+On the Claude API, the `context-1m-2025-08-07` beta is retired for Claude Sonnet 4.5 and Claude Sonnet 4. If you still pass it with either model, requests that exceed the standard 200K-token context window return an error, so remove it from `betas`. To run a session with a 1M-token context window, set `model` to a model that [runs with the 1M window by default](</docs/en/model-config#extended-context>), such as `claude-sonnet-5-5` or `claude-opus-5-5`. For a model that reaches 1M only through its `[1m]` variant, append the suffix to the model ID, as in `claude-opus-4-6[1m]`.
###
@@ -1572,6 +1574,37 @@
`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
+
+###
+
+
+
+`ContextUsageResponse`
+
+Response from `ClaudeSDKClient.get_context_usage()`. This is the same payload Claude Code renders for the `/context` command in an interactive session, so alongside the token counts it carries display fields such as `color` and `gridRows` that Claude Code uses to draw the `/context` usage grid. Claude Code builds this payload by sending several requests to the [token-counting](<https://platform.claude.com/docs/en/build-with-claude/token-counting>) API. These requests don’t appear in the message stream, so cost tracking that reads the stream won’t see them. On the Anthropic API, token counting isn’t billed.
+
+ class ContextUsageResponse(TypedDict):
+ categories: list[ContextUsageCategory]
+ totalTokens: int
+ maxTokens: int
+ rawMaxTokens: int
+ percentage: float
+ model: str
+ isAutoCompactEnabled: bool
+ memoryFiles: list[dict[str, Any]]
+ mcpTools: list[dict[str, Any]]
+ agents: list[dict[str, Any]]
+ gridRows: list[list[dict[str, Any]]]
+ autoCompactThreshold: NotRequired[int]
+ deferredBuiltinTools: NotRequired[list[dict[str, Any]]]
+ systemTools: NotRequired[list[dict[str, Any]]]
+ systemPromptSections: NotRequired[list[dict[str, Any]]]
+ slashCommands: NotRequired[dict[str, Any]]
+ skills: NotRequired[dict[str, Any]] # skill usage with frontmatter breakdown
+ messageBreakdown: NotRequired[dict[str, Any]] # message tokens by type
+ apiUsage: NotRequired[dict[str, Any] | None]
+
+Each `ContextUsageCategory` entry carries `name`, `tokens`, `color`, and an optional `isDeferred` flag. `totalTokens` is the session’s current context usage, and `maxTokens` is the window that usage is measured against. That window is the model’s context window, or the lower auto-compaction window when one applies, and `rawMaxTokens` carries the same value as `maxTokens`. `apiUsage` holds the usage from the latest API response, not a running total for the session. Claude Code leaves the optional `deferredBuiltinTools`, `systemTools`, and `systemPromptSections` keys unset, so expect them to be absent even though the type declares them.
###
Show diff (433 lines)
--- a/python.md
+++ b/python.md
@@ -555,7 +555,7 @@
`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
+`toggle_mcp_server(server_name, enabled)`| Enable or disable an MCP server mid-session. Disabling a stdio, SSE, or HTTP server 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 the server’s initialization info, including available commands and output styles
`disconnect()`| Disconnect from Claude
@@ -628,24 +628,21 @@
Example - Streaming input with ClaudeSDKClient
+`query()` also accepts an async iterable of user message dicts, so you can assemble the prompt at send time or include content blocks such as images. Claude Code starts responding to the first yielded message as soon as it arrives, without waiting for the iterable to finish, and `receive_response()` stops at the `ResultMessage` that ends that response. Put everything Claude should read before answering into one message, as this generator does, and pair each `query()` call with its own `receive_response()` loop.
+
import asyncio
from claude_agent_sdk import ClaudeSDKClient
async def message_stream():
- """Generate messages dynamically."""
+ """Assemble the prompt at send time and yield it as one user message."""
+ readings = {"Temperature": "25°C", "Humidity": "60%"}
+ data = ", ".join(f"{name}: {value}" for name, value in readings.items())
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?"},
+ "message": {
+ "role": "user",
+ "content": f"Analyze the following sensor data and describe any patterns you see: {data}",
+ },
}
async def main():
@@ -2659,7 +2656,7 @@
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.
+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. Each output shown is the value you read from `UserMessage.tool_use_result` for that tool. Key names appear exactly as Claude Code emits them. A key annotated `| None` with a “present when” or “optional” comment is omitted when it doesn’t apply.
###
@@ -2814,11 +2811,11 @@
Bash
-**Tool name:** `Bash` **Input:**
+**Tool name:** `Bash` For what sets the foreground ceiling, see [Timeout and output limits](</docs/en/tools-reference#timeout-and-output-limits>). For the background time limit, see [Time limit for background commands](</docs/en/tools-reference#time-limit-for-background-commands>). **Input:**
{
"command": str, # The command to execute
- "timeout": int | None, # Optional timeout in milliseconds (max 600000; higher values are clamped to the max)
+ "timeout": int | None, # Milliseconds. Foreground: capped at 600000 by default, higher values are clamped. With run_in_background (Claude Code v2.1.285 or later): the background time limit, 1800000 when omitted, capped at 7200000 unless raised
"description": str | None, # Clear, concise description (5-10 words)
"run_in_background": bool | None, # Set to true to run in background
}
@@ -2874,9 +2871,30 @@
**Output:**
{
- "message": str, # Confirmation message
- "replacements": int, # Number of replacements made
- "file_path": str, # File path that was edited
+ "filePath": str, # The file that was edited
+ "oldString": str, # The text that was replaced
+ "newString": str, # The text that replaced it
+ "originalFile": str | None, # File contents before the edit
+ "structuredPatch": [ # Diff hunks for the change
+ {
+ "oldStart": int,
+ "oldLines": int,
+ "newStart": int,
+ "newLines": int,
+ "lines": list[str],
+ }
+ ],
+ "userModified": bool, # Whether the user changed the proposed edit before accepting it
+ "replaceAll": bool, # Whether all occurrences were replaced
+ "gitDiff": { # Optional git diff summary for the file
+ "filename": str,
+ "status": "modified" | "added",
+ "additions": int,
+ "deletions": int,
+ "changes": int,
+ "patch": str,
+ "repository": str | None, # GitHub owner/repo when available
+ } | None,
}
###
@@ -2893,20 +2911,79 @@
"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
+The output takes one of the following shapes depending on what Claude read. Check the `type` key to tell them apart. **Output (type:`"text"`):**
+
+ {
+ "type": "text",
+ "file": {
+ "filePath": str, # The file that was read
+ "content": str, # The returned content
+ "numLines": int, # Number of lines in the returned content
+ "startLine": int, # Line number the content starts at
+ "totalLines": int, # Total number of lines in the file
+ "truncatedByTokenCap": bool | None, # Present and True when a whole-file read exceeded the token cap and content is the first page
+ },
+ }
+
+**Output (type:`"image"`):**
+
+ {
+ "type": "image",
+ "file": {
+ "base64": str, # Base64-encoded image data
+ "type": "image/jpeg" | "image/png" | "image/gif" | "image/webp", # Image MIME type
+ "originalSize": int, # Original file size in bytes
+ "dimensions": { # Optional sizing info for coordinate mapping
+ "originalWidth": int | None, # Optional; original width in pixels
+ "originalHeight": int | None, # Optional; original height in pixels
+ "displayWidth": int | None, # Optional; width after resizing
+ "displayHeight": int | None, # Optional; height after resizing
+ } | None,
+ },
+ }
+
+**Output (type:`"notebook"`):**
+
+ {
+ "type": "notebook",
+ "file": {
+ "filePath": str, # The notebook that was read
+ "cells": list, # Notebook cells
+ },
+ }
+
+**Output (type:`"pdf"`):**
+
+ {
+ "type": "pdf",
+ "file": {
+ "filePath": str, # The PDF that was read
+ "base64": str, # Base64-encoded PDF data
+ "originalSize": int, # File size in bytes
+ },
+ }
+
+**Output (type:`"parts"`):**
+
+ {
+ "type": "parts",
+ "file": {
+ "filePath": str, # The PDF that was read
+ "originalSize": int, # File size in bytes
+ "count": int, # Number of pages extracted as images
+ "outputDir": str, # Directory containing the extracted page images
+ },
+ "firstPage": int | None, # Optional document page number of the first extracted page
+ }
+
+**Output (type:`"file_unchanged"`):**
+
+ {
+ "type": "file_unchanged", # The file is unchanged since Claude last read it in this session, so the content isn't repeated
+ "file": {
+ "filePath": str,
+ },
+ "source": "seeded" | None, # Present when the earlier copy came from a CLAUDE.md or memory file loaded at startup rather than a Read call
}
###
@@ -2925,9 +3002,29 @@
**Output:**
{
- "message": str, # Success message
- "bytes_written": int, # Number of bytes written
- "file_path": str, # File path that was written
+ "type": "create" | "update", # Whether the write created a new file or overwrote an existing one
+ "filePath": str, # The file that was written
+ "content": str, # The content that was written
+ "structuredPatch": [ # Diff hunks; empty for a new file, when nothing changed, or when Claude Code skipped the diff
+ {
+ "oldStart": int,
+ "oldLines": int,
+ "newStart": int,
+ "newLines": int,
+ "lines": list[str],
+ }
+ ],
+ "originalFile": str | None, # Previous content; None for a new file or when the previous content was too large to include
+ "gitDiff": { # Optional git diff summary for the file
+ "filename": str,
+ "status": "modified" | "added",
+ "additions": int,
+ "deletions": int,
+ "changes": int,
+ "patch": str,
+ "repository": str | None, # GitHub owner/repo when available
+ } | None,
+ "userModified": bool | None, # Optional; whether the user edited the proposed content before accepting it
}
###
@@ -2946,10 +3043,15 @@
**Output:**
{
- "matches": list[str], # Array of matching file paths
- "count": int, # Number of matches found
- "search_path": str, # Search directory used
- }
+ "durationMs": int, # Time taken to run the search, in milliseconds
+ "numFiles": int, # Number of paths returned, after any truncation
+ "filenames": list[str], # Matching file paths
+ "truncated": bool, # Whether the results were truncated at the 100-file limit
+ "totalMatches": int | None, # Optional total number of matching files before truncation; a lower bound when countIsComplete is False
+ "countIsComplete": bool | None, # Optional; whether totalMatches is exact
+ }
+
+`totalMatches` and `countIsComplete` require Claude Code v2.1.191 or later.
###
@@ -2970,31 +3072,29 @@
"-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
+ "context": int | None, # Lines to show before and after; -C is an alias
+ "-o": bool | None, # Print only the matched parts of each line
"head_limit": int | None, # Limit output to first N lines/entries
+ "offset": int | None, # Skip first N lines/entries before applying head_limit
"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
- }
+**Output:**
+
+ {
+ "mode": "content" | "files_with_matches" | "count" | None, # The output mode that was used
+ "numFiles": int, # Number of files in the result; always 0 in content mode
+ "filenames": list[str], # Matching files in files_with_matches mode; empty in the other modes
+ "content": str | None, # Matching lines in content mode, or per-file counts in count mode
+ "numLines": int | None, # Number of lines in content, present in content mode
+ "numMatches": int | None, # Total match count, present in count mode
+ "totalFiles": int | None, # Optional total before head_limit and offset, in files_with_matches mode
+ "totalLines": int | None, # Optional total before head_limit and offset, in content mode
+ "appliedLimit": int | None, # Present when head_limit truncated the result
+ "appliedOffset": int | None, # Present when an offset was applied
+ }
+
+Grep returns this dict shape in each output mode. Which optional keys are present depends on `output_mode`. `totalFiles` requires Claude Code v2.1.208 or later. `totalLines` requires Claude Code v2.1.210 or later.
###
@@ -3015,10 +3115,16 @@
**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
+ "new_source": str, # The source written to the cell
+ "old_source": str | None, # Previous cell source, present for replace and delete
+ "cell_id": str | None, # ID of the edited cell, when available
+ "cell_type": "code" | "markdown", # The cell type
+ "language": str, # The notebook's programming language
+ "edit_mode": str, # The edit mode that was used
+ "error": str | None, # Error message when the operation failed
+ "notebook_path": str, # The notebook file
+ "original_file": str, # Notebook content before the edit
+ "updated_file": str, # Notebook content after the edit
}
###
@@ -3100,8 +3206,20 @@
**Output:**
{
- "message": str, # Success message
- "stats": {"total": int, "pending": int, "in_progress": int, "completed": int},
+ "oldTodos": [ # The todo list before the update
+ {
+ "content": str,
+ "status": "pending" | "in_progress" | "completed",
+ "activeForm": str,
+ }
+ ],
+ "newTodos": [ # The todo list after the update
+ {
+ "content": str,
+ "status": "pending" | "in_progress" | "completed",
+ "activeForm": str,
+ }
+ ],
}
###
@@ -3249,8 +3367,13 @@
**Output:**
{
- "message": str, # Confirmation message
- "approved": bool | None, # Whether user approved the plan
+ "plan": str | None, # The plan that was presented to the user
+ "isAgent": bool, # True when a subagent called the tool
+ "filePath": str | None, # Present when the plan was saved to a file
+ "hasTaskTool": bool | None, # Optional; whether the Agent tool is available in the current context
+ "planWasEdited": bool | None, # Present and True when the user edited the plan before approving
+ "awaitingLeaderApproval": bool | None, # Present and True when a teammate sent the plan to the team lead for approval
+ "requestId": str | None, # Optional ID of that approval request
}
###
@@ -3265,41 +3388,43 @@
"server": str | None # Optional server name to filter resources by
}
+The result is a list rather than a dict, so `tool_use_result` holds a `list` for this tool. **Output:**
+
+ [ # One entry per resource
+ {
+ "uri": str, # Resource URI
+ "name": str, # Resource name
+ "mimeType": str | None, # Optional MIME type
+ "description": str | None, # Optional description
+ "server": str, # Server that provides this resource
+ }
+ ]
+
+###
+
+
+
+ReadMcpResource
+
+**Tool name:** `ReadMcpResourceTool` **Input:**
+
+ {
+ "server": str, # The MCP server name
+ "uri": str, # The resource URI to read
+ }
+
**Output:**
{
- "resources": [
+ "contents": [
{
- "uri": str,
- "name": str,
- "description": str | None,
- "mimeType": str | None,
- "server": str,
+ "uri": str, # Resource URI
+ "mimeType": str | None, # Optional MIME type
+ "text": str | None, # Text content, or a note about the binary content
+ "blobSavedTo": str | None, # Present when Claude Code saved binary content to disk; path of the saved file
}
],
- "total": int,
- }
-
-###
-
-
-
-ReadMcpResource
-
-**Tool name:** `ReadMcpResourceTool` **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,
+ "error": str | None, # Present when the server couldn't read the resource
}
##
--- a/python.md
+++ b/python.md
@@ -1005,7 +1005,7 @@
`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
-`exclude_dynamic_sections`| No| Move per-session context such as working directory, the git-repo flag, and auto memory paths from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>)
+`exclude_dynamic_sections`| No| Move per-user context, such as the auto memory location, from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>)
`snapshot`| No| Set to `False` to rebuild the system prompt on every request instead of [reusing the prompt the session recorded on its first request](</docs/en/agent-sdk/modifying-system-prompts#change-the-prompt-of-an-existing-session>). Requires `claude-agent-sdk` v0.2.153 or later
###
--- a/python.md
+++ b/python.md
@@ -295,7 +295,7 @@
Property| Type| Description
---|---|---
`session_id`| `str`| Unique session identifier
-`summary`| `str`| Display title: custom title, auto-generated summary, or first prompt
+`summary`| `str`| Display title: custom title, most recent prompt, 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`| Session title: the user-set title, or the auto-generated title when none is set
@@ -3605,7 +3605,7 @@
asyncio.run(main())
-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 approval prompts, apart from the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). This combination effectively allows the model to escape sandbox isolation silently.
+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 `allowUnsandboxedCommands` is enabled, the model can autonomously execute commands outside the sandbox without approval prompts, apart from the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). This combination effectively allows the model to escape sandbox isolation silently.
##
--- a/python.md
+++ b/python.md
@@ -873,6 +873,7 @@
include_partial_messages: bool = False
include_hook_events: bool = False
forward_subagent_text: bool = False
+ verbatim_prompts: bool = False
fork_session: bool = False
resume_session_at: str | None = None
resume_drops_turn: str | None = None
@@ -925,6 +926,7 @@
`include_partial_messages`| `bool`| `False`| Include partial message streaming events. When enabled, `StreamEvent` messages are yielded
`include_hook_events`| `bool`| `False`| Include hook lifecycle events in the message stream as `HookEventMessage` objects
`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. Without this option, Claude Code emits subagent `tool_use` and `tool_result` blocks but not text or thinking. Requires Python Agent SDK 0.2.140 or later
+`verbatim_prompts`| `bool`| `False`| Deliver every prompt as written. The SDK sends each user message with `client_composed` set to `True`. See [`client_composed`](</docs/en/agent-sdk/typescript#sdkusermessage>) for what Claude Code skips on those messages. Use this option when your prompt text includes content the end user didn’t type. For per-turn control, leave it off and set `"client_composed": True` on individual streamed messages instead. While the option is on, the SDK overwrites any `client_composed` value you set. Requires Python Agent SDK 0.2.158 or later and Claude Code v2.1.248 or later; the CLI bundled with those SDK versions satisfies the Claude Code requirement
`fork_session`| `bool`| `False`| When resuming with `resume`, fork to a new session ID instead of continuing the original session
`resume_session_at`| `str | None`| `None`| When resuming, load the conversation only up to and including the message with this UUID. Use with `resume`, and usually `fork_session`, to branch from an earlier point. Requires Python Agent SDK 0.2.137 or later
`resume_drops_turn`| `str | None`| `None`| UUID of the user prompt whose turn a `resume_session_at` truncation discards. When set, the CLI refuses the resume if the discarded range holds entries not attributable to that turn. Requires Python Agent SDK 0.2.137 or later and Claude Code v2.1.223 or later; the CLI bundled with those SDK versions satisfies the Claude Code requirement
@@ -1205,7 +1207,7 @@
"plan", # Planning mode - explore without editing
"dontAsk", # Deny anything not pre-approved instead of prompting
"bypassPermissions", # Bypass permission checks; explicit ask rules still prompt (use with caution)
- "auto", # Model classifier approves or denies permission prompts
+ "auto", # A model classifier reviews actions such as shell commands and network requests
]
###
--- a/python.md
+++ b/python.md
@@ -914,14 +914,14 @@
`cli_path`| `str | Path | None`| `None`| Custom path to the Claude Code CLI executable
`settings`| `str | None`| `None`| Path to a settings file or an inline JSON string
`add_dirs`| `list[str | Path]`| `[]`| Additional directories Claude can access. The SDK passes each entry to Claude Code as `--add-dir`, so with the `project` setting source Claude Code also [loads the directory’s skills, commands, and subagents](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>)
-`env`| `dict[str, str]`| `{}`| Environment variables merged on top of the inherited process environment. See [Environment variables](</docs/en/env-vars>) for variables the underlying CLI reads, and Handle slow or stalled API responses for timeout-related variables
+`env`| `dict[str, str]`| `{}`| Environment variables merged on top of the inherited process environment. See [Environment variables](</docs/en/env-vars>) for variables the underlying CLI reads, and Handle slow or stalled API responses for timeout-related variables. Set `CLAUDE_AGENT_SDK_CLIENT_APP` to identify your app in the User-Agent header
`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
+`debug_stderr`| `Any`| `sys.stderr`| _Deprecated_ \- The SDK ignores this value. Use the `stderr` callback for CLI stderr output
`stderr`| `Callable[[str], None] | None`| `None`| Callback function for stderr output from CLI
`can_use_tool`| `CanUseTool` ` | None`| `None`| Tool permission callback, invoked only when the [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) falls through to a prompt. Not invoked for calls auto-approved by `allowed_tools`, allow rules, or `permission_mode`. An allow rule doesn’t pre-approve the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). See `CanUseTool` for details
`hooks`| `dict[HookEvent, list[HookMatcher]] | None`| `None`| Hook configurations for intercepting events
-`user`| `str | None`| `None`| User identifier
+`user`| `str | None`| `None`| On POSIX platforms, the OS user account the Claude Code subprocess runs as. Claude Code keeps the parent process’s environment, including `HOME`, and runs in `cwd`
`include_partial_messages`| `bool`| `False`| Include partial message streaming events. When enabled, `StreamEvent` messages are yielded
`include_hook_events`| `bool`| `False`| Include hook lifecycle events in the message stream as `HookEventMessage` objects
`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. Without this option, Claude Code emits subagent `tool_use` and `tool_result` blocks but not text or thinking. Requires Python Agent SDK 0.2.140 or later
@@ -1846,7 +1846,7 @@
Field| Type| Description
---|---|---
-`status`| `RateLimitStatus`| Current status. `"allowed_warning"` means approaching the limit; `"rejected"` means the limit was hit
+`status`| `RateLimitStatus`| Current status, one of `"allowed"`, `"allowed_warning"`, or `"rejected"`. `"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)
--- a/python.md
+++ b/python.md
@@ -1457,7 +1457,7 @@
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 Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
+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 Opus 5.5, Claude Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
###
@@ -1678,7 +1678,7 @@
`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
-`stop_reason`| `str | None`| Stop reason from the API (e.g. `end_turn`, `tool_use`)
+`stop_reason`| `str | None`| Stop reason from the API (for example, `end_turn`, `tool_use`)
`session_id`| `str | None`| ID of the session this message belongs to
`uuid`| `str | None`| Unique message identifier within the session transcript
@@ -3515,7 +3515,7 @@
`allowManagedDomainsOnly`| `bool`| `False`| Managed-settings only: when set in managed settings, ignore `allowedDomains` and `WebFetch(domain:...)` allow rules from non-managed settings sources. Has no effect when set via SDK options
`allowUnixSockets`| `list[str]`| `[]`| macOS only: Unix socket paths that processes can access, such as the Docker socket. Ignored on Linux
`allowAllUnixSockets`| `bool`| `False`| Allow access to all Unix sockets
-`allowLocalBinding`| `bool`| `False`| Allow processes to bind to local ports (e.g., for dev servers)
+`allowLocalBinding`| `bool`| `False`| Allow processes to bind to local ports (for example, for dev servers)
`allowMachLookup`| `list[str]`| `[]`| macOS only: XPC/Mach service names to allow. Supports a trailing wildcard
`httpProxyPort`| `int`| `None`| HTTP proxy port for network requests
`socksProxyPort`| `int`| `None`| SOCKS proxy port for network requests
--- a/python.md
+++ b/python.md
@@ -902,7 +902,7 @@
`resume`| `str | None`| `None`| Session ID to resume
`session_id`| `str | None`| `None`| Use a specific session ID instead of an auto-generated one. Must be a valid UUID. Can’t be combined with `continue_conversation` or `resume` unless `fork_session` is also set
`max_turns`| `int | None`| `None`| Maximum agentic turns (tool-use round trips)
-`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`. For accuracy caveats and reset behavior, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>)
+`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. Counts only the call’s own spend; totals restored from a resumed session don’t count. For accuracy caveats and reset behavior, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>)
`disallowed_tools`| `list[str]`| `[]`| Tools to deny. A bare name such as `"Bash"` removes the tool from Claude’s context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`, for the command [as written](</docs/en/permissions#bash-rule-limits>). See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
`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 alias or full model name. See [accepted values and provider-specific IDs](</docs/en/model-config#available-models>)
@@ -1762,7 +1762,7 @@
`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. It covers every model call made through the query pipeline: the main loop, subagents, and internal calls such as compaction and Workflow agents. Helper calls outside that pipeline, such as the permission classifier and token-counting requests, are excluded from `model_usage`. Treat `model_usage` as an estimate, not a billing statement. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), `model_usage` and `total_cost_usd` are cumulative across turns, so read the latest result rather than summing across results. See [Track costs in streaming input mode](</docs/en/agent-sdk/cost-tracking#track-costs-in-streaming-input-mode>) for resets and [Recover totals after a session crash](</docs/en/agent-sdk/cost-tracking#recover-totals-after-a-session-crash>) for zeroed results. Each value in `model_usage` is a `ModelUsage` TypedDict, imported via `from claude_agent_sdk.types import ModelUsage`. Its keys use camelCase because the SDK passes the value through unmodified from the underlying CLI process, matching the TypeScript [`ModelUsage`](</docs/en/agent-sdk/typescript#modelusage>) type:
+The `model_usage` dict maps model names to per-model usage. It covers every model call made through the query pipeline: the main loop, subagents, and internal calls such as compaction and Workflow agents. Helper calls outside that pipeline, such as the permission classifier and token-counting requests, are excluded from `model_usage`. Treat `model_usage` as an estimate, not a billing statement. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), `model_usage` and `total_cost_usd` are cumulative across turns, so read the latest result rather than summing across results. A call that resumes a session also counts the [totals restored from the session’s earlier calls](</docs/en/agent-sdk/cost-tracking#accumulate-costs-across-multiple-calls>). See [Track costs in streaming input mode](</docs/en/agent-sdk/cost-tracking#track-costs-in-streaming-input-mode>) for resets and [Recover totals after a session crash](</docs/en/agent-sdk/cost-tracking#recover-totals-after-a-session-crash>) for zeroed results. Each value in `model_usage` is a `ModelUsage` TypedDict, imported via `from claude_agent_sdk.types import ModelUsage`. Its keys use camelCase because the SDK passes the value through unmodified from the underlying CLI process, matching the TypeScript [`ModelUsage`](</docs/en/agent-sdk/typescript#modelusage>) type:
Key| Type| Description
---|---|---
@@ -2843,16 +2843,15 @@
"command": str | None, # Shell script; each stdout line is an event, exit ends the watch
"ws": dict | None, # WebSocket source: {"url": str, "protocols": list[str] | None}; each text frame is an event
"description": str, # Short description shown in notifications
- "timeout_ms": int | None, # Kill after this deadline (default 300000, max 3600000)
- "persistent": bool | None, # Run for the lifetime of the session; stop with TaskStop
+ "timeout_ms": int | None, # Deadline in milliseconds (default 300000, max 3600000; the effective deadline is at most 1800000)
}
**Output:**
{
"taskId": str, # ID of the background monitor task
- "timeoutMs": int, # Timeout deadline in milliseconds (0 when persistent)
- "persistent": bool | None, # True when running until TaskStop or session end
+ "timeoutMs": int, # The watch's effective deadline in milliseconds
+ "persistent": bool | None, # False: every watch has a deadline
}
###
@@ -3209,24 +3208,7 @@
TaskOutput
-**Tool name:** `TaskOutput`. The previous name `BashOutput` is still accepted as an alias.
-
-`TaskOutput` is deprecated; prefer `Read` on the task’s output file path. The schemas below remain valid for hooks and permission handlers that encounter the tool.
-
-**Input:**
-
- {
- "task_id": str, # The task ID to get output from
- "block": bool, # Whether to wait for completion (default True)
- "timeout": int, # Max wait time in ms (default 30000)
- }
-
-**Output:**
-
- {
- "retrieval_status": "success" | "timeout" | "not_ready", # Whether the output was retrieved
- "task": dict | None, # Task details: task_id, task_type, status, description, output, plus type-specific fields such as exitCode
- }
+Removed in Claude Code v2.1.277. Previously retrieved output from a running or completed background task, with `BashOutput` accepted as an alias; Claude reads a background task’s output file with `Read` instead. A `disallowed_tools` entry or a deny rule that still names either name is ignored without a warning.
###
@@ -3466,7 +3448,7 @@
---|---|---|---
`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
+`excludedCommands`| `list[str]`| `[]`| Commands that bypass sandbox restrictions, such as `["docker *"]`. These run unsandboxed automatically without model involvement; [`sandbox.excludedCommands`](</docs/en/settings-reference#sandbox-excludedcommands>) covers when an entry applies
`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
@@ -3563,7 +3545,7 @@
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. Commands listed in `excludedCommands` instead bypass the sandbox automatically, with no model involvement; see `SandboxSettings`. The following example logs each unsandboxed request and denies it unless your own authorization logic allows it:
+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 is invoked, allowing you to implement custom authorization logic. Your `excludedCommands` entries instead take a call out of the sandbox with no model involvement; [`sandbox.excludedCommands`](</docs/en/settings-reference#sandbox-excludedcommands>) covers when an entry applies. The following example logs each unsandboxed request and denies it unless your own authorization logic allows it:
import asyncio
from claude_agent_sdk import (
--- a/python.md
+++ b/python.md
@@ -843,7 +843,7 @@
class ClaudeAgentOptions:
tools: list[str] | ToolsPreset | None = None
allowed_tools: list[str] = field(default_factory=list)
- system_prompt: str | SystemPromptPreset | SystemPromptFile | None = None
+ system_prompt: str | SystemPromptPreset | SystemPromptCustom | SystemPromptFile | None = None
mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
strict_mcp_config: bool = False
permission_mode: PermissionMode | None = None
@@ -894,7 +894,7 @@
---|---|---|---
`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. If you name one of the [task-tracking tools](</docs/en/agent-sdk/todo-tracking#model-availability>) here, Claude Code also opts the session in. Other 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 | SystemPromptFile | None`| `None`| System prompt configuration. Pass a string for a custom prompt, `{"type": "preset", "preset": "claude_code"}` for Claude Code’s system prompt with optional `"append"`, or `{"type": "file", "path": "..."}` to load a large prompt from disk. See `SystemPromptPreset` and `SystemPromptFile`
+`system_prompt`| `str | SystemPromptPreset | SystemPromptCustom | SystemPromptFile | None`| `None`| System prompt configuration. Pass a string for a custom prompt, `{"type": "preset", "preset": "claude_code"}` for Claude Code’s system prompt with optional `"append"`, `{"type": "custom", "prompt": "..."}` for a custom prompt that can also set `"snapshot"`, or `{"type": "file", "path": "..."}` to load a large prompt from disk. See `SystemPromptPreset`, `SystemPromptCustom`, and `SystemPromptFile`
`mcp_servers`| `dict[str, McpServerConfig] | str | Path`| `{}`| MCP server configurations or path to config file
`strict_mcp_config`| `bool`| `False`| When `True`, use only the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, plugin-provided MCP servers, and [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>). Maps to the CLI `--strict-mcp-config` flag
`permission_mode`| `PermissionMode | None`| `None`| Permission mode for tool usage
@@ -996,6 +996,7 @@
preset: Literal["claude_code"]
append: NotRequired[str]
exclude_dynamic_sections: NotRequired[bool]
+ snapshot: NotRequired[bool]
Field| Required| Description
---|---|---
@@ -1003,6 +1004,26 @@
`preset`| Yes| Must be `"claude_code"` to use Claude Code’s system prompt
`append`| No| Additional instructions to append to the preset system prompt
`exclude_dynamic_sections`| No| Move per-session context such as working directory, the git-repo flag, and auto memory paths from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>)
+`snapshot`| No| Set to `False` to rebuild the system prompt on every request instead of [reusing the prompt the session recorded on its first request](</docs/en/agent-sdk/modifying-system-prompts#change-the-prompt-of-an-existing-session>). Requires `claude-agent-sdk` v0.2.153 or later
+
+###
+
+
+
+`SystemPromptCustom`
+
+A custom system prompt in object form, equivalent to passing a string as `system_prompt`, that can also set `snapshot`. Requires `claude-agent-sdk` v0.2.153 or later.
+
+ class SystemPromptCustom(TypedDict):
+ type: Literal["custom"]
+ prompt: str
+ snapshot: NotRequired[bool]
+
+Field| Required| Description
+---|---|---
+`type`| Yes| Must be `"custom"`
+`prompt`| Yes| The system prompt text. Passed to the CLI as a command-line argument, so the command-line length limits apply
+`snapshot`| No| Same as `SystemPromptPreset.snapshot`, applied to `prompt`
###
--- a/python.md
+++ b/python.md
@@ -122,7 +122,7 @@
---|---|---
`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)
+`input_schema`| `type | dict[str, Any]`| Schema defining the tool’s input parameters. See Input schema options
`annotations`| `ToolAnnotations`` | None`| Optional MCP tool annotations providing behavioral hints to clients
####
@@ -551,7 +551,7 @@
`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
+`set_model(model)`| Change the model for the current session. Pass `None` to reset to [Claude Code’s default model](</docs/en/model-config>)
`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
@@ -902,17 +902,17 @@
`resume`| `str | None`| `None`| Session ID to resume
`session_id`| `str | None`| `None`| Use a specific session ID instead of an auto-generated one. Must be a valid UUID. Can’t be combined with `continue_conversation` or `resume` unless `fork_session` is also set
`max_turns`| `int | None`| `None`| Maximum agentic turns (tool-use round trips)
-`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for accuracy caveats
+`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`. For accuracy caveats and reset behavior, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>)
`disallowed_tools`| `list[str]`| `[]`| Tools to deny. A bare name such as `"Bash"` removes the tool from Claude’s context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`, for the command [as written](</docs/en/permissions#bash-rule-limits>). See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
`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 alias or full model name. See [accepted values and provider-specific IDs](</docs/en/model-config#available-models>)
-`fallback_model`| `str | None`| `None`| Fallback model to use if the primary model fails
+`fallback_model`| `str | None`| `None`| Fallback model to use if the primary model fails. Accepts a comma-separated list. For guidance, see [Choose a model](</docs/en/agent-sdk/configuration#choose-a-model>)
`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
+`settings`| `str | None`| `None`| Path to a settings file or an inline JSON string
`add_dirs`| `list[str | Path]`| `[]`| Additional directories Claude can access. The SDK passes each entry to Claude Code as `--add-dir`, so with the `project` setting source Claude Code also [loads the directory’s skills, commands, and subagents](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>)
`env`| `dict[str, str]`| `{}`| Environment variables merged on top of the inherited process environment. See [Environment variables](</docs/en/env-vars>) for variables the underlying CLI reads, and Handle slow or stalled API responses for timeout-related variables
`extra_args`| `dict[str, str | None]`| `{}`| Additional CLI arguments to pass directly to the CLI
@@ -931,7 +931,7 @@
`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` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Endpoint-managed policy loads regardless; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
+`setting_sources`| `list[SettingSource] | None`| `None` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. With `skills` set and this field unset, only user and project sources load. Set `setting_sources` explicitly to keep local settings. Endpoint-managed policy loads regardless; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). For inputs read regardless of this option, see [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. Pass exact names only. The SDK rejects malformed and wildcard-form names with a `ValueError` before starting the Claude Code process; this check requires Python Agent SDK 0.2.129 or later. When set, the SDK adds the Skill tool to `allowed_tools` automatically. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
`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`
@@ -1043,7 +1043,7 @@
Default behavior
-When `setting_sources` is omitted or `None`, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. Endpoint-managed policy is loaded in all cases; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read regardless of this option, and how to disable them.
+When `setting_sources` is omitted or `None` and `skills` is not set, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. With `skills` set, the `setting_sources` row describes the current default. Endpoint-managed policy is loaded in all cases; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). For more information, see [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>).
####
@@ -1126,7 +1126,7 @@
2. Project settings (`.claude/settings.json`)
3. User settings (`~/.claude/settings.json`)
-Programmatic options such as `agents` and `allowed_tools` override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options.
+Programmatic options such as `agents`, `allowed_tools`, and `settings` override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options.
###
@@ -2581,7 +2581,7 @@
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.
+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.
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext
@@ -2722,14 +2722,14 @@
{
"status": "remote_launched",
- "taskId": str, # ID of the remote task
- "sessionUrl": str, # Link to the remote cloud session
+ "taskId": str, # ID of the dispatched task
+ "sessionUrl": str, # Link to the cloud session
"description": str, # The task description
"prompt": str, # The prompt the agent runs
"outputFile": str, # File path where the agent's output is written
}
-Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it. If Claude Code [kept the subagent’s isolated worktree](</docs/en/worktrees#isolate-subagents-with-worktrees>), `worktreePath` on the `completed` variant is where to find it, and `worktreeBranch` is its branch when Claude Code created the worktree with git. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On the `async_launched` variant, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The `modelsUsed` field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later. Claude Code fills `usage` and `totalTokens` from the subagent’s final API request, not from the whole run. When present, `thinking_tokens` under `output_tokens_details` in `usage` is the number of that request’s output tokens that were thinking tokens. The `output_tokens_details` key requires Python SDK v0.2.136 or later, which bundles Claude Code v2.1.228.
+Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a cloud session, where `sessionUrl` links to that session and `taskId` identifies it. If Claude Code [kept the subagent’s isolated worktree](</docs/en/worktrees#isolate-subagents-with-worktrees>), `worktreePath` on the `completed` variant is where to find it, and `worktreeBranch` is its branch when Claude Code created the worktree with git. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On the `async_launched` variant, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The `modelsUsed` field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later. Claude Code fills `usage` and `totalTokens` from the subagent’s final API request, not from the whole run. When present, `thinking_tokens` under `output_tokens_details` in `usage` is the number of that request’s output tokens that were thinking tokens. The `output_tokens_details` key requires Python SDK v0.2.136 or later, which bundles Claude Code v2.1.228.
###
--- a/python.md
+++ b/python.md
@@ -298,7 +298,7 @@
`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
+`custom_title`| `str | None`| Session title: the user-set title, or the auto-generated title when none is set
`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
@@ -526,7 +526,7 @@
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_permission_mode(self, mode: PermissionMode) -> 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
@@ -557,7 +557,7 @@
`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
+`get_server_info()`| Get the server’s initialization info, including available commands and output styles
`disconnect()`| Disconnect from Claude
####
@@ -1967,7 +1967,14 @@
Union type of all content blocks.
- ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
+ ContentBlock = (
+ TextBlock
+ | ThinkingBlock
+ | ToolUseBlock
+ | ToolResultBlock
+ | ServerToolUseBlock
+ | ServerToolResultBlock
+ )
###
@@ -3503,7 +3510,7 @@
`allowedDomains`| `list[str]`| `[]`| Domain names that sandboxed processes can access
`deniedDomains`| `list[str]`| `[]`| Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains`
`allowManagedDomainsOnly`| `bool`| `False`| Managed-settings only: when set in managed settings, ignore `allowedDomains` and `WebFetch(domain:...)` allow rules from non-managed settings sources. Has no effect when set via SDK options
-`allowUnixSockets`| `list[str]`| `[]`| Unix socket paths that processes can access (e.g., Docker socket)
+`allowUnixSockets`| `list[str]`| `[]`| macOS only: Unix socket paths that processes can access, such as the Docker socket. Ignored on Linux
`allowAllUnixSockets`| `bool`| `False`| Allow access to all Unix sockets
`allowLocalBinding`| `bool`| `False`| Allow processes to bind to local ports (e.g., for dev servers)
`allowMachLookup`| `list[str]`| `[]`| macOS only: XPC/Mach service names to allow. Supports a trailing wildcard
--- a/python.md
+++ b/python.md
@@ -3046,7 +3046,7 @@
**Tool name:** `TodoWrite`
-On Python Agent SDK 0.2.139 and later, the following restriction applies.The following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
+The following tools are available by default only on Claude 3.x models, Opus 4 through 4.7, Sonnet 4 through 4.6, and Haiku 4.5. On every other model, including model IDs Claude Code doesn’t recognize, they aren’t available unless you opt in:
* `TodoWrite`
* `TaskCreate`
@@ -3054,7 +3054,7 @@
* `TaskUpdate`
* `TaskList`
-On other models, Claude Code provides the Task tools by default and `TodoWrite` only when you set `CLAUDE_CODE_ENABLE_TASKS=0`.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in.
+Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`.This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in.
**Input:**
--- a/python.md
+++ b/python.md
@@ -903,7 +903,7 @@
`session_id`| `str | None`| `None`| Use a specific session ID instead of an auto-generated one. Must be a valid UUID. Can’t be combined with `continue_conversation` or `resume` unless `fork_session` is also set
`max_turns`| `int | None`| `None`| Maximum agentic turns (tool-use round trips)
`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for accuracy caveats
-`disallowed_tools`| `list[str]`| `[]`| Tools to deny. A bare name such as `"Bash"` removes the tool from Claude’s context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`. See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
+`disallowed_tools`| `list[str]`| `[]`| Tools to deny. A bare name such as `"Bash"` removes the tool from Claude’s context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`, for the command [as written](</docs/en/permissions#bash-rule-limits>). See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
`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 alias or full model name. See [accepted values and provider-specific IDs](</docs/en/model-config#available-models>)
`fallback_model`| `str | None`| `None`| Fallback model to use if the primary model fails
@@ -924,7 +924,7 @@
`user`| `str | None`| `None`| User identifier
`include_partial_messages`| `bool`| `False`| Include partial message streaming events. When enabled, `StreamEvent` messages are yielded
`include_hook_events`| `bool`| `False`| Include hook lifecycle events in the message stream as `HookEventMessage` objects
-`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. By default only subagent `tool_use` and `tool_result` blocks are emitted. Requires Python Agent SDK 0.2.140 or later
+`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. Without this option, Claude Code emits subagent `tool_use` and `tool_result` blocks but not text or thinking. Requires Python Agent SDK 0.2.140 or later
`fork_session`| `bool`| `False`| When resuming with `resume`, fork to a new session ID instead of continuing the original session
`resume_session_at`| `str | None`| `None`| When resuming, load the conversation only up to and including the message with this UUID. Use with `resume`, and usually `fork_session`, to branch from an earlier point. Requires Python Agent SDK 0.2.137 or later
`resume_drops_turn`| `str | None`| `None`| UUID of the user prompt whose turn a `resume_session_at` truncation discards. When set, the CLI refuses the resume if the discarded range holds entries not attributable to that turn. Requires Python Agent SDK 0.2.137 or later and Claude Code v2.1.223 or later; the CLI bundled with those SDK versions satisfies the Claude Code requirement
@@ -1166,7 +1166,7 @@
`maxTurns`| No| Maximum number of agentic turns before the agent stops
`background`| No| Run this agent as a non-blocking background task when invoked
`effort`| No| Reasoning effort level for this agent. Accepts a named level or an integer. See `EffortLevel`
-`permissionMode`| No| Permission mode for tool execution within this agent. See `PermissionMode`
+`permissionMode`| No| Permission mode for tool execution within this agent. The [subagent inheritance rules](</docs/en/agent-sdk/permissions#available-modes>) decide when it applies. See `PermissionMode`
`AgentDefinition` field names use camelCase, such as `disallowedTools`, `permissionMode`, and `maxTurns`. These names map directly to the wire format shared with the TypeScript SDK. This differs from `ClaudeAgentOptions`, which uses Python snake_case for the equivalent top-level fields such as `disallowed_tools` and `permission_mode`. Because `AgentDefinition` is a dataclass, passing a snake_case keyword raises a `TypeError` at construction time.
@@ -2647,7 +2647,7 @@
"run_in_background": bool | None, # Agents run in the background by default; set to False to run synchronously
"name": str | None, # Name for the spawned agent
"team_name": str | None, # Deprecated; ignored
- "mode": "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan" | None, # Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it
+ "mode": "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan" | None, # Deprecated; ignored. The subagent inheritance rules decide a subagent's permission mode
"isolation": "worktree" | "remote" | None, # Isolation mode for the agent's changes
}
--- a/python.md
+++ b/python.md
@@ -1729,7 +1729,7 @@
* `api_error_status`: the HTTP status code of the terminating API error. `None` when the turn ended without one. Populated only on `subtype="success"`.
* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.
* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.
- * `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are `interrupt()` and a permission callback returning `PermissionResultDeny` with `interrupt=True`. `None` on CLI versions that predate the field, on results that bypassed the query loop such as local slash commands, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK’s [`SDKResultMessage.terminal_reason`](</docs/en/agent-sdk/typescript#sdkresultmessage>), which lists the full set of values.
+ * `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are `interrupt()` and a permission callback returning `PermissionResultDeny` with `interrupt=True`. `None` on CLI versions that predate the field, on results from local commands such as `/voice` or `/usage`, which bypass the query loop, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK’s [`SDKResultMessage.terminal_reason`](</docs/en/agent-sdk/typescript#sdkresultmessage>), which lists the full set of values.
* `origin`: origin of the user message that triggered this turn. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), check this to tell the result of your own prompt, where `origin` is `None` or `{"kind": "human"}`, from the result of an injected turn such as a background-task notification. Requires Python Agent SDK 0.2.137 or later.
The `usage` dict covers the main agent loop only and excludes subagent and other nested or auxiliary model calls. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), the values are per-turn. Prefer `model_usage` for token and cost accounting. The `usage` dict contains the following keys when present:
--- a/python.md
+++ b/python.md
@@ -961,8 +961,8 @@
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set [`CLAUDE_CODE_RETRY_WATCHDOG=1`](</docs/en/errors#tune-retry-behavior>): it retries transient capacity errors indefinitely and, on Claude Code v2.1.199 or later, raises the default for other transient errors to `300` and removes the cap on this variable.
- * `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
- * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed.
+ * `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents. While the stream watchdog is on, the default is `CLAUDE_STREAM_IDLE_TIMEOUT_MS` plus 5 minutes, which comes to `600000` unless you raise that variable. With the stream watchdog off, the default is `600000`. Before v2.1.257, the default was always `600000`. The timer resets on each stream event. On a stall, Claude Code aborts the subagent and reports the stall to the parent. For a background subagent, it also marks the task failed and attaches any partial result.
+ * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: stream watchdog that aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed. While the watchdog waits out a response that a gateway behind `ANTHROPIC_BASE_URL` holds open with keep-alive pings, a host that sets `include_partial_messages` keeps receiving `ping` `StreamEvent` messages. Read those frames as liveness rather than timing the session out on silence. Before v2.1.257, the frames stopped 5 minutes after the last real stream event.
###
@@ -1626,6 +1626,8 @@
`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
`origin`| `MessageOrigin | None`| Provenance of this message, populated on injected turns such as task notifications and peer messages. `None` when the CLI didn’t attribute it. Requires Python Agent SDK 0.2.137 or later
+
+The SDK passes `tool_use_result` through from the CLI unmodified. For a tool on an external MCP server whose result contains `resource_link` blocks, the dict has a `resourceLinks` key holding a list of dicts with the keys of the TypeScript [`SDKMcpResourceLink`](</docs/en/agent-sdk/typescript#sdkmcpresourcelink>) type. Claude receives each link as a line of text in the tool result. To render the files the server returned, read `resourceLinks` instead of parsing that text. The `resourceLinks` key requires Python Agent SDK 0.2.150 or later and Claude Code v2.1.257 or later; the CLI bundled with that SDK version satisfies the Claude Code requirement. The CLI omits the key when the result has no links and on results from subagents. The CLI keeps at most 50 links per result and stops adding links once the list reaches 64 KiB of serialized JSON. A tool you define in-process with `tool()` never produces the key, because the SDK flattens its `resource_link` blocks to text before the CLI sees the result.
###
@@ -1748,6 +1750,7 @@
`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.
+`thinkingTokens`| `int`| Thinking tokens generated by this model, already counted in `outputTokens`. Absent until a turn runs on a Claude Code version that records it, and not declared on the TypedDict, so read it with `.get()`. Requires Python Agent SDK 0.2.150 or later, whose bundled CLI records it.
`costUSD`| `float`| Estimated cost in USD for this model, computed client-side. See [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for billing caveats.
`contextWindow`| `int`| Context window size for this model.
`maxOutputTokens`| `int`| Maximum output token limit for this model.
@@ -1947,6 +1950,8 @@
`session_id`| `str`| Session identifier
`tool_use_id`| `str | None`| Associated tool use ID
`usage`| `TaskUsage | None`| Final token usage for the task
+
+When the CLI [moves a long MCP tool call to the background](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), the tool result for that call holds only a placeholder and the call’s real result arrives in this message. On a `"completed"` notification for such a call, the CLI adds a `resource_links` key listing the files the tool returned by reference, with the same entries and limits as the `resourceLinks` key on `UserMessage.tool_use_result`. The `resource_links` key requires Python Agent SDK 0.2.150 or later and Claude Code v2.1.257 or later; the CLI bundled with that SDK version satisfies the Claude Code requirement. The dataclass has no field for `resource_links`. Read it from the `data` dict the message inherits from `SystemMessage`: `message.data.get("resource_links")`. Match the notification to the call with `tool_use_id`. The CLI omits the key when the result had no links and on notifications for tasks that aren’t MCP tool calls.
##
--- a/python.md
+++ b/python.md
@@ -1158,7 +1158,7 @@
`prompt`| Yes| The agent’s system prompt
`tools`| No| Array of allowed tool names. If omitted, inherits every [tool available to subagents](</docs/en/sub-agents#available-tools>)
`disallowedTools`| No| Array of tool names to remove from the agent’s tool set. MCP server-level patterns are also accepted: `mcp__server` or `mcp__server__*` removes every tool from that server, and `mcp__*` removes every MCP tool from any server
-`model`| No| Model override for this agent. Accepts an alias such as `"sonnet"`, `"opus"`, `"haiku"`, or `"inherit"`, or a full model ID. If omitted, uses the main model
+`model`| No| Model override for this agent. Accepts an alias such as `"sonnet"`, `"opus"`, `"haiku"`, or `"inherit"`, or a full model ID. When you omit it, Claude Code picks the model in the [subagent model order](</docs/en/sub-agents#choose-a-model>)
`skills`| No| List of skill names to preload into the agent’s context at startup. Unlisted skills remain invocable through the Skill tool
`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
--- a/python.md
+++ b/python.md
@@ -173,7 +173,7 @@
`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.
+Behavioral hints for a tool, passed as the `annotations` argument of `tool()`. `ToolAnnotations` extends the MCP SDK’s `mcp.types.ToolAnnotations` with a `maxResultSizeChars` field, and you can write each hint in camelCase or snake_case: `ToolAnnotations(readOnlyHint=True)` and `ToolAnnotations(read_only_hint=True)` are equivalent. You can also pass a plain `mcp.types.ToolAnnotations` wherever the SDK accepts annotations. The snake_case names and the typed `maxResultSizeChars` field require Python Agent SDK 0.2.140 or later. Versions 0.1.31 through 0.2.139 re-export `mcp.types.ToolAnnotations` unchanged. On versions 0.1.55 through 0.2.139 you can still pass `maxResultSizeChars` as a keyword argument: the MCP class accepts extra fields, and the SDK forwards the value to Claude Code. All fields are optional. Clients shouldn’t rely on the hints for security decisions.
Field| Type| Default| Description
---|---|---|---
@@ -182,6 +182,7 @@
`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)
+`maxResultSizeChars`| `int | None`| `None`| Number of characters up to which Claude Code keeps this tool’s text result inline in the conversation instead of saving it to a file, up to 500,000. Results that contain images aren’t affected. A Claude Code setting rather than an MCP hint: the SDK sends it in the tool’s `_meta` as `anthropic/maxResultSizeChars`. See [Raise the limit for a specific tool](</docs/en/mcp#raise-the-limit-for-a-specific-tool>)
from claude_agent_sdk import tool, ToolAnnotations
from typing import Any
@@ -784,7 +785,7 @@
`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`
+`annotations`| `ToolAnnotations`` | None`| Optional tool annotations (for example `readOnlyHint`, `destructiveHint`, `openWorldHint`, `maxResultSizeChars`)
###
@@ -3471,7 +3472,7 @@
asyncio.run(main())
-**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.
+**Unix socket security** : The `allowUnixSockets` option can grant access to system services that reach outside the sandbox. 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.
###
Show diff (302 lines)
--- a/python.md
+++ b/python.md
@@ -2022,6 +2022,8 @@
Error Types
+The types below define what your code catches. For entries keyed to the error messages these types raise, with the cause and fix for each, see [Troubleshooting](</docs/en/agent-sdk/troubleshooting>).
+
###
@@ -2163,11 +2165,7 @@
* `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`: warning message shown to the user
- * `hookSpecificOutput`: Hook-specific output data
+Returns a `HookJSONOutput`.
###
@@ -3042,7 +3040,7 @@
**Tool name:** `TodoWrite`
-On Python Agent SDK 0.2.139 and later, the following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
+On Python Agent SDK 0.2.139 and later, the following restriction applies.The following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
* `TodoWrite`
* `TaskCreate`
@@ -3290,13 +3288,9 @@
-Advanced Features with ClaudeSDKClient
-
-###
-
-
-
-Building a Continuous Conversation Interface
+Build a continuous conversation interface
+
+The following example keeps one `ClaudeSDKClient` connected across turns, so Claude remembers earlier messages. Type `new` to disconnect and reconnect for a fresh session, or `exit` to end the conversation.
from claude_agent_sdk import (
ClaudeSDKClient,
@@ -3370,166 +3364,13 @@
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",
- )
-
- 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
-This example catches `ResultError`, which requires Python Agent SDK 0.2.140 or later.
+The following example wraps a `query()` call in handlers for four of the error types the SDK raises. This example catches `ResultError`, which requires Python Agent SDK 0.2.140 or later.
import asyncio
@@ -3564,76 +3405,6 @@
asyncio.run(main())
-###
-
-
-
-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())
-
##
@@ -3826,5 +3597,6 @@
* [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts
* [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) \- TypeScript SDK documentation
+ * [Custom tools](</docs/en/agent-sdk/custom-tools>) \- Define in-process MCP tools for Claude to call
* [CLI reference](</docs/en/cli-reference>) \- Command-line interface
* [Common workflows](</docs/en/common-workflows>) \- Step-by-step guides
--- a/python.md
+++ b/python.md
@@ -2033,7 +2033,7 @@
class ClaudeSDKError(Exception):
"""Base error for Claude SDK."""
-When a single-shot `query()` ends with an error result, for example a turn-limit error, the SDK raises a plain `Exception` after yielding the final result message, not a `ClaudeSDKError` subclass.
+When a single-shot `query()` ends with an error result, for example a turn-limit error, the SDK raises a `ResultError` after yielding the final result message. Python Agent SDK versions before 0.2.140 raised a plain `Exception` that wasn’t a `ClaudeSDKError` subclass.
###
@@ -2078,6 +2078,25 @@
):
self.exit_code = exit_code
self.stderr = stderr
+
+###
+
+
+
+`ResultError`
+
+Raised after the final `ResultMessage` when the Claude Code process exits because the run ended with an error result, such as a turn-limit error or an API error. `ResultError` subclasses `ProcessError`, so an existing `except ProcessError` handler also catches it. Its attributes carry the fields of that result message, so you can branch on why the run failed without parsing the message text. Requires Python Agent SDK 0.2.140 or later.
+
+ class ResultError(ProcessError):
+ subtype: str | None # "error_max_turns", "error_during_execution", ...; "success" when the run ended on a failed request
+ errors: list[str] # an empty list when the result message reported none
+ result: str | None
+ api_error_status: int | None
+ terminal_reason: str | None # "max_turns", "api_error", ...; check this before subtype
+ session_id: str | None
+ data: dict[str, Any] # the raw result message payload
+
+To tell failures apart, check `terminal_reason` before `subtype`. When the final request fails, such as on an API error, Claude Code reports `subtype` `"success"` with the cause in `terminal_reason`, for example `"api_error"`; when a limit you set ends the run, such as `max_turns` or `max_budget_usd`, it reports an `error_*` subtype.
###
@@ -3510,9 +3529,17 @@
Error handling
+This example catches `ResultError`, which requires Python Agent SDK 0.2.140 or later.
+
import asyncio
- from claude_agent_sdk import query, CLINotFoundError, ProcessError, CLIJSONDecodeError
+ from claude_agent_sdk import (
+ query,
+ CLINotFoundError,
+ ProcessError,
+ ResultError,
+ CLIJSONDecodeError,
+ )
async def main():
try:
@@ -3522,13 +3549,18 @@
print(
"Claude Code CLI not found. Try reinstalling: pip install --force-reinstall claude-agent-sdk"
)
+ # Catch ResultError before ProcessError, which it subclasses. Its message
+ # carries the error text. A failed final request, such as an API error,
+ # arrives with subtype "success", so branch on terminal_reason first.
+ except ResultError as e:
+ if e.terminal_reason == "api_error":
+ print(f"API request failed: {e}")
+ else:
+ print(f"Query ended with an error result ({e.terminal_reason or e.subtype}): {e}")
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}")
- # A single-shot query() raises a plain Exception after yielding an error result
- except Exception as e:
- print(f"Query ended with an error result: {e}")
asyncio.run(main())
--- a/python.md
+++ b/python.md
@@ -358,7 +358,7 @@
`session_id`| `str`| Session identifier
`message`| `Any`| Raw message content
`parent_tool_use_id`| `str | None`| For subagent messages, the id of the spawning `Agent` tool-use block. `None` for main-session messages and older sessions
-`parent_agent_id`| `str | None`| For messages from a [nested subagent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), the agent id of the parent subagent. `None` for main-session messages, top-level subagent messages, and older sessions
+`parent_agent_id`| `str | None`| For messages from a [nested subagent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), the agent id of the parent subagent. `None` for main-session messages, top-level subagent messages, and older sessions. Requires Python Agent SDK 0.2.140 or later
####
@@ -923,15 +923,15 @@
`user`| `str | None`| `None`| User identifier
`include_partial_messages`| `bool`| `False`| Include partial message streaming events. When enabled, `StreamEvent` messages are yielded
`include_hook_events`| `bool`| `False`| Include hook lifecycle events in the message stream as `HookEventMessage` objects
-`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. By default only subagent `tool_use` and `tool_result` blocks are emitted
+`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. By default only subagent `tool_use` and `tool_result` blocks are emitted. Requires Python Agent SDK 0.2.140 or later
`fork_session`| `bool`| `False`| When resuming with `resume`, fork to a new session ID instead of continuing the original session
-`resume_session_at`| `str | None`| `None`| When resuming, load the conversation only up to and including the message with this UUID. Use with `resume`, and usually `fork_session`, to branch from an earlier point
-`resume_drops_turn`| `str | None`| `None`| UUID of the user prompt whose turn a `resume_session_at` truncation discards. When set, the CLI refuses the resume if the discarded range holds entries not attributable to that turn. Requires Claude Code v2.1.223 or later; the bundled CLI satisfies this
+`resume_session_at`| `str | None`| `None`| When resuming, load the conversation only up to and including the message with this UUID. Use with `resume`, and usually `fork_session`, to branch from an earlier point. Requires Python Agent SDK 0.2.137 or later
+`resume_drops_turn`| `str | None`| `None`| UUID of the user prompt whose turn a `resume_session_at` truncation discards. When set, the CLI refuses the resume if the discarded range holds entries not attributable to that turn. Requires Python Agent SDK 0.2.137 or later and Claude Code v2.1.223 or later; the CLI bundled with those SDK versions satisfies the Claude Code requirement
`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` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Endpoint-managed policy loads regardless; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
-`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. Pass exact names only. The SDK rejects malformed and wildcard-form names with a `ValueError` before starting the Claude Code process. When set, the SDK adds the Skill tool to `allowed_tools` automatically. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
+`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. Pass exact names only. The SDK rejects malformed and wildcard-form names with a `ValueError` before starting the Claude Code process; this check requires Python Agent SDK 0.2.129 or later. When set, the SDK adds the Skill tool to `allowed_tools` automatically. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
`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`| `EffortLevel` ` | None`| `None`| Effort level for thinking depth. See [adjust the effort level](</docs/en/model-config#adjust-effort-level>)
@@ -1624,7 +1624,7 @@
`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
-`origin`| `MessageOrigin | None`| Provenance of this message, populated on injected turns such as task notifications and peer messages. `None` when the CLI didn’t attribute it
+`origin`| `MessageOrigin | None`| Provenance of this message, populated on injected turns such as task notifications and peer messages. `None` when the CLI didn’t attribute it. Requires Python Agent SDK 0.2.137 or later
###
@@ -1727,7 +1727,7 @@
* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.
* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.
* `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are `interrupt()` and a permission callback returning `PermissionResultDeny` with `interrupt=True`. `None` on CLI versions that predate the field, on results that bypassed the query loop such as local slash commands, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK’s [`SDKResultMessage.terminal_reason`](</docs/en/agent-sdk/typescript#sdkresultmessage>), which lists the full set of values.
- * `origin`: origin of the user message that triggered this turn. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), check this to tell the result of your own prompt, where `origin` is `None` or `{"kind": "human"}`, from the result of an injected turn such as a background-task notification.
+ * `origin`: origin of the user message that triggered this turn. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), check this to tell the result of your own prompt, where `origin` is `None` or `{"kind": "human"}`, from the result of an injected turn such as a background-task notification. Requires Python Agent SDK 0.2.137 or later.
The `usage` dict covers the main agent loop only and excludes subagent and other nested or auxiliary model calls. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), the values are per-turn. Prefer `model_usage` for token and cost accounting. The `usage` dict contains the following keys when present:
@@ -1836,7 +1836,7 @@
`ConversationResetMessage`
-Emitted when the conversation is replaced without ending the connection, such as after `/clear`. See [Track costs in streaming input mode](</docs/en/agent-sdk/cost-tracking#track-costs-in-streaming-input-mode>) for how a reset affects the running totals on later `ResultMessage` objects.
+Emitted when the conversation is replaced without ending the connection, such as after `/clear`. See [Track costs in streaming input mode](</docs/en/agent-sdk/cost-tracking#track-costs-in-streaming-input-mode>) for how a reset affects the running totals on later `ResultMessage` objects. Requires Python Agent SDK 0.2.137 or later.
@dataclass
class ConversationResetMessage:
--- a/python.md
+++ b/python.md
@@ -959,7 +959,7 @@
)
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
- * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.
+ * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set [`CLAUDE_CODE_RETRY_WATCHDOG=1`](</docs/en/errors#tune-retry-behavior>): it retries transient capacity errors indefinitely and, on Claude Code v2.1.199 or later, raises the default for other transient errors to `300` and removes the cap on this variable.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed.
--- a/python.md
+++ b/python.md
@@ -912,7 +912,7 @@
`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
+`add_dirs`| `list[str | Path]`| `[]`| Additional directories Claude can access. The SDK passes each entry to Claude Code as `--add-dir`, so with the `project` setting source Claude Code also [loads the directory’s skills, commands, and subagents](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>)
`env`| `dict[str, str]`| `{}`| Environment variables merged on top of the inherited process environment. See [Environment variables](</docs/en/env-vars>) for variables the underlying CLI reads, and Handle slow or stalled API responses for timeout-related 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
@@ -3031,7 +3031,7 @@
* `TaskUpdate`
* `TaskList`
-On other models, Claude Code provides the Task tools by default and `TodoWrite` only when you set `CLAUDE_CODE_ENABLE_TASKS=0`.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in and [Migrate to Task tools](</docs/en/agent-sdk/todo-tracking#migrate-to-task-tools>) to update your monitoring code.
+On other models, Claude Code provides the Task tools by default and `TodoWrite` only when you set `CLAUDE_CODE_ENABLE_TASKS=0`.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in.
**Input:**
--- a/python.md
+++ b/python.md
@@ -357,7 +357,8 @@
`uuid`| `str`| Unique message identifier
`session_id`| `str`| Session identifier
`message`| `Any`| Raw message content
-`parent_tool_use_id`| `None`| Reserved for future use
+`parent_tool_use_id`| `str | None`| For subagent messages, the id of the spawning `Agent` tool-use block. `None` for main-session messages and older sessions
+`parent_agent_id`| `str | None`| For messages from a [nested subagent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), the agent id of the parent subagent. `None` for main-session messages, top-level subagent messages, and older sessions
####
@@ -870,6 +871,7 @@
user: str | None = None
include_partial_messages: bool = False
include_hook_events: bool = False
+ forward_subagent_text: bool = False
fork_session: bool = False
resume_session_at: str | None = None
resume_drops_turn: str | None = None
@@ -921,6 +923,7 @@
`user`| `str | None`| `None`| User identifier
`include_partial_messages`| `bool`| `False`| Include partial message streaming events. When enabled, `StreamEvent` messages are yielded
`include_hook_events`| `bool`| `False`| Include hook lifecycle events in the message stream as `HookEventMessage` objects
+`forward_subagent_text`| `bool`| `False`| Forward subagent text and thinking blocks in the message stream. By default only subagent `tool_use` and `tool_result` blocks are emitted
`fork_session`| `bool`| `False`| When resuming with `resume`, fork to a new session ID instead of continuing the original session
`resume_session_at`| `str | None`| `None`| When resuming, load the conversation only up to and including the message with this UUID. Use with `resume`, and usually `fork_session`, to branch from an earlier point
`resume_drops_turn`| `str | None`| `None`| UUID of the user prompt whose turn a `resume_session_at` truncation discards. When set, the CLI refuses the resume if the discarded range holds entries not attributable to that turn. Requires Claude Code v2.1.223 or later; the bundled CLI satisfies this
--- a/python.md
+++ b/python.md
@@ -916,7 +916,7 @@
`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, invoked only when the [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) falls through to a prompt. Not invoked for calls auto-approved by `allowed_tools`, allow rules, or `permission_mode`. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) reach it even if you’ve allowed them; in `dontAsk` mode these are denied instead. See `CanUseTool` for details
+`can_use_tool`| `CanUseTool` ` | None`| `None`| Tool permission callback, invoked only when the [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) falls through to a prompt. Not invoked for calls auto-approved by `allowed_tools`, allow rules, or `permission_mode`. An allow rule doesn’t pre-approve the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). See `CanUseTool` 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
@@ -1217,7 +1217,7 @@
* `input_data`: The tool’s input parameters
* `context`: A `ToolPermissionContext` with additional information
-Returns a `PermissionResult` (either `PermissionResultAllow` or `PermissionResultDeny`). The callback is the SDK replacement for the interactive permission prompt: it’s invoked only when the [permission evaluation flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) resolves to a prompt. Tool calls already approved by an `allowed_tools` entry, a settings allow rule, or the permission mode, such as `acceptEdits` or `bypassPermissions`, never invoke it. To gate every tool call, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>) instead. `AskUserQuestion`, MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), and connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) reach the callback even when an allow rule matches. In `dontAsk` mode these calls are denied instead, without invoking the callback.
+Returns a `PermissionResult` (either `PermissionResultAllow` or `PermissionResultDeny`). The callback is the SDK replacement for the interactive permission prompt: it’s invoked only when the [permission evaluation flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) resolves to a prompt. Tool calls already approved by an `allowed_tools` entry, a settings allow rule, or the permission mode, such as `acceptEdits` or `bypassPermissions`, never invoke it. To gate every tool call, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>) instead. An allow rule doesn’t pre-approve the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>); see [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) for which of them reach the callback and what happens in `dontAsk` and `auto` mode.
###
@@ -3781,7 +3781,7 @@
asyncio.run(main())
-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 approval prompts (an explicit [`ask` rule](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) still forces one). This combination effectively allows the model to escape sandbox isolation silently.
+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 approval prompts, apart from the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). This combination effectively allows the model to escape sandbox isolation silently.
##
--- a/python.md
+++ b/python.md
@@ -890,7 +890,7 @@
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>)
+`allowed_tools`| `list[str]`| `[]`| Tools to auto-approve without prompting. This does not restrict Claude to only these tools. If you name one of the [task-tracking tools](</docs/en/agent-sdk/todo-tracking#model-availability>) here, Claude Code also opts the session in. Other 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 | SystemPromptFile | None`| `None`| System prompt configuration. Pass a string for a custom prompt, `{"type": "preset", "preset": "claude_code"}` for Claude Code’s system prompt with optional `"append"`, or `{"type": "file", "path": "..."}` to load a large prompt from disk. See `SystemPromptPreset` and `SystemPromptFile`
`mcp_servers`| `dict[str, McpServerConfig] | str | Path`| `{}`| MCP server configurations or path to config file
`strict_mcp_config`| `bool`| `False`| When `True`, use only the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, plugin-provided MCP servers, and [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>). Maps to the CLI `--strict-mcp-config` flag
--- a/python.md
+++ b/python.md
@@ -3020,7 +3020,15 @@
**Tool name:** `TodoWrite`
-As of Claude Code v2.1.142, `TodoWrite` is disabled by default. Use `TaskCreate`, `TaskGet`, `TaskUpdate`, and `TaskList` instead. See [Migrate to Task tools](</docs/en/agent-sdk/todo-tracking#migrate-to-task-tools>) to update your monitoring code, or set `CLAUDE_CODE_ENABLE_TASKS=0` to revert to `TodoWrite`.
+On Python Agent SDK 0.2.139 and later, the following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
+
+ * `TodoWrite`
+ * `TaskCreate`
+ * `TaskGet`
+ * `TaskUpdate`
+ * `TaskList`
+
+On other models, Claude Code provides the Task tools by default and `TodoWrite` only when you set `CLAUDE_CODE_ENABLE_TASKS=0`.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in and [Migrate to Task tools](</docs/en/agent-sdk/todo-tracking#migrate-to-task-tools>) to update your monitoring code.
**Input:**
--- a/python.md
+++ b/python.md
@@ -871,6 +871,8 @@
include_partial_messages: bool = False
include_hook_events: bool = False
fork_session: bool = False
+ resume_session_at: str | None = None
+ resume_drops_turn: str | None = None
agents: dict[str, AgentDefinition] | None = None
setting_sources: list[SettingSource] | None = None
skills: list[str] | Literal["all"] | None = None
@@ -920,6 +922,8 @@
`include_partial_messages`| `bool`| `False`| Include partial message streaming events. When enabled, `StreamEvent` messages are yielded
`include_hook_events`| `bool`| `False`| Include hook lifecycle events in the message stream as `HookEventMessage` objects
`fork_session`| `bool`| `False`| When resuming with `resume`, fork to a new session ID instead of continuing the original session
+`resume_session_at`| `str | None`| `None`| When resuming, load the conversation only up to and including the message with this UUID. Use with `resume`, and usually `fork_session`, to branch from an earlier point
+`resume_drops_turn`| `str | None`| `None`| UUID of the user prompt whose turn a `resume_session_at` truncation discards. When set, the CLI refuses the resume if the discarded range holds entries not attributable to that turn. Requires Claude Code v2.1.223 or later; the bundled CLI satisfies this
`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
@@ -1592,6 +1596,7 @@
| ResultMessage
| StreamEvent
| RateLimitEvent
+ | ConversationResetMessage
)
###
@@ -1608,6 +1613,7 @@
uuid: str | None = None
parent_tool_use_id: str | None = None
tool_use_result: dict[str, Any] | None = None
+ origin: MessageOrigin | None = None
Field| Type| Description
---|---|---
@@ -1615,6 +1621,7 @@
`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
+`origin`| `MessageOrigin | None`| Provenance of this message, populated on injected turns such as task notifications and peer messages. `None` when the CLI didn’t attribute it
###
@@ -1708,6 +1715,7 @@
api_error_status: int | None = None
uuid: str | None = None
terminal_reason: str | None = None
+ origin: MessageOrigin | None = None
The `subtype` field determines which other fields are populated. It is one of `"success"`, `"error_during_execution"`, `"error_max_turns"`, `"error_max_budget_usd"`, or `"error_max_structured_output_retries"`. The Python dataclass flattens all variants into one shape, so fields that don’t apply to the returned subtype are `None`. Several fields carry diagnostic detail about how the conversation ended:
@@ -1716,6 +1724,7 @@
* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.
* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.
* `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are `interrupt()` and a permission callback returning `PermissionResultDeny` with `interrupt=True`. `None` on CLI versions that predate the field, on results that bypassed the query loop such as local slash commands, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK’s [`SDKResultMessage.terminal_reason`](</docs/en/agent-sdk/typescript#sdkresultmessage>), which lists the full set of values.
+ * `origin`: origin of the user message that triggered this turn. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), check this to tell the result of your own prompt, where `origin` is `None` or `{"kind": "human"}`, from the result of an injected turn such as a background-task notification.
The `usage` dict covers the main agent loop only and excludes subagent and other nested or auxiliary model calls. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), the values are per-turn. Prefer `model_usage` for token and cost accounting. The `usage` dict contains the following keys when present:
@@ -1817,6 +1826,26 @@
`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
+
+###
+
+
+
+`ConversationResetMessage`
+
+Emitted when the conversation is replaced without ending the connection, such as after `/clear`. See [Track costs in streaming input mode](</docs/en/agent-sdk/cost-tracking#track-costs-in-streaming-input-mode>) for how a reset affects the running totals on later `ResultMessage` objects.
+
+ @dataclass
+ class ConversationResetMessage:
+ new_conversation_id: str
+ uuid: str
+ session_id: str
+
+Field| Type| Description
+---|---|---
+`new_conversation_id`| `str`| Opaque identifier for the fresh conversation. Not the `session_id` of subsequent messages; read that from the next message
+`uuid`| `str`| Unique message identifier
+`session_id`| `str`| ID of the session that was reset. Messages after the reset carry a new `session_id`
###
--- a/python.md
+++ b/python.md
@@ -928,7 +928,7 @@
`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`| `EffortLevel` ` | None`| `None`| Effort level for thinking depth. See [adjust the effort level](</docs/en/model-config#adjust-effort-level>)
-`session_store`| [`SessionStore`](</docs/en/agent-sdk/session-storage#the-sessionstore-interface>) ` | None`| `None`| Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](</docs/en/agent-sdk/session-storage>)
+`session_store`| [`SessionStore`](</docs/en/agent-sdk/session-storage#the-sessionstore-interface>) ` | None`| `None`| Mirror session transcripts to an external backend so another host can resume them. See [Persist sessions to external storage](</docs/en/agent-sdk/session-storage>)
`session_store_flush`| `Literal["batched", "eager"]`| `"batched"`| When to flush mirrored transcript entries to `session_store`. `"batched"` flushes once per turn or when the buffer fills; `"eager"` triggers a background flush after every frame. Ignored when `session_store` is `None`
`load_timeout_ms`| `int`| `60000`| Per-call timeout for `session_store.load()` and `list_subkeys()` during resume materialization, in milliseconds
`task_budget`| `TaskBudget | None`| `None`| API-side token budget. Sent as `output_config.task_budget` with the `task-budgets-2026-03-13` beta header. Pass `{"total": <int>}`.
@@ -994,7 +994,7 @@
`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
-`exclude_dynamic_sections`| No| Move per-session context such as working directory, the git-repo flag, and auto-memory paths from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>)
+`exclude_dynamic_sections`| No| Move per-session context such as working directory, the git-repo flag, and auto memory paths from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>)
###
@@ -2625,6 +2625,7 @@
"inference_geo": str | None,
"speed": str | None,
"iterations": Any | None,
+ "output_tokens_details": {"thinking_tokens": int | None} | None,
},
"toolStats": { # Aggregate tool activity for the run
"readCount": int,
@@ -2637,8 +2638,8 @@
"frameCount": int | None,
} | None,
"prompt": str, # The prompt the agent ran
- "worktreePath": str | None, # Present for worktree-isolated runs
- "worktreeBranch": str | None, # Present for worktree-isolated runs
+ "worktreePath": str | None, # Present when Claude Code kept the subagent's worktree
+ "worktreeBranch": str | None, # Present when Claude Code created that worktree with git
}
**Output (status:`"async_launched"`):**
@@ -2666,7 +2667,7 @@
"outputFile": str, # File path where the agent's output is written
}
-Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it. Worktree-isolated runs include `worktreePath` and `worktreeBranch` on the `completed` variant. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On the `async_launched` variant, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The `modelsUsed` field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later.
+Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it. If Claude Code [kept the subagent’s isolated worktree](</docs/en/worktrees#isolate-subagents-with-worktrees>), `worktreePath` on the `completed` variant is where to find it, and `worktreeBranch` is its branch when Claude Code created the worktree with git. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On the `async_launched` variant, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The `modelsUsed` field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later. Claude Code fills `usage` and `totalTokens` from the subagent’s final API request, not from the whole run. When present, `thinking_tokens` under `output_tokens_details` in `usage` is the number of that request’s output tokens that were thinking tokens. The `output_tokens_details` key requires Python SDK v0.2.136 or later, which bundles Claude Code v2.1.228.
###
@@ -3652,7 +3653,7 @@
---|---|---|---
`allowedDomains`| `list[str]`| `[]`| Domain names that sandboxed processes can access
`deniedDomains`| `list[str]`| `[]`| Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains`
-`allowManagedDomainsOnly`| `bool`| `False`| Managed-settings only: when set in managed settings, ignore `allowedDomains` from non-managed settings sources. Has no effect when set via SDK options
+`allowManagedDomainsOnly`| `bool`| `False`| Managed-settings only: when set in managed settings, ignore `allowedDomains` and `WebFetch(domain:...)` allow rules from non-managed settings sources. Has no effect when set via SDK options
`allowUnixSockets`| `list[str]`| `[]`| Unix socket paths that processes can access (e.g., Docker socket)
`allowAllUnixSockets`| `bool`| `False`| Allow access to all Unix sockets
`allowLocalBinding`| `bool`| `False`| Allow processes to bind to local ports (e.g., for dev servers)
--- a/python.md
+++ b/python.md
@@ -1717,7 +1717,7 @@
* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.
* `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are `interrupt()` and a permission callback returning `PermissionResultDeny` with `interrupt=True`. `None` on CLI versions that predate the field, on results that bypassed the query loop such as local slash commands, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK’s [`SDKResultMessage.terminal_reason`](</docs/en/agent-sdk/typescript#sdkresultmessage>), which lists the full set of values.
-The `usage` dict contains the following keys when present:
+The `usage` dict covers the main agent loop only and excludes subagent and other nested or auxiliary model calls. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), the values are per-turn. Prefer `model_usage` for token and cost accounting. The `usage` dict contains the following keys when present:
Key| Type| Description
---|---|---
@@ -1726,7 +1726,7 @@
`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. Each value is a `ModelUsage` TypedDict whose keys use camelCase, because the value is passed through unmodified from the underlying CLI process. Import via `from claude_agent_sdk.types import ModelUsage`. The keys are:
+The `model_usage` dict maps model names to per-model usage. It covers every model call made through the query pipeline: the main loop, subagents, and internal calls such as compaction and Workflow agents. Helper calls outside that pipeline, such as the permission classifier and token-counting requests, are excluded from `model_usage`. Treat `model_usage` as an estimate, not a billing statement. In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), `model_usage` and `total_cost_usd` are cumulative across turns, so read the latest result rather than summing across results. See [Track costs in streaming input mode](</docs/en/agent-sdk/cost-tracking#track-costs-in-streaming-input-mode>) for resets and [Recover totals after a session crash](</docs/en/agent-sdk/cost-tracking#recover-totals-after-a-session-crash>) for zeroed results. Each value in `model_usage` is a `ModelUsage` TypedDict, imported via `from claude_agent_sdk.types import ModelUsage`. Its keys use camelCase because the SDK passes the value through unmodified from the underlying CLI process, matching the TypeScript [`ModelUsage`](</docs/en/agent-sdk/typescript#modelusage>) type:
Key| Type| Description
---|---|---
@@ -2613,7 +2613,7 @@
"modelsUsed": list[str] | None, # Models used in order, with consecutive repeats collapsed
"totalToolUseCount": int, # Number of tool calls the agent made
"totalDurationMs": int, # Execution duration in milliseconds
- "totalTokens": int, # Total tokens used
+ "totalTokens": int, # Token count from the final API request, not the whole run
"usage": { # Token usage statistics
"input_tokens": int,
"output_tokens": int,
Show diff (218 lines)
--- a/python.md
+++ b/python.md
@@ -19,12 +19,6 @@
Choosing between `query()` and `ClaudeSDKClient`
The Python SDK provides two ways to interact with Claude Code:
-
-###
-
-
-
-Quick comparison
Feature| `query()`| `ClaudeSDKClient`
---|---|---
@@ -38,32 +32,7 @@
**Continue Chat**| Manual via `continue_conversation` or `resume`| ✅ Automatic
**Use Case**| One-off tasks| Continuous conversations
-###
-
-
-
-When to use `query()` (one-off tasks)
-
-**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
+Use `ClaudeSDKClient` for interactive applications such as chat interfaces, or when the next action depends on Claude’s response.
##
@@ -546,20 +515,7 @@
`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
+**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. See the comparison with `query()`.
class ClaudeSDKClient:
def __init__(self, options: ClaudeAgentOptions | None = None, transport: Transport | None = None)
@@ -1106,22 +1062,6 @@
In Python SDK 0.1.59 and earlier, an empty list was treated the same as omitting the option, so `setting_sources=[]` did not disable filesystem settings. Upgrade to a newer release if you need an empty list to take effect. The TypeScript SDK is not affected.
-**Load all filesystem settings explicitly:**
-
- import asyncio
- from claude_agent_sdk import query, ClaudeAgentOptions
-
- async def main():
- async for message in query(
- prompt="Analyze this code",
- options=ClaudeAgentOptions(
- setting_sources=["user", "project", "local"]
- ),
- ):
- print(message)
-
- asyncio.run(main())
-
**Load only specific setting sources:**
# Load only project settings, ignore user and local
@@ -1133,24 +1073,6 @@
prompt="Run CI checks",
options=ClaudeAgentOptions(
setting_sources=["project"] # Only .claude/settings.json
- ),
- ):
- print(message)
-
- asyncio.run(main())
-
-**Testing and CI environments:**
-
- # Ensure consistent behavior in CI by excluding local settings
- import asyncio
- from claude_agent_sdk import query, ClaudeAgentOptions
-
- async def main():
- async for message in query(
- prompt="Run tests",
- options=ClaudeAgentOptions(
- setting_sources=["project"], # Only team-shared settings
- permission_mode="bypassPermissions",
),
):
print(message)
@@ -1182,27 +1104,7 @@
asyncio.run(main())
-**Loading CLAUDE.md project instructions:**
-
- # Load project settings to include CLAUDE.md files
- import asyncio
- from claude_agent_sdk import query, ClaudeAgentOptions
-
- async def main():
- 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"], # Loads CLAUDE.md from project
- allowed_tools=["Read", "Write", "Edit"],
- ),
- ):
- print(message)
-
- asyncio.run(main())
+To load CLAUDE.md project instructions, include `"project"` in `setting_sources`. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#claude-md-files-for-project-level-instructions>) for how CLAUDE.md loading interacts with the system prompt options.
####
@@ -2552,7 +2454,7 @@
`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.
+A discriminated union of event-specific `TypedDict` output types. The `hookEventName` field determines which fields are valid. For full details on available fields per hook event, see [Control execution with hooks](</docs/en/agent-sdk/hooks#outputs>).
class PreToolUseHookSpecificOutput(TypedDict):
hookEventName: Literal["PreToolUse"]
@@ -3593,33 +3495,6 @@
-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 (
@@ -3810,12 +3685,7 @@
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.
+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. Commands listed in `excludedCommands` instead bypass the sandbox automatically, with no model involvement; see `SandboxSettings`. The following example logs each unsandboxed request and denies it unless your own authorization logic allows it:
import asyncio
from claude_agent_sdk import (
@@ -3873,12 +3743,6 @@
asyncio.run(main())
-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 approval prompts (an explicit [`ask` rule](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) still forces one). This combination effectively allows the model to escape sandbox isolation silently.
##
--- a/python.md
+++ b/python.md
@@ -2367,7 +2367,7 @@
`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
+`is_interrupt`| `bool` (optional)| True when the failure reached Claude Code as an abort rather than as an error the tool reported. Cancelling a running tool with `interrupt()` does not fire this hook; the tool result carries the interruption message instead
`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
@@ -2838,10 +2838,11 @@
**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
+ "stdout": str, # The command's output; stdout and stderr arrive merged into this one interleaved stream
+ "stderr": str, # Notices the tool itself adds, not the command's stderr
+ "interrupted": bool, # Whether the command was interrupted
+ "isImage": bool | None, # Whether stdout contains image data
+ "backgroundTaskId": str | None, # ID of the background task if command is running in background
}
###
@@ -3216,7 +3217,7 @@
**Tool name:** `TaskOutput`. The previous name `BashOutput` is still accepted as an alias.
-`TaskOutput` is deprecated; prefer `Read` on the task’s output file path. Deprecated since Claude Code v2.1.83. The schemas below remain valid for hooks and permission handlers that encounter the tool.
+`TaskOutput` is deprecated; prefer `Read` on the task’s output file path. The schemas below remain valid for hooks and permission handlers that encounter the tool.
**Input:**
--- a/python.md
+++ b/python.md
@@ -968,7 +968,7 @@
`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` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Endpoint-managed policy loads regardless; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
-`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. When set, the SDK adds the Skill tool to `allowed_tools` automatically. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
+`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. Pass exact names only. The SDK rejects malformed and wildcard-form names with a `ValueError` before starting the Claude Code process. When set, the SDK adds the Skill tool to `allowed_tools` automatically. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
`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`| `EffortLevel` ` | None`| `None`| Effort level for thinking depth. See [adjust the effort level](</docs/en/model-config#adjust-effort-level>)
@@ -998,7 +998,7 @@
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
- * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, Claude Code retries the request at most once, and only before Claude has started a block of text or a tool call in the response; once Claude has completed a block of text or a tool call, Claude Code keeps the completed output, appends an [incomplete-response notice](</docs/en/errors#the-response-above-may-be-incomplete>) instead of retrying, and still runs any completed tool call.
+ * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed.
###
Show diff (134 lines)
--- a/python.md
+++ b/python.md
@@ -10,7 +10,7 @@
source .venv/bin/activate
pip install claude-agent-sdk
-For uv, Windows PowerShell, and API key setup, see [Get started in the Agent SDK overview](</docs/en/agent-sdk/overview#get-started>).
+For uv, Windows PowerShell, and API key setup, see [Setup in the Agent SDK quickstart](</docs/en/agent-sdk/quickstart#setup>).
##
@@ -733,8 +733,9 @@
# 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
+ print(f"Interrupted task: terminal_reason={message.terminal_reason!r}")
+ # terminal_reason is "aborted_streaming" or "aborted_tools"
+ # for interrupted turns
# Send a new command
await client.query("Just say hello instead")
@@ -746,7 +747,7 @@
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.
+**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`, 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.
####
@@ -997,7 +998,7 @@
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
- * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
+ * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, Claude Code retries the request at most once, and only before Claude has started a block of text or a tool call in the response; once Claude has completed a block of text or a tool call, Claude Code keeps the completed output, appends an [incomplete-response notice](</docs/en/errors#the-response-above-may-be-incomplete>) instead of retrying, and still runs any completed tool call.
###
@@ -1070,7 +1071,7 @@
---|---|---
`"user"`| Global user settings| `~/.claude/settings.json`
`"project"`| Shared project settings (version controlled)| `.claude/settings.json`
-`"local"`| Local project settings (not version controlled)| `.claude/settings.local.json`
+`"local"`| Local project settings, gitignored when Claude Code saves a setting to it| `.claude/settings.local.json`
####
@@ -1484,7 +1485,7 @@
`enabled`| `type`, `budget_tokens`, `display`| Enable thinking with a specific token budget
`disabled`| `type`| Disable thinking
-The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. 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`:
+The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. Claude Code doesn’t send `display` to Amazon Bedrock or Google Cloud’s Agent Platform, so on those providers Opus 4.7 and later return empty `ThinkingBlock` outputs even when you set `display` to `"summarized"`. 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
@@ -1525,7 +1526,7 @@
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 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
+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 Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
###
@@ -1759,9 +1760,10 @@
"rate_limit",
"invalid_request",
"server_error",
- "max_output_tokens",
"unknown",
]
+
+The underlying CLI process can emit error types this Literal doesn’t list, such as `max_output_tokens`. The SDK passes the value through unmodified, so treat strings outside this list the way you treat `unknown`. The TypeScript [`SDKAssistantMessageError`](</docs/en/agent-sdk/typescript#sdkassistantmessage>) type lists the full set of values the CLI can emit.
###
@@ -1811,7 +1813,7 @@
* `api_error_status`: the HTTP status code of the terminating API error. `None` when the turn ended without one. Populated only on `subtype="success"`.
* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.
* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.
- * `terminal_reason`: why the query loop terminated, such as `"completed"`, `"max_turns"`, or `"aborted_streaming"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was cancelled by an interrupt. `None` when the CLI didn’t report a terminal reason, such as with an older CLI version. See [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) for the full list of values.
+ * `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are `interrupt()` and a permission callback returning `PermissionResultDeny` with `interrupt=True`. `None` on CLI versions that predate the field, on results that bypassed the query loop such as local slash commands, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK’s [`SDKResultMessage.terminal_reason`](</docs/en/agent-sdk/typescript#sdkresultmessage>), which lists the full set of values.
The `usage` dict contains the following keys when present:
@@ -2097,6 +2099,8 @@
class ClaudeSDKError(Exception):
"""Base error for Claude SDK."""
+When a single-shot `query()` ends with an error result, for example a turn-limit error, the SDK raises a plain `Exception` after yielding the final result message, not a `ClaudeSDKError` subclass.
+
###
@@ -2240,7 +2244,8 @@
default_factory=list
) # List of callbacks to execute
timeout: float | None = (
- None # Timeout in seconds. When omitted, the per-event default applies
+ None # Timeout in seconds. When omitted, the per-event default applies:
+ # 600 for most events, 30 for UserPromptSubmit
)
###
@@ -3577,6 +3582,9 @@
print(f"Process failed with exit code: {e.exit_code}")
except CLIJSONDecodeError as e:
print(f"Failed to parse response: {e}")
+ # A single-shot query() raises a plain Exception after yielding an error result
+ except Exception as e:
+ print(f"Query ended with an error result: {e}")
asyncio.run(main())
@@ -3720,11 +3728,12 @@
import asyncio
- from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings
-
- sandbox_settings: SandboxSettings = {
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ sandbox_settings = {
"enabled": True,
"autoAllowBashIfSandboxed": True,
+ "failIfUnavailable": True,
"network": {"allowLocalBinding": True},
}
--- a/python.md
+++ b/python.md
@@ -1797,19 +1797,21 @@
usage: dict[str, Any] | None = None
result: str | None = None
structured_output: Any = None
- model_usage: dict[str, Any] | None = None
+ model_usage: dict[str, ModelUsage] | None = None
permission_denials: list[Any] | None = None
deferred_tool_use: DeferredToolUse | None = None
errors: list[str] | None = None
api_error_status: int | None = None
uuid: str | None = None
-
-The `subtype` field determines which other fields are populated. It is one of `"success"`, `"error_during_execution"`, `"error_max_turns"`, `"error_max_budget_usd"`, or `"error_max_structured_output_retries"`. The Python dataclass flattens all variants into one shape, so fields that don’t apply to the returned subtype are `None`. Several fields carry diagnostic detail when the conversation ends on an error:
+ terminal_reason: str | None = None
+
+The `subtype` field determines which other fields are populated. It is one of `"success"`, `"error_during_execution"`, `"error_max_turns"`, `"error_max_budget_usd"`, or `"error_max_structured_output_retries"`. The Python dataclass flattens all variants into one shape, so fields that don’t apply to the returned subtype are `None`. Several fields carry diagnostic detail about how the conversation ended:
* `is_error`: `True` when the conversation ended in an error state. Always `True` on the `error_*` subtypes. On `subtype="success"` it is `True` when the final model request failed, meaning the agent loop completed but the last API call returned an error.
* `api_error_status`: the HTTP status code of the terminating API error. `None` when the turn ended without one. Populated only on `subtype="success"`.
* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.
* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.
+ * `terminal_reason`: why the query loop terminated, such as `"completed"`, `"max_turns"`, or `"aborted_streaming"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was cancelled by an interrupt. `None` when the CLI didn’t report a terminal reason, such as with an older CLI version. See [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) for the full list of values.
The `usage` dict contains the following keys when present:
@@ -1820,7 +1822,7 @@
`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#modelusage>) type:
+The `model_usage` dict maps model names to per-model usage. Each value is a `ModelUsage` TypedDict whose keys use camelCase, because the value is passed through unmodified from the underlying CLI process. Import via `from claude_agent_sdk.types import ModelUsage`. The keys are:
Key| Type| Description
---|---|---
@@ -1832,6 +1834,8 @@
`costUSD`| `float`| Estimated cost in USD for this model, computed client-side. See [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for billing caveats.
`contextWindow`| `int`| Context window size for this model.
`maxOutputTokens`| `int`| Maximum output token limit for this model.
+`canonicalModel`| `str`| Canonical model ID used for the pricing lookup. May differ from the raw model string the entry is keyed by, such as a provider-specific ID or alias. Not always present.
+`provider`| `str`| API provider that served this model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`. Not always present.
###
--- a/python.md
+++ b/python.md
@@ -1245,7 +1245,7 @@
---|---|---
`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
+`tools`| No| Array of allowed tool names. If omitted, inherits every [tool available to subagents](</docs/en/sub-agents#available-tools>)
`disallowedTools`| No| Array of tool names to remove from the agent’s tool set. MCP server-level patterns are also accepted: `mcp__server` or `mcp__server__*` removes every tool from that server, and `mcp__*` removes every MCP tool from any server
`model`| No| Model override for this agent. Accepts an alias such as `"sonnet"`, `"opus"`, `"haiku"`, or `"inherit"`, or a full model ID. If omitted, uses the main model
`skills`| No| List of skill names to preload into the agent’s context at startup. Unlisted skills remain invocable through the Skill tool
--- a/python.md
+++ b/python.md
@@ -2678,9 +2678,10 @@
"prompt": str, # The task for the agent to perform
"subagent_type": str | None, # The type of specialized agent to use
"model": "sonnet" | "opus" | "haiku" | "fable" | None, # Model override for this agent
- "run_in_background": bool | None, # Launch the agent in the background
+ "run_in_background": bool | None, # Agents run in the background by default; set to False to run synchronously
"name": str | None, # Name for the spawned agent
- "mode": "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan" | None, # Permission mode for the agent
+ "team_name": str | None, # Deprecated; ignored
+ "mode": "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan" | None, # Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it
"isolation": "worktree" | "remote" | None, # Isolation mode for the agent's changes
}
@@ -2697,7 +2698,8 @@
"citations": list | None,
}
],
- "resolvedModel": str | None, # Model the subagent actually ran on
+ "resolvedModel": str | None, # Model the subagent started on
+ "modelsUsed": list[str] | None, # Models used in order, with consecutive repeats collapsed
"totalToolUseCount": int, # Number of tool calls the agent made
"totalDurationMs": int, # Execution duration in milliseconds
"totalTokens": int, # Total tokens used
@@ -2735,7 +2737,8 @@
"isAsync": bool | None, # True on background launches
"agentId": str, # ID of the launched agent
"description": str, # The task description
- "resolvedModel": str | None, # Model the subagent runs on
+ "resolvedModel": str | None, # Model in use at the backgrounding transition
+ "modelsUsed": list[str] | None, # Models used before backgrounding, in order, with consecutive repeats collapsed
"prompt": str, # The prompt the agent runs
"outputFile": str, # File path where the agent's output is written
"canReadOutputFile": bool | None, # Whether the output file can be read directly
@@ -2752,7 +2755,7 @@
"outputFile": str, # File path where the agent's output is written
}
-Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it. Worktree-isolated runs include `worktreePath` and `worktreeBranch` on the `completed` variant. The `resolvedModel` field on the `completed` and `async_launched` variants names the model the subagent actually ran on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later.
+Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it. Worktree-isolated runs include `worktreePath` and `worktreeBranch` on the `completed` variant. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On the `async_launched` variant, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The `modelsUsed` field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later.
###
@@ -2771,6 +2774,7 @@
{
"label": str, # Display text for this option (1-5 words)
"description": str, # Explanation of what this option means
+ "preview": str | None, # Preview content rendered when the option is focused
}
],
"multiSelect": bool, # Set to true to allow multiple selections
@@ -2780,6 +2784,11 @@
# User answers populated by the permission system. Multi-select
# answers are a comma-joined string of the selected labels; a
# list of labels is accepted on input and coerced to that form
+ "annotations": dict[str, dict] | None,
+ # Per-question annotations from the user, keyed by question text.
+ # Each value can carry "preview" (the selected option's preview
+ # content) and "notes" (free-text notes on the selection)
+ "metadata": dict | None, # Analytics metadata, such as {"source": "remember"}; not displayed to the user
}
**Output:**
@@ -2789,12 +2798,17 @@
{
"question": str,
"header": str,
- "options": [{"label": str, "description": str}],
+ "options": [{"label": str, "description": str, "preview": str | None}],
"multiSelect": bool,
}
],
"answers": dict[str, str], # Maps question text to answer string
# Multi-select answers are comma-separated
+ "response": str | None,
+ # Freeform reply typed instead of answering the questions; when set,
+ # Claude receives "The user responded: ..." in place of the answer list
+ "annotations": dict[str, dict] | None, # Per-question "preview" and "notes" from the user's selections
+ "afkTimeoutMs": int | None, # Set when the dialog auto-resolved after this many milliseconds of user inactivity; absent when the user answered
}
###
Show diff (624 lines)
--- a/python.md
+++ b/python.md
@@ -71,6 +71,8 @@
Functions
+Signature blocks and bare `async for` / `async with` fragments on this page are illustrative. To run them, wrap the body in `async def main(): ...` and call `asyncio.run(main())`.
+
###
@@ -119,7 +121,6 @@
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):
@@ -265,7 +266,7 @@
Example
- from claude_agent_sdk import tool, create_sdk_mcp_server
+ from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions
@tool("add", "Add two numbers", {"a": float, "b": float})
async def add(args):
@@ -523,8 +524,10 @@
from claude_agent_sdk import list_sessions, tag_session
- # Tag a session
- tag_session("550e8400-e29b-41d4-a716-446655440000", "needs-review")
+ # Tag the most recent session
+ sessions = list_sessions(directory="/path/to/project", limit=1)
+ if sessions:
+ tag_session(sessions[0].session_id, "needs-review")
# Later: find all sessions with that tag
for session in list_sessions(directory="/path/to/project"):
@@ -607,10 +610,16 @@
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)
+ import asyncio
+ from claude_agent_sdk import ClaudeSDKClient
+
+ async def main():
+ async with ClaudeSDKClient() as client:
+ await client.query("Hello Claude")
+ async for message in client.receive_response():
+ print(message)
+
+ asyncio.run(main())
> **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.
@@ -745,6 +754,7 @@
Example - Advanced permission control
+ import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
from claude_agent_sdk.types import (
PermissionResultAllow,
@@ -880,6 +890,7 @@
permission_mode: PermissionMode | None = None
continue_conversation: bool = False
resume: str | None = None
+ session_id: str | None = None
max_turns: int | None = None
max_budget_usd: float | None = None
disallowed_tools: list[str] = field(default_factory=list)
@@ -914,6 +925,8 @@
enable_file_checkpointing: bool = False
session_store: SessionStore | None = None
session_store_flush: SessionStoreFlushMode = "batched"
+ load_timeout_ms: int = 60_000
+ task_budget: TaskBudget | None = None
Property| Type| Default| Description
---|---|---|---
@@ -925,6 +938,7 @@
`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
+`session_id`| `str | None`| `None`| Use a specific session ID instead of an auto-generated one. Must be a valid UUID. Can’t be combined with `continue_conversation` or `resume` unless `fork_session` is also set
`max_turns`| `int | None`| `None`| Maximum agentic turns (tool-use round trips)
`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for accuracy caveats
`disallowed_tools`| `list[str]`| `[]`| Tools to deny. A bare name such as `"Bash"` removes the tool from Claude’s context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`. See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
@@ -959,6 +973,8 @@
`effort`| `EffortLevel` ` | None`| `None`| Effort level for thinking depth. See [adjust the effort level](</docs/en/model-config#adjust-effort-level>)
`session_store`| [`SessionStore`](</docs/en/agent-sdk/session-storage#the-sessionstore-interface>) ` | None`| `None`| Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](</docs/en/agent-sdk/session-storage>)
`session_store_flush`| `Literal["batched", "eager"]`| `"batched"`| When to flush mirrored transcript entries to `session_store`. `"batched"` flushes once per turn or when the buffer fills; `"eager"` triggers a background flush after every frame. Ignored when `session_store` is `None`
+`load_timeout_ms`| `int`| `60000`| Per-call timeout for `session_store.load()` and `list_subkeys()` during resume materialization, in milliseconds
+`task_budget`| `TaskBudget | None`| `None`| API-side token budget. Sent as `output_config.task_budget` with the `task-budgets-2026-03-13` beta header. Pass `{"total": <int>}`.
####
@@ -967,6 +983,8 @@
Handle slow or stalled API responses
The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through `ClaudeAgentOptions.env`:
+
+ from claude_agent_sdk import ClaudeAgentOptions
options = ClaudeAgentOptions(
env={
@@ -1071,83 +1089,119 @@
**Disable filesystem settings:**
# Do not load user, project, or local settings from disk
+ import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
- async for message in query(
- prompt="Analyze this code",
- options=ClaudeAgentOptions(
- setting_sources=[]
- ),
- ):
- print(message)
+ async def main():
+ async for message in query(
+ prompt="Analyze this code",
+ options=ClaudeAgentOptions(
+ setting_sources=[]
+ ),
+ ):
+ print(message)
+
+ asyncio.run(main())
In Python SDK 0.1.59 and earlier, an empty list was treated the same as omitting the option, so `setting_sources=[]` did not disable filesystem settings. Upgrade to a newer release if you need an empty list to take effect. The TypeScript SDK is not affected.
**Load all filesystem settings explicitly:**
+ import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
- async for message in query(
- prompt="Analyze this code",
- options=ClaudeAgentOptions(
- setting_sources=["user", "project", "local"]
- ),
- ):
- print(message)
+ async def main():
+ async for message in query(
+ prompt="Analyze this code",
+ options=ClaudeAgentOptions(
+ setting_sources=["user", "project", "local"]
+ ),
+ ):
+ print(message)
+
+ asyncio.run(main())
**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)
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async def main():
+ async for message in query(
+ prompt="Run CI checks",
+ options=ClaudeAgentOptions(
+ setting_sources=["project"] # Only .claude/settings.json
+ ),
+ ):
+ print(message)
+
+ asyncio.run(main())
**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)
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async def main():
+ async for message in query(
+ prompt="Run tests",
+ options=ClaudeAgentOptions(
+ setting_sources=["project"], # Only team-shared settings
+ permission_mode="bypassPermissions",
+ ),
+ ):
+ print(message)
+
+ asyncio.run(main())
**SDK-only applications:**
# Define everything programmatically.
# Pass [] to opt out of filesystem setting sources.
- async for message in query(
- prompt="Review this PR",
- options=ClaudeAgentOptions(
- setting_sources=[],
- agents={...},
- mcp_servers={...},
- allowed_tools=["Read", "Grep", "Glob"],
- ),
- ):
- print(message)
+ import asyncio
+ from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions, query
+
+ async def main():
+ async for message in query(
+ prompt="Review this PR",
+ options=ClaudeAgentOptions(
+ setting_sources=[],
+ agents={
+ "code-reviewer": AgentDefinition(
+ description="Reviews code changes",
+ prompt="You are a code reviewer. Report issues in the diff.",
+ ),
+ },
+ allowed_tools=["Read", "Grep", "Glob"],
+ ),
+ ):
+ print(message)
+
+ asyncio.run(main())
**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"], # Loads CLAUDE.md from project
- allowed_tools=["Read", "Write", "Edit"],
- ),
- ):
- print(message)
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async def main():
+ 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"], # Loads CLAUDE.md from project
+ allowed_tools=["Read", "Write", "Edit"],
+ ),
+ ):
+ print(message)
+
+ asyncio.run(main())
####
@@ -1219,7 +1273,7 @@
"plan", # Planning mode - explore without editing
"dontAsk", # Deny anything not pre-approved instead of prompting
"bypassPermissions", # Bypass permission checks; explicit ask rules still prompt (use with caution)
- "auto", # A model classifier approves or denies each tool call
+ "auto", # Model classifier approves or denies permission prompts
]
###
@@ -1270,6 +1324,8 @@
class ToolPermissionContext:
signal: Any | None = None # Future: abort signal support
suggestions: list[PermissionUpdate] = field(default_factory=list)
+ tool_use_id: str | None = None
+ agent_id: str | None = None
blocked_path: str | None = None
decision_reason: str | None = None
title: str | None = None
@@ -1280,6 +1336,8 @@
---|---|---
`signal`| `Any | None`| Reserved for future abort signal support
`suggestions`| `list[PermissionUpdate]`| Permission update suggestions from the CLI. Bash prompts include a suggestion with the `localSettings` destination, so returning it in `updated_permissions` writes the rule to `.claude/settings.local.json` and persists across sessions.
+`tool_use_id`| `str | None`| Identifier of the specific tool call this prompt is for. Always populated when delivered to `can_use_tool`
+`agent_id`| `str | None`| Sub-agent ID when the call originates from a subagent; `None` for the main agent
`blocked_path`| `str | None`| File path that triggered the permission request, when applicable. For example, when a Bash command tries to access a path outside allowed directories
`decision_reason`| `str | None`| Reason this permission request was triggered. Forwarded from a PreToolUse hook’s `permissionDecisionReason` when the hook returned `"ask"`
`title`| `str | None`| Full permission prompt sentence, such as `Claude wants to read foo.txt`. Use as the primary prompt text when present
@@ -1442,6 +1500,23 @@
+`TaskBudget`
+
+API-side task budget in tokens, used with the `task_budget` field in `ClaudeAgentOptions`.
+
+ class TaskBudget(TypedDict):
+ total: int
+
+Field| Type| Description
+---|---|---
+`total`| `int`| Total token budget for the task
+
+Because this is a `TypedDict`, pass it as a plain dict, such as `ClaudeAgentOptions(task_budget={"total": 50000})`.
+
+###
+
+
+
`SdkBeta`
Literal type for SDK beta features.
@@ -1654,6 +1729,9 @@
error: AssistantMessageError | None = None
usage: dict[str, Any] | None = None
message_id: str | None = None
+ stop_reason: str | None = None
+ session_id: str | None = None
+ uuid: str | None = None
Field| Type| Description
---|---|---
@@ -1663,6 +1741,9 @@
`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
+`stop_reason`| `str | None`| Stop reason from the API (e.g. `end_turn`, `tool_use`)
+`session_id`| `str | None`| ID of the session this message belongs to
+`uuid`| `str | None`| Unique message identifier within the session transcript
###
@@ -2103,7 +2184,7 @@
"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`, `WorktreeRemove`, `PostToolBatch`, and `MessageDisplay`.
+The TypeScript SDK supports additional hook events not yet available in Python. See the [hook availability table](</docs/en/agent-sdk/hooks#available-hooks>) for per-SDK support.
###
@@ -2155,7 +2236,7 @@
default_factory=list
) # List of callbacks to execute
timeout: float | None = (
- None # Timeout in seconds for all hooks in this matcher (default: 60)
+ None # Timeout in seconds. When omitted, the per-event default applies
)
###
@@ -2529,6 +2610,7 @@
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.
+ import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext
from typing import Any
@@ -2563,14 +2645,17 @@
), # 2 min for validation
HookMatcher(
hooks=[log_tool_use]
- ), # Applies to all tools (default 60s timeout)
+ ), # Applies to all tools (per-event default timeout)
],
"PostToolUse": [HookMatcher(hooks=[log_tool_use])],
}
)
- async for message in query(prompt="Analyze this codebase", options=options):
- print(message)
+ async def main():
+ async for message in query(prompt="Analyze this codebase", options=options):
+ print(message)
+
+ asyncio.run(main())
##
@@ -2586,22 +2671,88 @@
Agent
-**Tool name:** `Agent` (previously `Task`, which is still accepted as an alias) **Input:**
+**Tool name:** `Agent`. The previous name `Task` is still accepted as an alias, and the `tools` list in the init `SystemMessage` reports this tool as `Task` for backward compatibility. **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, # Estimated total cost in USD
- "duration_ms": int | None, # Execution duration in milliseconds
- }
+ "subagent_type": str | None, # The type of specialized agent to use
+ "model": "sonnet" | "opus" | "haiku" | "fable" | None, # Model override for this agent
+ "run_in_background": bool | None, # Launch the agent in the background
+ "name": str | None, # Name for the spawned agent
+ "mode": "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan" | None, # Permission mode for the agent
+ "isolation": "worktree" | "remote" | None, # Isolation mode for the agent's changes
+ }
+
+Launches a new agent to handle complex, multi-step tasks autonomously. **Output (status:`"completed"`):**
+
+ {
+ "status": "completed",
+ "agentId": str, # ID of the agent that ran
+ "agentType": str | None, # The subagent type that handled the task
+ "content": [ # Result content blocks
+ {
+ "type": "text",
+ "text": str,
+ "citations": list | None,
+ }
+ ],
+ "resolvedModel": str | None, # Model the subagent actually ran on
+ "totalToolUseCount": int, # Number of tool calls the agent made
+ "totalDurationMs": int, # Execution duration in milliseconds
+ "totalTokens": int, # Total tokens used
+ "usage": { # Token usage statistics
+ "input_tokens": int,
+ "output_tokens": int,
+ "cache_creation_input_tokens": int | None,
+ "cache_read_input_tokens": int | None,
+ "server_tool_use": {"web_search_requests": int, "web_fetch_requests": int} | None,
+ "service_tier": str | None,
+ "cache_creation": {"ephemeral_1h_input_tokens": int, "ephemeral_5m_input_tokens": int} | None,
+ "inference_geo": str | None,
+ "speed": str | None,
+ "iterations": Any | None,
+ },
+ "toolStats": { # Aggregate tool activity for the run
+ "readCount": int,
+ "searchCount": int,
+ "bashCount": int,
+ "editFileCount": int,
+ "linesAdded": int,
+ "linesRemoved": int,
+ "otherToolCount": int,
+ "frameCount": int | None,
+ } | None,
+ "prompt": str, # The prompt the agent ran
+ "worktreePath": str | None, # Present for worktree-isolated runs
+ "worktreeBranch": str | None, # Present for worktree-isolated runs
+ }
+
+**Output (status:`"async_launched"`):**
+
+ {
+ "status": "async_launched",
+ "isAsync": bool | None, # True on background launches
+ "agentId": str, # ID of the launched agent
+ "description": str, # The task description
+ "resolvedModel": str | None, # Model the subagent runs on
+ "prompt": str, # The prompt the agent runs
+ "outputFile": str, # File path where the agent's output is written
+ "canReadOutputFile": bool | None, # Whether the output file can be read directly
+ }
+
+**Output (status:`"remote_launched"`):**
+
+ {
+ "status": "remote_launched",
+ "taskId": str, # ID of the remote task
+ "sessionUrl": str, # Link to the remote cloud session
+ "description": str, # The task description
+ "prompt": str, # The prompt the agent runs
+ "outputFile": str, # File path where the agent's output is written
+ }
+
+Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it. Worktree-isolated runs include `worktreePath` and `worktreeBranch` on the `completed` variant. The `resolvedModel` field on the `completed` and `async_launched` variants names the model the subagent actually ran on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later.
###
@@ -2625,9 +2776,10 @@
"multiSelect": bool, # Set to true to allow multiple selections
}
],
- "answers": dict[str, str | list[str]] | None,
+ "answers": dict[str, str] | None,
# User answers populated by the permission system. Multi-select
- # answers may be a list of labels or a comma-joined string
+ # answers are a comma-joined string of the selected labels; a
+ # list of labels is accepted on input and coerced to that form
}
**Output:**
@@ -3037,40 +3189,47 @@
-BashOutput
-
-**Tool name:** `BashOutput` **Input:**
-
- {
- "bash_id": str, # The ID of the background shell
- "filter": str | None, # Optional regex to filter output lines
+TaskOutput
+
+**Tool name:** `TaskOutput`. The previous name `BashOutput` is still accepted as an alias.
+
+`TaskOutput` is deprecated; prefer `Read` on the task’s output file path. Deprecated since Claude Code v2.1.83. The schemas below remain valid for hooks and permission handlers that encounter the tool.
+
+**Input:**
+
+ {
+ "task_id": str, # The task ID to get output from
+ "block": bool, # Whether to wait for completion (default True)
+ "timeout": int, # Max wait time in ms (default 30000)
}
**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
+ "retrieval_status": "success" | "timeout" | "not_ready", # Whether the output was retrieved
+ "task": dict | None, # Task details: task_id, task_type, status, description, output, plus type-specific fields such as exitCode
+ }
+
+###
+
+
+
+TaskStop
+
+**Tool name:** `TaskStop`. The previous names `KillShell` and `KillBash` are still accepted as aliases. **Input:**
+
+ {
+ "task_id": str | None, # The ID of the background task to stop
+ "shell_id": str | None, # Deprecated: use task_id instead
}
**Output:**
{
- "message": str, # Success message
- "shell_id": str, # ID of the killed shell
+ "message": str, # Status message about the operation
+ "task_id": str, # The ID of the task that was stopped
+ "task_type": str, # The type of the task that was stopped
+ "command": str | None, # The command or description of the stopped task
}
###
@@ -3366,7 +3525,6 @@
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Bash"],
permission_mode="acceptEdits",
- cwd="/home/user/project",
)
async for message in query(
@@ -3631,6 +3789,7 @@
* `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 asyncio
from claude_agent_sdk import (
query,
ClaudeAgentOptions,
@@ -3639,6 +3798,10 @@
PermissionResultDeny,
ToolPermissionContext,
)
+
+ def is_command_authorized(command: str | None) -> bool:
+ # Replace with your own authorization logic
+ return False
async def can_use_tool(
tool: str, input: dict, context: ToolPermissionContext
@@ -3680,6 +3843,8 @@
):
print(message)
+ asyncio.run(main())
+
This pattern enables you to:
* **Audit model requests** : Log when the model requests unsandboxed execution
--- a/python.md
+++ b/python.md
@@ -3385,19 +3385,24 @@
Error handling
+ import asyncio
+
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}")
+ async def main():
+ 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}")
+
+ asyncio.run(main())
###
@@ -3529,13 +3534,15 @@
`ignoreViolations`| `SandboxIgnoreViolations`| `None`| Configure which sandbox violations to ignore
`enableWeakerNestedSandbox`| `bool`| `False`| Enable a weaker nested sandbox for compatibility
-The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. By default, when `enabled` is `True` but the sandbox can’t start, commands run unsandboxed with a warning on stderr. This default differs from the TypeScript SDK, where `failIfUnavailable` defaults to `true`.Set `"failIfUnavailable": True` in your sandbox settings to stop instead. The key isn’t declared on `SandboxSettings` yet, but the SDK forwards it to Claude Code, which honors it. `query()` then reports a `ResultMessage` with `subtype="error_during_execution"` and the reason in `errors`. Watch for that subtype rather than expecting `query()` to raise before yielding messages.
+The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. By default, when `enabled` is `True` but the sandbox can’t start, commands run unsandboxed with a warning on stderr. This default differs from the TypeScript SDK, where `failIfUnavailable` defaults to `true`.Set `"failIfUnavailable": True` in your sandbox settings to stop instead. The key isn’t declared on `SandboxSettings` yet, but the SDK forwards it to Claude Code, which honors it. `query()` then reports a `ResultMessage` with `subtype="error_during_execution"` and the reason in `errors`. Because this is a single-shot `query()` call, the SDK raises after yielding that error result, so wrap the loop in a try block to continue past it. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the error contract.
####
Example usage
+
+ import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings
@@ -3545,11 +3552,19 @@
"network": {"allowLocalBinding": True},
}
- async for message in query(
- prompt="Build and test my project",
- options=ClaudeAgentOptions(sandbox=sandbox_settings),
- ):
- print(message)
+ async def main():
+ try:
+ async for message in query(
+ prompt="Build and test my project",
+ options=ClaudeAgentOptions(sandbox=sandbox_settings),
+ ):
+ print(message)
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result,
+ # such as when failIfUnavailable is set and the sandbox can't start.
+ print(f"Session ended with an error: {error}")
+
+ asyncio.run(main())
**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.
--- a/python.md
+++ b/python.md
@@ -298,6 +298,7 @@
def list_sessions(
directory: str | None = None,
limit: int | None = None,
+ offset: int = 0,
include_worktrees: bool = True
) -> list[SDKSessionInfo]
@@ -311,6 +312,7 @@
---|---|---|---
`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
+`offset`| `int`| `0`| Number of sessions to skip from the start of the sorted results. Use with `limit` for pagination
`include_worktrees`| `bool`| `True`| When `directory` is inside a git repository, include sessions from all worktree paths
####
@@ -941,7 +943,7 @@
`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, invoked only when the [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) falls through to a prompt. Not invoked for calls auto-approved by `allowed_tools`, allow rules, or `permission_mode`. See `CanUseTool` for details
+`can_use_tool`| `CanUseTool` ` | None`| `None`| Tool permission callback, invoked only when the [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) falls through to a prompt. Not invoked for calls auto-approved by `allowed_tools`, allow rules, or `permission_mode`. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) reach it even if you’ve allowed them; in `dontAsk` mode these are denied instead. See `CanUseTool` 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
@@ -1254,7 +1256,7 @@
* `input_data`: The tool’s input parameters
* `context`: A `ToolPermissionContext` with additional information
-Returns a `PermissionResult` (either `PermissionResultAllow` or `PermissionResultDeny`). The callback is the SDK replacement for the interactive permission prompt: it’s invoked only when the [permission evaluation flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) resolves to a prompt. Tool calls already approved by an `allowed_tools` entry, a settings allow rule, or the permission mode, such as `acceptEdits` or `bypassPermissions`, never invoke it. To gate every tool call, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>) instead.
+Returns a `PermissionResult` (either `PermissionResultAllow` or `PermissionResultDeny`). The callback is the SDK replacement for the interactive permission prompt: it’s invoked only when the [permission evaluation flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) resolves to a prompt. Tool calls already approved by an `allowed_tools` entry, a settings allow rule, or the permission mode, such as `acceptEdits` or `bypassPermissions`, never invoke it. To gate every tool call, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>) instead. `AskUserQuestion`, MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), and connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) reach the callback even when an allow rule matches. In `dontAsk` mode these calls are denied instead, without invoking the callback.
###
@@ -1732,8 +1734,8 @@
Key| Type| Description
---|---|---
-`input_tokens`| `int`| Total input tokens consumed.
-`output_tokens`| `int`| Total output tokens generated.
+`input_tokens`| `int`| Input tokens consumed by the top-level agent loop. [Subagent tokens aren’t included](</docs/en/agent-sdk/cost-tracking#get-the-total-cost-of-a-query>); use `model_usage` for whole-tree accounting.
+`output_tokens`| `int`| Output tokens generated by the top-level agent loop. Subagent tokens aren’t included.
`cache_creation_input_tokens`| `int`| Tokens used to create new cache entries.
`cache_read_input_tokens`| `int`| Tokens read from existing cache entries.
@@ -2653,7 +2655,7 @@
{
"command": str, # The command to execute
- "timeout": int | None, # Optional timeout in milliseconds (max 600000)
+ "timeout": int | None, # Optional timeout in milliseconds (max 600000; higher values are clamped to the max)
"description": str | None, # Clear, concise description (5-10 words)
"run_in_background": bool | None, # Set to true to run in background
}
--- a/python.md
+++ b/python.md
@@ -4,7 +4,13 @@
Installation
+Install the package into a virtual environment. On recent Debian, Ubuntu, and Homebrew Python installs, running `pip install` against system Python fails with `error: externally-managed-environment`.
+
+ python3 -m venv .venv
+ source .venv/bin/activate
pip install claude-agent-sdk
+
+For uv, Windows PowerShell, and API key setup, see [Get started in the Agent SDK overview](</docs/en/agent-sdk/overview#get-started>).
##
--- a/python.md
+++ b/python.md
@@ -866,7 +866,7 @@
class ClaudeAgentOptions:
tools: list[str] | ToolsPreset | None = None
allowed_tools: list[str] = field(default_factory=list)
- system_prompt: str | SystemPromptPreset | None = None
+ system_prompt: str | SystemPromptPreset | SystemPromptFile | None = None
mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
strict_mcp_config: bool = False
permission_mode: PermissionMode | None = None
@@ -911,7 +911,7 @@
---|---|---|---
`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
+`system_prompt`| `str | SystemPromptPreset | SystemPromptFile | None`| `None`| System prompt configuration. Pass a string for a custom prompt, `{"type": "preset", "preset": "claude_code"}` for Claude Code’s system prompt with optional `"append"`, or `{"type": "file", "path": "..."}` to load a large prompt from disk. See `SystemPromptPreset` and `SystemPromptFile`
`mcp_servers`| `dict[str, McpServerConfig] | str | Path`| `{}`| MCP server configurations or path to config file
`strict_mcp_config`| `bool`| `False`| When `True`, use only the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, plugin-provided MCP servers, and [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>). Maps to the CLI `--strict-mcp-config` flag
`permission_mode`| `PermissionMode | None`| `None`| Permission mode for tool usage
@@ -1017,6 +1017,23 @@
+`SystemPromptFile`
+
+Configuration for loading a custom system prompt from a file instead of passing it as a string. The SDK maps this to the CLI [`--system-prompt-file`](</docs/en/cli-reference#system-prompt-flags>) flag. Use the file form when the prompt is large: the SDK passes a string `system_prompt` on the CLI subprocess argv, which is subject to OS command-line length limits before the SDK sends any API request. On Linux a single argument longer than roughly 128 KB fails at process spawn with `Argument list too long`. On Windows the whole command line is capped at roughly 32 KB, so the string form fails at a lower threshold.
+
+ class SystemPromptFile(TypedDict):
+ type: Literal["file"]
+ path: str
+
+Field| Required| Description
+---|---|---
+`type`| Yes| Must be `"file"` to load the prompt from disk
+`path`| Yes| Path to a file containing the system prompt
+
+###
+
+
+
`SettingSource`
Controls which filesystem-based configuration sources the SDK loads settings from.
--- a/python.md
+++ b/python.md
@@ -1194,6 +1194,7 @@
"plan", # Planning mode - explore without editing
"dontAsk", # Deny anything not pre-approved instead of prompting
"bypassPermissions", # Bypass permission checks; explicit ask rules still prompt (use with caution)
+ "auto", # A model classifier approves or denies each tool call
]
###
@@ -2384,6 +2385,8 @@
tool_name: str
tool_input: dict[str, Any]
permission_suggestions: NotRequired[list[Any]]
+ agent_id: NotRequired[str]
+ agent_type: NotRequired[str]
Field| Type| Description
---|---|---
@@ -2391,6 +2394,8 @@
`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
+`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
###
--- a/python.md
+++ b/python.md
@@ -1746,7 +1746,7 @@
`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
+`parent_tool_use_id`| `str | None`| Always `None`. Stream events are emitted for the main session only. For subagent attribution, use complete messages such as `AssistantMessage`
###
--- a/python.md
+++ b/python.md
@@ -969,7 +969,7 @@
)
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
- * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1` to retry capacity errors indefinitely.
+ * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
--- a/python.md
+++ b/python.md
@@ -766,9 +766,8 @@
return PermissionResultAllow(updated_input=input_data)
async def main():
- options = ClaudeAgentOptions(
- can_use_tool=custom_permission_handler, allowed_tools=["Read", "Write", "Edit"]
- )
+ # Don't also list the gated tools in allowed_tools: allow rules approve calls before can_use_tool runs
+ options = ClaudeAgentOptions(can_use_tool=custom_permission_handler)
async with ClaudeSDKClient(options=options) as client:
await client.query("Update the system config file")
@@ -936,7 +935,7 @@
`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
+`can_use_tool`| `CanUseTool` ` | None`| `None`| Tool permission callback, invoked only when the [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) falls through to a prompt. Not invoked for calls auto-approved by `allowed_tools`, allow rules, or `permission_mode`. See `CanUseTool` 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
@@ -1231,7 +1230,7 @@
* `input_data`: The tool’s input parameters
* `context`: A `ToolPermissionContext` with additional information
-Returns a `PermissionResult` (either `PermissionResultAllow` or `PermissionResultDeny`).
+Returns a `PermissionResult` (either `PermissionResultAllow` or `PermissionResultDeny`). The callback is the SDK replacement for the interactive permission prompt: it’s invoked only when the [permission evaluation flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) resolves to a prompt. Tool calls already approved by an `allowed_tools` entry, a settings allow rule, or the permission mode, such as `acceptEdits` or `bypassPermissions`, never invoke it. To gate every tool call, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>) instead.
###
@@ -1425,7 +1424,7 @@
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, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
+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 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
###
--- a/python.md
+++ b/python.md
@@ -898,6 +898,7 @@
fork_session: bool = False
agents: dict[str, AgentDefinition] | None = None
setting_sources: list[SettingSource] | None = None
+ skills: list[str] | Literal["all"] | None = None
sandbox: SandboxSettings | None = None
plugins: list[SdkPluginConfig] = field(default_factory=list)
max_thinking_tokens: int | None = None # Deprecated: use thinking instead
@@ -971,7 +972,7 @@
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1` to retry capacity errors indefinitely.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
- * `CLAUDE_ENABLE_STREAM_WATCHDOG=1` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. When `CLAUDE_ENABLE_STREAM_WATCHDOG` is unset, the default is server-controlled on the direct Anthropic API and off on other providers. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
+ * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
###
@@ -1208,7 +1209,7 @@
"low", # Minimal thinking, fastest responses
"medium", # Moderate thinking
"high", # Deep reasoning
- "xhigh", # Extended reasoning (Opus 4.8 and Opus 4.7; falls back to "high" on other models)
+ "xhigh", # Extended reasoning; falls back to "high" on models that don't support it
"max", # Maximum effort
]
@@ -2645,10 +2646,11 @@
Monitor
-**Tool name:** `Monitor` Runs a background script and delivers each stdout line to Claude as an event so it can react without polling. Monitor follows the same permission rules as Bash. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for behavior and provider availability. **Input:**
-
- {
- "command": str, # Shell script; each stdout line is an event, exit ends the watch
+**Tool name:** `Monitor` Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. When Monitor runs a command, it follows the same permission rules as Bash; a WebSocket watch prompts for approval separately. The `ws` source requires Claude Code v2.1.195 or later. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for behavior and provider availability. **Input:**
+
+ {
+ "command": str | None, # Shell script; each stdout line is an event, exit ends the watch
+ "ws": dict | None, # WebSocket source: {"url": str, "protocols": list[str] | None}; each text frame is an event
"description": str, # Short description shown in notifications
"timeout_ms": int | None, # Kill after this deadline (default 300000, max 3600000)
"persistent": bool | None, # Run for the lifetime of the session; stop with TaskStop
--- a/python.md
+++ b/python.md
@@ -944,7 +944,7 @@
`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` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
+`setting_sources`| `list[SettingSource] | None`| `None` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Endpoint-managed policy loads regardless; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. When set, the SDK adds the Skill tool to `allowed_tools` automatically. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
`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`
@@ -1035,7 +1035,7 @@
Default behavior
-When `setting_sources` is omitted or `None`, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. Managed policy settings are loaded in all cases. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read regardless of this option, and how to disable them.
+When `setting_sources` is omitted or `None`, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. Endpoint-managed policy is loaded in all cases; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read regardless of this option, and how to disable them.
####
--- a/python.md
+++ b/python.md
@@ -969,7 +969,7 @@
)
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
- * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff.
+ * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1` to retry capacity errors indefinitely.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
* `CLAUDE_ENABLE_STREAM_WATCHDOG=1` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. When `CLAUDE_ENABLE_STREAM_WATCHDOG` is unset, the default is server-controlled on the direct Anthropic API and off on other providers. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
--- a/python.md
+++ b/python.md
@@ -1167,7 +1167,7 @@
`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
-`disallowedTools`| No| Array of tool names to remove from the agent’s tool set
+`disallowedTools`| No| Array of tool names to remove from the agent’s tool set. MCP server-level patterns are also accepted: `mcp__server` or `mcp__server__*` removes every tool from that server, and `mcp__*` removes every MCP tool from any server
`model`| No| Model override for this agent. Accepts an alias such as `"sonnet"`, `"opus"`, `"haiku"`, or `"inherit"`, or a full model ID. If omitted, uses the main model
`skills`| No| List of skill names to preload into the agent’s context at startup. Unlisted skills remain invocable through the Skill tool
`memory`| No| Memory source for this agent: `"user"`, `"project"`, or `"local"`
--- a/python.md
+++ b/python.md
@@ -921,7 +921,7 @@
`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for accuracy caveats
`disallowed_tools`| `list[str]`| `[]`| Tools to deny. A bare name such as `"Bash"` removes the tool from Claude’s context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`. See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
`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
+`model`| `str | None`| `None`| Claude model alias or full model name. See [accepted values and provider-specific IDs](</docs/en/model-config#available-models>)
`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
@@ -948,7 +948,7 @@
`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. When set, the SDK adds the Skill tool to `allowed_tools` automatically. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
`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`| `EffortLevel` ` | None`| `None`| Effort level for thinking depth
+`effort`| `EffortLevel` ` | None`| `None`| Effort level for thinking depth. See [adjust the effort level](</docs/en/model-config#adjust-effort-level>)
`session_store`| [`SessionStore`](</docs/en/agent-sdk/session-storage#the-sessionstore-interface>) ` | None`| `None`| Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](</docs/en/agent-sdk/session-storage>)
`session_store_flush`| `Literal["batched", "eager"]`| `"batched"`| When to flush mirrored transcript entries to `session_store`. `"batched"` flushes once per turn or when the buffer fills; `"eager"` triggers a background flush after every frame. Ignored when `session_store` is `None`
@@ -971,7 +971,7 @@
* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff.
* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
- * `CLAUDE_ENABLE_STREAM_WATCHDOG=1` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. Off by default. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
+ * `CLAUDE_ENABLE_STREAM_WATCHDOG=1` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. When `CLAUDE_ENABLE_STREAM_WATCHDOG` is unset, the default is server-controlled on the direct Anthropic API and off on other providers. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
###
@@ -1027,7 +1027,7 @@
---|---|---
`"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`
+`"local"`| Local project settings (not version controlled)| `.claude/settings.local.json`
####
@@ -1191,9 +1191,9 @@
PermissionMode = Literal[
"default", # Standard permission behavior
"acceptEdits", # Auto-accept file edits
- "plan", # Planning mode - read-only tools only
+ "plan", # Planning mode - explore without editing
"dontAsk", # Deny anything not pre-approved instead of prompting
- "bypassPermissions", # Bypass all permission checks (use with caution)
+ "bypassPermissions", # Bypass permission checks; explicit ask rules still prompt (use with caution)
]
###
@@ -1208,7 +1208,7 @@
"low", # Minimal thinking, fastest responses
"medium", # Moderate thinking
"high", # Deep reasoning
- "xhigh", # Extended reasoning (Opus 4.7 only; falls back to "high" on other models)
+ "xhigh", # Extended reasoning (Opus 4.8 and Opus 4.7; falls back to "high" on other models)
"max", # Maximum effort
]
@@ -1424,7 +1424,7 @@
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, Claude Opus 4.6, or Claude Opus 4.7](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
+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, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
###
@@ -3640,7 +3640,7 @@
* **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.
+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 approval prompts (an explicit [`ask` rule](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) still forces one). This combination effectively allows the model to escape sandbox isolation silently.
##
--- a/python.md
+++ b/python.md
@@ -1697,6 +1697,13 @@
api_error_status: int | None = None
uuid: str | None = None
+The `subtype` field determines which other fields are populated. It is one of `"success"`, `"error_during_execution"`, `"error_max_turns"`, `"error_max_budget_usd"`, or `"error_max_structured_output_retries"`. The Python dataclass flattens all variants into one shape, so fields that don’t apply to the returned subtype are `None`. Several fields carry diagnostic detail when the conversation ends on an error:
+
+ * `is_error`: `True` when the conversation ended in an error state. Always `True` on the `error_*` subtypes. On `subtype="success"` it is `True` when the final model request failed, meaning the agent loop completed but the last API call returned an error.
+ * `api_error_status`: the HTTP status code of the terminating API error. `None` when the turn ended without one. Populated only on `subtype="success"`.
+ * `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.
+ * `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.
+
The `usage` dict contains the following keys when present:
Key| Type| Description
--- a/python.md
+++ b/python.md
@@ -1,9 +1,3 @@
-> ## Documentation Index
->
-> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
->
-> Use this file to discover all available pages before exploring further.
-
##
--- a/python.md
+++ b/python.md
@@ -919,7 +919,7 @@
`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
-`strict_mcp_config`| `bool`| `False`| When `True`, use only the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, and plugin-provided MCP servers. Maps to the CLI `--strict-mcp-config` flag
+`strict_mcp_config`| `bool`| `False`| When `True`, use only the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, plugin-provided MCP servers, and [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>). Maps to the CLI `--strict-mcp-config` flag
`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
@@ -951,7 +951,7 @@
`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` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
-`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. When set, the SDK enables the Skill tool automatically without listing it in `allowed_tools`. See [Skills](</docs/en/agent-sdk/skills>)
+`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. When set, the SDK adds the Skill tool to `allowed_tools` automatically. If you also pass `tools`, include `"Skill"` in that list. See [Skills](</docs/en/agent-sdk/skills>)
`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`| `EffortLevel` ` | None`| `None`| Effort level for thinking depth
@@ -3066,7 +3066,7 @@
ListMcpResources
-**Tool name:** `ListMcpResources` **Input:**
+**Tool name:** `ListMcpResourcesTool` **Input:**
{
"server": str | None # Optional server name to filter resources by
@@ -3093,7 +3093,7 @@
ReadMcpResource
-**Tool name:** `ReadMcpResource` **Input:**
+**Tool name:** `ReadMcpResourceTool` **Input:**
{
"server": str, # The MCP server name
@@ -3527,7 +3527,7 @@
`SandboxNetworkConfig`
-Network-specific configuration for sandbox mode.
+Network-specific configuration for sandbox mode. These settings apply to sandboxed Bash commands when `enabled` is `True` in the parent `SandboxSettings`. They do not restrict the WebFetch tool, which uses [permission rules](</docs/en/permissions#webfetch>) instead.
class SandboxNetworkConfig(TypedDict, total=False):
allowedDomains: list[str]
--- a/python.md
+++ b/python.md
@@ -2076,7 +2076,7 @@
"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`, `WorktreeRemove`, and `PostToolBatch`.
+The TypeScript SDK supports additional hook events not yet available in Python: `SessionStart`, `SessionEnd`, `Setup`, `TeammateIdle`, `TaskCompleted`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `PostToolBatch`, and `MessageDisplay`.
###
@@ -3497,6 +3497,8 @@
`ignoreViolations`| `SandboxIgnoreViolations`| `None`| Configure which sandbox violations to ignore
`enableWeakerNestedSandbox`| `bool`| `False`| Enable a weaker nested sandbox for compatibility
+The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. By default, when `enabled` is `True` but the sandbox can’t start, commands run unsandboxed with a warning on stderr. This default differs from the TypeScript SDK, where `failIfUnavailable` defaults to `true`.Set `"failIfUnavailable": True` in your sandbox settings to stop instead. The key isn’t declared on `SandboxSettings` yet, but the SDK forwards it to Claude Code, which honors it. `query()` then reports a `ResultMessage` with `subtype="error_during_execution"` and the reason in `errors`. Watch for that subtype rather than expecting `query()` to raise before yielding messages.
+
####
--- a/python.md
+++ b/python.md
@@ -925,7 +925,7 @@
`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`| Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for accuracy caveats
-`disallowed_tools`| `list[str]`| `[]`| Tools to always deny. Deny rules are checked first and override `allowed_tools` and `permission_mode` (including `bypassPermissions`)
+`disallowed_tools`| `list[str]`| `[]`| Tools to deny. A bare name such as `"Bash"` removes the tool from Claude’s context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`. See [Permissions](</docs/en/agent-sdk/permissions#allow-and-deny-rules>)
`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
Show diff (145 lines)
--- a/python.md
+++ b/python.md
@@ -28,21 +28,21 @@
Feature| `query()`| `ClaudeSDKClient`
---|---|---
-**Session**| Creates new session each time| Reuses same session
+**Session**| Creates a new session by default| 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
+**Continue Chat**| Manual via `continue_conversation` or `resume`| ✅ Automatic
**Use Case**| One-off tasks| Continuous conversations
###
-When to use `query()` (new session each time)
+When to use `query()` (one-off tasks)
**Best for:**
@@ -77,7 +77,7 @@
`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.
+Creates a new session for each interaction with Claude Code by default. Returns an async iterator that yields messages as they arrive. Each call to `query()` starts fresh with no memory of previous interactions unless you pass `continue_conversation=True` or `resume` in `ClaudeAgentOptions`. See [Sessions](</docs/en/agent-sdk/sessions>).
async def query(
*,
@@ -908,7 +908,7 @@
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", "xhigh", "max"] | None = None
+ effort: EffortLevel | None = None
enable_file_checkpointing: bool = False
session_store: SessionStore | None = None
session_store_flush: SessionStoreFlushMode = "batched"
@@ -954,7 +954,7 @@
`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. When set, the SDK enables the Skill tool automatically without listing it in `allowed_tools`. See [Skills](</docs/en/agent-sdk/skills>)
`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", "xhigh", "max"] | None`| `None`| Effort level for thinking depth
+`effort`| `EffortLevel` ` | None`| `None`| Effort level for thinking depth
`session_store`| [`SessionStore`](</docs/en/agent-sdk/session-storage#the-sessionstore-interface>) ` | None`| `None`| Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](</docs/en/agent-sdk/session-storage>)
`session_store_flush`| `Literal["batched", "eager"]`| `"batched"`| When to flush mirrored transcript entries to `session_store`. `"batched"` flushes once per turn or when the buffer fills; `"eager"` triggers a background flush after every frame. Ignored when `session_store` is `None`
@@ -1165,7 +1165,7 @@
initialPrompt: str | None = None
maxTurns: int | None = None
background: bool | None = None
- effort: Literal["low", "medium", "high", "xhigh", "max"] | int | None = None
+ effort: EffortLevel | int | None = None
permissionMode: PermissionMode | None = None
Field| Required| Description
@@ -1181,7 +1181,7 @@
`initialPrompt`| No| Auto-submitted as the first user turn when this agent runs as the main thread agent
`maxTurns`| No| Maximum number of agentic turns before the agent stops
`background`| No| Run this agent as a non-blocking background task when invoked
-`effort`| No| Reasoning effort level for this agent. Accepts a named level or an integer
+`effort`| No| Reasoning effort level for this agent. Accepts a named level or an integer. See `EffortLevel`
`permissionMode`| No| Permission mode for tool execution within this agent. See `PermissionMode`
`AgentDefinition` field names use camelCase, such as `disallowedTools`, `permissionMode`, and `maxTurns`. These names map directly to the wire format shared with the TypeScript SDK. This differs from `ClaudeAgentOptions`, which uses Python snake_case for the equivalent top-level fields such as `disallowed_tools` and `permission_mode`. Because `AgentDefinition` is a dataclass, passing a snake_case keyword raises a `TypeError` at construction time.
@@ -1200,6 +1200,22 @@
"plan", # Planning mode - read-only tools only
"dontAsk", # Deny anything not pre-approved instead of prompting
"bypassPermissions", # Bypass all permission checks (use with caution)
+ ]
+
+###
+
+
+
+`EffortLevel`
+
+Effort levels for guiding thinking depth.
+
+ EffortLevel = Literal[
+ "low", # Minimal thinking, fastest responses
+ "medium", # Moderate thinking
+ "high", # Deep reasoning
+ "xhigh", # Extended reasoning (Opus 4.7 only; falls back to "high" on other models)
+ "max", # Maximum effort
]
###
@@ -1368,12 +1384,16 @@
Controls extended thinking behavior. A union of three configurations:
+ ThinkingDisplay = Literal["summarized", "omitted"]
+
class ThinkingConfigAdaptive(TypedDict):
type: Literal["adaptive"]
+ display: NotRequired[ThinkingDisplay]
class ThinkingConfigEnabled(TypedDict):
type: Literal["enabled"]
budget_tokens: int
+ display: NotRequired[ThinkingDisplay]
class ThinkingConfigDisabled(TypedDict):
type: Literal["disabled"]
@@ -1382,11 +1402,11 @@
Variant| Fields| Description
---|---|---
-`adaptive`| `type`| Claude adaptively decides when to think
-`enabled`| `type`, `budget_tokens`| Enable thinking with a specific token budget
+`adaptive`| `type`, `display`| Claude adaptively decides when to think
+`enabled`| `type`, `budget_tokens`, `display`| 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`:
+The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `ThinkingBlock` outputs. 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
@@ -2424,7 +2444,7 @@
hookEventName: Literal["PostToolUse"]
additionalContext: NotRequired[str]
updatedToolOutput: NotRequired[Any]
- updatedMCPToolOutput: NotRequired[Any]
+ updatedMCPToolOutput: NotRequired[Any] # Deprecated: use updatedToolOutput, which works for all tools
class PostToolUseFailureHookSpecificOutput(TypedDict):
hookEventName: Literal["PostToolUseFailure"]
@@ -2860,7 +2880,7 @@
**Tool name:** `TodoWrite`
-`TodoWrite` is deprecated and will be removed in a future release. Use `TaskCreate`, `TaskGet`, `TaskUpdate`, and `TaskList` instead. Set `CLAUDE_CODE_ENABLE_TASKS=1` to opt in. See [Migrate to Task tools](</docs/en/agent-sdk/todo-tracking#migrate-to-task-tools>) for how monitoring code changes.
+As of Claude Code v2.1.142, `TodoWrite` is disabled by default. Use `TaskCreate`, `TaskGet`, `TaskUpdate`, and `TaskList` instead. See [Migrate to Task tools](</docs/en/agent-sdk/todo-tracking#migrate-to-task-tools>) to update your monitoring code, or set `CLAUDE_CODE_ENABLE_TASKS=0` to revert to `TodoWrite`.
**Input:**
--- a/python.md
+++ b/python.md
@@ -2077,7 +2077,7 @@
Returns a `HookJSONOutput` that may contain:
* `decision`: `"block"` to block the action
- * `systemMessage`: System message to add to the transcript
+ * `systemMessage`: warning message shown to the user
* `hookSpecificOutput`: Hook-specific output data
###
Show diff (131 lines)
--- a/python.md
+++ b/python.md
@@ -1017,7 +1017,7 @@
`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
-`exclude_dynamic_sections`| No| Move per-session context such as working directory, git status, and memory paths from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>)
+`exclude_dynamic_sections`| No| Move per-session context such as working directory, the git-repo flag, and auto-memory paths from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>)
###
@@ -2858,7 +2858,11 @@
TodoWrite
-**Tool name:** `TodoWrite` **Input:**
+**Tool name:** `TodoWrite`
+
+`TodoWrite` is deprecated and will be removed in a future release. Use `TaskCreate`, `TaskGet`, `TaskUpdate`, and `TaskList` instead. Set `CLAUDE_CODE_ENABLE_TASKS=1` to opt in. See [Migrate to Task tools](</docs/en/agent-sdk/todo-tracking#migrate-to-task-tools>) for how monitoring code changes.
+
+**Input:**
{
"todos": [
@@ -2875,6 +2879,106 @@
{
"message": str, # Success message
"stats": {"total": int, "pending": int, "in_progress": int, "completed": int},
+ }
+
+###
+
+
+
+TaskCreate
+
+**Tool name:** `TaskCreate` **Input:**
+
+ {
+ "subject": str, # Short task title
+ "description": str, # Detailed task body
+ "activeForm": str | None, # Present-tense label shown while in progress
+ "metadata": dict | None, # Arbitrary caller metadata
+ }
+
+**Output:**
+
+ {
+ "task": {"id": str, "subject": str}, # Created task with assigned ID
+ }
+
+###
+
+
+
+TaskUpdate
+
+**Tool name:** `TaskUpdate` **Input:**
+
+ {
+ "taskId": str, # ID of the task to patch
+ "status": Literal["pending", "in_progress", "completed", "deleted"] | None,
+ "subject": str | None,
+ "description": str | None,
+ "activeForm": str | None,
+ "addBlocks": list[str] | None, # Task IDs this task now blocks
+ "addBlockedBy": list[str] | None, # Task IDs that now block this task
+ "owner": str | None,
+ "metadata": dict | None,
+ }
+
+**Output:**
+
+ {
+ "success": bool,
+ "taskId": str,
+ "updatedFields": list[str], # Names of fields that changed
+ "error": str | None,
+ "statusChange": {"from": str, "to": str} | None,
+ }
+
+###
+
+
+
+TaskGet
+
+**Tool name:** `TaskGet` **Input:**
+
+ {
+ "taskId": str, # ID of the task to read
+ }
+
+**Output:**
+
+ {
+ "task": {
+ "id": str,
+ "subject": str,
+ "description": str,
+ "status": Literal["pending", "in_progress", "completed"],
+ "blocks": list[str],
+ "blockedBy": list[str],
+ } | None, # None when the ID is not found
+ }
+
+###
+
+
+
+TaskList
+
+**Tool name:** `TaskList` **Input:**
+
+ {}
+
+**Output:**
+
+ {
+ "tasks": [
+ {
+ "id": str,
+ "subject": str,
+ "status": Literal["pending", "in_progress", "completed"],
+ "owner": str | None,
+ "blockedBy": list[str],
+ }
+ ],
}
###
--- a/python.md
+++ b/python.md
@@ -2822,10 +2822,12 @@
**Output:**
{
- "response": str, # AI model's response to the prompt
+ "bytes": int, # Size of the fetched content in bytes
+ "code": int, # HTTP response code
+ "codeText": str, # HTTP response code text
+ "result": str, # Processed result from applying the prompt to the content
+ "durationMs": int, # Time to fetch and process the content, in milliseconds
"url": str, # URL that was fetched
- "final_url": str | None, # Final URL after redirects
- "status_code": int | None, # HTTP status code
}
###
@@ -2845,9 +2847,9 @@
**Output:**
{
- "results": [{"title": str, "url": str, "snippet": str, "metadata": dict | None}],
- "total_results": int,
- "query": str,
+ "query": str, # The search query
+ "results": list[str | {"tool_use_id": str, "content": list[{"title": str, "url": str}]}],
+ "durationSeconds": float, # Search duration in seconds
}
###
--- a/python.md
+++ b/python.md
@@ -2574,7 +2574,9 @@
"multiSelect": bool, # Set to true to allow multiple selections
}
],
- "answers": dict | None, # User answers populated by the permission system
+ "answers": dict[str, str | list[str]] | None,
+ # User answers populated by the permission system. Multi-select
+ # answers may be a list of labels or a comma-joined string
}
**Output:**
--- a/python.md
+++ b/python.md
@@ -951,6 +951,7 @@
`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` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
+`skills`| `list[str] | Literal["all"] | None`| `None`| Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. When set, the SDK enables the Skill tool automatically without listing it in `allowed_tools`. See [Skills](</docs/en/agent-sdk/skills>)
`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", "xhigh", "max"] | None`| `None`| Effort level for thinking depth
@@ -1174,7 +1175,7 @@
`tools`| No| Array of allowed tool names. If omitted, inherits all tools
`disallowedTools`| No| Array of tool names to remove from the agent’s tool set
`model`| No| Model override for this agent. Accepts an alias such as `"sonnet"`, `"opus"`, `"haiku"`, or `"inherit"`, or a full model ID. If omitted, uses the main model
-`skills`| No| List of skill names available to this agent
+`skills`| No| List of skill names to preload into the agent’s context at startup. Unlisted skills remain invocable through the Skill tool
`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
`initialPrompt`| No| Auto-submitted as the first user turn when this agent runs as the main thread agent
@@ -1670,13 +1671,17 @@
is_error: bool
num_turns: int
session_id: str
+ stop_reason: str | None = None
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
+ permission_denials: list[Any] | None = None
deferred_tool_use: DeferredToolUse | None = None
+ errors: list[str] | None = None
+ api_error_status: int | None = None
+ uuid: str | None = None
The `usage` dict contains the following keys when present:
Show diff (140 lines)
--- a/python.md
+++ b/python.md
@@ -875,6 +875,7 @@
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)
+ strict_mcp_config: bool = False
permission_mode: PermissionMode | None = None
continue_conversation: bool = False
resume: str | None = None
@@ -899,6 +900,7 @@
hooks: dict[HookEvent, list[HookMatcher]] | None = None
user: str | None = None
include_partial_messages: bool = False
+ include_hook_events: bool = False
fork_session: bool = False
agents: dict[str, AgentDefinition] | None = None
setting_sources: list[SettingSource] | None = None
@@ -906,7 +908,7 @@
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
+ effort: Literal["low", "medium", "high", "xhigh", "max"] | None = None
enable_file_checkpointing: bool = False
session_store: SessionStore | None = None
session_store_flush: SessionStoreFlushMode = "batched"
@@ -917,6 +919,7 @@
`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
+`strict_mcp_config`| `bool`| `False`| When `True`, use only the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, and plugin-provided MCP servers. Maps to the CLI `--strict-mcp-config` flag
`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
@@ -933,7 +936,7 @@
`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 merged on top of the inherited process environment. See [Environment variables](</docs/en/env-vars>) for variables the underlying CLI reads
+`env`| `dict[str, str]`| `{}`| Environment variables merged on top of the inherited process environment. See [Environment variables](</docs/en/env-vars>) for variables the underlying CLI reads, and Handle slow or stalled API responses for timeout-related 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
@@ -942,6 +945,7 @@
`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
+`include_hook_events`| `bool`| `False`| Include hook lifecycle events in the message stream as `HookEventMessage` objects
`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
@@ -949,9 +953,30 @@
`setting_sources`| `list[SettingSource] | None`| `None` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
`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
+`effort`| `Literal["low", "medium", "high", "xhigh", "max"] | None`| `None`| Effort level for thinking depth
`session_store`| [`SessionStore`](</docs/en/agent-sdk/session-storage#the-sessionstore-interface>) ` | None`| `None`| Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](</docs/en/agent-sdk/session-storage>)
`session_store_flush`| `Literal["batched", "eager"]`| `"batched"`| When to flush mirrored transcript entries to `session_store`. `"batched"` flushes once per turn or when the buffer fills; `"eager"` triggers a background flush after every frame. Ignored when `session_store` is `None`
+
+####
+
+
+
+Handle slow or stalled API responses
+
+The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through `ClaudeAgentOptions.env`:
+
+ options = ClaudeAgentOptions(
+ env={
+ "API_TIMEOUT_MS": "120000",
+ "CLAUDE_CODE_MAX_RETRIES": "2",
+ "CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS": "120000",
+ },
+ )
+
+ * `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
+ * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff.
+ * `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
+ * `CLAUDE_ENABLE_STREAM_WATCHDOG=1` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. Off by default. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.
###
@@ -1139,7 +1164,7 @@
initialPrompt: str | None = None
maxTurns: int | None = None
background: bool | None = None
- effort: Literal["low", "medium", "high", "max"] | int | None = None
+ effort: Literal["low", "medium", "high", "xhigh", "max"] | int | None = None
permissionMode: PermissionMode | None = None
Field| Required| Description
@@ -1208,11 +1233,21 @@
class ToolPermissionContext:
signal: Any | None = None # Future: abort signal support
suggestions: list[PermissionUpdate] = field(default_factory=list)
+ blocked_path: str | None = None
+ decision_reason: str | None = None
+ title: str | None = None
+ display_name: str | None = None
+ description: str | None = None
Field| Type| Description
---|---|---
`signal`| `Any | None`| Reserved for future abort signal support
`suggestions`| `list[PermissionUpdate]`| Permission update suggestions from the CLI. Bash prompts include a suggestion with the `localSettings` destination, so returning it in `updated_permissions` writes the rule to `.claude/settings.local.json` and persists across sessions.
+`blocked_path`| `str | None`| File path that triggered the permission request, when applicable. For example, when a Bash command tries to access a path outside allowed directories
+`decision_reason`| `str | None`| Reason this permission request was triggered. Forwarded from a PreToolUse hook’s `permissionDecisionReason` when the hook returned `"ask"`
+`title`| `str | None`| Full permission prompt sentence, such as `Claude wants to read foo.txt`. Use as the primary prompt text when present
+`display_name`| `str | None`| Short noun phrase for the tool action, such as `Read file`, suitable for button labels
+`description`| `str | None`| Human-readable subtitle for the permission UI
###
@@ -1641,6 +1676,7 @@
stop_reason: str | None = None
structured_output: Any = None
model_usage: dict[str, Any] | None = None
+ deferred_tool_use: DeferredToolUse | None = None
The `usage` dict contains the following keys when present:
@@ -2374,7 +2410,7 @@
class PreToolUseHookSpecificOutput(TypedDict):
hookEventName: Literal["PreToolUse"]
- permissionDecision: NotRequired[Literal["allow", "deny", "ask"]]
+ permissionDecision: NotRequired[Literal["allow", "deny", "ask", "defer"]]
permissionDecisionReason: NotRequired[str]
updatedInput: NotRequired[dict[str, Any]]
additionalContext: NotRequired[str]
@@ -2382,6 +2418,7 @@
class PostToolUseHookSpecificOutput(TypedDict):
hookEventName: Literal["PostToolUse"]
additionalContext: NotRequired[str]
+ updatedToolOutput: NotRequired[Any]
updatedMCPToolOutput: NotRequired[Any]
class PostToolUseFailureHookSpecificOutput(TypedDict):
--- a/python.md
+++ b/python.md
@@ -909,6 +909,7 @@
effort: Literal["low", "medium", "high", "max"] | None = None
enable_file_checkpointing: bool = False
session_store: SessionStore | None = None
+ session_store_flush: SessionStoreFlushMode = "batched"
Property| Type| Default| Description
---|---|---|---
@@ -949,7 +950,8 @@
`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
-`session_store`| [`SessionStore`](</docs/en/agent-sdk/session-storage#the-session-store-interface>) ` | None`| `None`| Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](</docs/en/agent-sdk/session-storage>)
+`session_store`| [`SessionStore`](</docs/en/agent-sdk/session-storage#the-sessionstore-interface>) ` | None`| `None`| Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](</docs/en/agent-sdk/session-storage>)
+`session_store_flush`| `Literal["batched", "eager"]`| `"batched"`| When to flush mirrored transcript entries to `session_store`. `"batched"` flushes once per turn or when the buffer fills; `"eager"` triggers a background flush after every frame. Ignored when `session_store` is `None`
###
@@ -1169,7 +1171,7 @@
PermissionMode = Literal[
"default", # Standard permission behavior
"acceptEdits", # Auto-accept file edits
- "plan", # Planning mode - no execution
+ "plan", # Planning mode - read-only tools only
"dontAsk", # Deny anything not pre-approved instead of prompting
"bypassPermissions", # Bypass all permission checks (use with caution)
]
@@ -1210,7 +1212,7 @@
Field| Type| Description
---|---|---
`signal`| `Any | None`| Reserved for future abort signal support
-`suggestions`| `list[PermissionUpdate]`| Permission update suggestions from the CLI
+`suggestions`| `list[PermissionUpdate]`| Permission update suggestions from the CLI. Bash prompts include a suggestion with the `localSettings` destination, so returning it in `updated_permissions` writes the rule to `.claude/settings.local.json` and persists across sessions.
###
@@ -1649,7 +1651,7 @@
`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:
+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#modelusage>) type:
Key| Type| Description
---|---|---
--- a/python.md
+++ b/python.md
@@ -3359,9 +3359,10 @@
allowedDomains: list[str]
deniedDomains: list[str]
allowManagedDomainsOnly: bool
- allowLocalBinding: bool
allowUnixSockets: list[str]
allowAllUnixSockets: bool
+ allowLocalBinding: bool
+ allowMachLookup: list[str]
httpProxyPort: int
socksProxyPort: int
@@ -3370,9 +3371,10 @@
`allowedDomains`| `list[str]`| `[]`| Domain names that sandboxed processes can access
`deniedDomains`| `list[str]`| `[]`| Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains`
`allowManagedDomainsOnly`| `bool`| `False`| Managed-settings only: when set in managed settings, ignore `allowedDomains` from non-managed settings sources. Has no effect when set via SDK options
-`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
+`allowLocalBinding`| `bool`| `False`| Allow processes to bind to local ports (e.g., for dev servers)
+`allowMachLookup`| `list[str]`| `[]`| macOS only: XPC/Mach service names to allow. Supports a trailing wildcard
`httpProxyPort`| `int`| `None`| HTTP proxy port for network requests
`socksProxyPort`| `int`| `None`| SOCKS proxy port for network requests
--- a/python.md
+++ b/python.md
@@ -1,3 +1,9 @@
+> ## Documentation Index
+>
+> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
+>
+> Use this file to discover all available pages before exploring further.
+
##
@@ -3319,14 +3325,6 @@
`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.
-
####
@@ -3358,6 +3356,9 @@
Network-specific configuration for sandbox mode.
class SandboxNetworkConfig(TypedDict, total=False):
+ allowedDomains: list[str]
+ deniedDomains: list[str]
+ allowManagedDomainsOnly: bool
allowLocalBinding: bool
allowUnixSockets: list[str]
allowAllUnixSockets: bool
@@ -3366,11 +3367,16 @@
Property| Type| Default| Description
---|---|---|---
+`allowedDomains`| `list[str]`| `[]`| Domain names that sandboxed processes can access
+`deniedDomains`| `list[str]`| `[]`| Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains`
+`allowManagedDomainsOnly`| `bool`| `False`| Managed-settings only: when set in managed settings, ignore `allowedDomains` from non-managed settings sources. Has no effect when set via SDK options
`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
+
+The built-in sandbox proxy enforces the network allowlist based on the requested hostname and does not terminate or inspect TLS traffic, so techniques such as [domain fronting](<https://en.wikipedia.org/wiki/Domain_fronting>) can potentially bypass it. See [Sandboxing security limitations](</docs/en/sandboxing#security-limitations>) for details and [Secure deployment](</docs/en/agent-sdk/secure-deployment#traffic-forwarding>) for configuring a TLS-terminating proxy.
###
--- a/python.md
+++ b/python.md
@@ -926,7 +926,7 @@
`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
+`env`| `dict[str, str]`| `{}`| Environment variables merged on top of the inherited process environment. See [Environment variables](</docs/en/env-vars>) for variables the underlying CLI reads
`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
@@ -2007,7 +2007,7 @@
"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`.
+The TypeScript SDK supports additional hook events not yet available in Python: `SessionStart`, `SessionEnd`, `Setup`, `TeammateIdle`, `TaskCompleted`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, and `PostToolBatch`.
###
--- a/python.md
+++ b/python.md
@@ -900,8 +900,9 @@
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", "xhigh", "max"] | None = None
+ effort: Literal["low", "medium", "high", "max"] | None = None
enable_file_checkpointing: bool = False
+ session_store: SessionStore | None = None
Property| Type| Default| Description
---|---|---|---
@@ -941,7 +942,8 @@
`setting_sources`| `list[SettingSource] | None`| `None` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
`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", "xhigh", "max"] | None`| `None`| Effort level for thinking depth
+`effort`| `Literal["low", "medium", "high", "max"] | None`| `None`| Effort level for thinking depth
+`session_store`| [`SessionStore`](</docs/en/agent-sdk/session-storage#the-session-store-interface>) ` | None`| `None`| Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](</docs/en/agent-sdk/session-storage>)
###
@@ -1121,20 +1123,34 @@
description: str
prompt: str
tools: list[str] | None = None
- model: Literal["sonnet", "opus", "haiku", "inherit"] | None = None
+ disallowedTools: list[str] | None = None
+ model: str | None = None
skills: list[str] | None = None
memory: Literal["user", "project", "local"] | None = None
mcpServers: list[str | dict[str, Any]] | None = None
+ initialPrompt: str | None = None
+ maxTurns: int | None = None
+ background: bool | None = None
+ effort: Literal["low", "medium", "high", "max"] | int | None = None
+ permissionMode: PermissionMode | 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
+`disallowedTools`| No| Array of tool names to remove from the agent’s tool set
+`model`| No| Model override for this agent. Accepts an alias such as `"sonnet"`, `"opus"`, `"haiku"`, or `"inherit"`, or a full model ID. 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
+`initialPrompt`| No| Auto-submitted as the first user turn when this agent runs as the main thread agent
+`maxTurns`| No| Maximum number of agentic turns before the agent stops
+`background`| No| Run this agent as a non-blocking background task when invoked
+`effort`| No| Reasoning effort level for this agent. Accepts a named level or an integer
+`permissionMode`| No| Permission mode for tool execution within this agent. See `PermissionMode`
+
+`AgentDefinition` field names use camelCase, such as `disallowedTools`, `permissionMode`, and `maxTurns`. These names map directly to the wire format shared with the TypeScript SDK. This differs from `ClaudeAgentOptions`, which uses Python snake_case for the equivalent top-level fields such as `disallowed_tools` and `permission_mode`. Because `AgentDefinition` is a dataclass, passing a snake_case keyword raises a `TypeError` at construction time.
###
Show diff (119 lines)
--- a/python.md
+++ b/python.md
@@ -900,7 +900,7 @@
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
+ effort: Literal["low", "medium", "high", "xhigh", "max"] | None = None
enable_file_checkpointing: bool = False
Property| Type| Default| Description
@@ -913,7 +913,7 @@
`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
+`max_budget_usd`| `float | None`| `None`| Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for accuracy caveats
`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
@@ -938,10 +938,10 @@
`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
+`setting_sources`| `list[SettingSource] | None`| `None` (CLI defaults: all sources)| Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>)
`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
+`effort`| `Literal["low", "medium", "high", "xhigh", "max"] | None`| `None`| Effort level for thinking depth
###
@@ -1005,7 +1005,7 @@
Default behavior
-When `setting_sources` is **omitted** or **`None`** , the SDK does **not** load any filesystem settings. This provides isolation for SDK applications.
+When `setting_sources` is omitted or `None`, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. Managed policy settings are loaded in all cases. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read regardless of this option, and how to disable them.
####
@@ -1013,15 +1013,29 @@
Why use setting_sources
-**Load all filesystem settings (legacy behavior):**
-
- # Load all settings like SDK v0.0.x did
+**Disable filesystem settings:**
+
+ # Do not load user, project, or local settings from disk
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
+ setting_sources=[]
+ ),
+ ):
+ print(message)
+
+In Python SDK 0.1.59 and earlier, an empty list was treated the same as omitting the option, so `setting_sources=[]` did not disable filesystem settings. Upgrade to a newer release if you need an empty list to take effect. The TypeScript SDK is not affected.
+
+**Load all filesystem settings explicitly:**
+
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ async for message in query(
+ prompt="Analyze this code",
+ options=ClaudeAgentOptions(
+ setting_sources=["user", "project", "local"]
),
):
print(message)
@@ -1051,12 +1065,12 @@
**SDK-only applications:**
- # Define everything programmatically (default behavior)
- # No filesystem dependencies - setting_sources defaults to None
+ # Define everything programmatically.
+ # Pass [] to opt out of filesystem setting sources.
async for message in query(
prompt="Review this PR",
options=ClaudeAgentOptions(
- # setting_sources=None is the default, no need to specify
+ setting_sources=[],
agents={...},
mcp_servers={...},
allowed_tools=["Read", "Grep", "Glob"],
@@ -1074,7 +1088,7 @@
"type": "preset",
"preset": "claude_code", # Use Claude Code's system prompt
},
- setting_sources=["project"], # Required to load CLAUDE.md from project
+ setting_sources=["project"], # Loads CLAUDE.md from project
allowed_tools=["Read", "Write", "Edit"],
),
):
@@ -1092,7 +1106,7 @@
2. Project settings (`.claude/settings.json`)
3. User settings (`~/.claude/settings.json`)
-Programmatic options (like `agents`, `allowed_tools`) always override filesystem settings.
+Programmatic options such as `agents` and `allowed_tools` override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options.
###
@@ -1336,7 +1350,7 @@
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.
+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, Claude Opus 4.6, or Claude Opus 4.7](<https://platform.claude.com/docs/en/about-claude/models/overview>), which include 1M context at standard pricing with no beta header required.
###
--- a/python.md
+++ b/python.md
@@ -974,12 +974,14 @@
type: Literal["preset"]
preset: Literal["claude_code"]
append: NotRequired[str]
+ exclude_dynamic_sections: NotRequired[bool]
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
+`exclude_dynamic_sections`| No| Move per-session context such as working directory, git status, and memory paths from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>)
###
@@ -1620,7 +1622,7 @@
`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.
+`costUSD`| `float`| Estimated cost in USD for this model, computed client-side. See [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for billing caveats.
`contextWindow`| `int`| Context window size for this model.
`maxOutputTokens`| `int`| Maximum output token limit for this model.
@@ -2466,7 +2468,7 @@
{
"result": str, # Final result from the subagent
"usage": dict | None, # Token usage statistics
- "total_cost_usd": float | None, # Total cost in USD
+ "total_cost_usd": float | None, # Estimated total cost in USD
"duration_ms": int | None, # Execution duration in milliseconds
}
--- a/python.md
+++ b/python.md
@@ -1707,7 +1707,7 @@
`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.
+Emitted when a background task starts. A background task is anything tracked outside the main turn: a backgrounded Bash command, a Monitor watch, 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):
@@ -1725,7 +1725,7 @@
`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"`
+`task_type`| `str | None`| Which kind of background task: `"local_bash"` for background Bash and Monitor watches, `"local_agent"`, or `"remote_agent"`
###
@@ -1774,7 +1774,7 @@
`TaskNotificationMessage`
-Emitted when a task completes, fails, or is stopped.
+Emitted when a background task completes, fails, or is stopped. Background tasks include `run_in_background` Bash commands, Monitor watches, and background subagents.
@dataclass
class TaskNotificationMessage(SystemMessage):
@@ -2538,6 +2538,29 @@
+Monitor
+
+**Tool name:** `Monitor` Runs a background script and delivers each stdout line to Claude as an event so it can react without polling. Monitor follows the same permission rules as Bash. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for behavior and provider availability. **Input:**
+
+ {
+ "command": str, # Shell script; each stdout line is an event, exit ends the watch
+ "description": str, # Short description shown in notifications
+ "timeout_ms": int | None, # Kill after this deadline (default 300000, max 3600000)
+ "persistent": bool | None, # Run for the lifetime of the session; stop with TaskStop
+ }
+
+**Output:**
+
+ {
+ "taskId": str, # ID of the background monitor task
+ "timeoutMs": int, # Timeout deadline in milliseconds (0 when persistent)
+ "persistent": bool | None, # True when running until TaskStop or session end
+ }
+
+###
+
+
+
Edit
**Tool name:** `Edit` **Input:**
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