SpyBara
Go Premium

agent-sdk/python.md 2026-05-13 23:01 UTC to 2026-05-14 17:02 UTC

113 added, 1 removed.

2026
Sun 31 06:39 Sat 30 06:23 Fri 29 06:38 Thu 28 06:37 Wed 27 06:42 Tue 26 06:33 Sun 24 06:25 Sat 23 06:18 Fri 22 06:33 Thu 21 06:36 Wed 20 06:35 Tue 19 06:34 Mon 18 23:59 Sun 17 01:01 Fri 15 22:58 Thu 14 17:02 Wed 13 23:01 Tue 12 22:57 Mon 11 23:00 Sun 10 23:03 Sat 9 04:57 Fri 8 22:00 Thu 7 22:59 Tue 5 23:00 Mon 4 22:58 Sat 2 18:14 Fri 1 18:19

Agent SDK リファレンス - Python

Python Agent SDK の完全な API リファレンス。すべての関数、型、クラスを含みます。

インストール

pip install claude-agent-sdk

query()ClaudeSDKClient の選択

Python SDK は Claude Code と対話するための 2 つの方法を提供します。

クイック比較

機能 query() ClaudeSDKClient
セッション 毎回新しいセッションを作成 同じセッションを再利用
会話 単一の交換 同じコンテキスト内の複数の交換
接続 自動的に管理 手動制御
ストリーミング入力 ✅ サポート ✅ サポート
割り込み ❌ サポートなし ✅ サポート
Hooks ✅ サポート ✅ サポート
カスタムツール ✅ サポート ✅ サポート
会話を続ける ❌ 毎回新しいセッション ✅ 会話を保持
ユースケース 1 回限りのタスク 継続的な会話

query() を使用する場合(毎回新しいセッション)

最適な用途:

  • 会話履歴が不要な 1 回限りの質問
  • 前の交換からのコンテキストが不要な独立したタスク
  • シンプルな自動化スクリプト
  • 毎回新しく開始したい場合

ClaudeSDKClient を使用する場合(継続的な会話)

最適な用途:

  • 会話を続ける - Claude がコンテキストを記憶する必要がある場合
  • フォローアップ質問 - 前の回答に基づいて構築する
  • インタラクティブなアプリケーション - チャットインターフェース、REPL
  • 応答駆動ロジック - 次のアクションが Claude の応答に依存する場合
  • セッション制御 - 会話ライフサイクルを明示的に管理する

関数

query()

Claude Code との各インタラクションのために新しいセッションを作成します。メッセージが到着するにつれて生成される非同期イテレータを返します。query() への各呼び出しは、前のインタラクションのメモリなしで新しく開始します。

async def query(
    *,
    prompt: str | AsyncIterable[dict[str, Any]],
    options: ClaudeAgentOptions | None = None,
    transport: Transport | None = None
) -> AsyncIterator[Message]

パラメータ

パラメータ 説明
prompt str | AsyncIterable[dict] 入力プロンプト(文字列またはストリーミングモード用の非同期イテレータ)
options ClaudeAgentOptions | None オプションの設定オブジェクト(None の場合は ClaudeAgentOptions() がデフォルト)
transport Transport | None CLI プロセスとの通信用のオプションのカスタムトランスポート

戻り値

会話からのメッセージを生成する AsyncIterator[Message] を返します。

例 - オプション付き

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions


async def main():
    options = ClaudeAgentOptions(
        system_prompt="You are an expert Python developer",
        permission_mode="acceptEdits",
        cwd="/home/user/project",
    )

    async for message in query(prompt="Create a Python web server", options=options):
        print(message)


asyncio.run(main())

tool()

型安全性を備えた MCP ツールを定義するためのデコレータ。

def tool(
    name: str,
    description: str,
    input_schema: type | dict[str, Any],
    annotations: ToolAnnotations | None = None
) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]

パラメータ

パラメータ 説明
name str ツールの一意の識別子
description str ツールが何をするかの人間が読める説明
input_schema type | dict[str, Any] ツールの入力パラメータを定義するスキーマ(以下を参照)
annotations ToolAnnotations | None クライアントに動作ヒントを提供するオプションの MCP ツールアノテーション

入力スキーマオプション

  1. シンプルな型マッピング(推奨):

    {"text": str, "count": int, "enabled": bool}
    
  2. JSON Schema 形式(複雑な検証用):

    {
        "type": "object",
        "properties": {
            "text": {"type": "string"},
            "count": {"type": "integer", "minimum": 0},
        },
        "required": ["text"],
    }
    

戻り値

ツール実装をラップし、SdkMcpTool インスタンスを返すデコレータ関数。

from claude_agent_sdk import tool
from typing import Any


@tool("greet", "Greet a user", {"name": str})
async def greet(args: dict[str, Any]) -> dict[str, Any]:
    return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}

ToolAnnotations

mcp.types から再エクスポート(from claude_agent_sdk import ToolAnnotations としても利用可能)。すべてのフィールドはオプションのヒントです。クライアントはセキュリティ決定のためにこれらに依存すべきではありません。

フィールド デフォルト 説明
title str | None None ツールの人間が読める題名
readOnlyHint bool | None False True の場合、ツールはその環境を変更しません
destructiveHint bool | None True True の場合、ツールは破壊的な更新を実行する可能性があります(readOnlyHintFalse の場合のみ意味があります)
idempotentHint bool | None False True の場合、同じ引数での繰り返し呼び出しは追加の効果がありません(readOnlyHintFalse の場合のみ意味があります)
openWorldHint bool | None True True の場合、ツールは外部エンティティと対話します(例:Web 検索)。False の場合、ツールのドメインは閉じています(例:メモリツール)
from claude_agent_sdk import tool, ToolAnnotations
from typing import Any


@tool(
    "search",
    "Search the web",
    {"query": str},
    annotations=ToolAnnotations(readOnlyHint=True, openWorldHint=True),
)
async def search(args: dict[str, Any]) -> dict[str, Any]:
    return {"content": [{"type": "text", "text": f"Results for: {args['query']}"}]}

create_sdk_mcp_server()

Python アプリケーション内で実行されるインプロセス MCP サーバーを作成します。

def create_sdk_mcp_server(
    name: str,
    version: str = "1.0.0",
    tools: list[SdkMcpTool[Any]] | None = None
) -> McpSdkServerConfig

パラメータ

パラメータ デフォルト 説明
name str - サーバーの一意の識別子
version str "1.0.0" サーバーバージョン文字列
tools list[SdkMcpTool[Any]] | None None @tool デコレータで作成されたツール関数のリスト

戻り値

ClaudeAgentOptions.mcp_servers に渡すことができる McpSdkServerConfig オブジェクトを返します。

from claude_agent_sdk import tool, create_sdk_mcp_server


@tool("add", "Add two numbers", {"a": float, "b": float})
async def add(args):
    return {"content": [{"type": "text", "text": f"Sum: {args['a'] + args['b']}"}]}


@tool("multiply", "Multiply two numbers", {"a": float, "b": float})
async def multiply(args):
    return {"content": [{"type": "text", "text": f"Product: {args['a'] * args['b']}"}]}


calculator = create_sdk_mcp_server(
    name="calculator",
    version="2.0.0",
    tools=[add, multiply],  # Pass decorated functions
)

# Use with Claude
options = ClaudeAgentOptions(
    mcp_servers={"calc": calculator},
    allowed_tools=["mcp__calc__add", "mcp__calc__multiply"],
)

list_sessions()

メタデータを含む過去のセッションをリストします。プロジェクトディレクトリでフィルタするか、すべてのプロジェクト全体のセッションをリストします。同期的です。すぐに返します。

def list_sessions(
    directory: str | None = None,
    limit: int | None = None,
    include_worktrees: bool = True
) -> list[SDKSessionInfo]

パラメータ

パラメータ デフォルト 説明
directory str | None None セッションをリストするディレクトリ。省略した場合、すべてのプロジェクト全体のセッションを返します
limit int | None None 返すセッションの最大数
include_worktrees bool True directory が git リポジトリ内にある場合、すべての worktree パスからのセッションを含めます

戻り値の型:SDKSessionInfo

