380 380
381#### Example381#### Example
382 382
383The example below resolves settings for a project directory and prints the source that controls the cleanup period.383The example below resolves settings for a project directory and prints the source that controls the cleanup period. On a machine where no settings file sets `cleanupPeriodDays`, both printed lines show `undefined` for the value, which is the expected output rather than an error.
384 384
385```typescript theme={null}385```typescript theme={null}
386import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";386import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";
424| `extraArgs` | `Record<string, string \| null>` | `{}` | Additional arguments |424| `extraArgs` | `Record<string, string \| null>` | `{}` | Additional arguments |
425| `fallbackModel` | `string` | `undefined` | Model to use if primary fails |425| `fallbackModel` | `string` | `undefined` | Model to use if primary fails |
426| `forkSession` | `boolean` | `false` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |426| `forkSession` | `boolean` | `false` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |
427| `forwardSubagentText` | `boolean` | `false` | Forward subagent text and thinking blocks as assistant and user messages with `parent_tool_use_id` set, so consumers can render a nested transcript. By default only `tool_use` and `tool_result` blocks from subagents are emitted |427| `forwardSubagentText` | `boolean` | `false` | Forward subagent text and thinking blocks as assistant and user messages with `parent_tool_use_id` set, so consumers can render a nested transcript. By default only `tool_use` and `tool_result` blocks from subagents are emitted. {/* min-version: 2.1.219 */}Messages from subagents at every nesting depth are forwarded on Claude Code v2.1.219 and later; before v2.1.219, only messages from depth-1 subagents appeared |
428| `hooks` | `Partial<Record<`[`HookEvent`](#hookevent)`, `[`HookCallbackMatcher`](#hookcallbackmatcher)`[]>>` | `{}` | Hook callbacks for events |428| `hooks` | `Partial<Record<`[`HookEvent`](#hookevent)`, `[`HookCallbackMatcher`](#hookcallbackmatcher)`[]>>` | `{}` | Hook callbacks for events |
429| `includeHookEvents` | `boolean` | `false` | Include hook lifecycle events for every hook event in the message stream as [`SDKHookStartedMessage`](#sdkhookstartedmessage), [`SDKHookProgressMessage`](#sdkhookprogressmessage), and [`SDKHookResponseMessage`](#sdkhookresponsemessage). Lifecycle events for `SessionStart` and `Setup` hooks are always included and don't need this option |429| `includeHookEvents` | `boolean` | `false` | Include hook lifecycle events for every hook event in the message stream as [`SDKHookStartedMessage`](#sdkhookstartedmessage), [`SDKHookProgressMessage`](#sdkhookprogressmessage), and [`SDKHookResponseMessage`](#sdkhookresponsemessage). Lifecycle events for `SessionStart` and `Setup` hooks are always included and don't need this option |
430| `includePartialMessages` | `boolean` | `false` | Include partial message events |430| `includePartialMessages` | `boolean` | `false` | Include partial message events |
470The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through the `env` option:470The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through the `env` option:
471 471
472```typescript theme={null}472```typescript theme={null}
473import { query } from "@anthropic-ai/claude-agent-sdk";
474
473const result = query({475const result = query({
474 prompt: "Analyze this code",476 prompt: "Analyze this code",
475 options: {477 options: {
486* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.488* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.
487* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and {/* min-version: 2.1.199 */}as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.489* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and {/* min-version: 2.1.199 */}as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.
488* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.490* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
489* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.491* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, Claude Code retries the request at most once, and only before Claude has started a block of text or a tool call in the response; once Claude has completed a block of text or a tool call, Claude Code keeps the completed output, appends an [incomplete-response notice](/docs/en/errors#the-response-above-may-be-incomplete) instead of retrying, and still runs any completed tool call.
490 492
491### `Query` object493### `Query` object
492 494
509 supportedModels(): Promise<ModelInfo[]>;511 supportedModels(): Promise<ModelInfo[]>;
510 supportedAgents(): Promise<AgentInfo[]>;512 supportedAgents(): Promise<AgentInfo[]>;
511 mcpServerStatus(): Promise<McpServerStatus[]>;513 mcpServerStatus(): Promise<McpServerStatus[]>;
514 getContextUsage(): Promise<SDKControlGetContextUsageResponse>;
512 accountInfo(): Promise<AccountInfo>;515 accountInfo(): Promise<AccountInfo>;
513 reconnectMcpServer(serverName: string): Promise<void>;516 reconnectMcpServer(serverName: string): Promise<void>;
514 toggleMcpServer(serverName: string, enabled: boolean): Promise<void>;517 toggleMcpServer(serverName: string, enabled: boolean): Promise<void>;
526| `interrupt()` | Interrupts the query. Only available in streaming input mode. {/* min-version: 2.1.205 */}When the CLI advertises the `interrupt_receipt_v1` capability in [`SDKSystemMessage.capabilities`](#sdksystemmessage), resolves with an [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse) listing the queued messages that survive the interrupt. Resolves `undefined` on CLIs before v2.1.205 |529| `interrupt()` | Interrupts the query. Only available in streaming input mode. {/* min-version: 2.1.205 */}When the CLI advertises the `interrupt_receipt_v1` capability in [`SDKSystemMessage.capabilities`](#sdksystemmessage), resolves with an [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse) listing the queued messages that survive the interrupt. Resolves `undefined` on CLIs before v2.1.205 |
527| `rewindFiles(userMessageId, options?)` | Restores files to their state at the specified user message. Pass `{ dryRun: true }` to preview changes. Requires `enableFileCheckpointing: true`. See [File checkpointing](/docs/en/agent-sdk/file-checkpointing) |530| `rewindFiles(userMessageId, options?)` | Restores files to their state at the specified user message. Pass `{ dryRun: true }` to preview changes. Requires `enableFileCheckpointing: true`. See [File checkpointing](/docs/en/agent-sdk/file-checkpointing) |
528| `setPermissionMode()` | Changes the permission mode (only available in streaming input mode) |531| `setPermissionMode()` | Changes the permission mode (only available in streaming input mode) |
529| `setModel()` | Changes the model (only available in streaming input mode) |532| `setModel()` | Changes the model (only available in streaming input mode). Passing `undefined` or the string `"default"` resets to the session default model |
530| `setMaxThinkingTokens()` | *Deprecated:* Use the `thinking` option instead. Changes the maximum thinking tokens. Passing `null` resets thinking to the session default: a mid-session override is cleared, and thinking stays off for sessions that have it disabled |533| `setMaxThinkingTokens()` | *Deprecated:* Use the `thinking` option instead. Changes the maximum thinking tokens. Passing `null` resets thinking to the session default: a mid-session override is cleared, and thinking stays off for sessions that have it disabled |
531| `applyFlagSettings(settings)` | Merges settings into the session's flag settings layer at runtime (only available in streaming input mode). See [`applyFlagSettings()`](#applyflagsettings) |534| `applyFlagSettings(settings)` | Merges settings into the session's flag settings layer at runtime (only available in streaming input mode). See [`applyFlagSettings()`](#applyflagsettings) |
532| `initializationResult()` | Returns the full initialization result including supported commands, models, account info, and output style configuration |535| `initializationResult()` | Returns the full initialization result including supported commands, models, account info, and output style configuration |
533| `reinitialize()` | {/* min-version: 2.1.195 */}Re-sends the `initialize` control request to the running CLI and returns a fresh result instead of the cached first-connect result. Use it after a transport gap, such as reattaching to a session after a disconnect, so pending permission requests reach your `canUseTool` callback again. Make the callback idempotent per request ID, because a request whose response was lost is dispatched again. Requires Claude Code v2.1.195 or later |536| `reinitialize()` | {/* min-version: 2.1.195 */}Re-sends the `initialize` control request to the running CLI and returns a fresh result instead of the cached first-connect result. Use it after a transport gap, such as reattaching to a session after a disconnect, so pending permission requests reach your `canUseTool` callback again. Make the callback idempotent per request ID, because a request whose response was lost is dispatched again. Requires Claude Code v2.1.195 or later |
534| `supportedCommands()` | Returns available slash commands |537| `supportedCommands()` | Returns available slash commands. {/* min-version: agent-sdk@0.3.216 */}From Agent SDK v0.3.216 the list reflects mid-session command changes; see [`SDKCommandsChangedMessage`](#sdkcommandschangedmessage) |
535| `supportedModels()` | Returns available models with display info |538| `supportedModels()` | Returns available models with display info |
536| `supportedAgents()` | Returns available subagents as [`AgentInfo`](#agentinfo)`[]` |539| `supportedAgents()` | Returns available subagents as [`AgentInfo`](#agentinfo)`[]` |
537| `mcpServerStatus()` | Returns status of connected MCP servers |540| `mcpServerStatus()` | Returns status of connected MCP servers |
541| `getContextUsage()` | Returns an [`SDKControlGetContextUsageResponse`](#sdkcontrolgetcontextusageresponse) breaking down the session's context window usage by category, skill, and tool. The same data `/context` shows in an interactive session |
538| `accountInfo()` | Returns account information |542| `accountInfo()` | Returns account information |
539| `reconnectMcpServer(serverName)` | Reconnect an MCP server by name |543| `reconnectMcpServer(serverName)` | Reconnect an MCP server by name |
540| `toggleMcpServer(serverName, enabled)` | Enable or disable an MCP server by name |544| `toggleMcpServer(serverName, enabled)` | Enable or disable an MCP server by name |
564The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify.568The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify.
565 569
566```typescript theme={null}570```typescript theme={null}
571import { query } from "@anthropic-ai/claude-agent-sdk";
572
567const q = query({ prompt: messageStream });573const q = query({ prompt: messageStream });
568 574
569// Override the model for the rest of the session575// Override the model for the rest of the session
610 models: ModelInfo[];616 models: ModelInfo[];
611 account: AccountInfo;617 account: AccountInfo;
612 fast_mode_state?: "off" | "cooldown" | "on";618 fast_mode_state?: "off" | "cooldown" | "on";
619 fast_mode_disabled_reason?: FastModeDisabledReason;
613};620};
614```621```
615 622
623{/* min-version: 2.1.219 */}The response always reports `fast_mode_state`, and when something blocks [fast mode](/docs/en/fast-mode), `fast_mode_disabled_reason` carries the reason code alongside it, so you can explain the blocked state instead of re-deriving availability. Both behaviors require Claude Code v2.1.219 or later. Before v2.1.219, the response omitted `fast_mode_state` when fast mode wasn't available and never carried a reason. For the reason codes and their meanings, see [`fast_mode_disabled_reason`](#sdkresultmessage) on the result message.
624
616When a client sends `initialize` to a session that is already running, the control-response wrapper also carries an optional `pending_permission_requests` array. The field is on the response wrapper itself, not in the `SDKControlInitializeResponse` payload above. Each entry is a complete `control_request` message with the same `{ type: "control_request", request_id, request }` shape the session streams for permission requests while running.625When a client sends `initialize` to a session that is already running, the control-response wrapper also carries an optional `pending_permission_requests` array. The field is on the response wrapper itself, not in the `SDKControlInitializeResponse` payload above. Each entry is a complete `control_request` message with the same `{ type: "control_request", request_id, request }` shape the session streams for permission requests while running.
617 626
618These are requests that were issued before the client connected and are still awaiting a reply. The SDK reads the array for you and dispatches each entry to your [`canUseTool`](#canusetool) callback, the same redelivery that [`reinitialize()`](#query-object) triggers after a transport gap. Handle repeated request IDs idempotently, because an entry can repeat a request the callback already received before the connection dropped.627These are requests that were issued before the client connected and are still awaiting a reply. The SDK reads the array for you and dispatches each entry to your [`canUseTool`](#canusetool) callback, the same redelivery that [`reinitialize()`](#query-object) triggers after a transport gap. Handle repeated request IDs idempotently, because an entry can repeat a request the callback already received before the connection dropped.
624```typescript theme={null}633```typescript theme={null}
625type SDKControlInterruptResponse = {634type SDKControlInterruptResponse = {
626 still_queued: string[];635 still_queued: string[];
636 cancelled?: string[];
627};637};
628```638```
629 639
635* Only main-thread messages are listed. Messages addressed to a subagent are out of scope.645* Only main-thread messages are listed. Messages addressed to a subagent are out of scope.
636* The list can include UUIDs your client never sent, such as [scheduled task](/docs/en/scheduled-tasks) triggers. Ignore UUIDs you don't recognize instead of treating them as an error.646* The list can include UUIDs your client never sent, such as [scheduled task](/docs/en/scheduled-tasks) triggers. Ignore UUIDs you don't recognize instead of treating them as an error.
637 647
648{/* min-version: 2.1.219 */}A client that drives the CLI's control protocol directly, rather than through `interrupt()`, can set `cancel_queued: true` on the `interrupt` control request. Claude Code v2.1.219 and later advertises support with the `interrupt_cancel_queued_v1` capability in [`SDKSystemMessage.capabilities`](#sdksystemmessage); older CLIs ignore the field and leave queued messages to run as usual. Such an interrupt also cancels every message that would otherwise be listed under `still_queued`: the receipt lists them under `cancelled` instead, `still_queued` is empty, and none of them run.
649
650The `cancelled` list carries the same caveats as `still_queued`. The `interrupt()` method never sends `cancel_queued`, so receipts it resolves with don't carry `cancelled`.
651
638The receipt is a snapshot taken at the moment the interrupt is processed, and on a clean interrupt it arrives before the interrupted turn's [`SDKResultMessage`](#sdkresultmessage). Read the receipt rather than inspecting the queue after that result: the loop starts the next queued turn immediately, so the queue you inspect after the result has already changed.652The receipt is a snapshot taken at the moment the interrupt is processed, and on a clean interrupt it arrives before the interrupted turn's [`SDKResultMessage`](#sdkresultmessage). Read the receipt rather than inspecting the queue after that result: the loop starts the next queued turn immediately, so the queue you inspect after the result has already changed.
639 653
654### `SDKControlGetContextUsageResponse`
655
656Return type of [`getContextUsage()`](#query-object). This is the same payload the `/context` command renders in an interactive session, so alongside the token counts it carries display fields such as `color`, `gridRows`, and `percentage` that `/context` uses to draw its usage grid.
657
658```typescript theme={null}
659type SDKControlGetContextUsageResponse = {
660 categories: {
661 name: string;
662 tokens: number;
663 color: string;
664 isDeferred?: boolean;
665 }[];
666 totalTokens: number;
667 maxTokens: number;
668 rawMaxTokens: number;
669 percentage: number;
670 gridRows: {
671 color: string;
672 isFilled: boolean;
673 categoryName: string;
674 tokens: number;
675 percentage: number;
676 squareFullness: number;
677 }[][];
678 model: string;
679 memoryFiles: {
680 path: string;
681 type: string;
682 tokens: number;
683 }[];
684 mcpTools: {
685 name: string;
686 serverName: string;
687 tokens: number;
688 isLoaded?: boolean;
689 }[];
690 deferredBuiltinTools?: {
691 name: string;
692 tokens: number;
693 isLoaded: boolean;
694 }[];
695 systemTools?: {
696 name: string;
697 tokens: number;
698 }[];
699 systemPromptSections?: {
700 name: string;
701 tokens: number;
702 }[];
703 agents: {
704 agentType: string;
705 source: string;
706 tokens: number;
707 }[];
708 slashCommands?: {
709 totalCommands: number;
710 includedCommands: number;
711 tokens: number;
712 };
713 skills?: {
714 totalSkills: number;
715 includedSkills: number;
716 tokens: number;
717 skillFrontmatter: {
718 name: string;
719 source: string;
720 tokens: number;
721 }[];
722 };
723 autoCompactThreshold?: number;
724 isAutoCompactEnabled: boolean;
725 messageBreakdown?: {
726 toolCallTokens: number;
727 toolResultTokens: number;
728 attachmentTokens: number;
729 assistantMessageTokens: number;
730 userMessageTokens: number;
731 redirectedContextTokens: number;
732 unattributedTokens: number;
733 toolCallsByType: {
734 name: string;
735 callTokens: number;
736 resultTokens: number;
737 }[];
738 attachmentsByType: {
739 name: string;
740 tokens: number;
741 }[];
742 };
743 apiUsage: {
744 input_tokens: number;
745 output_tokens: number;
746 cache_creation_input_tokens: number;
747 cache_read_input_tokens: number;
748 } | null;
749};
750```
751
752Read token attribution from the collection fields:
753
754* `categories` holds the per-category totals.
755* `mcpTools` and `agents` attribute tokens to individual MCP tools and subagents.
756* `memoryFiles` lists each loaded memory file with its cost.
757* `skills.skillFrontmatter` attributes the skill listing's tokens to each included skill. The per-skill counts measure each skill's listing entry as Claude Code actually sends it, which can be shorter than the skill's full frontmatter. Compare `skills.totalSkills` with `skills.includedSkills` to see whether every discovered skill made it into the listing.
758
759`totalTokens` is the session's current context usage, and `maxTokens` is the window that usage is measured against. That window is the model's context window, or the lower auto-compaction window when one applies. Claude Code leaves the optional `deferredBuiltinTools`, `systemTools`, and `systemPromptSections` diagnostics unset, so expect them to be absent even though the type declares them.
760
640### `AgentDefinition`761### `AgentDefinition`
641 762
642Configuration for a subagent defined programmatically.763Configuration for a subagent defined programmatically.
696```817```
697 818
698| Value | Description | Location |819| Value | Description | Location |
699| :---------- | :---------------------------------------------- | :---------------------------- |820| :---------- | :------------------------------------------------------------------------ | :---------------------------- |
700| `'user'` | Global user settings | `~/.claude/settings.json` |821| `'user'` | Global user settings | `~/.claude/settings.json` |
701| `'project'` | Shared project settings (version controlled) | `.claude/settings.json` |822| `'project'` | Shared project settings (version controlled) | `.claude/settings.json` |
702| `'local'` | Local project settings (not version controlled) | `.claude/settings.local.json` |823| `'local'` | Local project settings, gitignored when Claude Code saves a setting to it | `.claude/settings.local.json` |
703 824
704#### Default behavior825#### Default behavior
705 826
710**Disable filesystem settings:**831**Disable filesystem settings:**
711 832
712```typescript theme={null}833```typescript theme={null}
834import { query } from "@anthropic-ai/claude-agent-sdk";
835
713// Do not load user, project, or local settings from disk836// Do not load user, project, or local settings from disk
714const result = query({837const result = query({
715 prompt: "Analyze this code",838 prompt: "Analyze this code",
720**Load all filesystem settings explicitly:**843**Load all filesystem settings explicitly:**
721 844
722```typescript theme={null}845```typescript theme={null}
846import { query } from "@anthropic-ai/claude-agent-sdk";
847
723const result = query({848const result = query({
724 prompt: "Analyze this code",849 prompt: "Analyze this code",
725 options: {850 options: {
731**Load only specific setting sources:**856**Load only specific setting sources:**
732 857
733```typescript theme={null}858```typescript theme={null}
859import { query } from "@anthropic-ai/claude-agent-sdk";
860
734// Load only project settings, ignore user and local861// Load only project settings, ignore user and local
735const result = query({862const result = query({
736 prompt: "Run CI checks",863 prompt: "Run CI checks",
743**Testing and CI environments:**870**Testing and CI environments:**
744 871
745```typescript theme={null}872```typescript theme={null}
873import { query } from "@anthropic-ai/claude-agent-sdk";
874
746// Ensure consistent behavior in CI by excluding local settings875// Ensure consistent behavior in CI by excluding local settings
747const result = query({876const result = query({
748 prompt: "Run tests",877 prompt: "Run tests",
749 options: {878 options: {
750 settingSources: ["project"], // Only team-shared settings879 settingSources: ["project"], // Only team-shared settings
751 permissionMode: "bypassPermissions"880 permissionMode: "bypassPermissions",
881 allowDangerouslySkipPermissions: true
752 }882 }
753});883});
754```884```
756**SDK-only applications:**886**SDK-only applications:**
757 887
758```typescript theme={null}888```typescript theme={null}
889import { query } from "@anthropic-ai/claude-agent-sdk";
890
759// Define everything programmatically.891// Define everything programmatically.
760// Pass [] to opt out of filesystem setting sources.892// Pass [] to opt out of filesystem setting sources.
761const result = query({893const result = query({
776**Loading CLAUDE.md project instructions:**908**Loading CLAUDE.md project instructions:**
777 909
778```typescript theme={null}910```typescript theme={null}
911import { query } from "@anthropic-ai/claude-agent-sdk";
912
779// Load project settings to include CLAUDE.md files913// Load project settings to include CLAUDE.md files
780const result = query({914const result = query({
781 prompt: "Add a new feature following project conventions",915 prompt: "Add a new feature following project conventions",
1036 message: BetaMessage; // From Anthropic SDK1170 message: BetaMessage; // From Anthropic SDK
1037 parent_tool_use_id: string | null;1171 parent_tool_use_id: string | null;
1038 error?: SDKAssistantMessageError;1172 error?: SDKAssistantMessageError;
1173 aborted?: true;
1039 timestamp?: string;1174 timestamp?: string;
1040};1175};
1041```1176```
1044 1179
1045`SDKAssistantMessageError` is one of: `'authentication_failed'`, `'oauth_org_not_allowed'`, `'billing_error'`, `'rate_limit'`, `'overloaded'`, `'invalid_request'`, `'model_not_found'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`. `'model_not_found'` means the selected model doesn't exist or isn't available to your account or deployment. `'overloaded'` means the API returned a 529 because the server is at capacity, as opposed to `'rate_limit'`, which is a 429 against your quota.1180`SDKAssistantMessageError` is one of: `'authentication_failed'`, `'oauth_org_not_allowed'`, `'billing_error'`, `'rate_limit'`, `'overloaded'`, `'invalid_request'`, `'model_not_found'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`. `'model_not_found'` means the selected model doesn't exist or isn't available to your account or deployment. `'overloaded'` means the API returned a 529 because the server is at capacity, as opposed to `'rate_limit'`, which is a 429 against your quota.
1046 1181
1182`aborted` is `true` when an interrupt or abort truncated the assistant message before the stream completed: the message has no `stop_reason` and the content may end mid-word. The field is absent on normally completed messages. It requires Agent SDK v0.3.214 or later.
1183
1047`timestamp` is the ISO 8601 time when the message's content finished generating on the process that produced it. The value comes from that machine's clock, so use it for display only and don't order messages by it. One API turn can produce several assistant messages that share a `message.id`, each with its own `timestamp`. When the field is absent, fall back to the time you received the message.1184`timestamp` is the ISO 8601 time when the message's content finished generating on the process that produced it. The value comes from that machine's clock, so use it for display only and don't order messages by it. One API turn can produce several assistant messages that share a `message.id`, each with its own `timestamp`. When the field is absent, fall back to the time you received the message.
1048 1185
1049### `SDKUserMessage`1186### `SDKUserMessage`
1110 stop_reason: string | null;1247 stop_reason: string | null;
1111 ttft_ms?: number;1248 ttft_ms?: number;
1112 ttft_stream_ms?: number;1249 ttft_stream_ms?: number;
1250 user_message_uuid?: string;
1251 request_sent_wall_ms?: number;
1113 total_cost_usd: number;1252 total_cost_usd: number;
1114 usage: NonNullableUsage;1253 usage: NonNullableUsage;
1115 modelUsage: { [modelName: string]: ModelUsage };1254 modelUsage: { [modelName: string]: ModelUsage };
1118 deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> };1257 deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> };
1119 terminal_reason?: TerminalReason;1258 terminal_reason?: TerminalReason;
1120 fast_mode_state?: FastModeState;1259 fast_mode_state?: FastModeState;
1260 fast_mode_disabled_reason?: FastModeDisabledReason;
1121 origin?: SDKMessageOrigin;1261 origin?: SDKMessageOrigin;
1122 }1262 }
1123 | {1263 | {
1141 errors: string[];1281 errors: string[];
1142 terminal_reason?: TerminalReason;1282 terminal_reason?: TerminalReason;
1143 fast_mode_state?: FastModeState;1283 fast_mode_state?: FastModeState;
1284 fast_mode_disabled_reason?: FastModeDisabledReason;
1144 origin?: SDKMessageOrigin;1285 origin?: SDKMessageOrigin;
1145 };1286 };
1146```1287```
1150* `api_error_status`: the HTTP status code of the API error that terminated the conversation. Absent or `null` when the turn ended without an API error.1291* `api_error_status`: the HTTP status code of the API error that terminated the conversation. Absent or `null` when the turn ended without an API error.
1151* `ttft_ms`: time to first token in milliseconds, measured when the first complete assistant message arrives. Present on the success arm only.1292* `ttft_ms`: time to first token in milliseconds, measured when the first complete assistant message arrives. Present on the success arm only.
1152* `ttft_stream_ms`: time in milliseconds until the first `message_start` stream event, when the response stream opens. Lower than `ttft_ms`; the gap between the two is time spent streaming the first message. Present on the success arm only.1293* `ttft_stream_ms`: time in milliseconds until the first `message_start` stream event, when the response stream opens. Lower than `ttft_ms`; the gap between the two is time spent streaming the first message. Present on the success arm only.
1294* {/* min-version: 2.1.216 */}`user_message_uuid`: the `uuid` of the [`SDKUserMessage`](#sdkusermessage) that started this turn, echoed back so you can match the result to the message you sent. Requires Claude Code v2.1.216 or later. Present on the success arm only, together with `request_sent_wall_ms`; absent on API-error results, subagent calls, and synthetic turns such as scheduled ones.
1295* `request_sent_wall_ms`: epoch milliseconds at which Claude Code dispatched the API request, for joins against server-side timestamps. Present only together with `user_message_uuid`.
1153* `terminal_reason`: why the loop ended. One of `"completed"`, `"max_turns"`, `"tool_deferred"`, `"aborted_streaming"`, `"aborted_tools"`, `"hook_stopped"`, `"stop_hook_prevented"`, `"background_requested"`, `"blocking_limit"`, `"rapid_refill_breaker"`, `"prompt_too_long"`, `"image_error"`, `"model_error"`, `"api_error"`, `"malformed_tool_use_exhausted"`, `"budget_exhausted"`, `"structured_output_retry_exhausted"`, `"tool_deferred_unavailable"`, or `"turn_setup_failed"`.1296* `terminal_reason`: why the loop ended. One of `"completed"`, `"max_turns"`, `"tool_deferred"`, `"aborted_streaming"`, `"aborted_tools"`, `"hook_stopped"`, `"stop_hook_prevented"`, `"background_requested"`, `"blocking_limit"`, `"rapid_refill_breaker"`, `"prompt_too_long"`, `"image_error"`, `"model_error"`, `"api_error"`, `"malformed_tool_use_exhausted"`, `"budget_exhausted"`, `"structured_output_retry_exhausted"`, `"tool_deferred_unavailable"`, or `"turn_setup_failed"`.
1154* `fast_mode_state`: one of `"on"`, `"off"`, or `"cooldown"`.1297* `fast_mode_state`: one of `"on"`, `"off"`, or `"cooldown"`.
1298* `fast_mode_disabled_reason`: {/* min-version: 2.1.219 */}why [fast mode](/docs/en/fast-mode) isn't available right now. Absent when nothing blocks fast mode, though a request may still run at standard speed. During the cooldown after a fast mode rate limit, Claude Code reports `fast_mode_state: "cooldown"` with no reason code and re-enables fast mode when the cooldown expires. Requires Claude Code v2.1.219 or later.
1299
1300Use the reason code to explain why fast mode is off in your own UI instead of re-deriving availability. Each code names the check that blocked fast mode:
1301
1302| Reason code | Meaning |
1303| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
1304| `free` | The account doesn't have the paid subscription or usage credits fast mode requires |
1305| `preference` | The organization has disabled fast mode |
1306| `extra_usage_disabled` | Usage credits are turned off for the account |
1307| `network_error` | The [availability check](/docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) couldn't reach `api.anthropic.com` |
1308| `unknown` | Claude Code couldn't determine availability |
1309| `not_first_party` | The session uses a provider other than the Anthropic API |
1310| `disabled_by_env` | [`CLAUDE_CODE_DISABLE_FAST_MODE`](/docs/en/env-vars) is set |
1311| `model_not_allowed` | The fast mode Opus model isn't in the organization's [`availableModels`](/docs/en/model-config#restrict-model-selection) allowlist |
1312| `sdk_opt_in_required` | The session hasn't opted in to fast mode: pass `fastMode: true` in the [`settings`](#options) option or through [`applyFlagSettings()`](#applyflagsettings) |
1313| `pending` | The availability check hasn't completed yet |
1314
1315The same pair of fields appears on [`SDKSystemMessage`](#sdksystemmessage) and on the [`SDKControlInitializeResponse`](#sdkcontrolinitializeresponse), so you can read the fast mode state before the first turn.
1155 1316
1156The `origin` field forwards the [`SDKMessageOrigin`](#sdkmessageorigin) of the user message that triggered this result. When a background task finishes and the SDK injects a synthetic follow-up turn, the resulting `SDKResultMessage` carries `origin: { kind: "task-notification" }`. Check this field to distinguish results that answer your prompt from results emitted for background-task follow-ups, so you can route or suppress the latter. The field is absent for results emitted before any user turn, such as startup errors.1317The `origin` field forwards the [`SDKMessageOrigin`](#sdkmessageorigin) of the user message that triggered this result. When a background task finishes and the SDK injects a synthetic follow-up turn, the resulting `SDKResultMessage` carries `origin: { kind: "task-notification" }`. Check this field to distinguish results that answer your prompt from results emitted for background-task follow-ups, so you can route or suppress the latter. The field is absent for results emitted before any user turn, such as startup errors.
1157 1318
1183 output_style: string;1344 output_style: string;
1184 skills: string[];1345 skills: string[];
1185 plugins: { name: string; path: string }[];1346 plugins: { name: string; path: string }[];
1347 fast_mode_state?: FastModeState;
1348 fast_mode_disabled_reason?: FastModeDisabledReason;
1186 capabilities?: string[];1349 capabilities?: string[];
1187};1350};
1188```1351```
1189 1352
1190{/* min-version: 2.1.205 */}1353`fast_mode_state` reports the session's [fast mode](/docs/en/fast-mode) state. {/* min-version: 2.1.219 */}When something blocks fast mode, `fast_mode_disabled_reason` names the check that blocked it; the field requires Claude Code v2.1.219 or later. For the reason codes and their meanings, see [`fast_mode_disabled_reason`](#sdkresultmessage) on the result message.
1191 1354
1192The `capabilities` array names the protocol behaviors this CLI implements, so you can feature-detect instead of comparing `claude_code_version` strings. It is an open set: ignore values you don't recognize, and check for the specific capability whose behavior you rely on. The field requires Claude Code v2.1.205 or later and is absent on earlier CLIs.1355The `capabilities` array names the protocol behaviors this CLI implements, so you can feature-detect instead of comparing `claude_code_version` strings. It is an open set: ignore values you don't recognize, and check for the specific capability whose behavior you rely on. The field requires Claude Code v2.1.205 or later and is absent on earlier CLIs.
1193 1356
1194| Capability | Meaning |1357| Capability | Meaning |
1195| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1358| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1196| `interrupt_receipt_v1` | [`interrupt()`](#query-object) resolves with an [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse) receipt naming the queued messages that survive the interrupt |1359| `interrupt_receipt_v1` | [`interrupt()`](#query-object) resolves with an [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse) receipt naming the queued messages that survive the interrupt |
1360| `interrupt_cancel_queued_v1` | {/* min-version: 2.1.219 */}The `interrupt` control request honors `cancel_queued: true`, cancelling the queued messages that would otherwise survive the interrupt and listing them on the receipt's `cancelled` field. See [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse). Requires Claude Code v2.1.219 or later |
1197 1361
1198### `SDKPartialAssistantMessage`1362### `SDKPartialAssistantMessage`
1199 1363
1328 kind: "peer";1492 kind: "peer";
1329 from: string;1493 from: string;
1330 name?: string;1494 name?: string;
1495 fromSession?: string;
1331 senderTaskId?: string;1496 senderTaskId?: string;
1332 body?: string;1497 body?: string;
1498 verifiedPeerPid?: number;
1333 }1499 }
1334 | { kind: "task-notification" }1500 | { kind: "task-notification" }
1335 | { kind: "coordinator" }1501 | { kind: "coordinator" }
1337```1503```
1338 1504
1339| `kind` | Meaning |1505| `kind` | Meaning |
1340| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1506| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1341| `human` | Direct input from the end user. If your application forwards what the user typed as a user message, set its `origin` to `{ kind: "human" }` explicitly: {/* min-version: 2.1.210 */}Claude Code treats a user message with no `origin` as unattributed, and checks that require a human-typed prompt, such as the [`ultracode` workflow keyword](/docs/en/workflows#ask-for-a-workflow-in-your-prompt), don't accept it. Before v2.1.210, Claude Code treated an absent `origin` on a user message as human input. |1507| `human` | Direct input from the end user. If your application forwards what the user typed as a user message, set its `origin` to `{ kind: "human" }` explicitly: {/* min-version: 2.1.210 */}Claude Code treats a user message with no `origin` as unattributed, and checks that require a human-typed prompt, such as the [`ultracode` workflow keyword](/docs/en/workflows#ask-for-a-workflow-in-your-prompt), don't accept it. Before v2.1.210, Claude Code treated an absent `origin` on a user message as human input. |
1342| `channel` | Message arriving on a [channel](/docs/en/channels). `server` is the source MCP server name. |1508| `channel` | Message arriving on a [channel](/docs/en/channels). `server` is the source MCP server name. |
1343| `peer` | Message from another agent. For an in-process [teammate](/docs/en/agent-teams) sending to `main` via `SendMessage`, `from` is the teammate's name and `senderTaskId` is its task ID. For a cross-session peer such as another local Claude Code process, `from` is the sender address and `senderTaskId` is absent. {/* min-version: 2.1.205 */}`name` and `body` require Claude Code v2.1.205 or later. `name` is the sender's display name, normalized by Claude Code: it strips Unicode control, format, surrogate, and line or paragraph separator code points, then trims the result and caps it at 64 code points with an ellipsis. `body` is the decoded message body with the peer envelope stripped, byte-exact with what the model sees. For a teammate message `body` is always present; for a cross-session peer it is present only when the turn is exactly one peer envelope formed by Claude Code. Render `name` and `body` instead of re-parsing the message text. |1509| `peer` | Message from another agent: an in-process [teammate](/docs/en/agent-teams) or a cross-session peer such as another local Claude Code process. See [Peer origin fields](#peer-origin-fields) for the per-field semantics and the trust model. |
1344| `task-notification` | Synthetic turn injected after a background task finished. See [`SDKTaskNotificationMessage`](#sdktasknotificationmessage). |1510| `task-notification` | Synthetic turn injected after a background task finished. See [`SDKTaskNotificationMessage`](#sdktasknotificationmessage). |
1345| `coordinator` | Message from a team coordinator in an [agent team](/docs/en/agent-teams). |1511| `coordinator` | Message from a team coordinator in an [agent team](/docs/en/agent-teams). |
1346| `auto-continuation` | Synthetic turn injected when the session continues without fresh user input, such as a command result that triggers a follow-up prompt. |1512| `auto-continuation` | Synthetic turn injected when the session continues without fresh user input, such as a command result that triggers a follow-up prompt. |
1347 1513
1514### Peer origin fields
1515
1516A `peer` origin identifies which agent sent the message: an in-process [teammate](/docs/en/agent-teams) sending to `main` with `SendMessage`, or a cross-session peer such as another local Claude Code process. The two kinds of sender fill the fields differently:
1517
1518* `from`: the teammate's name, or the sender address for a cross-session peer. The value is sender-authored; `verifiedPeerPid` is the verified identity.
1519* `senderTaskId`: the teammate's task ID. Absent for a cross-session peer.
1520* {/* min-version: 2.1.205 */}`name`: the sender's display name, normalized by Claude Code: it strips Unicode control, format, surrogate, and line or paragraph separator code points, then trims the result and caps it at 64 code points with an ellipsis. Requires Claude Code v2.1.205 or later.
1521* {/* min-version: 2.1.205 */}`body`: the decoded message body with the peer envelope stripped, byte-exact with what the model sees. Always present for a teammate message; for a cross-session peer, present only when the turn is exactly one peer envelope formed by Claude Code. Render `name` and `body` instead of re-parsing the message text. Requires Claude Code v2.1.205 or later.
1522* {/* min-version: 2.1.216 */}`fromSession`: the sender's host-openable session ID, set by the sender's host so your UI can link back to the sending session. Like `from`, it is sender-asserted: use it as a navigation target only, and don't treat it as proof of the sender's identity. Requires Claude Code v2.1.216 or later.
1523* {/* min-version: 2.1.216 */}`verifiedPeerPid`: the process ID of the process that connected to this session's cross-session messaging socket, verified by the kernel and read from the connection itself, never from the payload. Use it, not `from`, to identify the sender: `from` is forgeable by any same-user process. The field is absent when Claude Code can't verify it, such as on Windows or non-socket ingress, so an absent value means the sender is unverified. For relayed traffic it identifies the relay rather than the message's author, and process IDs are recyclable, so treat it as provenance rather than an authentication token. Requires Claude Code v2.1.216 or later.
1524
1348## Hook Types1525## Hook Types
1349 1526
1350For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](/docs/en/agent-sdk/hooks).1527For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](/docs/en/agent-sdk/hooks).
1365 | "SessionStart"1542 | "SessionStart"
1366 | "SessionEnd"1543 | "SessionEnd"
1367 | "Stop"1544 | "Stop"
1545 | "StopFailure"
1368 | "SubagentStart"1546 | "SubagentStart"
1369 | "SubagentStop"1547 | "SubagentStop"
1370 | "PreCompact"1548 | "PreCompact"
1549 | "PostCompact"
1371 | "PermissionRequest"1550 | "PermissionRequest"
1551 | "PermissionDenied"
1372 | "Setup"1552 | "Setup"
1373 | "TeammateIdle"1553 | "TeammateIdle"
1554 | "TaskCreated"
1374 | "TaskCompleted"1555 | "TaskCompleted"
1556 | "Elicitation"
1557 | "ElicitationResult"
1375 | "ConfigChange"1558 | "ConfigChange"
1559 | "DirectoryAdded"
1376 | "WorktreeCreate"1560 | "WorktreeCreate"
1377 | "WorktreeRemove"1561 | "WorktreeRemove"
1562 | "InstructionsLoaded"
1563 | "CwdChanged"
1564 | "FileChanged"
1378 | "MessageDisplay";1565 | "MessageDisplay";
1379```1566```
1380 1567
1412 | PostToolUseHookInput1599 | PostToolUseHookInput
1413 | PostToolUseFailureHookInput1600 | PostToolUseFailureHookInput
1414 | PostToolBatchHookInput1601 | PostToolBatchHookInput
1602 | PermissionDeniedHookInput
1415 | NotificationHookInput1603 | NotificationHookInput
1416 | UserPromptSubmitHookInput1604 | UserPromptSubmitHookInput
1605 | UserPromptExpansionHookInput
1417 | SessionStartHookInput1606 | SessionStartHookInput
1418 | SessionEndHookInput1607 | SessionEndHookInput
1419 | StopHookInput1608 | StopHookInput
1609 | StopFailureHookInput
1420 | SubagentStartHookInput1610 | SubagentStartHookInput
1421 | SubagentStopHookInput1611 | SubagentStopHookInput
1422 | PreCompactHookInput1612 | PreCompactHookInput
1613 | PostCompactHookInput
1423 | PermissionRequestHookInput1614 | PermissionRequestHookInput
1424 | SetupHookInput1615 | SetupHookInput
1425 | TeammateIdleHookInput1616 | TeammateIdleHookInput
1617 | TaskCreatedHookInput
1426 | TaskCompletedHookInput1618 | TaskCompletedHookInput
1619 | ElicitationHookInput
1620 | ElicitationResultHookInput
1427 | ConfigChangeHookInput1621 | ConfigChangeHookInput
1622 | InstructionsLoadedHookInput
1623 | DirectoryAddedHookInput
1428 | WorktreeCreateHookInput1624 | WorktreeCreateHookInput
1429 | WorktreeRemoveHookInput1625 | WorktreeRemoveHookInput
1626 | CwdChangedHookInput
1627 | FileChangedHookInput
1430 | MessageDisplayHookInput;1628 | MessageDisplayHookInput;
1431```1629```
1432 1630
1505};1703};
1506```1704```
1507 1705
1706#### `PermissionDeniedHookInput`
1707
1708```typescript theme={null}
1709type PermissionDeniedHookInput = BaseHookInput & {
1710 hook_event_name: "PermissionDenied";
1711 tool_name: string;
1712 tool_input: unknown;
1713 tool_use_id: string;
1714 reason: string;
1715};
1716```
1717
1508#### `NotificationHookInput`1718#### `NotificationHookInput`
1509 1719
1510```typescript theme={null}1720```typescript theme={null}
1522type UserPromptSubmitHookInput = BaseHookInput & {1732type UserPromptSubmitHookInput = BaseHookInput & {
1523 hook_event_name: "UserPromptSubmit";1733 hook_event_name: "UserPromptSubmit";
1524 prompt: string;1734 prompt: string;
1735 session_title?: string;
1736};
1737```
1738
1739#### `UserPromptExpansionHookInput`
1740
1741```typescript theme={null}
1742type UserPromptExpansionHookInput = BaseHookInput & {
1743 hook_event_name: "UserPromptExpansion";
1744 expansion_type: "slash_command" | "mcp_prompt";
1745 command_name: string;
1746 command_args: string;
1747 command_source?: string;
1748 prompt: string;
1525};1749};
1526```1750```
1527 1751
1530```typescript theme={null}1754```typescript theme={null}
1531type SessionStartHookInput = BaseHookInput & {1755type SessionStartHookInput = BaseHookInput & {
1532 hook_event_name: "SessionStart";1756 hook_event_name: "SessionStart";
1533 source: "startup" | "resume" | "clear" | "compact";1757 source: "startup" | "resume" | "clear" | "compact" | "fork";
1534 agent_type?: string;1758 agent_type?: string;
1535 model?: string;1759 model?: string;
1760 session_title?: string;
1536};1761};
1537```1762```
1538 1763
1557};1782};
1558```1783```
1559 1784
1785#### `StopFailureHookInput`
1786
1787```typescript theme={null}
1788type StopFailureHookInput = BaseHookInput & {
1789 hook_event_name: "StopFailure";
1790 error: SDKAssistantMessageError;
1791 error_details?: string;
1792 last_assistant_message?: string;
1793};
1794```
1795
1560#### `SubagentStartHookInput`1796#### `SubagentStartHookInput`
1561 1797
1562```typescript theme={null}1798```typescript theme={null}
1611};1847};
1612```1848```
1613 1849
1850#### `PostCompactHookInput`
1851
1852```typescript theme={null}
1853type PostCompactHookInput = BaseHookInput & {
1854 hook_event_name: "PostCompact";
1855 trigger: "manual" | "auto";
1856 compact_summary: string;
1857};
1858```
1859
1614#### `PermissionRequestHookInput`1860#### `PermissionRequestHookInput`
1615 1861
1616```typescript theme={null}1862```typescript theme={null}
1642};1888};
1643```1889```
1644 1890
1891#### `TaskCreatedHookInput`
1892
1893```typescript theme={null}
1894type TaskCreatedHookInput = BaseHookInput & {
1895 hook_event_name: "TaskCreated";
1896 task_id: string;
1897 task_subject: string;
1898 task_description?: string;
1899 teammate_name?: string;
1900 /** @deprecated since v2.1.178. Carries the session-derived team name; will be removed. */
1901 team_name?: string;
1902};
1903```
1904
1645#### `TaskCompletedHookInput`1905#### `TaskCompletedHookInput`
1646 1906
1647```typescript theme={null}1907```typescript theme={null}
1656};1916};
1657```1917```
1658 1918
1919#### `ElicitationHookInput`
1920
1921```typescript theme={null}
1922type ElicitationHookInput = BaseHookInput & {
1923 hook_event_name: "Elicitation";
1924 mcp_server_name: string;
1925 message: string;
1926 mode?: "form" | "url";
1927 url?: string;
1928 elicitation_id?: string;
1929 requested_schema?: Record<string, unknown>;
1930};
1931```
1932
1933#### `ElicitationResultHookInput`
1934
1935```typescript theme={null}
1936type ElicitationResultHookInput = BaseHookInput & {
1937 hook_event_name: "ElicitationResult";
1938 mcp_server_name: string;
1939 elicitation_id?: string;
1940 mode?: "form" | "url";
1941 action: "accept" | "decline" | "cancel";
1942 content?: Record<string, unknown>;
1943};
1944```
1945
1659#### `ConfigChangeHookInput`1946#### `ConfigChangeHookInput`
1660 1947
1661```typescript theme={null}1948```typescript theme={null}
1671};1958};
1672```1959```
1673 1960
1961#### `InstructionsLoadedHookInput`
1962
1963```typescript theme={null}
1964type InstructionsLoadedHookInput = BaseHookInput & {
1965 hook_event_name: "InstructionsLoaded";
1966 file_path: string;
1967 memory_type: "User" | "Project" | "Local" | "Managed";
1968 load_reason:
1969 | "session_start"
1970 | "nested_traversal"
1971 | "path_glob_match"
1972 | "include"
1973 | "compact";
1974 globs?: string[];
1975 trigger_file_path?: string;
1976 parent_file_path?: string;
1977};
1978```
1979
1980#### `DirectoryAddedHookInput`
1981
1982```typescript theme={null}
1983type DirectoryAddedHookInput = BaseHookInput & {
1984 hook_event_name: "DirectoryAdded";
1985 directory: string;
1986 source: "slash_command" | "register_repo_root";
1987};
1988```
1989
1990`directory` is the absolute path of the directory that was added. `source` is `"slash_command"` when `/add-dir` added it and `"register_repo_root"` when the SDK control request did.
1991
1674#### `WorktreeCreateHookInput`1992#### `WorktreeCreateHookInput`
1675 1993
1676```typescript theme={null}1994```typescript theme={null}
1689};2007};
1690```2008```
1691 2009
2010#### `CwdChangedHookInput`
2011
2012```typescript theme={null}
2013type CwdChangedHookInput = BaseHookInput & {
2014 hook_event_name: "CwdChanged";
2015 old_cwd: string;
2016 new_cwd: string;
2017};
2018```
2019
2020#### `FileChangedHookInput`
2021
2022```typescript theme={null}
2023type FileChangedHookInput = BaseHookInput & {
2024 hook_event_name: "FileChanged";
2025 file_path: string;
2026 event: "change" | "add" | "unlink";
2027};
2028```
2029
1692#### `MessageDisplayHookInput`2030#### `MessageDisplayHookInput`
1693 2031
1694```typescript theme={null}2032```typescript theme={null}
1728 stopReason?: string;2066 stopReason?: string;
1729 decision?: "approve" | "block";2067 decision?: "approve" | "block";
1730 systemMessage?: string;2068 systemMessage?: string;
2069 /**
2070 * A terminal escape sequence (e.g. OSC 9 / OSC 777 desktop-notification)
2071 * for Claude Code to emit on your behalf. Only notification/title OSCs
2072 * (0, 1, 2, 9, 99, 777) and BEL are permitted; a value containing
2073 * anything else is ignored as a whole.
2074 */
2075 terminalSequence?: string;
1731 reason?: string;2076 reason?: string;
1732 hookSpecificOutput?:2077 hookSpecificOutput?:
1733 | {2078 | {
1740 | {2085 | {
1741 hookEventName: "UserPromptSubmit";2086 hookEventName: "UserPromptSubmit";
1742 additionalContext?: string;2087 additionalContext?: string;
2088 sessionTitle?: string;
2089 /** When decision is "block", omit the original prompt from the block message. */
2090 suppressOriginalPrompt?: boolean;
2091 }
2092 | {
2093 hookEventName: "UserPromptExpansion";
2094 additionalContext?: string;
1743 }2095 }
1744 | {2096 | {
1745 hookEventName: "SessionStart";2097 hookEventName: "SessionStart";
1746 additionalContext?: string;2098 additionalContext?: string;
2099 initialUserMessage?: string;
2100 sessionTitle?: string;
2101 watchPaths?: string[];
2102 /**
2103 * Re-scan skill and command directories after SessionStart hooks
2104 * complete, so skills installed by the hook are available in the
2105 * same session.
2106 */
2107 reloadSkills?: boolean;
1747 }2108 }
1748 | {2109 | {
1749 hookEventName: "Setup";2110 hookEventName: "Setup";
1768 hookEventName: "PostToolBatch";2129 hookEventName: "PostToolBatch";
1769 additionalContext?: string;2130 additionalContext?: string;
1770 }2131 }
2132 | {
2133 hookEventName: "Stop";
2134 additionalContext?: string;
2135 }
2136 | {
2137 hookEventName: "SubagentStop";
2138 additionalContext?: string;
2139 }
2140 | {
2141 hookEventName: "PermissionDenied";
2142 retry?: boolean;
2143 }
1771 | {2144 | {
1772 hookEventName: "Notification";2145 hookEventName: "Notification";
1773 additionalContext?: string;2146 additionalContext?: string;
1785 message?: string;2158 message?: string;
1786 interrupt?: boolean;2159 interrupt?: boolean;
1787 };2160 };
2161 }
2162 | {
2163 hookEventName: "Elicitation";
2164 action?: "accept" | "decline" | "cancel";
2165 content?: Record<string, unknown>;
2166 }
2167 | {
2168 hookEventName: "ElicitationResult";
2169 action?: "accept" | "decline" | "cancel";
2170 content?: Record<string, unknown>;
2171 }
2172 | {
2173 hookEventName: "CwdChanged";
2174 watchPaths?: string[];
2175 }
2176 | {
2177 hookEventName: "FileChanged";
2178 watchPaths?: string[];
2179 }
2180 | {
2181 hookEventName: "WorktreeCreate";
2182 worktreePath: string;
2183 }
2184 | {
2185 hookEventName: "MessageDisplay";
2186 /** Text displayed in place of the delta. Omit (or return the delta unchanged) to display the original. */
2187 displayContent?: string;
1788 };2188 };
1789};2189};
1790```2190```
1795 2195
1796### `ToolInputSchemas`2196### `ToolInputSchemas`
1797 2197
1798Union of all tool input types, exported from `@anthropic-ai/claude-agent-sdk`.2198Union of tool input types exported from `@anthropic-ai/claude-agent-sdk`; members include:
1799 2199
1800```typescript theme={null}2200```typescript theme={null}
1801type ToolInputSchemas =2201type ToolInputSchemas =
1802 | AgentInput2202 | AgentInput
2203 | ArtifactInput
1803 | AskUserQuestionInput2204 | AskUserQuestionInput
1804 | BashInput2205 | BashInput
1805 | TaskOutputInput2206 | CronCreateInput
2207 | CronDeleteInput
2208 | CronListInput
2209 | EnterPlanModeInput
1806 | EnterWorktreeInput2210 | EnterWorktreeInput
1807 | ExitPlanModeInput2211 | ExitPlanModeInput
2212 | ExitWorktreeInput
1808 | FileEditInput2213 | FileEditInput
1809 | FileReadInput2214 | FileReadInput
1810 | FileWriteInput2215 | FileWriteInput
1814 | McpInput2219 | McpInput
1815 | MonitorInput2220 | MonitorInput
1816 | NotebookEditInput2221 | NotebookEditInput
2222 | ProjectsInput
2223 | PushNotificationInput
2224 | ReadMcpResourceDirInput
1817 | ReadMcpResourceInput2225 | ReadMcpResourceInput
1818 | SubscribeMcpResourceInput2226 | RefreshMcpToolsInput
1819 | SubscribePollingInput2227 | RemoteTriggerInput
2228 | REPLInput
2229 | ReportFindingsInput
2230 | ScheduleWakeupInput
2231 | ShowOnboardingRolePickerInput
1820 | TaskCreateInput2232 | TaskCreateInput
1821 | TaskGetInput2233 | TaskGetInput
1822 | TaskListInput2234 | TaskListInput
2235 | TaskOutputInput
1823 | TaskStopInput2236 | TaskStopInput
1824 | TaskUpdateInput2237 | TaskUpdateInput
1825 | TodoWriteInput2238 | TodoWriteInput
1826 | UnsubscribeMcpResourceInput
1827 | UnsubscribePollingInput
1828 | WebFetchInput2239 | WebFetchInput
1829 | WebSearchInput2240 | WebSearchInput
1830 | WorkflowInput;2241 | WorkflowInput;
1832 2243
1833### Agent2244### Agent
1834 2245
1835**Tool name:** `Agent` (previously `Task`, which is still accepted as an alias)2246**Tool name:** `Agent`. The previous name `Task` is still accepted as an alias, and the `tools` array in the [`SDKSystemMessage`](#sdksystemmessage) init message currently lists this tool as `Task` for backward compatibility.
1836 2247
1837<Note>2248<Note>
1838 {/* min-version: 2.1.212 */}The `mode` field is deprecated and ignored on Claude Code v2.1.212 or later: subagents [inherit the parent session's permission mode](/docs/en/agent-sdk/permissions#available-modes), and a subagent definition's [`permissionMode`](#agentdefinition) can override it, except when the parent uses `bypassPermissions`, `acceptEdits`, or `auto`.2249 {/* min-version: 2.1.212 */}The `mode` field is deprecated and ignored on Claude Code v2.1.212 or later: subagents [inherit the parent session's permission mode](/docs/en/agent-sdk/permissions#available-modes), and a subagent definition's [`permissionMode`](#agentdefinition) can override it, except when the parent uses `bypassPermissions`, `acceptEdits`, or `auto`.
1846 model?: "sonnet" | "opus" | "haiku" | "fable";2257 model?: "sonnet" | "opus" | "haiku" | "fable";
1847 run_in_background?: boolean;2258 run_in_background?: boolean;
1848 name?: string;2259 name?: string;
1849 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan";2260 team_name?: string; // Deprecated; ignored
2261 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan"; // Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it
1850 isolation?: "worktree" | "remote";2262 isolation?: "worktree" | "remote";
1851};2263};
1852```2264```
1865 options: Array<{ label: string; description: string; preview?: string }>;2277 options: Array<{ label: string; description: string; preview?: string }>;
1866 multiSelect: boolean;2278 multiSelect: boolean;
1867 }>;2279 }>;
2280 answers?: Record<string, string>;
2281 annotations?: Record<string, { preview?: string; notes?: string }>;
2282 metadata?: { source?: string };
1868};2283};
1869```2284```
1870 2285
1898 protocols?: string[];2313 protocols?: string[];
1899 };2314 };
1900 description: string;2315 description: string;
1901 timeout_ms?: number;2316 timeout_ms: number;
1902 persistent?: boolean;2317 persistent: boolean;
1903};2318};
1904```2319```
1905 2320
1906Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. {/* min-version: 2.1.195 */}The `ws` source requires Claude Code v2.1.195 or later.2321Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. {/* min-version: 2.1.195 */}The `ws` source requires Claude Code v2.1.195 or later.
1907 2322
1908Set `persistent: true` for session-length watches such as log tails. When Monitor runs a command, it follows the same permission rules as Bash; a WebSocket watch prompts for approval separately. See the [Monitor tool reference](/docs/en/tools-reference#monitor-tool) for behavior and provider availability.2323Set `persistent: true` for session-length watches such as log tails. When Monitor runs a command, it follows the same permission rules as Bash; a WebSocket watch prompts for approval separately. See the [Monitor tool reference](/docs/en/tools-reference#monitor-tool) for behavior and provider availability. The exported type marks `timeout_ms` and `persistent` as required because the schema fills in their defaults, 300000 and `false`; a call that omits them validates.
1909 2324
1910### TaskOutput2325### TaskOutput
1911 2326
1912**Tool name:** `TaskOutput`2327**Tool name:** `TaskOutput`
1913 2328
2329<Note>`TaskOutput` is deprecated; prefer `Read` on the task's output file path. {/* min-version: 2.1.83 */}Deprecated since Claude Code v2.1.83. The schemas below remain valid for hooks and permission handlers that encounter the tool.</Note>
2330
1914```typescript theme={null}2331```typescript theme={null}
1915type TaskOutputInput = {2332type TaskOutputInput = {
1916 task_id: string;2333 task_id: string;
1989 type?: string;2406 type?: string;
1990 output_mode?: "content" | "files_with_matches" | "count";2407 output_mode?: "content" | "files_with_matches" | "count";
1991 "-i"?: boolean;2408 "-i"?: boolean;
2409 "-o"?: boolean; // print only the matched parts of each line; requires output_mode: "content"
1992 "-n"?: boolean;2410 "-n"?: boolean;
1993 "-B"?: number;2411 "-B"?: number;
1994 "-A"?: number;2412 "-A"?: number;
2067 script?: string;2485 script?: string;
2068 name?: string;2486 name?: string;
2069 scriptPath?: string;2487 scriptPath?: string;
2070 args?: unknown;2488 args?: unknown; // any JSON value; the published typings render this as an object map
2071 resumeFromRunId?: string;2489 resumeFromRunId?: string;
2490 title?: string; // ignored; the script's meta block sets the title
2491 description?: string; // ignored; the script's meta block sets the description
2072};2492};
2073```2493```
2074 2494
2081| `scriptPath` | `string` | Path to a workflow script file on disk. Takes precedence over `script` and `name`. Every invocation persists its script and returns the path in the result, so you can edit that file and re-invoke with the same `scriptPath` to iterate |2501| `scriptPath` | `string` | Path to a workflow script file on disk. Takes precedence over `script` and `name`. Every invocation persists its script and returns the path in the result, so you can edit that file and re-invoke with the same `scriptPath` to iterate |
2082| `args` | `unknown` | Input value exposed to the script as the global `args`, for parameterized named workflows such as a research question or a list of file paths. Pass arrays and objects as actual JSON values, not as a JSON-encoded string |2502| `args` | `unknown` | Input value exposed to the script as the global `args`, for parameterized named workflows such as a research question or a list of file paths. Pass arrays and objects as actual JSON values, not as a JSON-encoded string |
2083| `resumeFromRunId` | `string` | Run ID of a prior `Workflow` invocation to resume. Completed `agent()` calls with unchanged inputs return cached results; only changed or new calls run live. Same session only |2503| `resumeFromRunId` | `string` | Run ID of a prior `Workflow` invocation to resume. Completed `agent()` calls with unchanged inputs return cached results; only changed or new calls run live. Same session only |
2504| `title` | `string` | Ignored; the script's `meta` block sets the title |
2505| `description` | `string` | Ignored; the script's `meta` block sets the description |
2506
2507The schema accepts any JSON value for `args`; the exported type marks it `unknown`, but the published typings render the field as an object map.
2084 2508
2085### TodoWrite2509### TodoWrite
2086 2510
2170 tool: "Bash";2594 tool: "Bash";
2171 prompt: string;2595 prompt: string;
2172 }>;2596 }>;
2597 [k: string]: unknown;
2173};2598};
2174```2599```
2175 2600
2213 2638
2214Creates and enters a temporary git worktree for isolated work. Pass `path` to switch into an existing worktree instead of creating a new one. On first entry the target must be a registered worktree of the current repository or, in a multi-repo workspace, of a repository nested inside it; from within a worktree session it must be under `.claude/worktrees/` of the session's repository. `name` and `path` are mutually exclusive.2639Creates and enters a temporary git worktree for isolated work. Pass `path` to switch into an existing worktree instead of creating a new one. On first entry the target must be a registered worktree of the current repository or, in a multi-repo workspace, of a repository nested inside it; from within a worktree session it must be under `.claude/worktrees/` of the session's repository. `name` and `path` are mutually exclusive.
2215 2640
2641### ExitWorktree
2642
2643**Tool name:** `ExitWorktree`
2644
2645```typescript theme={null}
2646type ExitWorktreeInput = {
2647 action: "keep" | "remove";
2648 discard_changes?: boolean;
2649};
2650```
2651
2652Exits the current git worktree and returns to the original working directory. The `keep` action leaves the worktree and branch on disk, while `remove` deletes both. `discard_changes` must be `true` when removing a worktree that has uncommitted files or unmerged commits.
2653
2654### EnterPlanMode
2655
2656**Tool name:** `EnterPlanMode`
2657
2658```typescript theme={null}
2659type EnterPlanModeInput = {};
2660```
2661
2662Enters plan mode, where Claude researches and presents a plan before making changes.
2663
2664### CronCreate
2665
2666**Tool name:** `CronCreate`
2667
2668```typescript theme={null}
2669type CronCreateInput = {
2670 cron: string;
2671 prompt: string;
2672 recurring?: boolean;
2673 durable?: boolean;
2674};
2675```
2676
2677Schedules a prompt to run on a 5-field cron schedule in local time. Set `recurring` to `false` to fire once at the next match. Jobs are session-scoped by default: starting a fresh conversation clears them, and resuming with `--resume` or `--continue` restores jobs that haven't expired. See [Scheduled tasks](/docs/en/scheduled-tasks).
2678
2679Setting `durable` to `true` requests persistence to `.claude/scheduled_tasks.json` so the job survives restarts. Durable scheduling isn't available in every session: when it isn't, Claude Code accepts `durable: true` but creates the job session-only. Read the output's `durable` field to see whether the job persisted.
2680
2681### CronDelete
2682
2683**Tool name:** `CronDelete`
2684
2685```typescript theme={null}
2686type CronDeleteInput = {
2687 id: string;
2688};
2689```
2690
2691Deletes a scheduled cron job by the ID returned from `CronCreate`.
2692
2693### CronList
2694
2695**Tool name:** `CronList`
2696
2697```typescript theme={null}
2698type CronListInput = {};
2699```
2700
2701Lists the scheduled cron jobs: durable jobs from `.claude/scheduled_tasks.json` and session-only jobs from the current session.
2702
2703### ScheduleWakeup
2704
2705**Tool name:** `ScheduleWakeup`
2706
2707```typescript theme={null}
2708type ScheduleWakeupInput = {
2709 delaySeconds?: number;
2710 reason?: string;
2711 prompt?: string;
2712 stop?: boolean;
2713};
2714```
2715
2716Schedules a one-shot wake-up that fires the given prompt after a delay. This tool backs the self-paced `/loop` command. The runtime clamps `delaySeconds` to between 60 and 3600 seconds. The `delaySeconds`, `reason`, and `prompt` fields are required unless `stop` is true. {/* min-version: 2.1.202 */}Setting `stop: true` cancels the pending wakeup and ends the self-paced `/loop`. The `stop` field requires Claude Code v2.1.202 or later. See the [ScheduleWakeup row in the tools reference](/docs/en/tools-reference) for provider availability; it isn't available on Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform, or Microsoft Foundry.
2717
2718### RemoteTrigger
2719
2720**Tool name:** `RemoteTrigger`
2721
2722```typescript theme={null}
2723type RemoteTriggerInput = {
2724 action: "list" | "get" | "create" | "update" | "run";
2725 trigger_id?: string;
2726 body?: {
2727 [k: string]: unknown;
2728 };
2729};
2730```
2731
2732Manages [Routines](/docs/en/routines), the scheduled and triggered Claude Code runs hosted on Anthropic-managed cloud infrastructure. This tool backs the `/schedule` command. `trigger_id` is required for the `get`, `update`, and `run` actions. `body` is required for `create` and `update`, and optional for `run`.
2733
2734This tool is available only when the session is authenticated with a claude.ai account on a plan with Routines enabled.
2735
2736### PushNotification
2737
2738**Tool name:** `PushNotification`
2739
2740```typescript theme={null}
2741type PushNotificationInput = {
2742 message: string;
2743 status: "proactive";
2744};
2745```
2746
2747Sends a proactive push notification to the user. Keep `message` under 200 characters because mobile operating systems truncate longer text. See the [PushNotification row in the tools reference](/docs/en/tools-reference) for provider availability; push delivery runs through Anthropic-hosted infrastructure that isn't accessible from Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform, or Microsoft Foundry.
2748
2749### REPL
2750
2751**Tool name:** `REPL`
2752
2753```typescript theme={null}
2754type REPLInput = {
2755 code: string;
2756 description?: string;
2757 timeout?: number;
2758};
2759```
2760
2761Executes JavaScript code in a persistent REPL. State persists across calls and top-level await is supported. `timeout` is in milliseconds, with a default of 30000 and a maximum of 600000.
2762
2763The types are exported, but the tool is off in SDK sessions unless you set `CLAUDE_CODE_REPL=1` in the [`env` option](#options). It also requires the Bun-based `claude` executable that the native installer provides.
2764
2765### ReportFindings
2766
2767**Tool name:** `ReportFindings`
2768
2769```typescript theme={null}
2770type ReportFindingsInput = {
2771 level?: "low" | "medium" | "high" | "xhigh" | "max";
2772 findings: Array<{
2773 file: string;
2774 line?: number;
2775 summary: string;
2776 failure_scenario: string;
2777 short_summary?: string;
2778 category?: string;
2779 verdict?: "CONFIRMED" | "PLAUSIBLE";
2780 outcome?: "fixed" | "skipped" | "no_change_needed";
2781 }>;
2782};
2783```
2784
2785Reports code-review findings as a structured list so Claude Code can render them instead of printing them as text. `level` is the effort level the review ran at. Findings are ordered most-severe first, with at most 32 per call, and the array is empty when none survived. Requires Claude Code v2.1.196 or later.
2786
2787Each finding carries these fields:
2788
2789* `file`: repo-relative path the finding is in. The optional `line` is the 1-indexed line it anchors to.
2790* `summary`: one-sentence statement of the defect. `failure_scenario` describes the concrete inputs and state that lead to the wrong output or crash.
2791* `short_summary`: optional compressed label of at most 60 characters for compact display. {/* min-version: 2.1.212 */}Requires Claude Code v2.1.212 or later.
2792* `category`: optional short kebab-case slug of the finding type, such as `correctness` or `test-coverage`. {/* min-version: 2.1.199 */}Requires Claude Code v2.1.199 or later.
2793* `verdict`: set when a verify pass ran; absent on inline-only reviews.
2794* `outcome`: set only when re-reporting after applying fixes.
2795
2796### Artifact
2797
2798**Tool name:** `Artifact`
2799
2800```typescript theme={null}
2801type ArtifactInput = {
2802 action?: "publish" | "list";
2803 file_path?: string;
2804 favicon?: string;
2805 limit?: number;
2806 scope?: "mine" | "shared" | "all";
2807 title?: string;
2808 description?: string;
2809 label?: string;
2810 url?: string;
2811 force?: boolean;
2812};
2813```
2814
2815Publishes a local `.html` or `.md` file as a hosted artifact page, or lists the user's published artifacts. Omit `action` or pass `"publish"` to publish `file_path`, which is required for the publish action along with `favicon`, one or two emoji for the browser tab. `title` names the published page in the browser tab and gallery when the HTML file has no `<title>` tag. `url` targets an existing artifact to update in place instead of minting a new one, and `force` is a last-resort overwrite that discards another session's published version; on a 409 conflict the normal fix is to re-read, merge, and publish again rather than pass `force`.
2816
2817Pass `"list"` to enumerate the user's published artifacts; only `limit` and `scope` may accompany it. `scope` defaults to `"mine"`, which lists artifacts the user owns; `"shared"` lists artifacts other people shared with the user, and `"all"` lists both.
2818
2819The types are exported, but the tool is off by default in Agent SDK sessions. Publishing also requires every condition in the [artifacts availability table](/docs/en/artifacts#availability), which sessions authenticated with an API key don't meet.
2820
2821### Projects
2822
2823**Tool name:** `Projects`
2824
2825```typescript theme={null}
2826type ProjectsInput = {
2827 method:
2828 | "project_info"
2829 | "project_read"
2830 | "project_search"
2831 | "project_write"
2832 | "project_delete";
2833 path?: string;
2834 content?: string;
2835 local_path?: string;
2836 present_to_user?: boolean;
2837 query?: string;
2838 n?: number;
2839};
2840```
2841
2842Reads and writes the claude.ai Project attached to the session. Dispatches on `method`:
2843
2844* `project_info`: returns project metadata and the doc list.
2845* `project_read`: reads one doc by `path`.
2846* `project_search`: queries the project's knowledge base with `query`. `n` caps the hits and defaults to 5.
2847* `project_write`: creates or replaces a doc at `path` from exactly one of `content`, which carries inline text, or `local_path`, which names a file inside the working directory. `present_to_user: true` marks the written doc as the deliverable the user needs to see.
2848* `project_delete`: deletes a doc by `path`.
2849
2850### ReadMcpResourceDir
2851
2852**Tool name:** `ReadMcpResourceDirTool`
2853
2854```typescript theme={null}
2855type ReadMcpResourceDirInput = {
2856 server: string;
2857 uri: string;
2858};
2859```
2860
2861Lists the direct children of a directory resource on an MCP server. Only usable against a server that has declared support for directory listing; the listing isn't recursive. Directory listing isn't enabled in every session: when it's off, the call returns an empty `resources` list and the `error` field reports that directory listing isn't enabled.
2862
2863### RefreshMcpTools
2864
2865**Tool name:** `RefreshMcpTools`
2866
2867```typescript theme={null}
2868type RefreshMcpToolsInput = {
2869 server?: string; // refresh only this server; omit to refresh all connected servers
2870};
2871```
2872
2873Re-queries the tool list of connected MCP servers and applies any changes. The types are exported, but Claude Code registers the tool only when you set `CLAUDE_CODE_ENABLE_REFRESH_MCP_TOOLS=1` in the [`env` option](#options), and only in sessions with at least one MCP server. {/* min-version: 2.1.211 */}Requires Claude Code v2.1.211 or later.
2874
2875### ShowOnboardingRolePicker
2876
2877**Tool name:** `ShowOnboardingRolePicker`
2878
2879```typescript theme={null}
2880type ShowOnboardingRolePickerInput = {};
2881```
2882
2883Renders a clickable role-picker chip row during Cowork onboarding so the user can pick their role and get a matching plugin installed. Takes no arguments; the role list is defined by the client. The call blocks until the user responds.
2884
2885### McpInput
2886
2887**Tool name:** dynamic MCP tool names of the form `mcp__<server>__<tool>`
2888
2889```typescript theme={null}
2890type McpInput = {
2891 [k: string]: unknown;
2892};
2893```
2894
2895MCP tool arguments are an open object: each server defines its own parameters, so the type places no constraints on field names or values. Consult the server's own tool schema for the fields a specific tool accepts.
2896
2216## Tool Output Types2897## Tool Output Types
2217 2898
2218Documentation of output schemas for all built-in Claude Code tools. These types are exported from `@anthropic-ai/claude-agent-sdk` and represent the actual response data returned by each tool.2899Documentation of output schemas for all built-in Claude Code tools. These types are exported from `@anthropic-ai/claude-agent-sdk` and represent the actual response data returned by each tool.
2219 2900
2220### `ToolOutputSchemas`2901### `ToolOutputSchemas`
2221 2902
2222Union of all tool output types.2903Union of tool output types exported from `@anthropic-ai/claude-agent-sdk`; members include:
2223 2904
2224```typescript theme={null}2905```typescript theme={null}
2225type ToolOutputSchemas =2906type ToolOutputSchemas =
2226 | AgentOutput2907 | AgentOutput
2908 | ArtifactOutput
2227 | AskUserQuestionOutput2909 | AskUserQuestionOutput
2228 | BashOutput2910 | BashOutput
2911 | CronCreateOutput
2912 | CronDeleteOutput
2913 | CronListOutput
2914 | EnterPlanModeOutput
2229 | EnterWorktreeOutput2915 | EnterWorktreeOutput
2230 | ExitPlanModeOutput2916 | ExitPlanModeOutput
2917 | ExitWorktreeOutput
2231 | FileEditOutput2918 | FileEditOutput
2232 | FileReadOutput2919 | FileReadOutput
2233 | FileWriteOutput2920 | FileWriteOutput
2234 | GlobOutput2921 | GlobOutput
2235 | GrepOutput2922 | GrepOutput
2236 | ListMcpResourcesOutput2923 | ListMcpResourcesOutput
2924 | McpOutput
2237 | MonitorOutput2925 | MonitorOutput
2238 | NotebookEditOutput2926 | NotebookEditOutput
2927 | ProjectsOutput
2928 | PushNotificationOutput
2929 | ReadMcpResourceDirOutput
2239 | ReadMcpResourceOutput2930 | ReadMcpResourceOutput
2931 | RefreshMcpToolsOutput
2932 | RemoteTriggerOutput
2933 | REPLOutput
2934 | ReportFindingsOutput
2935 | ScheduleWakeupOutput
2936 | ShowOnboardingRolePickerOutput
2240 | TaskCreateOutput2937 | TaskCreateOutput
2241 | TaskGetOutput2938 | TaskGetOutput
2242 | TaskListOutput2939 | TaskListOutput
2250 2947
2251### Agent2948### Agent
2252 2949
2253**Tool name:** `Agent` (previously `Task`, which is still accepted as an alias)2950**Tool name:** `Agent`. The previous name `Task` is still accepted as an alias, and the `tools` array in the [`SDKSystemMessage`](#sdksystemmessage) init message currently lists this tool as `Task` for backward compatibility.
2254 2951
2255```typescript theme={null}2952```typescript theme={null}
2256type AgentOutput =2953type AgentOutput =
2319 3016
2320Returns the result from the subagent. Discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it.3017Returns the result from the subagent. Discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it.
2321 3018
2322The `resolvedModel` field on the `completed` and `async_launched` variants names the model the subagent actually ran on, which can differ from the requested `model` input when [`availableModels`](/docs/en/model-config#restrict-model-selection) or another override applies. {/* min-version: 2.1.174 */}This field requires Claude Code v2.1.174 or later. {/* min-version: 2.1.212 */}On `async_launched`, it names the model in use when the task moved to the background.3019On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](/docs/en/model-config#restrict-model-selection) or another override applies. {/* min-version: 2.1.174 */}This field requires Claude Code v2.1.174 or later. {/* min-version: 2.1.212 */}On `async_launched`, it names the model in use when the task moved to the background.
2323 3020
2324`modelsUsed` lists the models the subagent used, in order. The field is present only when a mid-run swap happened, and a model appears again when the run swapped back to it. On `async_launched`, the list covers the models used before backgrounding. {/* min-version: 2.1.212 */}Both `modelsUsed` and the backgrounding behavior of `resolvedModel` require Claude Code v2.1.212 or later.3021`modelsUsed` lists the models the subagent used, in order. The field is present only when a mid-run swap happened, and a model appears again when the run swapped back to it. On `async_launched`, the list covers the models used before backgrounding. {/* min-version: 2.1.212 */}Both `modelsUsed` and the backgrounding behavior of `resolvedModel` require Claude Code v2.1.212 or later.
2325 3022
2341 }>;3038 }>;
2342 answers: Record<string, string>;3039 answers: Record<string, string>;
2343 response?: string;3040 response?: string;
3041 annotations?: Record<string, { preview?: string; notes?: string }>;
3042 afkTimeoutMs?: number;
2344};3043};
2345```3044```
2346 3045
2363 backgroundCwdHint?: string;3062 backgroundCwdHint?: string;
2364 dangerouslyDisableSandbox?: boolean;3063 dangerouslyDisableSandbox?: boolean;
2365 returnCodeInterpretation?: string;3064 returnCodeInterpretation?: string;
3065 noOutputExpected?: boolean;
2366 structuredContent?: unknown[];3066 structuredContent?: unknown[];
2367 persistedOutputPath?: string;3067 persistedOutputPath?: string;
2368 persistedOutputSize?: number;3068 persistedOutputSize?: number;
3069 staleReadFileStateHint?: string;
3070 ghRateLimitHint?: string;
3071 gitOperation?: {
3072 commit?: { sha: string; kind: "committed" | "amended" | "cherry-picked" };
3073 push?: { branch: string };
3074 branch?: { ref: string; action: "merged" | "rebased" };
3075 pr?: {
3076 number: number;
3077 url?: string;
3078 action: "created" | "edited" | "merged" | "commented" | "closed" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled";
3079 };
3080 };
2369};3081};
2370```3082```
2371 3083
2396 filePath: string;3108 filePath: string;
2397 oldString: string;3109 oldString: string;
2398 newString: string;3110 newString: string;
2399 originalFile: string;3111 originalFile: string | null;
2400 structuredPatch: Array<{3112 structuredPatch: Array<{
2401 oldStart: number;3113 oldStart: number;
2402 oldLines: number;3114 oldLines: number;
2413 deletions: number;3125 deletions: number;
2414 changes: number;3126 changes: number;
2415 patch: string;3127 patch: string;
3128 repository?: string | null;
2416 };3129 };
2417};3130};
2418```3131```
2433 numLines: number;3146 numLines: number;
2434 startLine: number;3147 startLine: number;
2435 totalLines: number;3148 totalLines: number;
3149 /** True when a whole-file read was auto-paginated because it exceeded the token cap (the content is a partial first page). */
3150 truncatedByTokenCap?: boolean;
2436 };3151 };
2437 }3152 }
2438 | {3153 | {
2472 count: number;3187 count: number;
2473 outputDir: string;3188 outputDir: string;
2474 };3189 };
3190 }
3191 | {
3192 type: "file_unchanged";
3193 file: {
3194 filePath: string;
3195 };
3196 /** Set when the dedup matched a startup-seeded entry (CLAUDE.md / nested memory) rather than a prior Read tool_result. */
3197 source?: "seeded";
2475 };3198 };
2476```3199```
2477 3200
2501 deletions: number;3224 deletions: number;
2502 changes: number;3225 changes: number;
2503 patch: string;3226 patch: string;
3227 repository?: string | null;
2504 };3228 };
3229 userModified?: boolean;
2505};3230};
2506```3231```
2507 3232
2571```typescript theme={null}3296```typescript theme={null}
2572type NotebookEditOutput = {3297type NotebookEditOutput = {
2573 new_source: string;3298 new_source: string;
3299 old_source?: string;
2574 cell_id?: string;3300 cell_id?: string;
2575 cell_type: "code" | "markdown";3301 cell_type: "code" | "markdown";
2576 language: string;3302 language: string;
2596 result: string;3322 result: string;
2597 durationMs: number;3323 durationMs: number;
2598 url: string;3324 url: string;
3325 artifactRead?: {
3326 slug: string;
3327 ver?: string;
3328 };
2599};3329};
2600```3330```
2601 3331
2616 | string3346 | string
2617 >;3347 >;
2618 durationSeconds: number;3348 durationSeconds: number;
3349 searchCount?: number;
2619};3350};
2620```3351```
2621 3352
2627 3358
2628```typescript theme={null}3359```typescript theme={null}
2629type WorkflowOutput = {3360type WorkflowOutput = {
2630 status: "async_launched";3361 status: "async_launched" | "remote_launched";
2631 taskId: string;3362 taskId: string;
3363 taskType?: "local_workflow" | "remote_agent";
3364 workflowName?: string;
2632 runId?: string;3365 runId?: string;
2633 summary?: string;3366 summary?: string;
2634 transcriptDir?: string;3367 transcriptDir?: string;
2635 scriptPath?: string;3368 scriptPath?: string;
3369 sessionUrl?: string; // set when the workflow launched as a remote session
3370 warning?: string;
2636 error?: string;3371 error?: string;
2637};3372};
2638```3373```
2640Returns immediately after the tool accepts the invocation. The final result arrives later as a task completion. Check `error` before treating the run as started: a script that fails its syntax check returns `status: "async_launched"` with `error` set, and never runs.3375Returns immediately after the tool accepts the invocation. The final result arrives later as a task completion. Check `error` before treating the run as started: a script that fails its syntax check returns `status: "async_launched"` with `error` set, and never runs.
2641 3376
2642| Field | Type | Description |3377| Field | Type | Description |
2643| --------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- |3378| --------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2644| `status` | `"async_launched"` | The tool accepted the invocation. This is the only value the field takes |3379| `status` | `"async_launched" \| "remote_launched"` | The tool accepted the invocation. `"async_launched"` for in-process runs, `"remote_launched"` for runs dispatched to a remote session instead of running in-process |
2645| `taskId` | `string` | Background task identifier for the run |3380| `taskId` | `string` | Background task identifier for the run |
2646| `runId` | `string` | Workflow run identifier to pass as `resumeFromRunId` on a later invocation |3381| `taskType` | `"local_workflow" \| "remote_agent"` | Task type of the registered background task, matching the `status` arm |
3382| `workflowName` | `string` | The `meta.name` from the workflow script |
3383| `runId` | `string` | Workflow run identifier to pass as `resumeFromRunId` on a later invocation. Absent for `remote_launched` runs, where the cloud session URL is the resume handle |
2647| `summary` | `string` | One-line description of what the workflow does |3384| `summary` | `string` | One-line description of what the workflow does |
2648| `transcriptDir` | `string` | Directory where subagent transcripts are written during execution |3385| `transcriptDir` | `string` | Directory where subagent transcripts are written during execution |
2649| `scriptPath` | `string` | Path to the persisted workflow script for this run. Edit it and pass back as `scriptPath` to rerun without resending the script |3386| `scriptPath` | `string` | Path to the persisted workflow script for this run. Edit it and pass back as `scriptPath` to rerun without resending the script |
2650| `error` | `string` | Set when the script fails its syntax check. When present, the run did not start despite the `async_launched` status |3387| `sessionUrl` | `string` | Cloud session URL, set when `status` is `"remote_launched"` |
3388| `warning` | `string` | Non-blocking heads-up, such as local git state diverging from the pushed branch a cloud session will clone |
3389| `error` | `string` | Set when the script fails its syntax check. When present, the run did not start despite the launched status |
2651 3390
2652### TodoWrite3391### TodoWrite
2653 3392
2755 isAgent: boolean;3494 isAgent: boolean;
2756 filePath?: string;3495 filePath?: string;
2757 hasTaskTool?: boolean;3496 hasTaskTool?: boolean;
3497 planWasEdited?: boolean;
2758 awaitingLeaderApproval?: boolean;3498 awaitingLeaderApproval?: boolean;
2759 requestId?: string;3499 requestId?: string;
2760};3500};
2788 uri: string;3528 uri: string;
2789 mimeType?: string;3529 mimeType?: string;
2790 text?: string;3530 text?: string;
3531 blobSavedTo?: string;
2791 }>;3532 }>;
3533 error?: string;
2792};3534};
2793```3535```
2794 3536
2808 3550
2809Returns information about the git worktree.3551Returns information about the git worktree.
2810 3552
3553### ExitWorktree
3554
3555**Tool name:** `ExitWorktree`
3556
3557```typescript theme={null}
3558type ExitWorktreeOutput = {
3559 action: "keep" | "remove";
3560 originalCwd: string;
3561 worktreePath: string;
3562 worktreeBranch?: string;
3563 tmuxSessionName?: string;
3564 discardedFiles?: number;
3565 discardedCommits?: number;
3566 message: string;
3567};
3568```
3569
3570Returns the action taken and details about the worktree that was exited.
3571
3572### EnterPlanMode
3573
3574**Tool name:** `EnterPlanMode`
3575
3576```typescript theme={null}
3577type EnterPlanModeOutput = {
3578 message: string;
3579};
3580```
3581
3582Returns a confirmation that plan mode was entered.
3583
3584### CronCreate
3585
3586**Tool name:** `CronCreate`
3587
3588```typescript theme={null}
3589type CronCreateOutput = {
3590 id: string;
3591 humanSchedule: string;
3592 recurring: boolean;
3593 durable?: boolean; // true when persisted to .claude/scheduled_tasks.json; false when session-only
3594};
3595```
3596
3597Returns the job ID and a human-readable description of the schedule.
3598
3599### CronDelete
3600
3601**Tool name:** `CronDelete`
3602
3603```typescript theme={null}
3604type CronDeleteOutput = {
3605 id: string;
3606};
3607```
3608
3609Returns the ID of the deleted job.
3610
3611### CronList
3612
3613**Tool name:** `CronList`
3614
3615```typescript theme={null}
3616type CronListOutput = {
3617 jobs: {
3618 id: string;
3619 cron: string;
3620 humanSchedule: string;
3621 prompt: string;
3622 recurring?: boolean;
3623 durable?: boolean;
3624 }[];
3625};
3626```
3627
3628Returns the scheduled cron jobs: durable jobs from `.claude/scheduled_tasks.json` and session-only jobs from the current session. A session-only job carries `durable: false`; jobs read from disk omit the field.
3629
3630### ScheduleWakeup
3631
3632**Tool name:** `ScheduleWakeup`
3633
3634```typescript theme={null}
3635type ScheduleWakeupOutput = {
3636 scheduledFor: number;
3637 clampedDelaySeconds: number;
3638 wasClamped: boolean;
3639 stopped?: boolean;
3640 cancelledWakeups?: number;
3641};
3642```
3643
3644Returns when the wake-up will fire as an epoch millisecond timestamp, the delay actually used, and whether the requested delay was clamped. {/* min-version: 2.1.202 */}The `stopped` field is `true` when the call ended the loop with `stop: true`. It requires Claude Code v2.1.202 or later. {/* min-version: 2.1.206 */}The `cancelledWakeups` field counts how many pending wakeups a `stop: true` call cancelled. A value of 0 means nothing was pending, and a recurring `/loop` cron isn't cancelled by `stop: true`. It requires Claude Code v2.1.206 or later.
3645
3646### RemoteTrigger
3647
3648**Tool name:** `RemoteTrigger`
3649
3650```typescript theme={null}
3651type RemoteTriggerOutput = {
3652 status: number;
3653 json: string;
3654 summary?: string;
3655};
3656```
3657
3658Returns the API response status and body for the trigger operation.
3659
3660### PushNotification
3661
3662**Tool name:** `PushNotification`
3663
3664```typescript theme={null}
3665type PushNotificationOutput = {
3666 message: string;
3667 pushSent?: boolean;
3668 localSent?: boolean;
3669 disabledReason?: "config_off" | "user_present" | "no_transport";
3670 sentAt?: string;
3671};
3672```
3673
3674Returns delivery details, including whether a push or local notification was sent and why delivery was skipped.
3675
3676### REPL
3677
3678**Tool name:** `REPL`
3679
3680```typescript theme={null}
3681type REPLOutput = {
3682 code: string;
3683 result: {
3684 [k: string]: unknown;
3685 };
3686 stdout: string;
3687 stderr: string;
3688 error?: string;
3689 registeredTools?: string[];
3690 images?: {
3691 base64: string;
3692 mediaType: string;
3693 }[];
3694 documents?: {
3695 base64: string;
3696 }[];
3697};
3698```
3699
3700Returns the execution result, captured console output, and any images or documents surfaced by inner `Read` calls.
3701
3702### ReportFindings
3703
3704**Tool name:** `ReportFindings`
3705
3706```typescript theme={null}
3707type ReportFindingsOutput = {
3708 count: number;
3709 level?: "low" | "medium" | "high" | "xhigh" | "max";
3710 findings: Array<{
3711 file: string;
3712 line?: number;
3713 summary: string;
3714 failure_scenario: string;
3715 short_summary?: string;
3716 category?: string;
3717 verdict?: "CONFIRMED" | "PLAUSIBLE";
3718 outcome?: "fixed" | "skipped" | "no_change_needed";
3719 }>;
3720};
3721```
3722
3723Returns the number of findings reported, the effort level the review ran at, and the findings echoed back for the result body. Requires Claude Code v2.1.196 or later. {/* min-version: 2.1.212 */}The echoed `short_summary` field requires Claude Code v2.1.212 or later.
3724
3725### Artifact
3726
3727**Tool name:** `Artifact`
3728
3729```typescript theme={null}
3730type ArtifactOutput =
3731 | {
3732 url: string;
3733 path: string;
3734 title?: string;
3735 version?: string;
3736 capabilities?: unknown;
3737 stored?: {
3738 contract: string;
3739 capabilities?: Record<string, unknown>;
3740 };
3741 warnings?: string[];
3742 contract?: string;
3743 updated?: boolean;
3744 liveSubscription?: string;
3745 }
3746 | {
3747 artifacts: Array<{
3748 title: string;
3749 url: string;
3750 updatedAt?: string;
3751 rel?: "mine" | "shared";
3752 }>;
3753 truncated?: boolean;
3754 scope?: "shared" | "all";
3755 };
3756```
3757
3758Returns the published page's `url` and the local `path` that was published for the publish action, with `updated` set to true when the publish redeployed an existing artifact, and `warnings` carrying any publish-time advisories. The list action returns the `artifacts` rows instead, with `truncated` set when more artifacts exist than the requested limit. On listings whose scope isn't `"mine"`, each row carries `rel` marking whether the user owns the artifact or it was shared with them, and the output's `scope` records which non-default scope produced the listing; both are absent on default listings.
3759
3760### Projects
3761
3762**Tool name:** `Projects`
3763
3764```typescript theme={null}
3765type ProjectsOutput =
3766 | {
3767 method: "project_info";
3768 notice?: string;
3769 name: string;
3770 description: string;
3771 instructions: string;
3772 docs: Array<{ path: string; created_at: string | null }>;
3773 files?: Array<{
3774 path: string;
3775 file_kind: string;
3776 created_at: string | null;
3777 }>;
3778 sync_sources?: Array<{
3779 type: string | null;
3780 config: Record<string, unknown>;
3781 }>;
3782 knowledge: {
3783 knowledge_size: number;
3784 max_knowledge_size: number;
3785 };
3786 }
3787 | {
3788 method: "project_read";
3789 notice?: string;
3790 path: string;
3791 file_kind?: string;
3792 content?: string;
3793 local_file?: string;
3794 created_at: string | null;
3795 }
3796 | {
3797 method: "project_search";
3798 notice?: string;
3799 rag: boolean;
3800 hits?: Array<{ name?: string; doc_uuid?: string; text?: string }>;
3801 docs?: string[];
3802 }
3803 | {
3804 method: "project_write";
3805 notice?: string;
3806 path: string;
3807 doc_uuid: string;
3808 replaced: boolean;
3809 present_to_user?: boolean;
3810 local_path?: string;
3811 }
3812 | {
3813 method: "project_delete";
3814 notice?: string;
3815 path: string;
3816 deleted: boolean;
3817 };
3818```
3819
3820Discriminated on the `method` field, mirroring the input. `project_read` returns small text docs inline in `content` and writes larger docs to a `local_file` path instead; `project_search` returns RAG `hits` with `rag: true` when the project's index is available and falls back to a `docs` path list otherwise.
3821
3822### ReadMcpResourceDir
3823
3824**Tool name:** `ReadMcpResourceDirTool`
3825
3826```typescript theme={null}
3827type ReadMcpResourceDirOutput = {
3828 resources: Array<{
3829 uri: string;
3830 name: string;
3831 mimeType?: string;
3832 }>;
3833 error?: string;
3834};
3835```
3836
3837Returns the direct children of the directory resource. Subdirectories appear with mimeType `"inode/directory"`; `error` carries a human-readable message when the server couldn't list the directory.
3838
3839### RefreshMcpTools
3840
3841**Tool name:** `RefreshMcpTools`
3842
3843```typescript theme={null}
3844type RefreshMcpToolsOutput = Array<{
3845 server: string;
3846 status: "refreshed" | "error" | "not_connected";
3847 toolCount?: number; // tools now available from this server
3848 added?: string[]; // tool names this refresh added
3849 removed?: string[]; // tool names this refresh removed
3850 error?: string; // why the refresh failed or the server was unavailable
3851}>;
3852```
3853
3854Returns one entry per server: `refreshed` means the re-queried tool list was applied, `error` means the re-query failed and the previous tool set was kept, and `not_connected` means the server has no live connection to query.
3855
3856### ShowOnboardingRolePicker
3857
3858**Tool name:** `ShowOnboardingRolePicker`
3859
3860```typescript theme={null}
3861type ShowOnboardingRolePickerOutput = {
3862 role?: string;
3863 dismissed?: boolean;
3864};
3865```
3866
3867Returns the user's selection: `role` when they picked a role chip or typed one, and `dismissed: true` when they closed the picker. An empty object means the user approved the call without picking a role.
3868
3869### McpOutput
3870
3871**Tool name:** dynamic MCP tool names of the form `mcp__<server>__<tool>`
3872
3873```typescript theme={null}
3874type McpOutput =
3875 | string
3876 | {
3877 type: string;
3878 [k: string]: unknown;
3879 }[]
3880 | {
3881 [k: string]: unknown;
3882 };
3883```
3884
3885MCP tool results are returned as a string or an array of content blocks, depending on the server. The trailing plain-object branch in the exported type is a schema-generation artifact: the SDK doesn't return a bare object, because a server's structured output is serialized to a JSON string before being returned. At runtime the value may also be `undefined`, although the exported type doesn't model this.
3886
2811## Permission Types3887## Permission Types
2812 3888
2813### `PermissionUpdate`3889### `PermissionUpdate`
2885type ApiKeySource = "user" | "project" | "org" | "temporary" | "oauth";3961type ApiKeySource = "user" | "project" | "org" | "temporary" | "oauth";
2886```3962```
2887 3963
3964<Note>
3965 At runtime, the `apiKeySource` field on the [`SDKSystemMessage`](#sdksystemmessage) init message can also be the string `"none"` when no API key is in use, for example when the session authenticates with an OAuth token. Handle values outside this union defensively.
3966</Note>
3967
2888### `SdkBeta`3968### `SdkBeta`
2889 3969
2890Available beta features that can be enabled via the `betas` option. See [Beta headers](https://platform.claude.com/docs/en/api/beta-headers) for more information.3970Available beta features that can be enabled via the `betas` option. See [Beta headers](https://platform.claude.com/docs/en/api/beta-headers) for more information.
2894```3974```
2895 3975
2896<Warning>3976<Warning>
2897 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this value with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.3977 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this value with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.
2898</Warning>3978</Warning>
2899 3979
2900### `SlashCommand`3980### `SlashCommand`
3028 costUSD: number;4108 costUSD: number;
3029 contextWindow: number;4109 contextWindow: number;
3030 maxOutputTokens: number;4110 maxOutputTokens: number;
4111 canonicalModel?: string;
4112 provider?: string;
3031};4113};
3032```4114```
3033 4115
4116{/* min-version: 2.1.218 */}The `canonicalModel` and `provider` fields require Claude Code v2.1.218 or later. `canonicalModel` is the canonical model ID that the pricing lookup uses; it can differ from the raw model string that keys the entry, for example when that string is a provider-specific ID or an alias.
4117
4118`provider` names the API backend that served the model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`.
4119
3034### `ConfigScope`4120### `ConfigScope`
3035 4121
3036```typescript theme={null}4122```typescript theme={null}
3099 | { type: "disabled" }; // No extended thinking4185 | { type: "disabled" }; // No extended thinking
3100```4186```
3101 4187
3102The 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 `thinking` blocks.4188The 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 `thinking` blocks. 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 `thinking` blocks even when you set `display` to `"summarized"`.
3103 4189
3104### `SpawnedProcess`4190### `SpawnedProcess`
3105 4191
3173 filesChanged?: string[];4259 filesChanged?: string[];
3174 insertions?: number;4260 insertions?: number;
3175 deletions?: number;4261 deletions?: number;
4262 skippedLinks?: number;
3176};4263};
3177```4264```
3178 4265
4266{/* min-version: 2.1.216 */}`skippedLinks` counts the tracked paths the rewind refused to restore or delete for link safety: a symlink, hard link, or other non-regular file at the tracked path, a parent directory that no longer resolves to where it pointed when the checkpoint was taken, or a backup that couldn't be read safely. The field requires Claude Code v2.1.216 or later. A preview call with `rewindFiles(userMessageId, { dryRun: true })` never sets it.
4267
3179### `SDKStatusMessage`4268### `SDKStatusMessage`
3180 4269
3181Status update message (e.g., compacting).4270Status update message (e.g., compacting).
3298 parent_tool_use_id: string | null;4387 parent_tool_use_id: string | null;
3299 elapsed_time_seconds: number;4388 elapsed_time_seconds: number;
3300 task_id?: string;4389 task_id?: string;
4390 heartbeat?: boolean;
4391 subagent_type?: string;
4392 subagent_retry?: {
4393 agent_id: string;
4394 attempt: number;
4395 max_retries: number;
4396 retry_delay_ms: number;
4397 error_status: number | null;
4398 error_category: string;
4399 };
3301 uuid: UUID;4400 uuid: UUID;
3302 session_id: string;4401 session_id: string;
3303};4402};
3304```4403```
3305 4404
4405While a tool call runs in the main conversation, Claude Code emits a `tool_progress` message every 30 seconds with `heartbeat: true`. Each heartbeat carries the tool name and elapsed seconds, so you can distinguish a long-running call from a stalled session. Claude Code doesn't emit heartbeats for the Agent tool, whose subagents stream their own progress, or for tool calls inside a subagent. The `heartbeat` field requires Agent SDK v0.3.214 or later.
4406
4407On `tool_progress` messages for the Agent tool, `subagent_type` names the running subagent type, such as `general-purpose`. `subagent_retry` is present while that subagent waits out an API error backoff, such as a rate limit or overload, with one message per retry attempt. Both fields require Agent SDK v0.3.214 or later.
4408
4409To render a retry indicator from `subagent_retry`:
4410
4411* Track the indicator by `parent_tool_use_id`, which is unique per subagent. `tool_use_id` is shared by parallel subagents from one assistant turn, so tracking by it would let one subagent's update clear another's indicator.
4412* Clear the indicator when a later `tool_progress` for the same `parent_tool_use_id` arrives without the field, or when the tool's result message arrives. `attempt` can exceed `max_retries` under persistent retry, so don't derive clearing from the counters.
4413* Treat `error_category` as a closed set of tokens for choosing your own message text, not as display text: `rate_limit`, `overloaded`, `authentication_failed`, `server_error`, or `unknown`.
4414
3306### `SDKAuthStatusMessage`4415### `SDKAuthStatusMessage`
3307 4416
3308Emitted during authentication flows.4417Emitted during authentication flows.
3476 4585
3477### `SDKCommandsChangedMessage`4586### `SDKCommandsChangedMessage`
3478 4587
3479Emitted when the set of available commands changes mid-session, such as when skills are discovered as the agent enters a subdirectory. The `commands` array is the full updated list, so replace any cached command list with this payload. Calling `supportedCommands()` again is not equivalent: that method returns the snapshot captured at initialization and does not reflect mid-session changes.4588Emitted when the set of available commands changes mid-session, such as when Claude Code discovers skills as the agent enters a subdirectory. The `commands` array is the full updated list, so replace any cached command list with this payload. {/* min-version: agent-sdk@0.3.216 */}Calling [`supportedCommands()`](#query-object) after this message returns the same updated list, because the method tracks the latest push; this requires Agent SDK v0.3.216 or later. In earlier SDK versions, `supportedCommands()` returns the snapshot captured at initialization and never reflects mid-session changes.
3480 4589
3481```typescript theme={null}4590```typescript theme={null}
3482type SDKCommandsChangedMessage = {4591type SDKCommandsChangedMessage = {
3603type SandboxNetworkConfig = {4712type SandboxNetworkConfig = {
3604 allowedDomains?: string[];4713 allowedDomains?: string[];
3605 deniedDomains?: string[];4714 deniedDomains?: string[];
4715 strictAllowlist?: boolean;
3606 allowManagedDomainsOnly?: boolean;4716 allowManagedDomainsOnly?: boolean;
3607 allowLocalBinding?: boolean;4717 allowLocalBinding?: boolean;
3608 allowUnixSockets?: string[];4718 allowUnixSockets?: string[];
3613```4723```
3614 4724
3615| Property | Type | Default | Description |4725| Property | Type | Default | Description |
3616| :------------------------ | :--------- | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |4726| :------------------------ | :--------- | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
3617| `allowedDomains` | `string[]` | `[]` | Domain names that sandboxed processes can access |4727| `allowedDomains` | `string[]` | `[]` | Domain names that sandboxed processes can access |
3618| `deniedDomains` | `string[]` | `[]` | Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains` |4728| `deniedDomains` | `string[]` | `[]` | Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains` |
4729| `strictAllowlist` | `boolean` | `false` | {/* min-version: 2.1.219 */}Deny sandboxed commands access to hosts not in `allowedDomains` instead of prompting. Enforced for sandboxed commands only; in-process tools such as WebFetch aren't gated by it. Only honored from user, managed, or CLI `--settings` settings; project settings are ignored. Requires Claude Code v2.1.219 or later |
3619| `allowManagedDomainsOnly` | `boolean` | `false` | Managed-settings only. When set in [managed settings](/docs/en/permissions#managed-settings), only `allowedDomains` entries from managed settings are honored and entries from user, project, or local settings are ignored. Has no effect when set via SDK options |4730| `allowManagedDomainsOnly` | `boolean` | `false` | Managed-settings only. When set in [managed settings](/docs/en/permissions#managed-settings), only `allowedDomains` entries from managed settings are honored and entries from user, project, or local settings are ignored. Has no effect when set via SDK options |
3620| `allowLocalBinding` | `boolean` | `false` | Allow processes to bind to local ports (e.g., for dev servers) |4731| `allowLocalBinding` | `boolean` | `false` | Allow processes to bind to local ports (e.g., for dev servers) |
3621| `allowUnixSockets` | `string[]` | `[]` | Unix socket paths that processes can access (e.g., Docker socket) |4732| `allowUnixSockets` | `string[]` | `[]` | Unix socket paths that processes can access (e.g., Docker socket) |