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, 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. After the abort, Automatic retries covers what Claude Code does, based on how far the response had progressed.
OutputFormat
Configuration for structured output validation. Pass this as a dict to the output_format field on ClaudeAgentOptions: