Installation
Install the package into a virtual environment. On recent Debian, Ubuntu, and Homebrew Python installs, runningpip install against system Python fails with error: externally-managed-environment.
Choosing between query() and ClaudeSDKClient
The Python SDK provides two ways to interact with Claude Code:
Quick comparison
When to use query() (one-off tasks)
Best for:
- One-off questions where you don’t need conversation history
- Independent tasks that don’t require context from previous exchanges
- Simple automation scripts
- When you want a fresh start each time
When to use ClaudeSDKClient (continuous conversation)
Best for:
- Continuing conversations - When you need Claude to remember context
- Follow-up questions - Building on previous responses
- Interactive applications - Chat interfaces, REPLs
- Response-driven logic - When next action depends on Claude’s response
- Session control - Managing conversation lifecycle explicitly
Functions
Signature blocks and bare
async for / async with fragments on this page are illustrative. To run them, wrap the body in async def main(): ... and call asyncio.run(main()).query()
Creates a new session for each interaction with Claude Code by default. Returns an async iterator that yields messages as they arrive. Each call to query() starts fresh with no memory of previous interactions unless you pass continue_conversation=True or resume in ClaudeAgentOptions. See Sessions.
Parameters
Returns
Returns anAsyncIterator[Message] that yields messages from the conversation.
Example - With options
tool()
Decorator for defining MCP tools with type safety.
Parameters
Input schema options
-
Simple type mapping (recommended):
-
JSON Schema format (for complex validation):
Returns
A decorator function that wraps the tool implementation and returns anSdkMcpTool instance.
Example
ToolAnnotations
Re-exported from mcp.types (also available as from claude_agent_sdk import ToolAnnotations). All fields are optional hints; clients should not rely on them for security decisions.
create_sdk_mcp_server()
Create an in-process MCP server that runs within your Python application.
Parameters
Returns
Returns anMcpSdkServerConfig object that can be passed to ClaudeAgentOptions.mcp_servers.
Example
list_sessions()
Lists past sessions with metadata. Filter by project directory or list sessions across all projects. Synchronous; returns immediately.
Parameters
Return type: SDKSessionInfo
Example
Print the 10 most recent sessions for a project. Results are sorted bylast_modified descending, so the first item is the newest. Omit directory to search across all projects.
get_session_messages()
Retrieves messages from a past session. Synchronous; returns immediately.
Parameters
Return type: SessionMessage
Example
get_session_info()
Reads metadata for a single session by ID without scanning the full project directory. Synchronous; returns immediately.
Parameters
Returns
SDKSessionInfo, or None if the session is not found.
Example
Look up a single session’s metadata without scanning the project directory. Useful when you already have a session ID from a previous run.rename_session()
Renames a session by appending a custom-title entry. Repeated calls are safe; the most recent title wins. Synchronous.
Parameters
Raises
ValueError if session_id is not a valid UUID or title is empty; FileNotFoundError if the session cannot be found.
Example
Rename the most recent session so it’s easier to find later. The new title appears inSDKSessionInfo.custom_title on subsequent reads.
tag_session()
Tags a session. Pass None to clear the tag. Repeated calls are safe; the most recent tag wins. Synchronous.
Parameters
Raises
ValueError if session_id is not a valid UUID or tag is empty after sanitization; FileNotFoundError if the session cannot be found.
Example
Tag a session, then filter by that tag on a later read. PassNone to clear an existing tag.
Classes
ClaudeSDKClient
Maintains a conversation session across multiple exchanges. This is the Python equivalent of how the TypeScript SDK’s query() function works internally - it creates a client object that can continue conversations.
Key Features
- Session continuity: Maintains conversation context across multiple
query()calls - Same conversation: The session retains previous messages
- Interrupt support: Can stop execution mid-task
- Explicit lifecycle: You control when the session starts and ends
- Response-driven flow: Can react to responses and send follow-ups
- Custom tools and hooks: Supports custom tools (created with
@tooldecorator) and hooks
Methods
Context Manager Support
The client can be used as an async context manager for automatic connection management:
Important: When iterating over messages, avoid using break to exit early as this can cause asyncio cleanup issues. Instead, let the iteration complete naturally or use flags to track when you’ve found what you need.
Example - Continuing a conversation
Example - Streaming input with ClaudeSDKClient
Example - Using interrupts
Buffer behavior after interrupt:
interrupt() sends a stop signal but does not clear the message buffer. Messages already produced by the interrupted task, including its ResultMessage (with subtype="error_during_execution"), remain in the stream. You must drain them with receive_response() before reading the response to a new query. If you send a new query immediately after interrupt() and call receive_response() only once, you’ll receive the interrupted task’s messages, not the new query’s response.Example - Advanced permission control
Types
@dataclass vs TypedDict: This SDK uses two kinds of types. Classes decorated with @dataclass (such as ResultMessage, AgentDefinition, TextBlock) are object instances at runtime and support attribute access: msg.result. Classes defined with TypedDict (such as ThinkingConfigEnabled, McpStdioServerConfig, SyncHookJSONOutput) are plain dicts at runtime and require key access: config["budget_tokens"], not config.budget_tokens. The ClassName(field=value) call syntax works for both, but only dataclasses produce objects with attributes.SdkMcpTool
Definition for an SDK MCP tool created with the @tool decorator.
Transport
Abstract base class for custom transport implementations. Use this to communicate with the Claude process over a custom channel (for example, a remote connection instead of a local subprocess).
Import:
from claude_agent_sdk import Transport
ClaudeAgentOptions
Configuration dataclass for Claude Code queries.
Handle slow or stalled API responses
The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them throughClaudeAgentOptions.env:
API_TIMEOUT_MS: per-request timeout on the Anthropic client, in milliseconds. Default600000. Applies to the main loop and all subagents.CLAUDE_CODE_MAX_RETRIES: maximum API retries. Default10, capped at15. Each retry gets its ownAPI_TIMEOUT_MSwindow, so worst-case wall time is roughlyAPI_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)plus backoff. For unattended runs that need to wait through longer outages, setCLAUDE_CODE_RETRY_WATCHDOG=1: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to300and removes the cap on this variable.CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS: stall watchdog for subagents launched withrun_in_background. Default600000. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.CLAUDE_ENABLE_STREAM_WATCHDOGwithCLAUDE_STREAM_IDLE_TIMEOUT_MS: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; setCLAUDE_ENABLE_STREAM_WATCHDOG=0to disable it.CLAUDE_STREAM_IDLE_TIMEOUT_MSdefaults to300000and is clamped to that minimum. The aborted request goes through the normal retry path.
OutputFormat
Configuration for structured output validation. Pass this as a dict to the output_format field on ClaudeAgentOptions:
SystemPromptPreset
Configuration for using Claude Code’s preset system prompt with optional additions.
SystemPromptFile
Configuration for loading a custom system prompt from a file instead of passing it as a string. The SDK maps this to the CLI --system-prompt-file flag. Use the file form when the prompt is large: the SDK passes a string system_prompt on the CLI subprocess argv, which is subject to OS command-line length limits before the SDK sends any API request. On Linux a single argument longer than roughly 128 KB fails at process spawn with Argument list too long. On Windows the whole command line is capped at roughly 32 KB, so the string form fails at a lower threshold.
SettingSource
Controls which filesystem-based configuration sources the SDK loads settings from.
Default behavior
Whensetting_sources is omitted or None, 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 setting_sources
Disable filesystem settings:In Python SDK 0.1.59 and earlier, an empty list was treated the same as omitting the option, so
setting_sources=[] did not disable filesystem settings. Upgrade to a newer release if you need an empty list to take effect. The TypeScript SDK is not affected.Settings precedence
When multiple sources are loaded, settings are merged with this precedence (highest to lowest):- Local settings (
.claude/settings.local.json) - Project settings (
.claude/settings.json) - User settings (
~/.claude/settings.json)
agents and allowed_tools override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options.
AgentDefinition
Configuration for a subagent defined programmatically.
AgentDefinition field names use camelCase, such as disallowedTools, permissionMode, and maxTurns. These names map directly to the wire format shared with the TypeScript SDK. This differs from ClaudeAgentOptions, which uses Python snake_case for the equivalent top-level fields such as disallowed_tools and permission_mode. Because AgentDefinition is a dataclass, passing a snake_case keyword raises a TypeError at construction time.PermissionMode
Permission modes for controlling tool execution.
EffortLevel
Effort levels for guiding thinking depth.
CanUseTool
Type alias for tool permission callback functions.
tool_name: Name of the tool being calledinput_data: The tool’s input parameterscontext: AToolPermissionContextwith additional information
PermissionResult (either PermissionResultAllow or PermissionResultDeny).
The callback 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 allowed_tools 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 callback even when an allow rule matches. In dontAsk mode these calls are denied instead, without invoking the callback.
ToolPermissionContext
Context information passed to tool permission callbacks.
PermissionResult
Union type for permission callback results.
PermissionResultAllow
Result indicating the tool call should be allowed.
PermissionResultDeny
Result indicating the tool call should be denied.
PermissionUpdate
Configuration for updating permissions programmatically.
PermissionRuleValue
A rule to add, replace, or remove in a permission update.
ToolsPreset
Preset tools configuration for using Claude Code’s default tool set.
ThinkingConfig
Controls extended thinking behavior. A union of three configurations:
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 ThinkingBlock outputs.
Because these are TypedDict classes, they’re plain dicts at runtime. Either construct them as dict literals or call the class like a constructor; both produce a dict. Access fields with config["budget_tokens"], not config.budget_tokens:
TaskBudget
API-side task budget in tokens, used with the task_budget field in ClaudeAgentOptions.
Because this is a
TypedDict, pass it as a plain dict, such as ClaudeAgentOptions(task_budget={"total": 50000}).
SdkBeta
Literal type for SDK beta features.
betas field in ClaudeAgentOptions to enable beta features.
McpSdkServerConfig
Configuration for SDK MCP servers created with create_sdk_mcp_server().
McpServerConfig
Union type for MCP server configurations.
McpStdioServerConfig
McpSSEServerConfig
McpHttpServerConfig
McpServerStatusConfig
The configuration of an MCP server as reported by get_mcp_status(). This is the union of all McpServerConfig transport variants plus an output-only claudeai-proxy variant for servers proxied through claude.ai.
McpSdkServerConfigStatus is the serializable form of McpSdkServerConfig with only type ("sdk") and name (str) fields; the in-process instance is omitted. McpClaudeAIProxyServerConfig has type ("claudeai-proxy"), url (str), and id (str) fields.
McpStatusResponse
Response from ClaudeSDKClient.get_mcp_status(). Wraps the list of server statuses under the mcpServers key.
McpServerStatus
Status of a connected MCP server, contained in McpStatusResponse.
SdkPluginConfig
Configuration for loading plugins in the SDK.
Example:
Message Types
Message
Union type of all possible messages.
UserMessage
User input message.
AssistantMessage
Assistant response message with content blocks.
AssistantMessageError
Possible error types for assistant messages.
SystemMessage
System message with metadata.
ResultMessage
Final result message with cost and usage information.
subtype field determines which other fields are populated. It is one of "success", "error_during_execution", "error_max_turns", "error_max_budget_usd", or "error_max_structured_output_retries". The Python dataclass flattens all variants into one shape, so fields that don’t apply to the returned subtype are None.
Several fields carry diagnostic detail when the conversation ends on an error:
is_error:Truewhen the conversation ended in an error state. AlwaysTrueon theerror_*subtypes. Onsubtype="success"it isTruewhen the final model request failed, meaning the agent loop completed but the last API call returned an error.api_error_status: the HTTP status code of the terminating API error.Nonewhen the turn ended without one. Populated only onsubtype="success".result: text of the final assistant message onsubtype="success", orNoneon theerror_*subtypes. Whensubtype="success"andis_error=True, this holds the API error string if one is available but can be empty, so checkapi_error_statusand the precedingAssistantMessagecontent for detail.errors: loop-level error strings such as the max-turns message. Populated only on theerror_*subtypes.
usage dict contains the following keys when present:
The
model_usage dict maps model names to per-model usage. The inner dict keys use camelCase because the value is passed through unmodified from the underlying CLI process, matching the TypeScript ModelUsage type:
StreamEvent
Stream event for partial message updates during streaming. Only received when include_partial_messages=True in ClaudeAgentOptions. Import via from claude_agent_sdk.types import StreamEvent.
RateLimitEvent
Emitted when rate limit status changes (for example, from "allowed" to "allowed_warning"). Use this to warn users before they hit a hard limit, or to back off when status is "rejected".
RateLimitInfo
Rate limit state carried by RateLimitEvent.
TaskStartedMessage
Emitted when a background task starts. A background task is anything tracked outside the main turn: a backgrounded Bash command, a Monitor watch, a subagent spawned via the Agent tool, or a remote agent. The task_type field tells you which. This naming is unrelated to the Task-to-Agent tool rename.
TaskUsage
Token and timing data for a background task.
TaskProgressMessage
Emitted periodically with progress updates for a running background task.
TaskNotificationMessage
Emitted when a background task completes, fails, or is stopped. Background tasks include run_in_background Bash commands, Monitor watches, and background subagents.
Content Block Types
ContentBlock
Union type of all content blocks.
TextBlock
Text content block.
ThinkingBlock
Thinking content block (for models with thinking capability).
ToolUseBlock
Tool use request block.
ToolResultBlock
Tool execution result block.
Error Types
ClaudeSDKError
Base exception class for all SDK errors.
CLINotFoundError
Raised when Claude Code CLI is not installed or not found.
CLIConnectionError
Raised when connection to Claude Code fails.
ProcessError
Raised when the Claude Code process fails.
CLIJSONDecodeError
Raised when JSON parsing fails.
Hook Types
For a comprehensive guide on using hooks with examples and common patterns, see the Hooks guide.HookEvent
Supported hook event types.
The TypeScript SDK supports additional hook events not yet available in Python. See the hook availability table for per-SDK support.
HookCallback
Type definition for hook callback functions.
input: Strongly-typed hook input with discriminated unions based onhook_event_name(seeHookInput)tool_use_id: Optional tool use identifier (for tool-related hooks)context: Hook context with additional information
HookJSONOutput that may contain:
decision:"block"to block the actionsystemMessage: warning message shown to the userhookSpecificOutput: Hook-specific output data
HookContext
Context information passed to hook callbacks.
HookMatcher
Configuration for matching hooks to specific events or tools.
HookInput
Union type of all hook input types. The actual type depends on the hook_event_name field.
BaseHookInput
Base fields present in all hook input types.
PreToolUseHookInput
Input data for PreToolUse hook events.
PostToolUseHookInput
Input data for PostToolUse hook events.
PostToolUseFailureHookInput
Input data for PostToolUseFailure hook events. Called when a tool execution fails.
UserPromptSubmitHookInput
Input data for UserPromptSubmit hook events.
StopHookInput
Input data for Stop hook events.
SubagentStopHookInput
Input data for SubagentStop hook events.
PreCompactHookInput
Input data for PreCompact hook events.
NotificationHookInput
Input data for Notification hook events.
SubagentStartHookInput
Input data for SubagentStart hook events.
PermissionRequestHookInput
Input data for PermissionRequest hook events. Allows hooks to handle permission decisions programmatically.
HookJSONOutput
Union type for hook callback return values.
SyncHookJSONOutput
Synchronous hook output with control and decision fields.
Use
continue_ (with underscore) in Python code. It is automatically converted to continue when sent to the CLI.HookSpecificOutput
A TypedDict containing the hook event name and event-specific fields. The shape depends on the hookEventName value. For full details on available fields per hook event, see Control execution with hooks.
A discriminated union of event-specific output types. The hookEventName field determines which fields are valid.
AsyncHookJSONOutput
Async hook output that defers hook execution.
Use
async_ (with underscore) in Python code. It is automatically converted to async when sent to the CLI.Hook Usage Example
This example registers two hooks: one that blocks dangerous bash commands likerm -rf /, and another that logs all tool usage for auditing. The security hook only runs on Bash commands (via the matcher), while the logging hook runs on all tools.
Tool Input/Output Types
Documentation of input/output schemas for all built-in Claude Code tools. While the Python SDK doesn’t export these as types, they represent the structure of tool inputs and outputs in messages.Agent
Tool name:Agent. The previous name Task is still accepted as an alias, and the tools list in the init SystemMessage reports this tool as Task for backward compatibility.
Input:
"completed"):
"async_launched"):
"remote_launched"):
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. Worktree-isolated runs include worktreePath and worktreeBranch on the completed variant.
On the completed variant, resolvedModel names the model the subagent started on, which can differ from the requested model input when availableModels or another override applies. This field requires Claude Code v2.1.174 or later. On the async_launched variant, resolvedModel names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The modelsUsed field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. modelsUsed and the backgrounding-time resolvedModel behavior require Claude Code v2.1.212 or later.
AskUserQuestion
Tool name:AskUserQuestion
Asks the user clarifying questions during execution. See Handle approvals and user input for usage details.
Input:
Bash
Tool name:Bash
Input:
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.
When Monitor runs a command, it follows the same permission rules as Bash; a WebSocket watch prompts for approval separately. The ws source requires Claude Code v2.1.195 or later. See the Monitor tool reference for behavior and provider availability.
Input:
Edit
Tool name:Edit
Input:
Read
Tool name:Read
Input:
Write
Tool name:Write
Input:
Glob
Tool name:Glob
Input:
Grep
Tool name:Grep
Input:
NotebookEdit
Tool name:NotebookEdit
Input:
WebFetch
Tool name:WebFetch
Input:
WebSearch
Tool name:WebSearch
Input:
TodoWrite
Tool name:TodoWrite
As of Claude Code v2.1.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
Input:
TaskUpdate
Tool name:TaskUpdate
Input:
TaskGet
Tool name:TaskGet
Input:
TaskList
Tool name:TaskList
Input:
TaskOutput
Tool name:TaskOutput. The previous name BashOutput is still accepted as an alias.
TaskOutput is deprecated; prefer Read on the task’s output file path. Deprecated since Claude Code v2.1.83. The schemas below remain valid for hooks and permission handlers that encounter the tool.TaskStop
Tool name:TaskStop. The previous names KillShell and KillBash are still accepted as aliases.
Input:
ExitPlanMode
Tool name:ExitPlanMode
Input:
ListMcpResources
Tool name:ListMcpResourcesTool
Input:
ReadMcpResource
Tool name:ReadMcpResourceTool
Input:
Advanced Features with ClaudeSDKClient
Building a Continuous Conversation Interface
Using Hooks for Behavior Modification
Real-time Progress Monitoring
Example Usage
Basic file operations (using query)
Error handling
Streaming mode with client
Using custom tools with ClaudeSDKClient
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. By default, when enabled is True but the sandbox can’t start, commands run unsandboxed with a warning on stderr. This default differs from the TypeScript SDK, where failIfUnavailable defaults to true.Set "failIfUnavailable": True in your sandbox settings to stop instead. The key isn’t declared on SandboxSettings yet, but the SDK forwards it to Claude Code, which honors it. query() then reports a ResultMessage with subtype="error_during_execution" and the reason in errors. Because this is a single-shot query() call, the SDK raises 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.Example usage
SandboxNetworkConfig
Network-specific configuration for sandbox mode. These settings apply to sandboxed Bash commands when enabled is True in the parent SandboxSettings. They do not restrict the WebFetch tool, which uses permission rules instead.
The built-in sandbox proxy enforces the network allowlist 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.
SandboxIgnoreViolations
Configuration for ignoring specific sandbox violations.
Permissions Fallback for Unsandboxed Commands
WhenallowUnsandboxedCommands is enabled, the model can request to run commands outside the sandbox by setting dangerouslyDisableSandbox: True in the tool input. These requests fall back to the existing permissions system, meaning your can_use_tool 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 settingdangerouslyDisableSandbox: Truein the tool input.
- 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
See also
- SDK overview - General SDK concepts
- TypeScript SDK reference - TypeScript SDK documentation
- CLI reference - Command-line interface
- Common workflows - Step-by-step guides