Functions
query()
The primary async function for interacting with Claude Code. Returns an async iterator that yields messages as they arrive.
Parameters
Parameter | Type | Description |
---|---|---|
prompt | str | AsyncIterable[dict] | The input prompt as a string or async iterable for streaming mode |
options | ClaudeCodeOptions | None | Optional configuration object (defaults to ClaudeCodeOptions() if None) |
Returns
Returns anAsyncIterator[Message]
that yields messages from the conversation.
Example - Simple query
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 ClaudeCodeOptions.mcp_servers
.
Example
Classes
ClaudeSDKClient
Client for bidirectional, interactive conversations with Claude Code. Provides full control over conversation flow with support for streaming, interrupts, and dynamic message sending.
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 - Interactive conversation
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 |
ClaudeCodeOptions
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 |
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 |
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:
Example Usage
Basic file operations
Error handling
Streaming mode with client
Using custom tools
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