Chapter 4
Types
TypeScript type definitions for the Claude Agent SDK.
Options
Configuration 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> | undefined | Programmatically define subagents |
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 |
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, fork to a new session ID instead of continuing the original |
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> | {} | MCP server configurations |
model | string | Default from CLI | Claude model to use |
outputFormat | { type: 'json_schema', schema: JSONSchema } | undefined | Define output format for structured results |
pathToClaudeCodeExecutable | string | 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 |
resume | string | undefined | Session ID to resume |
resumeSessionAt | string | undefined | Resume session at a specific message UUID |
sandbox | SandboxSettings | undefined | Configure sandbox behavior programmatically |
settingSources | SettingSource[] | [] | Control which filesystem settings to load. 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 | System prompt configuration. Use preset object form to extend Claude Code's system prompt |
tools | string[] | { type: 'preset', preset: 'claude_code' } | undefined | Tools available to the agent |
Query
Interface 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>;
}Methods
| 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 |
setPermissionMode(mode) | Changes the permission mode (only available in streaming input mode) |
setModel(model) | Changes the model (only available in streaming input mode) |
setMaxThinkingTokens(maxThinkingTokens) | Changes the maximum thinking tokens (only available in streaming input mode) |
supportedCommands() | Returns available slash commands |
supportedModels() | Returns available models with display info |
mcpServerStatus() | Returns status of connected MCP servers |
accountInfo() | Returns account information |
AgentDefinition
Configuration 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 |
SettingSource
Controls 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 |
Default behavior
When settingSources is omitted or undefined, the SDK does not load any filesystem settings. This provides isolation for SDK applications.
Why use settingSources?
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']
}
});CanUseTool
Custom permission function type for controlling tool usage.
type CanUseTool = (
toolName: string,
input: ToolInput,
options: {
signal: AbortSignal;
suggestions?: PermissionUpdate[];
}
) => Promise<PermissionResult>;PermissionResult
Result of a permission check.
type PermissionResult =
| {
behavior: 'allow';
updatedInput: ToolInput;
updatedPermissions?: PermissionUpdate[];
}
| {
behavior: 'deny';
message: string;
interrupt?: boolean;
}McpServerConfig
Configuration for MCP servers.
type McpServerConfig =
| McpStdioServerConfig
| McpSSEServerConfig
| McpHttpServerConfig
| McpSdkServerConfigWithInstance;McpStdioServerConfig
type McpStdioServerConfig = {
type?: 'stdio';
command: string;
args?: string[];
env?: Record<string, string>;
};McpSSEServerConfig
type McpSSEServerConfig = {
type: 'sse';
url: string;
headers?: Record<string, string>;
};McpHttpServerConfig
type McpHttpServerConfig = {
type: 'http';
url: string;
headers?: Record<string, string>;
};McpSdkServerConfigWithInstance
type McpSdkServerConfigWithInstance = {
type: 'sdk';
name: string;
instance: McpServer;
};SdkPluginConfig
Configuration 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.
Message Types
SDKMessage
Union type of all possible messages returned by the query.
type SDKMessage =
| SDKAssistantMessage
| SDKUserMessage
| SDKUserMessageReplay
| SDKResultMessage
| SDKSystemMessage
| SDKPartialAssistantMessage
| SDKCompactBoundaryMessage;SDKAssistantMessage
Assistant response message.
type SDKAssistantMessage = {
type: 'assistant';
uuid: UUID;
session_id: string;
message: APIAssistantMessage; // From Anthropic SDK
parent_tool_use_id: string | null;
};SDKUserMessage
User input message.
type SDKUserMessage = {
type: 'user';
uuid?: UUID;
session_id: string;
message: APIUserMessage; // From Anthropic SDK
parent_tool_use_id: string | null;
};SDKUserMessageReplay
Replayed user message with required UUID.
type SDKUserMessageReplay = {
type: 'user';
uuid: UUID;
session_id: string;
message: APIUserMessage;
parent_tool_use_id: string | null;
};SDKResultMessage
Final 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[];
}SDKSystemMessage
System 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;
};SDKPartialAssistantMessage
Streaming 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;
};SDKCompactBoundaryMessage
Message 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;
};
};SDKPermissionDenial
Information about a denied tool use.
type SDKPermissionDenial = {
tool_name: string;
tool_use_id: string;
tool_input: ToolInput;
};Hook Types
For a comprehensive guide on using hooks with examples and common patterns, see the Hooks guide.
HookEvent
Available hook events.
type HookEvent =
| 'PreToolUse'
| 'PostToolUse'
| 'PostToolUseFailure'
| 'Notification'
| 'UserPromptSubmit'
| 'SessionStart'
| 'SessionEnd'
| 'Stop'
| 'SubagentStart'
| 'SubagentStop'
| 'PreCompact'
| 'PermissionRequest';HookCallback
Hook callback function type.
type HookCallback = (
input: HookInput, // Union of all hook input types
toolUseID: string | undefined,
options: { signal: AbortSignal }
) => Promise<HookJSONOutput>;HookCallbackMatcher
Hook configuration with optional matcher.
interface HookCallbackMatcher {
matcher?: string;
hooks: HookCallback[];
}HookInput
Union type of all hook input types.
type HookInput =
| PreToolUseHookInput
| PostToolUseHookInput
| PostToolUseFailureHookInput
| NotificationHookInput
| UserPromptSubmitHookInput
| SessionStartHookInput
| SessionEndHookInput
| StopHookInput
| SubagentStartHookInput
| SubagentStopHookInput
| PreCompactHookInput
| PermissionRequestHookInput;BaseHookInput
Base interface that all hook input types extend.
type BaseHookInput = {
session_id: string;
transcript_path: string;
cwd: string;
permission_mode?: string;
};PreToolUseHookInput
type PreToolUseHookInput = BaseHookInput & {
hook_event_name: 'PreToolUse';
tool_name: string;
tool_input: unknown;
};PostToolUseHookInput
type PostToolUseHookInput = BaseHookInput & {
hook_event_name: 'PostToolUse';
tool_name: string;
tool_input: unknown;
tool_response: unknown;
};PostToolUseFailureHookInput
type PostToolUseFailureHookInput = BaseHookInput & {
hook_event_name: 'PostToolUseFailure';
tool_name: string;
tool_input: unknown;
error: string;
is_interrupt?: boolean;
};NotificationHookInput
type NotificationHookInput = BaseHookInput & {
hook_event_name: 'Notification';
message: string;
title?: string;
};UserPromptSubmitHookInput
type UserPromptSubmitHookInput = BaseHookInput & {
hook_event_name: 'UserPromptSubmit';
prompt: string;
};SessionStartHookInput
type SessionStartHookInput = BaseHookInput & {
hook_event_name: 'SessionStart';
source: 'startup' | 'resume' | 'clear' | 'compact';
};SessionEndHookInput
type SessionEndHookInput = BaseHookInput & {
hook_event_name: 'SessionEnd';
reason: ExitReason; // String from EXIT_REASONS array
};StopHookInput
type StopHookInput = BaseHookInput & {
hook_event_name: 'Stop';
stop_hook_active: boolean;
};SubagentStartHookInput
type SubagentStartHookInput = BaseHookInput & {
hook_event_name: 'SubagentStart';
agent_id: string;
agent_type: string;
};SubagentStopHookInput
type SubagentStopHookInput = BaseHookInput & {
hook_event_name: 'SubagentStop';
stop_hook_active: boolean;
};PreCompactHookInput
type PreCompactHookInput = BaseHookInput & {
hook_event_name: 'PreCompact';
trigger: 'manual' | 'auto';
custom_instructions: string | null;
};PermissionRequestHookInput
type PermissionRequestHookInput = BaseHookInput & {
hook_event_name: 'PermissionRequest';
tool_name: string;
tool_input: unknown;
permission_suggestions?: PermissionUpdate[];
};HookJSONOutput
Hook return value.
type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;AsyncHookJSONOutput
type AsyncHookJSONOutput = {
async: true;
asyncTimeout?: number;
};SyncHookJSONOutput
type 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;
};
};