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 と対話するための 2 つの方法を提供します。
18
19### クイック比較
20
21| 機能 | `query()` | `ClaudeSDKClient` |
22| :------------ | :------------ | :---------------- |
23| **セッション** | 毎回新しいセッションを作成 | 同じセッションを再利用 |
24| **会話** | 単一の交換 | 同じコンテキスト内の複数の交換 |
25| **接続** | 自動的に管理 | 手動制御 |
26| **ストリーミング入力** | ✅ サポート | ✅ サポート |
27| **割り込み** | ❌ サポートなし | ✅ サポート |
28| **Hooks** | ✅ サポート | ✅ サポート |
29| **カスタムツール** | ✅ サポート | ✅ サポート |
30| **会話を続ける** | ❌ 毎回新しいセッション | ✅ 会話を保持 |
31| **ユースケース** | 1 回限りのタスク | 継続的な会話 |
32
33### `query()` を使用する場合(毎回新しいセッション)
34
35**最適な用途:**
36
37* 会話履歴が不要な 1 回限りの質問
38* 前の交換からのコンテキストが不要な独立したタスク
39* シンプルな自動化スクリプト
40* 毎回新しく開始したい場合
41
42### `ClaudeSDKClient` を使用する場合(継続的な会話)
43
44**最適な用途:**
45
46* **会話を続ける** - Claude がコンテキストを記憶する必要がある場合
47* **フォローアップ質問** - 前の回答に基づいて構築する
48* **インタラクティブなアプリケーション** - チャットインターフェース、REPL
49* **応答駆動ロジック** - 次のアクションが Claude の応答に依存する場合
50* **セッション制御** - 会話ライフサイクルを明示的に管理する
51
52## 関数
53
54### `query()`
55
56Claude Code との各インタラクションのために新しいセッションを作成します。メッセージが到着するにつれて生成される非同期イテレータを返します。`query()` への各呼び出しは、前のインタラクションのメモリなしで新しく開始します。
57
58```python theme={null}
59async def query(
60 *,
61 prompt: str | AsyncIterable[dict[str, Any]],
62 options: ClaudeAgentOptions | None = None,
63 transport: Transport | None = None
64) -> AsyncIterator[Message]
65```
66
67#### パラメータ
68
69| パラメータ | 型 | 説明 |
70| :---------- | :--------------------------- | :------------------------------------------------------ |
71| `prompt` | `str \| AsyncIterable[dict]` | 入力プロンプト(文字列またはストリーミングモード用の非同期イテレータ) |
72| `options` | `ClaudeAgentOptions \| None` | オプションの設定オブジェクト(None の場合は `ClaudeAgentOptions()` がデフォルト) |
73| `transport` | `Transport \| None` | CLI プロセスとの通信用のオプションのカスタムトランスポート |
74
75#### 戻り値
76
77会話からのメッセージを生成する `AsyncIterator[Message]` を返します。
78
79#### 例 - オプション付き
80
81```python theme={null}
82import asyncio
83from claude_agent_sdk import query, ClaudeAgentOptions
84
85
86async def main():
87 options = ClaudeAgentOptions(
88 system_prompt="You are an expert Python developer",
89 permission_mode="acceptEdits",
90 cwd="/home/user/project",
91 )
92
93 async for message in query(prompt="Create a Python web server", options=options):
94 print(message)
95
96
97asyncio.run(main())
98```
99
100### `tool()`
101
102型安全性を備えた MCP ツールを定義するためのデコレータ。
103
104```python theme={null}
105def tool(
106 name: str,
107 description: str,
108 input_schema: type | dict[str, Any],
109 annotations: ToolAnnotations | None = None
110) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]
111```
112
113#### パラメータ
114
115| パラメータ | 型 | 説明 |
116| :------------- | :----------------------------------------------- | :------------------------------------- |
117| `name` | `str` | ツールの一意の識別子 |
118| `description` | `str` | ツールが何をするかの人間が読める説明 |
119| `input_schema` | `type \| dict[str, Any]` | ツールの入力パラメータを定義するスキーマ(以下を参照) |
120| `annotations` | [`ToolAnnotations`](#tool-annotations)` \| None` | クライアントに動作ヒントを提供するオプションの MCP ツールアノテーション |
121
122#### 入力スキーマオプション
123
1241. **シンプルな型マッピング**(推奨):
125
126 ```python theme={null}
127 {"text": str, "count": int, "enabled": bool}
128 ```
129
1302. **JSON Schema 形式**(複雑な検証用):
131 ```python theme={null}
132 {
133 "type": "object",
134 "properties": {
135 "text": {"type": "string"},
136 "count": {"type": "integer", "minimum": 0},
137 },
138 "required": ["text"],
139 }
140 ```
141
142#### 戻り値
143
144ツール実装をラップし、`SdkMcpTool` インスタンスを返すデコレータ関数。
145
146#### 例
147
148```python theme={null}
149from claude_agent_sdk import tool
150from typing import Any
151
152
153@tool("greet", "Greet a user", {"name": str})
154async def greet(args: dict[str, Any]) -> dict[str, Any]:
155 return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}
156```
157
158#### `ToolAnnotations`
159
160`mcp.types` から再エクスポート(`from claude_agent_sdk import ToolAnnotations` としても利用可能)。すべてのフィールドはオプションのヒントです。クライアントはセキュリティ決定のためにこれらに依存すべきではありません。
161
162| フィールド | 型 | デフォルト | 説明 |
163| :---------------- | :------------- | :------ | :---------------------------------------------------------------------------- |
164| `title` | `str \| None` | `None` | ツールの人間が読める題名 |
165| `readOnlyHint` | `bool \| None` | `False` | `True` の場合、ツールはその環境を変更しません |
166| `destructiveHint` | `bool \| None` | `True` | `True` の場合、ツールは破壊的な更新を実行する可能性があります(`readOnlyHint` が `False` の場合のみ意味があります) |
167| `idempotentHint` | `bool \| None` | `False` | `True` の場合、同じ引数での繰り返し呼び出しは追加の効果がありません(`readOnlyHint` が `False` の場合のみ意味があります) |
168| `openWorldHint` | `bool \| None` | `True` | `True` の場合、ツールは外部エンティティと対話します(例:Web 検索)。`False` の場合、ツールのドメインは閉じています(例:メモリツール) |
169
170```python theme={null}
171from claude_agent_sdk import tool, ToolAnnotations
172from typing import Any
173
174
175@tool(
176 "search",
177 "Search the web",
178 {"query": str},
179 annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True),
180)
181async def search(args: dict[str, Any]) -> dict[str, Any]:
182 return {"content": [{"type": "text", "text": f"Results for: {args['query']}"}]}
183```
184
185### `create_sdk_mcp_server()`
186
187Python アプリケーション内で実行されるインプロセス MCP サーバーを作成します。
188
189```python theme={null}
190def create_sdk_mcp_server(
191 name: str,
192 version: str = "1.0.0",
193 tools: list[SdkMcpTool[Any]] | None = None
194) -> McpSdkServerConfig
195```
196
197#### パラメータ
198
199| パラメータ | 型 | デフォルト | 説明 |
200| :-------- | :------------------------------ | :-------- | :--------------------------- |
201| `name` | `str` | - | サーバーの一意の識別子 |
202| `version` | `str` | `"1.0.0"` | サーバーバージョン文字列 |
203| `tools` | `list[SdkMcpTool[Any]] \| None` | `None` | `@tool` デコレータで作成されたツール関数のリスト |
204
205#### 戻り値
206
207`ClaudeAgentOptions.mcp_servers` に渡すことができる `McpSdkServerConfig` オブジェクトを返します。
208
209#### 例
210
211```python theme={null}
212from claude_agent_sdk import tool, create_sdk_mcp_server
213
214
215@tool("add", "Add two numbers", {"a": float, "b": float})
216async def add(args):
217 return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}
218
219
220@tool("multiply", "Multiply two numbers", {"a": float, "b": float})
221async def multiply(args):
222 return {"content": [{"type": "text", "text": f"Product: {args['a'] * args['b']}"}]}
223
224
225calculator = create_sdk_mcp_server(
226 name="calculator",
227 version="2.0.0",
228 tools=[add, multiply], # Pass decorated functions
229)
230
231# Use with Claude
232options = ClaudeAgentOptions(
233 mcp_servers={"calc": calculator},
234 allowed_tools=["mcp__calc__add", "mcp__calc__multiply"],
235)
236```
237
238### `list_sessions()`
239
240メタデータを含む過去のセッションをリストします。プロジェクトディレクトリでフィルタするか、すべてのプロジェクト全体のセッションをリストします。同期的です。すぐに返します。
241
242```python theme={null}
243def list_sessions(
244 directory: str | None = None,
245 limit: int | None = None,
246 include_worktrees: bool = True
247) -> list[SDKSessionInfo]
248```
249
250#### パラメータ
251
252| パラメータ | 型 | デフォルト | 説明 |
253| :------------------ | :------------ | :----- | :---------------------------------------------------------- |
254| `directory` | `str \| None` | `None` | セッションをリストするディレクトリ。省略した場合、すべてのプロジェクト全体のセッションを返します |
255| `limit` | `int \| None` | `None` | 返すセッションの最大数 |
256| `include_worktrees` | `bool` | `True` | `directory` が git リポジトリ内にある場合、すべての worktree パスからのセッションを含めます |
257
258#### 戻り値の型:`SDKSessionInfo`
259
260| プロパティ | 型 | 説明 |
261| :-------------- | :------------ | :---------------------------------------------------- |
262| `session_id` | `str` | 一意のセッション識別子 |
263| `summary` | `str` | 表示タイトル:カスタムタイトル、自動生成されたサマリー、または最初のプロンプト |
264| `last_modified` | `int` | エポック以降のミリ秒単位での最後の変更時刻 |
265| `file_size` | `int \| None` | セッションファイルサイズ(バイト)(リモートストレージバックエンドの場合は `None`) |
266| `custom_title` | `str \| None` | ユーザーが設定したセッションタイトル |
267| `first_prompt` | `str \| None` | セッション内の最初の意味のあるユーザープロンプト |
268| `git_branch` | `str \| None` | セッション終了時の Git ブランチ |
269| `cwd` | `str \| None` | セッションの作業ディレクトリ |
270| `tag` | `str \| None` | ユーザーが設定したセッションタグ([`tag_session()`](#tag-session) を参照) |
271| `created_at` | `int \| None` | エポック以降のミリ秒単位でのセッション作成時刻 |
272
273#### 例
274
275プロジェクトの 10 個の最新セッションを出力します。結果は `last_modified` の降順でソートされるため、最初の項目が最新です。`directory` を省略するとすべてのプロジェクト全体を検索します。
276
277```python theme={null}
278from claude_agent_sdk import list_sessions
279
280for session in list_sessions(directory="/path/to/project", limit=10):
281 print(f"{session.summary} ({session.session_id})")
282```
283
284### `get_session_messages()`
285
286過去のセッションからメッセージを取得します。同期的です。すぐに返します。
287
288```python theme={null}
289def get_session_messages(
290 session_id: str,
291 directory: str | None = None,
292 limit: int | None = None,
293 offset: int = 0
294) -> list[SessionMessage]
295```
296
297#### パラメータ
298
299| パラメータ | 型 | デフォルト | 説明 |
300| :----------- | :------------ | :----- | :--------------------------------------- |
301| `session_id` | `str` | 必須 | メッセージを取得するセッション ID |
302| `directory` | `str \| None` | `None` | 検索するプロジェクトディレクトリ。省略した場合、すべてのプロジェクトを検索します |
303| `limit` | `int \| None` | `None` | 返すメッセージの最大数 |
304| `offset` | `int` | `0` | 開始から スキップするメッセージ数 |
305
306#### 戻り値の型:`SessionMessage`
307
308| プロパティ | 型 | 説明 |
309| :------------------- | :----------------------------- | :------------ |
310| `type` | `Literal["user", "assistant"]` | メッセージロール |
311| `uuid` | `str` | 一意のメッセージ識別子 |
312| `session_id` | `str` | セッション識別子 |
313| `message` | `Any` | 生のメッセージコンテンツ |
314| `parent_tool_use_id` | `None` | 将来の使用のために予約済み |
315
316#### 例
317
318```python theme={null}
319from claude_agent_sdk import list_sessions, get_session_messages
320
321sessions = list_sessions(limit=1)
322if sessions:
323 messages = get_session_messages(sessions[0].session_id)
324 for msg in messages:
325 print(f"[{msg.type}] {msg.uuid}")
326```
327
328### `get_session_info()`
329
330プロジェクトディレクトリ全体をスキャンせずに、ID でシングルセッションのメタデータを読み取ります。同期的です。すぐに返します。
331
332```python theme={null}
333def get_session_info(
334 session_id: str,
335 directory: str | None = None,
336) -> SDKSessionInfo | None
337```
338
339#### パラメータ
340
341| パラメータ | 型 | デフォルト | 説明 |
342| :----------- | :------------ | :----- | :------------------------------------------- |
343| `session_id` | `str` | 必須 | 検索するセッションの UUID |
344| `directory` | `str \| None` | `None` | プロジェクトディレクトリパス。省略した場合、すべてのプロジェクトディレクトリを検索します |
345
346[`SDKSessionInfo`](#return-type-sdk-session-info) を返すか、セッションが見つからない場合は `None`。
347
348#### 例
349
350プロジェクトディレクトリをスキャンせずに、シングルセッションのメタデータを検索します。前の実行からセッション ID を既に持っている場合に便利です。
351
352```python theme={null}
353from claude_agent_sdk import get_session_info
354
355info = get_session_info("550e8400-e29b-41d4-a716-446655440000")
356if info:
357 print(f"{info.summary} (branch: {info.git_branch}, tag: {info.tag})")
358```
359
360### `rename_session()`
361
362カスタムタイトルエントリを追加することでセッションの名前を変更します。繰り返し呼び出しは安全です。最新のタイトルが優先されます。同期的です。
363
364```python theme={null}
365def rename_session(
366 session_id: str,
367 title: str,
368 directory: str | None = None,
369) -> None
370```
371
372#### パラメータ
373
374| パラメータ | 型 | デフォルト | 説明 |
375| :----------- | :------------ | :----- | :------------------------------------------- |
376| `session_id` | `str` | 必須 | 名前を変更するセッションの UUID |
377| `title` | `str` | 必須 | 新しいタイトル。空白をストリップした後、空でない必要があります |
378| `directory` | `str \| None` | `None` | プロジェクトディレクトリパス。省略した場合、すべてのプロジェクトディレクトリを検索します |
379
380`session_id` が有効な UUID でない場合、または `title` が空の場合は `ValueError` を発生させます。セッションが見つからない場合は `FileNotFoundError`。
381
382#### 例
383
384最新のセッションの名前を変更して、後で見つけやすくします。新しいタイトルは、その後の読み取りで [`SDKSessionInfo.custom_title`](#return-type-sdk-session-info) に表示されます。
385
386```python theme={null}
387from claude_agent_sdk import list_sessions, rename_session
388
389sessions = list_sessions(directory="/path/to/project", limit=1)
390if sessions:
391 rename_session(sessions[0].session_id, "Refactor auth module")
392```
393
394### `tag_session()`
395
396セッションにタグを付けます。`None` を渡してタグをクリアします。繰り返し呼び出しは安全です。最新のタグが優先されます。同期的です。
397
398```python theme={null}
399def tag_session(
400 session_id: str,
401 tag: str | None,
402 directory: str | None = None,
403) -> None
404```
405
406#### パラメータ
407
408| パラメータ | 型 | デフォルト | 説明 |
409| :----------- | :------------ | :----- | :---------------------------------------------- |
410| `session_id` | `str` | 必須 | タグを付けるセッションの UUID |
411| `tag` | `str \| None` | 必須 | タグ文字列、またはクリアする場合は `None`。保存前に Unicode サニタイズされます |
412| `directory` | `str \| None` | `None` | プロジェクトディレクトリパス。省略した場合、すべてのプロジェクトディレクトリを検索します |
413
414`session_id` が有効な UUID でない場合、またはサニタイズ後に `tag` が空の場合は `ValueError` を発生させます。セッションが見つからない場合は `FileNotFoundError`。
415
416#### 例
417
418セッションにタグを付けてから、後の読み取りでそのタグでフィルタします。既存のタグをクリアするには `None` を渡します。
419
420```python theme={null}
421from claude_agent_sdk import list_sessions, tag_session
422
423# Tag a session
424tag_session("550e8400-e29b-41d4-a716-446655440000", "needs-review")
425
426# Later: find all sessions with that tag
427for session in list_sessions(directory="/path/to/project"):
428 if session.tag == "needs-review":
429 print(session.summary)
430```
431
432## クラス
433
434### `ClaudeSDKClient`
435
436**複数の交換にわたってセッションを維持します。** これは TypeScript SDK の `query()` 関数が内部的にどのように機能するかの Python 同等物です。会話を続けることができるクライアントオブジェクトを作成します。
437
438#### 主な機能
439
440* **セッション継続性**:複数の `query()` 呼び出しにわたって会話コンテキストを維持します
441* **同じ会話**:セッションは前のメッセージを保持します
442* **割り込みサポート**:タスク途中で実行を停止できます
443* **明示的なライフサイクル**:セッションの開始と終了を制御します
444* **応答駆動フロー**:応答に反応してフォローアップを送信できます
445* **カスタムツールと hooks**:カスタムツール(`@tool` デコレータで作成)と hooks をサポートします
446
447```python theme={null}
448class ClaudeSDKClient:
449 def __init__(self, options: ClaudeAgentOptions | None = None, transport: Transport | None = None)
450 async def connect(self, prompt: str | AsyncIterable[dict] | None = None) -> None
451 async def query(self, prompt: str | AsyncIterable[dict], session_id: str = "default") -> None
452 async def receive_messages(self) -> AsyncIterator[Message]
453 async def receive_response(self) -> AsyncIterator[Message]
454 async def interrupt(self) -> None
455 async def set_permission_mode(self, mode: str) -> None
456 async def set_model(self, model: str | None = None) -> None
457 async def rewind_files(self, user_message_id: str) -> None
458 async def get_mcp_status(self) -> McpStatusResponse
459 async def reconnect_mcp_server(self, server_name: str) -> None
460 async def toggle_mcp_server(self, server_name: str, enabled: bool) -> None
461 async def stop_task(self, task_id: str) -> None
462 async def get_server_info(self) -> dict[str, Any] | None
463 async def disconnect(self) -> None
464```
465
466#### メソッド
467
468| メソッド | 説明 |
469| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------- |
470| `__init__(options)` | オプションの設定でクライアントを初期化します |
471| `connect(prompt)` | オプションの初期プロンプトまたはメッセージストリームで Claude に接続します |
472| `query(prompt, session_id)` | ストリーミングモードで新しいリクエストを送信します |
473| `receive_messages()` | Claude からのすべてのメッセージを非同期イテレータとして受け取ります |
474| `receive_response()` | ResultMessage を含むまでのメッセージを受け取ります |
475| `interrupt()` | 割り込み信号を送信します(ストリーミングモードでのみ機能) |
476| `set_permission_mode(mode)` | 現在のセッションのパーミッションモードを変更します |
477| `set_model(model)` | 現在のセッションのモデルを変更します。デフォルトにリセットするには `None` を渡します |
478| `rewind_files(user_message_id)` | ファイルを指定されたユーザーメッセージの状態に復元します。`enable_file_checkpointing=True` が必要です。[ファイルチェックポイント](/ja/agent-sdk/file-checkpointing) を参照 |
479| `get_mcp_status()` | すべての設定済み MCP サーバーのステータスを取得します。[`McpStatusResponse`](#mcp-status-response) を返します |
480| `reconnect_mcp_server(server_name)` | 失敗したか切断された MCP サーバーへの再接続を試みます |
481| `toggle_mcp_server(server_name, enabled)` | セッション中に MCP サーバーを有効または無効にします。無効にするとそのツールが削除されます |
482| `stop_task(task_id)` | 実行中のバックグラウンドタスクを停止します。ステータス `"stopped"` の [`TaskNotificationMessage`](#task-notification-message) がメッセージストリームに続きます |
483| `get_server_info()` | セッション ID と機能を含むサーバー情報を取得します |
484| `disconnect()` | Claude から切断します |
485
486#### コンテキストマネージャーサポート
487
488クライアントは自動接続管理のための非同期コンテキストマネージャーとして使用できます:
489
490```python theme={null}
491async with ClaudeSDKClient() as client:
492 await client.query("Hello Claude")
493 async for message in client.receive_response():
494 print(message)
495```
496
497> **重要:** メッセージを反復処理する場合、早期に終了するために `break` を使用することは避けてください。これは asyncio クリーンアップの問題を引き起こす可能性があります。代わりに、反復を自然に完了させるか、フラグを使用して必要なものを見つけたときを追跡してください。
498
499#### 例 - 会話を続ける
500
501```python theme={null}
502import asyncio
503from claude_agent_sdk import ClaudeSDKClient, AssistantMessage, TextBlock, ResultMessage
504
505
506async def main():
507 async with ClaudeSDKClient() as client:
508 # First question
509 await client.query("What's the capital of France?")
510
511 # Process response
512 async for message in client.receive_response():
513 if isinstance(message, AssistantMessage):
514 for block in message.content:
515 if isinstance(block, TextBlock):
516 print(f"Claude: {block.text}")
517
518 # Follow-up question - the session retains the previous context
519 await client.query("What's the population of that city?")
520
521 async for message in client.receive_response():
522 if isinstance(message, AssistantMessage):
523 for block in message.content:
524 if isinstance(block, TextBlock):
525 print(f"Claude: {block.text}")
526
527 # Another follow-up - still in the same conversation
528 await client.query("What are some famous landmarks there?")
529
530 async for message in client.receive_response():
531 if isinstance(message, AssistantMessage):
532 for block in message.content:
533 if isinstance(block, TextBlock):
534 print(f"Claude: {block.text}")
535
536
537asyncio.run(main())
538```
539
540#### 例 - ClaudeSDKClient でのストリーミング入力
541
542```python theme={null}
543import asyncio
544from claude_agent_sdk import ClaudeSDKClient
545
546
547async def message_stream():
548 """Generate messages dynamically."""
549 yield {
550 "type": "user",
551 "message": {"role": "user", "content": "Analyze the following data:"},
552 }
553 await asyncio.sleep(0.5)
554 yield {
555 "type": "user",
556 "message": {"role": "user", "content": "Temperature: 25°C, Humidity: 60%"},
557 }
558 await asyncio.sleep(0.5)
559 yield {
560 "type": "user",
561 "message": {"role": "user", "content": "What patterns do you see?"},
562 }
563
564
565async def main():
566 async with ClaudeSDKClient() as client:
567 # Stream input to Claude
568 await client.query(message_stream())
569
570 # Process response
571 async for message in client.receive_response():
572 print(message)
573
574 # Follow-up in same session
575 await client.query("Should we be concerned about these readings?")
576
577 async for message in client.receive_response():
578 print(message)
579
580
581asyncio.run(main())
582```
583
584#### 例 - 割り込みの使用
585
586```python theme={null}
587import asyncio
588from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, ResultMessage
589
590
591async def interruptible_task():
592 options = ClaudeAgentOptions(allowed_tools=["Bash"], permission_mode="acceptEdits")
593
594 async with ClaudeSDKClient(options=options) as client:
595 # Start a long-running task
596 await client.query("Count from 1 to 100 slowly, using the bash sleep command")
597
598 # Let it run for a bit
599 await asyncio.sleep(2)
600
601 # Interrupt the task
602 await client.interrupt()
603 print("Task interrupted!")
604
605 # Drain the interrupted task's messages (including its ResultMessage)
606 async for message in client.receive_response():
607 if isinstance(message, ResultMessage):
608 print(f"Interrupted task finished with subtype={message.subtype!r}")
609 # subtype is "error_during_execution" for interrupted tasks
610
611 # Send a new command
612 await client.query("Just say hello instead")
613
614 # Now receive the new response
615 async for message in client.receive_response():
616 if isinstance(message, ResultMessage) and message.subtype == "success":
617 print(f"New result: {message.result}")
618
619
620asyncio.run(interruptible_task())
621```
622
623<Note>
624 **割り込み後のバッファ動作:** `interrupt()` は停止信号を送信しますが、メッセージバッファをクリアしません。割り込まれたタスクによって既に生成されたメッセージ(`subtype="error_during_execution"` の `ResultMessage` を含む)はストリームに残ります。新しいクエリの応答を読む前に、`receive_response()` でそれらをドレインする必要があります。`interrupt()` の直後に新しいクエリを送信し、`receive_response()` を 1 回だけ呼び出すと、割り込まれたタスクのメッセージが受け取られ、新しいクエリの応答ではありません。
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 は 2 種類の型を使用します。`@dataclass` で装飾されたクラス(`ResultMessage`、`AgentDefinition`、`TextBlock` など)は実行時にオブジェクトインスタンスであり、属性アクセスをサポートします:`msg.result`。`TypedDict` で定義されたクラス(`ThinkingConfigEnabled`、`McpStdioServerConfig`、`SyncHookJSONOutput` など)は**実行時にプレーンな dict** であり、キーアクセスが必要です:`config["budget_tokens"]`、`config.budget_tokens` ではなく。`ClassName(field=value)` 呼び出し構文は両方で機能しますが、dataclass のみが属性を持つオブジェクトを生成します。
680</Note>
681
682### `SdkMcpTool`
683
684`@tool` デコレータで作成された SDK MCP ツールの定義。
685
686```python theme={null}
687@dataclass
688class SdkMcpTool(Generic[T]):
689 name: str
690 description: str
691 input_schema: type[T] | dict[str, Any]
692 handler: Callable[[T], Awaitable[dict[str, Any]]]
693 annotations: ToolAnnotations | None = None
694```
695
696| プロパティ | 型 | 説明 |
697| :------------- | :----------------------------------------- | :--------------------------------------------------------------------------------------- |
698| `name` | `str` | ツールの一意の識別子 |
699| `description` | `str` | 人間が読める説明 |
700| `input_schema` | `type[T] \| dict[str, Any]` | 入力検証用のスキーマ |
701| `handler` | `Callable[[T], Awaitable[dict[str, Any]]]` | ツール実行を処理する非同期関数 |
702| `annotations` | `ToolAnnotations \| None` | オプションの MCP ツールアノテーション(例:`readOnlyHint`、`destructiveHint`、`openWorldHint`)。`mcp.types` から |
703
704### `Transport`
705
706カスタムトランスポート実装の抽象基本クラス。これを使用して、カスタムチャネル(例:ローカルサブプロセスの代わりにリモート接続)を介して Claude プロセスと通信します。
707
708<Warning>
709 これは低レベルの内部 API です。インターフェースは将来のリリースで変更される可能性があります。カスタム実装は、インターフェースの変更に合わせて更新する必要があります。
710</Warning>
711
712```python theme={null}
713from abc import ABC, abstractmethod
714from collections.abc import AsyncIterator
715from typing import Any
716
717
718class Transport(ABC):
719 @abstractmethod
720 async def connect(self) -> None: ...
721
722 @abstractmethod
723 async def write(self, data: str) -> None: ...
724
725 @abstractmethod
726 def read_messages(self) -> AsyncIterator[dict[str, Any]]: ...
727
728 @abstractmethod
729 async def close(self) -> None: ...
730
731 @abstractmethod
732 def is_ready(self) -> bool: ...
733
734 @abstractmethod
735 async def end_input(self) -> None: ...
736```
737
738| メソッド | 説明 |
739| :---------------- | :---------------------------------------- |
740| `connect()` | トランスポートを接続し、通信の準備をします |
741| `write(data)` | 生データ(JSON + 改行)をトランスポートに書き込みます |
742| `read_messages()` | 解析された JSON メッセージを生成する非同期イテレータ |
743| `close()` | 接続を閉じてリソースをクリーンアップします |
744| `is_ready()` | トランスポートが送受信できる場合は `True` を返します |
745| `end_input()` | 入力ストリームを閉じます(例:サブプロセストランスポートの stdin を閉じる) |
746
747インポート:`from claude_agent_sdk import Transport`
748
749### `ClaudeAgentOptions`
750
751Claude Code クエリの設定 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` | ツール設定。Claude Code のデフォルトツールには `{"type": "preset", "preset": "claude_code"}` を使用します |
799| `allowed_tools` | `list[str]` | `[]` | プロンプトなしで自動承認するツール。これは Claude をこれらのツールのみに制限しません。リストされていないツールは `permission_mode` と `can_use_tool` にフォールスルーします。`disallowed_tools` を使用してツールをブロックします。[パーミッション](/ja/agent-sdk/permissions#allow-and-deny-rules) を参照 |
800| `system_prompt` | `str \| SystemPromptPreset \| None` | `None` | システムプロンプト設定。カスタムプロンプトの場合は文字列を渡すか、Claude Code のシステムプロンプトの場合は `{"type": "preset", "preset": "claude_code"}` を使用します。プリセットを拡張するには `"append"` を追加します |
801| `mcp_servers` | `dict[str, McpServerConfig] \| str \| Path` | `{}` | MCP サーバー設定または設定ファイルへのパス |
802| `permission_mode` | `PermissionMode \| None` | `None` | ツール使用のパーミッションモード |
803| `continue_conversation` | `bool` | `False` | 最新の会話を続ける |
804| `resume` | `str \| None` | `None` | 再開するセッション ID |
805| `max_turns` | `int \| None` | `None` | 最大 agentic ターン数(ツール使用ラウンドトリップ) |
806| `max_budget_usd` | `float \| None` | `None` | クライアント側のコスト推定がこの USD 値に達したときにクエリを停止します。`total_cost_usd` と同じ推定と比較されます。[コストと使用状況を追跡](/ja/agent-sdk/cost-tracking) で精度の注意事項を参照 |
807| `disallowed_tools` | `list[str]` | `[]` | 常に拒否するツール。拒否ルールが最初にチェックされ、`allowed_tools` と `permission_mode`(`bypassPermissions` を含む)をオーバーライドします |
808| `enable_file_checkpointing` | `bool` | `False` | ファイル変更追跡を有効にして巻き戻しを可能にします。[ファイルチェックポイント](/ja/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": {...}}`)。詳細については [構造化出力](/ja/agent-sdk/structured-outputs) を参照 |
813| `permission_prompt_tool_name` | `str \| None` | `None` | パーミッションプロンプト用の MCP ツール名 |
814| `cwd` | `str \| Path \| None` | `None` | 現在の作業ディレクトリ |
815| `cli_path` | `str \| Path \| None` | `None` | Claude Code CLI 実行可能ファイルへのカスタムパス |
816| `settings` | `str \| None` | `None` | 設定ファイルへのパス |
817| `add_dirs` | `list[str \| Path]` | `[]` | Claude がアクセスできる追加ディレクトリ |
818| `env` | `dict[str, str]` | `{}` | 継承されたプロセス環境の上にマージされた環境変数。[環境変数](/ja/env-vars) で、基盤となる CLI が読み込む変数を参照 |
819| `extra_args` | `dict[str, str \| None]` | `{}` | CLI に直接渡す追加 CLI 引数 |
820| `max_buffer_size` | `int \| None` | `None` | CLI stdout をバッファリングする場合の最大バイト数 |
821| `debug_stderr` | `Any` | `sys.stderr` | *非推奨* - デバッグ出力用のファイルのようなオブジェクト。代わりに `stderr` コールバックを使用してください |
822| `stderr` | `Callable[[str], None] \| None` | `None` | CLI からの stderr 出力用のコールバック関数 |
823| `can_use_tool` | [`CanUseTool`](#can-use-tool) ` \| None` | `None` | ツールパーミッションコールバック関数。詳細については [パーミッション型](#can-use-tool) を参照 |
824| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | イベントをインターセプトするための hook 設定 |
825| `user` | `str \| None` | `None` | ユーザー識別子 |
826| `include_partial_messages` | `bool` | `False` | 部分的なメッセージストリーミングイベントを含めます。有効にすると、[`StreamEvent`](#stream-event) メッセージが生成されます |
827| `fork_session` | `bool` | `False` | `resume` で再開する場合、元のセッションを続ける代わりに新しいセッション ID にフォークします |
828| `agents` | `dict[str, AgentDefinition] \| None` | `None` | プログラムで定義されたサブエージェント |
829| `plugins` | `list[SdkPluginConfig]` | `[]` | ローカルパスからカスタムプラグインを読み込みます。詳細については [プラグイン](/ja/agent-sdk/plugins) を参照 |
830| `sandbox` | [`SandboxSettings`](#sandbox-settings) ` \| None` | `None` | プログラムでサンドボックス動作を設定します。詳細については [サンドボックス設定](#sandbox-settings) を参照 |
831| `setting_sources` | `list[SettingSource] \| None` | `None`(CLI デフォルト:すべてのソース) | 読み込むファイルシステム設定を制御します。`[]` を渡してユーザー、プロジェクト、ローカル設定を無効にします。管理ポリシー設定は常に読み込まれます。[Claude Code 機能を使用](/ja/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`](/ja/agent-sdk/session-storage#the-session-store-interface) ` \| None` | `None` | セッショントランスクリプトを外部バックエンドにミラーリングして、任意のホストがそれらを再開できるようにします。[セッションを外部ストレージに永続化](/ja/agent-sdk/session-storage) を参照 |
836
837### `OutputFormat`
838
839構造化出力検証の設定。これを `ClaudeAgentOptions` の `output_format` フィールドに dict として渡します:
840
841```python theme={null}
842# Expected dict shape for output_format
843{
844 "type": "json_schema",
845 "schema": {...}, # Your JSON Schema definition
846}
847```
848
849| フィールド | 必須 | 説明 |
850| :------- | :- | :-------------------------------------------- |
851| `type` | はい | JSON Schema 検証の場合は `"json_schema"` である必要があります |
852| `schema` | はい | 出力検証用の JSON Schema 定義 |
853
854### `SystemPromptPreset`
855
856オプションの追加を含む Claude Code のプリセットシステムプロンプトを使用するための設定。
857
858```python theme={null}
859class SystemPromptPreset(TypedDict):
860 type: Literal["preset"]
861 preset: Literal["claude_code"]
862 append: NotRequired[str]
863 exclude_dynamic_sections: NotRequired[bool]
864```
865
866| フィールド | 必須 | 説明 |
867| :------------------------- | :-- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
868| `type` | はい | プリセットシステムプロンプトを使用するには `"preset"` である必要があります |
869| `preset` | はい | Claude Code のシステムプロンプトを使用するには `"claude_code"` である必要があります |
870| `append` | いいえ | プリセットシステムプロンプトに追加する追加の指示 |
871| `exclude_dynamic_sections` | いいえ | 作業ディレクトリ、git ステータス、メモリパスなどのセッションごとのコンテキストをシステムプロンプトから最初のユーザーメッセージに移動します。ユーザーとマシン全体でのプロンプトキャッシュの再利用を改善します。[システムプロンプトを変更](/ja/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) を参照 |
872
873### `SettingSource`
874
875SDK が設定を読み込むファイルシステムベースの設定ソースを制御します。
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 が制御しないもの](/ja/agent-sdk/claude-code-features#what-settingsources-does-not-control) を参照し、それらを無効にする方法を参照してください。
890
891#### setting\_sources を使用する理由
892
893**ファイルシステム設定を無効にする:**
894
895```python theme={null}
896# Do not load user, project, or local settings from disk
897from claude_agent_sdk import query, ClaudeAgentOptions
898
899async for message in query(
900 prompt="Analyze this code",
901 options=ClaudeAgentOptions(
902 setting_sources=[]
903 ),
904):
905 print(message)
906```
907
908<Note>
909 Python SDK 0.1.59 以前では、空のリストはオプションを省略するのと同じように扱われていたため、`setting_sources=[]` はファイルシステム設定を無効にしませんでした。空のリストが有効になる必要がある場合は、新しいリリースにアップグレードしてください。TypeScript SDK は影響を受けません。
910</Note>
911
912**すべてのファイルシステム設定を明示的に読み込む:**
913
914```python theme={null}
915from claude_agent_sdk import query, ClaudeAgentOptions
916
917async for message in query(
918 prompt="Analyze this code",
919 options=ClaudeAgentOptions(
920 setting_sources=["user", "project", "local"]
921 ),
922):
923 print(message)
924```
925
926**特定の設定ソースのみを読み込む:**
927
928```python theme={null}
929# Load only project settings, ignore user and local
930async for message in query(
931 prompt="Run CI checks",
932 options=ClaudeAgentOptions(
933 setting_sources=["project"] # Only .claude/settings.json
934 ),
935):
936 print(message)
937```
938
939**テストと CI 環境:**
940
941```python theme={null}
942# Ensure consistent behavior in CI by excluding local settings
943async for message in query(
944 prompt="Run tests",
945 options=ClaudeAgentOptions(
946 setting_sources=["project"], # Only team-shared settings
947 permission_mode="bypassPermissions",
948 ),
949):
950 print(message)
951```
952
953**SDK のみのアプリケーション:**
954
955```python theme={null}
956# Define everything programmatically.
957# Pass [] to opt out of filesystem setting sources.
958async for message in query(
959 prompt="Review this PR",
960 options=ClaudeAgentOptions(
961 setting_sources=[],
962 agents={...},
963 mcp_servers={...},
964 allowed_tools=["Read", "Grep", "Glob"],
965 ),
966):
967 print(message)
968```
969
970**CLAUDE.md プロジェクト指示を読み込む:**
971
972```python theme={null}
973# Load project settings to include CLAUDE.md files
974async for message in query(
975 prompt="Add a new feature following project conventions",
976 options=ClaudeAgentOptions(
977 system_prompt={
978 "type": "preset",
979 "preset": "claude_code", # Use Claude Code's system prompt
980 },
981 setting_sources=["project"], # Loads CLAUDE.md from project
982 allowed_tools=["Read", "Write", "Edit"],
983 ),
984):
985 print(message)
986```
987
988#### 設定の優先順位
989
990複数のソースが読み込まれる場合、設定はこの優先順位(最高から最低)でマージされます:
991
9921. ローカル設定(`.claude/settings.local.json`)
9932. プロジェクト設定(`.claude/settings.json`)
9943. ユーザー設定(`~/.claude/settings.json`)
995
996`agents` と `allowed_tools` などのプログラム的なオプションは、ユーザー、プロジェクト、ローカルのファイルシステム設定をオーバーライドします。管理ポリシー設定はプログラム的なオプションより優先されます。
997
998### `AgentDefinition`
999
1000プログラムで定義されたサブエージェントの設定。
1001
1002```python theme={null}
1003@dataclass
1004class AgentDefinition:
1005 description: str
1006 prompt: str
1007 tools: list[str] | None = None
1008 disallowedTools: list[str] | None = None
1009 model: str | None = None
1010 skills: list[str] | None = None
1011 memory: Literal["user", "project", "local"] | None = None
1012 mcpServers: list[str | dict[str, Any]] | None = None
1013 initialPrompt: str | None = None
1014 maxTurns: int | None = None
1015 background: bool | None = None
1016 effort: Literal["low", "medium", "high", "max"] | int | None = None
1017 permissionMode: PermissionMode | None = None
1018```
1019
1020| フィールド | 必須 | 説明 |
1021| :---------------- | :-- | :-------------------------------------------------------------------------------------------------------------- |
1022| `description` | はい | このエージェントを使用する場合の自然言語説明 |
1023| `prompt` | はい | エージェントのシステムプロンプト |
1024| `tools` | いいえ | 許可されたツール名の配列。省略した場合、すべてのツールを継承します |
1025| `disallowedTools` | いいえ | エージェントのツールセットから削除するツール名の配列 |
1026| `model` | いいえ | このエージェントのモデルオーバーライド。`"sonnet"`、`"opus"`、`"haiku"`、`"inherit"` などのエイリアス、または完全なモデル ID を受け入れます。省略した場合、メインモデルを使用します |
1027| `skills` | いいえ | このエージェントが利用可能なスキル名のリスト |
1028| `memory` | いいえ | このエージェントのメモリソース:`"user"`、`"project"`、または `"local"` |
1029| `mcpServers` | いいえ | このエージェントが利用可能な MCP サーバー。各エントリはサーバー名またはインライン `{name: config}` dict です |
1030| `initialPrompt` | いいえ | このエージェントがメインスレッドエージェントとして実行される場合、最初のユーザーターンとして自動送信されます |
1031| `maxTurns` | いいえ | エージェントが停止する前の最大 agentic ターン数 |
1032| `background` | いいえ | 呼び出されたときにこのエージェントをブロッキングされないバックグラウンドタスクとして実行します |
1033| `effort` | いいえ | このエージェントの推論努力レベル。名前付きレベルまたは整数を受け入れます |
1034| `permissionMode` | いいえ | このエージェント内のツール実行のパーミッションモード。[`PermissionMode`](#permission-mode) を参照 |
1035
1036<Note>
1037 `AgentDefinition` フィールド名は `disallowedTools`、`permissionMode`、`maxTurns` などの camelCase を使用します。これらの名前は TypeScript SDK と共有される wire 形式に直接マップされます。これは `disallowed_tools` と `permission_mode` などの同等のトップレベルフィールドに Python snake\_case を使用する `ClaudeAgentOptions` とは異なります。`AgentDefinition` は dataclass であるため、snake\_case キーワードを渡すと構築時に `TypeError` が発生します。
1038</Note>
1039
1040### `PermissionMode`
1041
1042ツール実行を制御するためのパーミッションモード。
1043
1044```python theme={null}
1045PermissionMode = Literal[
1046 "default", # Standard permission behavior
1047 "acceptEdits", # Auto-accept file edits
1048 "plan", # Planning mode - no execution
1049 "dontAsk", # Deny anything not pre-approved instead of prompting
1050 "bypassPermissions", # Bypass all permission checks (use with caution)
1051]
1052```
1053
1054### `CanUseTool`
1055
1056ツールパーミッションコールバック関数の型エイリアス。
1057
1058```python theme={null}
1059CanUseTool = Callable[
1060 [str, dict[str, Any], ToolPermissionContext], Awaitable[PermissionResult]
1061]
1062```
1063
1064コールバックは以下を受け取ります:
1065
1066* `tool_name`:呼び出されるツールの名前
1067* `input_data`:ツールの入力パラメータ
1068* `context`:追加情報を含む `ToolPermissionContext`
1069
1070`PermissionResult`(`PermissionResultAllow` または `PermissionResultDeny`)を返します。
1071
1072### `ToolPermissionContext`
1073
1074ツールパーミッションコールバックに渡されるコンテキスト情報。
1075
1076```python theme={null}
1077@dataclass
1078class ToolPermissionContext:
1079 signal: Any | None = None # Future: abort signal support
1080 suggestions: list[PermissionUpdate] = field(default_factory=list)
1081```
1082
1083| フィールド | 型 | 説明 |
1084| :------------ | :----------------------- | :----------------- |
1085| `signal` | `Any \| None` | 将来の中止信号サポート用に予約済み |
1086| `suggestions` | `list[PermissionUpdate]` | CLI からのパーミッション更新提案 |
1087
1088### `PermissionResult`
1089
1090パーミッションコールバック結果の Union 型。
1091
1092```python theme={null}
1093PermissionResult = PermissionResultAllow | PermissionResultDeny
1094```
1095
1096### `PermissionResultAllow`
1097
1098ツール呼び出しを許可すべきことを示す結果。
1099
1100```python theme={null}
1101@dataclass
1102class PermissionResultAllow:
1103 behavior: Literal["allow"] = "allow"
1104 updated_input: dict[str, Any] | None = None
1105 updated_permissions: list[PermissionUpdate] | None = None
1106```
1107
1108| フィールド | 型 | デフォルト | 説明 |
1109| :-------------------- | :------------------------------- | :-------- | :----------------- |
1110| `behavior` | `Literal["allow"]` | `"allow"` | "allow" である必要があります |
1111| `updated_input` | `dict[str, Any] \| None` | `None` | 元の代わりに使用する変更された入力 |
1112| `updated_permissions` | `list[PermissionUpdate] \| None` | `None` | 適用するパーミッション更新 |
1113
1114### `PermissionResultDeny`
1115
1116ツール呼び出しを拒否すべきことを示す結果。
1117
1118```python theme={null}
1119@dataclass
1120class PermissionResultDeny:
1121 behavior: Literal["deny"] = "deny"
1122 message: str = ""
1123 interrupt: bool = False
1124```
1125
1126| フィールド | 型 | デフォルト | 説明 |
1127| :---------- | :---------------- | :------- | :-------------------- |
1128| `behavior` | `Literal["deny"]` | `"deny"` | "deny" である必要があります |
1129| `message` | `str` | `""` | ツールが拒否された理由を説明するメッセージ |
1130| `interrupt` | `bool` | `False` | 現在の実行を割り込むかどうか |
1131
1132### `PermissionUpdate`
1133
1134プログラムでパーミッションを更新するための設定。
1135
1136```python theme={null}
1137@dataclass
1138class PermissionUpdate:
1139 type: Literal[
1140 "addRules",
1141 "replaceRules",
1142 "removeRules",
1143 "setMode",
1144 "addDirectories",
1145 "removeDirectories",
1146 ]
1147 rules: list[PermissionRuleValue] | None = None
1148 behavior: Literal["allow", "deny", "ask"] | None = None
1149 mode: PermissionMode | None = None
1150 directories: list[str] | None = None
1151 destination: (
1152 Literal["userSettings", "projectSettings", "localSettings", "session"] | None
1153 ) = None
1154```
1155
1156| フィールド | 型 | 説明 |
1157| :------------ | :---------------------------------------- | :-------------------- |
1158| `type` | `Literal[...]` | パーミッション更新操作のタイプ |
1159| `rules` | `list[PermissionRuleValue] \| None` | 追加/置換/削除操作用のルール |
1160| `behavior` | `Literal["allow", "deny", "ask"] \| None` | ルールベースの操作の動作 |
1161| `mode` | `PermissionMode \| None` | setMode 操作のモード |
1162| `directories` | `list[str] \| None` | ディレクトリ追加/削除操作用のディレクトリ |
1163| `destination` | `Literal[...] \| None` | パーミッション更新を適用する場所 |
1164
1165### `PermissionRuleValue`
1166
1167パーミッション更新で追加、置換、または削除するルール。
1168
1169```python theme={null}
1170@dataclass
1171class PermissionRuleValue:
1172 tool_name: str
1173 rule_content: str | None = None
1174```
1175
1176### `ToolsPreset`
1177
1178Claude Code のデフォルトツールセットを使用するためのプリセットツール設定。
1179
1180```python theme={null}
1181class ToolsPreset(TypedDict):
1182 type: Literal["preset"]
1183 preset: Literal["claude_code"]
1184```
1185
1186### `ThinkingConfig`
1187
1188拡張思考動作を制御します。3 つの設定の Union:
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 です。dict リテラルとして構築するか、クラスをコンストラクタのように呼び出します。どちらも `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 ベータ機能の Literal 型。
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 サーバー設定の Union 型。
1255
1256```python theme={null}
1257McpServerConfig = (
1258 McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig
1259)
1260```
1261
1262#### `McpStdioServerConfig`
1263
1264```python theme={null}
1265class McpStdioServerConfig(TypedDict):
1266 type: NotRequired[Literal["stdio"]] # Optional for backwards compatibility
1267 command: str
1268 args: NotRequired[list[str]]
1269 env: NotRequired[dict[str, str]]
1270```
1271
1272#### `McpSSEServerConfig`
1273
1274```python theme={null}
1275class McpSSEServerConfig(TypedDict):
1276 type: Literal["sse"]
1277 url: str
1278 headers: NotRequired[dict[str, str]]
1279```
1280
1281#### `McpHttpServerConfig`
1282
1283```python theme={null}
1284class McpHttpServerConfig(TypedDict):
1285 type: Literal["http"]
1286 url: str
1287 headers: NotRequired[dict[str, str]]
1288```
1289
1290### `McpServerStatusConfig`
1291
1292[`get_mcp_status()`](#methods) によって報告される MCP サーバーの設定。これは、すべての [`McpServerConfig`](#mcp-server-config) トランスポートバリアント、および claude.ai を通じてプロキシされるサーバー用の出力のみの `claudeai-proxy` バリアントの Union です。
1293
1294```python theme={null}
1295McpServerStatusConfig = (
1296 McpStdioServerConfig
1297 | McpSSEServerConfig
1298 | McpHttpServerConfig
1299 | McpSdkServerConfigStatus
1300 | McpClaudeAIProxyServerConfig
1301)
1302```
1303
1304`McpSdkServerConfigStatus` は [`McpSdkServerConfig`](#mcp-sdk-server-config) のシリアライズ可能な形式で、`type`(`"sdk"`)と `name`(`str`)フィールドのみです。インプロセス `instance` は省略されます。`McpClaudeAIProxyServerConfig` には `type`(`"claudeai-proxy"`)、`url`(`str`)、`id`(`str`)フィールドがあります。
1305
1306### `McpStatusResponse`
1307
1308[`ClaudeSDKClient.get_mcp_status()`](#methods) からの応答。サーバーステータスのリストを `mcpServers` キーの下にラップします。
1309
1310```python theme={null}
1311class McpStatusResponse(TypedDict):
1312 mcpServers: list[McpServerStatus]
1313```
1314
1315### `McpServerStatus`
1316
1317接続された MCP サーバーのステータス。[`McpStatusResponse`](#mcp-status-response) に含まれます。
1318
1319```python theme={null}
1320class McpServerStatus(TypedDict):
1321 name: str
1322 status: McpServerConnectionStatus # "connected" | "failed" | "needs-auth" | "pending" | "disabled"
1323 serverInfo: NotRequired[McpServerInfo]
1324 error: NotRequired[str]
1325 config: NotRequired[McpServerStatusConfig]
1326 scope: NotRequired[str]
1327 tools: NotRequired[list[McpToolInfo]]
1328```
1329
1330| フィールド | 型 | 説明 |
1331| :----------- | :---------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
1332| `name` | `str` | サーバー名 |
1333| `status` | `str` | `"connected"`、`"failed"`、`"needs-auth"`、`"pending"`、または `"disabled"` のいずれか |
1334| `serverInfo` | `dict`(オプション) | サーバー名とバージョン(`{"name": str, "version": str}`) |
1335| `error` | `str`(オプション) | サーバーが接続に失敗した場合のエラーメッセージ |
1336| `config` | [`McpServerStatusConfig`](#mcp-server-status-config)(オプション) | サーバー設定。[`McpServerConfig`](#mcp-server-config) と同じ形状(stdio、SSE、HTTP、または SDK)、および claude.ai を通じて接続されたサーバー用の `claudeai-proxy` バリアント |
1337| `scope` | `str`(オプション) | 設定スコープ |
1338| `tools` | `list`(オプション) | このサーバーが提供するツール。各ツールには `name`、`description`、`annotations` フィールドがあります |
1339
1340### `SdkPluginConfig`
1341
1342SDK でプラグインを読み込むための設定。
1343
1344```python theme={null}
1345class SdkPluginConfig(TypedDict):
1346 type: Literal["local"]
1347 path: str
1348```
1349
1350| フィールド | 型 | 説明 |
1351| :----- | :----------------- | :-------------------------------------- |
1352| `type` | `Literal["local"]` | `"local"` である必要があります(現在ローカルプラグインのみサポート) |
1353| `path` | `str` | プラグインディレクトリへの絶対パスまたは相対パス |
1354
1355**例:**
1356
1357```python theme={null}
1358plugins = [
1359 {"type": "local", "path": "./my-plugin"},
1360 {"type": "local", "path": "/absolute/path/to/plugin"},
1361]
1362```
1363
1364プラグインの作成と使用に関する完全な情報については、[プラグイン](/ja/agent-sdk/plugins) を参照してください。
1365
1366## メッセージ型
1367
1368### `Message`
1369
1370すべての可能なメッセージの Union 型。
1371
1372```python theme={null}
1373Message = (
1374 UserMessage
1375 | AssistantMessage
1376 | SystemMessage
1377 | ResultMessage
1378 | StreamEvent
1379 | RateLimitEvent
1380)
1381```
1382
1383### `UserMessage`
1384
1385ユーザー入力メッセージ。
1386
1387```python theme={null}
1388@dataclass
1389class UserMessage:
1390 content: str | list[ContentBlock]
1391 uuid: str | None = None
1392 parent_tool_use_id: str | None = None
1393 tool_use_result: dict[str, Any] | None = None
1394```
1395
1396| フィールド | 型 | 説明 |
1397| :------------------- | :-------------------------- | :----------------------------- |
1398| `content` | `str \| list[ContentBlock]` | テキストまたはコンテンツブロックとしてのメッセージコンテンツ |
1399| `uuid` | `str \| None` | 一意のメッセージ識別子 |
1400| `parent_tool_use_id` | `str \| None` | このメッセージがツール結果応答の場合のツール使用 ID |
1401| `tool_use_result` | `dict[str, Any] \| None` | 該当する場合のツール結果データ |
1402
1403### `AssistantMessage`
1404
1405コンテンツブロック付きのアシスタント応答メッセージ。
1406
1407```python theme={null}
1408@dataclass
1409class AssistantMessage:
1410 content: list[ContentBlock]
1411 model: str
1412 parent_tool_use_id: str | None = None
1413 error: AssistantMessageError | None = None
1414 usage: dict[str, Any] | None = None
1415 message_id: str | None = None
1416```
1417
1418| フィールド | 型 | 説明 |
1419| :------------------- | :------------------------------------------------------------- | :--------------------------------------------------------------- |
1420| `content` | `list[ContentBlock]` | 応答内のコンテンツブロックのリスト |
1421| `model` | `str` | 応答を生成したモデル |
1422| `parent_tool_use_id` | `str \| None` | これがネストされた応答の場合のツール使用 ID |
1423| `error` | [`AssistantMessageError`](#assistant-message-error) ` \| None` | 応答がエラーに遭遇した場合のエラー型 |
1424| `usage` | `dict[str, Any] \| None` | メッセージごとのトークン使用状況([`ResultMessage.usage`](#result-message) と同じキー) |
1425| `message_id` | `str \| None` | API メッセージ ID。1 つのターンからの複数のメッセージは同じ 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` dict には、存在する場合、以下のキーが含まれます:
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` dict はモデル名をモデルごとの使用状況にマップします。内部 dict キーは camelCase を使用します。これは、基になる CLI プロセスから変更されずに渡される値であり、TypeScript [`ModelUsage`](/ja/agent-sdk/typescript#model-usage) 型と一致するためです:
1485
1486| キー | 型 | 説明 |
1487| -------------------------- | ------- | --------------------------------------------------------------------------------------------- |
1488| `inputTokens` | `int` | このモデルの入力トークン。 |
1489| `outputTokens` | `int` | このモデルの出力トークン。 |
1490| `cacheReadInputTokens` | `int` | このモデルのキャッシュ読み取りトークン。 |
1491| `cacheCreationInputTokens` | `int` | このモデルのキャッシュ作成トークン。 |
1492| `webSearchRequests` | `int` | このモデルが行った Web 検索リクエスト。 |
1493| `costUSD` | `float` | このモデルの推定 USD コスト。クライアント側で計算されます。[コストと使用状況を追跡](/ja/agent-sdk/cost-tracking) で請求の注意事項を参照してください。 |
1494| `contextWindow` | `int` | このモデルのコンテキストウィンドウサイズ。 |
1495| `maxOutputTokens` | `int` | このモデルの最大出力トークン制限。 |
1496
1497### `StreamEvent`
1498
1499ストリーミング中の部分的なメッセージ更新のためのストリームイベント。`ClaudeAgentOptions` で `include_partial_messages=True` の場合のみ受け取られます。`from claude_agent_sdk.types import StreamEvent` でインポートしてください。
1500
1501```python theme={null}
1502@dataclass
1503class StreamEvent:
1504 uuid: str
1505 session_id: str
1506 event: dict[str, Any] # The raw Claude API stream event
1507 parent_tool_use_id: str | None = None
1508```
1509
1510| フィールド | 型 | 説明 |
1511| :------------------- | :--------------- | :----------------------------- |
1512| `uuid` | `str` | このイベントの一意の識別子 |
1513| `session_id` | `str` | セッション識別子 |
1514| `event` | `dict[str, Any]` | 生の Claude API ストリームイベントデータ |
1515| `parent_tool_use_id` | `str \| None` | このイベントがサブエージェントからの場合の親ツール使用 ID |
1516
1517### `RateLimitEvent`
1518
1519レート制限ステータスが変更されたときに発行されます(例:`"allowed"` から `"allowed_warning"` へ)。ユーザーにハード制限に達する前に警告するか、ステータスが `"rejected"` の場合にバックオフするために使用します。
1520
1521```python theme={null}
1522@dataclass
1523class RateLimitEvent:
1524 rate_limit_info: RateLimitInfo
1525 uuid: str
1526 session_id: str
1527```
1528
1529| フィールド | 型 | 説明 |
1530| :---------------- | :---------------------------------- | :--------- |
1531| `rate_limit_info` | [`RateLimitInfo`](#rate-limit-info) | 現在のレート制限状態 |
1532| `uuid` | `str` | 一意のイベント識別子 |
1533| `session_id` | `str` | セッション識別子 |
1534
1535### `RateLimitInfo`
1536
1537[`RateLimitEvent`](#rate-limit-event) によって運ばれるレート制限状態。
1538
1539```python theme={null}
1540RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]
1541RateLimitType = Literal[
1542 "five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet", "overage"
1543]
1544
1545
1546@dataclass
1547class RateLimitInfo:
1548 status: RateLimitStatus
1549 resets_at: int | None = None
1550 rate_limit_type: RateLimitType | None = None
1551 utilization: float | None = None
1552 overage_status: RateLimitStatus | None = None
1553 overage_resets_at: int | None = None
1554 overage_disabled_reason: str | None = None
1555 raw: dict[str, Any] = field(default_factory=dict)
1556```
1557
1558| フィールド | 型 | 説明 |
1559| :------------------------ | :------------------------ | :--------------------------------------------------------------------------- |
1560| `status` | `RateLimitStatus` | 現在のステータス。`"allowed_warning"` は制限に近づいていることを意味します。`"rejected"` は制限に達したことを意味します |
1561| `resets_at` | `int \| None` | レート制限ウィンドウがリセットされる Unix タイムスタンプ |
1562| `rate_limit_type` | `RateLimitType \| None` | どのレート制限ウィンドウが適用されるか |
1563| `utilization` | `float \| None` | 消費されたレート制限の割合(0.0 から 1.0) |
1564| `overage_status` | `RateLimitStatus \| None` | 該当する場合の従量課金超過使用のステータス |
1565| `overage_resets_at` | `int \| None` | 超過ウィンドウがリセットされる Unix タイムスタンプ |
1566| `overage_disabled_reason` | `str \| None` | ステータスが `"rejected"` の場合、超過が利用できない理由 |
1567| `raw` | `dict[str, Any]` | 上記でモデル化されていないフィールドを含む、CLI からの完全な生 dict |
1568
1569### `TaskStartedMessage`
1570
1571バックグラウンドタスクが開始されたときに発行されます。バックグラウンドタスクは、メインターンの外で追跡されるもの:バックグラウンド Bash コマンド、[Monitor](#monitor) ウォッチ、Agent ツール経由で生成されたサブエージェント、またはリモートエージェント。`task_type` フィールドはどれであるかを示します。このネーミングは `Task` から `Agent` ツールへの名前変更とは無関係です。
1572
1573```python theme={null}
1574@dataclass
1575class TaskStartedMessage(SystemMessage):
1576 task_id: str
1577 description: str
1578 uuid: str
1579 session_id: str
1580 tool_use_id: str | None = None
1581 task_type: str | None = None
1582```
1583
1584| フィールド | 型 | 説明 |
1585| :------------ | :------------ | :-------------------------------------------------------------------------------------------------- |
1586| `task_id` | `str` | タスクの一意の識別子 |
1587| `description` | `str` | タスクの説明 |
1588| `uuid` | `str` | 一意のメッセージ識別子 |
1589| `session_id` | `str` | セッション識別子 |
1590| `tool_use_id` | `str \| None` | 関連するツール使用 ID |
1591| `task_type` | `str \| None` | バックグラウンドタスクの種類:バックグラウンド Bash と Monitor ウォッチの場合は `"local_bash"`、`"local_agent"`、または `"remote_agent"` |
1592
1593### `TaskUsage`
1594
1595バックグラウンドタスクのトークンとタイミングデータ。
1596
1597```python theme={null}
1598class TaskUsage(TypedDict):
1599 total_tokens: int
1600 tool_uses: int
1601 duration_ms: int
1602```
1603
1604### `TaskProgressMessage`
1605
1606実行中のバックグラウンドタスクの進捗更新で定期的に発行されます。
1607
1608```python theme={null}
1609@dataclass
1610class TaskProgressMessage(SystemMessage):
1611 task_id: str
1612 description: str
1613 usage: TaskUsage
1614 uuid: str
1615 session_id: str
1616 tool_use_id: str | None = None
1617 last_tool_name: str | None = None
1618```
1619
1620| フィールド | 型 | 説明 |
1621| :--------------- | :------------ | :------------------ |
1622| `task_id` | `str` | タスクの一意の識別子 |
1623| `description` | `str` | 現在のステータス説明 |
1624| `usage` | `TaskUsage` | これまでのこのタスクのトークン使用状況 |
1625| `uuid` | `str` | 一意のメッセージ識別子 |
1626| `session_id` | `str` | セッション識別子 |
1627| `tool_use_id` | `str \| None` | 関連するツール使用 ID |
1628| `last_tool_name` | `str \| None` | タスクが最後に使用したツールの名前 |
1629
1630### `TaskNotificationMessage`
1631
1632バックグラウンドタスクが完了、失敗、または停止されたときに発行されます。バックグラウンドタスクには、`run_in_background` Bash コマンド、Monitor ウォッチ、バックグラウンドサブエージェントが含まれます。
1633
1634```python theme={null}
1635@dataclass
1636class TaskNotificationMessage(SystemMessage):
1637 task_id: str
1638 status: TaskNotificationStatus # "completed" | "failed" | "stopped"
1639 output_file: str
1640 summary: str
1641 uuid: str
1642 session_id: str
1643 tool_use_id: str | None = None
1644 usage: TaskUsage | None = None
1645```
1646
1647| フィールド | 型 | 説明 |
1648| :------------ | :----------------------- | :--------------------------------------------- |
1649| `task_id` | `str` | タスクの一意の識別子 |
1650| `status` | `TaskNotificationStatus` | `"completed"`、`"failed"`、または `"stopped"` のいずれか |
1651| `output_file` | `str` | タスク出力ファイルへのパス |
1652| `summary` | `str` | タスク結果のサマリー |
1653| `uuid` | `str` | 一意のメッセージ識別子 |
1654| `session_id` | `str` | セッション識別子 |
1655| `tool_use_id` | `str \| None` | 関連するツール使用 ID |
1656| `usage` | `TaskUsage \| None` | タスクの最終トークン使用状況 |
1657
1658## コンテンツブロック型
1659
1660### `ContentBlock`
1661
1662すべてのコンテンツブロックの Union 型。
1663
1664```python theme={null}
1665ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
1666```
1667
1668### `TextBlock`
1669
1670テキストコンテンツブロック。
1671
1672```python theme={null}
1673@dataclass
1674class TextBlock:
1675 text: str
1676```
1677
1678### `ThinkingBlock`
1679
1680思考コンテンツブロック(思考機能を持つモデル用)。
1681
1682```python theme={null}
1683@dataclass
1684class ThinkingBlock:
1685 thinking: str
1686 signature: str
1687```
1688
1689### `ToolUseBlock`
1690
1691ツール使用リクエストブロック。
1692
1693```python theme={null}
1694@dataclass
1695class ToolUseBlock:
1696 id: str
1697 name: str
1698 input: dict[str, Any]
1699```
1700
1701### `ToolResultBlock`
1702
1703ツール実行結果ブロック。
1704
1705```python theme={null}
1706@dataclass
1707class ToolResultBlock:
1708 tool_use_id: str
1709 content: str | list[dict[str, Any]] | None = None
1710 is_error: bool | None = None
1711```
1712
1713## エラー型
1714
1715### `ClaudeSDKError`
1716
1717すべての SDK エラーの基本例外クラス。
1718
1719```python theme={null}
1720class ClaudeSDKError(Exception):
1721 """Base error for Claude SDK."""
1722```
1723
1724### `CLINotFoundError`
1725
1726Claude 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
1742Claude Code への接続に失敗した場合に発生します。
1743
1744```python theme={null}
1745class CLIConnectionError(ClaudeSDKError):
1746 """Failed to connect to Claude Code."""
1747```
1748
1749### `ProcessError`
1750
1751Claude 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
1764JSON 解析に失敗した場合に発生します。
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
1780hooks の使用に関する包括的なガイド、例、一般的なパターンについては、[Hooks ガイド](/ja/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_event_name` に基づいた判別 Union を持つ強く型付けされた hook 入力([`HookInput`](#hook-input) を参照)
1816* `tool_use_id`:オプションのツール使用識別子(ツール関連の hook 用)
1817* `context`:追加情報を含む hook コンテキスト
1818
1819以下を含む可能性のある [`HookJSONOutput`](#hook-json-output) を返します:
1820
1821* `decision`:アクションをブロックするには `"block"`
1822* `systemMessage`:トランスクリプトに追加するシステムメッセージ
1823* `hookSpecificOutput`:hook 固有の出力データ
1824
1825### `HookContext`
1826
1827hook コールバックに渡されるコンテキスト情報。
1828
1829```python theme={null}
1830class HookContext(TypedDict):
1831 signal: Any | None # Future: abort signal support
1832```
1833
1834### `HookMatcher`
1835
1836特定のイベントまたはツールに hook をマッチングするための設定。
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 入力型の Union 型。実際の型は `hook_event_name` フィールドに依存します。
1855
1856```python theme={null}
1857HookInput = (
1858 PreToolUseHookInput
1859 | PostToolUseHookInput
1860 | PostToolUseFailureHookInput
1861 | UserPromptSubmitHookInput
1862 | StopHookInput
1863 | SubagentStopHookInput
1864 | PreCompactHookInput
1865 | NotificationHookInput
1866 | SubagentStartHookInput
1867 | PermissionRequestHookInput
1868)
1869```
1870
1871### `BaseHookInput`
1872
1873すべての hook 入力型に存在する基本フィールド。
1874
1875```python theme={null}
1876class BaseHookInput(TypedDict):
1877 session_id: str
1878 transcript_path: str
1879 cwd: str
1880 permission_mode: NotRequired[str]
1881```
1882
1883| フィールド | 型 | 説明 |
1884| :---------------- | :----------- | :-------------------- |
1885| `session_id` | `str` | 現在のセッション識別子 |
1886| `transcript_path` | `str` | セッショントランスクリプトファイルへのパス |
1887| `cwd` | `str` | 現在の作業ディレクトリ |
1888| `permission_mode` | `str`(オプション) | 現在のパーミッションモード |
1889
1890### `PreToolUseHookInput`
1891
1892`PreToolUse` hook イベントの入力データ。
1893
1894```python theme={null}
1895class PreToolUseHookInput(BaseHookInput):
1896 hook_event_name: Literal["PreToolUse"]
1897 tool_name: str
1898 tool_input: dict[str, Any]
1899 tool_use_id: str
1900 agent_id: NotRequired[str]
1901 agent_type: NotRequired[str]
1902```
1903
1904| フィールド | 型 | 説明 |
1905| :---------------- | :---------------------- | :------------------------------------ |
1906| `hook_event_name` | `Literal["PreToolUse"]` | 常に "PreToolUse" |
1907| `tool_name` | `str` | 実行しようとしているツールの名前 |
1908| `tool_input` | `dict[str, Any]` | ツールの入力パラメータ |
1909| `tool_use_id` | `str` | このツール使用の一意の識別子 |
1910| `agent_id` | `str`(オプション) | サブエージェント識別子。hook がサブエージェント内で発火する場合に存在 |
1911| `agent_type` | `str`(オプション) | サブエージェント型。hook がサブエージェント内で発火する場合に存在 |
1912
1913### `PostToolUseHookInput`
1914
1915`PostToolUse` hook イベントの入力データ。
1916
1917```python theme={null}
1918class PostToolUseHookInput(BaseHookInput):
1919 hook_event_name: Literal["PostToolUse"]
1920 tool_name: str
1921 tool_input: dict[str, Any]
1922 tool_response: Any
1923 tool_use_id: str
1924 agent_id: NotRequired[str]
1925 agent_type: NotRequired[str]
1926```
1927
1928| フィールド | 型 | 説明 |
1929| :---------------- | :----------------------- | :------------------------------------ |
1930| `hook_event_name` | `Literal["PostToolUse"]` | 常に "PostToolUse" |
1931| `tool_name` | `str` | 実行されたツールの名前 |
1932| `tool_input` | `dict[str, Any]` | 使用された入力パラメータ |
1933| `tool_response` | `Any` | ツール実行からの応答 |
1934| `tool_use_id` | `str` | このツール使用の一意の識別子 |
1935| `agent_id` | `str`(オプション) | サブエージェント識別子。hook がサブエージェント内で発火する場合に存在 |
1936| `agent_type` | `str`(オプション) | サブエージェント型。hook がサブエージェント内で発火する場合に存在 |
1937
1938### `PostToolUseFailureHookInput`
1939
1940`PostToolUseFailure` hook イベントの入力データ。ツール実行が失敗したときに呼び出されます。
1941
1942```python theme={null}
1943class PostToolUseFailureHookInput(BaseHookInput):
1944 hook_event_name: Literal["PostToolUseFailure"]
1945 tool_name: str
1946 tool_input: dict[str, Any]
1947 tool_use_id: str
1948 error: str
1949 is_interrupt: NotRequired[bool]
1950 agent_id: NotRequired[str]
1951 agent_type: NotRequired[str]
1952```
1953
1954| フィールド | 型 | 説明 |
1955| :---------------- | :------------------------------ | :------------------------------------ |
1956| `hook_event_name` | `Literal["PostToolUseFailure"]` | 常に "PostToolUseFailure" |
1957| `tool_name` | `str` | 失敗したツールの名前 |
1958| `tool_input` | `dict[str, Any]` | 使用された入力パラメータ |
1959| `tool_use_id` | `str` | このツール使用の一意の識別子 |
1960| `error` | `str` | 失敗した実行からのエラーメッセージ |
1961| `is_interrupt` | `bool`(オプション) | 失敗が割り込みによって引き起こされたかどうか |
1962| `agent_id` | `str`(オプション) | サブエージェント識別子。hook がサブエージェント内で発火する場合に存在 |
1963| `agent_type` | `str`(オプション) | サブエージェント型。hook がサブエージェント内で発火する場合に存在 |
1964
1965### `UserPromptSubmitHookInput`
1966
1967`UserPromptSubmit` hook イベントの入力データ。
1968
1969```python theme={null}
1970class UserPromptSubmitHookInput(BaseHookInput):
1971 hook_event_name: Literal["UserPromptSubmit"]
1972 prompt: str
1973```
1974
1975| フィールド | 型 | 説明 |
1976| :---------------- | :---------------------------- | :-------------------- |
1977| `hook_event_name` | `Literal["UserPromptSubmit"]` | 常に "UserPromptSubmit" |
1978| `prompt` | `str` | ユーザーが送信したプロンプト |
1979
1980### `StopHookInput`
1981
1982`Stop` hook イベントの入力データ。
1983
1984```python theme={null}
1985class StopHookInput(BaseHookInput):
1986 hook_event_name: Literal["Stop"]
1987 stop_hook_active: bool
1988```
1989
1990| フィールド | 型 | 説明 |
1991| :----------------- | :---------------- | :------------------- |
1992| `hook_event_name` | `Literal["Stop"]` | 常に "Stop" |
1993| `stop_hook_active` | `bool` | stop hook がアクティブかどうか |
1994
1995### `SubagentStopHookInput`
1996
1997`SubagentStop` hook イベントの入力データ。
1998
1999```python theme={null}
2000class SubagentStopHookInput(BaseHookInput):
2001 hook_event_name: Literal["SubagentStop"]
2002 stop_hook_active: bool
2003 agent_id: str
2004 agent_transcript_path: str
2005 agent_type: str
2006```
2007
2008| フィールド | 型 | 説明 |
2009| :---------------------- | :------------------------ | :------------------------ |
2010| `hook_event_name` | `Literal["SubagentStop"]` | 常に "SubagentStop" |
2011| `stop_hook_active` | `bool` | stop hook がアクティブかどうか |
2012| `agent_id` | `str` | サブエージェントの一意の識別子 |
2013| `agent_transcript_path` | `str` | サブエージェントのトランスクリプトファイルへのパス |
2014| `agent_type` | `str` | サブエージェントの型 |
2015
2016### `PreCompactHookInput`
2017
2018`PreCompact` hook イベントの入力データ。
2019
2020```python theme={null}
2021class PreCompactHookInput(BaseHookInput):
2022 hook_event_name: Literal["PreCompact"]
2023 trigger: Literal["manual", "auto"]
2024 custom_instructions: str | None
2025```
2026
2027| フィールド | 型 | 説明 |
2028| :-------------------- | :-------------------------- | :---------------- |
2029| `hook_event_name` | `Literal["PreCompact"]` | 常に "PreCompact" |
2030| `trigger` | `Literal["manual", "auto"]` | コンパクション をトリガーしたもの |
2031| `custom_instructions` | `str \| None` | コンパクション用のカスタム指示 |
2032
2033### `NotificationHookInput`
2034
2035`Notification` hook イベントの入力データ。
2036
2037```python theme={null}
2038class NotificationHookInput(BaseHookInput):
2039 hook_event_name: Literal["Notification"]
2040 message: str
2041 title: NotRequired[str]
2042 notification_type: str
2043```
2044
2045| フィールド | 型 | 説明 |
2046| :------------------ | :------------------------ | :---------------- |
2047| `hook_event_name` | `Literal["Notification"]` | 常に "Notification" |
2048| `message` | `str` | 通知メッセージコンテンツ |
2049| `title` | `str`(オプション) | 通知タイトル |
2050| `notification_type` | `str` | 通知の型 |
2051
2052### `SubagentStartHookInput`
2053
2054`SubagentStart` hook イベントの入力データ。
2055
2056```python theme={null}
2057class SubagentStartHookInput(BaseHookInput):
2058 hook_event_name: Literal["SubagentStart"]
2059 agent_id: str
2060 agent_type: str
2061```
2062
2063| フィールド | 型 | 説明 |
2064| :---------------- | :------------------------- | :----------------- |
2065| `hook_event_name` | `Literal["SubagentStart"]` | 常に "SubagentStart" |
2066| `agent_id` | `str` | サブエージェントの一意の識別子 |
2067| `agent_type` | `str` | サブエージェントの型 |
2068
2069### `PermissionRequestHookInput`
2070
2071`PermissionRequest` hook イベントの入力データ。hooks がパーミッション決定をプログラムで処理できるようにします。
2072
2073```python theme={null}
2074class PermissionRequestHookInput(BaseHookInput):
2075 hook_event_name: Literal["PermissionRequest"]
2076 tool_name: str
2077 tool_input: dict[str, Any]
2078 permission_suggestions: NotRequired[list[Any]]
2079```
2080
2081| フィールド | 型 | 説明 |
2082| :----------------------- | :----------------------------- | :--------------------- |
2083| `hook_event_name` | `Literal["PermissionRequest"]` | 常に "PermissionRequest" |
2084| `tool_name` | `str` | パーミッションをリクエストするツールの名前 |
2085| `tool_input` | `dict[str, Any]` | ツールの入力パラメータ |
2086| `permission_suggestions` | `list[Any]`(オプション) | CLI からの提案されたパーミッション更新 |
2087
2088### `HookJSONOutput`
2089
2090hook コールバック戻り値の Union 型。
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
2122hook イベント名とイベント固有のフィールドを含む `TypedDict`。形状は `hookEventName` 値に依存します。hook イベントごとに利用可能なフィールドの詳細については、[hooks で実行を制御](/ja/agent-sdk/hooks#outputs) を参照してください。
2123
2124イベント固有の出力型の判別 union。`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
2179hook 実行を遅延させる非同期 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この例は 2 つの hook を登録します:1 つは `rm -rf /` のような危険な bash コマンドをブロックし、もう 1 つは監査のためにすべてのツール使用をログします。セキュリティ hook は `matcher` を介して Bash コマンドでのみ実行され、ログ hook はすべてのツールで実行されます。
2194
2195```python theme={null}
2196from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext
2197from typing import Any
2198
2199
2200async def validate_bash_command(
2201 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2202) -> dict[str, Any]:
2203 """Validate and potentially block dangerous bash commands."""
2204 if input_data["tool_name"] == "Bash":
2205 command = input_data["tool_input"].get("command", "")
2206 if "rm -rf /" in command:
2207 return {
2208 "hookSpecificOutput": {
2209 "hookEventName": "PreToolUse",
2210 "permissionDecision": "deny",
2211 "permissionDecisionReason": "Dangerous command blocked",
2212 }
2213 }
2214 return {}
2215
2216
2217async def log_tool_use(
2218 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2219) -> dict[str, Any]:
2220 """Log all tool usage for auditing."""
2221 print(f"Tool used: {input_data.get('tool_name')}")
2222 return {}
2223
2224
2225options = ClaudeAgentOptions(
2226 hooks={
2227 "PreToolUse": [
2228 HookMatcher(
2229 matcher="Bash", hooks=[validate_bash_command], timeout=120
2230 ), # 2 min for validation
2231 HookMatcher(
2232 hooks=[log_tool_use]
2233 ), # Applies to all tools (default 60s timeout)
2234 ],
2235 "PostToolUse": [HookMatcher(hooks=[log_tool_use])],
2236 }
2237)
2238
2239async for message in query(prompt="Analyze this codebase", options=options):
2240 print(message)
2241```
2242
2243## ツール入出力型
2244
2245すべての組み込み Claude Code ツールの入出力スキーマのドキュメント。Python SDK はこれらを型としてエクスポートしませんが、メッセージ内のツール入出力の構造を表します。
2246
2247### Agent
2248
2249**ツール名:** `Agent`(以前は `Task`。これはまだエイリアスとして受け入れられます)
2250
2251**入力:**
2252
2253```python theme={null}
2254{
2255 "description": str, # A short (3-5 word) description of the task
2256 "prompt": str, # The task for the agent to perform
2257 "subagent_type": str, # The type of specialized agent to use
2258}
2259```
2260
2261**出力:**
2262
2263```python theme={null}
2264{
2265 "result": str, # Final result from the subagent
2266 "usage": dict | None, # Token usage statistics
2267 "total_cost_usd": float | None, # Estimated total cost in USD
2268 "duration_ms": int | None, # Execution duration in milliseconds
2269}
2270```
2271
2272### AskUserQuestion
2273
2274**ツール名:** `AskUserQuestion`
2275
2276実行中にユーザーに明確化の質問をします。使用の詳細については [承認とユーザー入力を処理](/ja/agent-sdk/user-input#handle-clarifying-questions) を参照してください。
2277
2278**入力:**
2279
2280```python theme={null}
2281{
2282 "questions": [ # Questions to ask the user (1-4 questions)
2283 {
2284 "question": str, # The complete question to ask the user
2285 "header": str, # Very short label displayed as a chip/tag (max 12 chars)
2286 "options": [ # The available choices (2-4 options)
2287 {
2288 "label": str, # Display text for this option (1-5 words)
2289 "description": str, # Explanation of what this option means
2290 }
2291 ],
2292 "multiSelect": bool, # Set to true to allow multiple selections
2293 }
2294 ],
2295 "answers": dict | None, # User answers populated by the permission system
2296}
2297```
2298
2299**出力:**
2300
2301```python theme={null}
2302{
2303 "questions": [ # The questions that were asked
2304 {
2305 "question": str,
2306 "header": str,
2307 "options": [{"label": str, "description": str}],
2308 "multiSelect": bool,
2309 }
2310 ],
2311 "answers": dict[str, str], # Maps question text to answer string
2312 # Multi-select answers are comma-separated
2313}
2314```
2315
2316### Bash
2317
2318**ツール名:** `Bash`
2319
2320**入力:**
2321
2322```python theme={null}
2323{
2324 "command": str, # The command to execute
2325 "timeout": int | None, # Optional timeout in milliseconds (max 600000)
2326 "description": str | None, # Clear, concise description (5-10 words)
2327 "run_in_background": bool | None, # Set to true to run in background
2328}
2329```
2330
2331**出力:**
2332
2333```python theme={null}
2334{
2335 "output": str, # Combined stdout and stderr output
2336 "exitCode": int, # Exit code of the command
2337 "killed": bool | None, # Whether command was killed due to timeout
2338 "shellId": str | None, # Shell ID for background processes
2339}
2340```
2341
2342### Monitor
2343
2344**ツール名:** `Monitor`
2345
2346バックグラウンドスクリプトを実行し、各 stdout 行を Claude にイベントとして配信して、ポーリングなしで反応できるようにします。Monitor は Bash と同じパーミッションルールに従います。動作とプロバイダーの可用性については、[Monitor ツールリファレンス](/ja/tools-reference#monitor-tool) を参照してください。
2347
2348**入力:**
2349
2350```python theme={null}
2351{
2352 "command": str, # Shell script; each stdout line is an event, exit ends the watch
2353 "description": str, # Short description shown in notifications
2354 "timeout_ms": int | None, # Kill after this deadline (default 300000, max 3600000)
2355 "persistent": bool | None, # Run for the lifetime of the session; stop with TaskStop
2356}
2357```
2358
2359**出力:**
2360
2361```python theme={null}
2362{
2363 "taskId": str, # ID of the background monitor task
2364 "timeoutMs": int, # Timeout deadline in milliseconds (0 when persistent)
2365 "persistent": bool | None, # True when running until TaskStop or session end
2366}
2367```
2368
2369### Edit
2370
2371**ツール名:** `Edit`
2372
2373**入力:**
2374
2375```python theme={null}
2376{
2377 "file_path": str, # The absolute path to the file to modify
2378 "old_string": str, # The text to replace
2379 "new_string": str, # The text to replace it with
2380 "replace_all": bool | None, # Replace all occurrences (default False)
2381}
2382```
2383
2384**出力:**
2385
2386```python theme={null}
2387{
2388 "message": str, # Confirmation message
2389 "replacements": int, # Number of replacements made
2390 "file_path": str, # File path that was edited
2391}
2392```
2393
2394### Read
2395
2396**ツール名:** `Read`
2397
2398**入力:**
2399
2400```python theme={null}
2401{
2402 "file_path": str, # The absolute path to the file to read
2403 "offset": int | None, # The line number to start reading from
2404 "limit": int | None, # The number of lines to read
2405}
2406```
2407
2408**出力(テキストファイル):**
2409
2410```python theme={null}
2411{
2412 "content": str, # File contents with line numbers
2413 "total_lines": int, # Total number of lines in file
2414 "lines_returned": int, # Lines actually returned
2415}
2416```
2417
2418**出力(画像):**
2419
2420```python theme={null}
2421{
2422 "image": str, # Base64 encoded image data
2423 "mime_type": str, # Image MIME type
2424 "file_size": int, # File size in bytes
2425}
2426```
2427
2428### Write
2429
2430**ツール名:** `Write`
2431
2432**入力:**
2433
2434```python theme={null}
2435{
2436 "file_path": str, # The absolute path to the file to write
2437 "content": str, # The content to write to the file
2438}
2439```
2440
2441**出力:**
2442
2443```python theme={null}
2444{
2445 "message": str, # Success message
2446 "bytes_written": int, # Number of bytes written
2447 "file_path": str, # File path that was written
2448}
2449```
2450
2451### Glob
2452
2453**ツール名:** `Glob`
2454
2455**入力:**
2456
2457```python theme={null}
2458{
2459 "pattern": str, # The glob pattern to match files against
2460 "path": str | None, # The directory to search in (defaults to cwd)
2461}
2462```
2463
2464**出力:**
2465
2466```python theme={null}
2467{
2468 "matches": list[str], # Array of matching file paths
2469 "count": int, # Number of matches found
2470 "search_path": str, # Search directory used
2471}
2472```
2473
2474### Grep
2475
2476**ツール名:** `Grep`
2477
2478**入力:**
2479
2480```python theme={null}
2481{
2482 "pattern": str, # The regular expression pattern
2483 "path": str | None, # File or directory to search in
2484 "glob": str | None, # Glob pattern to filter files
2485 "type": str | None, # File type to search
2486 "output_mode": str | None, # "content", "files_with_matches", or "count"
2487 "-i": bool | None, # Case insensitive search
2488 "-n": bool | None, # Show line numbers
2489 "-B": int | None, # Lines to show before each match
2490 "-A": int | None, # Lines to show after each match
2491
2492 "-C": int | None, # Lines to show before and after
2493 "head_limit": int | None, # Limit output to first N lines/entries
2494 "multiline": bool | None, # Enable multiline mode
2495}
2496```
2497
2498**出力(content モード):**
2499
2500```python theme={null}
2501{
2502 "matches": [
2503 {
2504 "file": str,
2505 "line_number": int | None,
2506 "line": str,
2507 "before_context": list[str] | None,
2508 "after_context": list[str] | None,
2509 }
2510 ],
2511 "total_matches": int,
2512}
2513```
2514
2515**出力(files\_with\_matches モード):**
2516
2517```python theme={null}
2518{
2519 "files": list[str], # Files containing matches
2520 "count": int, # Number of files with matches
2521}
2522```
2523
2524### NotebookEdit
2525
2526**ツール名:** `NotebookEdit`
2527
2528**入力:**
2529
2530```python theme={null}
2531{
2532 "notebook_path": str, # Absolute path to the Jupyter notebook
2533 "cell_id": str | None, # The ID of the cell to edit
2534 "new_source": str, # The new source for the cell
2535 "cell_type": "code" | "markdown" | None, # The type of the cell
2536 "edit_mode": "replace" | "insert" | "delete" | None, # Edit operation type
2537}
2538```
2539
2540**出力:**
2541
2542```python theme={null}
2543{
2544 "message": str, # Success message
2545 "edit_type": "replaced" | "inserted" | "deleted", # Type of edit performed
2546 "cell_id": str | None, # Cell ID that was affected
2547 "total_cells": int, # Total cells in notebook after edit
2548}
2549```
2550
2551### WebFetch
2552
2553**ツール名:** `WebFetch`
2554
2555**入力:**
2556
2557```python theme={null}
2558{
2559 "url": str, # The URL to fetch content from
2560 "prompt": str, # The prompt to run on the fetched content
2561}
2562```
2563
2564**出力:**
2565
2566```python theme={null}
2567{
2568 "response": str, # AI model's response to the prompt
2569 "url": str, # URL that was fetched
2570 "final_url": str | None, # Final URL after redirects
2571 "status_code": int | None, # HTTP status code
2572}
2573```
2574
2575### WebSearch
2576
2577**ツール名:** `WebSearch`
2578
2579**入力:**
2580
2581```python theme={null}
2582{
2583 "query": str, # The search query to use
2584 "allowed_domains": list[str] | None, # Only include results from these domains
2585 "blocked_domains": list[str] | None, # Never include results from these domains
2586}
2587```
2588
2589**出力:**
2590
2591```python theme={null}
2592{
2593 "results": [{"title": str, "url": str, "snippet": str, "metadata": dict | None}],
2594 "total_results": int,
2595 "query": str,
2596}
2597```
2598
2599### TodoWrite
2600
2601**ツール名:** `TodoWrite`
2602
2603**入力:**
2604
2605```python theme={null}
2606{
2607 "todos": [
2608 {
2609 "content": str, # The task description
2610 "status": "pending" | "in_progress" | "completed", # Task status
2611 "activeForm": str, # Active form of the description
2612 }
2613 ]
2614}
2615```
2616
2617**出力:**
2618
2619```python theme={null}
2620{
2621 "message": str, # Success message
2622 "stats": {"total": int, "pending": int, "in_progress": int, "completed": int},
2623}
2624```
2625
2626### BashOutput
2627
2628**ツール名:** `BashOutput`
2629
2630**入力:**
2631
2632```python theme={null}
2633{
2634 "bash_id": str, # The ID of the background shell
2635 "filter": str | None, # Optional regex to filter output lines
2636}
2637```
2638
2639**出力:**
2640
2641```python theme={null}
2642{
2643 "output": str, # New output since last check
2644 "status": "running" | "completed" | "failed", # Current shell status
2645 "exitCode": int | None, # Exit code when completed
2646}
2647```
2648
2649### KillBash
2650
2651**ツール名:** `KillBash`
2652
2653**入力:**
2654
2655```python theme={null}
2656{
2657 "shell_id": str # The ID of the background shell to kill
2658}
2659```
2660
2661**出力:**
2662
2663```python theme={null}
2664{
2665 "message": str, # Success message
2666 "shell_id": str, # ID of the killed shell
2667}
2668```
2669
2670### ExitPlanMode
2671
2672**ツール名:** `ExitPlanMode`
2673
2674**入力:**
2675
2676```python theme={null}
2677{
2678 "plan": str # The plan to run by the user for approval
2679}
2680```
2681
2682**出力:**
2683
2684```python theme={null}
2685{
2686 "message": str, # Confirmation message
2687 "approved": bool | None, # Whether user approved the plan
2688}
2689```
2690
2691### ListMcpResources
2692
2693**ツール名:** `ListMcpResources`
2694
2695**入力:**
2696
2697```python theme={null}
2698{
2699 "server": str | None # Optional server name to filter resources by
2700}
2701```
2702
2703**出力:**
2704
2705```python theme={null}
2706{
2707 "resources": [
2708 {
2709 "uri": str,
2710 "name": str,
2711 "description": str | None,
2712 "mimeType": str | None,
2713 "server": str,
2714 }
2715 ],
2716 "total": int,
2717}
2718```
2719
2720### ReadMcpResource
2721
2722**ツール名:** `ReadMcpResource`
2723
2724**入力:**
2725
2726```python theme={null}
2727{
2728 "server": str, # The MCP server name
2729 "uri": str, # The resource URI to read
2730}
2731```
2732
2733**出力:**
2734
2735```python theme={null}
2736{
2737 "contents": [
2738 {"uri": str, "mimeType": str | None, "text": str | None, "blob": str | None}
2739 ],
2740 "server": str,
2741}
2742```
2743
2744## ClaudeSDKClient を使用した高度な機能
2745
2746### 継続的な会話インターフェースの構築
2747
2748```python theme={null}
2749from claude_agent_sdk import (
2750 ClaudeSDKClient,
2751 ClaudeAgentOptions,
2752 AssistantMessage,
2753 TextBlock,
2754)
2755import asyncio
2756
2757
2758class ConversationSession:
2759 """Maintains a single conversation session with Claude."""
2760
2761 def __init__(self, options: ClaudeAgentOptions | None = None):
2762 self.client = ClaudeSDKClient(options)
2763 self.turn_count = 0
2764
2765 async def start(self):
2766 await self.client.connect()
2767 print("Starting conversation session. Claude will remember context.")
2768 print(
2769 "Commands: 'exit' to quit, 'interrupt' to stop current task, 'new' for new session"
2770 )
2771
2772 while True:
2773 user_input = input(f"\n[Turn {self.turn_count + 1}] You: ")
2774
2775 if user_input.lower() == "exit":
2776 break
2777 elif user_input.lower() == "interrupt":
2778 await self.client.interrupt()
2779 print("Task interrupted!")
2780 continue
2781 elif user_input.lower() == "new":
2782 # Disconnect and reconnect for a fresh session
2783 await self.client.disconnect()
2784 await self.client.connect()
2785 self.turn_count = 0
2786 print("Started new conversation session (previous context cleared)")
2787 continue
2788
2789 # Send message - the session retains all previous messages
2790 await self.client.query(user_input)
2791 self.turn_count += 1
2792
2793 # Process response
2794 print(f"[Turn {self.turn_count}] Claude: ", end="")
2795 async for message in self.client.receive_response():
2796 if isinstance(message, AssistantMessage):
2797 for block in message.content:
2798 if isinstance(block, TextBlock):
2799 print(block.text, end="")
2800 print() # New line after response
2801
2802 await self.client.disconnect()
2803 print(f"Conversation ended after {self.turn_count} turns.")
2804
2805
2806async def main():
2807 options = ClaudeAgentOptions(
2808 allowed_tools=["Read", "Write", "Bash"], permission_mode="acceptEdits"
2809 )
2810 session = ConversationSession(options)
2811 await session.start()
2812
2813
2814# Example conversation:
2815# Turn 1 - You: "Create a file called hello.py"
2816# Turn 1 - Claude: "I'll create a hello.py file for you..."
2817# Turn 2 - You: "What's in that file?"
2818# Turn 2 - Claude: "The hello.py file I just created contains..." (remembers!)
2819# Turn 3 - You: "Add a main function to it"
2820# Turn 3 - Claude: "I'll add a main function to hello.py..." (knows which file!)
2821
2822asyncio.run(main())
2823```
2824
2825### 動作修正のための Hooks の使用
2826
2827```python theme={null}
2828from claude_agent_sdk import (
2829 ClaudeSDKClient,
2830 ClaudeAgentOptions,
2831 HookMatcher,
2832 HookContext,
2833)
2834import asyncio
2835from typing import Any
2836
2837
2838async def pre_tool_logger(
2839 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2840) -> dict[str, Any]:
2841 """Log all tool usage before execution."""
2842 tool_name = input_data.get("tool_name", "unknown")
2843 print(f"[PRE-TOOL] About to use: {tool_name}")
2844
2845 # You can modify or block the tool execution here
2846 if tool_name == "Bash" and "rm -rf" in str(input_data.get("tool_input", {})):
2847 return {
2848 "hookSpecificOutput": {
2849 "hookEventName": "PreToolUse",
2850 "permissionDecision": "deny",
2851 "permissionDecisionReason": "Dangerous command blocked",
2852 }
2853 }
2854 return {}
2855
2856
2857async def post_tool_logger(
2858 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2859) -> dict[str, Any]:
2860 """Log results after tool execution."""
2861 tool_name = input_data.get("tool_name", "unknown")
2862 print(f"[POST-TOOL] Completed: {tool_name}")
2863 return {}
2864
2865
2866async def user_prompt_modifier(
2867 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
2868) -> dict[str, Any]:
2869 """Add context to user prompts."""
2870 original_prompt = input_data.get("prompt", "")
2871
2872 # Add a timestamp as additional context for Claude to see
2873 from datetime import datetime
2874
2875 timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
2876
2877 return {
2878 "hookSpecificOutput": {
2879 "hookEventName": "UserPromptSubmit",
2880 "additionalContext": f"[Submitted at {timestamp}] Original prompt: {original_prompt}",
2881 }
2882 }
2883
2884
2885async def main():
2886 options = ClaudeAgentOptions(
2887 hooks={
2888 "PreToolUse": [
2889 HookMatcher(hooks=[pre_tool_logger]),
2890 HookMatcher(matcher="Bash", hooks=[pre_tool_logger]),
2891 ],
2892 "PostToolUse": [HookMatcher(hooks=[post_tool_logger])],
2893 "UserPromptSubmit": [HookMatcher(hooks=[user_prompt_modifier])],
2894 },
2895 allowed_tools=["Read", "Write", "Bash"],
2896 )
2897
2898 async with ClaudeSDKClient(options=options) as client:
2899 await client.query("List files in current directory")
2900
2901 async for message in client.receive_response():
2902 # Hooks will automatically log tool usage
2903 pass
2904
2905
2906asyncio.run(main())
2907```
2908
2909### リアルタイム進捗監視
2910
2911```python theme={null}
2912from claude_agent_sdk import (
2913 ClaudeSDKClient,
2914 ClaudeAgentOptions,
2915 AssistantMessage,
2916 ToolUseBlock,
2917 ToolResultBlock,
2918 TextBlock,
2919)
2920import asyncio
2921
2922
2923async def monitor_progress():
2924 options = ClaudeAgentOptions(
2925 allowed_tools=["Write", "Bash"], permission_mode="acceptEdits"
2926 )
2927
2928 async with ClaudeSDKClient(options=options) as client:
2929 await client.query("Create 5 Python files with different sorting algorithms")
2930
2931 # Monitor progress in real-time
2932 async for message in client.receive_response():
2933 if isinstance(message, AssistantMessage):
2934 for block in message.content:
2935 if isinstance(block, ToolUseBlock):
2936 if block.name == "Write":
2937 file_path = block.input.get("file_path", "")
2938 print(f"Creating: {file_path}")
2939 elif isinstance(block, ToolResultBlock):
2940 print("Completed tool execution")
2941 elif isinstance(block, TextBlock):
2942 print(f"Claude says: {block.text[:100]}...")
2943
2944 print("Task completed!")
2945
2946
2947asyncio.run(monitor_progress())
2948```
2949
2950## 使用例
2951
2952### 基本的なファイル操作(query を使用)
2953
2954```python theme={null}
2955from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock
2956import asyncio
2957
2958
2959async def create_project():
2960 options = ClaudeAgentOptions(
2961 allowed_tools=["Read", "Write", "Bash"],
2962 permission_mode="acceptEdits",
2963 cwd="/home/user/project",
2964 )
2965
2966 async for message in query(
2967 prompt="Create a Python project structure with setup.py", options=options
2968 ):
2969 if isinstance(message, AssistantMessage):
2970 for block in message.content:
2971 if isinstance(block, ToolUseBlock):
2972 print(f"Using tool: {block.name}")
2973
2974
2975asyncio.run(create_project())
2976```
2977
2978### エラー処理
2979
2980```python theme={null}
2981from claude_agent_sdk import query, CLINotFoundError, ProcessError, CLIJSONDecodeError
2982
2983try:
2984 async for message in query(prompt="Hello"):
2985 print(message)
2986except CLINotFoundError:
2987 print(
2988 "Claude Code CLI not found. Try reinstalling: pip install --force-reinstall claude-agent-sdk"
2989 )
2990except ProcessError as e:
2991 print(f"Process failed with exit code: {e.exit_code}")
2992except CLIJSONDecodeError as e:
2993 print(f"Failed to parse response: {e}")
2994```
2995
2996### クライアントでのストリーミングモード
2997
2998```python theme={null}
2999from claude_agent_sdk import ClaudeSDKClient
3000import asyncio
3001
3002
3003async def interactive_session():
3004 async with ClaudeSDKClient() as client:
3005 # Send initial message
3006 await client.query("What's the weather like?")
3007
3008 # Process responses
3009 async for msg in client.receive_response():
3010 print(msg)
3011
3012 # Send follow-up
3013 await client.query("Tell me more about that")
3014
3015 # Process follow-up response
3016 async for msg in client.receive_response():
3017 print(msg)
3018
3019
3020asyncio.run(interactive_session())
3021```
3022
3023### ClaudeSDKClient でカスタムツールを使用する
3024
3025```python theme={null}
3026from claude_agent_sdk import (
3027 ClaudeSDKClient,
3028 ClaudeAgentOptions,
3029 tool,
3030 create_sdk_mcp_server,
3031 AssistantMessage,
3032 TextBlock,
3033)
3034import asyncio
3035from typing import Any
3036
3037
3038# Define custom tools with @tool decorator
3039@tool("calculate", "Perform mathematical calculations", {"expression": str})
3040async def calculate(args: dict[str, Any]) -> dict[str, Any]:
3041 try:
3042 result = eval(args["expression"], {"__builtins__": {}})
3043 return {"content": [{"type": "text", "text": f"Result: {result}"}]}
3044 except Exception as e:
3045 return {
3046 "content": [{"type": "text", "text": f"Error: {str(e)}"}],
3047 "is_error": True,
3048 }
3049
3050
3051@tool("get_time", "Get current time", {})
3052async def get_time(args: dict[str, Any]) -> dict[str, Any]:
3053 from datetime import datetime
3054
3055 current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
3056 return {"content": [{"type": "text", "text": f"Current time: {current_time}"}]}
3057
3058
3059async def main():
3060 # Create SDK MCP server with custom tools
3061 my_server = create_sdk_mcp_server(
3062 name="utilities", version="1.0.0", tools=[calculate, get_time]
3063 )
3064
3065 # Configure options with the server
3066 options = ClaudeAgentOptions(
3067 mcp_servers={"utils": my_server},
3068 allowed_tools=["mcp__utils__calculate", "mcp__utils__get_time"],
3069 )
3070
3071 # Use ClaudeSDKClient for interactive tool usage
3072 async with ClaudeSDKClient(options=options) as client:
3073 await client.query("What's 123 * 456?")
3074
3075 # Process calculation response
3076 async for message in client.receive_response():
3077 if isinstance(message, AssistantMessage):
3078 for block in message.content:
3079 if isinstance(block, TextBlock):
3080 print(f"Calculation: {block.text}")
3081
3082 # Follow up with time query
3083 await client.query("What time is it now?")
3084
3085 async for message in client.receive_response():
3086 if isinstance(message, AssistantMessage):
3087 for block in message.content:
3088 if isinstance(block, TextBlock):
3089 print(f"Time: {block.text}")
3090
3091
3092asyncio.run(main())
3093```
3094
3095## サンドボックス設定
3096
3097### `SandboxSettings`
3098
3099サンドボックス動作の設定。これを使用してコマンドサンドボックスを有効にし、ネットワーク制限をプログラムで設定します。
3100
3101```python theme={null}
3102class SandboxSettings(TypedDict, total=False):
3103 enabled: bool
3104 autoAllowBashIfSandboxed: bool
3105 excludedCommands: list[str]
3106 allowUnsandboxedCommands: bool
3107 network: SandboxNetworkConfig
3108 ignoreViolations: SandboxIgnoreViolations
3109 enableWeakerNestedSandbox: bool
3110```
3111
3112| プロパティ | 型 | デフォルト | 説明 |
3113| :-------------------------- | :------------------------------------------------------ | :------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
3114| `enabled` | `bool` | `False` | コマンド実行のサンドボックスモードを有効にします |
3115| `autoAllowBashIfSandboxed` | `bool` | `True` | サンドボックスが有効な場合、bash コマンドを自動承認します |
3116| `excludedCommands` | `list[str]` | `[]` | 常にサンドボックス制限をバイパスするコマンド(例:`["docker"]`)。これらはモデルの関与なしに自動的にサンドボックスなしで実行されます |
3117| `allowUnsandboxedCommands` | `bool` | `True` | モデルがサンドボックスの外でコマンドを実行するようにリクエストすることを許可します。`True` の場合、モデルはツール入力で `dangerouslyDisableSandbox` を設定でき、[パーミッションシステム](#permissions-fallback-for-unsandboxed-commands) にフォールバックします |
3118| `network` | [`SandboxNetworkConfig`](#sandbox-network-config) | `None` | ネットワーク固有のサンドボックス設定 |
3119| `ignoreViolations` | [`SandboxIgnoreViolations`](#sandbox-ignore-violations) | `None` | 無視するサンドボックス違反を設定します |
3120| `enableWeakerNestedSandbox` | `bool` | `False` | 互換性のためにより弱いネストされたサンドボックスを有効にします |
3121
3122#### 使用例
3123
3124```python theme={null}
3125from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings
3126
3127sandbox_settings: SandboxSettings = {
3128 "enabled": True,
3129 "autoAllowBashIfSandboxed": True,
3130 "network": {"allowLocalBinding": True},
3131}
3132
3133async for message in query(
3134 prompt="Build and test my project",
3135 options=ClaudeAgentOptions(sandbox=sandbox_settings),
3136):
3137 print(message)
3138```
3139
3140<Warning>
3141 **Unix ソケットセキュリティ**:`allowUnixSockets` オプションは強力なシステムサービスへのアクセスを許可できます。例えば、`/var/run/docker.sock` を許可すると、Docker API を通じてホストシステムへの完全なアクセスが効果的に許可され、サンドボックス分離がバイパスされます。厳密に必要な Unix ソケットのみを許可し、各ソケットのセキュリティへの影響を理解してください。
3142</Warning>
3143
3144### `SandboxNetworkConfig`
3145
3146サンドボックスモード用のネットワーク固有の設定。
3147
3148```python theme={null}
3149class SandboxNetworkConfig(TypedDict, total=False):
3150 allowedDomains: list[str]
3151 deniedDomains: list[str]
3152 allowManagedDomainsOnly: bool
3153 allowUnixSockets: list[str]
3154 allowAllUnixSockets: bool
3155 allowLocalBinding: bool
3156 allowMachLookup: list[str]
3157 httpProxyPort: int
3158 socksProxyPort: int
3159```
3160
3161| プロパティ | 型 | デフォルト | 説明 |
3162| :------------------------ | :---------- | :------ | :-------------------------------------------------------------------------------------------- |
3163| `allowedDomains` | `list[str]` | `[]` | サンドボックス化されたプロセスがアクセスできるドメイン名 |
3164| `deniedDomains` | `list[str]` | `[]` | サンドボックス化されたプロセスがアクセスできないドメイン名。`allowedDomains` より優先されます |
3165| `allowManagedDomainsOnly` | `bool` | `False` | マネージド設定のみ:マネージド設定で設定されている場合、非マネージド設定ソースからの `allowedDomains` を無視します。SDK オプションで設定された場合は効果がありません |
3166| `allowUnixSockets` | `list[str]` | `[]` | プロセスがアクセスできる Unix ソケットパス(例:Docker ソケット) |
3167| `allowAllUnixSockets` | `bool` | `False` | すべての Unix ソケットへのアクセスを許可します |
3168| `allowLocalBinding` | `bool` | `False` | プロセスがローカルポートにバインドすることを許可します(例:dev サーバー用) |
3169| `allowMachLookup` | `list[str]` | `[]` | macOS のみ:許可する XPC/Mach サービス名。末尾のワイルドカードをサポートします |
3170| `httpProxyPort` | `int` | `None` | ネットワークリクエスト用の HTTP プロキシポート |
3171| `socksProxyPort` | `int` | `None` | ネットワークリクエスト用の SOCKS プロキシポート |
3172
3173<Note>
3174 組み込みサンドボックスプロキシは、リクエストされたホスト名に基づいてネットワーク許可リストを強制し、TLS トラフィックを終了または検査しないため、[ドメインフロンティング](https://en.wikipedia.org/wiki/Domain_fronting) などの技術がそれをバイパスする可能性があります。詳細は [サンドボックスセキュリティの制限事項](/ja/sandboxing#security-limitations) を参照し、TLS 終了プロキシの設定については [セキュアなデプロイ](/ja/agent-sdk/secure-deployment#traffic-forwarding) を参照してください。
3175</Note>
3176
3177### `SandboxIgnoreViolations`
3178
3179特定のサンドボックス違反を無視するための設定。
3180
3181```python theme={null}
3182class SandboxIgnoreViolations(TypedDict, total=False):
3183 file: list[str]
3184 network: list[str]
3185```
3186
3187| プロパティ | 型 | デフォルト | 説明 |
3188| :-------- | :---------- | :---- | :---------------- |
3189| `file` | `list[str]` | `[]` | 違反を無視するファイルパスパターン |
3190| `network` | `list[str]` | `[]` | 違反を無視するネットワークパターン |
3191
3192### サンドボックスなしコマンドのパーミッションフォールバック
3193
3194`allowUnsandboxedCommands` が有効な場合、モデルはツール入力で `dangerouslyDisableSandbox: True` を設定することでサンドボックスの外でコマンドを実行するようにリクエストできます。これらのリクエストは既存のパーミッションシステムにフォールバックします。つまり、`can_use_tool` ハンドラーが呼び出され、カスタム認可ロジックを実装できます。
3195
3196<Note>
3197 **`excludedCommands` vs `allowUnsandboxedCommands`:**
3198
3199 * `excludedCommands`:常にサンドボックスを自動的にバイパスするコマンドの静的リスト(例:`["docker"]`)。モデルはこれを制御できません。
3200 * `allowUnsandboxedCommands`:モデルが実行時にツール入力で `dangerouslyDisableSandbox: True` を設定することでサンドボックスなし実行をリクエストすることを許可します。
3201</Note>
3202
3203```python theme={null}
3204from claude_agent_sdk import (
3205 query,
3206 ClaudeAgentOptions,
3207 HookMatcher,
3208 PermissionResultAllow,
3209 PermissionResultDeny,
3210 ToolPermissionContext,
3211)
3212
3213
3214async def can_use_tool(
3215 tool: str, input: dict, context: ToolPermissionContext
3216) -> PermissionResultAllow | PermissionResultDeny:
3217 # Check if the model is requesting to bypass the sandbox
3218 if tool == "Bash" and input.get("dangerouslyDisableSandbox"):
3219 # The model is requesting to run this command outside the sandbox
3220 print(f"Unsandboxed command requested: {input.get('command')}")
3221
3222 if is_command_authorized(input.get("command")):
3223 return PermissionResultAllow()
3224 return PermissionResultDeny(
3225 message="Command not authorized for unsandboxed execution"
3226 )
3227 return PermissionResultAllow()
3228
3229
3230# Required: dummy hook keeps the stream open for can_use_tool
3231async def dummy_hook(input_data, tool_use_id, context):
3232 return {"continue_": True}
3233
3234
3235async def prompt_stream():
3236 yield {
3237 "type": "user",
3238 "message": {"role": "user", "content": "Deploy my application"},
3239 }
3240
3241
3242async def main():
3243 async for message in query(
3244 prompt=prompt_stream(),
3245 options=ClaudeAgentOptions(
3246 sandbox={
3247 "enabled": True,
3248 "allowUnsandboxedCommands": True, # Model can request unsandboxed execution
3249 },
3250 permission_mode="default",
3251 can_use_tool=can_use_tool,
3252 hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]},
3253 ),
3254 ):
3255 print(message)
3256```
3257
3258このパターンにより、以下が可能になります:
3259
3260* **モデルリクエストを監査する**:モデルがサンドボックスなし実行をリクエストするときをログします
3261* **許可リストを実装する**:特定のコマンドのみがサンドボックスなしで実行されることを許可します
3262* **承認ワークフローを追加する**:特権操作に明示的な認可を要求します
3263
3264<Warning>
3265 `dangerouslyDisableSandbox: True` で実行されるコマンドはシステムへの完全なアクセスを持ちます。`can_use_tool` ハンドラーがこれらのリクエストを慎重に検証することを確認してください。
3266
3267 `permission_mode` が `bypassPermissions` に設定され、`allow_unsandboxed_commands` が有効な場合、モデルは承認プロンプトなしにサンドボックスの外でコマンドを自律的に実行できます。この組み合わせは、モデルがサンドボックス分離をサイレントに逃れることを効果的に許可します。
3268</Warning>
3269
3270## 関連項目
3271
3272* [SDK 概要](/ja/agent-sdk/overview) - 一般的な SDK 概念
3273* [TypeScript SDK リファレンス](/ja/agent-sdk/typescript) - TypeScript SDK ドキュメント
3274* [CLI リファレンス](/ja/cli-reference) - コマンドラインインターフェース
3275* [一般的なワークフロー](/ja/common-workflows) - ステップバイステップガイド