Python SDK for Claude Code providing simple query functions and advanced bidirectional interactive conversations with custom tool support
npx @tessl/cli install tessl/pypi-claude-code-sdk@0.0.00
# Claude Code SDK
1
2
Python SDK for Claude Code providing comprehensive integration with Claude AI capabilities through both simple query functions and advanced bidirectional interactive conversations. The SDK supports custom tools implemented as in-process MCP servers that run directly within Python applications, eliminating the need for separate processes while providing better performance and easier debugging.
3
4
## Package Information
5
6
- **Package Name**: claude-code-sdk
7
- **Language**: Python
8
- **Python Version**: 3.10+
9
- **Installation**: `pip install claude-code-sdk`
10
11
## Core Imports
12
13
```python
14
from claude_code_sdk import query
15
```
16
17
For interactive conversations with custom tools and hooks:
18
19
```python
20
from claude_code_sdk import ClaudeSDKClient, ClaudeCodeOptions
21
```
22
23
For creating custom tools:
24
25
```python
26
from claude_code_sdk import tool, create_sdk_mcp_server, SdkMcpTool
27
```
28
29
For type safety:
30
31
```python
32
from claude_code_sdk import (
33
AssistantMessage, UserMessage, SystemMessage, ResultMessage,
34
TextBlock, ToolUseBlock, ToolResultBlock,
35
PermissionMode, McpServerConfig
36
)
37
```
38
39
## Basic Usage
40
41
```python
42
import anyio
43
from claude_code_sdk import query
44
45
async def main():
46
# Simple one-shot query
47
async for message in query(prompt="What is 2 + 2?"):
48
print(message)
49
50
anyio.run(main)
51
```
52
53
With options and tool usage:
54
55
```python
56
from claude_code_sdk import query, ClaudeCodeOptions, AssistantMessage, TextBlock
57
58
async def main():
59
options = ClaudeCodeOptions(
60
allowed_tools=["Read", "Write", "Bash"],
61
permission_mode='acceptEdits', # auto-accept file edits
62
cwd="/path/to/project"
63
)
64
65
async for message in query(
66
prompt="Create a hello.py file",
67
options=options
68
):
69
if isinstance(message, AssistantMessage):
70
for block in message.content:
71
if isinstance(block, TextBlock):
72
print(block.text)
73
74
anyio.run(main)
75
```
76
77
## Architecture
78
79
The Claude Code SDK is built around two main interaction patterns:
80
81
- **Unidirectional Communication**: The `query()` function for simple, stateless interactions where all inputs are known upfront
82
- **Bidirectional Communication**: The `ClaudeSDKClient` class for interactive, stateful conversations with full control over message flow
83
84
**Key Components:**
85
- **Transport Layer**: Abstracts communication with Claude Code CLI through subprocess, network, or custom implementations
86
- **Message System**: Structured message types (User, Assistant, System, Result, Stream) with rich content blocks
87
- **Permission System**: Fine-grained control over tool execution with callbacks and permission modes
88
- **MCP Integration**: Support for both external MCP servers and in-process SDK MCP servers
89
- **Hook System**: Python functions that execute at specific points in the Claude agent loop for deterministic processing
90
91
## Capabilities
92
93
### Simple Queries
94
95
Unidirectional query interface for one-shot interactions with Claude Code. Ideal for simple questions, batch processing, code generation, and automated scripts where all inputs are known upfront.
96
97
```python { .api }
98
async def query(
99
*,
100
prompt: str | AsyncIterable[dict[str, Any]],
101
options: ClaudeCodeOptions | None = None,
102
transport: Transport | None = None,
103
) -> AsyncIterator[Message]:
104
```
105
106
[Simple Queries](./simple-queries.md)
107
108
### Interactive Client
109
110
Bidirectional client for interactive, stateful conversations with Claude Code. Provides full control over conversation flow with support for streaming, interrupts, dynamic message sending, custom tools, and hooks.
111
112
```python { .api }
113
class ClaudeSDKClient:
114
def __init__(self, options: ClaudeCodeOptions | None = None): ...
115
async def connect(self, prompt: str | AsyncIterable[dict[str, Any]] | None = None) -> None: ...
116
async def receive_messages(self) -> AsyncIterator[Message]: ...
117
async def query(self, prompt: str | AsyncIterable[dict[str, Any]], session_id: str = "default") -> None: ...
118
async def interrupt(self) -> None: ...
119
async def receive_response(self) -> AsyncIterator[Message]: ...
120
async def disconnect(self) -> None: ...
121
async def __aenter__(self) -> "ClaudeSDKClient": ...
122
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool: ...
123
```
124
125
[Interactive Client](./interactive-client.md)
126
127
### Custom Tools
128
129
In-process MCP tools that run directly within your Python application. Create custom tools that Claude can invoke, with better performance than external MCP servers, simpler deployment, and direct access to your application's state.
130
131
```python { .api }
132
def tool(
133
name: str,
134
description: str,
135
input_schema: type | dict[str, Any]
136
) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]: ...
137
138
def create_sdk_mcp_server(
139
name: str,
140
version: str = "1.0.0",
141
tools: list[SdkMcpTool[Any]] | None = None
142
) -> McpSdkServerConfig: ...
143
```
144
145
[Custom Tools](./custom-tools.md)
146
147
### Configuration and Options
148
149
Comprehensive configuration system for controlling Claude Code behavior including tool permissions, working directory, system prompts, MCP server configurations, and advanced features.
150
151
```python { .api }
152
@dataclass
153
class ClaudeCodeOptions:
154
allowed_tools: list[str] = field(default_factory=list)
155
system_prompt: str | None = None
156
permission_mode: PermissionMode | None = None
157
cwd: str | Path | None = None
158
mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
159
can_use_tool: CanUseTool | None = None
160
hooks: dict[HookEvent, list[HookMatcher]] | None = None
161
# ... additional fields
162
```
163
164
[Configuration and Options](./configuration-options.md)
165
166
### Hook System
167
168
Python functions that the Claude Code application invokes at specific points of the Claude agent loop. Hooks provide deterministic processing and automated feedback for Claude, enabling custom validation, permission checks, and automated responses.
169
170
```python { .api }
171
@dataclass
172
class HookMatcher:
173
matcher: str | None = None
174
hooks: list[HookCallback] = field(default_factory=list)
175
176
HookCallback = Callable[
177
[dict[str, Any], str | None, HookContext],
178
Awaitable[HookJSONOutput]
179
]
180
```
181
182
[Hook System](./hook-system.md)
183
184
### Message Types and Content
185
186
Rich message system with structured content blocks supporting text, tool usage, tool results, thinking blocks, and streaming events. Includes complete type definitions for all message and content types.
187
188
```python { .api }
189
Message = UserMessage | AssistantMessage | SystemMessage | ResultMessage | StreamEvent
190
ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
191
192
@dataclass
193
class AssistantMessage:
194
content: list[ContentBlock]
195
model: str
196
parent_tool_use_id: str | None = None
197
```
198
199
[Message Types and Content](./message-types.md)
200
201
### Transport System
202
203
Abstract transport interface for custom Claude Code communication implementations. Enables custom transport implementations for remote Claude Code connections or alternative communication methods.
204
205
```python { .api }
206
class Transport(ABC):
207
@abstractmethod
208
async def connect(self) -> None: ...
209
@abstractmethod
210
async def write(self, data: str) -> None: ...
211
@abstractmethod
212
def read_messages(self) -> AsyncIterator[dict[str, Any]]: ...
213
# ... additional abstract methods
214
```
215
216
[Transport System](./transport-system.md)
217
218
### Error Handling
219
220
Comprehensive error handling with specific exception types for different failure modes. Includes connection errors, process failures, JSON parsing issues, and message parsing errors.
221
222
```python { .api }
223
class ClaudeSDKError(Exception): ...
224
class CLIConnectionError(ClaudeSDKError): ...
225
class CLINotFoundError(CLIConnectionError): ...
226
class ProcessError(ClaudeSDKError): ...
227
class CLIJSONDecodeError(ClaudeSDKError): ...
228
```
229
230
[Error Handling](./error-handling.md)
231
232
## Constants
233
234
```python { .api }
235
__version__: str # "0.0.23"
236
```