プロパティ 説明
session_id str 一意のセッション識別子
summary str 表示タイトル:カスタムタイトル、自動生成されたサマリー、または最初のプロンプト
last_modified int エポック以降のミリ秒単位での最後の変更時刻
file_size int | None セッションファイルサイズ(バイト)(リモートストレージバックエンドの場合は None
custom_title str | None ユーザーが設定したセッションタイトル
first_prompt str | None セッション内の最初の意味のあるユーザープロンプト
git_branch str | None セッション終了時の Git ブランチ
cwd str | None セッションの作業ディレクトリ
tag str | None ユーザーが設定したセッションタグ(tag_session() を参照)
created_at int | None エポック以降のミリ秒単位でのセッション作成時刻

プロジェクトの 10 個の最新セッションを出力します。結果は last_modified の降順でソートされるため、最初の項目が最新です。directory を省略するとすべてのプロジェクト全体を検索します。

from claude_agent_sdk import list_sessions

for session in list_sessions(directory="/path/to/project", limit=10):
    print(f"{session.summary} ({session.session_id})")

get_session_messages()

過去のセッションからメッセージを取得します。同期的です。すぐに返します。

def get_session_messages(
    session_id: str,
    directory: str | None = None,
    limit: int | None = None,
    offset: int = 0
) -> list[SessionMessage]

パラメータ

パラメータ デフォルト 説明
session_id str 必須 メッセージを取得するセッション ID
directory str | None None 検索するプロジェクトディレクトリ。省略した場合、すべてのプロジェクトを検索します
limit int | None None 返すメッセージの最大数
offset int 0 開始からスキップするメッセージ数

戻り値の型:SessionMessage

プロパティ 説明
type Literal["user", "assistant"] メッセージロール
uuid str 一意のメッセージ識別子
session_id str セッション識別子
message Any 生のメッセージコンテンツ
parent_tool_use_id None 将来の使用のために予約済み

from claude_agent_sdk import list_sessions, get_session_messages

sessions = list_sessions(limit=1)
if sessions:
    messages = get_session_messages(sessions[0].session_id)
    for msg in messages:
        print(f"[{msg.type}] {msg.uuid}")

get_session_info()

プロジェクトディレクトリ全体をスキャンせずに、ID でシングルセッションのメタデータを読み取ります。同期的です。すぐに返します。

def get_session_info(
    session_id: str,
    directory: str | None = None,
) -> SDKSessionInfo | None

パラメータ

パラメータ デフォルト 説明
session_id str 必須 検索するセッションの UUID
directory str | None None プロジェクトディレクトリパス。省略した場合、すべてのプロジェクトディレクトリを検索します

SDKSessionInfo を返すか、セッションが見つからない場合は None

プロジェクトディレクトリをスキャンせずに、シングルセッションのメタデータを検索します。前の実行からセッション ID を既に持っている場合に便利です。

from claude_agent_sdk import get_session_info

info = get_session_info("550e8400-e29b-41d4-a716-446655440000")
if info:
    print(f"{info.summary} (branch: {info.git_branch}, tag: {info.tag})")

rename_session()

カスタムタイトルエントリを追加することでセッションの名前を変更します。繰り返し呼び出しは安全です。最新のタイトルが優先されます。同期的です。

def rename_session(
    session_id: str,
    title: str,
    directory: str | None = None,
) -> None

パラメータ

パラメータ デフォルト 説明
session_id str 必須 名前を変更するセッションの UUID
title str 必須 新しいタイトル。空白をストリップした後、空でない必要があります
directory str | None None プロジェクトディレクトリパス。省略した場合、すべてのプロジェクトディレクトリを検索します

session_id が有効な UUID でない場合、または title が空の場合は ValueError を発生させます。セッションが見つからない場合は FileNotFoundError

最新のセッションの名前を変更して、後で見つけやすくします。新しいタイトルは、その後の読み取りで SDKSessionInfo.custom_title に表示されます。

from claude_agent_sdk import list_sessions, rename_session

sessions = list_sessions(directory="/path/to/project", limit=1)
if sessions:
    rename_session(sessions[0].session_id, "Refactor auth module")

tag_session()

セッションにタグを付けます。None を渡してタグをクリアします。繰り返し呼び出しは安全です。最新のタグが優先されます。同期的です。

def tag_session(
    session_id: str,
    tag: str | None,
    directory: str | None = None,
) -> None

パラメータ

パラメータ デフォルト 説明
session_id str 必須 タグを付けるセッションの UUID
tag str | None 必須 タグ文字列、またはクリアする場合は None。保存前に Unicode サニタイズされます
directory str | None None プロジェクトディレクトリパス。省略した場合、すべてのプロジェクトディレクトリを検索します

session_id が有効な UUID でない場合、またはサニタイズ後に tag が空の場合は ValueError を発生させます。セッションが見つからない場合は FileNotFoundError

セッションにタグを付けてから、後の読み取りでそのタグでフィルタします。既存のタグをクリアするには None を渡します。

from claude_agent_sdk import list_sessions, tag_session

# Tag a session
tag_session("550e8400-e29b-41d4-a716-446655440000", "needs-review")

# Later: find all sessions with that tag
for session in list_sessions(directory="/path/to/project"):
    if session.tag == "needs-review":
        print(session.summary)

クラス

ClaudeSDKClient

複数の交換にわたってセッションを維持します。 これは TypeScript SDK の query() 関数が内部的にどのように機能するかの Python 同等物です。会話を続けることができるクライアントオブジェクトを作成します。

主な機能

  • セッション継続性:複数の query() 呼び出しにわたって会話コンテキストを維持します
  • 同じ会話:セッションは前のメッセージを保持します
  • 割り込みサポート:タスク途中で実行を停止できます
  • 明示的なライフサイクル:セッションの開始と終了を制御します
  • 応答駆動フロー:応答に反応してフォローアップを送信できます
  • カスタムツールと hooks:カスタムツール(@tool デコレータで作成)と hooks をサポートします
class ClaudeSDKClient:
    def __init__(self, options: ClaudeAgentOptions | None = None, transport: Transport | None = None)
    async def connect(self, prompt: str | AsyncIterable[dict] | None = None) -> None
    async def query(self, prompt: str | AsyncIterable[dict], session_id: str = "default") -> None
    async def receive_messages(self) -> AsyncIterator[Message]
    async def receive_response(self) -> AsyncIterator[Message]
    async def interrupt(self) -> None
    async def set_permission_mode(self, mode: str) -> None
    async def set_model(self, model: str | None = None) -> None
    async def rewind_files(self, user_message_id: str) -> None
    async def get_mcp_status(self) -> McpStatusResponse
    async def reconnect_mcp_server(self, server_name: str) -> None
    async def toggle_mcp_server(self, server_name: str, enabled: bool) -> None
    async def stop_task(self, task_id: str) -> None
    async def get_server_info(self) -> dict[str, Any] | None
    async def disconnect(self) -> None

メソッド

メソッド 説明
__init__(options) オプションの設定でクライアントを初期化します
connect(prompt) オプションの初期プロンプトまたはメッセージストリームで Claude に接続します
query(prompt, session_id) ストリーミングモードで新しいリクエストを送信します
receive_messages() Claude からのすべてのメッセージを非同期イテレータとして受け取ります
receive_response() ResultMessage を含むまでのメッセージを受け取ります
interrupt() 割り込み信号を送信します(ストリーミングモードでのみ機能)
set_permission_mode(mode) 現在のセッションのパーミッションモードを変更します
set_model(model) 現在のセッションのモデルを変更します。デフォルトにリセットするには None を渡します
rewind_files(user_message_id) ファイルを指定されたユーザーメッセージの状態に復元します。enable_file_checkpointing=True が必要です。ファイルチェックポイント を参照
get_mcp_status() すべての設定済み MCP サーバーのステータスを取得します。McpStatusResponse を返します
reconnect_mcp_server(server_name) 失敗したか切断された MCP サーバーへの再接続を試みます
toggle_mcp_server(server_name, enabled) セッション中に MCP サーバーを有効または無効にします。無効にするとそのツールが削除されます
stop_task(task_id) 実行中のバックグラウンドタスクを停止します。ステータス "stopped"TaskNotificationMessage がメッセージストリームに続きます
get_server_info() セッション ID と機能を含むサーバー情報を取得します
disconnect() Claude から切断します

コンテキストマネージャーサポート

クライアントは自動接続管理のための非同期コンテキストマネージャーとして使用できます:

async with ClaudeSDKClient() as client:
    await client.query("Hello Claude")
    async for message in client.receive_response():
        print(message)

重要: メッセージを反復処理する場合、早期に終了するために break を使用することは避けてください。これは asyncio クリーンアップの問題を引き起こす可能性があります。代わりに、反復を自然に完了させるか、フラグを使用して必要なものを見つけたときを追跡してください。

例 - 会話を続ける

import asyncio
from claude_agent_sdk import ClaudeSDKClient, AssistantMessage, TextBlock, ResultMessage


async def main():
    async with ClaudeSDKClient() as client:
        # First question
        await client.query("What's the capital of France?")

        # Process response
        async for message in client.receive_response():
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        print(f"Claude: {block.text}")

        # Follow-up question - the session retains the previous context
        await client.query("What's the population of that city?")

        async for message in client.receive_response():
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        print(f"Claude: {block.text}")

        # Another follow-up - still in the same conversation
        await client.query("What are some famous landmarks there?")

        async for message in client.receive_response():
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        print(f"Claude: {block.text}")


asyncio.run(main())

例 - ClaudeSDKClient でのストリーミング入力

import asyncio
from claude_agent_sdk import ClaudeSDKClient


async def message_stream():
    """Generate messages dynamically."""
    yield {
        "type": "user",
        "message": {"role": "user", "content": "Analyze the following data:"},
    }
    await asyncio.sleep(0.5)
    yield {
        "type": "user",
        "message": {"role": "user", "content": "Temperature: 25°C, Humidity: 60%"},
    }
    await asyncio.sleep(0.5)
    yield {
        "type": "user",
        "message": {"role": "user", "content": "What patterns do you see?"},
    }


async def main():
    async with ClaudeSDKClient() as client:
        # Stream input to Claude
        await client.query(message_stream())

        # Process response
        async for message in client.receive_response():
            print(message)

        # Follow-up in same session
        await client.query("Should we be concerned about these readings?")

        async for message in client.receive_response():
            print(message)


asyncio.run(main())

例 - 割り込みの使用

import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, ResultMessage


async def interruptible_task():
    options = ClaudeAgentOptions(allowed_tools=["Bash"], permission_mode="acceptEdits")

    async with ClaudeSDKClient(options=options) as client:
        # Start a long-running task
        await client.query("Count from 1 to 100 slowly, using the bash sleep command")

        # Let it run for a bit
        await asyncio.sleep(2)

        # Interrupt the task
        await client.interrupt()
        print("Task interrupted!")

        # Drain the interrupted task's messages (including its ResultMessage)
        async for message in client.receive_response():
            if isinstance(message, ResultMessage):
                print(f"Interrupted task finished with subtype={message.subtype!r}")
                # subtype is "error_during_execution" for interrupted tasks

        # Send a new command
        await client.query("Just say hello instead")

        # Now receive the new response
        async for message in client.receive_response():
            if isinstance(message, ResultMessage) and message.subtype == "success":
                print(f"New result: {message.result}")


asyncio.run(interruptible_task())

例 - 高度なパーミッション制御

from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
from claude_agent_sdk.types import (
    PermissionResultAllow,
    PermissionResultDeny,
    ToolPermissionContext,
)


async def custom_permission_handler(
    tool_name: str, input_data: dict, context: ToolPermissionContext
) -> PermissionResultAllow | PermissionResultDeny:
    """Custom logic for tool permissions."""

    # Block writes to system directories
    if tool_name == "Write" and input_data.get("file_path", "").startswith("/system/"):
        return PermissionResultDeny(
            message="System directory write not allowed", interrupt=True
        )

    # Redirect sensitive file operations
    if tool_name in ["Write", "Edit"] and "config" in input_data.get("file_path", ""):
        safe_path = f"./sandbox/{input_data['file_path']}"
        return PermissionResultAllow(
            updated_input={**input_data, "file_path": safe_path}
        )

    # Allow everything else
    return PermissionResultAllow(updated_input=input_data)


async def main():
    options = ClaudeAgentOptions(
        can_use_tool=custom_permission_handler, allowed_tools=["Read", "Write", "Edit"]
    )

    async with ClaudeSDKClient(options=options) as client:
        await client.query("Update the system config file")

        async for message in client.receive_response():
            # Will use sandbox path instead
            print(message)


asyncio.run(main())

SdkMcpTool

@tool デコレータで作成された SDK MCP ツールの定義。

@dataclass
class SdkMcpTool(Generic[T]):
    name: str
    description: str
    input_schema: type[T] | dict[str, Any]
    handler: Callable[[T], Awaitable[dict[str, Any]]]
    annotations: ToolAnnotations | None = None
プロパティ 説明
name str ツールの一意の識別子
description str 人間が読める説明
input_schema type[T] | dict[str, Any] 入力検証用のスキーマ
handler Callable[[T], Awaitable[dict[str, Any]]] ツール実行を処理する非同期関数
annotations ToolAnnotations | None オプションの MCP ツールアノテーション(例:readOnlyHintdestructiveHintopenWorldHint)。mcp.types から

Transport

カスタムトランスポート実装の抽象基本クラス。これを使用して、カスタムチャネル(例:ローカルサブプロセスの代わりにリモート接続)を介して Claude プロセスと通信します。

from abc import ABC, abstractmethod
from collections.abc import AsyncIterator
from typing import Any


class Transport(ABC):
    @abstractmethod
    async def connect(self) -> None: ...

    @abstractmethod
    async def write(self, data: str) -> None: ...

    @abstractmethod
    def read_messages(self) -> AsyncIterator[dict[str, Any]]: ...

    @abstractmethod
    async def close(self) -> None: ...

    @abstractmethod
    def is_ready(self) -> bool: ...

    @abstractmethod
    async def end_input(self) -> None: ...
メソッド 説明
connect() トランスポートを接続し、通信の準備をします
write(data) 生データ(JSON + 改行)をトランスポートに書き込みます
read_messages() 解析された JSON メッセージを生成する非同期イテレータ
close() 接続を閉じてリソースをクリーンアップします
is_ready() トランスポートが送受信できる場合は True を返します
end_input() 入力ストリームを閉じます(例:サブプロセストランスポートの stdin を閉じる)

インポート:from claude_agent_sdk import Transport

ClaudeAgentOptions

Claude Code クエリの設定 dataclass。

@dataclass
class ClaudeAgentOptions:
    tools: list[str] | ToolsPreset | None = None
    allowed_tools: list[str] = field(default_factory=list)
    system_prompt: str | SystemPromptPreset | None = None
    mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)
    strict_mcp_config: bool = False
    permission_mode: PermissionMode | None = None
    continue_conversation: bool = False
    resume: str | None = None
    max_turns: int | None = None
    max_budget_usd: float | None = None
    disallowed_tools: list[str] = field(default_factory=list)
    model: str | None = None
    fallback_model: str | None = None
    betas: list[SdkBeta] = field(default_factory=list)
    output_format: dict[str, Any] | None = None
    permission_prompt_tool_name: str | None = None
    cwd: str | Path | None = None
    cli_path: str | Path | None = None
    settings: str | None = None
    add_dirs: list[str | Path] = field(default_factory=list)
    env: dict[str, str] = field(default_factory=dict)
    extra_args: dict[str, str | None] = field(default_factory=dict)
    max_buffer_size: int | None = None
    debug_stderr: Any = sys.stderr  # Deprecated
    stderr: Callable[[str], None] | None = None
    can_use_tool: CanUseTool | None = None
    hooks: dict[HookEvent, list[HookMatcher]] | None = None
    user: str | None = None
    include_partial_messages: bool = False
    include_hook_events: bool = False
    fork_session: bool = False
    agents: dict[str, AgentDefinition] | None = None
    setting_sources: list[SettingSource] | None = None
    sandbox: SandboxSettings | None = None
    plugins: list[SdkPluginConfig] = field(default_factory=list)
    max_thinking_tokens: int | None = None  # Deprecated: use thinking instead
    thinking: ThinkingConfig | None = None
    effort: Literal["low", "medium", "high", "xhigh", "max"] | None = None
    enable_file_checkpointing: bool = False
    session_store: SessionStore | None = None
    session_store_flush: SessionStoreFlushMode = "batched"
