Skip to main content

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. You don’t need to install Claude Code separately. 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.

Compile to a single executable

When you compile your application into a single-file executable with bun 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 a Query 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 a Promise<WarmQuery> that resolves once the subprocess has spawned and completed its initialize handshake.

Example

Call startup() 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 by lastModified 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. The trust filter the CLI applies before honoring escalating permission modes is not applied.

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.

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 the env option:
  • API_TIMEOUT_MS: per-request timeout on the Anthropic client, in milliseconds. Default 600000. Applies to the main loop and all subagents.
  • CLAUDE_CODE_MAX_RETRIES: maximum API retries. Default 10, capped at 15. Each retry gets its own API_TIMEOUT_MS window, so worst-case wall time is roughly API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1) plus backoff. For unattended runs that need to wait through longer outages, set CLAUDE_CODE_RETRY_WATCHDOG=1: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to 300 and removes the cap on this variable.
  • CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS: stall watchdog for subagents launched with run_in_background. Default 600000. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.
  • CLAUDE_ENABLE_STREAM_WATCHDOG with CLAUDE_STREAM_IDLE_TIMEOUT_MS: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set CLAUDE_ENABLE_STREAM_WATCHDOG=0 to disable it. CLAUDE_STREAM_IDLE_TIMEOUT_MS defaults to 300000 and is clamped to that minimum. The aborted request goes through the normal retry path.

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. Switching agent also applies that agent’s model override, hooks, and system prompt on the next turn.
  • Applied during the current turn: model. If you switch model while 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. Flag settings sit near the top of the settings precedence order: they override user, project, and local settings, and only managed policy settings can override them. 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.
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.
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.

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.
Where McpServerConfigForProcessTransport is McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig.

SettingSource

Controls which filesystem-based configuration sources the SDK loads settings from.

Default behavior

When settingSources is omitted or undefined, query() loads the same filesystem settings as the Claude Code CLI: user, project, and local. Endpoint-managed policy is loaded in all cases; server-managed settings are fetched when the session authenticates with an organization credential on an eligible configuration. 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:
Load all filesystem settings explicitly:
Load only specific setting sources:
Testing and CI environments:
SDK-only applications:
Loading CLAUDE.md project instructions:

Settings precedence

When multiple sources are loaded, settings are merged with this precedence (highest to lowest):
  1. Local settings (.claude/settings.local.json)
  2. Project settings (.claude/settings.json)
  3. User settings (~/.claude/settings.json)
Programmatic options such as 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. AskUserQuestion, MCP tools marked requiresUserInteraction, and connector tools your organization set to ask reach the function even when an allow rule matches. In dontAsk mode these calls are denied instead, without invoking it.
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:
For complete information on creating and using plugins, see Plugins.

Message Types

SDKMessage

Union type of all possible messages returned by the query.

SDKAssistantMessage

Assistant response message.
The 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. 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.

SDKUserMessage

User input message.
Set 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.
A user turn injected from outside the session, one whose 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.
Several fields on the result carry diagnostic detail beyond subtype:
  • 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.
  • 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 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.
  • 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".
The origin field forwards the 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. 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.
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. 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 auto-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. The interactive ask path reaches your application separately through the canUseTool callback. Denials issued by a PreToolUse hook are not reported through this event. This event requires Claude Code v2.1.136 or later.

SDKPermissionDenial

Information about a denied tool use.

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.

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.
The 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.

NotificationHookInput

UserPromptSubmitHookInput

SessionStartHookInput

SessionEndHookInput

StopHookInput

SubagentStartHookInput

SubagentStopHookInput

PreCompactHookInput

PermissionRequestHookInput

SetupHookInput

TeammateIdleHookInput

TaskCompletedHookInput

ConfigChangeHookInput

WorktreeCreateHookInput

WorktreeRemoveHookInput

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 all tool input types, exported from @anthropic-ai/claude-agent-sdk.

