Agent SDK reference - Python changedagent-sdk/python
Nearest release: v2.1.284, published 6 hours before upstream edited the page. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.
Upstream edited this page at 28 Sep 2026 23:26 UTC, give or take a minute or two: the time comes from Anthropic’s own sitemap rather than from a commit. This site recorded the change at 28 Sep 2026 23:37 UTC.
Upstream edited
Recorded here
Lines+435added
Lines−435removed
From line
18
where the diff opens
First seen
14 Aug 2026
this site's first read of the page
Recorded edits33to this page, all time
The whole hunk
from line 18, old and new numbered
/
The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.
from line 18
1818
1919The Python SDK provides two ways to interact with Claude Code:
2020
21| Feature | `query()` | `ClaudeSDKClient` |
22| :------------------ | :--------------------------------------------- | :--------------------------------- |
23| **Session** | Creates a new session by default | Reuses same session |
24| **Conversation** | Single exchange | Multiple exchanges in same context |
25| **Connection** | Managed automatically | Manual control |
26| **Streaming Input** | ✅ Supported | ✅ Supported |
27| **Interrupts** | ❌ Not supported | ✅ Supported |
28| **Hooks** | ✅ Supported | ✅ Supported |
29| **Custom Tools** | ✅ Supported | ✅ Supported |
30| **Continue Chat** | Manual via `continue_conversation` or `resume` | ✅ Automatic |
31| **Use Case** | One-off tasks | Continuous conversations |
21| Feature | `query()` | `ClaudeSDKClient` |
22| :- | :- | :- |
23| **Session** | Creates a new session by default | Reuses same session |
24| **Conversation** | Single exchange | Multiple exchanges in same context |
25| **Connection** | Managed automatically | Manual control |
26| **Streaming Input** | ✅ Supported | ✅ Supported |
27| **Interrupts** | ❌ Not supported | ✅ Supported |
28| **Hooks** | ✅ Supported | ✅ Supported |
29| **Custom Tools** | ✅ Supported | ✅ Supported |
30| **Continue Chat** | Manual via `continue_conversation` or `resume` | ✅ Automatic |
31| **Use Case** | One-off tasks | Continuous conversations |
3232
3333Use `ClaudeSDKClient` for interactive applications such as chat interfaces, or when the next action depends on Claude's response.
3434
from line 51
5151
5252#### Parameters
5353
54| Parameter | Type | Description |
55| :---------- | :--------------------------- | :------------------------------------------------------------------------- |
56| `prompt` | `str \| AsyncIterable[dict]` | The input prompt as a string or async iterable for streaming mode |
57| `options` | `ClaudeAgentOptions \| None` | Optional configuration object (defaults to `ClaudeAgentOptions()` if None) |
58| `transport` | `Transport \| None` | Optional custom transport for communicating with the CLI process |
54| Parameter | Type | Description |
55| :- | :- | :- |
56| `prompt` | `str \| AsyncIterable[dict]` | The input prompt as a string or async iterable for streaming mode |
57| `options` | `ClaudeAgentOptions \| None` | Optional configuration object (defaults to `ClaudeAgentOptions()` if None) |
58| `transport` | `Transport \| None` | Optional custom transport for communicating with the CLI process |
5959
6060#### Returns
6161
from line 96
9696
9797#### Parameters
9898
99| Parameter | Type | Description |
100| :------------- | :---------------------------------------------- | :--------------------------------------------------------------------------------------------- |
101| `name` | `str` | Unique identifier for the tool |
102| `description` | `str` | Human-readable description of what the tool does |
103| `input_schema` | `type \| dict[str, Any]` | Schema defining the tool's input parameters. See [Input schema options](#input-schema-options) |
104| `annotations` | [`ToolAnnotations`](#toolannotations)` \| None` | Optional MCP tool annotations providing behavioral hints to clients |
99| Parameter | Type | Description |
100| :- | :- | :- |
101| `name` | `str` | Unique identifier for the tool |
102| `description` | `str` | Human-readable description of what the tool does |
103| `input_schema` | `type \| dict[str, Any]` | Schema defining the tool's input parameters. See [Input schema options](#input-schema-options) |
104| `annotations` | [`ToolAnnotations`](#toolannotations)` \| None` | Optional MCP tool annotations providing behavioral hints to clients |
105105
106106#### Input schema options
107107
from line 147
147147
148148All fields are optional. Clients shouldn't rely on the hints for security decisions.
149149
150| Field | Type | Default | Description |
151| :------------------- | :------------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
152| `title` | `str \| None` | `None` | Human-readable title for the tool |
153| `readOnlyHint` | `bool \| None` | `False` | If `True`, the tool does not modify its environment |
154| `destructiveHint` | `bool \| None` | `True` | If `True`, the tool may perform destructive updates (only meaningful when `readOnlyHint` is `False`) |
155| `idempotentHint` | `bool \| None` | `False` | If `True`, repeated calls with the same arguments have no additional effect (only meaningful when `readOnlyHint` is `False`) |
156| `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) |
157| `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) |
150| Field | Type | Default | Description |
151| :- | :- | :- | :- |
152| `title` | `str \| None` | `None` | Human-readable title for the tool |
153| `readOnlyHint` | `bool \| None` | `False` | If `True`, the tool does not modify its environment |
154| `destructiveHint` | `bool \| None` | `True` | If `True`, the tool may perform destructive updates (only meaningful when `readOnlyHint` is `False`) |
155| `idempotentHint` | `bool \| None` | `False` | If `True`, repeated calls with the same arguments have no additional effect (only meaningful when `readOnlyHint` is `False`) |
156| `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) |
157| `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) |
158158
159159```python theme={null}
160160from claude_agent_sdk import tool, ToolAnnotations
from line 185
185185
186186#### Parameters
187187
188| Parameter | Type | Default | Description |
189| :-------- | :------------------------------ | :-------- | :---------------------------------------------------- |
190| `name` | `str` | - | Unique identifier for the server |
191| `version` | `str` | `"1.0.0"` | Server version string |
192| `tools` | `list[SdkMcpTool[Any]] \| None` | `None` | List of tool functions created with `@tool` decorator |
188| Parameter | Type | Default | Description |
189| :- | :- | :- | :- |
190| `name` | `str` | - | Unique identifier for the server |
191| `version` | `str` | `"1.0.0"` | Server version string |
192| `tools` | `list[SdkMcpTool[Any]] \| None` | `None` | List of tool functions created with `@tool` decorator |
193193
194194#### Returns
195195
from line 239
239239
240240#### Parameters
241241
242| Parameter | Type | Default | Description |
243| :------------------ | :------------ | :------ | :----------------------------------------------------------------------------------------------- |
244| `directory` | `str \| None` | `None` | Directory to list sessions for. When omitted, returns sessions across all projects |
245| `limit` | `int \| None` | `None` | Maximum number of sessions to return |
246| `offset` | `int` | `0` | Number of sessions to skip from the start of the sorted results. Use with `limit` for pagination |
247| `include_worktrees` | `bool` | `True` | When `directory` is inside a git repository, include sessions from all worktree paths |
242| Parameter | Type | Default | Description |
243| :- | :- | :- | :- |
244| `directory` | `str \| None` | `None` | Directory to list sessions for. When omitted, returns sessions across all projects |
245| `limit` | `int \| None` | `None` | Maximum number of sessions to return |
246| `offset` | `int` | `0` | Number of sessions to skip from the start of the sorted results. Use with `limit` for pagination |
247| `include_worktrees` | `bool` | `True` | When `directory` is inside a git repository, include sessions from all worktree paths |
248248
249249#### Return type: `SDKSessionInfo`
250250
251| Property | Type | Description |
252| :-------------- | :------------ | :--------------------------------------------------------------------------------------- |
253| `session_id` | `str` | Unique session identifier |
254| `summary` | `str` | Display title: custom title, most recent prompt, auto-generated summary, or first prompt |
255| `last_modified` | `int` | Last modified time in milliseconds since epoch |
256| `file_size` | `int \| None` | Session file size in bytes (`None` for remote storage backends) |
257| `custom_title` | `str \| None` | Session title: the user-set title, or the auto-generated title when none is set |
258| `first_prompt` | `str \| None` | First meaningful user prompt in the session |
259| `git_branch` | `str \| None` | Git branch at the end of the session |
260| `cwd` | `str \| None` | Working directory for the session |
261| `tag` | `str \| None` | User-set session tag (see [`tag_session()`](#tag_session)) |
262| `created_at` | `int \| None` | Session creation time in milliseconds since epoch |
251| Property | Type | Description |
252| :- | :- | :- |
253| `session_id` | `str` | Unique session identifier |
254| `summary` | `str` | Display title: custom title, most recent prompt, auto-generated summary, or first prompt |
255| `last_modified` | `int` | Last modified time in milliseconds since epoch |
256| `file_size` | `int \| None` | Session file size in bytes (`None` for remote storage backends) |
257| `custom_title` | `str \| None` | Session title: the user-set title, or the auto-generated title when none is set |
258| `first_prompt` | `str \| None` | First meaningful user prompt in the session |
259| `git_branch` | `str \| None` | Git branch at the end of the session |
260| `cwd` | `str \| None` | Working directory for the session |
261| `tag` | `str \| None` | User-set session tag (see [`tag_session()`](#tag_session)) |
262| `created_at` | `int \| None` | Session creation time in milliseconds since epoch |
263263
264264#### Example
265265
from line 287
287287
288288#### Parameters
289289
290| Parameter | Type | Default | Description |
291| :----------- | :------------ | :------- | :---------------------------------------------------------------- |
292| `session_id` | `str` | required | The session ID to retrieve messages for |
293| `directory` | `str \| None` | `None` | Project directory to look in. When omitted, searches all projects |
294| `limit` | `int \| None` | `None` | Maximum number of messages to return |
295| `offset` | `int` | `0` | Number of messages to skip from the start |
290| Parameter | Type | Default | Description |
291| :- | :- | :- | :- |
292| `session_id` | `str` | required | The session ID to retrieve messages for |
293| `directory` | `str \| None` | `None` | Project directory to look in. When omitted, searches all projects |
294| `limit` | `int \| None` | `None` | Maximum number of messages to return |
295| `offset` | `int` | `0` | Number of messages to skip from the start |
296296
297297#### Return type: `SessionMessage`
298298
299| Property | Type | Description |
300| :------------------- | :----------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
301| `type` | `Literal["user", "assistant"]` | Message role |
302| `uuid` | `str` | Unique message identifier |
303| `session_id` | `str` | Session identifier |
304| `message` | `Any` | Raw message content |
305| `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 |
306| `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 |
299| Property | Type | Description |
300| :- | :- | :- |
301| `type` | `Literal["user", "assistant"]` | Message role |
302| `uuid` | `str` | Unique message identifier |
303| `session_id` | `str` | Session identifier |
304| `message` | `Any` | Raw message content |
305| `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 |
306| `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 |
307307
308308#### Example
309309
from line 330
330330
331331#### Parameters
332332
333| Parameter | Type | Default | Description |
334| :----------- | :------------ | :------- | :--------------------------------------------------------------------- |
335| `session_id` | `str` | required | UUID of the session to look up |
336| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |
333| Parameter | Type | Default | Description |
334| :- | :- | :- | :- |
335| `session_id` | `str` | required | UUID of the session to look up |
336| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |
337337
338338Returns [`SDKSessionInfo`](#return-type-sdksessioninfo), or `None` if the session is not found.
339339
from line 363
363363
364364#### Parameters
365365
366| Parameter | Type | Default | Description |
367| :----------- | :------------ | :------- | :--------------------------------------------------------------------- |
368| `session_id` | `str` | required | UUID of the session to rename |
369| `title` | `str` | required | New title. Must be non-empty after stripping whitespace |
370| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |
366| Parameter | Type | Default | Description |
367| :- | :- | :- | :- |
368| `session_id` | `str` | required | UUID of the session to rename |
369| `title` | `str` | required | New title. Must be non-empty after stripping whitespace |
370| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |
371371
372372Raises `ValueError` if `session_id` is not a valid UUID or `title` is empty; `FileNotFoundError` if the session cannot be found.
373373
from line 397
397397
398398#### Parameters
399399
400| Parameter | Type | Default | Description |
401| :----------- | :------------ | :------- | :--------------------------------------------------------------------- |
402| `session_id` | `str` | required | UUID of the session to tag |
403| `tag` | `str \| None` | required | Tag string, or `None` to clear. Unicode-sanitized before storing |
404| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |
400| Parameter | Type | Default | Description |
401| :- | :- | :- | :- |
402| `session_id` | `str` | required | UUID of the session to tag |
403| `tag` | `str \| None` | required | Tag string, or `None` to clear. Unicode-sanitized before storing |
404| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |
405405
406406Raises `ValueError` if `session_id` is not a valid UUID or `tag` is empty after sanitization; `FileNotFoundError` if the session cannot be found.
407407
from line 450
450450
451451#### Methods
452452
453| Method | Description |
454| :---------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
455| `__init__(options)` | Initialize the client with optional configuration |
456| `connect(prompt)` | Connect to Claude with an optional initial prompt or message stream |
457| `query(prompt, session_id)` | Send a new request in streaming mode |
458| `receive_messages()` | Receive all messages from Claude as an async iterator |
459| `receive_response()` | Receive messages until and including a ResultMessage |
460| `interrupt()` | Send interrupt signal (only works in streaming mode) |
461| `set_permission_mode(mode)` | Change the permission mode for the current session |
462| `set_model(model)` | Change the model for the current session. Pass `None` to reset to [Claude Code's default model](/docs/en/model-config) |
463| `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) |
464| `get_mcp_status()` | Get the status of all configured MCP servers. Returns [`McpStatusResponse`](#mcpstatusresponse) |
465| `reconnect_mcp_server(server_name)` | Retry connecting to an MCP server that failed or was disconnected |
466| `toggle_mcp_server(server_name, enabled)` | Enable or disable an MCP server mid-session. Disabling removes its tools |
467| `stop_task(task_id)` | Stop a running background task. A [`TaskNotificationMessage`](#tasknotificationmessage) with status `"stopped"` follows in the message stream |
468| `get_server_info()` | Get the server's initialization info, including available commands and output styles |
469| `disconnect()` | Disconnect from Claude |
453| Method | Description |
454| :- | :- |
455| `__init__(options)` | Initialize the client with optional configuration |
456| `connect(prompt)` | Connect to Claude with an optional initial prompt or message stream |
457| `query(prompt, session_id)` | Send a new request in streaming mode |
458| `receive_messages()` | Receive all messages from Claude as an async iterator |
459| `receive_response()` | Receive messages until and including a ResultMessage |
460| `interrupt()` | Send interrupt signal (only works in streaming mode) |
461| `set_permission_mode(mode)` | Change the permission mode for the current session |
462| `set_model(model)` | Change the model for the current session. Pass `None` to reset to [Claude Code's default model](/docs/en/model-config) |
463| `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) |
464| `get_mcp_status()` | Get the status of all configured MCP servers. Returns [`McpStatusResponse`](#mcpstatusresponse) |
465| `reconnect_mcp_server(server_name)` | Retry connecting to an MCP server that failed or was disconnected |
466| `toggle_mcp_server(server_name, enabled)` | Enable or disable an MCP server mid-session. Disabling removes its tools |
467| `stop_task(task_id)` | Stop a running background task. A [`TaskNotificationMessage`](#tasknotificationmessage) with status `"stopped"` follows in the message stream |
468| `get_server_info()` | Get the server's initialization info, including available commands and output styles |
469| `disconnect()` | Disconnect from Claude |
470470
471471#### Context Manager Support
472472
from line 687
687687 annotations: ToolAnnotations | None = None
688688```
689689
690| Property | Type | Description |
691| :------------- | :---------------------------------------------- | :--------------------------------------------------------------------------------------------------------------- |
692| `name` | `str` | Unique identifier for the tool |
693| `description` | `str` | Human-readable description |
694| `input_schema` | `type[T] \| dict[str, Any]` | Schema for input validation |
695| `handler` | `Callable[[T], Awaitable[dict[str, Any]]]` | Async function that handles tool execution |
696| `annotations` | [`ToolAnnotations`](#toolannotations)` \| None` | Optional tool annotations (for example `readOnlyHint`, `destructiveHint`, `openWorldHint`, `maxResultSizeChars`) |
690| Property | Type | Description |
691| :- | :- | :- |
692| `name` | `str` | Unique identifier for the tool |
693| `description` | `str` | Human-readable description |
694| `input_schema` | `type[T] \| dict[str, Any]` | Schema for input validation |
695| `handler` | `Callable[[T], Awaitable[dict[str, Any]]]` | Async function that handles tool execution |
696| `annotations` | [`ToolAnnotations`](#toolannotations)` \| None` | Optional tool annotations (for example `readOnlyHint`, `destructiveHint`, `openWorldHint`, `maxResultSizeChars`) |
697697
698698### `Transport`
699699
from line 729
729729 async def end_input(self) -> None: ...
730730```
731731
732| Method | Description |
733| :---------------- | :-------------------------------------------------------------------------- |
734| `connect()` | Connect the transport and prepare for communication |
735| `write(data)` | Write raw data (JSON + newline) to the transport |
736| `read_messages()` | Async iterator that yields parsed JSON messages |
737| `close()` | Close the connection and clean up resources |
738| `is_ready()` | Returns `True` if the transport can send and receive |
739| `end_input()` | Close the input stream (for example, close stdin for subprocess transports) |
732| Method | Description |
733| :- | :- |
734| `connect()` | Connect the transport and prepare for communication |
735| `write(data)` | Write raw data (JSON + newline) to the transport |
736| `read_messages()` | Async iterator that yields parsed JSON messages |
737| `close()` | Close the connection and clean up resources |
738| `is_ready()` | Returns `True` if the transport can send and receive |
739| `end_input()` | Close the input stream (for example, close stdin for subprocess transports) |
740740
741741Import: `from claude_agent_sdk import Transport`
742742
from line 798
798798 task_budget: TaskBudget | None = None
799799```
800800
801| Property | Type | Default | Description |
802| :---------------------------- | :------------------------------------------------------------------------------------ | :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
803| `tools` | `list[str] \| ToolsPreset \| None` | `None` | Tools configuration. Use `{"type": "preset", "preset": "claude_code"}` for Claude Code's default tools |
804| `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) |
805| `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`](#systempromptpreset), [`SystemPromptCustom`](#systempromptcustom), and [`SystemPromptFile`](#systempromptfile) |
806| `mcp_servers` | `dict[str, McpServerConfig] \| str \| Path` | `{}` | MCP server configurations or path to config file |
807| `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 |
808| `permission_mode` | `PermissionMode \| None` | `None` | Permission mode for tool usage |
809| `continue_conversation` | `bool` | `False` | Continue the most recent conversation |
810| `resume` | `str \| None` | `None` | Session ID to resume |
811| `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 |
812| `max_turns` | `int \| None` | `None` | Maximum agentic turns (tool-use round trips) |
813| `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) |
814| `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) |
815| `enable_file_checkpointing` | `bool` | `False` | Enable file change tracking for rewinding. See [File checkpointing](/docs/en/agent-sdk/file-checkpointing) |
816| `model` | `str \| None` | `None` | Claude model alias or full model name. See [accepted values and provider-specific IDs](/docs/en/model-config#available-models) |
817| `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) |
818| `betas` | `list[SdkBeta]` | `[]` | Beta features to enable. See [`SdkBeta`](#sdkbeta) for available options |
819| `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 |
820| `permission_prompt_tool_name` | `str \| None` | `None` | MCP tool name for permission prompts |
821| `cwd` | `str \| Path \| None` | `None` | Current working directory |
822| `cli_path` | `str \| Path \| None` | `None` | Custom path to the Claude Code CLI executable |
823| `settings` | `str \| None` | `None` | Path to a settings file or an inline JSON string |
824| `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) |
825| `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](#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 |
826| `extra_args` | `dict[str, str \| None]` | `{}` | Additional CLI arguments to pass directly to the CLI |
827| `max_buffer_size` | `int \| None` | `None` | Maximum bytes when buffering CLI stdout |
828| `debug_stderr` | `Any` | `sys.stderr` | *Deprecated* - The SDK ignores this value. Use the `stderr` callback for CLI stderr output |
829| `stderr` | `Callable[[str], None] \| None` | `None` | Callback function for stderr output from CLI |
830| `can_use_tool` | [`CanUseTool`](#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`](#canusetool) for details |
831| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | Hook configurations for intercepting events |
832| `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` |
833| `include_partial_messages` | `bool` | `False` | Include partial message streaming events. When enabled, [`StreamEvent`](#streamevent) messages are yielded |
834| `include_hook_events` | `bool` | `False` | Include hook lifecycle events in the message stream as `HookEventMessage` objects |
835| `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 |
836| `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 |
837| `fork_session` | `bool` | `False` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |
838| `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 |
839| `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 |
840| `agents` | `dict[str, AgentDefinition] \| None` | `None` | Programmatically defined subagents |
841| `plugins` | `list[SdkPluginConfig]` | `[]` | Load custom plugins from local paths. See [Plugins](/docs/en/agent-sdk/plugins) for details |
842| `sandbox` | [`SandboxSettings`](#sandboxsettings) ` \| None` | `None` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandboxsettings) for details |
843| `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) |
844| `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) |
845| `max_thinking_tokens` | `int \| None` | `None` | *Deprecated* - Maximum tokens for thinking blocks. Use `thinking` instead |
846| `thinking` | [`ThinkingConfig`](#thinkingconfig) ` \| None` | `None` | Controls extended thinking behavior. Takes precedence over `max_thinking_tokens` |
847| `effort` | [`EffortLevel`](#effortlevel) ` \| None` | `None` | Effort level for thinking depth. See [adjust the effort level](/docs/en/model-config#adjust-effort-level) |
848| `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) |
849| `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` |
850| `load_timeout_ms` | `int` | `60000` | Per-call timeout for `session_store.load()` and `list_subkeys()` during resume materialization, in milliseconds |
851| `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>}`. |
801| Property | Type | Default | Description |
802| :- | :- | :- | :- |
803| `tools` | `list[str] \| ToolsPreset \| None` | `None` | Tools configuration. Use `{"type": "preset", "preset": "claude_code"}` for Claude Code's default tools |
804| `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) |
805| `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`](#systempromptpreset), [`SystemPromptCustom`](#systempromptcustom), and [`SystemPromptFile`](#systempromptfile) |
806| `mcp_servers` | `dict[str, McpServerConfig] \| str \| Path` | `{}` | MCP server configurations or path to config file |
807| `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 |
808| `permission_mode` | `PermissionMode \| None` | `None` | Permission mode for tool usage |
809| `continue_conversation` | `bool` | `False` | Continue the most recent conversation |
810| `resume` | `str \| None` | `None` | Session ID to resume |
811| `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 |
812| `max_turns` | `int \| None` | `None` | Maximum agentic turns (tool-use round trips) |
813| `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) |
814| `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) |
815| `enable_file_checkpointing` | `bool` | `False` | Enable file change tracking for rewinding. See [File checkpointing](/docs/en/agent-sdk/file-checkpointing) |
816| `model` | `str \| None` | `None` | Claude model alias or full model name. See [accepted values and provider-specific IDs](/docs/en/model-config#available-models) |
817| `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) |
818| `betas` | `list[SdkBeta]` | `[]` | Beta features to enable. See [`SdkBeta`](#sdkbeta) for available options |
819| `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 |
820| `permission_prompt_tool_name` | `str \| None` | `None` | MCP tool name for permission prompts |
821| `cwd` | `str \| Path \| None` | `None` | Current working directory |
822| `cli_path` | `str \| Path \| None` | `None` | Custom path to the Claude Code CLI executable |
823| `settings` | `str \| None` | `None` | Path to a settings file or an inline JSON string |
824| `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) |
825| `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](#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 |
826| `extra_args` | `dict[str, str \| None]` | `{}` | Additional CLI arguments to pass directly to the CLI |
827| `max_buffer_size` | `int \| None` | `None` | Maximum bytes when buffering CLI stdout |
828| `debug_stderr` | `Any` | `sys.stderr` | *Deprecated* - The SDK ignores this value. Use the `stderr` callback for CLI stderr output |
829| `stderr` | `Callable[[str], None] \| None` | `None` | Callback function for stderr output from CLI |
830| `can_use_tool` | [`CanUseTool`](#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`](#canusetool) for details |
831| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | Hook configurations for intercepting events |
832| `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` |
833| `include_partial_messages` | `bool` | `False` | Include partial message streaming events. When enabled, [`StreamEvent`](#streamevent) messages are yielded |
834| `include_hook_events` | `bool` | `False` | Include hook lifecycle events in the message stream as `HookEventMessage` objects |
835| `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 |
836| `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 |
837| `fork_session` | `bool` | `False` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |
838| `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 |
839| `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 |
840| `agents` | `dict[str, AgentDefinition] \| None` | `None` | Programmatically defined subagents |
841| `plugins` | `list[SdkPluginConfig]` | `[]` | Load custom plugins from local paths. See [Plugins](/docs/en/agent-sdk/plugins) for details |
842| `sandbox` | [`SandboxSettings`](#sandboxsettings) ` \| None` | `None` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandboxsettings) for details |
843| `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) |
844| `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) |
845| `max_thinking_tokens` | `int \| None` | `None` | *Deprecated* - Maximum tokens for thinking blocks. Use `thinking` instead |
846| `thinking` | [`ThinkingConfig`](#thinkingconfig) ` \| None` | `None` | Controls extended thinking behavior. Takes precedence over `max_thinking_tokens` |
847| `effort` | [`EffortLevel`](#effortlevel) ` \| None` | `None` | Effort level for thinking depth. See [adjust the effort level](/docs/en/model-config#adjust-effort-level) |
848| `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) |
849| `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` |
850| `load_timeout_ms` | `int` | `60000` | Per-call timeout for `session_store.load()` and `list_subkeys()` during resume materialization, in milliseconds |
851| `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>}`. |
852852
853853#### Handle slow or stalled API responses
854854
from line 887
887887}
888888```
889889
890| Field | Required | Description |
891| :------- | :------- | :------------------------------------------------- |
892| `type` | Yes | Must be `"json_schema"` for JSON Schema validation |
893| `schema` | Yes | JSON Schema definition for output validation |
890| Field | Required | Description |
891| :- | :- | :- |
892| `type` | Yes | Must be `"json_schema"` for JSON Schema validation |
893| `schema` | Yes | JSON Schema definition for output validation |
894894
895895### `SystemPromptPreset`
896896
from line 905
905905 snapshot: NotRequired[bool]
906906```
907907
908| Field | Required | Description |
909| :------------------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
910| `type` | Yes | Must be `"preset"` to use a preset system prompt |
911| `preset` | Yes | Must be `"claude_code"` to use Claude Code's system prompt |
912| `append` | No | Additional instructions to append to the preset system prompt |
913| `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) |
914| `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 |
908| Field | Required | Description |
909| :- | :- | :- |
910| `type` | Yes | Must be `"preset"` to use a preset system prompt |
911| `preset` | Yes | Must be `"claude_code"` to use Claude Code's system prompt |
912| `append` | No | Additional instructions to append to the preset system prompt |
913| `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) |
914| `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 |
915915
916916### `SystemPromptCustom`
917917
from line 924
924924 snapshot: NotRequired[bool]
925925```
926926
927| Field | Required | Description |
928| :--------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------- |
929| `type` | Yes | Must be `"custom"` |
930| `prompt` | Yes | The system prompt text. Passed to the CLI as a command-line argument, so the [command-line length limits](#systempromptfile) apply |
931| `snapshot` | No | Same as [`SystemPromptPreset.snapshot`](#systempromptpreset), applied to `prompt` |
927| Field | Required | Description |
928| :- | :- | :- |
929| `type` | Yes | Must be `"custom"` |
930| `prompt` | Yes | The system prompt text. Passed to the CLI as a command-line argument, so the [command-line length limits](#systempromptfile) apply |
931| `snapshot` | No | Same as [`SystemPromptPreset.snapshot`](#systempromptpreset), applied to `prompt` |
932932
933933### `SystemPromptFile`
934934
from line 940
940940 path: str
941941```
942942
943| Field | Required | Description |
944| :----- | :------- | :-------------------------------------------- |
945| `type` | Yes | Must be `"file"` to load the prompt from disk |
946| `path` | Yes | Path to a file containing the system prompt |
943| Field | Required | Description |
944| :- | :- | :- |
945| `type` | Yes | Must be `"file"` to load the prompt from disk |
946| `path` | Yes | Path to a file containing the system prompt |
947947
948948### `SettingSource`
949949
from line 953
953953SettingSource = Literal["user", "project", "local"]
954954```
955955
956| Value | Description | Location |
957| :---------- | :------------------------------------------------------------------------ | :---------------------------- |
958| `"user"` | Global user settings | `~/.claude/settings.json` |
959| `"project"` | Shared project settings (version controlled) | `.claude/settings.json` |
960| `"local"` | Local project settings, gitignored when Claude Code saves a setting to it | `.claude/settings.local.json` |
956| Value | Description | Location |
957| :- | :- | :- |
958| `"user"` | Global user settings | `~/.claude/settings.json` |
959| `"project"` | Shared project settings (version controlled) | `.claude/settings.json` |
960| `"local"` | Local project settings, gitignored when Claude Code saves a setting to it | `.claude/settings.local.json` |
961961
962962#### Default behavior
963963
from line 1074
10741074 permissionMode: PermissionMode | None = None
10751075```
10761076
1077| Field | Required | Description |
1078| :---------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1079| `description` | Yes | Natural language description of when to use this agent |
1080| `prompt` | Yes | The agent's system prompt |
1081| `tools` | No | Array of allowed tool names. If omitted, inherits every [tool available to subagents](/docs/en/sub-agents#available-tools) |
1082| `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 |
1083| `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) |
1084| `skills` | No | List of skill names to preload into the agent's context at startup. Unlisted skills remain invocable through the Skill tool |
1085| `memory` | No | Memory source for this agent: `"user"`, `"project"`, or `"local"` |
1086| `mcpServers` | No | MCP servers available to this agent. Each entry is a server name or an inline `{name: config}` dict |
1087| `initialPrompt` | No | Auto-submitted as the first user turn when this agent runs as the main thread agent |
1088| `maxTurns` | No | Maximum number of agentic turns before the agent stops |
1089| `background` | No | Run this agent as a non-blocking background task when invoked |
1090| `effort` | No | Reasoning effort level for this agent. Accepts a named level or an integer. See [`EffortLevel`](#effortlevel) |
1091| `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`](#permissionmode) |
1077| Field | Required | Description |
1078| :- | :- | :- |
1079| `description` | Yes | Natural language description of when to use this agent |
1080| `prompt` | Yes | The agent's system prompt |
1081| `tools` | No | Array of allowed tool names. If omitted, inherits every [tool available to subagents](/docs/en/sub-agents#available-tools) |
1082| `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 |
1083| `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) |
1084| `skills` | No | List of skill names to preload into the agent's context at startup. Unlisted skills remain invocable through the Skill tool |
1085| `memory` | No | Memory source for this agent: `"user"`, `"project"`, or `"local"` |
1086| `mcpServers` | No | MCP servers available to this agent. Each entry is a server name or an inline `{name: config}` dict |
1087| `initialPrompt` | No | Auto-submitted as the first user turn when this agent runs as the main thread agent |
1088| `maxTurns` | No | Maximum number of agentic turns before the agent stops |
1089| `background` | No | Run this agent as a non-blocking background task when invoked |
1090| `effort` | No | Reasoning effort level for this agent. Accepts a named level or an integer. See [`EffortLevel`](#effortlevel) |
1091| `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`](#permissionmode) |
10921092
10931093<Note>
10941094 `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.
from line 1163
11631163 description: str | None = None
11641164```
11651165
1166| Field | Type | Description |
1167| :---------------- | :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1168| `signal` | `Any \| None` | Reserved for future abort signal support |
1169| `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. |
1170| `tool_use_id` | `str \| None` | Identifier of the specific tool call this prompt is for. Always populated when delivered to `can_use_tool` |
1171| `agent_id` | `str \| None` | Sub-agent ID when the call originates from a subagent; `None` for the main agent |
1172| `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 |
1173| `decision_reason` | `str \| None` | Reason this permission request was triggered. Forwarded from a PreToolUse hook's `permissionDecisionReason` when the hook returned `"ask"` |
1174| `title` | `str \| None` | Full permission prompt sentence, such as `Claude wants to read foo.txt`. Use as the primary prompt text when present |
1175| `display_name` | `str \| None` | Short noun phrase for the tool action, such as `Read file`, suitable for button labels |
1176| `description` | `str \| None` | Human-readable subtitle for the permission UI |
1166| Field | Type | Description |
1167| :- | :- | :- |
1168| `signal` | `Any \| None` | Reserved for future abort signal support |
1169| `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. |
1170| `tool_use_id` | `str \| None` | Identifier of the specific tool call this prompt is for. Always populated when delivered to `can_use_tool` |
1171| `agent_id` | `str \| None` | Sub-agent ID when the call originates from a subagent; `None` for the main agent |
1172| `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 |
1173| `decision_reason` | `str \| None` | Reason this permission request was triggered. Forwarded from a PreToolUse hook's `permissionDecisionReason` when the hook returned `"ask"` |
1174| `title` | `str \| None` | Full permission prompt sentence, such as `Claude wants to read foo.txt`. Use as the primary prompt text when present |
1175| `display_name` | `str \| None` | Short noun phrase for the tool action, such as `Read file`, suitable for button labels |
1176| `description` | `str \| None` | Human-readable subtitle for the permission UI |
11771177
11781178### `PermissionResult`
11791179
from line 1195
11951195 updated_permissions: list[PermissionUpdate] | None = None
11961196```
11971197
1198| Field | Type | Default | Description |
1199| :-------------------- | :------------------------------- | :-------- | :---------------------------------------- |
1200| `behavior` | `Literal["allow"]` | `"allow"` | Must be "allow" |
1201| `updated_input` | `dict[str, Any] \| None` | `None` | Modified input to use instead of original |
1202| `updated_permissions` | `list[PermissionUpdate] \| None` | `None` | Permission updates to apply |
1198| Field | Type | Default | Description |
1199| :- | :- | :- | :- |
1200| `behavior` | `Literal["allow"]` | `"allow"` | Must be "allow" |
1201| `updated_input` | `dict[str, Any] \| None` | `None` | Modified input to use instead of original |
1202| `updated_permissions` | `list[PermissionUpdate] \| None` | `None` | Permission updates to apply |
12031203
12041204### `PermissionResultDeny`
12051205
from line 1213
12131213 interrupt: bool = False
12141214```
12151215
1216| Field | Type | Default | Description |
1217| :---------- | :---------------- | :------- | :----------------------------------------- |
1218| `behavior` | `Literal["deny"]` | `"deny"` | Must be "deny" |
1219| `message` | `str` | `""` | Message explaining why the tool was denied |
1220| `interrupt` | `bool` | `False` | Whether to interrupt the current execution |
1216| Field | Type | Default | Description |
1217| :- | :- | :- | :- |
1218| `behavior` | `Literal["deny"]` | `"deny"` | Must be "deny" |
1219| `message` | `str` | `""` | Message explaining why the tool was denied |
1220| `interrupt` | `bool` | `False` | Whether to interrupt the current execution |
12211221
12221222### `PermissionUpdate`
12231223
from line 1243
12431243 ) = None
12441244```
12451245
1246| Field | Type | Description |
1247| :------------ | :---------------------------------------- | :---------------------------------------------- |
1248| `type` | `Literal[...]` | The type of permission update operation |
1249| `rules` | `list[PermissionRuleValue] \| None` | Rules for add/replace/remove operations |
1250| `behavior` | `Literal["allow", "deny", "ask"] \| None` | Behavior for rule-based operations |
1251| `mode` | `PermissionMode \| None` | Mode for setMode operation |
1252| `directories` | `list[str] \| None` | Directories for add/remove directory operations |
1253| `destination` | `Literal[...] \| None` | Where to apply the permission update |
1246| Field | Type | Description |
1247| :- | :- | :- |
1248| `type` | `Literal[...]` | The type of permission update operation |
1249| `rules` | `list[PermissionRuleValue] \| None` | Rules for add/replace/remove operations |
1250| `behavior` | `Literal["allow", "deny", "ask"] \| None` | Behavior for rule-based operations |
1251| `mode` | `PermissionMode \| None` | Mode for setMode operation |
1252| `directories` | `list[str] \| None` | Directories for add/remove directory operations |
1253| `destination` | `Literal[...] \| None` | Where to apply the permission update |
12541254
12551255### `PermissionRuleValue`
12561256
from line 1299
12991299ThinkingConfig = ThinkingConfigAdaptive | ThinkingConfigEnabled | ThinkingConfigDisabled
13001300```
13011301
1302| Variant | Fields | Description |
1303| :--------- | :--------------------------------- | :------------------------------------------- |
1304| `adaptive` | `type`, `display` | Claude adaptively decides when to think |
1305| `enabled` | `type`, `budget_tokens`, `display` | Enable thinking with a specific token budget |
1306| `disabled` | `type` | Disable thinking |
1302| Variant | Fields | Description |
1303| :- | :- | :- |
1304| `adaptive` | `type`, `display` | Claude adaptively decides when to think |
1305| `enabled` | `type`, `budget_tokens`, `display` | Enable thinking with a specific token budget |
1306| `disabled` | `type` | Disable thinking |
13071307
13081308The 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`](#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"`.
13091309
from line 1330
13301330 total: int
13311331```
13321332
1333| Field | Type | Description |
1334| :------ | :---- | :------------------------------ |
1333| Field | Type | Description |
1334| :- | :- | :- |
13351335| `total` | `int` | Total token budget for the task |
13361336
13371337Because this is a `TypedDict`, pass it as a plain dict, such as `ClaudeAgentOptions(task_budget={"total": 50000})`.
from line 1439
14391439 tools: NotRequired[list[McpToolInfo]]
14401440```
14411441
1442| Field | Type | Description |
1443| :----------- | :----------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1444| `name` | `str` | Server name |
1445| `status` | `str` | One of `"connected"`, `"failed"`, `"needs-auth"`, `"pending"`, or `"disabled"` |
1446| `serverInfo` | `dict` (optional) | Server name and version (`{"name": str, "version": str}`) |
1447| `error` | `str` (optional) | Error message if the server failed to connect |
1448| `config` | [`McpServerStatusConfig`](#mcpserverstatusconfig) (optional) | Server configuration. Same shape as [`McpServerConfig`](#mcpserverconfig) (stdio, SSE, HTTP, or SDK), plus a `claudeai-proxy` variant for servers connected through claude.ai |
1449| `scope` | `str` (optional) | Configuration scope |
1450| `tools` | `list` (optional) | Tools provided by this server, each with `name`, `description`, and `annotations` fields |
1442| Field | Type | Description |
1443| :- | :- | :- |
1444| `name` | `str` | Server name |
1445| `status` | `str` | One of `"connected"`, `"failed"`, `"needs-auth"`, `"pending"`, or `"disabled"` |
1446| `serverInfo` | `dict` (optional) | Server name and version (`{"name": str, "version": str}`) |
1447| `error` | `str` (optional) | Error message if the server failed to connect |
1448| `config` | [`McpServerStatusConfig`](#mcpserverstatusconfig) (optional) | Server configuration. Same shape as [`McpServerConfig`](#mcpserverconfig) (stdio, SSE, HTTP, or SDK), plus a `claudeai-proxy` variant for servers connected through claude.ai |
1449| `scope` | `str` (optional) | Configuration scope |
1450| `tools` | `list` (optional) | Tools provided by this server, each with `name`, `description`, and `annotations` fields |
14511451
14521452### `SdkPluginConfig`
14531453
from line 1459
14591459 path: str
14601460```
14611461
1462| Field | Type | Description |
1463| :----- | :----------------- | :--------------------------------------------------------- |
1462| Field | Type | Description |
1463| :- | :- | :- |
14641464| `type` | `Literal["local"]` | Must be `"local"` (only local plugins currently supported) |
1465| `path` | `str` | Absolute or relative path to the plugin directory |
1465| `path` | `str` | Absolute or relative path to the plugin directory |
14661466
14671467**Example:**
14681468
from line 1507
15071507 origin: MessageOrigin | None = None
15081508```
15091509
1510| Field | Type | Description |
1511| :------------------- | :-------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1512| `content` | `str \| list[ContentBlock]` | Message content as text or content blocks |
1513| `uuid` | `str \| None` | Unique message identifier |
1514| `parent_tool_use_id` | `str \| None` | Tool use ID if this message is a tool result response |
1515| `tool_use_result` | `dict[str, Any] \| None` | Tool result data if applicable |
1516| `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 |
1510| Field | Type | Description |
1511| :- | :- | :- |
1512| `content` | `str \| list[ContentBlock]` | Message content as text or content blocks |
1513| `uuid` | `str \| None` | Unique message identifier |
1514| `parent_tool_use_id` | `str \| None` | Tool use ID if this message is a tool result response |
1515| `tool_use_result` | `dict[str, Any] \| None` | Tool result data if applicable |
1516| `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 |
15171517
15181518The 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.
15191519
from line 1537
15371537 uuid: str | None = None
15381538```
15391539
1540| Field | Type | Description |
1541| :------------------- | :----------------------------------------------------------- | :----------------------------------------------------------------------------- |
1542| `content` | `list[ContentBlock]` | List of content blocks in the response |
1543| `model` | `str` | Model that generated the response |
1544| `parent_tool_use_id` | `str \| None` | Tool use ID if this is a nested response |
1545| `error` | [`AssistantMessageError`](#assistantmessageerror) ` \| None` | Error type if the response encountered an error |
1546| `usage` | `dict[str, Any] \| None` | Per-message token usage (same keys as [`ResultMessage.usage`](#resultmessage)) |
1547| `message_id` | `str \| None` | API message ID. Multiple messages from one turn share the same ID |
1548| `stop_reason` | `str \| None` | Stop reason from the API (for example, `end_turn`, `tool_use`) |
1549| `session_id` | `str \| None` | ID of the session this message belongs to |
1550| `uuid` | `str \| None` | Unique message identifier within the session transcript |
1540| Field | Type | Description |
1541| :- | :- | :- |
1542| `content` | `list[ContentBlock]` | List of content blocks in the response |
1543| `model` | `str` | Model that generated the response |
1544| `parent_tool_use_id` | `str \| None` | Tool use ID if this is a nested response |
1545| `error` | [`AssistantMessageError`](#assistantmessageerror) ` \| None` | Error type if the response encountered an error |
1546| `usage` | `dict[str, Any] \| None` | Per-message token usage (same keys as [`ResultMessage.usage`](#resultmessage)) |
1547| `message_id` | `str \| None` | API message ID. Multiple messages from one turn share the same ID |
1548| `stop_reason` | `str \| None` | Stop reason from the API (for example, `end_turn`, `tool_use`) |
1549| `session_id` | `str \| None` | ID of the session this message belongs to |
1550| `uuid` | `str \| None` | Unique message identifier within the session transcript |
15511551
15521552### `AssistantMessageError`
15531553
from line 1618
16181618
16191619The `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:
16201620
1621| Key | Type | Description |
1622| ----------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1623| `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. |
1624| `output_tokens` | `int` | Output tokens generated by the top-level agent loop. Subagent tokens aren't included. |
1625| `cache_creation_input_tokens` | `int` | Tokens used to create new cache entries. |
1626| `cache_read_input_tokens` | `int` | Tokens read from existing cache entries. |
1621| Key | Type | Description |
1622| - | - | - |
1623| `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. |
1624| `output_tokens` | `int` | Output tokens generated by the top-level agent loop. Subagent tokens aren't included. |
1625| `cache_creation_input_tokens` | `int` | Tokens used to create new cache entries. |
1626| `cache_read_input_tokens` | `int` | Tokens read from existing cache entries. |
16271627
16281628The `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.
16291629
from line 1631
16311631
16321632Each 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:
16331633
1634| Key | Type | Description |
1635| -------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1636| `inputTokens` | `int` | Input tokens for this model. |
1637| `outputTokens` | `int` | Output tokens for this model. |
1638| `cacheReadInputTokens` | `int` | Cache read tokens for this model. |
1639| `cacheCreationInputTokens` | `int` | Cache creation tokens for this model. |
1640| `webSearchRequests` | `int` | Web search requests made by this model. |
1641| `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. |
1642| `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. |
1643| `contextWindow` | `int` | Context window size for this model. |
1644| `maxOutputTokens` | `int` | Maximum output token limit for this model. |
1645| `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. |
1646| `provider` | `str` | API provider that served this model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`. Not always present. |
1634| Key | Type | Description |
1635| - | - | - |
1636| `inputTokens` | `int` | Input tokens for this model. |
1637| `outputTokens` | `int` | Output tokens for this model. |
1638| `cacheReadInputTokens` | `int` | Cache read tokens for this model. |
1639| `cacheCreationInputTokens` | `int` | Cache creation tokens for this model. |
1640| `webSearchRequests` | `int` | Web search requests made by this model. |
1641| `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. |
1642| `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. |
1643| `contextWindow` | `int` | Context window size for this model. |
1644| `maxOutputTokens` | `int` | Maximum output token limit for this model. |
1645| `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. |
1646| `provider` | `str` | API provider that served this model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`. Not always present. |
16471647
16481648### `StreamEvent`
16491649
from line 1658
16581658 parent_tool_use_id: str | None = None
16591659```
16601660
1661| Field | Type | Description |
1662| :------------------- | :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1663| `uuid` | `str` | Unique identifier for this event |
1664| `session_id` | `str` | Session identifier |
1665| `event` | `dict[str, Any]` | The raw Claude API stream event data |
1666| `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`](#assistantmessage) |
1661| Field | Type | Description |
1662| :- | :- | :- |
1663| `uuid` | `str` | Unique identifier for this event |
1664| `session_id` | `str` | Session identifier |
1665| `event` | `dict[str, Any]` | The raw Claude API stream event data |
1666| `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`](#assistantmessage) |
16671667
16681668### `RateLimitEvent`
16691669
from line 1677
16771677 session_id: str
16781678```
16791679
1680| Field | Type | Description |
1681| :---------------- | :-------------------------------- | :----------------------- |
1680| Field | Type | Description |
1681| :- | :- | :- |
16821682| `rate_limit_info` | [`RateLimitInfo`](#ratelimitinfo) | Current rate limit state |
1683| `uuid` | `str` | Unique event identifier |
1684| `session_id` | `str` | Session identifier |
1683| `uuid` | `str` | Unique event identifier |
1684| `session_id` | `str` | Session identifier |
16851685
16861686### `RateLimitInfo`
16871687
from line 1706
17061706 raw: dict[str, Any] = field(default_factory=dict)
17071707```
17081708
1709| Field | Type | Description |
1710| :------------------------ | :------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1711| `status` | `RateLimitStatus` | Current status, one of `"allowed"`, `"allowed_warning"`, or `"rejected"`. `"allowed_warning"` means approaching the limit; `"rejected"` means the limit was hit |
1712| `resets_at` | `int \| None` | Unix timestamp when the rate limit window resets |
1713| `rate_limit_type` | `RateLimitType \| None` | Which rate limit window applies |
1714| `utilization` | `float \| None` | Fraction of the rate limit consumed (0.0 to 1.0) |
1715| `overage_status` | `RateLimitStatus \| None` | Status of pay-as-you-go overage usage, if applicable |
1716| `overage_resets_at` | `int \| None` | Unix timestamp when the overage window resets |
1717| `overage_disabled_reason` | `str \| None` | Why overage is unavailable, if status is `"rejected"` |
1718| `raw` | `dict[str, Any]` | Full raw dict from the CLI, including fields not modeled above |
1709| Field | Type | Description |
1710| :- | :- | :- |
1711| `status` | `RateLimitStatus` | Current status, one of `"allowed"`, `"allowed_warning"`, or `"rejected"`. `"allowed_warning"` means approaching the limit; `"rejected"` means the limit was hit |
1712| `resets_at` | `int \| None` | Unix timestamp when the rate limit window resets |
1713| `rate_limit_type` | `RateLimitType \| None` | Which rate limit window applies |
1714| `utilization` | `float \| None` | Fraction of the rate limit consumed (0.0 to 1.0) |
1715| `overage_status` | `RateLimitStatus \| None` | Status of pay-as-you-go overage usage, if applicable |
1716| `overage_resets_at` | `int \| None` | Unix timestamp when the overage window resets |
1717| `overage_disabled_reason` | `str \| None` | Why overage is unavailable, if status is `"rejected"` |
1718| `raw` | `dict[str, Any]` | Full raw dict from the CLI, including fields not modeled above |
17191719
17201720### `ConversationResetMessage`
17211721
from line 1729
17291729 session_id: str
17301730```
17311731
1732| Field | Type | Description |
1733| :-------------------- | :---- | :------------------------------------------------------------------------------------------------------------------------- |
1732| Field | Type | Description |
1733| :- | :- | :- |
17341734| `new_conversation_id` | `str` | Opaque identifier for the fresh conversation. Not the `session_id` of subsequent messages; read that from the next message |
1735| `uuid` | `str` | Unique message identifier |
1736| `session_id` | `str` | ID of the session that was reset. Messages after the reset carry a new `session_id` |
1735| `uuid` | `str` | Unique message identifier |
1736| `session_id` | `str` | ID of the session that was reset. Messages after the reset carry a new `session_id` |
17371737
17381738### `TaskStartedMessage`
17391739
from line 1750
17501750 task_type: str | None = None
17511751```
17521752
1753| Field | Type | Description |
1754| :------------ | :------------ | :-------------------------------------------------------------------------------------------------------------------------- |
1755| `task_id` | `str` | Unique identifier for the task |
1756| `description` | `str` | Description of the task |
1757| `uuid` | `str` | Unique message identifier |
1758| `session_id` | `str` | Session identifier |
1759| `tool_use_id` | `str \| None` | Associated tool use ID |
1760| `task_type` | `str \| None` | Which kind of background task: `"local_bash"` for background Bash and Monitor watches, `"local_agent"`, or `"remote_agent"` |
1753| Field | Type | Description |
1754| :- | :- | :- |
1755| `task_id` | `str` | Unique identifier for the task |
1756| `description` | `str` | Description of the task |
1757| `uuid` | `str` | Unique message identifier |
1758| `session_id` | `str` | Session identifier |
1759| `tool_use_id` | `str \| None` | Associated tool use ID |
1760| `task_type` | `str \| None` | Which kind of background task: `"local_bash"` for background Bash and Monitor watches, `"local_agent"`, or `"remote_agent"` |
17611761
17621762### `TaskUsage`
17631763
from line 1786
17861786 last_tool_name: str | None = None
17871787```
17881788
1789| Field | Type | Description |
1790| :--------------- | :------------ | :---------------------------------- |
1791| `task_id` | `str` | Unique identifier for the task |
1792| `description` | `str` | Current status description |
1793| `usage` | `TaskUsage` | Token usage for this task so far |
1794| `uuid` | `str` | Unique message identifier |
1795| `session_id` | `str` | Session identifier |
1796| `tool_use_id` | `str \| None` | Associated tool use ID |
1789| Field | Type | Description |
1790| :- | :- | :- |
1791| `task_id` | `str` | Unique identifier for the task |
1792| `description` | `str` | Current status description |
1793| `usage` | `TaskUsage` | Token usage for this task so far |
1794| `uuid` | `str` | Unique message identifier |
1795| `session_id` | `str` | Session identifier |
1796| `tool_use_id` | `str \| None` | Associated tool use ID |
17971797| `last_tool_name` | `str \| None` | Name of the last tool the task used |
17981798
17991799### `TaskNotificationMessage`
from line 1813
18131813 usage: TaskUsage | None = None
18141814```
18151815
1816| Field | Type | Description |
1817| :------------ | :----------------------- | :----------------------------------------------- |
1818| `task_id` | `str` | Unique identifier for the task |
1819| `status` | `TaskNotificationStatus` | One of `"completed"`, `"failed"`, or `"stopped"` |
1820| `output_file` | `str` | Path to the task output file |
1821| `summary` | `str` | Summary of the task result |
1822| `uuid` | `str` | Unique message identifier |
1823| `session_id` | `str` | Session identifier |
1824| `tool_use_id` | `str \| None` | Associated tool use ID |
1825| `usage` | `TaskUsage \| None` | Final token usage for the task |
1816| Field | Type | Description |
1817| :- | :- | :- |
1818| `task_id` | `str` | Unique identifier for the task |
1819| `status` | `TaskNotificationStatus` | One of `"completed"`, `"failed"`, or `"stopped"` |
1820| `output_file` | `str` | Path to the task output file |
1821| `summary` | `str` | Summary of the task result |
1822| `uuid` | `str` | Unique message identifier |
1823| `session_id` | `str` | Session identifier |
1824| `tool_use_id` | `str \| None` | Associated tool use ID |
1825| `usage` | `TaskUsage \| None` | Final token usage for the task |
18261826
18271827When 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`](#usermessage). 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.
18281828
from line 2078
20782078 permission_mode: NotRequired[str]
20792079```
20802080
2081| Field | Type | Description |
2082| :---------------- | :--------------- | :---------------------------------- |
2083| `session_id` | `str` | Current session identifier |
2084| `transcript_path` | `str` | Path to the session transcript file |
2085| `cwd` | `str` | Current working directory |
2086| `permission_mode` | `str` (optional) | Current permission mode |
2081| Field | Type | Description |
2082| :- | :- | :- |
2083| `session_id` | `str` | Current session identifier |
2084| `transcript_path` | `str` | Path to the session transcript file |
2085| `cwd` | `str` | Current working directory |
2086| `permission_mode` | `str` (optional) | Current permission mode |
20872087
20882088### `PreToolUseHookInput`
20892089
from line 2099
20992099 agent_type: NotRequired[str]
21002100```
21012101
2102| Field | Type | Description |
2103| :---------------- | :---------------------- | :----------------------------------------------------------------- |
2104| `hook_event_name` | `Literal["PreToolUse"]` | Always "PreToolUse" |
2105| `tool_name` | `str` | Name of the tool about to be executed |
2106| `tool_input` | `dict[str, Any]` | Input parameters for the tool |
2107| `tool_use_id` | `str` | Unique identifier for this tool use |
2108| `agent_id` | `str` (optional) | Subagent identifier, present when the hook fires inside a subagent |
2109| `agent_type` | `str` (optional) | Subagent type, present when the hook fires inside a subagent |
2102| Field | Type | Description |
2103| :- | :- | :- |
2104| `hook_event_name` | `Literal["PreToolUse"]` | Always "PreToolUse" |
2105| `tool_name` | `str` | Name of the tool about to be executed |
2106| `tool_input` | `dict[str, Any]` | Input parameters for the tool |
2107| `tool_use_id` | `str` | Unique identifier for this tool use |
2108| `agent_id` | `str` (optional) | Subagent identifier, present when the hook fires inside a subagent |
2109| `agent_type` | `str` (optional) | Subagent type, present when the hook fires inside a subagent |
21102110
21112111### `PostToolUseHookInput`
21122112
from line 2123
21232123 agent_type: NotRequired[str]
21242124```
21252125
2126| Field | Type | Description |
2127| :---------------- | :----------------------- | :----------------------------------------------------------------- |
2128| `hook_event_name` | `Literal["PostToolUse"]` | Always "PostToolUse" |
2129| `tool_name` | `str` | Name of the tool that was executed |
2130| `tool_input` | `dict[str, Any]` | Input parameters that were used |
2131| `tool_response` | `Any` | Response from the tool execution |
2132| `tool_use_id` | `str` | Unique identifier for this tool use |
2133| `agent_id` | `str` (optional) | Subagent identifier, present when the hook fires inside a subagent |
2134| `agent_type` | `str` (optional) | Subagent type, present when the hook fires inside a subagent |
2126| Field | Type | Description |
2127| :- | :- | :- |
2128| `hook_event_name` | `Literal["PostToolUse"]` | Always "PostToolUse" |
2129| `tool_name` | `str` | Name of the tool that was executed |
2130| `tool_input` | `dict[str, Any]` | Input parameters that were used |
2131| `tool_response` | `Any` | Response from the tool execution |
2132| `tool_use_id` | `str` | Unique identifier for this tool use |
2133| `agent_id` | `str` (optional) | Subagent identifier, present when the hook fires inside a subagent |
2134| `agent_type` | `str` (optional) | Subagent type, present when the hook fires inside a subagent |
21352135
21362136### `PostToolUseFailureHookInput`
21372137
from line 2149
21492149 agent_type: NotRequired[str]
21502150```
21512151
2152| Field | Type | Description |
2153| :---------------- | :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
2154| `hook_event_name` | `Literal["PostToolUseFailure"]` | Always "PostToolUseFailure" |
2155| `tool_name` | `str` | Name of the tool that failed |
2156| `tool_input` | `dict[str, Any]` | Input parameters that were used |
2157| `tool_use_id` | `str` | Unique identifier for this tool use |
2158| `error` | `str` | Error message from the failed execution |
2159| `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 |
2160| `agent_id` | `str` (optional) | Subagent identifier, present when the hook fires inside a subagent |
2161| `agent_type` | `str` (optional) | Subagent type, present when the hook fires inside a subagent |
2152| Field | Type | Description |
2153| :- | :- | :- |
2154| `hook_event_name` | `Literal["PostToolUseFailure"]` | Always "PostToolUseFailure" |
2155| `tool_name` | `str` | Name of the tool that failed |
2156| `tool_input` | `dict[str, Any]` | Input parameters that were used |
2157| `tool_use_id` | `str` | Unique identifier for this tool use |
2158| `error` | `str` | Error message from the failed execution |
2159| `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 |
2160| `agent_id` | `str` (optional) | Subagent identifier, present when the hook fires inside a subagent |
2161| `agent_type` | `str` (optional) | Subagent type, present when the hook fires inside a subagent |
21622162
21632163### `UserPromptSubmitHookInput`
21642164
from line 2170
21702170 prompt: str
21712171```
21722172
2173| Field | Type | Description |
2174| :---------------- | :---------------------------- | :-------------------------- |
2175| `hook_event_name` | `Literal["UserPromptSubmit"]` | Always "UserPromptSubmit" |
2176| `prompt` | `str` | The user's submitted prompt |
2173| Field | Type | Description |
2174| :- | :- | :- |
2175| `hook_event_name` | `Literal["UserPromptSubmit"]` | Always "UserPromptSubmit" |
2176| `prompt` | `str` | The user's submitted prompt |
21772177
21782178### `StopHookInput`
21792179
from line 2185
21852185 stop_hook_active: bool
21862186```
21872187
2188| Field | Type | Description |
2189| :----------------- | :---------------- | :------------------------------ |
2190| `hook_event_name` | `Literal["Stop"]` | Always "Stop" |
2191| `stop_hook_active` | `bool` | Whether the stop hook is active |
2188| Field | Type | Description |
2189| :- | :- | :- |
2190| `hook_event_name` | `Literal["Stop"]` | Always "Stop" |
2191| `stop_hook_active` | `bool` | Whether the stop hook is active |
21922192
21932193### `SubagentStopHookInput`
21942194
from line 2203
22032203 agent_type: str
22042204```
22052205
2206| Field | Type | Description |
2207| :---------------------- | :------------------------ | :------------------------------------- |
2208| `hook_event_name` | `Literal["SubagentStop"]` | Always "SubagentStop" |
2209| `stop_hook_active` | `bool` | Whether the stop hook is active |
2210| `agent_id` | `str` | Unique identifier for the subagent |
2211| `agent_transcript_path` | `str` | Path to the subagent's transcript file |
2212| `agent_type` | `str` | Type of the subagent |
2206| Field | Type | Description |
2207| :- | :- | :- |
2208| `hook_event_name` | `Literal["SubagentStop"]` | Always "SubagentStop" |
2209| `stop_hook_active` | `bool` | Whether the stop hook is active |
2210| `agent_id` | `str` | Unique identifier for the subagent |
2211| `agent_transcript_path` | `str` | Path to the subagent's transcript file |
2212| `agent_type` | `str` | Type of the subagent |
22132213
22142214### `PreCompactHookInput`
22152215
from line 2222
22222222 custom_instructions: str | None
22232223```
22242224
2225| Field | Type | Description |
2226| :-------------------- | :-------------------------- | :--------------------------------- |
2227| `hook_event_name` | `Literal["PreCompact"]` | Always "PreCompact" |
2228| `trigger` | `Literal["manual", "auto"]` | What triggered the compaction |
2229| `custom_instructions` | `str \| None` | Custom instructions for compaction |
2225| Field | Type | Description |
2226| :- | :- | :- |
2227| `hook_event_name` | `Literal["PreCompact"]` | Always "PreCompact" |
2228| `trigger` | `Literal["manual", "auto"]` | What triggered the compaction |
2229| `custom_instructions` | `str \| None` | Custom instructions for compaction |
22302230
22312231### `NotificationHookInput`
22322232
from line 2240
22402240 notification_type: str
22412241```
22422242
2243| Field | Type | Description |
2244| :------------------ | :------------------------ | :--------------------------- |
2245| `hook_event_name` | `Literal["Notification"]` | Always "Notification" |
2246| `message` | `str` | Notification message content |
2247| `title` | `str` (optional) | Notification title |
2248| `notification_type` | `str` | Type of notification |
2243| Field | Type | Description |
2244| :- | :- | :- |
2245| `hook_event_name` | `Literal["Notification"]` | Always "Notification" |
2246| `message` | `str` | Notification message content |
2247| `title` | `str` (optional) | Notification title |
2248| `notification_type` | `str` | Type of notification |
22492249
22502250### `SubagentStartHookInput`
22512251
from line 2258
22582258 agent_type: str
22592259```
22602260
2261| Field | Type | Description |
2262| :---------------- | :------------------------- | :--------------------------------- |
2263| `hook_event_name` | `Literal["SubagentStart"]` | Always "SubagentStart" |
2264| `agent_id` | `str` | Unique identifier for the subagent |
2265| `agent_type` | `str` | Type of the subagent |
2261| Field | Type | Description |
2262| :- | :- | :- |
2263| `hook_event_name` | `Literal["SubagentStart"]` | Always "SubagentStart" |
2264| `agent_id` | `str` | Unique identifier for the subagent |
2265| `agent_type` | `str` | Type of the subagent |
22662266
22672267### `PermissionRequestHookInput`
22682268
from line 2278
22782278 agent_type: NotRequired[str]
22792279```
22802280
2281| Field | Type | Description |
2282| :----------------------- | :----------------------------- | :----------------------------------------------------------------- |
2283| `hook_event_name` | `Literal["PermissionRequest"]` | Always "PermissionRequest" |
2284| `tool_name` | `str` | Name of the tool requesting permission |
2285| `tool_input` | `dict[str, Any]` | Input parameters for the tool |
2286| `permission_suggestions` | `list[Any]` (optional) | Suggested permission updates from the CLI |
2287| `agent_id` | `str` (optional) | Subagent identifier, present when the hook fires inside a subagent |
2288| `agent_type` | `str` (optional) | Subagent type, present when the hook fires inside a subagent |
2281| Field | Type | Description |
2282| :- | :- | :- |
2283| `hook_event_name` | `Literal["PermissionRequest"]` | Always "PermissionRequest" |
2284| `tool_name` | `str` | Name of the tool requesting permission |
2285| `tool_input` | `dict[str, Any]` | Input parameters for the tool |
2286| `permission_suggestions` | `list[Any]` (optional) | Suggested permission updates from the CLI |
2287| `agent_id` | `str` (optional) | Subagent identifier, present when the hook fires inside a subagent |
2288| `agent_type` | `str` (optional) | Subagent type, present when the hook fires inside a subagent |
22892289
22902290### `HookJSONOutput`
22912291
from line 3296
32963296 enableWeakerNestedSandbox: bool
32973297```
32983298
3299| Property | Type | Default | Description |
3300| :-------------------------- | :---------------------------------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
3301| `enabled` | `bool` | `False` | Enable sandbox mode for command execution |
3302| `autoAllowBashIfSandboxed` | `bool` | `True` | Auto-approve bash commands when sandbox is enabled |
3303| `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 |
3304| `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](#permissions-fallback-for-unsandboxed-commands) |
3305| `network` | [`SandboxNetworkConfig`](#sandboxnetworkconfig) | `None` | Network-specific sandbox configuration |
3306| `ignoreViolations` | [`SandboxIgnoreViolations`](#sandboxignoreviolations) | `None` | Configure which sandbox violations to ignore |
3307| `enableWeakerNestedSandbox` | `bool` | `False` | Enable a weaker nested sandbox for compatibility |
3299| Property | Type | Default | Description |
3300| :- | :- | :- | :- |
3301| `enabled` | `bool` | `False` | Enable sandbox mode for command execution |
3302| `autoAllowBashIfSandboxed` | `bool` | `True` | Auto-approve bash commands when sandbox is enabled |
3303| `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 |
3304| `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](#permissions-fallback-for-unsandboxed-commands) |
3305| `network` | [`SandboxNetworkConfig`](#sandboxnetworkconfig) | `None` | Network-specific sandbox configuration |
3306| `ignoreViolations` | [`SandboxIgnoreViolations`](#sandboxignoreviolations) | `None` | Configure which sandbox violations to ignore |
3307| `enableWeakerNestedSandbox` | `bool` | `False` | Enable a weaker nested sandbox for compatibility |
33083308
33093309<Note>
33103310 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`.
from line 3364
33643364 socksProxyPort: int
33653365```
33663366
3367| Property | Type | Default | Description |
3368| :------------------------ | :---------- | :------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
3369| `allowedDomains` | `list[str]` | `[]` | Domain names that sandboxed processes can access |
3370| `deniedDomains` | `list[str]` | `[]` | Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains` |
3371| `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 |
3372| `allowUnixSockets` | `list[str]` | `[]` | macOS only: Unix socket paths that processes can access, such as the Docker socket. Ignored on Linux |
3373| `allowAllUnixSockets` | `bool` | `False` | Allow access to all Unix sockets |
3374| `allowLocalBinding` | `bool` | `False` | Allow processes to bind to local ports (for example, for dev servers) |
3375| `allowMachLookup` | `list[str]` | `[]` | macOS only: XPC/Mach service names to allow. Supports a trailing wildcard |
3376| `httpProxyPort` | `int` | `None` | HTTP proxy port for network requests |
3377| `socksProxyPort` | `int` | `None` | SOCKS proxy port for network requests |
3367| Property | Type | Default | Description |
3368| :- | :- | :- | :- |
3369| `allowedDomains` | `list[str]` | `[]` | Domain names that sandboxed processes can access |
3370| `deniedDomains` | `list[str]` | `[]` | Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains` |
3371| `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 |
3372| `allowUnixSockets` | `list[str]` | `[]` | macOS only: Unix socket paths that processes can access, such as the Docker socket. Ignored on Linux |
3373| `allowAllUnixSockets` | `bool` | `False` | Allow access to all Unix sockets |
3374| `allowLocalBinding` | `bool` | `False` | Allow processes to bind to local ports (for example, for dev servers) |
3375| `allowMachLookup` | `list[str]` | `[]` | macOS only: XPC/Mach service names to allow. Supports a trailing wildcard |
3376| `httpProxyPort` | `int` | `None` | HTTP proxy port for network requests |
3377| `socksProxyPort` | `int` | `None` | SOCKS proxy port for network requests |
33783378
33793379<Note>
33803380 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.
from line 3390
33903390 network: list[str]
33913391```
33923392
3393| Property | Type | Default | Description |
3394| :-------- | :---------- | :------ | :------------------------------------------ |
3395| `file` | `list[str]` | `[]` | File path patterns to ignore violations for |
3396| `network` | `list[str]` | `[]` | Network patterns to ignore violations for |
3393| Property | Type | Default | Description |
3394| :- | :- | :- | :- |
3395| `file` | `list[str]` | `[]` | File path patterns to ignore violations for |
3396| `network` | `list[str]` | `[]` | Network patterns to ignore violations for |
33973397
33983398### Permissions Fallback for Unsandboxed Commands
33993399
34003400
No line in this hunk matches that.