claude-agent-sdk 0.0.23__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of claude-agent-sdk might be problematic. Click here for more details.
- claude_agent_sdk/__init__.py +325 -0
- claude_agent_sdk/_errors.py +56 -0
- claude_agent_sdk/_internal/__init__.py +1 -0
- claude_agent_sdk/_internal/client.py +121 -0
- claude_agent_sdk/_internal/message_parser.py +172 -0
- claude_agent_sdk/_internal/query.py +523 -0
- claude_agent_sdk/_internal/transport/__init__.py +68 -0
- claude_agent_sdk/_internal/transport/subprocess_cli.py +456 -0
- claude_agent_sdk/_version.py +3 -0
- claude_agent_sdk/client.py +325 -0
- claude_agent_sdk/py.typed +0 -0
- claude_agent_sdk/query.py +126 -0
- claude_agent_sdk/types.py +412 -0
- claude_agent_sdk-0.0.23.dist-info/METADATA +309 -0
- claude_agent_sdk-0.0.23.dist-info/RECORD +17 -0
- claude_agent_sdk-0.0.23.dist-info/WHEEL +4 -0
- claude_agent_sdk-0.0.23.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"""Type definitions for Claude SDK."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from collections.abc import Awaitable, Callable
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Literal, TypedDict
|
|
8
|
+
|
|
9
|
+
from typing_extensions import NotRequired
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from mcp.server import Server as McpServer
|
|
13
|
+
|
|
14
|
+
# Permission modes
|
|
15
|
+
PermissionMode = Literal["default", "acceptEdits", "plan", "bypassPermissions"]
|
|
16
|
+
|
|
17
|
+
# Agent definitions
|
|
18
|
+
SettingSource = Literal["user", "project", "local"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SystemPromptPreset(TypedDict):
|
|
22
|
+
"""System prompt preset configuration."""
|
|
23
|
+
|
|
24
|
+
type: Literal["preset"]
|
|
25
|
+
preset: Literal["claude_code"]
|
|
26
|
+
append: NotRequired[str]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class AgentDefinition:
|
|
31
|
+
"""Agent definition configuration."""
|
|
32
|
+
|
|
33
|
+
description: str
|
|
34
|
+
prompt: str
|
|
35
|
+
tools: list[str] | None = None
|
|
36
|
+
model: Literal["sonnet", "opus", "haiku", "inherit"] | None = None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# Permission Update types (matching TypeScript SDK)
|
|
40
|
+
PermissionUpdateDestination = Literal[
|
|
41
|
+
"userSettings", "projectSettings", "localSettings", "session"
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
PermissionBehavior = Literal["allow", "deny", "ask"]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class PermissionRuleValue:
|
|
49
|
+
"""Permission rule value."""
|
|
50
|
+
|
|
51
|
+
tool_name: str
|
|
52
|
+
rule_content: str | None = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class PermissionUpdate:
|
|
57
|
+
"""Permission update configuration."""
|
|
58
|
+
|
|
59
|
+
type: Literal[
|
|
60
|
+
"addRules",
|
|
61
|
+
"replaceRules",
|
|
62
|
+
"removeRules",
|
|
63
|
+
"setMode",
|
|
64
|
+
"addDirectories",
|
|
65
|
+
"removeDirectories",
|
|
66
|
+
]
|
|
67
|
+
rules: list[PermissionRuleValue] | None = None
|
|
68
|
+
behavior: PermissionBehavior | None = None
|
|
69
|
+
mode: PermissionMode | None = None
|
|
70
|
+
directories: list[str] | None = None
|
|
71
|
+
destination: PermissionUpdateDestination | None = None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# Tool callback types
|
|
75
|
+
@dataclass
|
|
76
|
+
class ToolPermissionContext:
|
|
77
|
+
"""Context information for tool permission callbacks."""
|
|
78
|
+
|
|
79
|
+
signal: Any | None = None # Future: abort signal support
|
|
80
|
+
suggestions: list[PermissionUpdate] = field(
|
|
81
|
+
default_factory=list
|
|
82
|
+
) # Permission suggestions from CLI
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# Match TypeScript's PermissionResult structure
|
|
86
|
+
@dataclass
|
|
87
|
+
class PermissionResultAllow:
|
|
88
|
+
"""Allow permission result."""
|
|
89
|
+
|
|
90
|
+
behavior: Literal["allow"] = "allow"
|
|
91
|
+
updated_input: dict[str, Any] | None = None
|
|
92
|
+
updated_permissions: list[PermissionUpdate] | None = None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class PermissionResultDeny:
|
|
97
|
+
"""Deny permission result."""
|
|
98
|
+
|
|
99
|
+
behavior: Literal["deny"] = "deny"
|
|
100
|
+
message: str = ""
|
|
101
|
+
interrupt: bool = False
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
PermissionResult = PermissionResultAllow | PermissionResultDeny
|
|
105
|
+
|
|
106
|
+
CanUseTool = Callable[
|
|
107
|
+
[str, dict[str, Any], ToolPermissionContext], Awaitable[PermissionResult]
|
|
108
|
+
]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
##### Hook types
|
|
112
|
+
# Supported hook event types. Due to setup limitations, the Python SDK does not
|
|
113
|
+
# support SessionStart, SessionEnd, and Notification hooks.
|
|
114
|
+
HookEvent = (
|
|
115
|
+
Literal["PreToolUse"]
|
|
116
|
+
| Literal["PostToolUse"]
|
|
117
|
+
| Literal["UserPromptSubmit"]
|
|
118
|
+
| Literal["Stop"]
|
|
119
|
+
| Literal["SubagentStop"]
|
|
120
|
+
| Literal["PreCompact"]
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# See https://docs.anthropic.com/en/docs/claude-code/hooks#advanced%3A-json-output
|
|
125
|
+
# for documentation of the output types. Currently, "continue", "stopReason",
|
|
126
|
+
# and "suppressOutput" are not supported in the Python SDK.
|
|
127
|
+
class HookJSONOutput(TypedDict):
|
|
128
|
+
# Whether to block the action related to the hook.
|
|
129
|
+
decision: NotRequired[Literal["block"]]
|
|
130
|
+
# Optionally add a system message that is not visible to Claude but saved in
|
|
131
|
+
# the chat transcript.
|
|
132
|
+
systemMessage: NotRequired[str]
|
|
133
|
+
# See each hook's individual "Decision Control" section in the documentation
|
|
134
|
+
# for guidance.
|
|
135
|
+
hookSpecificOutput: NotRequired[Any]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass
|
|
139
|
+
class HookContext:
|
|
140
|
+
"""Context information for hook callbacks."""
|
|
141
|
+
|
|
142
|
+
signal: Any | None = None # Future: abort signal support
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
HookCallback = Callable[
|
|
146
|
+
# HookCallback input parameters:
|
|
147
|
+
# - input
|
|
148
|
+
# See https://docs.anthropic.com/en/docs/claude-code/hooks#hook-input for
|
|
149
|
+
# the type of 'input', the first value.
|
|
150
|
+
# - tool_use_id
|
|
151
|
+
# - context
|
|
152
|
+
[dict[str, Any], str | None, HookContext],
|
|
153
|
+
Awaitable[HookJSONOutput],
|
|
154
|
+
]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# Hook matcher configuration
|
|
158
|
+
@dataclass
|
|
159
|
+
class HookMatcher:
|
|
160
|
+
"""Hook matcher configuration."""
|
|
161
|
+
|
|
162
|
+
# See https://docs.anthropic.com/en/docs/claude-code/hooks#structure for the
|
|
163
|
+
# expected string value. For example, for PreToolUse, the matcher can be
|
|
164
|
+
# a tool name like "Bash" or a combination of tool names like
|
|
165
|
+
# "Write|MultiEdit|Edit".
|
|
166
|
+
matcher: str | None = None
|
|
167
|
+
|
|
168
|
+
# A list of Python functions with function signature HookCallback
|
|
169
|
+
hooks: list[HookCallback] = field(default_factory=list)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# MCP Server config
|
|
173
|
+
class McpStdioServerConfig(TypedDict):
|
|
174
|
+
"""MCP stdio server configuration."""
|
|
175
|
+
|
|
176
|
+
type: NotRequired[Literal["stdio"]] # Optional for backwards compatibility
|
|
177
|
+
command: str
|
|
178
|
+
args: NotRequired[list[str]]
|
|
179
|
+
env: NotRequired[dict[str, str]]
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class McpSSEServerConfig(TypedDict):
|
|
183
|
+
"""MCP SSE server configuration."""
|
|
184
|
+
|
|
185
|
+
type: Literal["sse"]
|
|
186
|
+
url: str
|
|
187
|
+
headers: NotRequired[dict[str, str]]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class McpHttpServerConfig(TypedDict):
|
|
191
|
+
"""MCP HTTP server configuration."""
|
|
192
|
+
|
|
193
|
+
type: Literal["http"]
|
|
194
|
+
url: str
|
|
195
|
+
headers: NotRequired[dict[str, str]]
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class McpSdkServerConfig(TypedDict):
|
|
199
|
+
"""SDK MCP server configuration."""
|
|
200
|
+
|
|
201
|
+
type: Literal["sdk"]
|
|
202
|
+
name: str
|
|
203
|
+
instance: "McpServer"
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
McpServerConfig = (
|
|
207
|
+
McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# Content block types
|
|
212
|
+
@dataclass
|
|
213
|
+
class TextBlock:
|
|
214
|
+
"""Text content block."""
|
|
215
|
+
|
|
216
|
+
text: str
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@dataclass
|
|
220
|
+
class ThinkingBlock:
|
|
221
|
+
"""Thinking content block."""
|
|
222
|
+
|
|
223
|
+
thinking: str
|
|
224
|
+
signature: str
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@dataclass
|
|
228
|
+
class ToolUseBlock:
|
|
229
|
+
"""Tool use content block."""
|
|
230
|
+
|
|
231
|
+
id: str
|
|
232
|
+
name: str
|
|
233
|
+
input: dict[str, Any]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@dataclass
|
|
237
|
+
class ToolResultBlock:
|
|
238
|
+
"""Tool result content block."""
|
|
239
|
+
|
|
240
|
+
tool_use_id: str
|
|
241
|
+
content: str | list[dict[str, Any]] | None = None
|
|
242
|
+
is_error: bool | None = None
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
# Message types
|
|
249
|
+
@dataclass
|
|
250
|
+
class UserMessage:
|
|
251
|
+
"""User message."""
|
|
252
|
+
|
|
253
|
+
content: str | list[ContentBlock]
|
|
254
|
+
parent_tool_use_id: str | None = None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
@dataclass
|
|
258
|
+
class AssistantMessage:
|
|
259
|
+
"""Assistant message with content blocks."""
|
|
260
|
+
|
|
261
|
+
content: list[ContentBlock]
|
|
262
|
+
model: str
|
|
263
|
+
parent_tool_use_id: str | None = None
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
@dataclass
|
|
267
|
+
class SystemMessage:
|
|
268
|
+
"""System message with metadata."""
|
|
269
|
+
|
|
270
|
+
subtype: str
|
|
271
|
+
data: dict[str, Any]
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@dataclass
|
|
275
|
+
class ResultMessage:
|
|
276
|
+
"""Result message with cost and usage information."""
|
|
277
|
+
|
|
278
|
+
subtype: str
|
|
279
|
+
duration_ms: int
|
|
280
|
+
duration_api_ms: int
|
|
281
|
+
is_error: bool
|
|
282
|
+
num_turns: int
|
|
283
|
+
session_id: str
|
|
284
|
+
total_cost_usd: float | None = None
|
|
285
|
+
usage: dict[str, Any] | None = None
|
|
286
|
+
result: str | None = None
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
@dataclass
|
|
290
|
+
class StreamEvent:
|
|
291
|
+
"""Stream event for partial message updates during streaming."""
|
|
292
|
+
|
|
293
|
+
uuid: str
|
|
294
|
+
session_id: str
|
|
295
|
+
event: dict[str, Any] # The raw Anthropic API stream event
|
|
296
|
+
parent_tool_use_id: str | None = None
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
Message = UserMessage | AssistantMessage | SystemMessage | ResultMessage | StreamEvent
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
@dataclass
|
|
303
|
+
class ClaudeAgentOptions:
|
|
304
|
+
"""Query options for Claude SDK."""
|
|
305
|
+
|
|
306
|
+
allowed_tools: list[str] = field(default_factory=list)
|
|
307
|
+
system_prompt: str | SystemPromptPreset | None = None
|
|
308
|
+
mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
|
|
309
|
+
permission_mode: PermissionMode | None = None
|
|
310
|
+
continue_conversation: bool = False
|
|
311
|
+
resume: str | None = None
|
|
312
|
+
max_turns: int | None = None
|
|
313
|
+
disallowed_tools: list[str] = field(default_factory=list)
|
|
314
|
+
model: str | None = None
|
|
315
|
+
permission_prompt_tool_name: str | None = None
|
|
316
|
+
cwd: str | Path | None = None
|
|
317
|
+
settings: str | None = None
|
|
318
|
+
add_dirs: list[str | Path] = field(default_factory=list)
|
|
319
|
+
env: dict[str, str] = field(default_factory=dict)
|
|
320
|
+
extra_args: dict[str, str | None] = field(
|
|
321
|
+
default_factory=dict
|
|
322
|
+
) # Pass arbitrary CLI flags
|
|
323
|
+
debug_stderr: Any = (
|
|
324
|
+
sys.stderr
|
|
325
|
+
) # Deprecated: File-like object for debug output. Use stderr callback instead.
|
|
326
|
+
stderr: Callable[[str], None] | None = None # Callback for stderr output from CLI
|
|
327
|
+
|
|
328
|
+
# Tool permission callback
|
|
329
|
+
can_use_tool: CanUseTool | None = None
|
|
330
|
+
|
|
331
|
+
# Hook configurations
|
|
332
|
+
hooks: dict[HookEvent, list[HookMatcher]] | None = None
|
|
333
|
+
|
|
334
|
+
user: str | None = None
|
|
335
|
+
|
|
336
|
+
# Partial message streaming support
|
|
337
|
+
include_partial_messages: bool = False
|
|
338
|
+
# When true resumed sessions will fork to a new session ID rather than
|
|
339
|
+
# continuing the previous session.
|
|
340
|
+
fork_session: bool = False
|
|
341
|
+
# Agent definitions for custom agents
|
|
342
|
+
agents: dict[str, AgentDefinition] | None = None
|
|
343
|
+
# Setting sources to load (user, project, local)
|
|
344
|
+
setting_sources: list[SettingSource] | None = None
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# SDK Control Protocol
|
|
348
|
+
class SDKControlInterruptRequest(TypedDict):
|
|
349
|
+
subtype: Literal["interrupt"]
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
class SDKControlPermissionRequest(TypedDict):
|
|
353
|
+
subtype: Literal["can_use_tool"]
|
|
354
|
+
tool_name: str
|
|
355
|
+
input: dict[str, Any]
|
|
356
|
+
# TODO: Add PermissionUpdate type here
|
|
357
|
+
permission_suggestions: list[Any] | None
|
|
358
|
+
blocked_path: str | None
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
class SDKControlInitializeRequest(TypedDict):
|
|
362
|
+
subtype: Literal["initialize"]
|
|
363
|
+
hooks: dict[HookEvent, Any] | None
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
class SDKControlSetPermissionModeRequest(TypedDict):
|
|
367
|
+
subtype: Literal["set_permission_mode"]
|
|
368
|
+
# TODO: Add PermissionMode
|
|
369
|
+
mode: str
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
class SDKHookCallbackRequest(TypedDict):
|
|
373
|
+
subtype: Literal["hook_callback"]
|
|
374
|
+
callback_id: str
|
|
375
|
+
input: Any
|
|
376
|
+
tool_use_id: str | None
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
class SDKControlMcpMessageRequest(TypedDict):
|
|
380
|
+
subtype: Literal["mcp_message"]
|
|
381
|
+
server_name: str
|
|
382
|
+
message: Any
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class SDKControlRequest(TypedDict):
|
|
386
|
+
type: Literal["control_request"]
|
|
387
|
+
request_id: str
|
|
388
|
+
request: (
|
|
389
|
+
SDKControlInterruptRequest
|
|
390
|
+
| SDKControlPermissionRequest
|
|
391
|
+
| SDKControlInitializeRequest
|
|
392
|
+
| SDKControlSetPermissionModeRequest
|
|
393
|
+
| SDKHookCallbackRequest
|
|
394
|
+
| SDKControlMcpMessageRequest
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
class ControlResponse(TypedDict):
|
|
399
|
+
subtype: Literal["success"]
|
|
400
|
+
request_id: str
|
|
401
|
+
response: dict[str, Any] | None
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
class ControlErrorResponse(TypedDict):
|
|
405
|
+
subtype: Literal["error"]
|
|
406
|
+
request_id: str
|
|
407
|
+
error: str
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
class SDKControlResponse(TypedDict):
|
|
411
|
+
type: Literal["control_response"]
|
|
412
|
+
response: ControlResponse | ControlErrorResponse
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: claude-agent-sdk
|
|
3
|
+
Version: 0.0.23
|
|
4
|
+
Summary: Python SDK for Claude Code
|
|
5
|
+
Project-URL: Homepage, https://github.com/anthropics/claude-agent-sdk-python
|
|
6
|
+
Project-URL: Documentation, https://docs.anthropic.com/en/docs/claude-code/sdk
|
|
7
|
+
Project-URL: Issues, https://github.com/anthropics/claude-agent-sdk-python/issues
|
|
8
|
+
Author-email: Anthropic <support@anthropic.com>
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: ai,anthropic,claude,sdk
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Requires-Dist: anyio>=4.0.0
|
|
23
|
+
Requires-Dist: mcp>=0.1.0
|
|
24
|
+
Requires-Dist: typing-extensions>=4.0.0; python_version < '3.11'
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: anyio[trio]>=4.0.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: mypy>=1.0.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest-asyncio>=0.20.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest>=7.0.0; extra == 'dev'
|
|
31
|
+
Requires-Dist: ruff>=0.1.0; extra == 'dev'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# Claude Agent SDK for Python
|
|
35
|
+
|
|
36
|
+
Python SDK for Claude Agent. See the [Claude Agent SDK documentation](https://docs.anthropic.com/en/docs/claude-code/sdk/sdk-python) for more information.
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install claude-agent-sdk
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
**Prerequisites:**
|
|
45
|
+
- Python 3.10+
|
|
46
|
+
- Node.js
|
|
47
|
+
- Claude Code: `npm install -g @anthropic-ai/claude-code`
|
|
48
|
+
|
|
49
|
+
## Quick Start
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import anyio
|
|
53
|
+
from claude_agent_sdk import query
|
|
54
|
+
|
|
55
|
+
async def main():
|
|
56
|
+
async for message in query(prompt="What is 2 + 2?"):
|
|
57
|
+
print(message)
|
|
58
|
+
|
|
59
|
+
anyio.run(main)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Basic Usage: query()
|
|
63
|
+
|
|
64
|
+
`query()` is an async function for querying Claude Code. It returns an `AsyncIterator` of response messages. See [src/claude_agent_sdk/query.py](src/claude_agent_sdk/query.py).
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock
|
|
68
|
+
|
|
69
|
+
# Simple query
|
|
70
|
+
async for message in query(prompt="Hello Claude"):
|
|
71
|
+
if isinstance(message, AssistantMessage):
|
|
72
|
+
for block in message.content:
|
|
73
|
+
if isinstance(block, TextBlock):
|
|
74
|
+
print(block.text)
|
|
75
|
+
|
|
76
|
+
# With options
|
|
77
|
+
options = ClaudeAgentOptions(
|
|
78
|
+
system_prompt="You are a helpful assistant",
|
|
79
|
+
max_turns=1
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
async for message in query(prompt="Tell me a joke", options=options):
|
|
83
|
+
print(message)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Using Tools
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
options = ClaudeAgentOptions(
|
|
90
|
+
allowed_tools=["Read", "Write", "Bash"],
|
|
91
|
+
permission_mode='acceptEdits' # auto-accept file edits
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
async for message in query(
|
|
95
|
+
prompt="Create a hello.py file",
|
|
96
|
+
options=options
|
|
97
|
+
):
|
|
98
|
+
# Process tool use and results
|
|
99
|
+
pass
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Working Directory
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from pathlib import Path
|
|
106
|
+
|
|
107
|
+
options = ClaudeAgentOptions(
|
|
108
|
+
cwd="/path/to/project" # or Path("/path/to/project")
|
|
109
|
+
)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## ClaudeSDKClient
|
|
113
|
+
|
|
114
|
+
`ClaudeSDKClient` supports bidirectional, interactive conversations with Claude
|
|
115
|
+
Code. See [src/claude_agent_sdk/client.py](src/claude_agent_sdk/client.py).
|
|
116
|
+
|
|
117
|
+
Unlike `query()`, `ClaudeSDKClient` additionally enables **custom tools** and **hooks**, both of which can be defined as Python functions.
|
|
118
|
+
|
|
119
|
+
### Custom Tools (as In-Process SDK MCP Servers)
|
|
120
|
+
|
|
121
|
+
A **custom tool** is a Python function that you can offer to Claude, for Claude to invoke as needed.
|
|
122
|
+
|
|
123
|
+
Custom tools are implemented in-process MCP servers that run directly within your Python application, eliminating the need for separate processes that regular MCP servers require.
|
|
124
|
+
|
|
125
|
+
For an end-to-end example, see [MCP Calculator](examples/mcp_calculator.py).
|
|
126
|
+
|
|
127
|
+
#### Creating a Simple Tool
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient
|
|
131
|
+
|
|
132
|
+
# Define a tool using the @tool decorator
|
|
133
|
+
@tool("greet", "Greet a user", {"name": str})
|
|
134
|
+
async def greet_user(args):
|
|
135
|
+
return {
|
|
136
|
+
"content": [
|
|
137
|
+
{"type": "text", "text": f"Hello, {args['name']}!"}
|
|
138
|
+
]
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
# Create an SDK MCP server
|
|
142
|
+
server = create_sdk_mcp_server(
|
|
143
|
+
name="my-tools",
|
|
144
|
+
version="1.0.0",
|
|
145
|
+
tools=[greet_user]
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
# Use it with Claude
|
|
149
|
+
options = ClaudeAgentOptions(
|
|
150
|
+
mcp_servers={"tools": server},
|
|
151
|
+
allowed_tools=["mcp__tools__greet"]
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
async with ClaudeSDKClient(options=options) as client:
|
|
155
|
+
await client.query("Greet Alice")
|
|
156
|
+
|
|
157
|
+
# Extract and print response
|
|
158
|
+
async for msg in client.receive_response():
|
|
159
|
+
print(msg)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
#### Benefits Over External MCP Servers
|
|
163
|
+
|
|
164
|
+
- **No subprocess management** - Runs in the same process as your application
|
|
165
|
+
- **Better performance** - No IPC overhead for tool calls
|
|
166
|
+
- **Simpler deployment** - Single Python process instead of multiple
|
|
167
|
+
- **Easier debugging** - All code runs in the same process
|
|
168
|
+
- **Type safety** - Direct Python function calls with type hints
|
|
169
|
+
|
|
170
|
+
#### Migration from External Servers
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
# BEFORE: External MCP server (separate process)
|
|
174
|
+
options = ClaudeAgentOptions(
|
|
175
|
+
mcp_servers={
|
|
176
|
+
"calculator": {
|
|
177
|
+
"type": "stdio",
|
|
178
|
+
"command": "python",
|
|
179
|
+
"args": ["-m", "calculator_server"]
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
# AFTER: SDK MCP server (in-process)
|
|
185
|
+
from my_tools import add, subtract # Your tool functions
|
|
186
|
+
|
|
187
|
+
calculator = create_sdk_mcp_server(
|
|
188
|
+
name="calculator",
|
|
189
|
+
tools=[add, subtract]
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
options = ClaudeAgentOptions(
|
|
193
|
+
mcp_servers={"calculator": calculator}
|
|
194
|
+
)
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
#### Mixed Server Support
|
|
198
|
+
|
|
199
|
+
You can use both SDK and external MCP servers together:
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
options = ClaudeAgentOptions(
|
|
203
|
+
mcp_servers={
|
|
204
|
+
"internal": sdk_server, # In-process SDK server
|
|
205
|
+
"external": { # External subprocess server
|
|
206
|
+
"type": "stdio",
|
|
207
|
+
"command": "external-server"
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
)
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
### Hooks
|
|
214
|
+
|
|
215
|
+
A **hook** is a Python function that the Claude Code *application* (*not* Claude) invokes at specific points of the Claude agent loop. Hooks can provide deterministic processing and automated feedback for Claude. Read more in [Claude Code Hooks Reference](https://docs.anthropic.com/en/docs/claude-code/hooks).
|
|
216
|
+
|
|
217
|
+
For more examples, see examples/hooks.py.
|
|
218
|
+
|
|
219
|
+
#### Example
|
|
220
|
+
|
|
221
|
+
```python
|
|
222
|
+
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, HookMatcher
|
|
223
|
+
|
|
224
|
+
async def check_bash_command(input_data, tool_use_id, context):
|
|
225
|
+
tool_name = input_data["tool_name"]
|
|
226
|
+
tool_input = input_data["tool_input"]
|
|
227
|
+
if tool_name != "Bash":
|
|
228
|
+
return {}
|
|
229
|
+
command = tool_input.get("command", "")
|
|
230
|
+
block_patterns = ["foo.sh"]
|
|
231
|
+
for pattern in block_patterns:
|
|
232
|
+
if pattern in command:
|
|
233
|
+
return {
|
|
234
|
+
"hookSpecificOutput": {
|
|
235
|
+
"hookEventName": "PreToolUse",
|
|
236
|
+
"permissionDecision": "deny",
|
|
237
|
+
"permissionDecisionReason": f"Command contains invalid pattern: {pattern}",
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return {}
|
|
241
|
+
|
|
242
|
+
options = ClaudeAgentOptions(
|
|
243
|
+
allowed_tools=["Bash"],
|
|
244
|
+
hooks={
|
|
245
|
+
"PreToolUse": [
|
|
246
|
+
HookMatcher(matcher="Bash", hooks=[check_bash_command]),
|
|
247
|
+
],
|
|
248
|
+
}
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
async with ClaudeSDKClient(options=options) as client:
|
|
252
|
+
# Test 1: Command with forbidden pattern (will be blocked)
|
|
253
|
+
await client.query("Run the bash command: ./foo.sh --help")
|
|
254
|
+
async for msg in client.receive_response():
|
|
255
|
+
print(msg)
|
|
256
|
+
|
|
257
|
+
print("\n" + "=" * 50 + "\n")
|
|
258
|
+
|
|
259
|
+
# Test 2: Safe command that should work
|
|
260
|
+
await client.query("Run the bash command: echo 'Hello from hooks example!'")
|
|
261
|
+
async for msg in client.receive_response():
|
|
262
|
+
print(msg)
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
## Types
|
|
267
|
+
|
|
268
|
+
See [src/claude_agent_sdk/types.py](src/claude_agent_sdk/types.py) for complete type definitions:
|
|
269
|
+
- `ClaudeAgentOptions` - Configuration options
|
|
270
|
+
- `AssistantMessage`, `UserMessage`, `SystemMessage`, `ResultMessage` - Message types
|
|
271
|
+
- `TextBlock`, `ToolUseBlock`, `ToolResultBlock` - Content blocks
|
|
272
|
+
|
|
273
|
+
## Error Handling
|
|
274
|
+
|
|
275
|
+
```python
|
|
276
|
+
from claude_agent_sdk import (
|
|
277
|
+
ClaudeSDKError, # Base error
|
|
278
|
+
CLINotFoundError, # Claude Code not installed
|
|
279
|
+
CLIConnectionError, # Connection issues
|
|
280
|
+
ProcessError, # Process failed
|
|
281
|
+
CLIJSONDecodeError, # JSON parsing issues
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
try:
|
|
285
|
+
async for message in query(prompt="Hello"):
|
|
286
|
+
pass
|
|
287
|
+
except CLINotFoundError:
|
|
288
|
+
print("Please install Claude Code")
|
|
289
|
+
except ProcessError as e:
|
|
290
|
+
print(f"Process failed with exit code: {e.exit_code}")
|
|
291
|
+
except CLIJSONDecodeError as e:
|
|
292
|
+
print(f"Failed to parse response: {e}")
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
See [src/claude_agent_sdk/_errors.py](src/claude_agent_sdk/_errors.py) for all error types.
|
|
296
|
+
|
|
297
|
+
## Available Tools
|
|
298
|
+
|
|
299
|
+
See the [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code/settings#tools-available-to-claude) for a complete list of available tools.
|
|
300
|
+
|
|
301
|
+
## Examples
|
|
302
|
+
|
|
303
|
+
See [examples/quick_start.py](examples/quick_start.py) for a complete working example.
|
|
304
|
+
|
|
305
|
+
See [examples/streaming_mode.py](examples/streaming_mode.py) for comprehensive examples involving `ClaudeSDKClient`. You can even run interactive examples in IPython from [examples/streaming_mode_ipython.py](examples/streaming_mode_ipython.py).
|
|
306
|
+
|
|
307
|
+
## License
|
|
308
|
+
|
|
309
|
+
MIT
|