Agent

Tool name: Agent (previously Task, which is still accepted as an alias)
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.
Launches a new agent to handle complex, multi-step tasks autonomously.

AskUserQuestion

Tool name: AskUserQuestion
Asks the user clarifying questions during execution. See Handle approvals and user input for usage details.

Bash

Tool name: Bash
Executes Bash commands with optional timeout and background execution. The working directory persists between commands; shell state such as exported environment variables doesn’t.

Monitor

Tool name: Monitor
Runs a background source and delivers each event to Claude so it can react without polling: command runs a script and emits one event per stdout line, and ws opens a WebSocket and emits one event per text frame. Provide exactly one of command or ws. The ws source requires Claude Code v2.1.195 or later. 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.

TaskOutput

Tool name: TaskOutput
Retrieves output from a running or completed background task.

Edit

Tool name: Edit
Performs exact string replacements in files.

Read

Tool name: Read
Reads files from the local filesystem, including text, images, PDFs, and Jupyter notebooks. Use pages for PDF page ranges (for example, "1-5").

Write

Tool name: Write
Writes a file to the local filesystem, overwriting if it exists.

Glob

Tool name: Glob
Fast file pattern matching that works with any codebase size.

Grep

Tool name: Grep
Powerful search tool built on ripgrep with regex support.

TaskStop

Tool name: TaskStop
Stops a running background task or shell by ID. As of v2.1.198, task_id also accepts an agent-team teammate or a named background agent by agent ID or name.

NotebookEdit

Tool name: NotebookEdit
Edits cells in Jupyter notebook files.

WebFetch

Tool name: WebFetch
Fetches content from a URL and processes it with an AI model.

WebSearch

Tool name: WebSearch
Searches the web and returns formatted results.

Workflow

Tool name: Workflow
Runs a dynamic workflow: a script that orchestrates many subagents in the background and returns one consolidated result. The 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
Creates and manages a structured task list for tracking progress.
As of TypeScript Agent SDK 0.3.142, TodoWrite is disabled by default. Use TaskCreate, TaskGet, TaskUpdate, and TaskList instead. See Migrate to Task tools to update your monitoring code, or set CLAUDE_CODE_ENABLE_TASKS=0 to revert to TodoWrite.

TaskCreate

Tool name: TaskCreate
Creates a single task and returns its assigned ID.

TaskUpdate

Tool name: TaskUpdate
Patches one task by ID. Set status to "deleted" to remove it.

TaskGet

Tool name: TaskGet
Returns full details for one task, or null when the ID is not found.

TaskList

Tool name: TaskList
Returns a snapshot of all tasks in the current list.

ExitPlanMode

Tool name: ExitPlanMode
Exits plan mode. The 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
Lists available MCP resources from connected servers.

ReadMcpResource

Tool name: ReadMcpResourceTool
Reads a specific MCP resource from a server.

EnterWorktree

Tool name: EnterWorktree
Creates 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.

Tool Output Types

Documentation of output schemas for all built-in Claude Code tools. These types are exported from @anthropic-ai/claude-agent-sdk and represent the actual response data returned by each tool.

ToolOutputSchemas

Union of all tool output types.

Agent

Tool name: Agent (previously Task, which is still accepted as an alias)
Returns 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. The resolvedModel field on the completed and async_launched variants names the model the subagent actually ran on, which can differ from the requested model input when availableModels 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. On the completed variant, worktreePath is set when the subagent ran in an isolated git worktree, and worktreeBranch names that worktree’s branch when Claude Code created it. usage.service_tier carries the service tier string the API reported for the subagent’s requests. 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
Returns the questions asked and the user’s answers. 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
Returns command output with stdout/stderr split. Background commands include a backgroundTaskId. 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.

Monitor

Tool name: Monitor
Returns the background task ID for the running monitor. Use this ID with TaskStop to cancel the watch early.

Edit