プロパティ デフォルト 説明
tools list[str] | ToolsPreset | None None ツール設定。Claude Code のデフォルトツールには {"type": "preset", "preset": "claude_code"} を使用します
allowed_tools list[str] [] プロンプトなしで自動承認するツール。これは Claude をこれらのツールのみに制限しません。リストされていないツールは permission_modecan_use_tool にフォールスルーします。disallowed_tools を使用してツールをブロックします。パーミッション を参照
system_prompt str | SystemPromptPreset | None None システムプロンプト設定。カスタムプロンプトの場合は文字列を渡すか、Claude Code のシステムプロンプトの場合は {"type": "preset", "preset": "claude_code"} を使用します。プリセットを拡張するには "append" を追加します
mcp_servers dict[str, McpServerConfig] | str | Path {} MCP サーバー設定または設定ファイルへのパス
strict_mcp_config bool False True の場合、mcp_servers で渡されたサーバーのみを使用し、プロジェクト .mcp.json、ユーザー設定、プラグイン提供の MCP サーバーを無視します。CLI --strict-mcp-config フラグにマップされます
permission_mode PermissionMode | None None ツール使用のパーミッションモード
continue_conversation bool False 最新の会話を続ける
resume str | None None 再開するセッション ID
max_turns int | None None 最大 agentic ターン数(ツール使用ラウンドトリップ)
max_budget_usd float | None None クライアント側のコスト推定がこの USD 値に達したときにクエリを停止します。total_cost_usd と同じ推定と比較されます。コストと使用状況を追跡 で精度の注意事項を参照
disallowed_tools list[str] [] 常に拒否するツール。拒否ルールが最初にチェックされ、allowed_toolspermission_modebypassPermissions を含む)をオーバーライドします
enable_file_checkpointing bool False ファイル変更追跡を有効にして巻き戻しを可能にします。ファイルチェックポイント を参照
model str | None None 使用する Claude モデル
fallback_model str | None None プライマリモデルが失敗した場合に使用するフォールバックモデル
betas list[SdkBeta] [] 有効にするベータ機能。利用可能なオプションについては SdkBeta を参照
output_format dict[str, Any] | None None 構造化応答の出力形式(例:{"type": "json_schema", "schema": {...}})。詳細については 構造化出力 を参照
permission_prompt_tool_name str | None None パーミッションプロンプト用の MCP ツール名
cwd str | Path | None None 現在の作業ディレクトリ
cli_path str | Path | None None Claude Code CLI 実行可能ファイルへのカスタムパス
settings str | None None 設定ファイルへのパス
add_dirs list[str | Path] [] Claude がアクセスできる追加ディレクトリ
env dict[str, str] {} 継承されたプロセス環境の上にマージされた環境変数。環境変数 で、基盤となる CLI が読み込む変数を参照し、遅いまたは停止した API レスポンスを処理 でタイムアウト関連の変数を参照してください
extra_args dict[str, str | None] {} CLI に直接渡す追加 CLI 引数
max_buffer_size int | None None CLI stdout をバッファリングする場合の最大バイト数
debug_stderr Any sys.stderr 非推奨 - デバッグ出力用のファイルのようなオブジェクト。代わりに stderr コールバックを使用してください
stderr Callable[[str], None] | None None CLI からの stderr 出力用のコールバック関数
can_use_tool CanUseTool | None None ツールパーミッションコールバック関数。詳細については パーミッション型 を参照
hooks dict[HookEvent, list[HookMatcher]] | None None イベントをインターセプトするための hook 設定
user str | None None ユーザー識別子
include_partial_messages bool False 部分的なメッセージストリーミングイベントを含めます。有効にすると、StreamEvent メッセージが生成されます
include_hook_events bool False hook ライフサイクルイベントをメッセージストリームに HookEventMessage オブジェクトとして含めます
fork_session bool False resume で再開する場合、元のセッションを続ける代わりに新しいセッション ID にフォークします
agents dict[str, AgentDefinition] | None None プログラムで定義されたサブエージェント
plugins list[SdkPluginConfig] [] ローカルパスからカスタムプラグインを読み込みます。詳細については プラグイン を参照
sandbox SandboxSettings | None None プログラムでサンドボックス動作を設定します。詳細については サンドボックス設定 を参照
setting_sources list[SettingSource] | None None(CLI デフォルト:すべてのソース) 読み込むファイルシステム設定を制御します。[] を渡してユーザー、プロジェクト、ローカル設定を無効にします。管理ポリシー設定は常に読み込まれます。Claude Code 機能を使用 を参照
skills list[str] | Literal["all"] | None None セッションで利用可能なスキル。すべての検出されたスキルを有効にするには "all" を渡すか、スキル名のリストを渡します。設定すると、SDK は allowed_tools にリストしなくても Skill ツールを自動的に有効にします。スキル を参照
max_thinking_tokens int | None None 非推奨 - 思考ブロックの最大トークン数。代わりに thinking を使用してください
thinking ThinkingConfig | None None 拡張思考動作を制御します。max_thinking_tokens より優先されます
effort Literal["low", "medium", "high", "xhigh", "max"] | None None 思考の深さの努力レベル
session_store SessionStore | None None セッショントランスクリプトを外部バックエンドにミラーリングして、任意のホストがそれらを再開できるようにします。セッションを外部ストレージに永続化 を参照
session_store_flush Literal["batched", "eager"] "batched" ミラーリングされたトランスクリプトエントリを session_store にフラッシュするタイミング。"batched" はターンごと、またはバッファが満杯になったときにフラッシュします。"eager" はすべてのフレームの後にバックグラウンドフラッシュをトリガーします。session_storeNone の場合は無視されます

遅いまたは停止した API レスポンスを処理

CLI サブプロセスは、API タイムアウトと停止検出を制御するいくつかの環境変数を読み込みます。ClaudeAgentOptions.env を通じてそれらを渡します:

options = ClaudeAgentOptions(
    env={
        "API_TIMEOUT_MS": "120000",
        "CLAUDE_CODE_MAX_RETRIES": "2",
        "CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS": "120000",
    },
)
  • API_TIMEOUT_MS:Anthropic クライアントのリクエストごとのタイムアウト(ミリ秒単位)。デフォルト 600000。メインループとすべてのサブエージェントに適用されます。
  • CLAUDE_CODE_MAX_RETRIES:最大 API リトライ数。デフォルト 10。各リトライは独自の API_TIMEOUT_MS ウィンドウを取得するため、最悪の場合の実時間はおおよそ API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1) にバックオフを加えたものです。
  • CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MSrun_in_background で起動されたサブエージェント用の停止ウォッチドッグ。デフォルト 600000。各ストリームイベントでリセットされます。停止時にサブエージェントを中止し、タスクを失敗とマークし、部分的な結果を含むエラーを親に表示します。同期サブエージェントには適用されません。
  • CLAUDE_ENABLE_STREAM_WATCHDOG=1CLAUDE_STREAM_IDLE_TIMEOUT_MS:ヘッダーが到着したがレスポンスボディがストリーミングを停止したときにリクエストを中止します。デフォルトではオフです。CLAUDE_STREAM_IDLE_TIMEOUT_MS はデフォルト 300000 で、その最小値にクランプされます。中止されたリクエストは通常のリトライパスを通ります。

OutputFormat

構造化出力検証の設定。これを ClaudeAgentOptionsoutput_format フィールドに dict として渡します:

# Expected dict shape for output_format
{
    "type": "json_schema",
    "schema": {...},  # Your JSON Schema definition
}
フィールド 必須 説明
type はい JSON Schema 検証の場合は "json_schema" である必要があります
schema はい 出力検証用の JSON Schema 定義

SystemPromptPreset

オプションの追加を含む Claude Code のプリセットシステムプロンプトを使用するための設定。

class SystemPromptPreset(TypedDict):
    type: Literal["preset"]
    preset: Literal["claude_code"]
    append: NotRequired[str]
    exclude_dynamic_sections: NotRequired[bool]
フィールド 必須 説明
type はい プリセットシステムプロンプトを使用するには "preset" である必要があります
preset はい Claude Code のシステムプロンプトを使用するには "claude_code" である必要があります
append いいえ プリセットシステムプロンプトに追加する追加の指示
exclude_dynamic_sections いいえ 作業ディレクトリ、git ステータス、メモリパスなどのセッションごとのコンテキストをシステムプロンプトから最初のユーザーメッセージに移動します。ユーザーとマシン全体でのプロンプトキャッシュの再利用を改善します。システムプロンプトを変更 を参照

SettingSource

SDK が設定を読み込むファイルシステムベースの設定ソースを制御します。

SettingSource = Literal["user", "project", "local"]
説明 場所
"user" グローバルユーザー設定 ~/.claude/settings.json
"project" 共有プロジェクト設定(バージョン管理) .claude/settings.json
"local" ローカルプロジェクト設定(gitignored) .claude/settings.local.json

デフォルト動作

setting_sources が省略されるか None の場合、query() は Claude Code CLI と同じファイルシステム設定を読み込みます:ユーザー、プロジェクト、ローカル。管理ポリシー設定はすべての場合に読み込まれます。このオプションに関係なく読み込まれる入力については settingSources が制御しないもの を参照し、それらを無効にする方法を参照してください。

setting_sources を使用する理由

ファイルシステム設定を無効にする:

# Do not load user, project, or local settings from disk
from claude_agent_sdk import query, ClaudeAgentOptions

async for message in query(
    prompt="Analyze this code",
    options=ClaudeAgentOptions(
        setting_sources=[]
    ),
):
    print(message)

すべてのファイルシステム設定を明示的に読み込む:

from claude_agent_sdk import query, ClaudeAgentOptions

async for message in query(
    prompt="Analyze this code",
    options=ClaudeAgentOptions(
        setting_sources=["user", "project", "local"]
    ),
):
    print(message)

特定の設定ソースのみを読み込む:

# Load only project settings, ignore user and local
async for message in query(
    prompt="Run CI checks",
    options=ClaudeAgentOptions(
        setting_sources=["project"]  # Only .claude/settings.json
    ),
):
    print(message)

テストと CI 環境:

# Ensure consistent behavior in CI by excluding local settings
async for message in query(
    prompt="Run tests",
    options=ClaudeAgentOptions(
        setting_sources=["project"],  # Only team-shared settings
        permission_mode="bypassPermissions",
    ),
):
    print(message)

SDK のみのアプリケーション:

# Define everything programmatically.
# Pass [] to opt out of filesystem setting sources.
async for message in query(
    prompt="Review this PR",
    options=ClaudeAgentOptions(
        setting_sources=[],
        agents={...},
        mcp_servers={...},
        allowed_tools=["Read", "Grep", "Glob"],
    ),
):
    print(message)

CLAUDE.md プロジェクト指示を読み込む:

# Load project settings to include CLAUDE.md files
async for message in query(
    prompt="Add a new feature following project conventions",
    options=ClaudeAgentOptions(
        system_prompt={
            "type": "preset",
            "preset": "claude_code",  # Use Claude Code's system prompt
        },
        setting_sources=["project"],  # Loads CLAUDE.md from project
        allowed_tools=["Read", "Write", "Edit"],
    ),
):
    print(message)

設定の優先順位

