Installation
Choosing Between query()
and ClaudeSDKClient
The Python SDK provides two ways to interact with Claude Code:
Quick Comparison
Feature | query() | ClaudeSDKClient |
---|---|---|
Session | Creates new session each time | Reuses same session |
Conversation | Single exchange | Multiple exchanges in same context |
Connection | Managed automatically | Manual control |
Streaming Input | ✅ Supported | ✅ Supported |
Interrupts | ❌ Not supported | ✅ Supported |
Hooks | ❌ Not supported | ✅ Supported |
Custom Tools | ❌ Not supported | ✅ Supported |
Continue Chat | ❌ New session each time | ✅ Maintains conversation |
Use Case | One-off tasks | Continuous conversations |
When to Use query()
(New Session Each Time)
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
query()
Creates a new session for each interaction with Claude Code. Returns an async iterator that yields messages as they arrive. Each call to query()
starts fresh with no memory of previous interactions.
Parameters
Parameter | Type | Description |
---|---|---|
prompt | str | AsyncIterable[dict] | The input prompt as a string or async iterable for streaming mode |
options | ClaudeAgentOptions | None | Optional configuration object (defaults to ClaudeAgentOptions() if None) |
Returns
Returns anAsyncIterator[Message]
that yields messages from the conversation.
Example - With options
tool()
Decorator for defining MCP tools with type safety.
Parameters
Parameter | Type | Description |
---|---|---|
name | str | Unique identifier for the tool |
description | str | Human-readable description of what the tool does |
input_schema | type | dict[str, Any] | Schema defining the tool’s input parameters (see below) |
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
create_sdk_mcp_server()
Create an in-process MCP server that runs within your Python application.
Parameters
Parameter | Type | Default | Description |
---|---|---|---|
name | str | - | Unique identifier for the server |
version | str | "1.0.0" | Server version string |
tools | list[SdkMcpTool[Any]] | None | None | List of tool functions created with @tool decorator |
Returns
Returns anMcpSdkServerConfig
object that can be passed to ClaudeAgentOptions.mcp_servers
.
Example
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: Claude remembers previous messages in the session
- Interrupt Support: Can stop Claude mid-execution
- Explicit Lifecycle: You control when the session starts and ends
- Response-driven Flow: Can react to responses and send follow-ups
- Custom Tools & Hooks: Supports custom tools (created with
@tool
decorator) and hooks
Methods
Method | Description |
---|---|
__init__(options) | Initialize the client with optional configuration |
connect(prompt) | Connect to Claude with an optional initial prompt or message stream |
query(prompt, session_id) | Send a new request in streaming mode |
receive_messages() | Receive all messages from Claude as an async iterator |
receive_response() | Receive messages until and including a ResultMessage |
interrupt() | Send interrupt signal (only works in streaming mode) |
disconnect() | Disconnect from Claude |
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
Example - Advanced permission control
Types
SdkMcpTool
Definition for an SDK MCP tool created with the @tool
decorator.
Property | Type | Description |
---|---|---|
name | str | Unique identifier for the tool |
description | str | Human-readable description |
input_schema | type[T] | dict[str, Any] | Schema for input validation |
handler | Callable[[T], Awaitable[dict[str, Any]]] | Async function that handles tool execution |
ClaudeAgentOptions
Configuration dataclass for Claude Code queries.
Property | Type | Default | Description |
---|---|---|---|
allowed_tools | list[str] | [] | List of allowed tool names |
max_thinking_tokens | int | 8000 | Maximum tokens for thinking process |
system_prompt | str | None | None | Replace the default system prompt entirely |
append_system_prompt | str | None | None | Text to append to the default system prompt |
mcp_servers | dict[str, McpServerConfig] | str | Path | {} | MCP server configurations or path to config file |
permission_mode | PermissionMode | None | None | Permission mode for tool usage |
continue_conversation | bool | False | Continue the most recent conversation |
resume | str | None | None | Session ID to resume |
fork_session | bool | False | When resuming with resume , fork to a new session ID instead of continuing the original session |
max_turns | int | None | None | Maximum conversation turns |
disallowed_tools | list[str] | [] | List of disallowed tool names |
model | str | None | None | Claude model to use |
permission_prompt_tool_name | str | None | None | MCP tool name for permission prompts |
cwd | str | Path | None | None | Current working directory |
settings | str | None | None | Path to settings file |
add_dirs | list[str | Path] | [] | Additional directories Claude can access |
extra_args | dict[str, str | None] | {} | Additional CLI arguments to pass directly to the CLI |
can_use_tool | CanUseTool | None | None | Tool permission callback function |
hooks | dict[HookEvent, list[HookMatcher]] | None | None | Hook configurations for intercepting events |
agents | dict[str, AgentDefinition] | None | None | Programmatically defined subagents |
setting_sources | list[SettingSource] | None | None (no settings) | Control which filesystem settings to load. When omitted, no settings are loaded |
SettingSource
Controls which filesystem-based configuration sources the SDK loads settings from.
Value | Description | Location |
---|---|---|
"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
Whensetting_sources
is omitted or None
, the SDK does not load any filesystem settings. This provides isolation for SDK applications.
Why use setting_sources?
Load all filesystem settings (legacy behavior):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
, allowed_tools
) always override filesystem settings.
AgentDefinition
Configuration for a subagent defined programmatically.
Field | Required | Description |
---|---|---|
description | Yes | Natural language description of when to use this agent |
tools | No | Array of allowed tool names. If omitted, inherits all tools |
prompt | Yes | The agent’s system prompt |
model | No | Model override for this agent. If omitted, uses the main model |
PermissionMode
Permission modes for controlling tool execution.
McpSdkServerConfig
Configuration for SDK MCP servers created with create_sdk_mcp_server()
.
McpServerConfig
Union type for MCP server configurations.
McpStdioServerConfig
McpSSEServerConfig
McpHttpServerConfig
Message Types
Message
Union type of all possible messages.
UserMessage
User input message.
AssistantMessage
Assistant response message with content blocks.
SystemMessage
System message with metadata.
ResultMessage
Final result message with cost and usage information.
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
HookEvent
Supported hook event types. Note that due to setup limitations, the Python SDK does not support SessionStart, SessionEnd, and Notification hooks.
HookCallback
Type definition for hook callback functions.
input_data
: Hook-specific input data (see hook documentation)tool_use_id
: Optional tool use identifier (for tool-related hooks)context
: Hook context with additional information
decision
:"block"
to block the actionsystemMessage
: System message to add to the transcripthookSpecificOutput
: Hook-specific output data
HookContext
Context information passed to hook callbacks.
HookMatcher
Configuration for matching hooks to specific events or tools.
Hook Usage Example
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.Task
Tool name:Task
Input:
Bash
Tool name:Bash
Input:
Edit
Tool name:Edit
Input:
MultiEdit
Tool name:MultiEdit
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
Input:
BashOutput
Tool name:BashOutput
Input:
KillBash
Tool name:KillBash
Input:
ExitPlanMode
Tool name:ExitPlanMode
Input:
ListMcpResources
Tool name:ListMcpResources
Input:
ReadMcpResource
Tool name:ReadMcpResource
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
See also
- Python SDK guide - Tutorial and examples
- SDK overview - General SDK concepts
- TypeScript SDK reference - TypeScript SDK documentation
- CLI reference - Command-line interface
- Common workflows - Step-by-step guides