Tool name: Edit
Returns the structured diff of the edit operation.

Read

Tool name: Read
Returns file contents in a format appropriate to the file type. Discriminated on the type field.

Write

Tool name: Write
Returns the write result with structured diff information.

Glob

Tool name: Glob
Returns file paths matching the glob pattern, sorted by modification time. 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
Returns search results. The shape varies by 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
Returns confirmation after stopping the background task.

NotebookEdit

Tool name: NotebookEdit
Returns the result of the notebook edit with original and updated file contents.

WebFetch

Tool name: WebFetch
Returns the fetched content with HTTP status and metadata.

WebSearch

Tool name: WebSearch
Returns search results from the web.

Workflow

Tool name: Workflow
Returns 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.

TodoWrite

Tool name: TodoWrite
Returns the previous and updated task lists.
As of TypeScript Agent SDK 0.3.142, TodoWrite is disabled by default. Use TaskCreate, TaskGet, TaskUpdate, and TaskList instead. See Migrate to Task tools to update your monitoring code, or set CLAUDE_CODE_ENABLE_TASKS=0 to revert to TodoWrite.

TaskCreate

Tool name: TaskCreate
Returns the created task with its assigned ID.

TaskUpdate

Tool name: TaskUpdate
Returns the update result, including which fields changed.

TaskGet

Tool name: TaskGet
Returns the full task record, or null when the ID is not found.

TaskList

Tool name: TaskList
Returns a snapshot of all tasks in the current list.

ExitPlanMode

Tool name: ExitPlanMode
Returns the plan state after exiting plan mode.

ListMcpResources

Tool name: ListMcpResourcesTool
Returns an array of available MCP resources.

ReadMcpResource

Tool name: ReadMcpResourceTool
Returns the contents of the requested MCP resource.

EnterWorktree

Tool name: EnterWorktree
Returns information about the git worktree.

Permission Types

PermissionUpdate

Operations for updating permissions.

PermissionBehavior

PermissionUpdateDestination

PermissionRuleValue

Other Types

ApiKeySource

SdkBeta

Available beta features that can be enabled via the betas option. See Beta headers for more information.
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, which include 1M context at standard pricing with no beta header required.

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.
See 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.

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.
The optional display field controls whether thinking text is returned "summarized" or "omitted". On Claude Opus 4.7 and later, the API default is "omitted", so set "summarized" to receive thinking content in thinking blocks.

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.

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.

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.

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.
When 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 slash command (for example, /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 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.

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, such as after /clear, on plan-mode exit, or when a fresh conversation starts. Mount an empty transcript under new_conversation_id and discard any cached session title.
The SDK’s published typings declare 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

Unix socket security: The allowUnixSockets option can grant access to powerful system services. For example, allowing /var/run/docker.sock effectively grants full host system access through the Docker API, bypassing sandbox isolation. Only allow Unix sockets that are strictly necessary and understand the security implications of each.

SandboxNetworkConfig

Network-specific configuration for sandbox mode. 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

When allowUnsandboxedCommands is enabled, the model can request to run commands outside the sandbox by setting dangerouslyDisableSandbox: true in the tool input. These requests fall back to the existing permissions system, meaning your canUseTool handler is invoked, allowing you to implement custom authorization logic. 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 setting dangerouslyDisableSandbox: true in the tool input.
This pattern enables you to:
  • Audit model requests: Log when the model requests unsandboxed execution
  • Implement allowlists: Only permit specific commands to run unsandboxed
  • Add approval workflows: Require explicit authorization for privileged operations
Commands running with dangerouslyDisableSandbox: true have full system access. Ensure your canUseTool handler validates these requests carefully.If permissionMode is set to bypassPermissions and allowUnsandboxedCommands is enabled, the model can autonomously execute commands outside the sandbox without approval prompts (an explicit ask rule still forces one). This combination effectively allows the model to escape sandbox isolation silently.

See also