Skip to main content

Overview

The ClaudeSDKClient 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

options
ClaudeAgentOptions | None
default:"None"
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
transport
Transport | None
default:"None"
Optional custom transport implementation. If None, uses default subprocess transport.

Methods

connect()

Connect to Claude with a prompt or message stream.
prompt
str | AsyncIterable[dict[str, Any]] | None
default:"None"
Initial prompt or message stream. If None, connects without sending any messages (for interactive use).
Example:

query()

Send a new request in streaming mode.
prompt
str | AsyncIterable[dict[str, Any]]
required
Either a string message or an async iterable of message dictionaries.
session_id
str
default:"default"
Session identifier for the conversation.
Example:

receive_messages()

Receive all messages from Claude as they arrive.
Returns: AsyncIterator yielding messages indefinitely until disconnect. Example:

receive_response()

Receive messages until and including a ResultMessage.
Returns: AsyncIterator that automatically terminates after yielding a 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
Example:

interrupt()

Send interrupt signal to stop the current operation.
Example:

set_permission_mode()

Change permission mode during conversation.
mode
str
required
The permission mode to set:
  • 'default': CLI prompts for dangerous tools
  • 'acceptEdits': Auto-accept file edits
  • 'bypassPermissions': Allow all tools (use with caution)
Example:

set_model()

Change the AI model during conversation.
model
str | None
default:"None"
The model to use, or None for default. Examples:
  • 'claude-sonnet-4-5'
  • 'claude-opus-4-1-20250805'
  • 'claude-opus-4-20250514'
Example:

rewind_files()

Rewind tracked files to their state at a specific user message.
user_message_id
str
required
UUID of the user message to rewind to. This should be the uuid field from a UserMessage received during the conversation.
Requirements:
  • enable_file_checkpointing=True to track file changes
  • extra_args={"replay-user-messages": None} to receive UserMessage objects with uuid
Example:

get_mcp_status()

Get current MCP server connection status.
Returns: McpStatusResponse dictionary with:
  • mcpServers: List of server status entries
Each server status includes:
  • 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 configuration
  • scope: Configuration scope
  • tools: List of tools provided (when connected)
Example:

reconnect_mcp_server()

Reconnect a disconnected or failed MCP server.
server_name
str
required
The name of the MCP server to reconnect.
Example:

toggle_mcp_server()

Enable or disable an MCP server.
server_name
str
required
The name of the MCP server to toggle.
enabled
bool
required
True to enable the server, False to disable it.
Example:

stop_task()

Stop a running task.
task_id
str
required
The task ID from task_notification events.
After this resolves, a task_notification system message with status 'stopped' will be emitted. Example:

get_server_info()

Get server initialization info including available commands and output styles.
Returns: Dictionary with server info, or None if not in streaming mode. Includes:
  • Available commands (slash commands, system commands, etc.)
  • Current and available output styles
  • Server capabilities
Example:

disconnect()

Disconnect from Claude.
Example:

Context Manager Support

The client supports async context manager protocol for automatic connection/disconnection:

Complete Example