複数のソースが読み込まれる場合、設定はこの優先順位(最高から最低)でマージされます:

  1. ローカル設定(.claude/settings.local.json
  2. プロジェクト設定(.claude/settings.json
  3. ユーザー設定(~/.claude/settings.json

agentsallowed_tools などのプログラム的なオプションは、ユーザー、プロジェクト、ローカルのファイルシステム設定をオーバーライドします。管理ポリシー設定はプログラム的なオプションより優先されます。

AgentDefinition

プログラムで定義されたサブエージェントの設定。

@dataclass
class AgentDefinition:
    description: str
    prompt: str
    tools: list[str] | None = None
    disallowedTools: list[str] | None = None
    model: str | None = None
    skills: list[str] | None = None
    memory: Literal["user", "project", "local"] | None = None
    mcpServers: list[str | dict[str, Any]] | None = None
    initialPrompt: str | None = None
    maxTurns: int | None = None
    background: bool | None = None
    effort: Literal["low", "medium", "high", "xhigh", "max"] | int | None = None
    permissionMode: PermissionMode | None = None
フィールド 必須 説明
description はい このエージェントを使用する場合の自然言語説明
prompt はい エージェントのシステムプロンプト
tools いいえ 許可されたツール名の配列。省略した場合、すべてのツールを継承します
disallowedTools いいえ エージェントのツールセットから削除するツール名の配列
model いいえ このエージェントのモデルオーバーライド。"sonnet""opus""haiku""inherit" などのエイリアス、または完全なモデル ID を受け入れます。省略した場合、メインモデルを使用します
skills いいえ このエージェントが利用可能なスキル名のリスト
memory いいえ このエージェントのメモリソース:"user""project"、または "local"
mcpServers いいえ このエージェントが利用可能な MCP サーバー。各エントリはサーバー名またはインライン {name: config} dict です
initialPrompt いいえ このエージェントがメインスレッドエージェントとして実行される場合、最初のユーザーターンとして自動送信されます
maxTurns いいえ エージェントが停止する前の最大 agentic ターン数
background いいえ 呼び出されたときにこのエージェントをブロッキングされないバックグラウンドタスクとして実行します
effort いいえ このエージェントの推論努力レベル。名前付きレベルまたは整数を受け入れます
permissionMode いいえ このエージェント内のツール実行のパーミッションモード。PermissionMode を参照

PermissionMode

ツール実行を制御するためのパーミッションモード。

PermissionMode = Literal[
    "default",  # Standard permission behavior
    "acceptEdits",  # Auto-accept file edits
    "plan",  # Planning mode - read-only tools only
    "dontAsk",  # Deny anything not pre-approved instead of prompting
    "bypassPermissions",  # Bypass all permission checks (use with caution)
]

CanUseTool

ツールパーミッションコールバック関数の型エイリアス。

CanUseTool = Callable[
    [str, dict[str, Any], ToolPermissionContext], Awaitable[PermissionResult]
]

コールバックは以下を受け取ります:

  • tool_name:呼び出されるツールの名前
  • input_data:ツールの入力パラメータ
  • context:追加情報を含む ToolPermissionContext

PermissionResultPermissionResultAllow または PermissionResultDeny)を返します。

ToolPermissionContext

ツールパーミッションコールバックに渡されるコンテキスト情報。

@dataclass
class ToolPermissionContext:
    signal: Any | None = None  # Future: abort signal support
    suggestions: list[PermissionUpdate] = field(default_factory=list)
    blocked_path: str | None = None
    decision_reason: str | None = None
    title: str | None = None
    display_name: str | None = None
    description: str | None = None
フィールド 説明
signal Any | None 将来の中止信号サポート用に予約済み
suggestions list[PermissionUpdate] CLI からのパーミッション更新提案。Bash プロンプトには localSettings 宛先の提案が含まれているため、updated_permissions で返すと、ルールを .claude/settings.local.json に書き込み、セッション全体で永続化します。
blocked_path str | None パーミッションリクエストをトリガーしたファイルパス(該当する場合)。例えば、Bash コマンドが許可されたディレクトリ外のパスにアクセスしようとした場合
decision_reason str | None このパーミッションリクエストがトリガーされた理由。PreToolUse hook が "ask" を返したときに hook の permissionDecisionReason から転送されます
title str | None 完全なパーミッションプロンプト文。例えば、Claude wants to read foo.txt。存在する場合は、プライマリプロンプトテキストとして使用します
display_name str | None ツールアクション用の短い名詞句。例えば、Read file。ボタンラベルに適しています
description str | None パーミッション UI 用の人間が読める字幕

PermissionResult

パーミッションコールバック結果の Union 型。

PermissionResult = PermissionResultAllow | PermissionResultDeny

PermissionResultAllow

ツール呼び出しを許可すべきことを示す結果。

@dataclass
class PermissionResultAllow:
    behavior: Literal["allow"] = "allow"
    updated_input: dict[str, Any] | None = None
    updated_permissions: list[PermissionUpdate] | None = None
フィールド デフォルト 説明
behavior Literal["allow"] "allow" "allow" である必要があります
updated_input dict[str, Any] | None None 元の代わりに使用する変更された入力
updated_permissions list[PermissionUpdate] | None None 適用するパーミッション更新

PermissionResultDeny

ツール呼び出しを拒否すべきことを示す結果。

@dataclass
class PermissionResultDeny:
    behavior: Literal["deny"] = "deny"
    message: str = ""
    interrupt: bool = False
フィールド デフォルト 説明
behavior Literal["deny"] "deny" "deny" である必要があります
message str "" ツールが拒否された理由を説明するメッセージ
interrupt bool False 現在の実行を割り込むかどうか

PermissionUpdate

プログラムでパーミッションを更新するための設定。

@dataclass
class PermissionUpdate:
    type: Literal[
        "addRules",
        "replaceRules",
        "removeRules",
        "setMode",
        "addDirectories",
        "removeDirectories",
    ]
    rules: list[PermissionRuleValue] | None = None
    behavior: Literal["allow", "deny", "ask"] | None = None
    mode: PermissionMode | None = None
    directories: list[str] | None = None
    destination: (
        Literal["userSettings", "projectSettings", "localSettings", "session"] | None
    ) = None
フィールド 説明
type Literal[...] パーミッション更新操作のタイプ
rules list[PermissionRuleValue] | None 追加/置換/削除操作用のルール
behavior Literal["allow", "deny", "ask"] | None ルールベースの操作の動作
mode PermissionMode | None setMode 操作のモード
directories list[str] | None ディレクトリ追加/削除操作用のディレクトリ
destination Literal[...] | None パーミッション更新を適用する場所

PermissionRuleValue

パーミッション更新で追加、置換、または削除するルール。

@dataclass
class PermissionRuleValue:
    tool_name: str
    rule_content: str | None = None

ToolsPreset

Claude Code のデフォルトツールセットを使用するためのプリセットツール設定。

class ToolsPreset(TypedDict):
    type: Literal["preset"]
    preset: Literal["claude_code"]

ThinkingConfig

拡張思考動作を制御します。3 つの設定の Union:

class ThinkingConfigAdaptive(TypedDict):
    type: Literal["adaptive"]


class ThinkingConfigEnabled(TypedDict):
    type: Literal["enabled"]
    budget_tokens: int


class ThinkingConfigDisabled(TypedDict):
    type: Literal["disabled"]


ThinkingConfig = ThinkingConfigAdaptive | ThinkingConfigEnabled | ThinkingConfigDisabled
バリアント フィールド 説明
adaptive type Claude は適応的に思考するタイミングを決定します
enabled typebudget_tokens 特定のトークン予算で思考を有効にします
disabled type 思考を無効にします

これらは TypedDict クラスであるため、実行時にはプレーンな dict です。dict リテラルとして構築するか、クラスをコンストラクタのように呼び出します。どちらも dict を生成します。config["budget_tokens"] でフィールドにアクセスし、config.budget_tokens ではなく:

from claude_agent_sdk import ClaudeAgentOptions, ThinkingConfigEnabled

# Option 1: dict literal (recommended, no import needed)
options = ClaudeAgentOptions(thinking={"type": "enabled", "budget_tokens": 20000})

# Option 2: constructor-style (returns a plain dict)
config = ThinkingConfigEnabled(type="enabled", budget_tokens=20000)
print(config["budget_tokens"])  # 20000
# config.budget_tokens would raise AttributeError

SdkBeta

SDK ベータ機能の Literal 型。

SdkBeta = Literal["context-1m-2025-08-07"]

ClaudeAgentOptionsbetas フィールドで使用してベータ機能を有効にします。

McpSdkServerConfig

create_sdk_mcp_server() で作成された SDK MCP サーバーの設定。

class McpSdkServerConfig(TypedDict):
    type: Literal["sdk"]
    name: str
    instance: Any  # MCP Server instance

McpServerConfig

MCP サーバー設定の Union 型。

McpServerConfig = (
    McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig
)

McpStdioServerConfig

class McpStdioServerConfig(TypedDict):
    type: NotRequired[Literal["stdio"]]  # Optional for backwards compatibility
    command: str
    args: NotRequired[list[str]]
    env: NotRequired[dict[str, str]]

McpSSEServerConfig

class McpSSEServerConfig(TypedDict):
    type: Literal["sse"]
    url: str
    headers: NotRequired[dict[str, str]]

McpHttpServerConfig

class McpHttpServerConfig(TypedDict):
    type: Literal["http"]
    url: str
    headers: NotRequired[dict[str, str]]

McpServerStatusConfig

get_mcp_status() によって報告される MCP サーバーの設定。これは、すべての McpServerConfig トランスポートバリアント、および claude.ai を通じてプロキシされるサーバー用の出力のみの claudeai-proxy バリアントの Union です。

McpServerStatusConfig = (
    McpStdioServerConfig
    | McpSSEServerConfig
    | McpHttpServerConfig
    | McpSdkServerConfigStatus
    | McpClaudeAIProxyServerConfig
)

McpSdkServerConfigStatusMcpSdkServerConfig のシリアライズ可能な形式で、type"sdk")と namestr)フィールドのみです。インプロセス instance は省略されます。McpClaudeAIProxyServerConfig には type"claudeai-proxy")、urlstr)、idstr)フィールドがあります。

McpStatusResponse

ClaudeSDKClient.get_mcp_status() からの応答。サーバーステータスのリストを mcpServers キーの下にラップします。

class McpStatusResponse(TypedDict):
    mcpServers: list[McpServerStatus]

McpServerStatus

接続された MCP サーバーのステータス。McpStatusResponse に含まれます。

class McpServerStatus(TypedDict):
    name: str
    status: McpServerConnectionStatus  # "connected" | "failed" | "needs-auth" | "pending" | "disabled"
    serverInfo: NotRequired[McpServerInfo]
    error: NotRequired[str]
    config: NotRequired[McpServerStatusConfig]
    scope: NotRequired[str]
    tools: NotRequired[list[McpToolInfo]]
