Overview
TheClaudeSDKClient provides full control over the conversation flow with support for streaming, interrupts, and dynamic message sending. For simple one-shot queries, consider using the query() function instead.
Key Features
- Bidirectional: Send and receive messages at any time
- Stateful: Maintains conversation context across messages
- Interactive: Send follow-ups based on responses
- Control flow: Support for interrupts and session management
When to Use ClaudeSDKClient
- Building chat interfaces or conversational UIs
- Interactive debugging or exploration sessions
- Multi-turn conversations with context
- When you need to react to Claude’s responses
- Real-time applications with user input
- When you need interrupt capabilities
When to Use query() Instead
- Simple one-off questions
- Batch processing of prompts
- Fire-and-forget automation scripts
- When all inputs are known upfront
- Stateless operations
Async Context Limitation: As of v0.0.20, you cannot use a ClaudeSDKClient instance across different async runtime contexts (e.g., different trio nurseries or asyncio task groups). The client internally maintains a persistent anyio task group for reading messages that remains active from
connect() until disconnect(). Complete all operations with the client within the same async context where it was connected.Constructor
Parameters
Optional configuration (defaults to
ClaudeAgentOptions() if None).Key options:- permission_mode: Control tool execution
- cwd: Working directory
- system_prompt: Custom system prompt
- mcp_servers: MCP server configurations
- can_use_tool: Callback for tool permission control
- hooks: Event hooks for custom behavior
- enable_file_checkpointing: Enable file state tracking
Optional custom transport implementation. If None, uses default subprocess transport.
Methods
connect()
Connect to Claude with a prompt or message stream.Initial prompt or message stream. If None, connects without sending any messages (for interactive use).
query()
Send a new request in streaming mode.Either a string message or an async iterable of message dictionaries.
Session identifier for the conversation.
receive_messages()
Receive all messages from Claude as they arrive.receive_response()
Receive messages until and including a ResultMessage.ResultMessage.
Stopping Behavior:
- Yields each message as it’s received
- Terminates immediately after yielding a ResultMessage
- The ResultMessage IS included in the yielded messages
- If no ResultMessage is received, the iterator continues indefinitely
interrupt()
Send interrupt signal to stop the current operation.set_permission_mode()
Change permission mode during conversation.The permission mode to set:
'default': CLI prompts for dangerous tools'acceptEdits': Auto-accept file edits'bypassPermissions': Allow all tools (use with caution)
set_model()
Change the AI model during conversation.The model to use, or None for default. Examples:
'claude-sonnet-4-5''claude-opus-4-1-20250805''claude-opus-4-20250514'
rewind_files()
Rewind tracked files to their state at a specific user message.UUID of the user message to rewind to. This should be the
uuid field from a UserMessage received during the conversation.enable_file_checkpointing=Trueto track file changesextra_args={"replay-user-messages": None}to receive UserMessage objects withuuid
get_mcp_status()
Get current MCP server connection status.McpStatusResponse dictionary with:
mcpServers: List of server status entries
name: Server name (str)status: Connection status ('connected','pending','failed','needs-auth','disabled')serverInfo: MCP server name/version (when connected)error: Error message (when status is'failed')config: Server configurationscope: Configuration scopetools: List of tools provided (when connected)
reconnect_mcp_server()
Reconnect a disconnected or failed MCP server.The name of the MCP server to reconnect.
toggle_mcp_server()
Enable or disable an MCP server.The name of the MCP server to toggle.
True to enable the server, False to disable it.
stop_task()
Stop a running task.The task ID from
task_notification events.task_notification system message with status 'stopped' will be emitted.
Example:
get_server_info()
Get server initialization info including available commands and output styles.- Available commands (slash commands, system commands, etc.)
- Current and available output styles
- Server capabilities
disconnect()
Disconnect from Claude.Context Manager Support
The client supports async context manager protocol for automatic connection/disconnection:Complete Example
Related
- query() - For simple one-shot queries
- ClaudeAgentOptions - Configuration options
- Message Types - Available message types
- Transport - Custom transport implementations