Installation
The SDK bundles a native Claude Code binary for your platform as an optional dependency such as
@anthropic-ai/claude-agent-sdk-darwin-arm64. Most installs need no separate Claude Code install. The SDK version tracks the bundled Claude Code version: SDK v0.3.191 bundles Claude Code v2.1.191, so a feature on this page that requires a Claude Code version needs the SDK release with the same patch number or later. If your package manager skips optional dependencies, the SDK throws Native CLI binary for <platform> not found; set pathToClaudeCodeExecutable to a separately installed claude binary instead.If your package manager doesn’t apply npm’s libc field, as Yarn 1.x doesn’t, you get both the glibc and musl platform packages on Linux, roughly doubling the install size. The SDK still launches the correct variant. To reclaim the space in a container image, delete the platform package that doesn’t match the libc where your app runs; for a glibc runtime on x64, that’s rm -rf node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl. On a development machine the deletion is temporary, since Yarn reinstalls the package on the next dependency change.Compile to a single executable
When you compile your application into a single-file executable withbun build --compile, the SDK cannot resolve the bundled CLI binary at runtime. require.resolve does not work inside the compiled executable’s $bunfs virtual filesystem, so the SDK throws Native CLI binary for <platform> not found.
To work around this, embed the platform binary as a file asset, extract it to a real path at startup with extractFromBunfs(), and pass that path to pathToClaudeCodeExecutable.
The extractFromBunfs() helper requires @anthropic-ai/claude-agent-sdk v0.3.144 or later. The example below builds for macOS on Apple Silicon:
extractFromBunfs() copies the embedded binary out of the compiled executable’s virtual filesystem to a per-user temp directory and returns the real path. Outside a compiled executable it returns the input path unchanged, so the same code runs in development without modification.
Each compiled executable embeds a single platform’s binary. Match the platform package in the import to your --target:
- To cross-compile, install the non-matching platform package, for example
npm install @anthropic-ai/claude-agent-sdk-linux-x64 --force. - On Windows, the binary subpath is
claude.exe, for example@anthropic-ai/claude-agent-sdk-win32-x64/claude.exe.
Functions
query()
The primary function for interacting with Claude Code. Creates an async generator that streams messages as they arrive.
Parameters
Returns
Returns aQuery object that extends AsyncGenerator<SDKMessage, void> with additional methods.
startup()
Pre-warms the CLI subprocess by spawning it and completing the initialize handshake before a prompt is available. The returned WarmQuery handle accepts a prompt later and writes it to an already-ready process, so the first query() call resolves without paying subprocess spawn and initialization cost inline.
Parameters
Returns
Returns aPromise<WarmQuery> that resolves once the subprocess has spawned and completed its initialize handshake.
Example
Callstartup() early, for example on application boot, then call .query() on the returned handle once a prompt is ready. This moves subprocess spawn and initialization out of the critical path.
tool()
Creates a type-safe MCP tool definition for use with SDK MCP servers.
Parameters
ToolAnnotations
Re-exported from @modelcontextprotocol/sdk/types.js. All fields are optional hints; clients should not rely on them for security decisions.
createSdkMcpServer()
Creates an MCP server instance that runs in the same process as your application.
Parameters
listSessions()
Discovers and lists past sessions with light metadata. Filter by project directory or list sessions across all projects.
Parameters
Return type: SDKSessionInfo
Example
Print the 10 most recent sessions for a project. Results are sorted bylastModified descending, so the first item is the newest. Omit dir to search across all projects.
getSessionMessages()
Reads user and assistant messages from a past session transcript.
Parameters
Return type: SessionMessage
Example
getSessionInfo()
Reads metadata for a single session by ID without scanning the full project directory.
Parameters
Returns
SDKSessionInfo, or undefined if the session is not found.
renameSession()
Renames a session by appending a custom-title entry. Repeated calls are safe; the most recent title wins.
Parameters
tagSession()
Tags a session. Pass null to clear the tag. Repeated calls are safe; the most recent tag wins.
Parameters
resolveSettings()
Resolves the effective Claude Code settings for a given directory using the same merge engine as the CLI, without spawning the Claude CLI. Use it to inspect what configuration a query() call would see before invoking one.
This function is alpha and its API may change before stabilization. It reads MDM sources, including macOS plist and Windows HKLM/HKCU, for parity with CLI startup, but does not execute the admin-configured
policyHelper subprocess. The permissions.defaultMode field is returned as-is from all tiers including project settings. In a live session, the CLI ignores defaultMode: 'auto' from project and local settings; resolveSettings() skips that check, so an auto from those tiers appears here even though a session would ignore it.Parameters
resolveSettings() accepts a single options object. All fields are optional.
Return type: ResolvedSettings
resolveSettings() returns an object describing the merged settings and the source that contributed each key.
Example
The example below resolves settings for a project directory and prints the source that controls the cleanup period. On a machine where no settings file setscleanupPeriodDays, both printed lines show undefined for the value, which is the expected output rather than an error.
Types
Options
Configuration object for the query() function.
Handle slow or stalled API responses
The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through theenv option:
API_TIMEOUT_MS: per-request timeout on the Anthropic client, in milliseconds. Default600000. Applies to the main loop and all subagents.CLAUDE_CODE_MAX_RETRIES: maximum API retries. Default10, capped at15. Each retry gets its ownAPI_TIMEOUT_MSwindow, so worst-case wall time is roughlyAPI_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)plus backoff. For unattended runs that need to wait through longer outages, setCLAUDE_CODE_RETRY_WATCHDOG=1: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to300and removes the cap on this variable.CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS: stall watchdog for subagents launched withrun_in_background. Default600000. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.CLAUDE_ENABLE_STREAM_WATCHDOGwithCLAUDE_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; setCLAUDE_ENABLE_STREAM_WATCHDOG=0to disable it.CLAUDE_STREAM_IDLE_TIMEOUT_MSdefaults to300000and is clamped to that minimum. After the abort, Automatic retries covers what Claude Code does, based on how far the response had progressed.
Query object
Interface returned by the query() function.
Methods
applyFlagSettings()
Changes settings on a running session without restarting the query. Use it when a setting that has no dedicated setter needs to change mid-session, such as tightening permissions after the agent reads untrusted input. setModel() and setPermissionMode() are dedicated setters for those two keys; applyFlagSettings() is the general form that accepts any subset of the settings keys, and passing model here behaves the same as setModel().
Only some keys take effect mid-session:
- Applied on the next turn:
effortLevel,ultracode,permissions,hooks,skillOverrides,fastMode,agent. Switchingagentalso applies that agent’s model override, hooks, and system prompt on the next turn. - Applied during the current turn:
model. If you switchmodelwhile Claude is working on a turn, the response Claude is already generating finishes on the old model, and the rest of the turn, starting with the next call Claude Code makes to the model, uses the new one. Subagents keep their own model. Before v2.1.212, a mid-turn switch waited for the next turn. - No effect mid-session: the system prompt options. These are resolved once at startup, so the running session keeps the original value even though the call succeeds. To change them, start a new session.
effortLevel accepts an effort level name. It also accepts "ultracode", which runs the session at xhigh effort and turns on ultracode. The Settings type declares effortLevel without that value, so pass the equivalent { ultracode: true } in TypeScript. The ultracode value requires Claude Code v2.1.203 or later and is accepted only by applyFlagSettings(), not by the effortLevel key in a settings file.
The values are written to the flag-settings layer, the same layer the inline settings option of query() populates at startup. This is the same tier the on-page precedence section calls programmatic options.
Successive calls shallow-merge top-level keys. A second call with { permissions: {...} } replaces the entire permissions object from the prior call rather than deep-merging into it. To clear a key from the flag layer and fall back to lower-precedence sources, pass null for that key. Passing undefined has no effect because JSON serialization drops it.
Only available in streaming input mode, the same constraint as setModel() and setPermissionMode().
The 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.
applyFlagSettings() is TypeScript-only. The Python SDK does not expose an equivalent method.WarmQuery
Handle returned by startup(). The subprocess is already spawned and initialized, so calling query() on this handle writes the prompt directly to a ready process with no startup latency.
Methods
WarmQuery implements AsyncDisposable, so it can be used with await using for automatic cleanup.
SDKControlInitializeResponse
Return type of initializationResult(). Contains session initialization data.
fast_mode_state, and when something blocks 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 on the result message.
When 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.
These 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 callback, the same redelivery that reinitialize() 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.
SDKControlInterruptResponse
The interrupt receipt: the value interrupt() resolves with on a CLI that advertises the interrupt_receipt_v1 capability in SDKSystemMessage.capabilities. Requires Claude Code v2.1.205 or later. Earlier CLIs answer the interrupt with an empty success payload, so interrupt() resolves to undefined.
still_queued lists the UUIDs of user messages that survive the interrupt: messages still in the queue, plus any batch already dequeued for the next turn but not yet reachable by the abort. Each one runs as its own turn after the interrupt unless you cancel it first. Use the receipt to decide whether to resend anything; resending a message that is already listed produces a duplicate turn.
Interpret the list with these caveats:
- Only messages that were enqueued with a UUID appear. An empty array doesn’t mean nothing else will run.
- Only main-thread messages are listed. Messages addressed to a subagent are out of scope.
- The list can include UUIDs your client never sent, such as scheduled task triggers. Ignore UUIDs you don’t recognize instead of treating them as an error.
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; 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.
The 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.
The 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. 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.
SDKControlGetContextUsageResponse
Return type of getContextUsage(). This is the same payload Claude Code renders for the /context command in an interactive session, so alongside the token counts it carries display fields such as color and gridRows that Claude Code uses to draw the /context usage grid.
When you send /context as a prompt instead of calling the method, Claude Code attaches an SDKContextUsage payload to the context_usage field of the assistant message that delivers the result. That field requires Agent SDK v0.3.232 or later.
categoriesholds the per-category totals.mcpToolsandagentsattribute tokens to individual MCP tools and subagents.memoryFileslists each loaded memory file with its cost.skills.skillFrontmatterattributes 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. Compareskills.totalSkillswithskills.includedSkillsto see whether every discovered skill made it into the listing.
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. rawMaxTokens carries the same value as maxTokens, and percentage is totalTokens as a rounded percentage of that window.
Claude Code leaves the optional deferredBuiltinTools, systemTools, and systemPromptSections diagnostics unset, so expect them to be absent even though the type declares them.
SDKControlReadFileResponse
Return type of readFile().
contents holds the file text, or base64 data when you requested encoding: 'base64'; the response’s encoding field is set to 'base64' in that case. absPath is the resolved absolute path. truncated is set when the file was longer than the maxBytes cap and the contents were cut at that limit.
AgentDefinition
Configuration for a subagent defined programmatically.
AgentMcpServerSpec
Specifies MCP servers available to a subagent. Can be a server name (string referencing a server from the parent’s mcpServers config) or an inline server configuration record mapping server names to configs.
McpServerConfigForProcessTransport is McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig.
SettingSource
Controls which filesystem-based configuration sources the SDK loads settings from.
Default behavior
WhensettingSources is omitted or undefined, query() loads the same filesystem settings as the Claude Code CLI: user, project, and local. See What settingSources does not control for inputs that are read regardless of this option, and how to disable them.
Why use settingSources
Disable filesystem settings:Settings precedence
When multiple sources are loaded, settings are merged with this precedence (highest to lowest):- Local settings (
.claude/settings.local.json) - Project settings (
.claude/settings.json) - User settings (
~/.claude/settings.json)
agents, allowedTools, and settings override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options.
PermissionMode
CanUseTool
Custom permission function type for controlling tool usage.
The function is the SDK replacement for the interactive permission prompt: it’s invoked only when the permission evaluation flow resolves to a prompt. Tool calls already approved by an allowedTools entry, a settings allow rule, or the permission mode, such as acceptEdits or bypassPermissions, never invoke it. To gate every tool call, use a PreToolUse hook instead.
An allow rule doesn’t pre-approve the actions no mode auto-approves; see How permissions are evaluated for which of them reach the callback and what happens in dontAsk and auto mode.
The callback normally resolves the request by returning a
PermissionResult, which the SDK writes back over its transport as the control_response. Return null only when your application has already sent the control_response for this request over its own channel, echoing requestId; the SDK then skips writing the response to its transport. Returning null in any other case leaves the tool call blocked indefinitely, because no control_response is ever sent and permission prompts don’t time out.
The requestId option and the null return value require Claude Code v2.1.199 or later.
PermissionResult
Result of a permission check.
ToolConfig
Configuration for built-in tool behavior.
McpServerConfig
Configuration for MCP servers.
McpStdioServerConfig
McpSSEServerConfig
McpHttpServerConfig
McpSdkServerConfigWithInstance
McpClaudeAIProxyServerConfig
SdkPluginConfig
Configuration for loading plugins in the SDK.
Example:
Message Types
SDKMessage
Union type of all possible messages returned by the query.
SDKAssistantMessage
Assistant response message.
message field is a BetaMessage from the Anthropic SDK. It includes fields like id, content, model, stop_reason, and usage.
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.
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.
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.
context_usage is a structured copy of the /context report, typed as SDKContextUsage, and requires Agent SDK v0.3.232 or later. When you send /context as a prompt, Claude Code delivers the report as an assistant message whose message.content holds the markdown table, and attaches context_usage to that same message. Claude Code doesn’t set the field on any other assistant message, and earlier versions deliver the /context table without it, so read the breakdown from the field when it’s present and fall back to the markdown text when it isn’t.
SDKUserMessage
User input message.
shouldQuery to false to append the message to the transcript without triggering an assistant turn. The message is held and merged into the next user message that does trigger a turn. Use this to inject context, such as the output of a command you ran out of band, without spending a model call on it.
On a message that carries a tool_result block, tool_use_result is the tool’s structured output object rather than the text sent to the model. Its shape depends on the tool named by the matching tool_use block, so the field is typed unknown; the built-in shapes are listed under Tool Output Types.
For the Agent tool, tool_use_result is AgentOutput. On a completed result, content holds the subagent’s report without the agent ID and usage trailer that Claude Code appends to the tool_result text, so render from tool_use_result instead of parsing that text.
SDKUserMessageReplay
Replayed user message with required UUID.
origin kind is peer or channel, reaches the stream as a replay whether it was delivered during an active turn or started a new turn while the session was idle. Before v2.1.207, an injected turn delivered while the session was idle produced no message on the stream and only appeared when you re-read the transcript.
SDKResultMessage
Final result message.
subtype:
api_error_status: the HTTP status code of the API error that terminated the conversation. Absent ornullwhen the turn ended without an API error.ttft_ms: time to first token in milliseconds, measured when the first complete assistant message arrives. Present on the success arm only.ttft_stream_ms: time in milliseconds until the firstmessage_startstream event, when the response stream opens. Lower thanttft_ms; the gap between the two is time spent streaming the first message. Present on the success arm only.user_message_uuid: theuuidof theSDKUserMessagethat 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 withrequest_sent_wall_ms; absent on API-error results, subagent calls, and synthetic turns such as scheduled ones.request_sent_wall_ms: epoch milliseconds at which Claude Code dispatched the API request, for joins against server-side timestamps. Present only together withuser_message_uuid.usage: main agent loop only. Excludes subagent and auxiliary model calls, and is per-turn in streaming-input sessions. PrefermodelUsagefor token/cost accounting.modelUsage: per-model totals for every model call made through the query pipeline during thisquery()call, including the main loop, subagents, and internal calls such as compaction and Workflow agents. Helper calls outside that pipeline, such as the permission classifier and token-counting requests, are excluded. In streaming-input sessions the totals are cumulative across turns, so read the latest result rather than summing across results. See Track costs in streaming input mode for resets and Recover totals after a session crash for zeroed results.total_cost_usd: cumulative estimated cost in USD for thisquery()call, covering the same calls asmodelUsageand reset at the same points. It is an estimate, not a billing statement. See Track cost and usage for accuracy caveats.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".fast_mode_state: one of"on","off", or"cooldown".fast_mode_disabled_reason: why 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 reportsfast_mode_state: "cooldown"with no reason code and re-enables fast mode when the cooldown expires. Requires Claude Code v2.1.219 or later.
The same pair of fields appears on
SDKSystemMessage and on the SDKControlInitializeResponse, so you can read the fast mode state before the first turn.
The origin field forwards the SDKMessageOrigin of the user message that triggered this result. When the SDK injects a synthetic follow-up turn, such as for a finished background task, the resulting SDKResultMessage carries origin: { kind: "task-notification" }. Routines whose trigger fired and server-verified messages from your other sessions arrive with this kind too, each with the subkind described in Task-notification subkinds. Check kind to distinguish results that answer your prompt from injected follow-ups before routing or suppressing them.
The field is absent for results emitted before any user turn, such as startup errors.
When a PreToolUse hook returns permissionDecision: "defer", the result has stop_reason: "tool_deferred" and deferred_tool_use carries the pending tool’s id, name, and input. Read this field to surface the request in your own UI, then resume with the same session_id to continue. See Defer a tool call for later for the full round trip.
SDKSystemMessage
System initialization message.
fast_mode_state reports the session’s fast mode state. 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 on the result message.
terminal_slash_commands names the entries in slash_commands whose interface is bound to the local terminal, such as exit. You can send them like any other entry in slash_commands; the field exists so a remote or mobile client can hide them from its command menus. The field is present only when non-empty, and requires Agent SDK v0.3.229 or later.
The 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.
SDKPartialAssistantMessage
Streaming partial message (only when includePartialMessages is true). The parent_tool_use_id field is always null: stream events are emitted for the main session only. For subagent attribution, use complete messages, which carry parent_tool_use_id, or enable forwardSubagentText to receive subagent text and thinking as complete messages.
SDKCompactBoundaryMessage
Message indicating a conversation compaction boundary.
SDKInformationalMessage
Generic text banner emitted by the loop. Carries non-error status lines, hook feedback such as a UserPromptSubmit hook’s block reason, and command output. On Claude Code v2.1.227 or later, a hook’s systemMessage can arrive as this message, with each line prefixed by the hook’s name, such as PostToolUse:Bash says:. Whether a hook’s systemMessage arrives as this message depends on the event. Each event’s section on the hooks page says how output surfaces. Render content as plaintext at the given level.
SDKWorkerShuttingDownMessage
Emitted on graceful worker teardown so remote clients can show why the worker exited instead of waiting for heartbeat timeout. The reason is a short snake_case string set by the host CLI, such as "host_exit" or "remote_control_disabled". Act on this only when streaming live. A resumed session replays past instances of this message, so ignore them in that case.
SDKPluginInstallMessage
Plugin installation progress event. Emitted when CLAUDE_CODE_SYNC_PLUGIN_INSTALL is set, so your Agent SDK application can track marketplace plugin installation before the first turn. The started and completed statuses bracket the overall install. The installed and failed statuses report individual marketplaces and include name.
SDKPermissionDeniedMessage
Stream event emitted when the permission system denies a tool call without an interactive prompt. Use it to render the denial in your UI as it happens, rather than only observing the is_error tool result that follows. Which denials it reports depends on how the run handles permission prompts:
- With a
canUseToolcallback: permission prompts go to your callback, and this event reports the denials Claude Code decides on its own without calling it. - With neither: a bare
-prun, orquery()that sets neithercanUseToolnorpermissionPromptToolName, denies any tool call that would have prompted, and this event reports those denials as well as the ones Claude Code decides on its own. Before v2.1.223, Claude Code didn’t emit this event in runs without a callback. - With an MCP prompt tool, set with
permissionPromptToolNameor the--permission-prompt-toolflag: Claude Code doesn’t emit this event at all, not even for the rule denials it decides on its own.
PreToolUse hook path, whether the hook denied the call itself or a deny rule overrode the hook’s allow or ask decision. The event is also best-effort: occasionally Claude Code records a denial without emitting this event, so permission_denials on the result message is the authoritative record.
SDKPermissionDenial
Information about a denied tool use.
SDKContextUsage
Structured form of the /context report, carried as context_usage on the SDKAssistantMessage that delivers a /context result. Agent SDK v0.3.232 and later export the type. Unlike SDKControlGetContextUsageResponse, it carries only the data needed to render the usage breakdown, without display fields such as color and gridRows.
model through over_limit describe the session as a whole, and the collection fields attribute tokens to individual items.
over_limit.kind records how Claude Code resolved the window, not whether the API accepts the next request:
hard_limit: the window is what Claude Code believes to be the model’s own limit, past which the API refuses requestscompaction_window: the window is a compaction-policy window, which may or may not coincide with the model’s limit
SDKContextUsageCategory
One row of the /context usage-by-category breakdown.
Each
kind value says what the row’s tokens are:
used: content that occupies the context windowfree: the remaining windowbuffer: the compaction reservedeferred: tool schemas Claude Code holds out of the window and excludes from the usage calculation, listed for awareness
SDKMessageOrigin
Provenance of a user-role message. This appears as origin on SDKUserMessage and is forwarded onto the corresponding SDKResultMessage so you can tell what triggered a given turn.
Task-notification subkinds
When Claude Code delivers a task notification into a session, it setssubkind on the notification’s origin only if Anthropic servers verified where that notification came from. subkind requires Claude Code v2.1.213 or later, and it takes one of two values:
scheduled-trigger: the notification is a routine’s stored prompt, delivered because one of the routine’s triggers fired: its schedule, its API trigger, its GitHub trigger, or Run now. Claude Code frames these to the model as the session’s assigned task, with a different notice from the notice that other task notifications carry.peer-send-message: the notification is a message that another of your sessions sent with the server-sidesend_messagetool that Claude Code on the web sessions use to message each other, not the cross-sessionSendMessagetool, and Anthropic servers verified that both sessions belong to the same private group of sessions. Requires Claude Code v2.1.224 or later. Asend_messagedelivery the servers didn’t verify that way gets no subkind.
subkind. That includes scheduled tasks that fire on your own machine, PR activity delivered into a session, and background events such as a finished task. Messages from the cross-session SendMessage tool aren’t task notifications at all: whether they come from a session on the same machine or through Anthropic servers from another machine, Claude Code gives them kind: "peer" and the peer origin fields.
Peer origin fields
Apeer origin identifies which agent sent the message: an in-process teammate sending to main with SendMessage, or a cross-session peer, another of your Claude Code sessions. A cross-session peer can run on the same machine, or on another of your machines or Claude Code on the web when its message arrives through Remote Control. The two kinds of sender fill the fields differently:
from: the teammate’s name, or the sender address for a cross-session peer. For a one-way cross-machine message, the sender has no reply address andfromis"unknown". The value is sender-authored;verifiedPeerPidis the verified identity.senderTaskId: the teammate’s task ID. Absent for a cross-session peer.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.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. Rendernameandbodyinstead of re-parsing the message text. Requires Claude Code v2.1.205 or later.fromSession: the sender’s host-openable session ID, set by the sender’s host so your UI can link back to the sending session. Likefrom, 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.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, notfrom, to identify the sender:fromis 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.
Hook Types
For a comprehensive guide on using hooks with examples and common patterns, see the Hooks guide.HookEvent
Available hook events.
HookCallback
Hook callback function type.
HookCallbackMatcher
Hook configuration with optional matcher.
HookInput
Union type of all hook input types.
BaseHookInput
Base interface that all hook input types extend.
prompt_id field is a UUID identifying the user prompt currently being processed. It matches the prompt.id attribute on OpenTelemetry events and is absent until the first user input. Requires Claude Code v2.1.196 or later.
PreToolUseHookInput
PostToolUseHookInput
PostToolUseFailureHookInput
PostToolBatchHookInput
Fires once after every tool call in a batch has resolved, before the next model request. tool_response carries the serialized tool_result content the model sees; the shape differs from PostToolUseHookInput’s structured Output object.
PermissionDeniedHookInput
NotificationHookInput
UserPromptSubmitHookInput
UserPromptExpansionHookInput
SessionStartHookInput
SessionEndHookInput
StopHookInput
StopFailureHookInput
SubagentStartHookInput
SubagentStopHookInput
PreCompactHookInput
PostCompactHookInput
PermissionRequestHookInput
SetupHookInput
TeammateIdleHookInput
TaskCreatedHookInput
TaskCompletedHookInput
ElicitationHookInput
ElicitationResultHookInput
ConfigChangeHookInput
InstructionsLoadedHookInput
DirectoryAddedHookInput
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.
WorktreeCreateHookInput
WorktreeRemoveHookInput
CwdChangedHookInput
FileChangedHookInput
MessageDisplayHookInput
HookJSONOutput
Hook return value.
AsyncHookJSONOutput
SyncHookJSONOutput
Tool Input Types
Documentation of input schemas for all built-in Claude Code tools. These types are exported from@anthropic-ai/claude-agent-sdk and can be used for type-safe tool interactions.
ToolInputSchemas
Union of tool input types exported from @anthropic-ai/claude-agent-sdk; members include:
Agent
Tool name:Agent. The previous name Task is still accepted as an alias, and the tools array in the SDKSystemMessage init message currently lists this tool as Task for backward compatibility.
The
mode field is deprecated and ignored on Claude Code v2.1.212 or later: subagents inherit the parent session’s permission mode, and a subagent definition’s permissionMode can override it, except when the parent uses bypassPermissions, acceptEdits, or auto, and Claude Code ignores a definition’s permissionMode: "bypassPermissions" when bypass mode is disabled by permissions.disableBypassPermissionsMode.AskUserQuestion
Tool name:AskUserQuestion
Bash
Tool name:Bash
Monitor
Tool name:Monitor
command runs a script and emits one event per stdout line, and ws opens a WebSocket and emits one event per text frame. Provide exactly one of command or ws. The ws source requires Claude Code v2.1.195 or later.
Set 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 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.
TaskOutput
Tool name:TaskOutput
TaskOutput is deprecated; prefer Read on the task’s output file path. The schemas below remain valid for hooks and permission handlers that encounter the tool.Edit
Tool name:Edit
Read
Tool name:Read
pages for PDF page ranges (for example, "1-5").
Write
Tool name:Write
Glob
Tool name:Glob
Grep
Tool name:Grep
TaskStop
Tool name:TaskStop
task_id also accepts an agent-team teammate or a named background agent by agent ID or name.
NotebookEdit
Tool name:NotebookEdit
WebFetch
Tool name:WebFetch
WebSearch
Tool name:WebSearch
Workflow
Tool name:Workflow
Workflow tool is available in Agent SDK v0.3.149 and later. At least one of script, name, or scriptPath is required.
TodoWrite
Tool name:TodoWrite
On TypeScript Agent SDK 0.3.233 and later, the following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
TodoWriteTaskCreateTaskGetTaskUpdateTaskList
TodoWrite only when you set CLAUDE_CODE_ENABLE_TASKS=0.See Model availability to opt in and Migrate to Task tools to update your monitoring code.TaskCreate
Tool name:TaskCreate
TaskUpdate
Tool name:TaskUpdate
status to "deleted" to remove it.
TaskGet
Tool name:TaskGet
null when the ID is not found.
TaskList
Tool name:TaskList
ExitPlanMode
Tool name:ExitPlanMode
allowedPrompts field is deprecated and ignored; Claude Code still accepts it so existing callers and transcripts validate. Before v2.1.205, it requested prompt-based Bash permissions for implementing the plan.
ListMcpResources
Tool name:ListMcpResourcesTool
ReadMcpResource
Tool name:ReadMcpResourceTool
EnterWorktree
Tool name:EnterWorktree
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.
ExitWorktree
Tool name:ExitWorktree
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.
EnterPlanMode
Tool name:EnterPlanMode
CronCreate
Tool name:CronCreate
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.
Setting 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.
CronDelete
Tool name:CronDelete
CronCreate.
CronList
Tool name:CronList
.claude/scheduled_tasks.json and session-only jobs from the current session.
ScheduleWakeup
Tool name:ScheduleWakeup
/loop command. The runtime clamps delaySeconds to between 60 and 3600 seconds. The delaySeconds, reason, and prompt fields are required unless stop is true. 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 for availability; it isn’t available on Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry, nor when you turn off feature-flag fetching.
RemoteTrigger
Tool name:RemoteTrigger
/schedule command. trigger_id is required for the get, update, run, and list_runs actions. body is required for create, update, and create_webhook_trigger, and optional for run.
create_webhook_trigger attaches an event source to an existing routine, such as a GitHub event that fires it. The body names the source, the events, and the routine to fire. Requires Claude Code v2.1.225 or later.
list_runs lists a routine’s recent runs, and get_run_log reads one run’s log. session_id names the run to read, from a list_runs result, and cursor pages through either action’s results. Both actions require Claude Code v2.1.227 or later.
This tool is available only when the session is authenticated with a claude.ai account on a plan with Routines enabled, and is absent when your organization’s policy disables Claude Code on the web or when you turn off feature-flag fetching. On Claude Code v2.1.227 or later, the tool is also absent when an Owner has turned off routines for the organization. Before v2.1.227, a session with only the routines toggle turned off still showed the tool, and the server denied its calls.
PushNotification
Tool name:PushNotification
message under 200 characters because mobile operating systems truncate longer text. See the PushNotification row in the 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.
REPL
Tool name:REPL
timeout is in milliseconds, with a default of 30000 and a maximum of 600000.
The types are exported, but the tool is off in SDK sessions unless you set CLAUDE_CODE_REPL=1 in the env option. It also requires the Bun-based claude executable that the native installer provides.
ReportFindings
Tool name:ReportFindings
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.
Each finding carries these fields:
file: repo-relative path the finding is in. The optionallineis the 1-indexed line it anchors to.summary: one-sentence statement of the defect.failure_scenariodescribes the concrete inputs and state that lead to the wrong output or crash.short_summary: optional compressed label of at most 60 characters for compact display. Requires Claude Code v2.1.212 or later.category: optional short kebab-case slug of the finding type, such ascorrectnessortest-coverage. Requires Claude Code v2.1.199 or later.verdict: set when a verify pass ran; absent on inline-only reviews.outcome: set only when re-reporting after applying fixes.
Artifact
Tool name:Artifact
.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.
Pass "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.
The types are exported, but the tool is off by default in Agent SDK sessions. Publishing also requires every condition in the artifacts availability table, which sessions authenticated with an API key don’t meet.
Projects
Tool name:Projects
method:
project_info: returns project metadata and the doc list.project_read: reads one doc bypath.project_search: queries the project’s knowledge base withquery.ncaps the hits and defaults to 5.project_write: creates or replaces a doc atpathfrom exactly one ofcontent, which carries inline text, orlocal_path, which names a file inside the working directory.present_to_user: truemarks the written doc as the deliverable the user needs to see.project_delete: deletes a doc bypath.
ReadMcpResourceDir
Tool name:ReadMcpResourceDirTool
resources list and the error field reports that directory listing isn’t enabled.
RefreshMcpTools
Tool name:RefreshMcpTools
CLAUDE_CODE_ENABLE_REFRESH_MCP_TOOLS=1 in the env option, and only in sessions with at least one MCP server. Requires Claude Code v2.1.211 or later.
ShowOnboardingRolePicker
Tool name:ShowOnboardingRolePicker
McpInput
Tool name: dynamic MCP tool names of the formmcp__<server>__<tool>
Tool Output Types
Documentation of output schemas for all built-in Claude Code tools. These types are exported from@anthropic-ai/claude-agent-sdk and represent the actual response data returned by each tool.
ToolOutputSchemas
Union of tool output types exported from @anthropic-ai/claude-agent-sdk; members include:
Agent
Tool name:Agent. The previous name Task is still accepted as an alias, and the tools array in the SDKSystemMessage init message currently lists this tool as Task for backward compatibility.
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.
On the completed variant, resolvedModel names the model the subagent started on, which can differ from the requested model input when availableModels or another override applies. This field requires Claude Code v2.1.174 or later. On async_launched, it names the model in use when the task moved to the background.
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. Both modelsUsed and the backgrounding behavior of resolvedModel require Claude Code v2.1.212 or later.
If Claude Code kept the subagent’s isolated worktree, worktreePath on the completed result is where to find it. worktreeBranch is its branch, present when Claude Code created the worktree with git.
Claude Code fills usage and totalTokens from the subagent’s final API request, not from the whole run, so usage.service_tier is the service tier string the API reported on that request. When present, usage.output_tokens_details.thinking_tokens is the number of that request’s output tokens that were thinking tokens. The output_tokens_details field requires TypeScript SDK v0.3.228 or later, which bundles Claude Code v2.1.228.
Before v2.1.207, the published type was narrower. It omitted worktreePath, worktreeBranch, citations, toolStats.frameCount, and the inference_geo, speed, and iterations usage fields, and it typed service_tier as "standard" | "priority" | "batch". Fields the type marks optional can be absent on results recorded by earlier versions.
AskUserQuestion
Tool name:AskUserQuestion
response is set when the user typed a freeform reply instead of answering the structured questions; when present, Claude receives “The user responded: …” instead of the per-question answer list.
Bash
Tool name:Bash
stdout, stderr, and backgroundTaskId fields carry:
timedOutAfterMs is the timeout in milliseconds, set when the command reached its timeout and moved to the background rather than starting there explicitly. backgroundCwdHint is set when the backgrounded command contained a directory-change builtin such as cd, pushd, popd, or chdir, and notes that the session working directory didn’t change. Both fields require Claude Code v2.1.210 or later.
When a subagent running in the foreground owns a backgrounded command, Claude Code terminates the command when that subagent gives its final response. Claude Code sets backgroundEndsWithFinalResponse to true on such commands, and omits the field when the command survives the turn, as commands started by the main conversation or by background subagents do. The field requires Claude Code v2.1.227 or later.
Monitor
Tool name:Monitor
TaskStop to cancel the watch early.
Edit
Tool name:Edit
Read
Tool name:Read
type field.
Write
Tool name:Write
Glob
Tool name:Glob
totalMatches and countIsComplete require Claude Code v2.1.191 or later. totalMatches reports the number of matching files before truncation. When countIsComplete is false, totalMatches is a lower bound because the underlying search truncated its own output.
Grep
Tool name:Grep
mode: file list, content with matches, or match counts. In count mode, numFiles and numMatches are totals over the full result set, not the paginated slice. Before v2.1.208, a head_limit or offset that truncated the listed entries also truncated those totals.
totalFiles requires Claude Code v2.1.208 or later and reports the total number of results before head_limit and offset pagination in files_with_matches mode. totalLines requires Claude Code v2.1.210 or later and reports the total number of lines before pagination in content mode.
TaskStop
Tool name:TaskStop
NotebookEdit
Tool name:NotebookEdit
WebFetch
Tool name:WebFetch
WebSearch
Tool name:WebSearch
Workflow
Tool name:Workflow
error before treating the run as started: a script that fails its syntax check returns status: "async_launched" with error set, and never runs.
TodoWrite
Tool name:TodoWrite
On TypeScript Agent SDK 0.3.233 and later, the following tools aren’t available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
TodoWriteTaskCreateTaskGetTaskUpdateTaskList
TodoWrite only when you set CLAUDE_CODE_ENABLE_TASKS=0.See Model availability to opt in and Migrate to Task tools to update your monitoring code.TaskCreate
Tool name:TaskCreate
TaskUpdate
Tool name:TaskUpdate
TaskGet
Tool name:TaskGet
null when the ID is not found.
TaskList
Tool name:TaskList
ExitPlanMode
Tool name:ExitPlanMode
ListMcpResources
Tool name:ListMcpResourcesTool
ReadMcpResource
Tool name:ReadMcpResourceTool
EnterWorktree
Tool name:EnterWorktree
ExitWorktree
Tool name:ExitWorktree
EnterPlanMode
Tool name:EnterPlanMode
CronCreate
Tool name:CronCreate
CronDelete
Tool name:CronDelete
CronList
Tool name:CronList
.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.
ScheduleWakeup
Tool name:ScheduleWakeup
stopped field is true when the call ended the loop with stop: true. It requires Claude Code v2.1.202 or later. 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.
RemoteTrigger
Tool name:RemoteTrigger
PushNotification
Tool name:PushNotification
REPL
Tool name:REPL
Read calls.
ReportFindings
Tool name:ReportFindings
short_summary field requires Claude Code v2.1.212 or later.
Artifact
Tool name:Artifact
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.
Projects
Tool name:Projects
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.
ReadMcpResourceDir
Tool name:ReadMcpResourceDirTool
"inode/directory"; error carries a human-readable message when the server couldn’t list the directory.
RefreshMcpTools
Tool name:RefreshMcpTools
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.
ShowOnboardingRolePicker
Tool name:ShowOnboardingRolePicker
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.
McpOutput
Tool name: dynamic MCP tool names of the formmcp__<server>__<tool>
undefined, although the exported type doesn’t model this.
Permission Types
PermissionUpdate
Operations for updating permissions.
PermissionBehavior
PermissionUpdateDestination
PermissionRuleValue
Other Types
ApiKeySource
At runtime, the
apiKeySource field on the 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.SdkBeta
Available beta features that can be enabled via the betas option. See Beta headers for more information.
SlashCommand
Information about an available slash command.
ModelInfo
Information about an available model.
AgentInfo
Information about an available subagent that can be invoked via the Agent tool.
McpServerStatus
Status of a connected MCP server.
McpServerStatusConfig
The configuration of an MCP server as reported by mcpServerStatus(). This is the union of all MCP server transport types.
McpServerConfig for details on each transport type.
AccountInfo
Account information for the authenticated user.
ModelUsage
Per-model usage statistics returned in result messages. The costUSD value is a client-side estimate. See Track cost and usage for billing caveats.
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.
provider names the API backend that served the model, such as firstParty, bedrock, vertex, foundry, anthropicAws, mantle, or gateway.
ConfigScope
NonNullableUsage
A version of Usage with all nullable fields made non-nullable.
Usage
Token usage statistics. This is the BetaUsage type from @anthropic-ai/sdk.
BetaServerToolUsage and BetaIterationsUsage are defined in @anthropic-ai/sdk.
CallToolResult
MCP tool result type (from @modelcontextprotocol/sdk/types.js). structuredContent is a JSON object that can be returned alongside content, including image blocks. See Return structured data.
ThinkingConfig
Controls Claude’s thinking/reasoning behavior. Takes precedence over the deprecated maxThinkingTokens.
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".
SpawnedProcess
Interface for custom process spawning (used with spawnClaudeCodeProcess option). ChildProcess already satisfies this interface.
SpawnOptions
Options passed to the custom spawn function.
The
signal field tells your spawn function when to tear down the process. Pass it as the signal option to Node’s spawn(), or pass it to your VM or container teardown handler.This signal does not fire the instant Options.abortController aborts. The SDK first closes the process’s stdin and waits about two seconds so the CLI can shut down cleanly, then aborts this signal. To react the moment the caller aborts instead, listen on your own Options.abortController.signal, which your spawn function can reference from its enclosing scope.McpSetServersResult
Result of a setMcpServers() operation.
RewindFilesResult
Result of a rewindFiles() operation.
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.
SDKStatusMessage
Status update message (e.g., compacting).
SDKTaskNotificationMessage
Notification when a background task completes, fails, or is stopped. Background tasks include run_in_background Bash commands, Monitor watches, and background subagents.
scheduled-trigger subkind, which carry an assigned-task framing instead. The notice states that no human input has occurred, so the model doesn’t treat the notification as a user instruction or approval.
To detect a task-notification turn, check origin.kind === "task-notification" on the SDKUserMessage or SDKResultMessage rather than matching on the notice text. Read subkind from the same field if you need to know what raised it. Before v2.1.205, Claude Code left the notice off notifications that arrived while the session was idle.
SDKToolUseSummaryMessage
Summary of tool usage in a conversation.
SDKHookStartedMessage
Emitted when a hook begins executing.
Claude Code delivers this message, SDKHookProgressMessage, and SDKHookResponseMessage to the message stream immediately, including while a SessionStart or Setup hook is still running during session startup. Claude Code v2.1.169 through v2.1.203 delivered these messages in one batch after a SessionStart or Setup hook completed; v2.1.204 restored live delivery.
SDKHookProgressMessage
Emitted while a hook is running, with stdout/stderr output.
SDKHookResponseMessage
Emitted when a hook finishes executing.
SDKToolProgressMessage
Emitted periodically while a tool is executing to indicate progress.
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.
On 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.
To render a retry indicator from subagent_retry:
- Track the indicator by
parent_tool_use_id, which is unique per subagent.tool_use_idis shared by parallel subagents from one assistant turn, so tracking by it would let one subagent’s update clear another’s indicator. - Clear the indicator when a later
tool_progressfor the sameparent_tool_use_idarrives without the field, or when the tool’s result message arrives.attemptcan exceedmax_retriesunder persistent retry, so don’t derive clearing from the counters. - Treat
error_categoryas a closed set of tokens for choosing your own message text, not as display text:rate_limit,overloaded,authentication_failed,server_error, orunknown.
SDKAuthStatusMessage
Emitted during authentication flows.
SDKTaskStartedMessage
Emitted when a background task begins. The task_type field is "local_bash" for background Bash commands and Monitor watches, "local_agent" for subagents, or "remote_agent".
SDKTaskProgressMessage
Emitted periodically while a subagent or background task is running. The summary field is populated only when agentProgressSummaries is enabled.
SDKTaskUpdatedMessage
Emitted when a background task’s state changes, such as when it transitions from running to completed. Merge patch into your local task map keyed by task_id. The end_time field is a Unix epoch timestamp in milliseconds, comparable with Date.now().
SDKBackgroundTasksChangedMessage
Emitted whenever the set of live background tasks changes: a task starts, completes, is killed, or a foreground agent is backgrounded. The tasks array is the full live set. Replace any cached set with each payload instead of pairing task_started and task_notification events, so the next membership change corrects any event you missed.
Ordering relative to those per-task events is unspecified, so don’t correlate the two streams.
Nothing is emitted at startup. Reset to an empty set whenever the session’s CLI process starts or restarts and let the next membership change repopulate it.
Requires Claude Code v2.1.203 or later.
SDKThinkingTokensMessage
Emitted while Claude is producing a thinking block, including a redacted one, carrying a running estimate of the thinking tokens generated so far. estimated_tokens is the running total for the current thinking block and estimated_tokens_delta is the increment carried by this frame. Use it for progress display. The final count for the top-level agent loop is the result message’s usage.output_tokens, which doesn’t include subagent tokens; use modelUsage for whole-tree accounting.
Requires Claude Code v2.1.153 or later.
SDKFilesPersistedEvent
Emitted when file checkpoints are persisted to disk.
SDKRateLimitEvent
Emitted when the session encounters a rate limit.
errorCode is "credits_required", the rejection is from a claude.ai subscription whose included usage is exhausted, and the session cannot continue until the user buys usage credits. canUserPurchaseCredits indicates whether the authenticated user can buy credits for the account, and hasChargeableSavedPaymentMethod indicates whether a saved payment method is on file. All three fields are absent on rate-limit events that are not credits-required rejections. Requires Claude Code v2.1.181 or later.
SDKLocalCommandOutputMessage
Output from a local command such as /voice or /usage. Displayed as assistant-style text in the transcript.
SDKCommandsChangedMessage
Emitted 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. Calling supportedCommands() 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.
SDKPromptSuggestionMessage
Emitted after each turn when promptSuggestions is enabled. Contains a predicted next user prompt.
SDKConversationResetMessage
Emitted when the session’s conversation is replaced without ending the session. In a query() call, only /clear and its aliases produce this message. Mount an empty transcript under new_conversation_id and discard any cached session title.
SDKConversationResetMessage in Claude Code v2.1.203 and later. Before v2.1.203, SDKMessage referenced the type without declaring it, so narrowing on type === "conversation_reset" failed to typecheck when skipLibCheck was disabled.
AbortError
Custom error class for abort operations.
Sandbox Configuration
SandboxSettings
Configuration for sandbox behavior. Use this to enable command sandboxing and configure network restrictions programmatically.
The sandbox depends on platform support and, on Linux, tools like
bubblewrap and socat. When enabled is true and the sandbox can’t start, query() reports a result message with subtype: "error_during_execution" and the reason in errors. For a single message query() call, the SDK throws after yielding that error result, so wrap the loop in a try block to continue past it. See Handle the result for the error contract.To run unsandboxed instead, set failIfUnavailable: false.Example usage
SandboxNetworkConfig
Network-specific configuration for sandbox mode. These settings apply to sandboxed Bash commands when enabled is true in the parent SandboxSettings. They do not restrict the WebFetch tool, which uses permission rules instead.
The built-in sandbox proxy enforces
allowedDomains based on the requested hostname and does not terminate or inspect TLS traffic, so techniques such as domain fronting can potentially bypass it. See Sandboxing security limitations for details and Secure deployment for configuring a TLS-terminating proxy.SandboxFilesystemConfig
Filesystem-specific configuration for sandbox mode.
Permissions Fallback for Unsandboxed Commands
WhenallowUnsandboxedCommands is enabled, the model can request to run commands outside the sandbox by setting dangerouslyDisableSandbox: true in the tool input. These requests fall back to the existing permissions system, meaning your canUseTool handler is invoked, allowing you to implement custom authorization logic. In the example below, isCommandAuthorized stands in for an authorization check you define.
excludedCommands vs allowUnsandboxedCommands:excludedCommands: A static list of commands that always bypass the sandbox automatically (e.g.,['docker']). The model has no control over this.allowUnsandboxedCommands: Lets the model decide at runtime whether to request unsandboxed execution by settingdangerouslyDisableSandbox: truein the tool input.
See also
- SDK overview - General SDK concepts
- Python SDK reference - Python SDK documentation
- CLI reference - Command-line interface
- Common workflows - Step-by-step guides