フィールド 説明
name str サーバー名
status str "connected""failed""needs-auth""pending"、または "disabled" のいずれか
serverInfo dict(オプション) サーバー名とバージョン({"name": str, "version": str}
error str(オプション) サーバーが接続に失敗した場合のエラーメッセージ
config McpServerStatusConfig(オプション) サーバー設定。McpServerConfig と同じ形状(stdio、SSE、HTTP、または SDK)、および claude.ai を通じて接続されたサーバー用の claudeai-proxy バリアント
scope str(オプション) 設定スコープ
tools list(オプション) このサーバーが提供するツール。各ツールには namedescriptionannotations フィールドがあります

SdkPluginConfig

SDK でプラグインを読み込むための設定。

class SdkPluginConfig(TypedDict):
    type: Literal["local"]
    path: str
フィールド 説明
type Literal["local"] "local" である必要があります(現在ローカルプラグインのみサポート)
path str プラグインディレクトリへの絶対パスまたは相対パス

例:

plugins = [
    {"type": "local", "path": "./my-plugin"},
    {"type": "local", "path": "/absolute/path/to/plugin"},
]

プラグインの作成と使用に関する完全な情報については、プラグイン を参照してください。

メッセージ型

Message

すべての可能なメッセージの Union 型。

Message = (
    UserMessage
    | AssistantMessage
    | SystemMessage
    | ResultMessage
    | StreamEvent
    | RateLimitEvent
)

UserMessage

ユーザー入力メッセージ。

@dataclass
class UserMessage:
    content: str | list[ContentBlock]
    uuid: str | None = None
    parent_tool_use_id: str | None = None
    tool_use_result: dict[str, Any] | None = None
フィールド 説明
content str | list[ContentBlock] テキストまたはコンテンツブロックとしてのメッセージコンテンツ
uuid str | None 一意のメッセージ識別子
parent_tool_use_id str | None このメッセージがツール結果応答の場合のツール使用 ID
tool_use_result dict[str, Any] | None 該当する場合のツール結果データ

AssistantMessage

コンテンツブロック付きのアシスタント応答メッセージ。

@dataclass
class AssistantMessage:
    content: list[ContentBlock]
    model: str
    parent_tool_use_id: str | None = None
    error: AssistantMessageError | None = None
    usage: dict[str, Any] | None = None
    message_id: str | None = None
フィールド 説明
content list[ContentBlock] 応答内のコンテンツブロックのリスト
model str 応答を生成したモデル
parent_tool_use_id str | None これがネストされた応答の場合のツール使用 ID
error AssistantMessageError | None 応答がエラーに遭遇した場合のエラー型
usage dict[str, Any] | None メッセージごとのトークン使用状況(ResultMessage.usage と同じキー)
message_id str | None API メッセージ ID。1 つのターンからの複数のメッセージは同じ ID を共有します

AssistantMessageError

アシスタントメッセージの可能なエラータイプ。

AssistantMessageError = Literal[
    "authentication_failed",
    "billing_error",
    "rate_limit",
    "invalid_request",
    "server_error",
    "max_output_tokens",
    "unknown",
]

SystemMessage

メタデータ付きのシステムメッセージ。

@dataclass
class SystemMessage:
    subtype: str
    data: dict[str, Any]

ResultMessage

コストと使用状況情報を含む最終結果メッセージ。

@dataclass
class ResultMessage:
    subtype: str
    duration_ms: int
    duration_api_ms: int
    is_error: bool
    num_turns: int
    session_id: str
    stop_reason: str | None = None
    total_cost_usd: float | None = None
    usage: dict[str, Any] | None = None
    result: str | None = None
    structured_output: Any = None
    model_usage: dict[str, Any] | None = None
    permission_denials: list[Any] | None = None
    deferred_tool_use: DeferredToolUse | None = None
    errors: list[str] | None = None
    api_error_status: int | None = None
    uuid: str | None = None

usage dict には、存在する場合、以下のキーが含まれます:

キー 説明
input_tokens int 消費された総入力トークン。
output_tokens int 生成された総出力トークン。
cache_creation_input_tokens int 新しいキャッシュエントリを作成するために使用されたトークン。
cache_read_input_tokens int 既存のキャッシュエントリから読み取られたトークン。

model_usage dict はモデル名をモデルごとの使用状況にマップします。内部 dict キーは camelCase を使用します。これは、基になる CLI プロセスから変更されずに渡される値であり、TypeScript ModelUsage 型と一致するためです:

キー 説明
inputTokens int このモデルの入力トークン。
outputTokens int このモデルの出力トークン。
cacheReadInputTokens int このモデルのキャッシュ読み取りトークン。
cacheCreationInputTokens int このモデルのキャッシュ作成トークン。
webSearchRequests int このモデルが行った Web 検索リクエスト。
costUSD float このモデルの推定 USD コスト。クライアント側で計算されます。コストと使用状況を追跡 で請求の注意事項を参照してください。
contextWindow int このモデルのコンテキストウィンドウサイズ。
maxOutputTokens int このモデルの最大出力トークン制限。

StreamEvent

ストリーミング中の部分的なメッセージ更新のためのストリームイベント。ClaudeAgentOptionsinclude_partial_messages=True の場合のみ受け取られます。from claude_agent_sdk.types import StreamEvent でインポートしてください。

@dataclass
class StreamEvent:
    uuid: str
    session_id: str
    event: dict[str, Any]  # The raw Claude API stream event
    parent_tool_use_id: str | None = None
フィールド 説明
uuid str このイベントの一意の識別子
session_id str セッション識別子
event dict[str, Any] 生の Claude API ストリームイベントデータ
parent_tool_use_id str | None このイベントがサブエージェントからの場合の親ツール使用 ID

RateLimitEvent

レート制限ステータスが変更されたときに発行されます(例:"allowed" から "allowed_warning" へ)。ユーザーにハード制限に達する前に警告するか、ステータスが "rejected" の場合にバックオフするために使用します。

@dataclass
class RateLimitEvent:
    rate_limit_info: RateLimitInfo
    uuid: str
    session_id: str
フィールド 説明
rate_limit_info RateLimitInfo 現在のレート制限状態
uuid str 一意のイベント識別子
session_id str セッション識別子

RateLimitInfo

RateLimitEvent によって運ばれるレート制限状態。

RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]
RateLimitType = Literal[
    "five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet", "overage"
]


@dataclass
class RateLimitInfo:
    status: RateLimitStatus
    resets_at: int | None = None
    rate_limit_type: RateLimitType | None = None
    utilization: float | None = None
    overage_status: RateLimitStatus | None = None
    overage_resets_at: int | None = None
    overage_disabled_reason: str | None = None
    raw: dict[str, Any] = field(default_factory=dict)
フィールド 説明
status RateLimitStatus 現在のステータス。"allowed_warning" は制限に近づいていることを意味します。"rejected" は制限に達したことを意味します
resets_at int | None レート制限ウィンドウがリセットされる Unix タイムスタンプ
rate_limit_type RateLimitType | None どのレート制限ウィンドウが適用されるか
utilization float | None 消費されたレート制限の割合(0.0 から 1.0)
overage_status RateLimitStatus | None 該当する場合の従量課金超過使用のステータス
overage_resets_at int | None 超過ウィンドウがリセットされる Unix タイムスタンプ
overage_disabled_reason str | None ステータスが "rejected" の場合、超過が利用できない理由
raw dict[str, Any] 上記でモデル化されていないフィールドを含む、CLI からの完全な生 dict

TaskStartedMessage

バックグラウンドタスクが開始されたときに発行されます。バックグラウンドタスクは、メインターンの外で追跡されるもの:バックグラウンド Bash コマンド、Monitor ウォッチ、Agent ツール経由で生成されたサブエージェント、またはリモートエージェント。task_type フィールドはどれであるかを示します。このネーミングは Task から Agent ツールへの名前変更とは無関係です。

@dataclass
class TaskStartedMessage(SystemMessage):
    task_id: str
    description: str
    uuid: str
    session_id: str
    tool_use_id: str | None = None
    task_type: str | None = None
フィールド 説明
task_id str タスクの一意の識別子
description str タスクの説明
uuid str 一意のメッセージ識別子
session_id str セッション識別子
tool_use_id str | None 関連するツール使用 ID
task_type str | None バックグラウンドタスクの種類:バックグラウンド Bash と Monitor ウォッチの場合は "local_bash""local_agent"、または "remote_agent"

TaskUsage

バックグラウンドタスクのトークンとタイミングデータ。

class TaskUsage(TypedDict):
    total_tokens: int
    tool_uses: int
    duration_ms: int

TaskProgressMessage

実行中のバックグラウンドタスクの進捗更新で定期的に発行されます。

@dataclass
class TaskProgressMessage(SystemMessage):
    task_id: str
    description: str
    usage: TaskUsage
    uuid: str
    session_id: str
    tool_use_id: str | None = None
    last_tool_name: str | None = None
フィールド 説明
task_id str タスクの一意の識別子
description str 現在のステータス説明
usage TaskUsage これまでのこのタスクのトークン使用状況
uuid str 一意のメッセージ識別子
session_id str セッション識別子
tool_use_id str | None 関連するツール使用 ID
last_tool_name str | None タスクが最後に使用したツールの名前

TaskNotificationMessage

バックグラウンドタスクが完了、失敗、または停止されたときに発行されます。バックグラウンドタスクには、run_in_background Bash コマンド、Monitor ウォッチ、バックグラウンドサブエージェントが含まれます。

@dataclass
class TaskNotificationMessage(SystemMessage):
    task_id: str
    status: TaskNotificationStatus  # "completed" | "failed" | "stopped"
    output_file: str
    summary: str
    uuid: str
    session_id: str
    tool_use_id: str | None = None
    usage: TaskUsage | None = None
フィールド 説明
task_id str タスクの一意の識別子
status TaskNotificationStatus "completed""failed"、または "stopped" のいずれか
output_file str タスク出力ファイルへのパス
summary str タスク結果のサマリー
uuid str 一意のメッセージ識別子
session_id str セッション識別子
tool_use_id str | None 関連するツール使用 ID
usage TaskUsage | None タスクの最終トークン使用状況

コンテンツブロック型

ContentBlock

すべてのコンテンツブロックの Union 型。

ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock

TextBlock

テキストコンテンツブロック。

@dataclass
class TextBlock:
    text: str

ThinkingBlock

思考コンテンツブロック(思考機能を持つモデル用)。

@dataclass
class ThinkingBlock:
    thinking: str
    signature: str

ToolUseBlock

ツール使用リクエストブロック。

@dataclass
class ToolUseBlock:
    id: str
    name: str
    input: dict[str, Any]

ToolResultBlock

ツール実行結果ブロック。

@dataclass
class ToolResultBlock:
    tool_use_id: str
    content: str | list[dict[str, Any]] | None = None
    is_error: bool | None = None

エラー型

ClaudeSDKError

すべての SDK エラーの基本例外クラス。

class ClaudeSDKError(Exception):
    """Base error for Claude SDK."""

CLINotFoundError

Claude Code CLI がインストールされていないか見つからない場合に発生します。

class CLINotFoundError(CLIConnectionError):
    def __init__(
        self, message: str = "Claude Code not found", cli_path: str | None = None
    ):
        """
        Args:
            message: Error message (default: "Claude Code not found")
            cli_path: Optional path to the CLI that was not found
        """

CLIConnectionError

Claude Code への接続に失敗した場合に発生します。

class CLIConnectionError(ClaudeSDKError):
    """Failed to connect to Claude Code."""

ProcessError

Claude Code プロセスが失敗した場合に発生します。

class ProcessError(ClaudeSDKError):
    def __init__(
        self, message: str, exit_code: int | None = None, stderr: str | None = None
    ):
        self.exit_code = exit_code
        self.stderr = stderr

CLIJSONDecodeError

JSON 解析に失敗した場合に発生します。

class CLIJSONDecodeError(ClaudeSDKError):
    def __init__(self, line: str, original_error: Exception):
        """
        Args:
            line: The line that failed to parse
            original_error: The original JSON decode exception
        """
        self.line = line
        self.original_error = original_error

Hook 型

hooks の使用に関する包括的なガイド、例、一般的なパターンについては、Hooks ガイド を参照してください。

HookEvent

サポートされている hook イベント型。

HookEvent = Literal[
    "PreToolUse",  # Called before tool execution
    "PostToolUse",  # Called after tool execution
    "PostToolUseFailure",  # Called when a tool execution fails
    "UserPromptSubmit",  # Called when user submits a prompt
    "Stop",  # Called when stopping execution
    "SubagentStop",  # Called when a subagent stops
    "PreCompact",  # Called before message compaction
    "Notification",  # Called for notification events
    "SubagentStart",  # Called when a subagent starts
    "PermissionRequest",  # Called when a permission decision is needed
]

HookCallback

hook コールバック関数の型定義。

HookCallback = Callable[[HookInput, str | None, HookContext], Awaitable[HookJSONOutput]]

パラメータ:

  • inputhook_event_name に基づいた判別 Union を持つ強く型付けされた hook 入力(HookInput を参照)
  • tool_use_id:オプションのツール使用識別子(ツール関連の hook 用)
  • context:追加情報を含む hook コンテキスト

以下を含む可能性のある HookJSONOutput を返します:

  • decision:アクションをブロックするには "block"
  • systemMessage:ユーザーに表示される警告メッセージ
  • hookSpecificOutput:hook 固有の出力データ

HookContext

hook コールバックに渡されるコンテキスト情報。

class HookContext(TypedDict):
    signal: Any | None  # Future: abort signal support

HookMatcher

特定のイベントまたはツールに hook をマッチングするための設定。

@dataclass
class HookMatcher:
    matcher: str | None = (
        None  # Tool name or pattern to match (e.g., "Bash", "Write|Edit")
    )
    hooks: list[HookCallback] = field(
        default_factory=list
    )  # List of callbacks to execute
    timeout: float | None = (
        None  # Timeout in seconds for all hooks in this matcher (default: 60)
    )

HookInput

すべての hook 入力型の Union 型。実際の型は hook_event_name フィールドに依存します。

HookInput = (
    PreToolUseHookInput
    | PostToolUseHookInput
    | PostToolUseFailureHookInput
    | UserPromptSubmitHookInput
    | StopHookInput
    | SubagentStopHookInput
    | PreCompactHookInput
    | NotificationHookInput
    | SubagentStartHookInput
    | PermissionRequestHookInput
)

