Try the new V2 interface (preview): A simplified interface with send() and receive() patterns is now available, making multi-turn conversations easier. Learn more
npm install @anthropic-ai/claude-agent-sdkquery()The primary function for interacting with Claude Code. Creates an async generator that streams messages as they arrive.
function query({
prompt,
options
}: {
prompt: string | AsyncIterable<SDKUserMessage>;
options?: Options;
}): Query| Parameter | Type | Description |
|---|---|---|
prompt | string | AsyncIterable<SDKUserMessage> | The input prompt as a string or async iterable for streaming mode |
options | Options | Optional configuration object (see Options type below) |
Returns a Query object that extends AsyncGenerator<SDKMessage, void> with additional methods.
tool()Creates a type-safe MCP tool definition for use with SDK MCP servers.
function tool<Schema extends ZodRawShape>(
name: string,
description: string,
inputSchema: Schema,
handler: (args: z.infer<ZodObject<Schema>>, extra: unknown) => Promise<CallToolResult>
): SdkMcpToolDefinition<Schema>| Parameter | Type | Description |
|---|---|---|
name | string | The name of the tool |
description | string | A description of what the tool does |
inputSchema | Schema extends ZodRawShape | Zod schema defining the tool's input parameters |
handler | (args, extra) => Promise<CallToolResult> | Async function that executes the tool logic |
createSdkMcpServer()Creates an MCP server instance that runs in the same process as your application.
function createSdkMcpServer(options: {
name: string;
version?: string;
tools?: Array<SdkMcpToolDefinition<any>>;
}): McpSdkServerConfigWithInstance| Parameter | Type | Description |
|---|---|---|
options.name | string | The name of the MCP server |
options.version | string | Optional version string |
options.tools | Array<SdkMcpToolDefinition> | Array of tool definitions created with tool() |
OptionsConfiguration object for the query() function.
| Property | Type | Default | Description |
|---|---|---|---|
abortController | AbortController | new AbortController() | Controller for cancelling operations |
additionalDirectories | string[] | [] | Additional directories Claude can access |
agents | Record<string, [AgentDefinition](#agentdefinition)> | undefined | Programmatically define subagents |
QueryInterface returned by the query() function.
interface Query extends AsyncGenerator<SDKMessage, void> {
interrupt(): Promise<void>;
rewindFiles(userMessageUuid: string): Promise<void>;
setPermissionMode(mode: PermissionMode): Promise<void>;
setModel(model?: string): Promise<void>;
setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;
supportedCommands(): Promise<SlashCommand[]>;
supportedModels(): Promise<ModelInfo[]>;
mcpServerStatus(): Promise<McpServerStatus[]>;
accountInfo(): Promise<AccountInfo>;
}| Method | Description |
|---|---|
interrupt() | Interrupts the query (only available in streaming input mode) |
rewindFiles(userMessageUuid) | Restores files to their state at the specified user message. Requires enableFileCheckpointing: true. See File checkpointing |
setPermissionMode() | Changes the permission mode (only available in streaming input mode) |
setModel() | Changes the model (only available in streaming input mode) |
setMaxThinkingTokens() | Changes the maximum thinking tokens (only available in streaming input mode) |
supportedCommands() | Returns available slash commands |
AgentDefinitionConfiguration for a subagent defined programmatically.
type AgentDefinition = {
description: string;
tools?: string[];
prompt: string;
model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
}| Field | Required | Description |
|---|---|---|
description | Yes | Natural language description of when to use this agent |
tools | No | Array of allowed tool names. If omitted, inherits all tools |
prompt | Yes | The agent's system prompt |
model | No | Model override for this agent. If omitted, uses the main model |
SettingSourceControls which filesystem-based configuration sources the SDK loads settings from.
type SettingSource = 'user' | 'project' | 'local';| Value | Description | Location |
|---|---|---|
'user' | Global user settings | ~/.claude/settings.json |
'project' | Shared project settings (version controlled) | .claude/settings.json |
'local' | Local project settings (gitignored) | .claude/settings.local.json |
When settingSources is omitted or undefined, the SDK does not load any filesystem settings. This provides isolation for SDK applications.
Load all filesystem settings (legacy behavior):
// Load all settings like SDK v0.0.x did
const result = query({
prompt: "Analyze this code",
options: {
settingSources: ['user', 'project', 'local'] // Load all settings
}
});Load only specific setting sources:
// Load only project settings, ignore user and local
const result = query({
prompt: "Run CI checks",
options: {
settingSources: ['project'] // Only .claude/settings.json
}
});Testing and CI environments:
// Ensure consistent behavior in CI by excluding local settings
const result = query({
prompt: "Run tests",
options: {
settingSources: ['project'], // Only team-shared settings
permissionMode: 'bypassPermissions'
}
});SDK-only applications:
// Define everything programmatically (default behavior)
// No filesystem dependencies - settingSources defaults to []
const result = query({
prompt: "Review this PR",
options: {
// settingSources: [] is the default, no need to specify
agents: { /* ... */ },
mcpServers: { /* ... */ },
allowedTools: ['Read', 'Grep', 'Glob']
}
});Loading CLAUDE.md project instructions:
// Load project settings to include CLAUDE.md files
const result = query({
prompt: "Add a new feature following project conventions",
options: {
systemPrompt: {
type: 'preset',
preset: 'claude_code' // Required to use CLAUDE.md
},
settingSources: ['project'], // Loads CLAUDE.md from project directory
allowedTools: ['Read', 'Write', 'Edit']
}
});When multiple sources are loaded, settings are merged with this precedence (highest to lowest):
.claude/settings.local.json).claude/settings.json)~/.claude/settings.json)Programmatic options (like agents, allowedTools) always override filesystem settings.
PermissionModetype PermissionMode =
| 'default' // Standard permission behavior
| 'acceptEdits' // Auto-accept file edits
| 'bypassPermissions' // Bypass all permission checks
| 'plan' // Planning mode - no executionCanUseToolCustom permission function type for controlling tool usage.
type CanUseTool = (
toolName: string,
input: ToolInput,
options: {
signal: AbortSignal;
suggestions?: PermissionUpdate[];
}
) => Promise<PermissionResult>;PermissionResultResult of a permission check.
type PermissionResult =
| {
behavior: 'allow';
updatedInput: ToolInput;
updatedPermissions?: PermissionUpdate[];
}
| {
behavior: 'deny';
message: string;
interrupt?: boolean;
}McpServerConfigConfiguration for MCP servers.
type McpServerConfig =
| McpStdioServerConfig
| McpSSEServerConfig
| McpHttpServerConfig
| McpSdkServerConfigWithInstance;McpStdioServerConfigtype McpStdioServerConfig = {
type?: 'stdio';
command: string;
args?: string[];
env?: Record<string, string>;
}McpSSEServerConfigtype McpSSEServerConfig = {
type: 'sse';
url: string;
headers?: Record<string, string>;
}McpHttpServerConfigtype McpHttpServerConfig = {
type: 'http';
url: string;
headers?: Record<string, string>;
}McpSdkServerConfigWithInstancetype McpSdkServerConfigWithInstance = {
type: 'sdk';
name: string;
instance: McpServer;
}SdkPluginConfigConfiguration for loading plugins in the SDK.
type SdkPluginConfig = {
type: 'local';
path: string;
}| Field | Type | Description |
|---|---|---|
type | 'local' | Must be 'local' (only local plugins currently supported) |
path | string | Absolute or relative path to the plugin directory |
Example:
plugins: [
{ type: 'local', path: './my-plugin' },
{ type: 'local', path: '/absolute/path/to/plugin' }
]For complete information on creating and using plugins, see Plugins.
SDKMessageUnion type of all possible messages returned by the query.
type SDKMessage =
| SDKAssistantMessage
| SDKUserMessage
| SDKUserMessageReplay
| SDKResultMessage
| SDKSystemMessage
| SDKPartialAssistantMessage
| SDKCompactBoundaryMessage;SDKAssistantMessageAssistant response message.
type SDKAssistantMessage = {
type: 'assistant';
uuid: UUID;
session_id: string;
message: APIAssistantMessage; // From Anthropic SDK
parent_tool_use_id: string | null;
}SDKUserMessageUser input message.
type SDKUserMessage = {
type: 'user';
uuid?: UUID;
session_id: string;
message: APIUserMessage; // From Anthropic SDK
parent_tool_use_id: string | null;
}SDKUserMessageReplayReplayed user message with required UUID.
type SDKUserMessageReplay = {
type: 'user';
uuid: UUID;
session_id: string;
message: APIUserMessage;
parent_tool_use_id: string | null;
}SDKResultMessageFinal result message.
type SDKResultMessage =
| {
type: 'result';
subtype: 'success';
uuid: UUID;
session_id: string;
duration_ms: number;
duration_api_ms: number;
is_error: boolean;
num_turns: number;
result: string;
total_cost_usd: number;
usage: NonNullableUsage;
modelUsage: { [modelName: string]: ModelUsage };
permission_denials: SDKPermissionDenial[];
structured_output?: unknown;
}
| {
type: 'result';
subtype:
| 'error_max_turns'
| 'error_during_execution'
| 'error_max_budget_usd'
| 'error_max_structured_output_retries';
uuid: UUID;
session_id: string;
duration_ms: number;
duration_api_ms: number;
is_error: boolean;
num_turns: number;
total_cost_usd: number;
usage: NonNullableUsage;
modelUsage: { [modelName: string]: ModelUsage };
permission_denials: SDKPermissionDenial[];
errors: string[];
}SDKSystemMessageSystem initialization message.
type SDKSystemMessage = {
type: 'system';
subtype: 'init';
uuid: UUID;
session_id: string;
apiKeySource: ApiKeySource;
cwd: string;
tools: string[];
mcp_servers: {
name: string;
status: string;
}[];
model: string;
permissionMode: PermissionMode;
slash_commands: string[];
output_style: string;
}SDKPartialAssistantMessageStreaming partial message (only when includePartialMessages is true).
type SDKPartialAssistantMessage = {
type: 'stream_event';
event: RawMessageStreamEvent; // From Anthropic SDK
parent_tool_use_id: string | null;
uuid: UUID;
session_id: string;
}SDKCompactBoundaryMessageMessage indicating a conversation compaction boundary.
type SDKCompactBoundaryMessage = {
type: 'system';
subtype: 'compact_boundary';
uuid: UUID;
session_id: string;
compact_metadata: {
trigger: 'manual' | 'auto';
pre_tokens: number;
};
}SDKPermissionDenialInformation about a denied tool use.
type SDKPermissionDenial = {
tool_name: string;
tool_use_id: string;
tool_input: ToolInput;
}For a comprehensive guide on using hooks with examples and common patterns, see the Hooks guide.
HookEventAvailable hook events.
type HookEvent =
| 'PreToolUse'
| 'PostToolUse'
| 'PostToolUseFailure'
| 'Notification'
| 'UserPromptSubmit'
| 'SessionStart'
| 'SessionEnd'
| 'Stop'
| 'SubagentStart'
| 'SubagentStop'
| 'PreCompact'
| 'PermissionRequest';HookCallbackHook callback function type.
type HookCallback = (
input: HookInput, // Union of all hook input types
toolUseID: string | undefined,
options: { signal: AbortSignal }
) => Promise<HookJSONOutput>;HookCallbackMatcherHook configuration with optional matcher.
interface HookCallbackMatcher {
matcher?: string;
hooks: HookCallback[];
}HookInputUnion type of all hook input types.
type HookInput =
| PreToolUseHookInput
| PostToolUseHookInput
| PostToolUseFailureHookInput
| NotificationHookInput
| UserPromptSubmitHookInput
| SessionStartHookInput
| SessionEndHookInput
| StopHookInput
| SubagentStartHookInput
| SubagentStopHookInput
| PreCompactHookInput
| PermissionRequestHookInput;BaseHookInputBase interface that all hook input types extend.
type BaseHookInput = {
session_id: string;
transcript_path: string;
cwd: string;
permission_mode?: string;
}PreToolUseHookInputtype PreToolUseHookInput = BaseHookInput & {
hook_event_name: 'PreToolUse';
tool_name: string;
tool_input: unknown;
}PostToolUseHookInputtype PostToolUseHookInput = BaseHookInput & {
hook_event_name: 'PostToolUse';
tool_name: string;
tool_input: unknown;
tool_response: unknown;
}PostToolUseFailureHookInputtype PostToolUseFailureHookInput = BaseHookInput & {
hook_event_name: 'PostToolUseFailure';
tool_name: string;
tool_input: unknown;
error: string;
is_interrupt?: boolean;
}NotificationHookInputtype NotificationHookInput = BaseHookInput & {
hook_event_name: 'Notification';
message: string;
title?: string;
}UserPromptSubmitHookInputtype UserPromptSubmitHookInput = BaseHookInput & {
hook_event_name: 'UserPromptSubmit';
prompt: string;
}SessionStartHookInputtype SessionStartHookInput = BaseHookInput & {
hook_event_name: 'SessionStart';
source: 'startup' | 'resume' | 'clear' | 'compact';
}SessionEndHookInputtype SessionEndHookInput = BaseHookInput & {
hook_event_name: 'SessionEnd';
reason: ExitReason; // String from EXIT_REASONS array
}StopHookInputtype StopHookInput = BaseHookInput & {
hook_event_name: 'Stop';
stop_hook_active: boolean;
}SubagentStartHookInputtype SubagentStartHookInput = BaseHookInput & {
hook_event_name: 'SubagentStart';
agent_id: string;
agent_type: string;
}SubagentStopHookInputtype SubagentStopHookInput = BaseHookInput & {
hook_event_name: 'SubagentStop';
stop_hook_active: boolean;
}PreCompactHookInputtype PreCompactHookInput = BaseHookInput & {
hook_event_name: 'PreCompact';
trigger: 'manual' | 'auto';
custom_instructions: string | null;
}PermissionRequestHookInputtype PermissionRequestHookInput = BaseHookInput & {
hook_event_name: 'PermissionRequest';
tool_name: string;
tool_input: unknown;
permission_suggestions?: PermissionUpdate[];
}HookJSONOutputHook return value.
type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;AsyncHookJSONOutputtype AsyncHookJSONOutput = {
async: true;
asyncTimeout?: number;
}SyncHookJSONOutputtype SyncHookJSONOutput = {
continue?: boolean;
suppressOutput?: boolean;
stopReason?: string;
decision?: 'approve' | 'block';
systemMessage?: string;
reason?: string;
hookSpecificOutput?:
| {
hookEventName: 'PreToolUse';
permissionDecision?: 'allow' | 'deny' | 'ask';
permissionDecisionReason?: string;
updatedInput?: Record<string, unknown>;
}
| {
hookEventName: 'UserPromptSubmit';
additionalContext?: string;
}
| {
hookEventName: 'SessionStart';
additionalContext?: string;
}
| {
hookEventName: 'PostToolUse';
additionalContext?: string;
};
}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.
ToolInputNote: This is a documentation-only type for clarity. It represents the union of all tool input types.
type ToolInput =
| AgentInput
| AskUserQuestionInput
| BashInput
| BashOutputInput
| FileEditInput
| FileReadInput
| FileWriteInput
| GlobInput
| GrepInput
| KillShellInput
| NotebookEditInput
| WebFetchInput
| WebSearchInput
| TodoWriteInput
| ExitPlanModeInput
| ListMcpResourcesInput
| ReadMcpResourceInput;Tool name: Task
interface AgentInput {
/**
* A short (3-5 word) description of the task
*/
description: string;
/**
* The task for the agent to perform
*/
prompt: string;
/**
* The type of specialized agent to use for this task
*/
subagent_type: string;
}Launches a new agent to handle complex, multi-step tasks autonomously.
Tool name: AskUserQuestion
interface AskUserQuestionInput {
/**
* Questions to ask the user (1-4 questions)
*/
questions: Array<{
/**
* The complete question to ask the user. Should be clear, specific,
* and end with a question mark.
*/
question: string;
/**
* Very short label displayed as a chip/tag (max 12 chars).
* Examples: "Auth method", "Library", "Approach"
*/
header: string;
/**
* The available choices (2-4 options). An "Other" option is
* automatically provided.
*/
options: Array<{
/**
* Display text for this option (1-5 words)
*/
label: string;
/**
* Explanation of what this option means
*/
description: string;
}>;
/**
* Set to true to allow multiple selections
*/
multiSelect: boolean;
}>;
/**
* User answers populated by the permission system.
* Maps question text to selected option label(s).
* Multi-select answers are comma-separated.
*/
answers?: Record<string, string>;
}Asks the user clarifying questions during execution. See Handling the AskUserQuestion Tool for usage details.
Tool name: Bash
interface BashInput {
/**
* The command to execute
*/
command: string;
/**
* Optional timeout in milliseconds (max 600000)
*/
timeout?: number;
/**
* Clear, concise description of what this command does in 5-10 words
*/
description?: string;
/**
* Set to true to run this command in the background
*/
run_in_background?: boolean;
}Executes bash commands in a persistent shell session with optional timeout and background execution.
Tool name: BashOutput
interface BashOutputInput {
/**
* The ID of the background shell to retrieve output from
*/
bash_id: string;
/**
* Optional regex to filter output lines
*/
filter?: string;
}Retrieves output from a running or completed background bash shell.
Tool name: Edit
interface FileEditInput {
/**
* The absolute path to the file to modify
*/
file_path: string;
/**
* The text to replace
*/
old_string: string;
/**
* The text to replace it with (must be different from old_string)
*/
new_string: string;
/**
* Replace all occurrences of old_string (default false)
*/
replace_all?: boolean;
}Performs exact string replacements in files.
Tool name: Read
interface FileReadInput {
/**
* The absolute path to the file to read
*/
file_path: string;
/**
* The line number to start reading from
*/
offset?: number;
/**
* The number of lines to read
*/
limit?: number;
}Reads files from the local filesystem, including text, images, PDFs, and Jupyter notebooks.
Tool name: Write
interface FileWriteInput {
/**
* The absolute path to the file to write
*/
file_path: string;
/**
* The content to write to the file
*/
content: string;
}Writes a file to the local filesystem, overwriting if it exists.
Tool name: Glob
interface GlobInput {
/**
* The glob pattern to match files against
*/
pattern: string;
/**
* The directory to search in (defaults to cwd)
*/
path?: string;
}Fast file pattern matching that works with any codebase size.
Tool name: Grep
interface GrepInput {
/**
* The regular expression pattern to search for
*/
pattern: string;
/**
* File or directory to search in (defaults to cwd)
*/
path?: string;
/**
* Glob pattern to filter files (e.g. "*.js")
*/
glob?: string;
/**
* File type to search (e.g. "js", "py", "rust")
*/
type?: string;
/**
* Output mode: "content", "files_with_matches", or "count"
*/
output_mode?: 'content' | 'files_with_matches' | 'count';
/**
* Case insensitive search
*/
'-i'?: boolean;
/**
* Show line numbers (for content mode)
*/
'-n'?: boolean;
/**
* Lines to show before each match
*/
'-B'?: number;
/**
* Lines to show after each match
*/
'-A'?: number;
/**
* Lines to show before and after each match
*/
'-C'?: number;
/**
* Limit output to first N lines/entries
*/
head_limit?: number;
/**
* Enable multiline mode
*/
multiline?: boolean;
}Powerful search tool built on ripgrep with regex support.
Tool name: KillBash
interface KillShellInput {
/**
* The ID of the background shell to kill
*/
shell_id: string;
}Kills a running background bash shell by its ID.
Tool name: NotebookEdit
interface NotebookEditInput {
/**
* The absolute path to the Jupyter notebook file
*/
notebook_path: string;
/**
* The ID of the cell to edit
*/
cell_id?: string;
/**
* The new source for the cell
*/
new_source: string;
/**
* The type of the cell (code or markdown)
*/
cell_type?: 'code' | 'markdown';
/**
* The type of edit (replace, insert, delete)
*/
edit_mode?: 'replace' | 'insert' | 'delete';
}Edits cells in Jupyter notebook files.
Tool name: WebFetch
interface WebFetchInput {
/**
* The URL to fetch content from
*/
url: string;
/**
* The prompt to run on the fetched content
*/
prompt: string;
}Fetches content from a URL and processes it with an AI model.
Tool name: WebSearch
interface WebSearchInput {
/**
* The search query to use
*/
query: string;
/**
* Only include results from these domains
*/
allowed_domains?: string[];
/**
* Never include results from these domains
*/
blocked_domains?: string[];
}Searches the web and returns formatted results.
Tool name: TodoWrite
interface TodoWriteInput {
/**
* The updated todo list
*/
todos: Array<{
/**
* The task description
*/
content: string;
/**
* The task status
*/
status: 'pending' | 'in_progress' | 'completed';
/**
* Active form of the task description
*/
activeForm: string;
}>;
}Creates and manages a structured task list for tracking progress.
Tool name: ExitPlanMode
interface ExitPlanModeInput {
/**
* The plan to run by the user for approval
*/
plan: string;
}Exits planning mode and prompts the user to approve the plan.
Tool name: ListMcpResources
interface ListMcpResourcesInput {
/**
* Optional server name to filter resources by
*/
server?: string;
}Lists available MCP resources from connected servers.
Tool name: ReadMcpResource
interface ReadMcpResourceInput {
/**
* The MCP server name
*/
server: string;
/**
* The resource URI to read
*/
uri: string;
}Reads a specific MCP resource from a server.
Documentation of output schemas for all built-in Claude Code tools. These types represent the actual response data returned by each tool.
ToolOutputNote: This is a documentation-only type for clarity. It represents the union of all tool output types.
type ToolOutput =
| TaskOutput
| AskUserQuestionOutput
| BashOutput
| BashOutputToolOutput
| EditOutput
| ReadOutput
| WriteOutput
| GlobOutput
| GrepOutput
| KillBashOutput
| NotebookEditOutput
| WebFetchOutput
| WebSearchOutput
| TodoWriteOutput
| ExitPlanModeOutput
| ListMcpResourcesOutput
| ReadMcpResourceOutput;Tool name: Task
interface TaskOutput {
/**
* Final result message from the subagent
*/
result: string;
/**
* Token usage statistics
*/
usage?: {
input_tokens: number;
output_tokens: number;
cache_creation_input_tokens?: number;
cache_read_input_tokens?: number;
};
/**
* Total cost in USD
*/
total_cost_usd?: number;
/**
* Execution duration in milliseconds
*/
duration_ms?: number;
}Returns the final result from the subagent after completing the delegated task.
Tool name: AskUserQuestion
interface AskUserQuestionOutput {
/**
* The questions that were asked
*/
questions: Array<{
question: string;
header: string;
options: Array<{
label: string;
description: string;
}>;
multiSelect: boolean;
}>;
/**
* The answers provided by the user.
* Maps question text to answer string.
* Multi-select answers are comma-separated.
*/
answers: Record<string, string>;
}Returns the questions asked and the user's answers.
Tool name: Bash
interface BashOutput {
/**
* Combined stdout and stderr output
*/
output: string;
/**
* Exit code of the command
*/
exitCode: number;
/**
* Whether the command was killed due to timeout
*/
killed?: boolean;
/**
* Shell ID for background processes
*/
shellId?: string;
}Returns command output with exit status. Background commands return immediately with a shellId.
Tool name: BashOutput
interface BashOutputToolOutput {
/**
* New output since last check
*/
output: string;
/**
* Current shell status
*/
status: 'running' | 'completed' | 'failed';
/**
* Exit code (when completed)
*/
exitCode?: number;
}Returns incremental output from background shells.
Tool name: Edit
interface EditOutput {
/**
* Confirmation message
*/
message: string;
/**
* Number of replacements made
*/
replacements: number;
/**
* File path that was edited
*/
file_path: string;
}Returns confirmation of successful edits with replacement count.
Tool name: Read
type ReadOutput =
| TextFileOutput
| ImageFileOutput
| PDFFileOutput
| NotebookFileOutput;
interface TextFileOutput {
/**
* File contents with line numbers
*/
content: string;
/**
* Total number of lines in file
*/
total_lines: number;
/**
* Lines actually returned
*/
lines_returned: number;
}
interface ImageFileOutput {
/**
* Base64 encoded image data
*/
image: string;
/**
* Image MIME type
*/
mime_type: string;
/**
* File size in bytes
*/
file_size: number;
}
interface PDFFileOutput {
/**
* Array of page contents
*/
pages: Array<{
page_number: number;
text?: string;
images?: Array<{
image: string;
mime_type: string;
}>;
}>;
/**
* Total number of pages
*/
total_pages: number;
}
interface NotebookFileOutput {
/**
* Jupyter notebook cells
*/
cells: Array<{
cell_type: 'code' | 'markdown';
source: string;
outputs?: any[];
execution_count?: number;
}>;
/**
* Notebook metadata
*/
metadata?: Record<string, any>;
}Returns file contents in format appropriate to file type.
Tool name: Write
interface WriteOutput {
/**
* Success message
*/
message: string;
/**
* Number of bytes written
*/
bytes_written: number;
/**
* File path that was written
*/
file_path: string;
}Returns confirmation after successfully writing the file.
Tool name: Glob
interface GlobOutput {
/**
* Array of matching file paths
*/
matches: string[];
/**
* Number of matches found
*/
count: number;
/**
* Search directory used
*/
search_path: string;
}Returns file paths matching the glob pattern, sorted by modification time.
Tool name: Grep
type GrepOutput =
| GrepContentOutput
| GrepFilesOutput
| GrepCountOutput;
interface GrepContentOutput {
/**
* Matching lines with context
*/
matches: Array<{
file: string;
line_number?: number;
line: string;
before_context?: string[];
after_context?: string[];
}>;
/**
* Total number of matches
*/
total_matches: number;
}
interface GrepFilesOutput {
/**
* Files containing matches
*/
files: string[];
/**
* Number of files with matches
*/
count: number;
}
interface GrepCountOutput {
/**
* Match counts per file
*/
counts: Array<{
file: string;
count: number;
}>;
/**
* Total matches across all files
*/
total: number;
}Returns search results in the format specified by output_mode.
Tool name: KillBash
interface KillBashOutput {
/**
* Success message
*/
message: string;
/**
* ID of the killed shell
*/
shell_id: string;
}Returns confirmation after terminating the background shell.
Tool name: NotebookEdit
interface NotebookEditOutput {
/**
* Success message
*/
message: string;
/**
* Type of edit performed
*/
edit_type: 'replaced' | 'inserted' | 'deleted';
/**
* Cell ID that was affected
*/
cell_id?: string;
/**
* Total cells in notebook after edit
*/
total_cells: number;
}Returns confirmation after modifying the Jupyter notebook.
Tool name: WebFetch
interface WebFetchOutput {
/**
* AI model's response to the prompt
*/
response: string;
/**
* URL that was fetched
*/
url: string;
/**
* Final URL after redirects
*/
final_url?: string;
/**
* HTTP status code
*/
status_code?: number;
}Returns the AI's analysis of the fetched web content.
Tool name: WebSearch
interface WebSearchOutput {
/**
* Search results
*/
results: Array<{
title: string;
url: string;
snippet: string;
/**
* Additional metadata if available
*/
metadata?: Record<string, any>;
}>;
/**
* Total number of results
*/
total_results: number;
/**
* The query that was searched
*/
query: string;
}Returns formatted search results from the web.
Tool name: TodoWrite
interface TodoWriteOutput {
/**
* Success message
*/
message: string;
/**
* Current todo statistics
*/
stats: {
total: number;
pending: number;
in_progress: number;
completed: number;
};
}Returns confirmation with current task statistics.
Tool name: ExitPlanMode
interface ExitPlanModeOutput {
/**
* Confirmation message
*/
message: string;
/**
* Whether user approved the plan
*/
approved?: boolean;
}Returns confirmation after exiting plan mode.
Tool name: ListMcpResources
interface ListMcpResourcesOutput {
/**
* Available resources
*/
resources: Array<{
uri: string;
name: string;
description?: string;
mimeType?: string;
server: string;
}>;
/**
* Total number of resources
*/
total: number;
}Returns list of available MCP resources.
Tool name: ReadMcpResource
interface ReadMcpResourceOutput {
/**
* Resource contents
*/
contents: Array<{
uri: string;
mimeType?: string;
text?: string;
blob?: string;
}>;
/**
* Server that provided the resource
*/
server: string;
}Returns the contents of the requested MCP resource.
PermissionUpdateOperations for updating permissions.
type PermissionUpdate =
| {
type: 'addRules';
rules: PermissionRuleValue[];
behavior: PermissionBehavior;
destination: PermissionUpdateDestination;
}
| {
type: 'replaceRules';
rules: PermissionRuleValue[];
behavior: PermissionBehavior;
destination: PermissionUpdateDestination;
}
| {
type: 'removeRules';
rules: PermissionRuleValue[];
behavior: PermissionBehavior;
destination: PermissionUpdateDestination;
}
| {
type: 'setMode';
mode: PermissionMode;
destination: PermissionUpdateDestination;
}
| {
type: 'addDirectories';
directories: string[];
destination: PermissionUpdateDestination;
}
| {
type: 'removeDirectories';
directories: string[];
destination: PermissionUpdateDestination;
}PermissionBehaviortype PermissionBehavior = 'allow' | 'deny' | 'ask';PermissionUpdateDestinationtype PermissionUpdateDestination =
| 'userSettings' // Global user settings
| 'projectSettings' // Per-directory project settings
| 'localSettings' // Gitignored local settings
| 'session' // Current session onlyPermissionRuleValuetype PermissionRuleValue = {
toolName: string;
ruleContent?: string;
}ApiKeySourcetype ApiKeySource = 'user' | 'project' | 'org' | 'temporary';SdkBetaAvailable beta features that can be enabled via the betas option. See Beta headers for more information.
type SdkBeta = 'context-1m-2025-08-07';| Value | Description | Compatible Models |
|---|---|---|
'context-1m-2025-08-07' | Enables 1 million token context window | Claude Sonnet 4, Claude Sonnet 4.5 |
SlashCommandInformation about an available slash command.
type SlashCommand = {
name: string;
description: string;
argumentHint: string;
}ModelInfoInformation about an available model.
type ModelInfo = {
value: string;
displayName: string;
description: string;
}McpServerStatusStatus of a connected MCP server.
type McpServerStatus = {
name: string;
status: 'connected' | 'failed' | 'needs-auth' | 'pending';
serverInfo?: {
name: string;
version: string;
};
}AccountInfoAccount information for the authenticated user.
type AccountInfo = {
email?: string;
organization?: string;
subscriptionType?: string;
tokenSource?: string;
apiKeySource?: string;
}ModelUsagePer-model usage statistics returned in result messages.
type ModelUsage = {
inputTokens: number;
outputTokens: number;
cacheReadInputTokens: number;
cacheCreationInputTokens: number;
webSearchRequests: number;
costUSD: number;
contextWindow: number;
}ConfigScopetype ConfigScope = 'local' | 'user' | 'project';NonNullableUsageA version of Usage with all nullable fields made non-nullable.
type NonNullableUsage = {
[K in keyof Usage]: NonNullable<Usage[K]>;
}UsageToken usage statistics (from @anthropic-ai/sdk).
type Usage = {
input_tokens: number | null;
output_tokens: number | null;
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
}CallToolResultMCP tool result type (from @modelcontextprotocol/sdk/types.js).
type CallToolResult = {
content: Array<{
type: 'text' | 'image' | 'resource';
// Additional fields vary by type
}>;
isError?: boolean;
}AbortErrorCustom error class for abort operations.
class AbortError extends Error {}SandboxSettingsConfiguration for sandbox behavior. Use this to enable command sandboxing and configure network restrictions programmatically.
type SandboxSettings = {
enabled?: boolean;
autoAllowBashIfSandboxed?: boolean;
excludedCommands?: string[];
allowUnsandboxedCommands?: boolean;
network?: NetworkSandboxSettings;
ignoreViolations?: SandboxIgnoreViolations;
enableWeakerNestedSandbox?: boolean;
}| Property | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enable sandbox mode for command execution |
autoAllowBashIfSandboxed | boolean | false | Auto-approve bash commands when sandbox is enabled |
excludedCommands | string[] | [] | Commands that always bypass sandbox restrictions (e.g., ['docker']). These run unsandboxed automatically without model involvement |
Filesystem and network access restrictions are NOT configured via sandbox settings. Instead, they are derived from permission rules:
Use sandbox settings for command execution sandboxing, and permission rules for filesystem and network access control.
import { query } from "@anthropic-ai/claude-agent-sdk";
const result = await query({
prompt: "Build and test my project",
options: {
sandbox: {
enabled: true,
autoAllowBashIfSandboxed: true,
excludedCommands: ["docker"],
network: {
allowLocalBinding: true,
allowUnixSockets: ["/var/run/docker.sock"]
}
}
}
});NetworkSandboxSettingsNetwork-specific configuration for sandbox mode.
type NetworkSandboxSettings = {
allowLocalBinding?: boolean;
allowUnixSockets?: string[];
allowAllUnixSockets?: boolean;
httpProxyPort?: number;
socksProxyPort?: number;
}| Property | Type | Default | Description |
|---|---|---|---|
allowLocalBinding | boolean | false | Allow processes to bind to local ports (e.g., for dev servers) |
allowUnixSockets | string[] | [] | Unix socket paths that processes can access (e.g., Docker socket) |
allowAllUnixSockets | boolean | false | Allow access to all Unix sockets |
httpProxyPort |
SandboxIgnoreViolationsConfiguration for ignoring specific sandbox violations.
type SandboxIgnoreViolations = {
file?: string[];
network?: string[];
}| Property | Type | Default | Description |
|---|---|---|---|
file | string[] | [] | File path patterns to ignore violations for |
network | string[] | [] | Network patterns to ignore violations for |
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 will be invoked, allowing you to implement custom authorization logic.
excludedCommands vs allowUnsandboxedCommands:
excludedCommands: A static list of commands that always bypass the sandbox automatically (e.g., ['docker']). The model has no control over this.allowUnsandboxedCommands: Lets the model decide at runtime whether to request unsandboxed execution by setting dangerouslyDisableSandbox: true in the tool input.import { query } from "@anthropic-ai/claude-agent-sdk";
const result = await query({
prompt: "Deploy my application",
options: {
sandbox: {
enabled: true,
allowUnsandboxedCommands: true // Model can request unsandboxed execution
},
permissionMode: "default",
canUseTool: async (tool, input) => {
// Check if the model is requesting to bypass the sandbox
if (tool === "Bash" && input.dangerouslyDisableSandbox) {
// The model wants to run this command outside the sandbox
console.log(`Unsandboxed command requested: ${input.command}`);
// Return true to allow, false to deny
return isCommandAuthorized(input.command);
}
return true;
}
}
});This pattern enables you to:
Commands running with dangerouslyDisableSandbox: true have full system access. Ensure your canUseTool handler validates these requests carefully.
allowDangerouslySkipPermissions |
boolean |
false |
Enable bypassing permissions. Required when using permissionMode: 'bypassPermissions' |
allowedTools | string[] | All tools | List of allowed tool names |
betas | SdkBeta[] | [] | Enable beta features (e.g., ['context-1m-2025-08-07']) |
canUseTool | CanUseTool | undefined | Custom permission function for tool usage |
continue | boolean | false | Continue the most recent conversation |
cwd | string | process.cwd() | Current working directory |
disallowedTools | string[] | [] | List of disallowed tool names |
enableFileCheckpointing | boolean | false | Enable file change tracking for rewinding. See File checkpointing |
env | Dict<string> | process.env | Environment variables |
executable | 'bun' | 'deno' | 'node' | Auto-detected | JavaScript runtime to use |
executableArgs | string[] | [] | Arguments to pass to the executable |
extraArgs | Record<string, string | null> | {} | Additional arguments |
fallbackModel | string | undefined | Model to use if primary fails |
forkSession | boolean | false | When resuming with resume, fork to a new session ID instead of continuing the original session |
hooks | Partial<Record<HookEvent, HookCallbackMatcher[]>> | {} | Hook callbacks for events |
includePartialMessages | boolean | false | Include partial message events |
maxBudgetUsd | number | undefined | Maximum budget in USD for the query |
maxThinkingTokens | number | undefined | Maximum tokens for thinking process |
maxTurns | number | undefined | Maximum conversation turns |
mcpServers | Record<string, [McpServerConfig](#mcpserverconfig)> | {} | MCP server configurations |
model | string | Default from CLI | Claude model to use |
outputFormat | { type: 'json_schema', schema: JSONSchema } | undefined | Define output format for agent results. See Structured outputs for details |
pathToClaudeCodeExecutable | string | Uses built-in executable | Path to Claude Code executable |
permissionMode | PermissionMode | 'default' | Permission mode for the session |
permissionPromptToolName | string | undefined | MCP tool name for permission prompts |
plugins | SdkPluginConfig[] | [] | Load custom plugins from local paths. See Plugins for details |
resume | string | undefined | Session ID to resume |
resumeSessionAt | string | undefined | Resume session at a specific message UUID |
sandbox | SandboxSettings | undefined | Configure sandbox behavior programmatically. See Sandbox settings for details |
settingSources | SettingSource[] | [] (no settings) | Control which filesystem settings to load. When omitted, no settings are loaded. Note: Must include 'project' to load CLAUDE.md files |
stderr | (data: string) => void | undefined | Callback for stderr output |
strictMcpConfig | boolean | false | Enforce strict MCP validation |
systemPrompt | string | { type: 'preset'; preset: 'claude_code'; append?: string } | undefined (empty prompt) | System prompt configuration. Pass a string for custom prompt, or { type: 'preset', preset: 'claude_code' } to use Claude Code's system prompt. When using the preset object form, add append to extend the system prompt with additional instructions |
tools | string[] | { type: 'preset'; preset: 'claude_code' } | undefined | Tool configuration. Pass an array of tool names or use the preset to get Claude Code's default tools |
supportedModels()| Returns available models with display info |
mcpServerStatus() | Returns status of connected MCP servers |
accountInfo() | Returns account information |
allowUnsandboxedCommands | boolean | false | Allow the model to request running commands outside the sandbox. When true, the model can set dangerouslyDisableSandbox in tool input, which falls back to the permissions system |
network | NetworkSandboxSettings | undefined | Network-specific sandbox configuration |
ignoreViolations | SandboxIgnoreViolations | undefined | Configure which sandbox violations to ignore |
enableWeakerNestedSandbox | boolean | false | Enable a weaker nested sandbox for compatibility |
number |
undefined |
| HTTP proxy port for network requests |
socksProxyPort | number | undefined | SOCKS proxy port for network requests |