Chapter 4

Types

TypeScript type definitions for the Claude Agent SDK.

Options

Configuration object for the query() function.

PropertyTypeDefaultDescription
abortControllerAbortControllernew AbortController()Controller for cancelling operations
additionalDirectoriesstring[][]Additional directories Claude can access
agentsRecord<string, AgentDefinition>undefinedProgrammatically define subagents
allowDangerouslySkipPermissionsbooleanfalseEnable bypassing permissions. Required when using permissionMode: 'bypassPermissions'
allowedToolsstring[]All toolsList of allowed tool names
betasSdkBeta[][]Enable beta features (e.g., ['context-1m-2025-08-07'])
canUseToolCanUseToolundefinedCustom permission function for tool usage
continuebooleanfalseContinue the most recent conversation
cwdstringprocess.cwd()Current working directory
disallowedToolsstring[][]List of disallowed tool names
enableFileCheckpointingbooleanfalseEnable file change tracking for rewinding
envDict<string>process.envEnvironment variables
executable'bun' | 'deno' | 'node'Auto-detectedJavaScript runtime to use
executableArgsstring[][]Arguments to pass to the executable
extraArgsRecord<string, string | null>{}Additional arguments
fallbackModelstringundefinedModel to use if primary fails
forkSessionbooleanfalseWhen resuming, fork to a new session ID instead of continuing the original
hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>{}Hook callbacks for events
includePartialMessagesbooleanfalseInclude partial message events
maxBudgetUsdnumberundefinedMaximum budget in USD for the query
maxThinkingTokensnumberundefinedMaximum tokens for thinking process
maxTurnsnumberundefinedMaximum conversation turns
mcpServersRecord<string, McpServerConfig>{}MCP server configurations
modelstringDefault from CLIClaude model to use
outputFormat{ type: 'json_schema', schema: JSONSchema }undefinedDefine output format for structured results
pathToClaudeCodeExecutablestringBuilt-in executablePath to Claude Code executable
permissionModePermissionMode'default'Permission mode for the session
permissionPromptToolNamestringundefinedMCP tool name for permission prompts
pluginsSdkPluginConfig[][]Load custom plugins from local paths
resumestringundefinedSession ID to resume
resumeSessionAtstringundefinedResume session at a specific message UUID
sandboxSandboxSettingsundefinedConfigure sandbox behavior programmatically
settingSourcesSettingSource[][]Control which filesystem settings to load. Must include 'project' to load CLAUDE.md files
stderr(data: string) => voidundefinedCallback for stderr output
strictMcpConfigbooleanfalseEnforce strict MCP validation
systemPromptstring | { type: 'preset', preset: 'claude_code', append?: string }undefinedSystem prompt configuration. Use preset object form to extend Claude Code's system prompt
toolsstring[] | { type: 'preset', preset: 'claude_code' }undefinedTools available to the agent

Query

Interface returned by the query() function.

Query.ts
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

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

AgentDefinition.ts
type AgentDefinition = {
  description: string;
  tools?: string[];
  prompt: string;
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
}
FieldRequiredDescription
descriptionYesNatural language description of when to use this agent
toolsNoArray of allowed tool names. If omitted, inherits all tools
promptYesThe agent's system prompt
modelNoModel override for this agent. If omitted, uses the main model

SettingSource

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

SettingSource.ts
type SettingSource = 'user' | 'project' | 'local';
ValueDescriptionLocation
'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.

CanUseTool.ts
type CanUseTool = (
  toolName: string,
  input: ToolInput,
  options: {
    signal: AbortSignal;
    suggestions?: PermissionUpdate[];
  }
) => Promise<PermissionResult>;

PermissionResult

Result of a permission check.

PermissionResult.ts
type PermissionResult = 
  | {
      behavior: 'allow';
      updatedInput: ToolInput;
      updatedPermissions?: PermissionUpdate[];
    }
  | {
      behavior: 'deny';
      message: string;
      interrupt?: boolean;
    }

McpServerConfig

Configuration for MCP servers.

McpServerConfig.ts
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.

SdkPluginConfig.ts
type SdkPluginConfig = {
  type: 'local';
  path: string;
};
FieldTypeDescription
type'local'Must be 'local' (only local plugins currently supported)
pathstringAbsolute 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.

SDKMessage.ts
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;
      };
};