BaseHookInput

すべての hook 入力型に存在する基本フィールド。

class BaseHookInput(TypedDict):
    session_id: str
    transcript_path: str
    cwd: str
    permission_mode: NotRequired[str]
フィールド 説明
session_id str 現在のセッション識別子
transcript_path str セッショントランスクリプトファイルへのパス
cwd str 現在の作業ディレクトリ
permission_mode str(オプション) 現在のパーミッションモード

PreToolUseHookInput

PreToolUse hook イベントの入力データ。

class PreToolUseHookInput(BaseHookInput):
    hook_event_name: Literal["PreToolUse"]
    tool_name: str
    tool_input: dict[str, Any]
    tool_use_id: str
    agent_id: NotRequired[str]
    agent_type: NotRequired[str]
フィールド 説明
hook_event_name Literal["PreToolUse"] 常に "PreToolUse"
tool_name str 実行しようとしているツールの名前
tool_input dict[str, Any] ツールの入力パラメータ
tool_use_id str このツール使用の一意の識別子
agent_id str(オプション) サブエージェント識別子。hook がサブエージェント内で発火する場合に存在
agent_type str(オプション) サブエージェント型。hook がサブエージェント内で発火する場合に存在

PostToolUseHookInput

PostToolUse hook イベントの入力データ。

class PostToolUseHookInput(BaseHookInput):
    hook_event_name: Literal["PostToolUse"]
    tool_name: str
    tool_input: dict[str, Any]
    tool_response: Any
    tool_use_id: str
    agent_id: NotRequired[str]
    agent_type: NotRequired[str]
フィールド 説明
hook_event_name Literal["PostToolUse"] 常に "PostToolUse"
tool_name str 実行されたツールの名前
tool_input dict[str, Any] 使用された入力パラメータ
tool_response Any ツール実行からの応答
tool_use_id str このツール使用の一意の識別子
agent_id str(オプション) サブエージェント識別子。hook がサブエージェント内で発火する場合に存在
agent_type str(オプション) サブエージェント型。hook がサブエージェント内で発火する場合に存在

PostToolUseFailureHookInput

PostToolUseFailure hook イベントの入力データ。ツール実行が失敗したときに呼び出されます。

class PostToolUseFailureHookInput(BaseHookInput):
    hook_event_name: Literal["PostToolUseFailure"]
    tool_name: str
    tool_input: dict[str, Any]
    tool_use_id: str
    error: str
    is_interrupt: NotRequired[bool]
    agent_id: NotRequired[str]
    agent_type: NotRequired[str]
フィールド 説明
hook_event_name Literal["PostToolUseFailure"] 常に "PostToolUseFailure"
tool_name str 失敗したツールの名前
tool_input dict[str, Any] 使用された入力パラメータ
tool_use_id str このツール使用の一意の識別子
error str 失敗した実行からのエラーメッセージ
is_interrupt bool(オプション) 失敗が割り込みによって引き起こされたかどうか
agent_id str(オプション) サブエージェント識別子。hook がサブエージェント内で発火する場合に存在
agent_type str(オプション) サブエージェント型。hook がサブエージェント内で発火する場合に存在

UserPromptSubmitHookInput

UserPromptSubmit hook イベントの入力データ。

class UserPromptSubmitHookInput(BaseHookInput):
    hook_event_name: Literal["UserPromptSubmit"]
    prompt: str
フィールド 説明
hook_event_name Literal["UserPromptSubmit"] 常に "UserPromptSubmit"
prompt str ユーザーが送信したプロンプト

StopHookInput

Stop hook イベントの入力データ。

class StopHookInput(BaseHookInput):
    hook_event_name: Literal["Stop"]
    stop_hook_active: bool
フィールド 説明
hook_event_name Literal["Stop"] 常に "Stop"
stop_hook_active bool stop hook がアクティブかどうか

SubagentStopHookInput

SubagentStop hook イベントの入力データ。

class SubagentStopHookInput(BaseHookInput):
    hook_event_name: Literal["SubagentStop"]
    stop_hook_active: bool
    agent_id: str
    agent_transcript_path: str
    agent_type: str
フィールド 説明
hook_event_name Literal["SubagentStop"] 常に "SubagentStop"
stop_hook_active bool stop hook がアクティブかどうか
agent_id str サブエージェントの一意の識別子
agent_transcript_path str サブエージェントのトランスクリプトファイルへのパス
agent_type str サブエージェントの型

PreCompactHookInput

PreCompact hook イベントの入力データ。

class PreCompactHookInput(BaseHookInput):
    hook_event_name: Literal["PreCompact"]
    trigger: Literal["manual", "auto"]
    custom_instructions: str | None
フィールド 説明
hook_event_name Literal["PreCompact"] 常に "PreCompact"
trigger Literal["manual", "auto"] コンパクションをトリガーしたもの
custom_instructions str | None コンパクション用のカスタム指示

NotificationHookInput

Notification hook イベントの入力データ。

class NotificationHookInput(BaseHookInput):
    hook_event_name: Literal["Notification"]
    message: str
    title: NotRequired[str]
    notification_type: str
フィールド 説明
hook_event_name Literal["Notification"] 常に "Notification"
message str 通知メッセージコンテンツ
title str(オプション) 通知タイトル
notification_type str 通知の型

SubagentStartHookInput

SubagentStart hook イベントの入力データ。

class SubagentStartHookInput(BaseHookInput):
    hook_event_name: Literal["SubagentStart"]
    agent_id: str
    agent_type: str
フィールド 説明
hook_event_name Literal["SubagentStart"] 常に "SubagentStart"
agent_id str サブエージェントの一意の識別子
agent_type str サブエージェントの型

PermissionRequestHookInput

PermissionRequest hook イベントの入力データ。hooks がパーミッション決定をプログラムで処理できるようにします。

class PermissionRequestHookInput(BaseHookInput):
    hook_event_name: Literal["PermissionRequest"]
    tool_name: str
    tool_input: dict[str, Any]
    permission_suggestions: NotRequired[list[Any]]
フィールド 説明
hook_event_name Literal["PermissionRequest"] 常に "PermissionRequest"
tool_name str パーミッションをリクエストするツールの名前
tool_input dict[str, Any] ツールの入力パラメータ
permission_suggestions list[Any](オプション) CLI からの提案されたパーミッション更新

HookJSONOutput

hook コールバック戻り値の Union 型。

HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput

SyncHookJSONOutput

制御フィールドと決定フィールドを持つ同期 hook 出力。

class SyncHookJSONOutput(TypedDict):
    # Control fields
    continue_: NotRequired[bool]  # Whether to proceed (default: True)
    suppressOutput: NotRequired[bool]  # Hide stdout from transcript
    stopReason: NotRequired[str]  # Message when continue is False

    # Decision fields
    decision: NotRequired[Literal["block"]]
    systemMessage: NotRequired[str]  # Warning message for user
    reason: NotRequired[str]  # Feedback for Claude

    # Hook-specific output
    hookSpecificOutput: NotRequired[HookSpecificOutput]

HookSpecificOutput

hook イベント名とイベント固有のフィールドを含む TypedDict。形状は hookEventName 値に依存します。hook イベントごとに利用可能なフィールドの詳細については、hooks で実行を制御 を参照してください。

イベント固有の出力型の判別 union。hookEventName フィールドはどのフィールドが有効かを決定します。

class PreToolUseHookSpecificOutput(TypedDict):
    hookEventName: Literal["PreToolUse"]
    permissionDecision: NotRequired[Literal["allow", "deny", "ask", "defer"]]
    permissionDecisionReason: NotRequired[str]
    updatedInput: NotRequired[dict[str, Any]]
    additionalContext: NotRequired[str]


class PostToolUseHookSpecificOutput(TypedDict):
    hookEventName: Literal["PostToolUse"]
    additionalContext: NotRequired[str]
    updatedToolOutput: NotRequired[Any]
    updatedMCPToolOutput: NotRequired[Any]


class PostToolUseFailureHookSpecificOutput(TypedDict):
    hookEventName: Literal["PostToolUseFailure"]
    additionalContext: NotRequired[str]


class UserPromptSubmitHookSpecificOutput(TypedDict):
    hookEventName: Literal["UserPromptSubmit"]
    additionalContext: NotRequired[str]


class NotificationHookSpecificOutput(TypedDict):
    hookEventName: Literal["Notification"]
    additionalContext: NotRequired[str]


class SubagentStartHookSpecificOutput(TypedDict):
    hookEventName: Literal["SubagentStart"]
    additionalContext: NotRequired[str]


class PermissionRequestHookSpecificOutput(TypedDict):
    hookEventName: Literal["PermissionRequest"]
    decision: dict[str, Any]


HookSpecificOutput = (
    PreToolUseHookSpecificOutput
    | PostToolUseHookSpecificOutput
    | PostToolUseFailureHookSpecificOutput
    | UserPromptSubmitHookSpecificOutput
    | NotificationHookSpecificOutput
    | SubagentStartHookSpecificOutput
    | PermissionRequestHookSpecificOutput
)

AsyncHookJSONOutput

hook 実行を遅延させる非同期 hook 出力。

class AsyncHookJSONOutput(TypedDict):
    async_: Literal[True]  # Set to True to defer execution
    asyncTimeout: NotRequired[int]  # Timeout in milliseconds

Hook 使用例

この例は 2 つの hook を登録します:1 つは rm -rf / のような危険な bash コマンドをブロックし、もう 1 つは監査のためにすべてのツール使用をログします。セキュリティ hook は matcher を介して Bash コマンドでのみ実行され、ログ hook はすべてのツールで実行されます。

from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext
from typing import Any


async def validate_bash_command(
    input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
) -> dict[str, Any]:
    """Validate and potentially block dangerous bash commands."""
    if input_data["tool_name"] == "Bash":
        command = input_data["tool_input"].get("command", "")
        if "rm -rf /" in command:
            return {
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "deny",
                    "permissionDecisionReason": "Dangerous command blocked",
                }
            }
    return {}


async def log_tool_use(
    input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
) -> dict[str, Any]:
    """Log all tool usage for auditing."""
    print(f"Tool used: {input_data.get('tool_name')}")
    return {}


options = ClaudeAgentOptions(
    hooks={
        "PreToolUse": [
            HookMatcher(
                matcher="Bash", hooks=[validate_bash_command], timeout=120
            ),  # 2 min for validation
            HookMatcher(
                hooks=[log_tool_use]
            ),  # Applies to all tools (default 60s timeout)
        ],
        "PostToolUse": [HookMatcher(hooks=[log_tool_use])],
    }
)

async for message in query(prompt="Analyze this codebase", options=options):
    print(message)

ツール入出力型

すべての組み込み Claude Code ツールの入出力スキーマのドキュメント。Python SDK はこれらを型としてエクスポートしませんが、メッセージ内のツール入出力の構造を表します。

Agent

ツール名: Agent(以前は Task。これはまだエイリアスとして受け入れられます)

入力:

{
    "description": str,  # タスクの短い説明(3~5 語)
    "prompt": str,  # エージェントが実行するタスク
    "subagent_type": str,  # 使用する特化したエージェントのタイプ
}

出力:

{
    "result": str,  # サブエージェントからの最終結果
    "usage": dict | None,  # トークン使用統計
    "total_cost_usd": float | None,  # 推定総コスト(USD)
    "duration_ms": int | None,  # 実行時間(ミリ秒)
}

AskUserQuestion

ツール名: AskUserQuestion

実行中にユーザーに明確化の質問をします。使用の詳細については 承認とユーザー入力を処理 を参照してください。

入力:

{
    "questions": [  # ユーザーに質問する質問(1~4 個の質問)
        {
            "question": str,  # ユーザーに質問する完全な質問
            "header": str,  # チップ/タグとして表示される非常に短いラベル(最大 12 文字)
            "options": [  # 利用可能な選択肢(2~4 個のオプション)
                {
                    "label": str,  # このオプションの表示テキスト(1~5 語)
                    "description": str,  # このオプションが何を意味するかの説明
                }
            ],
            "multiSelect": bool,  # 複数選択を許可する場合は true に設定
        }
    ],
    "answers": dict[str, str | list[str]] | None,
    # パーミッションシステムによって入力されたユーザーの回答。マルチセレクト
    # 回答はラベルのリストまたはカンマ区切り文字列の場合があります
}

