Skip to main content

Installation

Install the package into a virtual environment. On recent Debian, Ubuntu, and Homebrew Python installs, running pip install against system Python fails with error: externally-managed-environment.
For uv, Windows PowerShell, and API key setup, see Setup in the Agent SDK quickstart.

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 an AsyncIterator[Message] that yields messages from the conversation.

Example - With options

tool()

Decorator for defining MCP tools with type safety.

Parameters

Input schema options

  1. Simple type mapping (recommended):
  2. JSON Schema format (for complex validation):

Returns

A decorator function that wraps the tool implementation and returns an SdkMcpTool 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 an McpSdkServerConfig 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 by last_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 in SDKSessionInfo.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. Pass None 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 @tool decorator) 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).
This is a low-level internal API. The interface may change in future releases. Custom implementations must be updated to match any interface changes.
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 through ClaudeAgentOptions.env:
  • API_TIMEOUT_MS: per-request timeout on the Anthropic client, in milliseconds. Default 600000. Applies to the main loop and all subagents.
  • CLAUDE_CODE_MAX_RETRIES: maximum API retries. Default 10, capped at 15. Each retry gets its own API_TIMEOUT_MS window, so worst-case wall time is roughly API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1) plus backoff. For unattended runs that need to wait through longer outages, set CLAUDE_CODE_RETRY_WATCHDOG=1: it retries capacity errors indefinitely, and as of Claude Code v2.1.199 raises the default for other transient errors to 300 and removes the cap on this variable.
  • CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS: stall watchdog for subagents launched with run_in_background. Default 600000. 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_WATCHDOG with CLAUDE_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; set CLAUDE_ENABLE_STREAM_WATCHDOG=0 to disable it. CLAUDE_STREAM_IDLE_TIMEOUT_MS defaults to 300000 and 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: