1> ## Documentation Index
2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
3> Use this file to discover all available pages before exploring further.
4
5# Agent SDK 参考 - Python
6
7> Python Agent SDK 的完整 API 参考,包括所有函数、类型和类。
8
9## 安装
10
11```bash theme={null}
12pip install claude-agent-sdk
13```
14
15## 在 `query()` 和 `ClaudeSDKClient` 之间选择
16
17Python SDK 提供了两种与 Claude Code 交互的方式:
18
19### 快速比较
20
21| 功能 | `query()` | `ClaudeSDKClient` |
22| :-------- | :-------- | :---------------- |
23| **会话** | 每次创建新会话 | 重用同一会话 |
24| **对话** | 单次交换 | 同一上下文中的多次交换 |
25| **连接** | 自动管理 | 手动控制 |
26| **流式输入** | ✅ 支持 | ✅ 支持 |
27| **中断** | ❌ 不支持 | ✅ 支持 |
28| **hooks** | ✅ 支持 | ✅ 支持 |
29| **自定义工具** | ✅ 支持 | ✅ 支持 |
30| **继续聊天** | ❌ 每次新会话 | ✅ 保持对话 |
31| **用例** | 一次性任务 | 持续对话 |
32
33### 何时使用 `query()`(每次新会话)
34
35**最适合:**
36
37* 不需要对话历史的一次性问题
38* 不需要来自之前交换的上下文的独立任务
39* 简单的自动化脚本
40* 当你想每次都重新开始时
41
42### 何时使用 `ClaudeSDKClient`(持续对话)
43
44**最适合:**
45
46* **继续对话** - 当你需要 Claude 记住上下文时
47* **后续问题** - 基于之前的响应进行构建
48* **交互式应用程序** - 聊天界面、REPL
49* **响应驱动的逻辑** - 当下一步操作取决于 Claude 的响应时
50* **会话控制** - 显式管理对话生命周期
51
52## 函数
53
54### `query()`
55
56为每次与 Claude Code 的交互创建一个新会话。返回一个异步迭代器,当消息到达时产生消息。每次调用 `query()` 都会重新开始,不记得之前的交互。
57
58```python theme={null}
59async def query(
60 *,
61 prompt: str | AsyncIterable[dict[str, Any]],
62 options: ClaudeAgentOptions | None = None,
63 transport: Transport | None = None
64) -> AsyncIterator[Message]
65```
66
67#### 参数
68
69| 参数 | 类型 | 描述 |
70| :---------- | :--------------------------- | :------------------------------------------ |
71| `prompt` | `str \| AsyncIterable[dict]` | 输入提示,可以是字符串或用于流式模式的异步可迭代对象 |
72| `options` | `ClaudeAgentOptions \| None` | 可选配置对象(如果为 None,默认为 `ClaudeAgentOptions()`) |
73| `transport` | `Transport \| None` | 用于与 CLI 进程通信的可选自定义传输 |
74
75#### 返回
76
77返回一个 `AsyncIterator[Message]`,从对话中产生消息。
78
79#### 示例 - 带选项
80
81```python theme={null}
82import asyncio
83from claude_agent_sdk import query, ClaudeAgentOptions
84
85
86async def main():
87 options = ClaudeAgentOptions(
88 system_prompt="You are an expert Python developer",
89 permission_mode="acceptEdits",
90 cwd="/home/user/project",
91 )
92
93 async for message in query(prompt="Create a Python web server", options=options):
94 print(message)
95
96
97asyncio.run(main())
98```
99
100### `tool()`
101
102用于定义具有类型安全的 MCP 工具的装饰器。
103
104```python theme={null}
105def tool(
106 name: str,
107 description: str,
108 input_schema: type | dict[str, Any],
109 annotations: ToolAnnotations | None = None
110) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]
111```
112
113#### 参数
114
115| 参数 | 类型 | 描述 |
116| :------------- | :----------------------------------------------- | :---------------------- |
117| `name` | `str` | 工具的唯一标识符 |
118| `description` | `str` | 工具功能的人类可读描述 |
119| `input_schema` | `type \| dict[str, Any]` | 定义工具输入参数的模式(见下文) |
120| `annotations` | [`ToolAnnotations`](#tool-annotations)` \| None` | 可选的 MCP 工具注解,为客户端提供行为提示 |
121
122#### 输入模式选项
123
1241. **简单类型映射**(推荐):
125
126 ```python theme={null}
127 {"text": str, "count": int, "enabled": bool}
128 ```
129
1302. **JSON Schema 格式**(用于复杂验证):
131 ```python theme={null}
132 {
133 "type": "object",
134 "properties": {
135 "text": {"type": "string"},
136 "count": {"type": "integer", "minimum": 0},
137 },
138 "required": ["text"],
139 }
140 ```
141
142#### 返回
143
144一个装饰器函数,包装工具实现并返回一个 `SdkMcpTool` 实例。
145
146#### 示例
147
148```python theme={null}
149from claude_agent_sdk import tool
150from typing import Any
151
152
153@tool("greet", "Greet a user", {"name": str})
154async def greet(args: dict[str, Any]) -> dict[str, Any]:
155 return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}
156```
157
158#### `ToolAnnotations`
159
160从 `mcp.types` 重新导出(也可以从 `claude_agent_sdk` 导入)。所有字段都是可选的提示;客户端不应依赖它们做出安全决策。
161
162| 字段 | 类型 | 默认值 | 描述 |
163| :---------------- | :------------- | :------ | :------------------------------------------------------------- |
164| `title` | `str \| None` | `None` | 工具的人类可读标题 |
165| `readOnlyHint` | `bool \| None` | `False` | 如果为 `True`,工具不修改其环境 |
166| `destructiveHint` | `bool \| None` | `True` | 如果为 `True`,工具可能执行破坏性更新(仅当 `readOnlyHint` 为 `False` 时有意义) |
167| `idempotentHint` | `bool \| None` | `False` | 如果为 `True`,使用相同参数的重复调用没有额外效果(仅当 `readOnlyHint` 为 `False` 时有意义) |
168| `openWorldHint` | `bool \| None` | `True` | 如果为 `True`,工具与外部实体交互(例如网络搜索)。如果为 `False`,工具的域是封闭的(例如内存工具) |
169
170```python theme={null}
171from claude_agent_sdk import tool, ToolAnnotations
172from typing import Any
173
174
175@tool(
176 "search",
177 "Search the web",
178 {"query": str},
179 annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True),
180)
181async def search(args: dict[str, Any]) -> dict[str, Any]:
182 return {"content": [{"type": "text", "text": f"Results for: {args['query']}"}]}
183```
184
185### `create_sdk_mcp_server()`
186
187创建在 Python 应用程序中运行的进程内 MCP 服务器。
188
189```python theme={null}
190def create_sdk_mcp_server(
191 name: str,
192 version: str = "1.0.0",
193 tools: list[SdkMcpTool[Any]] | None = None
194) -> McpSdkServerConfig
195```
196
197#### 参数
198
199| 参数 | 类型 | 默认值 | 描述 |
200| :-------- | :------------------------------ | :-------- | :---------------------- |
201| `name` | `str` | - | 服务器的唯一标识符 |
202| `version` | `str` | `"1.0.0"` | 服务器版本字符串 |
203| `tools` | `list[SdkMcpTool[Any]] \| None` | `None` | 使用 `@tool` 装饰器创建的工具函数列表 |
204
205#### 返回
206
207返回一个 `McpSdkServerConfig` 对象,可以传递给 `ClaudeAgentOptions.mcp_servers`。
208
209#### 示例
210
211```python theme={null}
212from claude_agent_sdk import tool, create_sdk_mcp_server
213
214
215@tool("add", "Add two numbers", {"a": float, "b": float})
216async def add(args):
217 return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}
218
219
220@tool("multiply", "Multiply two numbers", {"a": float, "b": float})
221async def multiply(args):
222 return {"content": [{"type": "text", "text": f"Product: {args['a'] * args['b']}"}]}
223
224
225calculator = create_sdk_mcp_server(
226 name="calculator",
227 version="2.0.0",
228 tools=[add, multiply], # Pass decorated functions
229)
230
231# Use with Claude
232options = ClaudeAgentOptions(
233 mcp_servers={"calc": calculator},
234 allowed_tools=["mcp__calc__add", "mcp__calc__multiply"],
235)
236```
237
238### `list_sessions()`
239
240列出带有元数据的过去会话。按项目目录过滤或列出所有项目中的会话。同步;立即返回。
241
242```python theme={null}
243def list_sessions(
244 directory: str | None = None,
245 limit: int | None = None,
246 include_worktrees: bool = True
247) -> list[SDKSessionInfo]
248```
249
250#### 参数
251
252| 参数 | 类型 | 默认值 | 描述 |
253| :------------------ | :------------ | :----- | :-------------------------------------------- |
254| `directory` | `str \| None` | `None` | 列出会话的目录。省略时,返回所有项目中的会话 |
255| `limit` | `int \| None` | `None` | 返回的最大会话数 |
256| `include_worktrees` | `bool` | `True` | 当 `directory` 在 git 仓库内时,包括所有 worktree 路径中的会话 |
257
258#### 返回类型:`SDKSessionInfo`
259
260| 属性 | 类型 | 描述 |
261| :-------------- | :------------ | :------------------------------------------- |
262| `session_id` | `str` | 唯一会话标识符 |
263| `summary` | `str` | 显示标题:自定义标题、自动生成的摘要或第一个提示 |
264| `last_modified` | `int` | 上次修改时间(自纪元以来的毫秒数) |
265| `file_size` | `int \| None` | 会话文件大小(字节)(远程存储后端为 `None`) |
266| `custom_title` | `str \| None` | 用户设置的会话标题 |
267| `first_prompt` | `str \| None` | 会话中的第一个有意义的用户提示 |
268| `git_branch` | `str \| None` | 会话结束时的 Git 分支 |
269| `cwd` | `str \| None` | 会话的工作目录 |
270| `tag` | `str \| None` | 用户设置的会话标签(见 [`tag_session()`](#tag-session)) |
271| `created_at` | `int \| None` | 会话创建时间(自纪元以来的毫秒数) |
272
273#### 示例
274
275打印项目的 10 个最近会话。结果按 `last_modified` 降序排序,所以第一项是最新的。省略 `directory` 以搜索所有项目。
276
277```python theme={null}
278from claude_agent_sdk import list_sessions
279
280for session in list_sessions(directory="/path/to/project", limit=10):
281 print(f"{session.summary} ({session.session_id})")
282```
283
284### `get_session_messages()`
285
286从过去的会话中检索消息。同步;立即返回。
287
288```python theme={null}
289def get_session_messages(
290 session_id: str,
291 directory: str | None = None,
292 limit: int | None = None,
293 offset: int = 0
294) -> list[SessionMessage]
295```
296
297#### 参数
298
299| 参数 | 类型 | 默认值 | 描述 |
300| :----------- | :------------ | :----- | :------------------ |
301| `session_id` | `str` | 必需 | 要检索消息的会话 ID |
302| `directory` | `str \| None` | `None` | 要查看的项目目录。省略时,搜索所有项目 |
303| `limit` | `int \| None` | `None` | 返回的最大消息数 |
304| `offset` | `int` | `0` | 从开始跳过的消息数 |
305
306#### 返回类型:`SessionMessage`
307
308| 属性 | 类型 | 描述 |
309| :------------------- | :----------------------------- | :------ |
310| `type` | `Literal["user", "assistant"]` | 消息角色 |
311| `uuid` | `str` | 唯一消息标识符 |
312| `session_id` | `str` | 会话标识符 |
313| `message` | `Any` | 原始消息内容 |
314| `parent_tool_use_id` | `None` | 保留供将来使用 |
315
316#### 示例
317
318```python theme={null}
319from claude_agent_sdk import list_sessions, get_session_messages
320
321sessions = list_sessions(limit=1)
322if sessions:
323 messages = get_session_messages(sessions[0].session_id)
324 for msg in messages:
325 print(f"[{msg.type}] {msg.uuid}")
326```
327
328### `get_session_info()`
329
330按 ID 读取单个会话的元数据,无需扫描完整项目目录。同步;立即返回。
331
332```python theme={null}
333def get_session_info(
334 session_id: str,
335 directory: str | None = None,
336) -> SDKSessionInfo | None
337```
338
339#### 参数
340
341| 参数 | 类型 | 默认值 | 描述 |
342| :----------- | :------------ | :----- | :------------------ |
343| `session_id` | `str` | 必需 | 要查找的会话的 UUID |
344| `directory` | `str \| None` | `None` | 项目目录路径。省略时,搜索所有项目目录 |
345
346返回 [`SDKSessionInfo`](#return-type-sdk-session-info),如果找不到会话则返回 `None`。
347
348#### 示例
349
350查找单个会话的元数据,无需扫描项目目录。当你已经从之前的运行中获得会话 ID 时很有用。
351
352```python theme={null}
353from claude_agent_sdk import get_session_info
354
355info = get_session_info("550e8400-e29b-41d4-a716-446655440000")
356if info:
357 print(f"{info.summary} (branch: {info.git_branch}, tag: {info.tag})")
358```
359
360### `rename_session()`
361
362通过追加自定义标题条目来重命名会话。重复调用是安全的;最新的标题获胜。同步。
363
364```python theme={null}
365def rename_session(
366 session_id: str,
367 title: str,
368 directory: str | None = None,
369) -> None
370```
371
372#### 参数
373
374| 参数 | 类型 | 默认值 | 描述 |
375| :----------- | :------------ | :----- | :------------------ |
376| `session_id` | `str` | 必需 | 要重命名的会话的 UUID |
377| `title` | `str` | 必需 | 新标题。去除空格后必须非空 |
378| `directory` | `str \| None` | `None` | 项目目录路径。省略时,搜索所有项目目录 |
379
380如果 `session_id` 不是有效的 UUID 或 `title` 为空,则抛出 `ValueError`;如果找不到会话,则抛出 `FileNotFoundError`。
381
382#### 示例
383
384重命名最近的会话,使其更容易找到。新标题在后续读取时出现在 [`SDKSessionInfo.custom_title`](#return-type-sdk-session-info) 中。
385
386```python theme={null}
387from claude_agent_sdk import list_sessions, rename_session
388
389sessions = list_sessions(directory="/path/to/project", limit=1)
390if sessions:
391 rename_session(sessions[0].session_id, "Refactor auth module")
392```
393
394### `tag_session()`
395
396标记会话。传递 `None` 以清除标签。重复调用是安全的;最新的标签获胜。同步。
397
398```python theme={null}
399def tag_session(
400 session_id: str,
401 tag: str | None,
402 directory: str | None = None,
403) -> None
404```
405
406#### 参数
407
408| 参数 | 类型 | 默认值 | 描述 |
409| :----------- | :------------ | :----- | :---------------------------------- |
410| `session_id` | `str` | 必需 | 要标记的会话的 UUID |
411| `tag` | `str \| None` | 必需 | 标签字符串,或 `None` 以清除。存储前进行 Unicode 清理 |
412| `directory` | `str \| None` | `None` | 项目目录路径。省略时,搜索所有项目目录 |
413
414如果 `session_id` 不是有效的 UUID 或 `tag` 在清理后为空,则抛出 `ValueError`;如果找不到会话,则抛出 `FileNotFoundError`。
415
416#### 示例
417
418标记会话,然后在稍后的读取中按该标签过滤。传递 `None` 以清除现有标签。
419
420```python theme={null}
421from claude_agent_sdk import list_sessions, tag_session
422
423# Tag a session
424tag_session("550e8400-e29b-41d4-a716-446655440000", "needs-review")
425
426# Later: find all sessions with that tag
427for session in list_sessions(directory="/path/to/project"):
428 if session.tag == "needs-review":
429 print(session.summary)
430```
431
432## 类
433
434### `ClaudeSDKClient`
435
436**在多次交换中维持对话会话。** 这是 TypeScript SDK 的 `query()` 函数内部工作方式的 Python 等价物 - 它创建一个可以继续对话的客户端对象。
437
438#### 关键特性
439
440* **会话连续性**:在多个 `query()` 调用中维持对话上下文
441* **同一对话**:会话保留之前的消息
442* **中断支持**:可以在任务中途停止执行
443* **显式生命周期**:你控制会话何时开始和结束
444* **响应驱动的流程**:可以对响应做出反应并发送后续消息
445* **自定义工具和 hooks**:支持自定义工具(使用 `@tool` 装饰器创建)和 hooks
446
447```python theme={null}
448class ClaudeSDKClient:
449 def __init__(self, options: ClaudeAgentOptions | None = None, transport: Transport | None = None)
450 async def connect(self, prompt: str | AsyncIterable[dict] | None = None) -> None
451 async def query(self, prompt: str | AsyncIterable[dict], session_id: str = "default") -> None
452 async def receive_messages(self) -> AsyncIterator[Message]
453 async def receive_response(self) -> AsyncIterator[Message]
454 async def interrupt(self) -> None
455 async def set_permission_mode(self, mode: str) -> None
456 async def set_model(self, model: str | None = None) -> None
457 async def rewind_files(self, user_message_id: str) -> None
458 async def get_mcp_status(self) -> McpStatusResponse
459 async def reconnect_mcp_server(self, server_name: str) -> None
460 async def toggle_mcp_server(self, server_name: str, enabled: bool) -> None
461 async def stop_task(self, task_id: str) -> None
462 async def get_server_info(self) -> dict[str, Any] | None
463 async def disconnect(self) -> None
464```
465
466#### 方法
467
468| 方法 | 描述 |
469| :---------------------------------------- | :-------------------------------------------------------------------------------------------------- |
470| `__init__(options)` | 使用可选配置初始化客户端 |
471| `connect(prompt)` | 连接到 Claude,可选初始提示或消息流 |
472| `query(prompt, session_id)` | 以流式模式发送新请求 |
473| `receive_messages()` | 以异步迭代器形式接收来自 Claude 的所有消息 |
474| `receive_response()` | 接收消息直到并包括 ResultMessage |
475| `interrupt()` | 发送中断信号(仅在流式模式下工作) |
476| `set_permission_mode(mode)` | 更改当前会话的权限模式 |
477| `set_model(model)` | 更改当前会话的模型。传递 `None` 以重置为默认值 |
478| `rewind_files(user_message_id)` | 将文件恢复到指定用户消息时的状态。需要 `enable_file_checkpointing=True`。见 [文件检查点](/zh-CN/agent-sdk/file-checkpointing) |
479| `get_mcp_status()` | 获取所有配置的 MCP 服务器的状态。返回 [`McpStatusResponse`](#mcp-status-response) |
480| `reconnect_mcp_server(server_name)` | 重试连接到失败或断开连接的 MCP 服务器 |
481| `toggle_mcp_server(server_name, enabled)` | 在会话中启用或禁用 MCP 服务器。禁用会移除其工具 |
482| `stop_task(task_id)` | 停止运行的后台任务。一个状态为 `"stopped"` 的 [`TaskNotificationMessage`](#task-notification-message) 随后在消息流中出现 |
483| `get_server_info()` | 获取服务器信息,包括会话 ID 和功能 |
484| `disconnect()` | 从 Claude 断开连接 |
485
486#### 上下文管理器支持
487
488客户端可以用作异步上下文管理器以自动管理连接:
489
490```python theme={null}
491async with ClaudeSDKClient() as client:
492 await client.query("Hello Claude")
493 async for message in client.receive_response():
494 print(message)
495```
496
497> **重要:** 迭代消息时,避免使用 `break` 提前退出,因为这可能导致 asyncio 清理问题。相反,让迭代自然完成或使用标志来跟踪何时找到了你需要的内容。
498
499#### 示例 - 继续对话
500
501```python theme={null}
502import asyncio
503from claude_agent_sdk import ClaudeSDKClient, AssistantMessage, TextBlock, ResultMessage
504
505
506async def main():
507 async with ClaudeSDKClient() as client:
508 # First question
509 await client.query("What's the capital of France?")
510
511 # Process response
512 async for message in client.receive_response():
513 if isinstance(message, AssistantMessage):
514 for block in message.content:
515 if isinstance(block, TextBlock):
516 print(f"Claude: {block.text}")
517
518 # Follow-up question - the session retains the previous context
519 await client.query("What's the population of that city?")
520
521 async for message in client.receive_response():
522 if isinstance(message, AssistantMessage):
523 for block in message.content:
524 if isinstance(block, TextBlock):
525 print(f"Claude: {block.text}")
526
527 # Another follow-up - still in the same conversation
528 await client.query("What are some famous landmarks there?")
529
530 async for message in client.receive_response():
531 if isinstance(message, AssistantMessage):
532 for block in message.content:
533 if isinstance(block, TextBlock):
534 print(f"Claude: {block.text}")
535
536
537asyncio.run(main())
538```
539
540#### 示例 - 使用 ClaudeSDKClient 进行流式输入
541
542```python theme={null}
543import asyncio
544from claude_agent_sdk import ClaudeSDKClient
545
546
547async def message_stream():
548 """Generate messages dynamically."""
549 yield {
550 "type": "user",
551 "message": {"role": "user", "content": "Analyze the following data:"},
552 }
553 await asyncio.sleep(0.5)
554 yield {
555 "type": "user",
556 "message": {"role": "user", "content": "Temperature: 25°C, Humidity: 60%"},
557 }
558 await asyncio.sleep(0.5)
559 yield {
560 "type": "user",
561 "message": {"role": "user", "content": "What patterns do you see?"},
562 }
563
564
565async def main():
566 async with ClaudeSDKClient() as client:
567 # Stream input to Claude
568 await client.query(message_stream())
569
570 # Process response
571 async for message in client.receive_response():
572 print(message)
573
574 # Follow-up in same session
575 await client.query("Should we be concerned about these readings?")
576
577 async for message in client.receive_response():
578 print(message)
579
580
581asyncio.run(main())
582```
583
584#### 示例 - 使用中断
585
586```python theme={null}
587import asyncio
588from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, ResultMessage
589
590
591async def interruptible_task():
592 options = ClaudeAgentOptions(allowed_tools=["Bash"], permission_mode="acceptEdits")
593
594 async with ClaudeSDKClient(options=options) as client:
595 # Start a long-running task
596 await client.query("Count from 1 to 100 slowly, using the bash sleep command")
597
598 # Let it run for a bit
599 await asyncio.sleep(2)
600
601 # Interrupt the task
602 await client.interrupt()
603 print("Task interrupted!")
604
605 # Drain the interrupted task's messages (including its ResultMessage)
606 async for message in client.receive_response():
607 if isinstance(message, ResultMessage):
608 print(f"Interrupted task finished with subtype={message.subtype!r}")
609 # subtype is "error_during_execution" for interrupted tasks
610
611 # Send a new command
612 await client.query("Just say hello instead")
613
614 # Now receive the new response
615 async for message in client.receive_response():
616 if isinstance(message, ResultMessage) and message.subtype == "success":
617 print(f"New result: {message.result}")
618
619
620asyncio.run(interruptible_task())
621```
622
623<Note>
624 **中断后的缓冲行为:** `interrupt()` 发送停止信号但不清除消息缓冲区。被中断任务已产生的消息,包括其 `ResultMessage`(带 `subtype="error_during_execution"`),保留在流中。你必须在读取新查询的响应之前用 `receive_response()` 清空它们。如果在 `interrupt()` 之后立即发送新查询并仅调用一次 `receive_response()`,你将收到被中断任务的消息,而不是新查询的响应。
625</Note>
626
627#### 示例 - 高级权限控制
628
629```python theme={null}
630from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
631from claude_agent_sdk.types import (
632 PermissionResultAllow,
633 PermissionResultDeny,
634 ToolPermissionContext,
635)
636
637
638async def custom_permission_handler(
639 tool_name: str, input_data: dict, context: ToolPermissionContext
640) -> PermissionResultAllow | PermissionResultDeny:
641 """Custom logic for tool permissions."""
642
643 # Block writes to system directories
644 if tool_name == "Write" and input_data.get("file_path", "").startswith("/system/"):
645 return PermissionResultDeny(
646 message="System directory write not allowed", interrupt=True
647 )
648
649 # Redirect sensitive file operations
650 if tool_name in ["Write", "Edit"] and "config" in input_data.get("file_path", ""):
651 safe_path = f"./sandbox/{input_data['file_path']}"
652 return PermissionResultAllow(
653 updated_input={**input_data, "file_path": safe_path}
654 )
655
656 # Allow everything else
657 return PermissionResultAllow(updated_input=input_data)
658
659
660async def main():
661 options = ClaudeAgentOptions(
662 can_use_tool=custom_permission_handler, allowed_tools=["Read", "Write", "Edit"]
663 )
664
665 async with ClaudeSDKClient(options=options) as client:
666 await client.query("Update the system config file")
667
668 async for message in client.receive_response():
669 # Will use sandbox path instead
670 print(message)
671
672
673asyncio.run(main())
674```
675
676## 类型
677
678<Note>
679 **`@dataclass` vs `TypedDict`:** 此 SDK 使用两种类型。用 `@dataclass` 装饰的类(如 `ResultMessage`、`AgentDefinition`、`TextBlock`)在运行时是对象实例,支持属性访问:`msg.result`。用 `TypedDict` 定义的类(如 `ThinkingConfigEnabled`、`McpStdioServerConfig`、`SyncHookJSONOutput`)在运行时是**普通字典**,需要键访问:`config["budget_tokens"]`,而不是 `config.budget_tokens`。`ClassName(field=value)` 调用语法对两者都有效,但只有数据类产生具有属性的对象。
680</Note>
681
682### `SdkMcpTool`
683
684使用 `@tool` 装饰器创建的 SDK MCP 工具的定义。
685
686```python theme={null}
687@dataclass
688class SdkMcpTool(Generic[T]):
689 name: str
690 description: str
691 input_schema: type[T] | dict[str, Any]
692 handler: Callable[[T], Awaitable[dict[str, Any]]]
693 annotations: ToolAnnotations | None = None
694```
695
696| 属性 | 类型 | 描述 |
697| :------------- | :----------------------------------------- | :------------------------------------------------------------------------------- |
698| `name` | `str` | 工具的唯一标识符 |
699| `description` | `str` | 人类可读的描述 |
700| `input_schema` | `type[T] \| dict[str, Any]` | 输入验证的模式 |
701| `handler` | `Callable[[T], Awaitable[dict[str, Any]]]` | 处理工具执行的异步函数 |
702| `annotations` | `ToolAnnotations \| None` | 可选的 MCP 工具注解(例如 `readOnlyHint`、`destructiveHint`、`openWorldHint`)。来自 `mcp.types` |
703
704### `Transport`
705
706自定义传输实现的抽象基类。使用此类通过自定义通道与 Claude 进程通信(例如,远程连接而不是本地子进程)。
707
708<Warning>
709 这是一个低级内部 API。接口可能在未来版本中更改。自定义实现必须更新以匹配任何接口更改。
710</Warning>
711
712```python theme={null}
713from abc import ABC, abstractmethod
714from collections.abc import AsyncIterator
715from typing import Any
716
717
718class Transport(ABC):
719 @abstractmethod
720 async def connect(self) -> None: ...
721
722 @abstractmethod
723 async def write(self, data: str) -> None: ...
724
725 @abstractmethod
726 def read_messages(self) -> AsyncIterator[dict[str, Any]]: ...
727
728 @abstractmethod
729 async def close(self) -> None: ...
730
731 @abstractmethod
732 def is_ready(self) -> bool: ...
733
734 @abstractmethod
735 async def end_input(self) -> None: ...
736```
737
738| 方法 | 描述 |
739| :---------------- | :----------------------- |
740| `connect()` | 连接传输并准备通信 |
741| `write(data)` | 将原始数据(JSON + 换行符)写入传输 |
742| `read_messages()` | 异步迭代器,产生解析的 JSON 消息 |
743| `close()` | 关闭连接并清理资源 |
744| `is_ready()` | 如果传输可以发送和接收,返回 `True` |
745| `end_input()` | 关闭输入流(例如,为子进程传输关闭 stdin) |
746
747导入:`from claude_agent_sdk import Transport`
748
749### `ClaudeAgentOptions`
750
751Claude Code 查询的配置数据类。
752
753```python theme={null}
754@dataclass
755class ClaudeAgentOptions:
756 tools: list[str] | ToolsPreset | None = None
757 allowed_tools: list[str] = field(default_factory=list)
758 system_prompt: str | SystemPromptPreset | None = None
759 mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
760 permission_mode: PermissionMode | None = None
761 continue_conversation: bool = False
762 resume: str | None = None
763 max_turns: int | None = None
764 max_budget_usd: float | None = None
765 disallowed_tools: list[str] = field(default_factory=list)
766 model: str | None = None
767 fallback_model: str | None = None
768 betas: list[SdkBeta] = field(default_factory=list)
769 output_format: dict[str, Any] | None = None
770 permission_prompt_tool_name: str | None = None
771 cwd: str | Path | None = None
772 cli_path: str | Path | None = None
773 settings: str | None = None
774 add_dirs: list[str | Path] = field(default_factory=list)
775 env: dict[str, str] = field(default_factory=dict)
776 extra_args: dict[str, str | None] = field(default_factory=dict)
777 max_buffer_size: int | None = None
778 debug_stderr: Any = sys.stderr # Deprecated
779 stderr: Callable[[str], None] | None = None
780 can_use_tool: CanUseTool | None = None
781 hooks: dict[HookEvent, list[HookMatcher]] | None = None
782 user: str | None = None
783 include_partial_messages: bool = False
784 fork_session: bool = False
785 agents: dict[str, AgentDefinition] | None = None
786 setting_sources: list[SettingSource] | None = None
787 sandbox: SandboxSettings | None = None
788 plugins: list[SdkPluginConfig] = field(default_factory=list)
789 max_thinking_tokens: int | None = None # Deprecated: use thinking instead
790 thinking: ThinkingConfig | None = None
791 effort: Literal["low", "medium", "high", "max"] | None = None
792 enable_file_checkpointing: bool = False
793 session_store: SessionStore | None = None
794```
795
796| 属性 | 类型 | 默认值 | 描述 |
797| :---------------------------- | :---------------------------------------------------------------------------------------- | :------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
798| `tools` | `list[str] \| ToolsPreset \| None` | `None` | 工具配置。使用 `{"type": "preset", "preset": "claude_code"}` 获取 Claude Code 的默认工具 |
799| `allowed_tools` | `list[str]` | `[]` | 无需提示即可自动批准的工具。这不会限制 Claude 仅使用这些工具;未列出的工具会通过 `permission_mode` 和 `can_use_tool` 处理。使用 `disallowed_tools` 阻止工具。见 [权限](/zh-CN/agent-sdk/permissions#allow-and-deny-rules) |
800| `system_prompt` | `str \| SystemPromptPreset \| None` | `None` | 系统提示配置。传递字符串以获取自定义提示,或使用 `{"type": "preset", "preset": "claude_code"}` 获取 Claude Code 的系统提示。添加 `"append"` 以扩展预设 |
801| `mcp_servers` | `dict[str, McpServerConfig] \| str \| Path` | `{}` | MCP 服务器配置或配置文件路径 |
802| `permission_mode` | `PermissionMode \| None` | `None` | 工具使用的权限模式 |
803| `continue_conversation` | `bool` | `False` | 继续最近的对话 |
804| `resume` | `str \| None` | `None` | 要恢复的会话 ID |
805| `max_turns` | `int \| None` | `None` | 最大代理轮次(工具使用往返) |
806| `max_budget_usd` | `float \| None` | `None` | 当客户端成本估计达到此 USD 值时停止查询。与 `total_cost_usd` 的相同估计进行比较;见 [跟踪成本和使用](/zh-CN/agent-sdk/cost-tracking) 了解准确性注意事项 |
807| `disallowed_tools` | `list[str]` | `[]` | 始终拒绝的工具。拒绝规则首先检查并覆盖 `allowed_tools` 和 `permission_mode`(包括 `bypassPermissions`) |
808| `enable_file_checkpointing` | `bool` | `False` | 启用文件更改跟踪以进行回滚。见 [文件检查点](/zh-CN/agent-sdk/file-checkpointing) |
809| `model` | `str \| None` | `None` | 要使用的 Claude 模型 |
810| `fallback_model` | `str \| None` | `None` | 主模型失败时使用的备用模型 |
811| `betas` | `list[SdkBeta]` | `[]` | 要启用的测试功能。见 [`SdkBeta`](#sdk-beta) 了解可用选项 |
812| `output_format` | `dict[str, Any] \| None` | `None` | 结构化响应的输出格式(例如 `{"type": "json_schema", "schema": {...}}`)。见 [结构化输出](/zh-CN/agent-sdk/structured-outputs) 了解详情 |
813| `permission_prompt_tool_name` | `str \| None` | `None` | 权限提示的 MCP 工具名称 |
814| `cwd` | `str \| Path \| None` | `None` | 当前工作目录 |
815| `cli_path` | `str \| Path \| None` | `None` | Claude Code CLI 可执行文件的自定义路径 |
816| `settings` | `str \| None` | `None` | 设置文件的路径 |
817| `add_dirs` | `list[str \| Path]` | `[]` | Claude 可以访问的其他目录 |
818| `env` | `dict[str, str]` | `{}` | 环境变量合并到继承的进程环境之上。见 [环境变量](/zh-CN/env-vars) 了解底层 CLI 读取的变量 |
819| `extra_args` | `dict[str, str \| None]` | `{}` | 直接传递给 CLI 的其他 CLI 参数 |
820| `max_buffer_size` | `int \| None` | `None` | 缓冲 CLI stdout 时的最大字节数 |
821| `debug_stderr` | `Any` | `sys.stderr` | *已弃用* - 用于调试输出的类文件对象。改用 `stderr` 回调 |
822| `stderr` | `Callable[[str], None] \| None` | `None` | CLI 中 stderr 输出的回调函数 |
823| `can_use_tool` | [`CanUseTool`](#can-use-tool) ` \| None` | `None` | 工具权限回调函数。见 [权限类型](#can-use-tool) 了解详情 |
824| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | 用于拦截事件的 hooks 配置 |
825| `user` | `str \| None` | `None` | 用户标识符 |
826| `include_partial_messages` | `bool` | `False` | 包括部分消息流式事件。启用时,会产生 [`StreamEvent`](#stream-event) 消息 |
827| `fork_session` | `bool` | `False` | 使用 `resume` 恢复时,分叉到新会话 ID 而不是继续原始会话 |
828| `agents` | `dict[str, AgentDefinition] \| None` | `None` | 以编程方式定义的子代理 |
829| `plugins` | `list[SdkPluginConfig]` | `[]` | 从本地路径加载自定义插件。见 [Plugins](/zh-CN/agent-sdk/plugins) 了解详情 |
830| `sandbox` | [`SandboxSettings`](#sandbox-settings) ` \| None` | `None` | 以编程方式配置沙箱行为。见 [沙箱设置](#sandbox-settings) 了解详情 |
831| `setting_sources` | `list[SettingSource] \| None` | `None`(CLI 默认值:所有源) | 控制加载哪些文件系统设置。传递 `[]` 以禁用用户、项目和本地设置。无论如何都会加载托管策略设置。见 [使用 Claude Code 功能](/zh-CN/agent-sdk/claude-code-features#what-settingsources-does-not-control) |
832| `max_thinking_tokens` | `int \| None` | `None` | *已弃用* - 思考块的最大令牌数。改用 `thinking` |
833| `thinking` | [`ThinkingConfig`](#thinking-config) ` \| None` | `None` | 控制扩展思考行为。优先于 `max_thinking_tokens` |
834| `effort` | `Literal["low", "medium", "high", "max"] \| None` | `None` | 思考深度的努力级别 |
835| `session_store` | [`SessionStore`](/zh-CN/agent-sdk/session-storage#the-session-store-interface) ` \| None` | `None` | 将会话记录镜像到外部后端,以便任何主机都可以恢复它们。见 [将会话持久化到外部存储](/zh-CN/agent-sdk/session-storage) |
836
837### `OutputFormat`
838
839结构化输出验证的配置。将其作为 `dict` 传递给 `ClaudeAgentOptions` 上的 `output_format` 字段:
840
841```python theme={null}
842# Expected dict shape for output_format
843{
844 "type": "json_schema",
845 "schema": {...}, # Your JSON Schema definition
846}
847```
848
849| 字段 | 必需 | 描述 |
850| :------- | :- | :------------------------------------ |
851| `type` | 是 | 必须是 `"json_schema"` 用于 JSON Schema 验证 |
852| `schema` | 是 | 用于输出验证的 JSON Schema 定义 |
853
854### `SystemPromptPreset`
855
856使用 Claude Code 的预设系统提示和可选添加的配置。
857
858```python theme={null}
859class SystemPromptPreset(TypedDict):
860 type: Literal["preset"]
861 preset: Literal["claude_code"]
862 append: NotRequired[str]
863 exclude_dynamic_sections: NotRequired[bool]
864```
865
866| 字段 | 必需 | 描述 |
867| :------------------------- | :- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
868| `type` | 是 | 必须是 `"preset"` 以使用预设系统提示 |
869| `preset` | 是 | 必须是 `"claude_code"` 以使用 Claude Code 的系统提示 |
870| `append` | 否 | 要追加到预设系统提示的其他说明 |
871| `exclude_dynamic_sections` | 否 | 将每个会话的上下文(如工作目录、git 状态和内存路径)从系统提示移到第一条用户消息。改进跨用户和机器的提示缓存重用。见 [修改系统提示](/zh-CN/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) |
872
873### `SettingSource`
874
875控制 SDK 从哪些基于文件系统的配置源加载设置。
876
877```python theme={null}
878SettingSource = Literal["user", "project", "local"]
879```
880
881| 值 | 描述 | 位置 |
882| :---------- | :----------------- | :---------------------------- |
883| `"user"` | 全局用户设置 | `~/.claude/settings.json` |
884| `"project"` | 共享项目设置(版本控制) | `.claude/settings.json` |
885| `"local"` | 本地项目设置(gitignored) | `.claude/settings.local.json` |
886
887#### 默认行为
888
889当 `setting_sources` 被省略或为 `None` 时,`query()` 加载与 Claude Code CLI 相同的文件系统设置:用户、项目和本地。无论如何都会加载托管策略设置。见 [settingSources 不控制什么](/zh-CN/agent-sdk/claude-code-features#what-settingsources-does-not-control) 了解无论此选项如何都会读取的输入,以及如何禁用它们。
890
891#### 为什么使用 setting\_sources
892
893**禁用文件系统设置:**
894
895```python theme={null}
896# Do not load user, project, or local settings from disk
897from claude_agent_sdk import query, ClaudeAgentOptions
898
899async for message in query(
900 prompt="Analyze this code",
901 options=ClaudeAgentOptions(
902 setting_sources=[]
903 ),
904):
905 print(message)
906```
907
908<Note>
909 在 Python SDK 0.1.59 及更早版本中,空列表的处理方式与省略选项相同,因此 `setting_sources=[]` 不会禁用文件系统设置。如果你需要空列表生效,请升级到较新版本。TypeScript SDK 不受影响。
910</Note>
911
912**显式加载所有文件系统设置:**
913
914```python theme={null}
915from claude_agent_sdk import query, ClaudeAgentOptions
916
917async for message in query(
918 prompt="Analyze this code",
919 options=ClaudeAgentOptions(
920 setting_sources=["user", "project", "local"]
921 ),
922):
923 print(message)
924```
925
926**仅加载特定设置源:**
927
928```python theme={null}
929# Load only project settings, ignore user and local
930async for message in query(
931 prompt="Run CI checks",
932 options=ClaudeAgentOptions(
933 setting_sources=["project"] # Only .claude/settings.json
934 ),
935):
936 print(message)
937```
938
939**测试和 CI 环境:**
940
941```python theme={null}
942# Ensure consistent behavior in CI by excluding local settings
943async for message in query(
944 prompt="Run tests",
945 options=ClaudeAgentOptions(
946 setting_sources=["project"], # Only team-shared settings
947 permission_mode="bypassPermissions",
948 ),
949):
950 print(message)
951```
952
953**仅 SDK 应用程序:**
954
955```python theme={null}
956# Define everything programmatically.
957# Pass [] to opt out of filesystem setting sources.
958async for message in query(
959 prompt="Review this PR",
960 options=ClaudeAgentOptions(
961 setting_sources=[],
962 agents={...},
963 mcp_servers={...},
964 allowed_tools=["Read", "Grep", "Glob"],
965 ),
966):
967 print(message)
968```
969
970**加载 CLAUDE.md 项目说明:**
971
972```python theme={null}
973# Load project settings to include CLAUDE.md files
974async for message in query(
975 prompt="Add a new feature following project conventions",
976 options=ClaudeAgentOptions(
977 system_prompt={
978 "type": "preset",
979 "preset": "claude_code", # Use Claude Code's system prompt
980 },
981 setting_sources=["project"], # Loads CLAUDE.md from project
982 allowed_tools=["Read", "Write", "Edit"],
983 ),
984):
985 print(message)
986```
987
988#### 设置优先级
989
990加载多个源时,设置按此优先级合并(从高到低):
991
9921. 本地设置(`.claude/settings.local.json`)
9932. 项目设置(`.claude/settings.json`)
9943. 用户设置(`~/.claude/settings.json`)
995
996编程选项(如 `agents` 和 `allowed_tools`)覆盖用户、项目和本地文件系统设置。托管策略设置优先于编程选项。
997
998### `AgentDefinition`
999
1000以编程方式定义的子代理的配置。
1001
1002```python theme={null}
1003@dataclass
1004class AgentDefinition:
1005 description: str
1006 prompt: str
1007 tools: list[str] | None = None
1008 disallowedTools: list[str] | None = None
1009 model: str | None = None
1010 skills: list[str] | None = None
1011 memory: Literal["user", "project", "local"] | None = None
1012 mcpServers: list[str | dict[str, Any]] | None = None
1013 initialPrompt: str | None = None
1014 maxTurns: int | None = None
1015 background: bool | None = None
1016 effort: Literal["low", "medium", "high", "max"] | int | None = None
1017 permissionMode: PermissionMode | None = None
1018```
1019
1020| 字段 | 必需 | 描述 |
1021| :---------------- | :- | :----------------------------------------------------------------------------- |
1022| `description` | 是 | 何时使用此代理的自然语言描述 |
1023| `prompt` | 是 | 代理的系统提示 |
1024| `tools` | 否 | 允许的工具名称数组。如果省略,继承所有工具 |
1025| `disallowedTools` | 否 | 要从代理的工具集中移除的工具名称数组 |
1026| `model` | 否 | 此代理的模型覆盖。接受别名如 `"sonnet"`、`"opus"`、`"haiku"` 或 `"inherit"`,或完整模型 ID。如果省略,使用主模型 |
1027| `skills` | 否 | 此代理可用的技能名称列表 |
1028| `memory` | 否 | 此代理的内存源:`"user"`、`"project"` 或 `"local"` |
1029| `mcpServers` | 否 | 此代理可用的 MCP 服务器。每个条目是服务器名称或内联 `{name: config}` 字典 |
1030| `initialPrompt` | 否 | 当此代理作为主线程代理运行时自动提交为第一个用户轮次 |
1031| `maxTurns` | 否 | 代理停止前的最大代理轮次数 |
1032| `background` | 否 | 调用时将此代理作为非阻塞后台任务运行 |
1033| `effort` | 否 | 此代理的推理努力级别。接受命名级别或整数 |
1034| `permissionMode` | 否 | 此代理内工具执行的权限模式。见 [`PermissionMode`](#permission-mode) |
1035
1036<Note>
1037 `AgentDefinition` 字段名称使用 camelCase,如 `disallowedTools`、`permissionMode` 和 `maxTurns`。这些名称直接映射到与 TypeScript SDK 共享的线路格式。这与 `ClaudeAgentOptions` 不同,后者对等效的顶级字段(如 `disallowed_tools` 和 `permission_mode`)使用 Python snake\_case。因为 `AgentDefinition` 是数据类,传递 snake\_case 关键字在构造时会引发 `TypeError`。
1038</Note>
1039
1040### `PermissionMode`
1041
1042用于控制工具执行的权限模式。
1043
1044```python theme={null}
1045PermissionMode = Literal[
1046 "default", # Standard permission behavior
1047 "acceptEdits", # Auto-accept file edits
1048 "plan", # Planning mode - no execution
1049 "dontAsk", # Deny anything not pre-approved instead of prompting
1050 "bypassPermissions", # Bypass all permission checks (use with caution)
1051]
1052```
1053
1054### `CanUseTool`
1055
1056工具权限回调函数的类型别名。
1057
1058```python theme={null}
1059CanUseTool = Callable[
1060 [str, dict[str, Any], ToolPermissionContext], Awaitable[PermissionResult]
1061]
1062```
1063
1064回调接收:
1065
1066* `tool_name`:被调用的工具的名称
1067* `input_data`:工具的输入参数
1068* `context`:带有附加信息的 `ToolPermissionContext`
1069
1070返回 `PermissionResult`(`PermissionResultAllow` 或 `PermissionResultDeny`)。
1071
1072### `ToolPermissionContext`
1073
1074传递给工具权限回调的上下文信息。
1075
1076```python theme={null}
1077@dataclass
1078class ToolPermissionContext:
1079 signal: Any | None = None # Future: abort signal support
1080 suggestions: list[PermissionUpdate] = field(default_factory=list)
1081```
1082
1083| 字段 | 类型 | 描述 |
1084| :------------ | :----------------------- | :------------- |
1085| `signal` | `Any \| None` | 保留供将来中止信号支持 |
1086| `suggestions` | `list[PermissionUpdate]` | 来自 CLI 的权限更新建议 |
1087
1088### `PermissionResult`
1089
1090权限回调结果的联合类型。
1091
1092```python theme={null}
1093PermissionResult = PermissionResultAllow | PermissionResultDeny
1094```
1095
1096### `PermissionResultAllow`
1097
1098指示应允许工具调用的结果。
1099
1100```python theme={null}
1101@dataclass
1102class PermissionResultAllow:
1103 behavior: Literal["allow"] = "allow"
1104 updated_input: dict[str, Any] | None = None
1105 updated_permissions: list[PermissionUpdate] | None = None
1106```
1107
1108| 字段 | 类型 | 默认值 | 描述 |
1109| :-------------------- | :------------------------------- | :-------- | :---------------- |
1110| `behavior` | `Literal["allow"]` | `"allow"` | 必须是 "allow" |
1111| `updated_input` | `dict[str, Any] \| None` | `None` | 要使用的修改后的输入而不是原始输入 |
1112| `updated_permissions` | `list[PermissionUpdate] \| None` | `None` | 要应用的权限更新 |
1113
1114### `PermissionResultDeny`
1115
1116指示应拒绝工具调用的结果。
1117
1118```python theme={null}
1119@dataclass
1120class PermissionResultDeny:
1121 behavior: Literal["deny"] = "deny"
1122 message: str = ""
1123 interrupt: bool = False
1124```
1125
1126| 字段 | 类型 | 默认值 | 描述 |
1127| :---------- | :---------------- | :------- | :----------- |
1128| `behavior` | `Literal["deny"]` | `"deny"` | 必须是 "deny" |
1129| `message` | `str` | `""` | 解释为什么拒绝工具的消息 |
1130| `interrupt` | `bool` | `False` | 是否中断当前执行 |
1131
1132### `PermissionUpdate`
1133
1134用于以编程方式更新权限的配置。
1135
1136```python theme={null}
1137@dataclass
1138class PermissionUpdate:
1139 type: Literal[
1140 "addRules",
1141 "replaceRules",
1142 "removeRules",
1143 "setMode",
1144 "addDirectories",
1145 "removeDirectories",
1146 ]
1147 rules: list[PermissionRuleValue] | None = None
1148 behavior: Literal["allow", "deny", "ask"] | None = None
1149 mode: PermissionMode | None = None
1150 directories: list[str] | None = None
1151 destination: (
1152 Literal["userSettings", "projectSettings", "localSettings", "session"] | None
1153 ) = None
1154```
1155
1156| 字段 | 类型 | 描述 |
1157| :------------ | :---------------------------------------- | :-------------- |
1158| `type` | `Literal[...]` | 权限更新操作的类型 |
1159| `rules` | `list[PermissionRuleValue] \| None` | 用于添加/替换/移除操作的规则 |
1160| `behavior` | `Literal["allow", "deny", "ask"] \| None` | 基于规则的操作的行为 |
1161| `mode` | `PermissionMode \| None` | setMode 操作的模式 |
1162| `directories` | `list[str] \| None` | 用于添加/移除目录操作的目录 |
1163| `destination` | `Literal[...] \| None` | 应用权限更新的位置 |
1164
1165### `PermissionRuleValue`
1166
1167要在权限更新中添加、替换或移除的规则。
1168
1169```python theme={null}
1170@dataclass
1171class PermissionRuleValue:
1172 tool_name: str
1173 rule_content: str | None = None
1174```
1175
1176### `ToolsPreset`
1177
1178使用 Claude Code 的默认工具集的预设工具配置。
1179
1180```python theme={null}
1181class ToolsPreset(TypedDict):
1182 type: Literal["preset"]
1183 preset: Literal["claude_code"]
1184```
1185
1186### `ThinkingConfig`
1187
1188控制扩展思考行为。三种配置的联合:
1189
1190```python theme={null}
1191class ThinkingConfigAdaptive(TypedDict):
1192 type: Literal["adaptive"]
1193
1194
1195class ThinkingConfigEnabled(TypedDict):
1196 type: Literal["enabled"]
1197 budget_tokens: int
1198
1199
1200class ThinkingConfigDisabled(TypedDict):
1201 type: Literal["disabled"]
1202
1203
1204ThinkingConfig = ThinkingConfigAdaptive | ThinkingConfigEnabled | ThinkingConfigDisabled
1205```
1206
1207| 变体 | 字段 | 描述 |
1208| :--------- | :---------------------- | :--------------- |
1209| `adaptive` | `type` | Claude 自适应决定何时思考 |
1210| `enabled` | `type`, `budget_tokens` | 启用具有特定令牌预算的思考 |
1211| `disabled` | `type` | 禁用思考 |
1212
1213因为这些是 `TypedDict` 类,它们在运行时是普通字典。要么将它们构造为字典字面量,要么调用类作为构造函数;两者都产生 `dict`。使用 `config["budget_tokens"]` 访问字段,而不是 `config.budget_tokens`:
1214
1215```python theme={null}
1216from claude_agent_sdk import ClaudeAgentOptions, ThinkingConfigEnabled
1217
1218# Option 1: dict literal (recommended, no import needed)
1219options = ClaudeAgentOptions(thinking={"type": "enabled", "budget_tokens": 20000})
1220
1221# Option 2: constructor-style (returns a plain dict)
1222config = ThinkingConfigEnabled(type="enabled", budget_tokens=20000)
1223print(config["budget_tokens"]) # 20000
1224# config.budget_tokens would raise AttributeError
1225```
1226
1227### `SdkBeta`
1228
1229SDK 测试功能的字面类型。
1230
1231```python theme={null}
1232SdkBeta = Literal["context-1m-2025-08-07"]
1233```
1234
1235与 `ClaudeAgentOptions` 中的 `betas` 字段一起使用以启用测试功能。
1236
1237<Warning>
1238 `context-1m-2025-08-07` 测试版自 2026 年 4 月 30 日起已停用。使用 Claude Sonnet 4.5 或 Sonnet 4 传递此标头无效,超过标准 200k 令牌上下文窗口的请求返回错误。要使用 1M 令牌上下文窗口,请迁移到 [Claude Sonnet 4.6、Claude Opus 4.6 或 Claude Opus 4.7](https://platform.claude.com/docs/en/about-claude/models/overview),它们以标准定价包括 1M 上下文,无需测试版标头。
1239</Warning>
1240
1241### `McpSdkServerConfig`
1242
1243使用 `create_sdk_mcp_server()` 创建的 SDK MCP 服务器的配置。
1244
1245```python theme={null}
1246class McpSdkServerConfig(TypedDict):
1247 type: Literal["sdk"]
1248 name: str
1249 instance: Any # MCP Server instance
1250```
1251
1252### `McpServerConfig`
1253
1254MCP 服务器配置的联合类型。
1255
1256```python theme={null}
1257McpServerConfig = (
1258 McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig
1259)
1260```
1261
1262#### `McpStdioServerConfig`
1263
1264```python theme={null}
1265class McpStdioServerConfig(TypedDict):
1266 type: NotRequired[Literal["stdio"]] # Optional for backwards compatibility
1267 command: str
1268 args: NotRequired[list[str]]
1269 env: NotRequired[dict[str, str]]
1270```
1271
1272#### `McpSSEServerConfig`
1273
1274```python theme={null}
1275class McpSSEServerConfig(TypedDict):
1276 type: Literal["sse"]
1277 url: str
1278 headers: NotRequired[dict[str, str]]
1279```
1280
1281#### `McpHttpServerConfig`
1282
1283```python theme={null}
1284class McpHttpServerConfig(TypedDict):
1285 type: Literal["http"]
1286 url: str
1287 headers: NotRequired[dict[str, str]]
1288```
1289
1290### `McpServerStatusConfig`
1291
1292由 [`get_mcp_status()`](#methods) 报告的 MCP 服务器的配置。这是所有 [`McpServerConfig`](#mcp-server-config) 传输变体加上用于通过 claude.ai 代理的服务器的仅输出 `claudeai-proxy` 变体的联合。
1293
1294```python theme={null}
1295McpServerStatusConfig = (
1296 McpStdioServerConfig
1297 | McpSSEServerConfig
1298 | McpHttpServerConfig
1299 | McpSdkServerConfigStatus
1300 | McpClaudeAIProxyServerConfig
1301)
1302```
1303
1304`McpSdkServerConfigStatus` 是 [`McpSdkServerConfig`](#mcp-sdk-server-config) 的可序列化形式,仅包含 `type`(`"sdk"`)和 `name`(`str`)字段;进程内 `instance` 被省略。`McpClaudeAIProxyServerConfig` 具有 `type`(`"claudeai-proxy"`)、`url`(`str`)和 `id`(`str`)字段。
1305
1306### `McpStatusResponse`
1307
1308来自 [`ClaudeSDKClient.get_mcp_status()`](#methods) 的响应。在 `mcpServers` 键下包装服务器状态列表。
1309
1310```python theme={null}
1311class McpStatusResponse(TypedDict):
1312 mcpServers: list[McpServerStatus]
1313```
1314
1315### `McpServerStatus`
1316
1317连接的 MCP 服务器的状态,包含在 [`McpStatusResponse`](#mcp-status-response) 中。
1318
1319```python theme={null}
1320class McpServerStatus(TypedDict):
1321 name: str
1322 status: McpServerConnectionStatus # "connected" | "failed" | "needs-auth" | "pending" | "disabled"
1323 serverInfo: NotRequired[McpServerInfo]
1324 error: NotRequired[str]
1325 config: NotRequired[McpServerStatusConfig]
1326 scope: NotRequired[str]
1327 tools: NotRequired[list[McpToolInfo]]
1328```
1329
1330| 字段 | 类型 | 描述 |
1331| :----------- | :------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------- |
1332| `name` | `str` | 服务器名称 |
1333| `status` | `str` | `"connected"`、`"failed"`、`"needs-auth"`、`"pending"` 或 `"disabled"` 之一 |
1334| `serverInfo` | `dict`(可选) | 服务器名称和版本(`{"name": str, "version": str}`) |
1335| `error` | `str`(可选) | 服务器连接失败时的错误消息 |
1336| `config` | [`McpServerStatusConfig`](#mcp-server-status-config)(可选) | 服务器配置。与 [`McpServerConfig`](#mcp-server-config) 形状相同(stdio、SSE、HTTP 或 SDK),加上通过 claude.ai 连接的服务器的 `claudeai-proxy` 变体 |
1337| `scope` | `str`(可选) | 配置范围 |
1338| `tools` | `list`(可选) | 此服务器提供的工具,每个都有 `name`、`description` 和 `annotations` 字段 |
1339
1340### `SdkPluginConfig`
1341
1342SDK 中加载插件的配置。
1343
1344```python theme={null}
1345class SdkPluginConfig(TypedDict):
1346 type: Literal["local"]
1347 path: str
1348```
1349
1350| 字段 | 类型 | 描述 |
1351| :----- | :----------------- | :----------------------- |
1352| `type` | `Literal["local"]` | 必须是 `"local"`(目前仅支持本地插件) |
1353| `path` | `str` | 插件目录的绝对或相对路径 |
1354
1355**示例:**
1356
1357```python theme={null}
1358plugins = [
1359 {"type": "local", "path": "./my-plugin"},
1360 {"type": "local", "path": "/absolute/path/to/plugin"},
1361]
1362```
1363
1364有关创建和使用插件的完整信息,见 [Plugins](/zh-CN/agent-sdk/plugins)。
1365
1366## 消息类型
1367
1368### `Message`
1369
1370所有可能消息的联合类型。
1371
1372```python theme={null}
1373Message = (
1374 UserMessage
1375 | AssistantMessage
1376 | SystemMessage
1377 | ResultMessage
1378 | StreamEvent
1379 | RateLimitEvent
1380)
1381```
1382
1383### `UserMessage`
1384
1385用户输入消息。
1386
1387```python theme={null}
1388@dataclass
1389class UserMessage:
1390 content: str | list[ContentBlock]
1391 uuid: str | None = None
1392 parent_tool_use_id: str | None = None
1393 tool_use_result: dict[str, Any] | None = None
1394```
1395
1396| 字段 | 类型 | 描述 |
1397| :------------------- | :-------------------------- | :--------------------- |
1398| `content` | `str \| list[ContentBlock]` | 消息内容为文本或内容块 |
1399| `uuid` | `str \| None` | 唯一消息标识符 |
1400| `parent_tool_use_id` | `str \| None` | 如果此消息是工具结果响应,则为工具使用 ID |
1401| `tool_use_result` | `dict[str, Any] \| None` | 工具结果数据(如果适用) |
1402
1403### `AssistantMessage`
1404
1405带有内容块的助手响应消息。
1406
1407```python theme={null}
1408@dataclass
1409class AssistantMessage:
1410 content: list[ContentBlock]
1411 model: str
1412 parent_tool_use_id: str | None = None
1413 error: AssistantMessageError | None = None
1414 usage: dict[str, Any] | None = None
1415 message_id: str | None = None
1416```
1417
1418| 字段 | 类型 | 描述 |
1419| :------------------- | :------------------------------------------------------------- | :----------------------------------------------------------- |
1420| `content` | `list[ContentBlock]` | 响应中的内容块列表 |
1421| `model` | `str` | 生成响应的模型 |
1422| `parent_tool_use_id` | `str \| None` | 如果这是嵌套响应,则为工具使用 ID |
1423| `error` | [`AssistantMessageError`](#assistant-message-error) ` \| None` | 如果响应遇到错误,则为错误类型 |
1424| `usage` | `dict[str, Any] \| None` | 每条消息的令牌使用情况(与 [`ResultMessage.usage`](#result-message) 相同的键) |
1425| `message_id` | `str \| None` | API 消息 ID。来自一个轮次的多条消息共享相同的 ID |
1426
1427### `AssistantMessageError`
1428
1429助手消息的可能错误类型。
1430
1431```python theme={null}
1432AssistantMessageError = Literal[
1433 "authentication_failed",
1434 "billing_error",
1435 "rate_limit",
1436 "invalid_request",
1437 "server_error",
1438 "max_output_tokens",
1439 "unknown",
1440]
1441```
1442
1443### `SystemMessage`
1444
1445带有元数据的系统消息。
1446
1447```python theme={null}
1448@dataclass
1449class SystemMessage:
1450 subtype: str
1451 data: dict[str, Any]
1452```
1453
1454### `ResultMessage`
1455
1456带有成本和使用信息的最终结果消息。
1457
1458```python theme={null}
1459@dataclass
1460class ResultMessage:
1461 subtype: str
1462 duration_ms: int
1463 duration_api_ms: int
1464 is_error: bool
1465 num_turns: int
1466 session_id: str
1467 total_cost_usd: float | None = None
1468 usage: dict[str, Any] | None = None
1469 result: str | None = None
1470 stop_reason: str | None = None
1471 structured_output: Any = None
1472 model_usage: dict[str, Any] | None = None
1473```
1474
1475`usage` 字典在存在时包含以下键:
1476
1477| 键 | 类型 | 描述 |
1478| ----------------------------- | ----- | ------------- |
1479| `input_tokens` | `int` | 消耗的总输入令牌。 |
1480| `output_tokens` | `int` | 生成的总输出令牌。 |
1481| `cache_creation_input_tokens` | `int` | 用于创建新缓存条目的令牌。 |
1482| `cache_read_input_tokens` | `int` | 从现有缓存条目读取的令牌。 |
1483
1484`model_usage` 字典将模型名称映射到每个模型的使用情况。内部字典键使用 camelCase,因为该值从底层 CLI 进程未修改地传递,匹配 TypeScript [`ModelUsage`](/zh-CN/agent-sdk/typescript#model-usage) 类型:
1485
1486| 键 | 类型 | 描述 |
1487| -------------------------- | ------- | ------------------------------------------------------------------------ |
1488| `inputTokens` | `int` | 此模型的输入令牌。 |
1489| `outputTokens` | `int` | 此模型的输出令牌。 |
1490| `cacheReadInputTokens` | `int` | 此模型的缓存读取令牌。 |
1491| `cacheCreationInputTokens` | `int` | 此模型的缓存创建令牌。 |
1492| `webSearchRequests` | `int` | 此模型进行的网络搜索请求。 |
1493| `costUSD` | `float` | 此模型的估计成本(美元),客户端计算。见 [跟踪成本和使用](/zh-CN/agent-sdk/cost-tracking) 了解计费注意事项。 |
1494| `contextWindow` | `int` | 此模型的上下文窗口大小。 |
1495| `maxOutputTokens` | `int` | 此模型的最大输出令牌限制。 |
1496
1497### `StreamEvent`
1498
1499流式事件,用于流式传输期间的部分消息更新。仅在 `ClaudeAgentOptions` 中 `include_partial_messages=True` 时接收。通过 `from claude_agent_sdk.types import StreamEvent` 导入。
1500
1501```python theme={null}
1502@dataclass
1503class StreamEvent:
1504 uuid: str
1505 session_id: str
1506 event: dict[str, Any] # The raw Claude API stream event
1507 parent_tool_use_id: str | None = None
1508```
1509
1510| 字段 | 类型 | 描述 |
1511| :------------------- | :--------------- | :-------------------- |
1512| `uuid` | `str` | 此事件的唯一标识符 |
1513| `session_id` | `str` | 会话标识符 |
1514| `event` | `dict[str, Any]` | 原始 Claude API 流事件数据 |
1515| `parent_tool_use_id` | `str \| None` | 如果此事件来自子代理,则为父工具使用 ID |
1516
1517### `RateLimitEvent`
1518
1519当速率限制状态更改时发出(例如,从 `"allowed"` 到 `"allowed_warning"`)。使用此来在用户达到硬限制之前警告他们,或在状态为 `"rejected"` 时退避。
1520
1521```python theme={null}
1522@dataclass
1523class RateLimitEvent:
1524 rate_limit_info: RateLimitInfo
1525 uuid: str
1526 session_id: str
1527```
1528
1529| 字段 | 类型 | 描述 |
1530| :---------------- | :---------------------------------- | :------- |
1531| `rate_limit_info` | [`RateLimitInfo`](#rate-limit-info) | 当前速率限制状态 |
1532| `uuid` | `str` | 唯一事件标识符 |
1533| `session_id` | `str` | 会话标识符 |
1534
1535### `RateLimitInfo`
1536
1537由 [`RateLimitEvent`](#rate-limit-event) 携带的速率限制状态。
1538
1539```python theme={null}
1540RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]
1541RateLimitType = Literal[
1542 "five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet", "overage"
1543]
1544
1545
1546@dataclass
1547class RateLimitInfo:
1548 status: RateLimitStatus
1549 resets_at: int | None = None
1550 rate_limit_type: RateLimitType | None = None
1551 utilization: float | None = None
1552 overage_status: RateLimitStatus | None = None
1553 overage_resets_at: int | None = None
1554 overage_disabled_reason: str | None = None
1555 raw: dict[str, Any] = field(default_factory=dict)
1556```
1557
1558| 字段 | 类型 | 描述 |
1559| :------------------------ | :------------------------ | :-------------------------------------------------- |
1560| `status` | `RateLimitStatus` | 当前状态。`"allowed_warning"` 表示接近限制;`"rejected"` 表示达到限制 |
1561| `resets_at` | `int \| None` | 速率限制窗口重置的 Unix 时间戳 |
1562| `rate_limit_type` | `RateLimitType \| None` | 哪个速率限制窗口适用 |
1563| `utilization` | `float \| None` | 消耗的速率限制的分数(0.0 到 1.0) |
1564| `overage_status` | `RateLimitStatus \| None` | 按需付费超额使用的状态(如果适用) |
1565| `overage_resets_at` | `int \| None` | 超额窗口重置的 Unix 时间戳 |
1566| `overage_disabled_reason` | `str \| None` | 为什么超额不可用,如果状态为 `"rejected"` |
1567| `raw` | `dict[str, Any]` | 来自 CLI 的完整原始字典,包括上面未建模的字段 |
1568
1569### `TaskStartedMessage`
1570
1571当后台任务启动时发出。后台任务是在主轮次之外跟踪的任何内容:后台 Bash 命令、[Monitor](#monitor) 监视、通过 Agent 工具生成的子代理或远程代理。`task_type` 字段告诉你是哪一个。此命名与 `Task` 到 `Agent` 工具重命名无关。
1572
1573```python theme={null}
1574@dataclass
1575class TaskStartedMessage(SystemMessage):
1576 task_id: str
1577 description: str
1578 uuid: str
1579 session_id: str
1580 tool_use_id: str | None = None
1581 task_type: str | None = None
1582```
1583
1584| 字段 | 类型 | 描述 |
1585| :------------ | :------------ | :------------------------------------------------------------------------------ |
1586| `task_id` | `str` | 任务的唯一标识符 |
1587| `description` | `str` | 任务的描述 |
1588| `uuid` | `str` | 唯一消息标识符 |
1589| `session_id` | `str` | 会话标识符 |
1590| `tool_use_id` | `str \| None` | 关联的工具使用 ID |
1591| `task_type` | `str \| None` | 哪种后台任务:`"local_bash"` 用于后台 Bash 和 Monitor 监视,`"local_agent"` 或 `"remote_agent"` |
1592
1593### `TaskUsage`
1594
1595后台任务的令牌和计时数据。
1596
1597```python theme={null}
1598class TaskUsage(TypedDict):
1599 total_tokens: int
1600 tool_uses: int
1601 duration_ms: int
1602```
1603
1604### `TaskProgressMessage`
1605
1606定期为运行的后台任务发出进度更新。
1607
1608```python theme={null}
1609@dataclass
1610class TaskProgressMessage(SystemMessage):
1611 task_id: str
1612 description: str
1613 usage: TaskUsage
1614 uuid: str
1615 session_id: str
1616 tool_use_id: str | None = None
1617 last_tool_name: str | None = None
1618```
1619
1620| 字段 | 类型 | 描述 |
1621| :--------------- | :------------ | :------------- |
1622| `task_id` | `str` | 任务的唯一标识符 |
1623| `description` | `str` | 当前状态描述 |
1624| `usage` | `TaskUsage` | 此任务迄今为止的令牌使用情况 |
1625| `uuid` | `str` | 唯一消息标识符 |
1626| `session_id` | `str` | 会话标识符 |
1627| `tool_use_id` | `str \| None` | 关联的工具使用 ID |
1628| `last_tool_name` | `str \| None` | 任务使用的最后一个工具的名称 |
1629
1630### `TaskNotificationMessage`
1631
1632当后台任务完成、失败或停止时发出。后台任务包括 `run_in_background` Bash 命令、Monitor 监视和后台子代理。
1633
1634```python theme={null}
1635@dataclass
1636class TaskNotificationMessage(SystemMessage):
1637 task_id: str
1638 status: TaskNotificationStatus # "completed" | "failed" | "stopped"
1639 output_file: str
1640 summary: str
1641 uuid: str
1642 session_id: str
1643 tool_use_id: str | None = None
1644 usage: TaskUsage | None = None
1645```
1646
1647| 字段 | 类型 | 描述 |
1648| :------------ | :----------------------- | :---------------------------------------- |
1649| `task_id` | `str` | 任务的唯一标识符 |
1650| `status` | `TaskNotificationStatus` | `"completed"`、`"failed"` 或 `"stopped"` 之一 |
1651| `output_file` | `str` | 任务输出文件的路径 |
1652| `summary` | `str` | 任务结果的摘要 |
1653| `uuid` | `str` | 唯一消息标识符 |
1654| `session_id` | `str` | 会话标识符 |
1655| `tool_use_id` | `str \| None` | 关联的工具使用 ID |
1656| `usage` | `TaskUsage \| None` | 任务的最终令牌使用情况 |
1657
1658## 内容块类型
1659
1660### `ContentBlock`
1661
1662所有内容块的联合类型。
1663
1664```python theme={null}
1665ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
1666```
1667
1668### `TextBlock`
1669
1670文本内容块。
1671
1672```python theme={null}
1673@dataclass
1674class TextBlock:
1675 text: str
1676```
1677
1678### `ThinkingBlock`
1679
1680思考内容块(用于具有思考能力的模型)。
1681
1682```python theme={null}
1683@dataclass
1684class ThinkingBlock:
1685 thinking: str
1686 signature: str
1687```
1688
1689### `ToolUseBlock`
1690
1691工具使用请求块。
1692
1693```python theme={null}
1694@dataclass
1695class ToolUseBlock:
1696 id: str
1697 name: str
1698 input: dict[str, Any]
1699```
1700
1701### `ToolResultBlock`
1702
1703工具执行结果块。
1704
1705```python theme={null}
1706@dataclass
1707class ToolResultBlock:
1708 tool_use_id: str
1709 content: str | list[dict[str, Any]] | None = None
1710 is_error: bool | None = None
1711```
1712
1713## 错误类型
1714
1715### `ClaudeSDKError`
1716
1717所有 SDK 错误的基础异常类。
1718
1719```python theme={null}
1720class ClaudeSDKError(Exception):
1721 """Base error for Claude SDK."""
1722```
1723
1724### `CLINotFoundError`
1725
1726当 Claude Code CLI 未安装或找不到时引发。
1727
1728```python theme={null}
1729class CLINotFoundError(CLIConnectionError):
1730 def __init__(
1731 self, message: str = "Claude Code not found", cli_path: str | None = None
1732 ):
1733 """
1734 Args:
1735 message: Error message (default: "Claude Code not found")
1736 cli_path: Optional path to the CLI that was not found
1737 """
1738```
1739
1740### `CLIConnectionError`
1741
1742当连接到 Claude Code 失败时引发。
1743
1744```python theme={null}
1745class CLIConnectionError(ClaudeSDKError):
1746 """Failed to connect to Claude Code."""
1747```
1748
1749### `ProcessError`
1750
1751当 Claude Code 进程失败时引发。
1752
1753```python theme={null}
1754class ProcessError(ClaudeSDKError):
1755 def __init__(
1756 self, message: str, exit_code: int | None = None, stderr: str | None = None
1757 ):
1758 self.exit_code = exit_code
1759 self.stderr = stderr
1760```
1761
1762### `CLIJSONDecodeError`
1763
1764当 JSON 解析失败时引发。
1765
1766```python theme={null}
1767class CLIJSONDecodeError(ClaudeSDKError):
1768 def __init__(self, line: str, original_error: Exception):
1769 """
1770 Args:
1771 line: The line that failed to parse
1772 original_error: The original JSON decode exception
1773 """
1774 self.line = line
1775 self.original_error = original_error
1776```
1777
1778## Hook 类型
1779
1780有关使用 hooks 的综合指南,包括示例和常见模式,见 [Hooks 指南](/zh-CN/agent-sdk/hooks)。
1781
1782### `HookEvent`
1783
1784支持的 hook 事件类型。
1785
1786```python theme={null}
1787HookEvent = Literal[
1788 "PreToolUse", # Called before tool execution
1789 "PostToolUse", # Called after tool execution
1790 "PostToolUseFailure", # Called when a tool execution fails
1791 "UserPromptSubmit", # Called when user submits a prompt
1792 "Stop", # Called when stopping execution
1793 "SubagentStop", # Called when a subagent stops
1794 "PreCompact", # Called before message compaction
1795 "Notification", # Called for notification events
1796 "SubagentStart", # Called when a subagent starts
1797 "PermissionRequest", # Called when a permission decision is needed
1798]
1799```
1800
1801<Note>
1802 TypeScript SDK 支持 Python 中尚未提供的其他 hook 事件:`SessionStart`、`SessionEnd`、`Setup`、`TeammateIdle`、`TaskCompleted`、`ConfigChange`、`WorktreeCreate`、`WorktreeRemove` 和 `PostToolBatch`。
1803</Note>
1804
1805### `HookCallback`
1806
1807hook 回调函数的类型定义。
1808
1809```python theme={null}
1810HookCallback = Callable[[HookInput, str | None, HookContext], Awaitable[HookJSONOutput]]
1811```
1812
1813参数:
1814
1815* `input`:强类型 hook 输入,具有基于 `hook_event_name` 的判别联合(见 [`HookInput`](#hook-input))
1816* `tool_use_id`:可选工具使用标识符(用于工具相关的 hooks)
1817* `context`:带有附加信息的 hook 上下文
1818
1819返回可能包含以下内容的 [`HookJSONOutput`](#hook-json-output):
1820
1821* `decision`:`"block"` 以阻止操作
1822* `systemMessage`:要添加到记录的系统消息
1823* `hookSpecificOutput`:hook 特定的输出数据
1824
1825### `HookContext`
1826
1827传递给 hook 回调的上下文信息。
1828
1829```python theme={null}
1830class HookContext(TypedDict):
1831 signal: Any | None # Future: abort signal support
1832```
1833
1834### `HookMatcher`
1835
1836用于将 hooks 匹配到特定事件或工具的配置。
1837
1838```python theme={null}
1839@dataclass
1840class HookMatcher:
1841 matcher: str | None = (
1842 None # Tool name or pattern to match (e.g., "Bash", "Write|Edit")
1843 )
1844 hooks: list[HookCallback] = field(
1845 default_factory=list
1846 ) # List of callbacks to execute
1847 timeout: float | None = (
1848 None # Timeout in seconds for all hooks in this matcher (default: 60)
1849 )
1850```
1851
1852### `HookInput`
1853
1854所有 hook 输入类型的联合类型。实际类型取决于 `hook_event_name` 字段。
1855
1856```python theme={null}
1857HookInput = (
1858 PreToolUseHookInput
1859 | PostToolUseHookInput
1860 | PostToolUseFailureHookInput
1861 | UserPromptSubmitHookInput
1862 | StopHookInput
1863 | SubagentStopHookInput
1864 | PreCompactHookInput
1865 | NotificationHookInput
1866 | SubagentStartHookInput
1867 | PermissionRequestHookInput
1868)
1869```
1870
1871### `BaseHookInput`
1872
1873所有 hook 输入类型中存在的基础字段。
1874
1875```python theme={null}
1876class BaseHookInput(TypedDict):
1877 session_id: str
1878 transcript_path: str
1879 cwd: str
1880 permission_mode: NotRequired[str]
1881```
1882
1883| 字段 | 类型 | 描述 |
1884| :---------------- | :-------- | :-------- |
1885| `session_id` | `str` | 当前会话标识符 |
1886| `transcript_path` | `str` | 会话记录文件的路径 |
1887| `cwd` | `str` | 当前工作目录 |
1888| `permission_mode` | `str`(可选) | 当前权限模式 |
1889
1890### `PreToolUseHookInput`
1891
1892`PreToolUse` hook 事件的输入数据。
1893
1894```python theme={null}
1895class PreToolUseHookInput(BaseHookInput):
1896 hook_event_name: Literal["PreToolUse"]
1897 tool_name: str
1898 tool_input: dict[str, Any]
1899 tool_use_id: str
1900 agent_id: NotRequired[str]
1901 agent_type: NotRequired[str]
1902```
1903
1904| 字段 | 类型 | 描述 |
1905| :---------------- | :---------------------- | :----------------------- |
1906| `hook_event_name` | `Literal["PreToolUse"]` | 始终为 "PreToolUse" |
1907| `tool_name` | `str` | 即将执行的工具的名称 |
1908| `tool_input` | `dict[str, Any]` | 工具的输入参数 |
1909| `tool_use_id` | `str` | 此工具使用的唯一标识符 |
1910| `agent_id` | `str`(可选) | 子代理标识符,当 hook 在子代理内触发时存在 |
1911| `agent_type` | `str`(可选) | 子代理类型,当 hook 在子代理内触发时存在 |
1912
1913### `PostToolUseHookInput`
1914
1915`PostToolUse` hook 事件的输入数据。
1916
1917```python theme={null}
1918class PostToolUseHookInput(BaseHookInput):
1919 hook_event_name: Literal["PostToolUse"]
1920 tool_name: str
1921 tool_input: dict[str, Any]
1922 tool_response: Any
1923 tool_use_id: str
1924 agent_id: NotRequired[str]
1925 agent_type: NotRequired[str]
1926```
1927
1928| 字段 | 类型 | 描述 |
1929| :---------------- | :----------------------- | :----------------------- |
1930| `hook_event_name` | `Literal["PostToolUse"]` | 始终为 "PostToolUse" |
1931| `tool_name` | `str` | 已执行的工具的名称 |
1932| `tool_input` | `dict[str, Any]` | 使用的输入参数 |
1933| `tool_response` | `Any` | 工具执行的响应 |
1934| `tool_use_id` | `str` | 此工具使用的唯一标识符 |
1935| `agent_id` | `str`(可选) | 子代理标识符,当 hook 在子代理内触发时存在 |
1936| `agent_type` | `str`(可选) | 子代理类型,当 hook 在子代理内触发时存在 |
1937
1938### `PostToolUseFailureHookInput`
1939
1940`PostToolUseFailure` hook 事件的输入数据。当工具执行失败时调用。
1941
1942```python theme={null}
1943class PostToolUseFailureHookInput(BaseHookInput):
1944 hook_event_name: Literal["PostToolUseFailure"]
1945 tool_name: str
1946 tool_input: dict[str, Any]
1947 tool_use_id: str
1948 error: str
1949 is_interrupt: NotRequired[bool]
1950 agent_id: NotRequired[str]
1951 agent_type: NotRequired[str]
1952```
1953
1954| 字段 | 类型 | 描述 |
1955| :---------------- | :------------------------------ | :----------------------- |
1956| `hook_event_name` | `Literal["PostToolUseFailure"]` | 始终为 "PostToolUseFailure" |
1957| `tool_name` | `str` | 失败的工具的名称 |
1958| `tool_input` | `dict[str, Any]` | 使用的输入参数 |
1959| `tool_use_id` | `str` | 此工具使用的唯一标识符 |
1960| `error` | `str` | 失败执行的错误消息 |
1961| `is_interrupt` | `bool`(可选) | 失败是否由中断引起 |
1962| `agent_id` | `str`(可选) | 子代理标识符,当 hook 在子代理内触发时存在 |
1963| `agent_type` | `str`(可选) | 子代理类型,当 hook 在子代理内触发时存在 |
1964
1965### `UserPromptSubmitHookInput`
1966
1967`UserPromptSubmit` hook 事件的输入数据。
1968
1969```python theme={null}
1970class UserPromptSubmitHookInput(BaseHookInput):
1971 hook_event_name: Literal["UserPromptSubmit"]
1972 prompt: str
1973```
1974
1975| 字段 | 类型 | 描述 |
1976| :---------------- | :---------------------------- | :--------------------- |
1977| `hook_event_name` | `Literal["UserPromptSubmit"]` | 始终为 "UserPromptSubmit" |
1978| `prompt` | `str` | 用户提交的提示 |
1979
1980### `StopHookInput`
1981
1982`Stop` hook 事件的输入数据。
1983
1984```python theme={null}
1985class StopHookInput(BaseHookInput):
1986 hook_event_name: Literal["Stop"]
1987 stop_hook_active: bool
1988```
1989
1990| 字段 | 类型 | 描述 |
1991| :----------------- | :---------------- | :------------- |
1992| `hook_event_name` | `Literal["Stop"]` | 始终为 "Stop" |
1993| `stop_hook_active` | `bool` | stop hook 是否活跃 |
1994
1995### `SubagentStopHookInput`
1996
1997`SubagentStop` hook 事件的输入数据。
1998
1999```python theme={null}
2000class SubagentStopHookInput(BaseHookInput):
2001 hook_event_name: Literal["SubagentStop"]
2002 stop_hook_active: bool
2003 agent_id: str
2004 agent_transcript_path: str
2005 agent_type: str
2006```
2007
2008| 字段 | 类型 | 描述 |
2009| :---------------------- | :------------------------ | :----------------- |
2010| `hook_event_name` | `Literal["SubagentStop"]` | 始终为 "SubagentStop" |
2011| `stop_hook_active` | `bool` | stop hook 是否活跃 |
2012| `agent_id` | `str` | 子代理的唯一标识符 |
2013| `agent_transcript_path` | `str` | 子代理的记录文件路径 |
2014| `agent_type` | `str` | 子代理的类型 |
2015
2016### `PreCompactHookInput`
2017
2018`PreCompact` hook 事件的输入数据。
2019
2020```python theme={null}
2021class PreCompactHookInput(BaseHookInput):
2022 hook_event_name: Literal["PreCompact"]
2023 trigger: Literal["manual", "auto"]
2024 custom_instructions: str | None
2025```
2026
2027| 字段 | 类型 | 描述 |
2028| :-------------------- | :-------------------------- | :--------------- |
2029| `hook_event_name` | `Literal["PreCompact"]` | 始终为 "PreCompact" |
2030| `trigger` | `Literal["manual", "auto"]` | 什么触发了压缩 |
2031| `custom_instructions` | `str \| None` | 压缩的自定义说明 |
2032
2033### `NotificationHookInput`
2034
2035`Notification` hook 事件的输入数据。
2036
2037```python theme={null}
2038class NotificationHookInput(BaseHookInput):
2039 hook_event_name: Literal["Notification"]
2040 message: str
2041 title: NotRequired[str]
2042 notification_type: str
2043```
2044
2045| 字段 | 类型 | 描述 |
2046| :------------------ | :------------------------ | :----------------- |
2047| `hook_event_name` | `Literal["Notification"]` | 始终为 "Notification" |
2048| `message` | `str` | 通知消息内容 |
2049| `title` | `str`(可选) | 通知标题 |
2050| `notification_type` | `str` | 通知类型 |
2051
2052### `SubagentStartHookInput`
2053
2054`SubagentStart` hook 事件的输入数据。
2055
2056```python theme={null}
2057class SubagentStartHookInput(BaseHookInput):
2058 hook_event_name: Literal["SubagentStart"]
2059 agent_id: str
2060 agent_type: str
2061```
2062
2063| 字段 | 类型 | 描述 |
2064| :---------------- | :------------------------- | :------------------ |
2065| `hook_event_name` | `Literal["SubagentStart"]` | 始终为 "SubagentStart" |
2066| `agent_id` | `str` | 子代理的唯一标识符 |
2067| `agent_type` | `str` | 子代理的类型 |
2068
2069### `PermissionRequestHookInput`
2070
2071`PermissionRequest` hook 事件的输入数据。允许 hooks 以编程方式处理权限决策。
2072
2073```python theme={null}
2074class PermissionRequestHookInput(BaseHookInput):
2075 hook_event_name: Literal["PermissionRequest"]
2076 tool_name: str
2077 tool_input: dict[str, Any]
2078 permission_suggestions: NotRequired[list[Any]]
2079```
2080
2081| 字段 | 类型 | 描述 |
2082| :----------------------- | :----------------------------- | :---------------------- |
2083| `hook_event_name` | `Literal["PermissionRequest"]` | 始终为 "PermissionRequest" |
2084| `tool_name` | `str` | 请求权限的工具的名称 |
2085| `tool_input` | `dict[str, Any]` | 工具的输入参数 |
2086| `permission_suggestions` | `list[Any]`(可选) | 来自 CLI 的建议权限更新 |
2087
2088### `HookJSONOutput`
2089
2090hook 回调返回值的联合类型。
2091
2092```python theme={null}
2093HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput
2094```
2095
2096#### `SyncHookJSONOutput`
2097
2098具有控制和决策字段的同步 hook 输出。
2099
2100```python theme={null}
2101class SyncHookJSONOutput(TypedDict):
2102 # Control fields
2103 continue_: NotRequired[bool] # Whether to proceed (default: True)
2104 suppressOutput: NotRequired[bool] # Hide stdout from transcript
2105 stopReason: NotRequired[str] # Message when continue is False
2106
2107 # Decision fields
2108 decision: NotRequired[Literal["block"]]
2109 systemMessage: NotRequired[str] # Warning message for user
2110 reason: NotRequired[str] # Feedback for Claude
2111
2112 # Hook-specific output
2113 hookSpecificOutput: NotRequired[HookSpecificOutput]
2114```
2115
2116<Note>
2117 在 Python 代码中使用 `continue_`(带下划线)。发送到 CLI 时会自动转换为 `continue`。
2118</Note>
2119
2120#### `HookSpecificOutput`
2121
2122包含 hook 事件名称和事件特定字段的 `TypedDict`。形状取决于 `hookEventName` 值。有关每个 hook 事件的可用字段的完整详情,见 [使用 hooks 控制执行](/zh-CN/agent-sdk/hooks#outputs)。
2123
2124事件特定输出类型的判别联合。`hookEventName` 字段确定哪些字段有效。
2125
2126```python theme={null}
2127class PreToolUseHookSpecificOutput(TypedDict):
2128 hookEventName: Literal["PreToolUse"]
2129 permissionDecision: NotRequired[Literal["allow", "deny", "ask"]]
2130 permissionDecisionReason: NotRequired[str]
2131 updatedInput: NotRequired[dict[str, Any]]
2132 additionalContext: NotRequired[str]
2133
2134
2135class PostToolUseHookSpecificOutput(TypedDict):
2136 hookEventName: Literal["PostToolUse"]
2137 additionalContext: NotRequired[str]
2138 updatedMCPToolOutput: NotRequired[Any]
2139
2140
2141class PostToolUseFailureHookSpecificOutput(TypedDict):
2142 hookEventName: Literal["PostToolUseFailure"]
2143 additionalContext: NotRequired[str]
2144
2145
2146class UserPromptSubmitHookSpecificOutput(TypedDict):
2147 hookEventName: Literal["UserPromptSubmit"]
2148 additionalContext: NotRequired[str]
2149
2150
2151class NotificationHookSpecificOutput(TypedDict):
2152 hookEventName: Literal["Notification"]
2153 additionalContext: NotRequired[str]
2154
2155
2156class SubagentStartHookSpecificOutput(TypedDict):
2157 hookEventName: Literal["SubagentStart"]
2158 additionalContext: NotRequired[str]
2159
2160
2161class PermissionRequestHookSpecificOutput(TypedDict):
2162 hookEventName: Literal["PermissionRequest"]
2163 decision: dict[str, Any]
2164
2165
2166HookSpecificOutput = (
2167 PreToolUseHookSpecificOutput
2168 | PostToolUseHookSpecificOutput
2169 | PostToolUseFailureHookSpecificOutput
2170 | UserPromptSubmitHookSpecificOutput
2171 | NotificationHookSpecificOutput
2172 | SubagentStartHookSpecificOutput
2173 | PermissionRequestHookSpecificOutput
2174)
2175```
2176
2177#### `AsyncHookJSONOutput`
2178
2179延迟 hook 执行的异步 hook 输出。
2180
2181```python theme={null}
2182class AsyncHookJSONOutput(TypedDict):
2183 async_: Literal[True] # Set to True to defer execution
2184 asyncTimeout: NotRequired[int] # Timeout in milliseconds
2185```
2186
2187<Note>
2188 在 Python 代码中使用 `async_`(带下划线)。发送到 CLI 时会自动转换为 `async`。
2189</Note>
2190
2191### Hook 使用示例
2192
2193此示例注册两个 hooks:一个阻止危险的 bash 命令(如 `rm -rf /`),另一个记录所有工具使用以进行审计。安全 hook 仅在 Bash 命令上运行(通过 `matcher`),而日志 hook 在所有工具上运行。
2194
2195```python theme={null}
2196from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext
2197from typing import Any
2198
2199
2200async def validate_bash_command(
2201 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2202) -> dict[str, Any]:
2203 """Validate and potentially block dangerous bash commands."""
2204 if input_data["tool_name"] == "Bash":
2205 command = input_data["tool_input"].get("command", "")
2206 if "rm -rf /" in command:
2207 return {
2208 "hookSpecificOutput": {
2209 "hookEventName": "PreToolUse",
2210 "permissionDecision": "deny",
2211 "permissionDecisionReason": "Dangerous command blocked",
2212 }
2213 }
2214 return {}
2215
2216
2217async def log_tool_use(
2218 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2219) -> dict[str, Any]:
2220 """Log all tool usage for auditing."""
2221 print(f"Tool used: {input_data.get('tool_name')}")
2222 return {}
2223
2224
2225options = ClaudeAgentOptions(
2226 hooks={
2227 "PreToolUse": [
2228 HookMatcher(
2229 matcher="Bash", hooks=[validate_bash_command], timeout=120
2230 ), # 2 min for validation
2231 HookMatcher(
2232 hooks=[log_tool_use]
2233 ), # Applies to all tools (default 60s timeout)
2234 ],
2235 "PostToolUse": [HookMatcher(hooks=[log_tool_use])],
2236 }
2237)
2238
2239async for message in query(prompt="Analyze this codebase", options=options):
2240 print(message)
2241```
2242
2243## 工具输入/输出类型
2244
2245所有内置 Claude Code 工具的输入/输出模式文档。虽然 Python SDK 不将这些导出为类型,但它们代表消息中工具输入和输出的结构。
2246
2247### Agent
2248
2249**工具名称:** `Agent`(之前为 `Task`,仍然接受作为别名)
2250
2251**输入:**
2252
2253```python theme={null}
2254{
2255 "description": str, # A short (3-5 word) description of the task
2256 "prompt": str, # The task for the agent to perform
2257 "subagent_type": str, # The type of specialized agent to use
2258}
2259```
2260
2261**输出:**
2262
2263```python theme={null}
2264{
2265 "result": str, # Final result from the subagent
2266 "usage": dict | None, # Token usage statistics
2267 "total_cost_usd": float | None, # Estimated total cost in USD
2268 "duration_ms": int | None, # Execution duration in milliseconds
2269}
2270```
2271
2272### AskUserQuestion
2273
2274**工具名称:** `AskUserQuestion`
2275
2276在执行期间向用户提出澄清问题。见 [处理批准和用户输入](/zh-CN/agent-sdk/user-input#handle-clarifying-questions) 了解使用详情。
2277
2278**输入:**
2279
2280```python theme={null}
2281{
2282 "questions": [ # Questions to ask the user (1-4 questions)
2283 {
2284 "question": str, # The complete question to ask the user
2285 "header": str, # Very short label displayed as a chip/tag (max 12 chars)
2286 "options": [ # The available choices (2-4 options)
2287 {
2288 "label": str, # Display text for this option (1-5 words)
2289 "description": str, # Explanation of what this option means
2290 }
2291 ],
2292 "multiSelect": bool, # Set to true to allow multiple selections
2293 }
2294 ],
2295 "answers": dict | None, # User answers populated by the permission system
2296}
2297```
2298
2299**输出:**
2300
2301```python theme={null}
2302{
2303 "questions": [ # The questions that were asked
2304 {
2305 "question": str,
2306 "header": str,
2307 "options": [{"label": str, "description": str}],
2308 "multiSelect": bool,
2309 }
2310 ],
2311 "answers": dict[str, str], # Maps question text to answer string
2312 # Multi-select answers are comma-separated
2313}
2314```
2315
2316### Bash
2317
2318**工具名称:** `Bash`
2319
2320**输入:**
2321
2322```python theme={null}
2323{
2324 "command": str, # The command to execute
2325 "timeout": int | None, # Optional timeout in milliseconds (max 600000)
2326 "description": str | None, # Clear, concise description (5-10 words)
2327 "run_in_background": bool | None, # Set to true to run in background
2328}
2329```
2330
2331**输出:**
2332
2333```python theme={null}
2334{
2335 "output": str, # Combined stdout and stderr output
2336 "exitCode": int, # Exit code of the command
2337 "killed": bool | None, # Whether command was killed due to timeout
2338 "shellId": str | None, # Shell ID for background processes
2339}
2340```
2341
2342### Monitor
2343
2344**工具名称:** `Monitor`
2345
2346运行后台脚本并将每个 stdout 行作为事件传递给 Claude,以便它可以做出反应而无需轮询。Monitor 遵循与 Bash 相同的权限规则。见 [Monitor 工具参考](/zh-CN/tools-reference#monitor-tool) 了解行为和提供商可用性。
2347
2348**输入:**
2349
2350```python theme={null}
2351{
2352 "command": str, # Shell script; each stdout line is an event, exit ends the watch
2353 "description": str, # Short description shown in notifications
2354 "timeout_ms": int | None, # Kill after this deadline (default 300000, max 3600000)
2355 "persistent": bool | None, # Run for the lifetime of the session; stop with TaskStop
2356}
2357```
2358
2359**输出:**
2360
2361```python theme={null}
2362{
2363 "taskId": str, # ID of the background monitor task
2364 "timeoutMs": int, # Timeout deadline in milliseconds (0 when persistent)
2365 "persistent": bool | None, # True when running until TaskStop or session end
2366}
2367```
2368
2369### Edit
2370
2371**工具名称:** `Edit`
2372
2373**输入:**
2374
2375```python theme={null}
2376{
2377 "file_path": str, # The absolute path to the file to modify
2378 "old_string": str, # The text to replace
2379 "new_string": str, # The text to replace it with
2380 "replace_all": bool | None, # Replace all occurrences (default False)
2381}
2382```
2383
2384**输出:**
2385
2386```python theme={null}
2387{
2388 "message": str, # Confirmation message
2389 "replacements": int, # Number of replacements made
2390 "file_path": str, # File path that was edited
2391}
2392```
2393
2394### Read
2395
2396**工具名称:** `Read`
2397
2398**输入:**
2399
2400```python theme={null}
2401{
2402 "file_path": str, # The absolute path to the file to read
2403 "offset": int | None, # The line number to start reading from
2404 "limit": int | None, # The number of lines to read
2405}
2406```
2407
2408**输出(文本文件):**
2409
2410```python theme={null}
2411{
2412 "content": str, # File contents with line numbers
2413 "total_lines": int, # Total number of lines in file
2414 "lines_returned": int, # Lines actually returned
2415}
2416```
2417
2418**输出(图像):**
2419
2420```python theme={null}
2421{
2422 "image": str, # Base64 encoded image data
2423 "mime_type": str, # Image MIME type
2424 "file_size": int, # File size in bytes
2425}
2426```
2427
2428### Write
2429
2430**工具名称:** `Write`
2431
2432**输入:**
2433
2434```python theme={null}
2435{
2436 "file_path": str, # The absolute path to the file to write
2437 "content": str, # The content to write to the file
2438}
2439```
2440
2441**输出:**
2442
2443```python theme={null}
2444{
2445 "message": str, # Success message
2446 "bytes_written": int, # Number of bytes written
2447 "file_path": str, # File path that was written
2448}
2449```
2450
2451### Glob
2452
2453**工具名称:** `Glob`
2454
2455**输入:**
2456
2457```python theme={null}
2458{
2459 "pattern": str, # The glob pattern to match files against
2460 "path": str | None, # The directory to search in (defaults to cwd)
2461}
2462```
2463
2464**输出:**
2465
2466```python theme={null}
2467{
2468 "matches": list[str], # Array of matching file paths
2469 "count": int, # Number of matches found
2470 "search_path": str, # Search directory used
2471}
2472```
2473
2474### Grep
2475
2476**工具名称:** `Grep`
2477
2478**输入:**
2479
2480```python theme={null}
2481{
2482 "pattern": str, # The regular expression pattern
2483 "path": str | None, # File or directory to search in
2484 "glob": str | None, # Glob pattern to filter files
2485 "type": str | None, # File type to search
2486 "output_mode": str | None, # "content", "files_with_matches", or "count"
2487 "-i": bool | None, # Case insensitive search
2488 "-n": bool | None, # Show line numbers
2489 "-B": int | None, # Lines to show before each match
2490 "-A": int | None, # Lines to show after each match
2491 "-C": int | None, # Lines to show before and after
2492 "head_limit": int | None, # Limit output to first N lines/entries
2493 "multiline": bool | None, # Enable multiline mode
2494}
2495```
2496
2497**输出(content 模式):**
2498
2499```python theme={null}
2500{
2501 "matches": [
2502 {
2503 "file": str,
2504 "line_number": int | None,
2505 "line": str,
2506 "before_context": list[str] | None,
2507 "after_context": list[str] | None,
2508 }
2509 ],
2510 "total_matches": int,
2511}
2512```
2513
2514**输出(files\_with\_matches 模式):**
2515
2516```python theme={null}
2517{
2518 "files": list[str], # Files containing matches
2519 "count": int, # Number of files with matches
2520}
2521```
2522
2523### NotebookEdit
2524
2525**工具名称:** `NotebookEdit`
2526
2527**输入:**
2528
2529```python theme={null}
2530{
2531 "notebook_path": str, # Absolute path to the Jupyter notebook
2532 "cell_id": str | None, # The ID of the cell to edit
2533 "new_source": str, # The new source for the cell
2534 "cell_type": "code" | "markdown" | None, # The type of the cell
2535 "edit_mode": "replace" | "insert" | "delete" | None, # Edit operation type
2536}
2537```
2538
2539**输出:**
2540
2541```python theme={null}
2542{
2543 "message": str, # Success message
2544 "edit_type": "replaced" | "inserted" | "deleted", # Type of edit performed
2545 "cell_id": str | None, # Cell ID that was affected
2546 "total_cells": int, # Total cells in notebook after edit
2547}
2548```
2549
2550### WebFetch
2551
2552**工具名称:** `WebFetch`
2553
2554**输入:**
2555
2556```python theme={null}
2557{
2558 "url": str, # The URL to fetch content from
2559 "prompt": str, # The prompt to run on the fetched content
2560}
2561```
2562
2563**输出:**
2564
2565```python theme={null}
2566{
2567 "response": str, # AI model's response to the prompt
2568 "url": str, # URL that was fetched
2569 "final_url": str | None, # Final URL after redirects
2570 "status_code": int | None, # HTTP status code
2571}
2572```
2573
2574### WebSearch
2575
2576**工具名称:** `WebSearch`
2577
2578**输入:**
2579
2580```python theme={null}
2581{
2582 "query": str, # The search query to use
2583 "allowed_domains": list[str] | None, # Only include results from these domains
2584 "blocked_domains": list[str] | None, # Never include results from these domains
2585}
2586```
2587
2588**输出:**
2589
2590```python theme={null}
2591{
2592 "results": [{"title": str, "url": str, "snippet": str, "metadata": dict | None}],
2593 "total_results": int,
2594 "query": str,
2595}
2596```
2597
2598### TodoWrite
2599
2600**工具名称:** `TodoWrite`
2601
2602**输入:**
2603
2604```python theme={null}
2605{
2606 "todos": [
2607 {
2608 "content": str, # The task description
2609 "status": "pending" | "in_progress" | "completed", # Task status
2610 "activeForm": str, # Active form of the description
2611 }
2612 ]
2613}
2614```
2615
2616**输出:**
2617
2618```python theme={null}
2619{
2620 "message": str, # Success message
2621 "stats": {"total": int, "pending": int, "in_progress": int, "completed": int},
2622}
2623```
2624
2625### BashOutput
2626
2627**工具名称:** `BashOutput`
2628
2629**输入:**
2630
2631```python theme={null}
2632{
2633 "bash_id": str, # The ID of the background shell
2634 "filter": str | None, # Optional regex to filter output lines
2635}
2636```
2637
2638**输出:**
2639
2640```python theme={null}
2641{
2642 "output": str, # New output since last check
2643 "status": "running" | "completed" | "failed", # Current shell status
2644 "exitCode": int | None, # Exit code when completed
2645}
2646```
2647
2648### KillBash
2649
2650**工具名称:** `KillBash`
2651
2652**输入:**
2653
2654```python theme={null}
2655{
2656 "shell_id": str # The ID of the background shell to kill
2657}
2658```
2659
2660**输出:**
2661
2662```python theme={null}
2663{
2664 "message": str, # Success message
2665 "shell_id": str, # ID of the killed shell
2666}
2667```
2668
2669### ExitPlanMode
2670
2671**工具名称:** `ExitPlanMode`
2672
2673**输入:**
2674
2675```python theme={null}
2676{
2677 "plan": str # The plan to run by the user for approval
2678}
2679```
2680
2681**输出:**
2682
2683```python theme={null}
2684{
2685 "message": str, # Confirmation message
2686 "approved": bool | None, # Whether user approved the plan
2687}
2688```
2689
2690### ListMcpResources
2691
2692**工具名称:** `ListMcpResources`
2693
2694**输入:**
2695
2696```python theme={null}
2697{
2698 "server": str | None # Optional server name to filter resources by
2699}
2700```
2701
2702**输出:**
2703
2704```python theme={null}
2705{
2706 "resources": [
2707 {
2708 "uri": str,
2709 "name": str,
2710 "description": str | None,
2711 "mimeType": str | None,
2712 "server": str,
2713 }
2714 ],
2715 "total": int,
2716}
2717```
2718
2719### ReadMcpResource
2720
2721**工具名称:** `ReadMcpResource`
2722
2723**输入:**
2724
2725```python theme={null}
2726{
2727 "server": str, # The MCP server name
2728 "uri": str, # The resource URI to read
2729}
2730```
2731
2732**输出:**
2733
2734```python theme={null}
2735{
2736 "contents": [
2737 {"uri": str, "mimeType": str | None, "text": str | None, "blob": str | None}
2738 ],
2739 "server": str,
2740}
2741```
2742
2743## ClaudeSDKClient 的高级功能
2744
2745### 构建持续对话界面
2746
2747```python theme={null}
2748from claude_agent_sdk import (
2749 ClaudeSDKClient,
2750 ClaudeAgentOptions,
2751 AssistantMessage,
2752 TextBlock,
2753)
2754import asyncio
2755
2756
2757class ConversationSession:
2758 """Maintains a single conversation session with Claude."""
2759
2760 def __init__(self, options: ClaudeAgentOptions | None = None):
2761 self.client = ClaudeSDKClient(options)
2762 self.turn_count = 0
2763
2764 async def start(self):
2765 await self.client.connect()
2766 print("Starting conversation session. Claude will remember context.")
2767 print(
2768 "Commands: 'exit' to quit, 'interrupt' to stop current task, 'new' for new session"
2769 )
2770
2771 while True:
2772 user_input = input(f"\n[Turn {self.turn_count + 1}] You: ")
2773
2774 if user_input.lower() == "exit":
2775 break
2776 elif user_input.lower() == "interrupt":
2777 await self.client.interrupt()
2778 print("Task interrupted!")
2779 continue
2780 elif user_input.lower() == "new":
2781 # Disconnect and reconnect for a fresh session
2782 await self.client.disconnect()
2783 await self.client.connect()
2784 self.turn_count = 0
2785 print("Started new conversation session (previous context cleared)")
2786 continue
2787
2788 # Send message - the session retains all previous messages
2789 await self.client.query(user_input)
2790 self.turn_count += 1
2791
2792 # Process response
2793 print(f"[Turn {self.turn_count}] Claude: ", end="")
2794 async for message in self.client.receive_response():
2795 if isinstance(message, AssistantMessage):
2796 for block in message.content:
2797 if isinstance(block, TextBlock):
2798 print(block.text, end="")
2799 print() # New line after response
2800
2801 await self.client.disconnect()
2802 print(f"Conversation ended after {self.turn_count} turns.")
2803
2804
2805async def main():
2806 options = ClaudeAgentOptions(
2807 allowed_tools=["Read", "Write", "Bash"], permission_mode="acceptEdits"
2808 )
2809 session = ConversationSession(options)
2810 await session.start()
2811
2812
2813# Example conversation:
2814# Turn 1 - You: "Create a file called hello.py"
2815# Turn 1 - Claude: "I'll create a hello.py file for you..."
2816# Turn 2 - You: "What's in that file?"
2817# Turn 2 - Claude: "The hello.py file I just created contains..." (remembers!)
2818# Turn 3 -You: "Add a main function to it"
2819# Turn 3 - Claude: "I'll add a main function to hello.py..." (knows which file!)
2820
2821asyncio.run(main())
2822```
2823
2824### 使用 Hooks 进行行为修改
2825
2826```python theme={null}
2827from claude_agent_sdk import (
2828 ClaudeSDKClient,
2829 ClaudeAgentOptions,
2830 HookMatcher,
2831 HookContext,
2832)
2833import asyncio
2834from typing import Any
2835
2836
2837async def pre_tool_logger(
2838 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2839) -> dict[str, Any]:
2840 """Log all tool usage before execution."""
2841 tool_name = input_data.get("tool_name", "unknown")
2842 print(f"[PRE-TOOL] About to use: {tool_name}")
2843
2844 # You can modify or block the tool execution here
2845 if tool_name == "Bash" and "rm -rf" in str(input_data.get("tool_input", {})):
2846 return {
2847 "hookSpecificOutput": {
2848 "hookEventName": "PreToolUse",
2849 "permissionDecision": "deny",
2850 "permissionDecisionReason": "Dangerous command blocked",
2851 }
2852 }
2853 return {}
2854
2855
2856async def post_tool_logger(
2857 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2858) -> dict[str, Any]:
2859 """Log results after tool execution."""
2860 tool_name = input_data.get("tool_name", "unknown")
2861 print(f"[POST-TOOL] Completed: {tool_name}")
2862 return {}
2863
2864
2865async def user_prompt_modifier(
2866 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2867) -> dict[str, Any]:
2868 """Add context to user prompts."""
2869 original_prompt = input_data.get("prompt", "")
2870
2871 # Add a timestamp as additional context for Claude to see
2872 from datetime import datetime
2873
2874 timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
2875
2876 return {
2877 "hookSpecificOutput": {
2878 "hookEventName": "UserPromptSubmit",
2879 "additionalContext": f"[Submitted at {timestamp}] Original prompt: {original_prompt}",
2880 }
2881 }
2882
2883
2884async def main():
2885 options = ClaudeAgentOptions(
2886 hooks={
2887 "PreToolUse": [
2888 HookMatcher(hooks=[pre_tool_logger]),
2889 HookMatcher(matcher="Bash", hooks=[pre_tool_logger]),
2890 ],
2891 "PostToolUse": [HookMatcher(hooks=[post_tool_logger])],
2892 "UserPromptSubmit": [HookMatcher(hooks=[user_prompt_modifier])],
2893 },
2894 allowed_tools=["Read", "Write", "Bash"],
2895 )
2896
2897 async with ClaudeSDKClient(options=options) as client:
2898 await client.query("List files in current directory")
2899
2900 async for message in client.receive_response():
2901 # Hooks will automatically log tool usage
2902 pass
2903
2904
2905asyncio.run(main())
2906```
2907
2908### 实时进度监控
2909
2910```python theme={null}
2911from claude_agent_sdk import (
2912 ClaudeSDKClient,
2913 ClaudeAgentOptions,
2914 AssistantMessage,
2915 ToolUseBlock,
2916 ToolResultBlock,
2917 TextBlock,
2918)
2919import asyncio
2920
2921
2922async def monitor_progress():
2923 options = ClaudeAgentOptions(
2924 allowed_tools=["Write", "Bash"], permission_mode="acceptEdits"
2925 )
2926
2927 async with ClaudeSDKClient(options=options) as client:
2928 await client.query("Create 5 Python files with different sorting algorithms")
2929
2930 # Monitor progress in real-time
2931 async for message in client.receive_response():
2932 if isinstance(message, AssistantMessage):
2933 for block in message.content:
2934 if isinstance(block, ToolUseBlock):
2935 if block.name == "Write":
2936 file_path = block.input.get("file_path", "")
2937 print(f"Creating: {file_path}")
2938 elif isinstance(block, ToolResultBlock):
2939 print("Completed tool execution")
2940 elif isinstance(block, TextBlock):
2941 print(f"Claude says: {block.text[:100]}...")
2942
2943 print("Task completed!")
2944
2945
2946asyncio.run(monitor_progress())
2947```
2948
2949## 示例用法
2950
2951### 基本文件操作(使用 query)
2952
2953```python theme={null}
2954from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock
2955import asyncio
2956
2957
2958async def create_project():
2959 options = ClaudeAgentOptions(
2960 allowed_tools=["Read", "Write", "Bash"],
2961 permission_mode="acceptEdits",
2962 cwd="/home/user/project",
2963 )
2964
2965 async for message in query(
2966 prompt="Create a Python project structure with setup.py", options=options
2967 ):
2968 if isinstance(message, AssistantMessage):
2969 for block in message.content:
2970 if isinstance(block, ToolUseBlock):
2971 print(f"Using tool: {block.name}")
2972
2973
2974asyncio.run(create_project())
2975```
2976
2977### 错误处理
2978
2979```python theme={null}
2980from claude_agent_sdk import query, CLINotFoundError, ProcessError, CLIJSONDecodeError
2981
2982try:
2983 async for message in query(prompt="Hello"):
2984 print(message)
2985except CLINotFoundError:
2986 print(
2987 "Claude Code CLI not found. Try reinstalling: pip install --force-reinstall claude-agent-sdk"
2988 )
2989except ProcessError as e:
2990 print(f"Process failed with exit code: {e.exit_code}")
2991except CLIJSONDecodeError as e:
2992 print(f"Failed to parse response: {e}")
2993```
2994
2995### 使用客户端的流式模式
2996
2997```python theme={null}
2998from claude_agent_sdk import ClaudeSDKClient
2999import asyncio
3000
3001
3002async def interactive_session():
3003 async with ClaudeSDKClient() as client:
3004 # Send initial message
3005 await client.query("What's the weather like?")
3006
3007 # Process responses
3008 async for msg in client.receive_response():
3009 print(msg)
3010
3011 # Send follow-up
3012 await client.query("Tell me more about that")
3013
3014 # Process follow-up response
3015 async for msg in client.receive_response():
3016 print(msg)
3017
3018
3019asyncio.run(interactive_session())
3020```
3021
3022### 使用 ClaudeSDKClient 的自定义工具
3023
3024```python theme={null}
3025from claude_agent_sdk import (
3026 ClaudeSDKClient,
3027 ClaudeAgentOptions,
3028 tool,
3029 create_sdk_mcp_server,
3030 AssistantMessage,
3031 TextBlock,
3032)
3033import asyncio
3034from typing import Any
3035
3036
3037# Define custom tools with @tool decorator
3038@tool("calculate", "Perform mathematical calculations", {"expression": str})
3039async def calculate(args: dict[str, Any]) -> dict[str, Any]:
3040 try:
3041 result = eval(args["expression"], {"__builtins__": {}})
3042 return {"content": [{"type": "text", "text": f"Result: {result}"}]}
3043 except Exception as e:
3044 return {
3045 "content": [{"type": "text", "text": f"Error: {str(e)}"}],
3046 "is_error": True,
3047 }
3048
3049
3050@tool("get_time", "Get current time", {})
3051async def get_time(args: dict[str, Any]) -> dict[str, Any]:
3052 from datetime import datetime
3053
3054 current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
3055 return {"content": [{"type": "text", "text": f"Current time: {current_time}"}]}
3056
3057
3058async def main():
3059 # Create SDK MCP server with custom tools
3060 my_server = create_sdk_mcp_server(
3061 name="utilities", version="1.0.0", tools=[calculate, get_time]
3062 )
3063
3064 # Configure options with the server
3065 options = ClaudeAgentOptions(
3066 mcp_servers={"utils": my_server},
3067 allowed_tools=["mcp__utils__calculate", "mcp__utils__get_time"],
3068 )
3069
3070 # Use ClaudeSDKClient for interactive tool usage
3071 async with ClaudeSDKClient(options=options) as client:
3072 await client.query("What's 123 * 456?")
3073
3074 # Process calculation response
3075 async for message in client.receive_response():
3076 if isinstance(message, AssistantMessage):
3077 for block in message.content:
3078 if isinstance(block, TextBlock):
3079 print(f"Calculation: {block.text}")
3080
3081 # Follow up with time query
3082 await client.query("What time is it now?")
3083
3084 async for message in client.receive_response():
3085 if isinstance(message, AssistantMessage):
3086 for block in message.content:
3087 if isinstance(block, TextBlock):
3088 print(f"Time: {block.text}")
3089
3090
3091asyncio.run(main())
3092```
3093
3094## 沙箱配置
3095
3096### `SandboxSettings`
3097
3098沙箱行为的配置。使用此来启用命令沙箱和以编程方式配置网络限制。
3099
3100```python theme={null}
3101class SandboxSettings(TypedDict, total=False):
3102 enabled: bool
3103 autoAllowBashIfSandboxed: bool
3104 excludedCommands: list[str]
3105 allowUnsandboxedCommands: bool
3106 network: SandboxNetworkConfig
3107 ignoreViolations: SandboxIgnoreViolations
3108 enableWeakerNestedSandbox: bool
3109```
3110
3111| 属性 | 类型 | 默认值 | 描述 |
3112| :-------------------------- | :------------------------------------------------------ | :------ | :------------------------------------------------------------------------------------------------------------------------------- |
3113| `enabled` | `bool` | `False` | 为命令执行启用沙箱模式 |
3114| `autoAllowBashIfSandboxed` | `bool` | `True` | 启用沙箱时自动批准 bash 命令 |
3115| `excludedCommands` | `list[str]` | `[]` | 始终绕过沙箱限制的命令(例如 `["docker"]`)。这些自动运行沙箱外,无需模型参与 |
3116| `allowUnsandboxedCommands` | `bool` | `True` | 允许模型请求在沙箱外运行命令。当为 `True` 时,模型可以在工具输入中设置 `dangerouslyDisableSandbox`,这会回退到 [权限系统](#permissions-fallback-for-unsandboxed-commands) |
3117| `network` | [`SandboxNetworkConfig`](#sandbox-network-config) | `None` | 网络特定的沙箱配置 |
3118| `ignoreViolations` | [`SandboxIgnoreViolations`](#sandbox-ignore-violations) | `None` | 配置要忽略的沙箱违规 |
3119| `enableWeakerNestedSandbox` | `bool` | `False` | 启用较弱的嵌套沙箱以实现兼容性 |
3120
3121#### 示例用法
3122
3123```python theme={null}
3124from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings
3125
3126sandbox_settings: SandboxSettings = {
3127 "enabled": True,
3128 "autoAllowBashIfSandboxed": True,
3129 "network": {"allowLocalBinding": True},
3130}
3131
3132async for message in query(
3133 prompt="Build and test my project",
3134 options=ClaudeAgentOptions(sandbox=sandbox_settings),
3135):
3136 print(message)
3137```
3138
3139<Warning>
3140 **Unix socket 安全性**:`allowUnixSockets` 选项可以授予对强大系统服务的访问权限。例如,允许 `/var/run/docker.sock` 实际上通过 Docker API 授予完整的主机系统访问权限,绕过沙箱隔离。仅允许严格必要的 Unix sockets,并理解每个的安全含义。
3141</Warning>
3142
3143### `SandboxNetworkConfig`
3144
3145沙箱模式的网络特定配置。
3146
3147```python theme={null}
3148class SandboxNetworkConfig(TypedDict, total=False):
3149 allowedDomains: list[str]
3150 deniedDomains: list[str]
3151 allowManagedDomainsOnly: bool
3152 allowUnixSockets: list[str]
3153 allowAllUnixSockets: bool
3154 allowLocalBinding: bool
3155 allowMachLookup: list[str]
3156 httpProxyPort: int
3157 socksProxyPort: int
3158```
3159
3160| 属性 | 类型 | 默认值 | 描述 |
3161| :------------------------ | :---------- | :------ | :----------------------------------------------------------- |
3162| `allowedDomains` | `list[str]` | `[]` | 沙箱化进程可以访问的域名 |
3163| `deniedDomains` | `list[str]` | `[]` | 沙箱化进程无法访问的域名。优先于 `allowedDomains` |
3164| `allowManagedDomainsOnly` | `bool` | `False` | 仅限托管设置:在托管设置中设置时,忽略来自非托管设置源的 `allowedDomains`。通过 SDK 选项设置时无效 |
3165| `allowUnixSockets` | `list[str]` | `[]` | 进程可以访问的 Unix socket 路径(例如 Docker socket) |
3166| `allowAllUnixSockets` | `bool` | `False` | 允许访问所有 Unix sockets |
3167| `allowLocalBinding` | `bool` | `False` | 允许进程绑定到本地端口(例如开发服务器) |
3168| `allowMachLookup` | `list[str]` | `[]` | 仅限 macOS:允许的 XPC/Mach 服务名称。支持尾部通配符 |
3169| `httpProxyPort` | `int` | `None` | 网络请求的 HTTP 代理端口 |
3170| `socksProxyPort` | `int` | `None` | 网络请求的 SOCKS 代理端口 |
3171
3172<Note>
3173 内置沙箱代理基于请求的主机名强制执行网络允许列表,不会终止或检查 TLS 流量,因此 [域名前置](https://en.wikipedia.org/wiki/Domain_fronting) 等技术可能会绕过它。有关详细信息,请参阅 [沙箱安全限制](/zh-CN/sandboxing#security-limitations),以及 [安全部署](/zh-CN/agent-sdk/secure-deployment#traffic-forwarding) 以配置 TLS 终止代理。
3174</Note>
3175
3176### `SandboxIgnoreViolations`
3177
3178用于忽略特定沙箱违规的配置。
3179
3180```python theme={null}
3181class SandboxIgnoreViolations(TypedDict, total=False):
3182 file: list[str]
3183 network: list[str]
3184```
3185
3186| 属性 | 类型 | 默认值 | 描述 |
3187| :-------- | :---------- | :--- | :----------- |
3188| `file` | `list[str]` | `[]` | 要忽略违规的文件路径模式 |
3189| `network` | `list[str]` | `[]` | 要忽略违规的网络模式 |
3190
3191### 沙箱外命令的权限回退
3192
3193当 `allowUnsandboxedCommands` 启用时,模型可以通过在工具输入中设置 `dangerouslyDisableSandbox: True` 来请求在沙箱外运行命令。这些请求回退到现有权限系统,意味着你的 `can_use_tool` 处理程序将被调用,允许你实现自定义授权逻辑。
3194
3195<Note>
3196 **`excludedCommands` vs `allowUnsandboxedCommands`:**
3197
3198 * `excludedCommands`:始终自动绕过沙箱的命令的静态列表(例如 `["docker"]`)。模型对此无控制权。
3199 * `allowUnsandboxedCommands`:让模型在运行时通过在工具输入中设置 `dangerouslyDisableSandbox: True` 来决定是否请求沙箱外执行。
3200</Note>
3201
3202```python theme={null}
3203from claude_agent_sdk import (
3204 query,
3205 ClaudeAgentOptions,
3206 HookMatcher,
3207 PermissionResultAllow,
3208 PermissionResultDeny,
3209 ToolPermissionContext,
3210)
3211
3212
3213async def can_use_tool(
3214 tool: str, input: dict, context: ToolPermissionContext
3215) -> PermissionResultAllow | PermissionResultDeny:
3216 # Check if the model is requesting to bypass the sandbox
3217 if tool == "Bash" and input.get("dangerouslyDisableSandbox"):
3218 # The model is requesting to run this command outside the sandbox
3219 print(f"Unsandboxed command requested: {input.get('command')}")
3220
3221 if is_command_authorized(input.get("command")):
3222 return PermissionResultAllow()
3223 return PermissionResultDeny(
3224 message="Command not authorized for unsandboxed execution"
3225 )
3226 return PermissionResultAllow()
3227
3228
3229# Required: dummy hook keeps the stream open for can_use_tool
3230async def dummy_hook(input_data, tool_use_id, context):
3231 return {"continue_": True}
3232
3233
3234async def prompt_stream():
3235 yield {
3236 "type": "user",
3237 "message": {"role": "user", "content": "Deploy my application"},
3238 }
3239
3240
3241async def main():
3242 async for message in query(
3243 prompt=prompt_stream(),
3244 options=ClaudeAgentOptions(
3245 sandbox={
3246 "enabled": True,
3247 "allowUnsandboxedCommands": True, # Model can request unsandboxed execution
3248 },
3249 permission_mode="default",
3250 can_use_tool=can_use_tool,
3251 hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]},
3252 ),
3253 ):
3254 print(message)
3255```
3256
3257此模式使你能够:
3258
3259* **审计模型请求**:记录模型何时请求沙箱外执行
3260* **实现允许列表**:仅允许特定命令在沙箱外运行
3261* **添加批准工作流**:需要显式授权以进行特权操作
3262
3263<Warning>
3264 使用 `dangerouslyDisableSandbox: True` 运行的命令具有完整的系统访问权限。确保你的 `can_use_tool` 处理程序仔细验证这些请求。
3265
3266 如果 `permission_mode` 设置为 `bypassPermissions` 且 `allow_unsandboxed_commands` 启用,模型可以自主执行沙箱外的命令,无需任何批准提示。此组合实际上允许模型无声地逃离沙箱隔离。
3267</Warning>
3268
3269## 另见
3270
3271* [SDK 概述](/zh-CN/agent-sdk/overview) - 一般 SDK 概念
3272* [TypeScript SDK 参考](/zh-CN/agent-sdk/typescript) - TypeScript SDK 文档
3273* [CLI 参考](/zh-CN/cli-reference) - 命令行界面
3274* [常见工作流](/zh-CN/common-workflows) - 分步指南