出力:

{
    "questions": [  # 質問された質問
        {
            "question": str,
            "header": str,
            "options": [{"label": str, "description": str}],
            "multiSelect": bool,
        }
    ],
    "answers": dict[str, str],  # 質問テキストを回答文字列にマップ
    # マルチセレクト回答はカンマ区切り
}

Bash

ツール名: Bash

入力:

{
    "command": str,  # 実行するコマンド
    "timeout": int | None,  # オプションのタイムアウト(ミリ秒、最大 600000)
    "description": str | None,  # 明確で簡潔な説明(5~10 語)
    "run_in_background": bool | None,  # バックグラウンドで実行する場合は true に設定
}

出力:

{
    "output": str,  # 標準出力と標準エラーの結合出力
    "exitCode": int,  # コマンドの終了コード
    "killed": bool | None,  # タイムアウトによってコマンドが強制終了されたかどうか
    "shellId": str | None,  # バックグラウンドプロセスのシェル ID
}

Monitor

ツール名: Monitor

バックグラウンドスクリプトを実行し、各 stdout 行を Claude にイベントとして配信して、ポーリングなしで反応できるようにします。Monitor は Bash と同じパーミッションルールに従います。動作とプロバイダーの可用性については、Monitor ツールリファレンス を参照してください。

入力:

{
    "command": str,  # シェルスクリプト。各 stdout 行はイベント、終了は監視を終了
    "description": str,  # 通知に表示される短い説明
    "timeout_ms": int | None,  # この期限後に強制終了(デフォルト 300000、最大 3600000)
    "persistent": bool | None,  # セッションの期間中実行。TaskStop で停止
}

出力:

{
    "taskId": str,  # バックグラウンド監視タスクの ID
    "timeoutMs": int,  # タイムアウト期限(ミリ秒)(persistent の場合は 0)
    "persistent": bool | None,  # TaskStop またはセッション終了まで実行する場合は True
}

Edit

ツール名: Edit

入力:

{
    "file_path": str,  # 変更するファイルの絶対パス
    "old_string": str,  # 置換するテキスト
    "new_string": str,  # 置換後のテキスト
    "replace_all": bool | None,  # すべての出現を置換(デフォルト False)
}

出力:

{
    "message": str,  # 確認メッセージ
    "replacements": int,  # 実行された置換の数
    "file_path": str,  # 編集されたファイルパス
}

Read

ツール名: Read

入力:

{
    "file_path": str,  # 読み込むファイルの絶対パス
    "offset": int | None,  # 読み込みを開始する行番号
    "limit": int | None,  # 読み込む行数
}

出力(テキストファイル):

{
    "content": str,  # 行番号付きのファイル内容
    "total_lines": int,  # ファイルの総行数
    "lines_returned": int,  # 実際に返された行数
}

出力(画像):

{
    "image": str,  # Base64 エンコードされた画像データ
    "mime_type": str,  # 画像の MIME タイプ
    "file_size": int,  # ファイルサイズ(バイト)
}

Write

ツール名: Write

入力:

{
    "file_path": str,  # 書き込むファイルの絶対パス
    "content": str,  # ファイルに書き込むコンテンツ
}

出力:

{
    "message": str,  # 成功メッセージ
    "bytes_written": int,  # 書き込まれたバイト数
    "file_path": str,  # 書き込まれたファイルパス
}

Glob

ツール名: Glob

入力:

{
    "pattern": str,  # ファイルにマッチさせるグロブパターン
    "path": str | None,  # 検索するディレクトリ(デフォルトは cwd)
}

出力:

{
    "matches": list[str],  # マッチしたファイルパスの配列
    "count": int,  # 見つかったマッチの数
    "search_path": str,  # 使用された検索ディレクトリ
}

Grep

ツール名: Grep

入力:

{
    "pattern": str,  # 正規表現パターン
    "path": str | None,  # 検索するファイルまたはディレクトリ
    "glob": str | None,  # ファイルをフィルタリングするグロブパターン
    "type": str | None,  # 検索するファイルタイプ
    "output_mode": str | None,  # 「content」、「files_with_matches」、または「count」
    "-i": bool | None,  # 大文字小文字を区別しない検索
    "-n": bool | None,  # 行番号を表示
    "-B": int | None,  # 各マッチの前に表示する行
    "-A": int | None,  # 各マッチの後に表示する行
    "-C": int | None,  # 前後に表示する行
    "head_limit": int | None,  # 出力を最初の N 行/エントリに制限
    "multiline": bool | None,  # マルチラインモードを有効化
}

出力(content モード):

{
    "matches": [
        {
            "file": str,
            "line_number": int | None,
            "line": str,
            "before_context": list[str] | None,
            "after_context": list[str] | None,
        }
    ],
    "total_matches": int,
}

出力(files_with_matches モード):

{
    "files": list[str],  # マッチを含むファイル
    "count": int,  # マッチを含むファイルの数
}

NotebookEdit

ツール名: NotebookEdit

入力:

{
    "notebook_path": str,  # Jupyter ノートブックの絶対パス
    "cell_id": str | None,  # 編集するセルの ID
    "new_source": str,  # セルの新しいソース
    "cell_type": "code" | "markdown" | None,  # セルのタイプ
    "edit_mode": "replace" | "insert" | "delete" | None,  # 編集操作のタイプ
}

出力:

{
    "message": str,  # 成功メッセージ
    "edit_type": "replaced" | "inserted" | "deleted",  # 実行された編集のタイプ
    "cell_id": str | None,  # 影響を受けたセル ID
    "total_cells": int,  # 編集後のノートブックの総セル数
}

WebFetch

ツール名: WebFetch

入力:

{
    "url": str,  # コンテンツを取得する URL
    "prompt": str,  # 取得したコンテンツで実行するプロンプト
}

出力:

{
    "bytes": int,  # 取得したコンテンツのサイズ(バイト)
    "code": int,  # HTTP レスポンスコード
    "codeText": str,  # HTTP レスポンスコードテキスト
    "result": str,  # コンテンツにプロンプトを適用した処理結果
    "durationMs": int,  # コンテンツを取得して処理するのにかかった時間(ミリ秒)
    "url": str,  # 取得された URL
}

ツール名: WebSearch

入力:

{
    "query": str,  # 使用する検索クエリ
    "allowed_domains": list[str] | None,  # これらのドメインからのみ結果を含める
    "blocked_domains": list[str] | None,  # これらのドメインからの結果は決して含めない
}

出力:

{
    "query": str,  # 検索クエリ
    "results": list[str | {"tool_use_id": str, "content": list[{"title": str, "url": str}]}],
    "durationSeconds": float,  # 検索時間(秒)
}

TodoWrite

ツール名: TodoWrite

入力:

{
    "todos": [
        {
            "content": str,  # タスクの説明
            "status": "pending" | "in_progress" | "completed",  # タスクのステータス
            "activeForm": str,  # 説明のアクティブな形式
        }
    ]
}

出力:

{
    "message": str,  # 成功メッセージ
    "stats": {"total": int, "pending": int, "in_progress": int, "completed": int},
}

TaskCreate

ツール名: TaskCreate

入力:

{
    "subject": str,  # 短いタスクタイトル
    "description": str,  # 詳細なタスク本文
    "activeForm": str | None,  # 進行中に表示される現在形ラベル
    "metadata": dict | None,  # 任意の呼び出し元メタデータ
}

出力:

{
    "task": {"id": str, "subject": str},  # 割り当てられた ID を持つ作成されたタスク
}

TaskUpdate

ツール名: TaskUpdate

入力:

{
    "taskId": str,  # パッチするタスクの ID
    "status": Literal["pending", "in_progress", "completed", "deleted"] | None,
    "subject": str | None,
    "description": str | None,
    "activeForm": str | None,
    "addBlocks": list[str] | None,  # このタスクが現在ブロックするタスク ID
    "addBlockedBy": list[str] | None,  # 現在このタスクをブロックするタスク ID
    "owner": str | None,
    "metadata": dict | None,
}

出力:

{
    "success": bool,
    "taskId": str,
    "updatedFields": list[str],  # 変更されたフィールドの名前
    "error": str | None,
    "statusChange": {"from": str, "to": str} | None,
}

TaskGet

ツール名: TaskGet

入力:

{
    "taskId": str,  # 読み込むタスクの ID
}

出力:

{
    "task": {
        "id": str,
        "subject": str,
        "description": str,
        "status": Literal["pending", "in_progress", "completed"],
        "blocks": list[str],
        "blockedBy": list[str],
    } | None,  # ID が見つからない場合は None
}

TaskList

ツール名: TaskList

入力:

{}

出力:

{
    "tasks": [
        {
            "id": str,
            "subject": str,
            "status": Literal["pending", "in_progress", "completed"],
            "owner": str | None,
            "blockedBy": list[str],
        }
    ],
}

BashOutput

ツール名: BashOutput

入力:

{
    "bash_id": str,  # バックグラウンドシェルの ID
    "filter": str | None,  # 出力行をフィルタリングするオプションの正規表現
}

出力:

{
    "output": str,  # 最後のチェック以降の新しい出力
    "status": "running" | "completed" | "failed",  # 現在のシェルステータス
    "exitCode": int | None,  # 完了時の終了コード
}

KillBash

ツール名: KillBash

入力:

{
    "shell_id": str  # 強制終了するバックグラウンドシェルの ID
}

出力:

{
    "message": str,  # 成功メッセージ
    "shell_id": str,  # 強制終了されたシェルの ID
}

ExitPlanMode

ツール名: ExitPlanMode

入力:

{
    "plan": str  # ユーザーが承認するために実行するプラン
}

出力:

{
    "message": str,  # 確認メッセージ
    "approved": bool | None,  # ユーザーがプランを承認したかどうか
}

ListMcpResources

ツール名: ListMcpResources

入力:

{
    "server": str | None  # リソースをフィルタリングするオプションのサーバー名
}

出力:

{
    "resources": [
        {
            "uri": str,
            "name": str,
            "description": str | None,
            "mimeType": str | None,
            "server": str,
        }
    ],
    "total": int,
}

ReadMcpResource

ツール名: ReadMcpResource

入力:

{
    "server": str,  # MCP サーバー名
    "uri": str,  # 読み込むリソース URI
}

出力:

{
    "contents": [
        {"uri": str, "mimeType": str | None, "text": str | None, "blob": str | None}
    ],
    "server": str,
}

ClaudeSDKClient を使用した高度な機能

継続的な会話インターフェースの構築

from claude_agent_sdk import (
    ClaudeSDKClient,
    ClaudeAgentOptions,
    AssistantMessage,
    TextBlock,
)
import asyncio


class ConversationSession:
    """Maintains a single conversation session with Claude."""

    def __init__(self, options: ClaudeAgentOptions | None = None):
        self.client = ClaudeSDKClient(options)
        self.turn_count = 0

    async def start(self):
        await self.client.connect()
        print("Starting conversation session. Claude will remember context.")
        print(
            "Commands: 'exit' to quit, 'interrupt' to stop current task, 'new' for new session"
        )

        while True:
            user_input = input(f"\n[Turn {self.turn_count + 1}] You: ")

            if user_input.lower() == "exit":
                break
            elif user_input.lower() == "interrupt":
                await self.client.interrupt()
                print("Task interrupted!")
                continue
            elif user_input.lower() == "new":
                # Disconnect and reconnect for a fresh session
                await self.client.disconnect()
                await self.client.connect()
                self.turn_count = 0
                print("Started new conversation session (previous context cleared)")
                continue

            # Send message - the session retains all previous messages
            await self.client.query(user_input)
            self.turn_count += 1

            # Process response
            print(f"[Turn {self.turn_count}] Claude: ", end="")
            async for message in self.client.receive_response():
                if isinstance(message, AssistantMessage):
                    for block in message.content:
                        if isinstance(block, TextBlock):
                            print(block.text, end="")
            print()  # New line after response

        await self.client.disconnect()
        print(f"Conversation ended after {self.turn_count} turns.")


