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:
Use
ClaudeSDKClient for interactive applications such as chat interfaces, or when the next action depends on Claude’s response.
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. See the comparison with query().
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.