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| **Session** | 每次建立新 session | 重複使用相同 session |
24| **Conversation** | 單一交換 | 同一上下文中的多個交換 |
25| **Connection** | 自動管理 | 手動控制 |
26| **Streaming Input** | ✅ 支援 | ✅ 支援 |
27| **Interrupts** | ❌ 不支援 | ✅ 支援 |
28| **Hooks** | ✅ 支援 | ✅ 支援 |
29| **Custom Tools** | ✅ 支援 | ✅ 支援 |
30| **Continue Chat** | ❌ 每次新 session | ✅ 維持對話 |
31| **Use Case** | 一次性任務 | 持續對話 |
32
33### 何時使用 `query()`(每次新 session)
34
35**最適合:**
36
37* 一次性問題,不需要對話歷史
38* 不需要先前交換上下文的獨立任務
39* 簡單的自動化腳本
40* 當您想每次都重新開始時
41
42### 何時使用 `ClaudeSDKClient`(持續對話)
43
44**最適合:**
45
46* **繼續對話** - 當您需要 Claude 記住上下文時
47* **後續問題** - 基於先前回應進行構建
48* **互動式應用程式** - 聊天介面、REPL
49* **回應驅動邏輯** - 當下一個動作取決於 Claude 的回應時
50* **Session 控制** - 明確管理對話生命週期
51
52## 函數
53
54### `query()`
55
56為每次與 Claude Code 的互動建立新 session。返回一個非同步迭代器,在消息到達時產生消息。每次呼叫 `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 tools 的裝飾器。
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` | tool 的唯一識別碼 |
118| `description` | `str` | tool 功能的人類可讀描述 |
119| `input_schema` | `type \| dict[str, Any]` | 定義 tool 輸入參數的架構(見下文) |
120| `annotations` | [`ToolAnnotations`](#tool-annotations)` \| None` | 可選的 MCP tool 註解,為客戶端提供行為提示 |
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一個裝飾器函數,包裝 tool 實現並返回 `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` | tool 的人類可讀標題 |
165| `readOnlyHint` | `bool \| None` | `False` | 如果為 `True`,tool 不會修改其環境 |
166| `destructiveHint` | `bool \| None` | `True` | 如果為 `True`,tool 可能執行破壞性更新(僅在 `readOnlyHint` 為 `False` 時有意義) |
167| `idempotentHint` | `bool \| None` | `False` | 如果為 `True`,使用相同參數的重複呼叫沒有額外效果(僅在 `readOnlyHint` 為 `False` 時有意義) |
168| `openWorldHint` | `bool \| None` | `True` | 如果為 `True`,tool 與外部實體互動(例如網路搜尋)。如果為 `False`,tool 的域是封閉的(例如記憶體 tool) |
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` 裝飾器建立的 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列出過去的 sessions 及其中繼資料。按專案目錄篩選或列出所有專案中的 sessions。同步;立即返回。
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` | 列出 sessions 的目錄。省略時,返回所有專案中的 sessions |
255| `limit` | `int \| None` | `None` | 返回的最大 sessions 數 |
256| `include_worktrees` | `bool` | `True` | 當 `directory` 在 git 儲存庫內時,包括所有 worktree 路徑中的 sessions |
257
258#### 返回類型:`SDKSessionInfo`
259
260| 屬性 | 類型 | 描述 |
261| :-------------- | :------------ | :--------------------------------------------------- |
262| `session_id` | `str` | 唯一 session 識別碼 |
263| `summary` | `str` | 顯示標題:自訂標題、自動生成的摘要或第一個提示 |
264| `last_modified` | `int` | 上次修改時間(自紀元以來的毫秒數) |
265| `file_size` | `int \| None` | Session 檔案大小(以位元組為單位)(遠端儲存後端為 `None`) |
266| `custom_title` | `str \| None` | 使用者設定的 session 標題 |
267| `first_prompt` | `str \| None` | session 中的第一個有意義的使用者提示 |
268| `git_branch` | `str \| None` | session 結束時的 Git 分支 |
269| `cwd` | `str \| None` | session 的工作目錄 |
270| `tag` | `str \| None` | 使用者設定的 session 標籤(見 [`tag_session()`](#tag-session)) |
271| `created_at` | `int \| None` | session 建立時間(自紀元以來的毫秒數) |
272
273#### 範例
274
275列印專案的 10 個最近 sessions。結果按 `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從過去的 session 中檢索消息。同步;立即返回。
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` | 必需 | 要檢索消息的 session 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` | session 識別碼 |
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 讀取單個 session 的中繼資料,無需掃描完整專案目錄。同步;立即返回。
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` | 必需 | 要查詢的 session 的 UUID |
344| `directory` | `str \| None` | `None` | 專案目錄路徑。省略時,搜尋所有專案目錄 |
345
346返回 [`SDKSessionInfo`](#return-type-sdk-session-info),如果找不到 session,則返回 `None`。
347
348#### 範例
349
350查詢單個 session 的中繼資料,無需掃描專案目錄。當您已經從先前的執行中獲得 session 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通過附加自訂標題項來重新命名 session。重複呼叫是安全的;最新的標題獲勝。同步。
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` | 必需 | 要重新命名的 session 的 UUID |
377| `title` | `str` | 必需 | 新標題。去除空格後必須非空 |
378| `directory` | `str \| None` | `None` | 專案目錄路徑。省略時,搜尋所有專案目錄 |
379
380如果 `session_id` 不是有效的 UUID 或 `title` 為空,則引發 `ValueError`;如果找不到 session,則引發 `FileNotFoundError`。
381
382#### 範例
383
384重新命名最近的 session,以便稍後更容易找到。新標題在後續讀取時出現在 [`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標記 session。傳遞 `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` | 必需 | 要標記的 session 的 UUID |
411| `tag` | `str \| None` | 必需 | 標籤字串,或 `None` 以清除。儲存前進行 Unicode 清理 |
412| `directory` | `str \| None` | `None` | 專案目錄路徑。省略時,搜尋所有專案目錄 |
413
414如果 `session_id` 不是有效的 UUID 或 `tag` 在清理後為空,則引發 `ValueError`;如果找不到 session,則引發 `FileNotFoundError`。
415
416#### 範例
417
418標記 session,然後在稍後的讀取中按該標籤篩選。傳遞 `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**在多個交換中維持對話 session。** 這是 TypeScript SDK 的 `query()` 函數內部工作方式的 Python 等效物 - 它建立一個可以繼續對話的客戶端物件。
437
438#### 主要功能
439
440* **Session 連續性**:在多個 `query()` 呼叫中維持對話上下文
441* **相同對話**:session 保留先前的消息
442* **中斷支援**:可以在任務中途停止執行
443* **明確生命週期**:您控制 session 何時開始和結束
444* **回應驅動流程**:可以對回應做出反應並發送後續消息
445* **自訂 tools 和 hooks**:支援自訂 tools(使用 `@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)` | 變更目前 session 的權限模式 |
477| `set_model(model)` | 變更目前 session 的模型。傳遞 `None` 以重設為預設值 |
478| `rewind_files(user_message_id)` | 將檔案還原到指定使用者消息時的狀態。需要 `enable_file_checkpointing=True`。見 [檔案 checkpointing](/zh-TW/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)` | 在 session 中途啟用或停用 MCP 伺服器。停用會移除其 tools |
482| `stop_task(task_id)` | 停止執行中的背景任務。[`TaskNotificationMessage`](#task-notification-message) 的狀態為 `"stopped"` 在消息流中跟隨 |
483| `get_server_info()` | 取得伺服器資訊,包括 session 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)` 呼叫語法對兩者都有效,但只有 dataclasses 產生具有屬性的物件。
680</Note>
681
682### `SdkMcpTool`
683
684使用 `@tool` 裝飾器建立的 SDK MCP tool 的定義。
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` | tool 的唯一識別碼 |
699| `description` | `str` | 人類可讀描述 |
700| `input_schema` | `type[T] \| dict[str, Any]` | 輸入驗證的架構 |
701| `handler` | `Callable[[T], Awaitable[dict[str, Any]]]` | 處理 tool 執行的非同步函數 |
702| `annotations` | `ToolAnnotations \| None` | 可選的 MCP tool 註解(例如 `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 查詢的配置 dataclass。
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` | Tools 配置。使用 `{"type": "preset", "preset": "claude_code"}` 以取得 Claude Code 的預設 tools |
799| `allowed_tools` | `list[str]` | `[]` | 自動批准的 tools,無需提示。這不會限制 Claude 僅使用這些 tools;未列出的 tools 會進入 `permission_mode` 和 `can_use_tool`。使用 `disallowed_tools` 來阻止 tools。見 [權限](/zh-TW/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` | tool 使用的權限模式 |
803| `continue_conversation` | `bool` | `False` | 繼續最近的對話 |
804| `resume` | `str \| None` | `None` | 要繼續的 session ID |
805| `max_turns` | `int \| None` | `None` | 最大代理轉數(tool 使用往返) |
806| `max_budget_usd` | `float \| None` | `None` | 當客戶端成本估計達到此 USD 值時停止查詢。與 `total_cost_usd` 的相同估計進行比較;見 [追蹤成本和使用情況](/zh-TW/agent-sdk/cost-tracking) 以了解準確性注意事項 |
807| `disallowed_tools` | `list[str]` | `[]` | 始終拒絕的 tools。拒絕規則首先檢查並覆蓋 `allowed_tools` 和 `permission_mode`(包括 `bypassPermissions`) |
808| `enable_file_checkpointing` | `bool` | `False` | 啟用檔案變更追蹤以進行倒帶。見 [檔案 checkpointing](/zh-TW/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-TW/agent-sdk/structured-outputs) 以了解詳情 |
813| `permission_prompt_tool_name` | `str \| None` | `None` | 權限提示的 MCP tool 名稱 |
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-TW/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` | tool 權限回呼函數。見 [權限類型](#can-use-tool) 以了解詳情 |
824| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | 用於攔截事件的 hook 配置 |
825| `user` | `str \| None` | `None` | 使用者識別碼 |
826| `include_partial_messages` | `bool` | `False` | 包括部分消息串流事件。啟用時,[`StreamEvent`](#stream-event) 消息會被產生 |
827| `fork_session` | `bool` | `False` | 使用 `resume` 繼續時,分叉到新 session ID 而不是繼續原始 session |
828| `agents` | `dict[str, AgentDefinition] \| None` | `None` | 以程式設計方式定義的子代理 |
829| `plugins` | `list[SdkPluginConfig]` | `[]` | 從本地路徑載入自訂外掛程式。見 [外掛程式](/zh-TW/agent-sdk/plugins) 以了解詳情 |
830| `sandbox` | [`SandboxSettings`](#sandbox-settings) ` \| None` | `None` | 以程式設計方式配置沙箱行為。見 [沙箱設定](#sandbox-settings) 以了解詳情 |
831| `setting_sources` | `list[SettingSource] \| None` | `None`(CLI 預設值:所有來源) | 控制要載入哪些檔案系統設定。傳遞 `[]` 以停用使用者、專案和本地設定。無論如何都會載入受管原則設定。見 [使用 Claude Code 功能](/zh-TW/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-TW/agent-sdk/session-storage#the-session-store-interface) ` \| None` | `None` | 將 session 記錄鏡像到外部後端,以便任何主機都可以繼續它們。見 [將 sessions 持久化到外部儲存](/zh-TW/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` | 否 | 將每個 session 上下文(例如工作目錄、git 狀態和記憶體路徑)從系統提示移到第一個使用者消息。改進跨使用者和機器的提示快取重複使用。見 [修改系統提示](/zh-TW/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-TW/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` | 否 | 允許的 tool 名稱陣列。如果省略,繼承所有 tools |
1025| `disallowedTools` | 否 | 要從代理的 tool 集中移除的 tool 名稱陣列 |
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` | 否 | 此代理內 tool 執行的權限模式。見 [`PermissionMode`](#permission-mode) |
1035
1036<Note>
1037 `AgentDefinition` 欄位名稱使用 camelCase,例如 `disallowedTools`、`permissionMode` 和 `maxTurns`。這些名稱直接對應到與 TypeScript SDK 共享的線路格式。這與 `ClaudeAgentOptions` 不同,後者對等頂級欄位(例如 `disallowed_tools` 和 `permission_mode`)使用 Python snake\_case。因為 `AgentDefinition` 是 dataclass,傳遞 snake\_case 關鍵字在構造時會引發 `TypeError`。
1038</Note>
1039
1040### `PermissionMode`
1041
1042用於控制 tool 執行的權限模式。
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
1056tool 權限回呼函數的類型別名。
1057
1058```python theme={null}
1059CanUseTool = Callable[
1060 [str, dict[str, Any], ToolPermissionContext], Awaitable[PermissionResult]
1061]
1062```
1063
1064回呼接收:
1065
1066* `tool_name`:被呼叫的 tool 名稱
1067* `input_data`:tool 的輸入參數
1068* `context`:具有其他資訊的 `ToolPermissionContext`
1069
1070返回 `PermissionResult`(`PermissionResultAllow` 或 `PermissionResultDeny`)。
1071
1072### `ToolPermissionContext`
1073
1074傳遞給 tool 權限回呼的上下文資訊。
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指示應允許 tool 呼叫的結果。
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指示應拒絕 tool 呼叫的結果。
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` | `""` | 解釋為什麼拒絕 tool 的消息 |
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 預設 tool 集的預設 tools 配置。
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
1292MCP 伺服器的配置,如 [`get_mcp_status()`](#methods) 所報告。這是所有 [`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`(可選) | 此伺服器提供的 tools,每個都具有 `name`、`description` 和 `annotations` 欄位 |
1339
1340### `SdkPluginConfig`
1341
1342在 SDK 中載入外掛程式的配置。
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如需建立和使用外掛程式的完整資訊,見 [外掛程式](/zh-TW/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` | 如果此消息是 tool 結果回應,則為 tool 使用 ID |
1401| `tool_use_result` | `dict[str, Any] \| None` | tool 結果資料(如適用) |
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` | 如果這是嵌套回應,則為 tool 使用 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-TW/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` | 此模型的估計成本(以 USD 為單位),在客戶端計算。見 [追蹤成本和使用情況](/zh-TW/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` | session 識別碼 |
1514| `event` | `dict[str, Any]` | 原始 Claude API 串流事件資料 |
1515| `parent_tool_use_id` | `str \| None` | 如果此事件來自子代理,則為父 tool 使用 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` | session 識別碼 |
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 tool 生成的子代理或遠端代理。`task_type` 欄位告訴您是哪一個。此命名與 `Task` 到 `Agent` tool 重新命名無關。
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` | session 識別碼 |
1590| `tool_use_id` | `str \| None` | 相關聯的 tool 使用 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` | session 識別碼 |
1627| `tool_use_id` | `str \| None` | 相關聯的 tool 使用 ID |
1628| `last_tool_name` | `str \| None` | 任務最後使用的 tool 名稱 |
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` | session 識別碼 |
1655| `tool_use_id` | `str \| None` | 相關聯的 tool 使用 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
1691tool 使用請求區塊。
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
1703tool 執行結果區塊。
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-TW/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`:可選 tool 使用識別碼(用於 tool 相關 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 符合到特定事件或 tools 的配置。
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` | 目前 session 識別碼 |
1886| `transcript_path` | `str` | session 記錄檔案的路徑 |
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` | 即將執行的 tool 名稱 |
1908| `tool_input` | `dict[str, Any]` | tool 的輸入參數 |
1909| `tool_use_id` | `str` | 此 tool 使用的唯一識別碼 |
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` | 已執行的 tool 名稱 |
1932| `tool_input` | `dict[str, Any]` | 使用的輸入參數 |
1933| `tool_response` | `Any` | tool 執行的回應 |
1934| `tool_use_id` | `str` | 此 tool 使用的唯一識別碼 |
1935| `agent_id` | `str`(可選) | 子代理識別碼,當 hook 在子代理內觸發時出現 |
1936| `agent_type` | `str`(可選) | 子代理類型,當 hook 在子代理內觸發時出現 |
1937
1938### `PostToolUseFailureHookInput`
1939
1940`PostToolUseFailure` hook 事件的輸入資料。在 tool 執行失敗時呼叫。
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` | 失敗的 tool 名稱 |
1958| `tool_input` | `dict[str, Any]` | 使用的輸入參數 |
1959| `tool_use_id` | `str` | 此 tool 使用的唯一識別碼 |
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` | 請求權限的 tool 名稱 |
2085| `tool_input` | `dict[str, Any]` | tool 的輸入參數 |
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-TW/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 /`),另一個記錄所有 tool 使用情況以進行審計。安全 hook 僅在 Bash 命令上執行(透過 `matcher`),而記錄 hook 在所有 tools 上執行。
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## Tool 輸入/輸出類型
2244
2245所有內建 Claude Code tools 的輸入/輸出架構文件。雖然 Python SDK 不將這些匯出為類型,但它們代表消息中 tool 輸入和輸出的結構。
2246
2247### Agent
2248
2249**Tool 名稱:** `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**Tool 名稱:** `AskUserQuestion`
2275
2276在執行期間詢問使用者澄清問題。見 [處理批准和使用者輸入](/zh-TW/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**Tool 名稱:** `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**Tool 名稱:** `Monitor`
2345
2346執行背景腳本並將每個 stdout 行作為事件傳遞給 Claude,以便它可以做出反應而無需輪詢。Monitor 遵循與 Bash 相同的權限規則。見 [Monitor tool 參考](/zh-TW/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
2365 "persistent": bool | None, # True when running until TaskStop or session end
2366}
2367```
2368
2369### Edit
2370
2371**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `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**Tool 名稱:** `ReadMcpResource`
2722
2723**輸入:**
2724
2725```python theme={null}
2726{
2727 "server": str, #MCP 伺服器名稱
2728 "uri": str, # 要讀取的資源 URI
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 的自訂 tools
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` 時,模型可以在 tool 輸入中設定 `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 proxy 連接埠 |
3170| `socksProxyPort` | `int` | `None` | 網路請求的 SOCKS proxy 連接埠 |
3171
3172<Note>
3173 內建沙箱 proxy 根據請求的主機名稱強制執行網路允許清單,不會終止或檢查 TLS 流量,因此[網域前置](https://en.wikipedia.org/wiki/Domain_fronting)等技術可能會繞過它。有關詳細資訊,請參閱[沙箱安全限制](/zh-TW/sandboxing#security-limitations),以及[安全部署](/zh-TW/agent-sdk/secure-deployment#traffic-forwarding)以配置 TLS 終止 proxy。
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` 啟用時,模型可以透過在 tool 輸入中設定 `dangerouslyDisableSandbox: True` 來請求在沙箱外執行命令。這些請求回退到現有權限系統,意味著您的 `can_use_tool` 處理程序將被呼叫,允許您實現自訂授權邏輯。
3194
3195<Note>
3196 **`excludedCommands` vs `allowUnsandboxedCommands`:**
3197
3198 * `excludedCommands`:始終自動繞過沙箱的靜態命令清單(例如 `["docker"]`)。模型無法控制此。
3199 * `allowUnsandboxedCommands`:讓模型在執行時透過在 tool 輸入中設定 `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-TW/agent-sdk/overview) - 一般 SDK 概念
3272* [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript) - TypeScript SDK 文件
3273* [CLI 參考](/zh-TW/cli-reference) - 命令列介面
3274* [常見工作流程](/zh-TW/common-workflows) - 逐步指南