async def main():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Write", "Bash"], permission_mode="acceptEdits"
    )
    session = ConversationSession(options)
    await session.start()


# Example conversation:
# Turn 1 - You: "Create a file called hello.py"
# Turn 1 - Claude: "I'll create a hello.py file for you..."
# Turn 2 - You: "What's in that file?"
# Turn 2 - Claude: "The hello.py file I just created contains..." (remembers!)
# Turn 3 - You: "Add a main function to it"
# Turn 3 - Claude: "I'll add a main function to hello.py..." (knows which file!)

asyncio.run(main())

動作修正のための Hooks の使用

from claude_agent_sdk import (
    ClaudeSDKClient,
    ClaudeAgentOptions,
    HookMatcher,
    HookContext,
)
import asyncio
from typing import Any


async def pre_tool_logger(
    input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
) -> dict[str, Any]:
    """Log all tool usage before execution."""
    tool_name = input_data.get("tool_name", "unknown")
    print(f"[PRE-TOOL] About to use: {tool_name}")

    # You can modify or block the tool execution here
    if tool_name == "Bash" and "rm -rf" in str(input_data.get("tool_input", {})):
        return {
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": "Dangerous command blocked",
            }
        }
    return {}


async def post_tool_logger(
    input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
) -> dict[str, Any]:
    """Log results after tool execution."""
    tool_name = input_data.get("tool_name", "unknown")
    print(f"[POST-TOOL] Completed: {tool_name}")
    return {}


async def user_prompt_modifier(
    input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
) -> dict[str, Any]:
    """Add context to user prompts."""
    original_prompt = input_data.get("prompt", "")

    # Add a timestamp as additional context for Claude to see
    from datetime import datetime

    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    return {
        "hookSpecificOutput": {
            "hookEventName": "UserPromptSubmit",
            "additionalContext": f"[Submitted at {timestamp}] Original prompt: {original_prompt}",
        }
    }


async def main():
    options = ClaudeAgentOptions(
        hooks={
            "PreToolUse": [
                HookMatcher(hooks=[pre_tool_logger]),
                HookMatcher(matcher="Bash", hooks=[pre_tool_logger]),
            ],
            "PostToolUse": [HookMatcher(hooks=[post_tool_logger])],
            "UserPromptSubmit": [HookMatcher(hooks=[user_prompt_modifier])],
        },
        allowed_tools=["Read", "Write", "Bash"],
    )

    async with ClaudeSDKClient(options=options) as client:
        await client.query("List files in current directory")

        async for message in client.receive_response():
            # Hooks will automatically log tool usage
            pass


asyncio.run(main())

リアルタイム進捗監視

from claude_agent_sdk import (
    ClaudeSDKClient,
    ClaudeAgentOptions,
    AssistantMessage,
    ToolUseBlock,
    ToolResultBlock,
    TextBlock,
)
import asyncio


async def monitor_progress():
    options = ClaudeAgentOptions(
        allowed_tools=["Write", "Bash"], permission_mode="acceptEdits"
    )

    async with ClaudeSDKClient(options=options) as client:
        await client.query("Create 5 Python files with different sorting algorithms")

        # Monitor progress in real-time
        async for message in client.receive_response():
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, ToolUseBlock):
                        if block.name == "Write":
                            file_path = block.input.get("file_path", "")
                            print(f"Creating: {file_path}")
                    elif isinstance(block, ToolResultBlock):
                        print("Completed tool execution")
                    elif isinstance(block, TextBlock):
                        print(f"Claude says: {block.text[:100]}...")

        print("Task completed!")


asyncio.run(monitor_progress())

使用例

基本的なファイル操作(query を使用)

from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock
import asyncio


async def create_project():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Write", "Bash"],
        permission_mode="acceptEdits",
        cwd="/home/user/project",
    )

    async for message in query(
        prompt="Create a Python project structure with setup.py", options=options
    ):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, ToolUseBlock):
                    print(f"Using tool: {block.name}")


asyncio.run(create_project())

エラー処理

from claude_agent_sdk import query, CLINotFoundError, ProcessError, CLIJSONDecodeError

try:
    async for message in query(prompt="Hello"):
        print(message)
except CLINotFoundError:
    print(
        "Claude Code CLI not found. Try reinstalling: pip install --force-reinstall claude-agent-sdk"
    )
except ProcessError as e:
    print(f"Process failed with exit code: {e.exit_code}")
except CLIJSONDecodeError as e:
    print(f"Failed to parse response: {e}")

クライアントでのストリーミングモード

from claude_agent_sdk import ClaudeSDKClient
import asyncio


async def interactive_session():
    async with ClaudeSDKClient() as client:
        # Send initial message
        await client.query("What's the weather like?")

        # Process responses
        async for msg in client.receive_response():
            print(msg)

        # Send follow-up
        await client.query("Tell me more about that")

        # Process follow-up response
        async for msg in client.receive_response():
            print(msg)


asyncio.run(interactive_session())

ClaudeSDKClient でカスタムツールを使用する

from claude_agent_sdk import (
    ClaudeSDKClient,
    ClaudeAgentOptions,
    tool,
    create_sdk_mcp_server,
    AssistantMessage,
    TextBlock,
)
import asyncio
from typing import Any


# Define custom tools with @tool decorator
@tool("calculate", "Perform mathematical calculations", {"expression": str})
async def calculate(args: dict[str, Any]) -> dict[str, Any]:
    try:
        result = eval(args["expression"], {"__builtins__": {}})
        return {"content": [{"type": "text", "text": f"Result: {result}"}]}
    except Exception as e:
        return {
            "content": [{"type": "text", "text": f"Error: {str(e)}"}],
            "is_error": True,
        }


@tool("get_time", "Get current time", {})
async def get_time(args: dict[str, Any]) -> dict[str, Any]:
    from datetime import datetime

    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return {"content": [{"type": "text", "text": f"Current time: {current_time}"}]}


async def main():
    # Create SDK MCP server with custom tools
    my_server = create_sdk_mcp_server(
        name="utilities", version="1.0.0", tools=[calculate, get_time]
    )

    # Configure options with the server
    options = ClaudeAgentOptions(
        mcp_servers={"utils": my_server},
        allowed_tools=["mcp__utils__calculate", "mcp__utils__get_time"],
    )

    # Use ClaudeSDKClient for interactive tool usage
    async with ClaudeSDKClient(options=options) as client:
        await client.query("What's 123 * 456?")

        # Process calculation response
        async for message in client.receive_response():
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        print(f"Calculation: {block.text}")

        # Follow up with time query
        await client.query("What time is it now?")

        async for message in client.receive_response():
            if isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        print(f"Time: {block.text}")


asyncio.run(main())

サンドボックス設定

SandboxSettings

サンドボックス動作の設定。これを使用してコマンドサンドボックスを有効にし、ネットワーク制限をプログラムで設定します。

class SandboxSettings(TypedDict, total=False):
    enabled: bool
    autoAllowBashIfSandboxed: bool
    excludedCommands: list[str]
    allowUnsandboxedCommands: bool
    network: SandboxNetworkConfig
    ignoreViolations: SandboxIgnoreViolations
    enableWeakerNestedSandbox: bool
プロパティ デフォルト 説明
enabled bool False コマンド実行のサンドボックスモードを有効にします
autoAllowBashIfSandboxed bool True サンドボックスが有効な場合、bash コマンドを自動承認します
excludedCommands list[str] [] 常にサンドボックス制限をバイパスするコマンド(例:["docker"])。これらはモデルの関与なしに自動的にサンドボックスなしで実行されます
allowUnsandboxedCommands bool True モデルがサンドボックスの外でコマンドを実行するようにリクエストすることを許可します。True の場合、モデルはツール入力で dangerouslyDisableSandbox を設定でき、パーミッションシステム にフォールバックします
network SandboxNetworkConfig None ネットワーク固有のサンドボックス設定
ignoreViolations SandboxIgnoreViolations None 無視するサンドボックス違反を設定します
enableWeakerNestedSandbox bool False 互換性のためにより弱いネストされたサンドボックスを有効にします

使用例

from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings

sandbox_settings: SandboxSettings = {
    "enabled": True,
    "autoAllowBashIfSandboxed": True,
    "network": {"allowLocalBinding": True},
}

async for message in query(
    prompt="Build and test my project",
    options=ClaudeAgentOptions(sandbox=sandbox_settings),
):
    print(message)

SandboxNetworkConfig

サンドボックスモード用のネットワーク固有の設定。

class SandboxNetworkConfig(TypedDict, total=False):
    allowedDomains: list[str]
    deniedDomains: list[str]
    allowManagedDomainsOnly: bool
    allowUnixSockets: list[str]
    allowAllUnixSockets: bool
    allowLocalBinding: bool
    allowMachLookup: list[str]
    httpProxyPort: int
    socksProxyPort: int
プロパティ デフォルト 説明
allowedDomains list[str] [] サンドボックス化されたプロセスがアクセスできるドメイン名
deniedDomains list[str] [] サンドボックス化されたプロセスがアクセスできないドメイン名。allowedDomains より優先されます
allowManagedDomainsOnly bool False マネージド設定のみ:マネージド設定で設定されている場合、非マネージド設定ソースからの allowedDomains を無視します。SDK オプションで設定された場合は効果がありません
allowUnixSockets list[str] [] プロセスがアクセスできる Unix ソケットパス(例:Docker ソケット)
allowAllUnixSockets bool False すべての Unix ソケットへのアクセスを許可します
allowLocalBinding bool False プロセスがローカルポートにバインドすることを許可します(例:dev サーバー用)
allowMachLookup list[str] [] macOS のみ:許可する XPC/Mach サービス名。末尾のワイルドカードをサポートします
httpProxyPort int None ネットワークリクエスト用の HTTP プロキシポート
socksProxyPort int None ネットワークリクエスト用の SOCKS プロキシポート

SandboxIgnoreViolations

特定のサンドボックス違反を無視するための設定。

class SandboxIgnoreViolations(TypedDict, total=False):
    file: list[str]
    network: list[str]
プロパティ デフォルト 説明
file list[str] [] 違反を無視するファイルパスパターン
network list[str] [] 違反を無視するネットワークパターン

サンドボックスなしコマンドのパーミッションフォールバック

allowUnsandboxedCommands が有効な場合、モデルはツール入力で dangerouslyDisableSandbox: True を設定することでサンドボックスの外でコマンドを実行するようにリクエストできます。これらのリクエストは既存のパーミッションシステムにフォールバックします。つまり、can_use_tool ハンドラーが呼び出され、カスタム認可ロジックを実装できます。

from claude_agent_sdk import (
    query,
    ClaudeAgentOptions,
    HookMatcher,
    PermissionResultAllow,
    PermissionResultDeny,
    ToolPermissionContext,
)


async def can_use_tool(
    tool: str, input: dict, context: ToolPermissionContext
) -> PermissionResultAllow | PermissionResultDeny:
    # Check if the model is requesting to bypass the sandbox
    if tool == "Bash" and input.get("dangerouslyDisableSandbox"):
        # The model is requesting to run this command outside the sandbox
        print(f"Unsandboxed command requested: {input.get('command')}")

        if is_command_authorized(input.get("command")):
            return PermissionResultAllow()
        return PermissionResultDeny(
            message="Command not authorized for unsandboxed execution"
        )
    return PermissionResultAllow()


# Required: dummy hook keeps the stream open for can_use_tool
async def dummy_hook(input_data, tool_use_id, context):
    return {"continue_": True}


async def prompt_stream():
    yield {
        "type": "user",
        "message": {"role": "user", "content": "Deploy my application"},
    }


async def main():
    async for message in query(
        prompt=prompt_stream(),
        options=ClaudeAgentOptions(
            sandbox={
                "enabled": True,
                "allowUnsandboxedCommands": True,  # Model can request unsandboxed execution
            },
            permission_mode="default",
            can_use_tool=can_use_tool,
            hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]},
        ),
    ):
        print(message)

このパターンにより、以下が可能になります:

  • モデルリクエストを監査する:モデルがサンドボックスなし実行をリクエストするときをログします
  • 許可リストを実装する:特定のコマンドのみがサンドボックスなしで実行されることを許可します
  • 承認ワークフローを追加する:特権操作に明示的な認可を要求します

関連項目