Loading...
    • 開発者ガイド
    • APIリファレンス
    • MCP
    • リソース
    • リリースノート
    Search...
    ⌘K
    最初のステップ
    Claudeの紹介クイックスタート
    モデルと価格
    モデル概要モデルの選択Claude 4.5の新機能Claude 4.5への移行モデルの廃止予定価格
    Claudeで構築
    機能概要Messages APIの使用コンテキストウィンドウプロンプトのベストプラクティス
    機能
    プロンプトキャッシングコンテキスト編集拡張思考エフォートストリーミングメッセージバッチ処理引用多言語対応トークンカウント埋め込みビジョンPDF対応Files API検索結果構造化出力
    ツール
    概要ツール使用の実装方法細粒度ツールストリーミングBashツールコード実行ツールプログラマティックツール呼び出しコンピュータ使用ツールテキストエディタツールWebフェッチツールWeb検索ツールメモリツールツール検索ツール
    エージェントスキル
    概要クイックスタートベストプラクティスAPIでスキルを使用
    Agent SDK
    概要クイックスタートTypeScript SDKTypeScript V2(プレビュー)Python SDK移行ガイド
    APIのMCP
    MCPコネクタリモートMCPサーバー
    サードパーティプラットフォームのClaude
    Amazon BedrockMicrosoft FoundryVertex AI
    プロンプトエンジニアリング
    概要プロンプトジェネレータプロンプトテンプレートの使用プロンプト改善ツール明確で直接的に例を使用(マルチショットプロンプティング)Claudeに考えさせる(CoT)XMLタグを使用Claudeに役割を与える(システムプロンプト)Claudeの応答を事前入力複雑なプロンプトをチェーン長いコンテキストのヒント拡張思考のヒント
    テストと評価
    成功基準の定義テストケースの開発評価ツールの使用レイテンシの削減
    ガードレールの強化
    ハルシネーションの削減出力の一貫性を向上ジェイルブレイクの軽減ストリーミング拒否プロンプトリークの削減Claudeをキャラクターのままに
    管理とモニタリング
    Admin API概要使用状況とコストAPIClaude Code Analytics API
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    Agent SDK

    Agent SDK reference - Python

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

    インストール

    pip install claude-agent-sdk

    query() と ClaudeSDKClient の選択

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

    クイック比較

    機能query()ClaudeSDKClient
    セッション毎回新しいセッションを作成同じセッションを再利用
    会話単一の交換同じコンテキスト内での複数の交換
    接続自動的に管理手動制御
    ストリーミング入力
    • query() と ClaudeSDKClient の選択
    • query() を使用する場合(毎回新しいセッション)
    • ClaudeSDKClient を使用する場合(継続的な会話)
    • query()
    • tool()
    • create_sdk_mcp_server()
    • ClaudeSDKClient
    • SdkMcpTool
    • ClaudeAgentOptions
    • OutputFormat
    • SystemPromptPreset
    • SettingSource
    • AgentDefinition
    • PermissionMode
    • McpSdkServerConfig
    • McpServerConfig
    • SdkPluginConfig
    • Message
    • UserMessage
    • AssistantMessage
    • SystemMessage
    • ResultMessage
    • ContentBlock
    • TextBlock
    • ThinkingBlock
    • ToolUseBlock
    • ToolResultBlock
    • ClaudeSDKError
    • CLINotFoundError
    • CLIConnectionError
    • ProcessError
    • CLIJSONDecodeError
    • HookEvent
    • HookCallback
    • HookContext
    • HookMatcher
    • Task
    • Bash
    • Edit
    • Read
    • Write
    • Glob
    • Grep
    • NotebookEdit
    • WebFetch
    • WebSearch
    • TodoWrite
    • BashOutput
    • KillBash
    • ExitPlanMode
    • ListMcpResources
    • ReadMcpResource
    • ClaudeSDKClientを使用した高度な機能
    • 基本的なファイル操作(queryを使用)
    • ClaudeSDKClientでカスタムツールを使用
    • SandboxSettings
    • SandboxNetworkConfig
    • SandboxIgnoreViolations
    ✅ サポート
    ✅ サポート
    割り込み❌ サポートなし✅ サポート
    フック❌ サポートなし✅ サポート
    カスタムツール❌ サポートなし✅ サポート
    チャット続行❌ 毎回新しいセッション✅ 会話を維持
    ユースケース1回限りのタスク継続的な会話

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

    最適な用途:

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

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

    最適な用途:

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

    関数

    query()

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

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

    パラメータ

    パラメータ型説明
    promptstr | AsyncIterable[dict]文字列またはストリーミングモード用の非同期イテレータとしての入力プロンプト
    optionsClaudeAgentOptions | Noneオプションの設定オブジェクト(Noneの場合は ClaudeAgentOptions() がデフォルト)

    戻り値

    会話からのメッセージを生成する 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]
    ) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]]

    パラメータ

    パラメータ型説明
    namestrツールの一意の識別子
    descriptionstrツールが何をするかの人間が読める説明
    input_schematype | dict[str, Any]ツールの入力パラメータを定義するスキーマ(以下を参照)

    入力スキーマオプション

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

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

      {
          "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']}!"
            }]
        }

    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

    パラメータ

    パラメータ型デフォルト説明
    namestr-サーバーの一意の識別子
    versionstr"1.0.0"サーバーバージョン文字列
    toolslist[SdkMcpTool[Any]] | NoneNone@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"]
    )

    クラス

    ClaudeSDKClient

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

    主な機能

    • セッション継続性: 複数の query() 呼び出しにわたって会話コンテキストを維持
    • 同じ会話: Claudeはセッション内の前のメッセージを記憶
    • 割り込みサポート: Claudeの実行中に停止できます
    • 明示的なライフサイクル: セッションの開始と終了を制御
    • 応答駆動フロー: 応答に反応してフォローアップを送信できます
    • カスタムツールとフック: カスタムツール(@tool デコレータで作成)とフックをサポート
    class ClaudeSDKClient:
        def __init__(self, options: ClaudeAgentOptions | 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 rewind_files(self, user_message_uuid: str) -> None
        async def disconnect(self) -> None

    メソッド

    メソッド説明
    __init__(options)オプションの設定でクライアントを初期化
    connect(prompt)オプションの初期プロンプトまたはメッセージストリームでClaudeに接続
    query(prompt, session_id)ストリーミングモードで新しいリクエストを送信
    receive_messages()Claudeからのすべてのメッセージを非同期イテレータとして受信
    receive_response()ResultMessageを含むまでのメッセージを受信
    interrupt()割り込み信号を送信(ストリーミングモードでのみ機能)
    rewind_files(user_message_uuid)ファイルを指定されたユーザーメッセージの状態に復元します。enable_file_checkpointing=True が必要です。ファイルチェックポイント を参照
    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 - Claude remembers 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": "text", "text": "Analyze the following data:"}
        await asyncio.sleep(0.5)
        yield {"type": "text", "text": "Temperature: 25°C"}
        await asyncio.sleep(0.5)
        yield {"type": "text", "text": "Humidity: 60%"}
        await asyncio.sleep(0.5)
        yield {"type": "text", "text": "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
    
    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")
    
            # Let it run for a bit
            await asyncio.sleep(2)
    
            # Interrupt the task
            await client.interrupt()
            print("Task interrupted!")
    
            # Send a new command
            await client.query("Just say hello instead")
    
            async for message in client.receive_response():
                # Process the new response
                pass
    
    asyncio.run(interruptible_task())

    例 - 高度な権限制御

    from claude_agent_sdk import (
        ClaudeSDKClient,
        ClaudeAgentOptions
    )
    
    async def custom_permission_handler(
        tool_name: str,
        input_data: dict,
        context: dict
    ):
        """Custom logic for tool permissions."""
    
        # Block writes to system directories
        if tool_name == "Write" and input_data.get("file_path", "").startswith("/system/"):
            return {
                "behavior": "deny",
                "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 {
                "behavior": "allow",
                "updatedInput": {**input_data, "file_path": safe_path}
            }
    
        # Allow everything else
        return {
            "behavior": "allow",
            "updatedInput": 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]]]
    プロパティ型説明
    namestrツールの一意の識別子
    descriptionstr人間が読める説明
    input_schematype[T] | dict[str, Any]入力検証用のスキーマ
    handlerCallable[[T], Awaitable[dict[str, Any]]]ツール実行を処理する非同期関数

    ClaudeAgentOptions

    Claude Codeクエリの設定データクラス。

    @dataclass
    class ClaudeAgentOptions:
        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)
        permission_mode: PermissionMode | None = None
        continue_conversation: bool = False
        resume: str | None = None
        max_turns: int | None = None
        disallowed_tools: list[str] = field(default_factory=list)
        model: str | None = None
        output_format: OutputFormat | None = None
        permission_prompt_tool_name: str | None = None
        cwd: 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
        fork_session: bool = False
        agents: dict[str, AgentDefinition] | None = None
        setting_sources: list[SettingSource] | None = None
    プロパティ型デフォルト説明
    allowed_toolslist[str][]許可されたツール名のリスト
    system_promptstr | SystemPromptPreset | NoneNoneシステムプロンプト設定。カスタムプロンプト用に文字列を渡すか、Claude Codeのシステムプロンプト用に {"type": "preset", "preset": "claude_code"} を使用します。プリセットを拡張するために "append" を追加
    mcp_serversdict[str, McpServerConfig] | str | Path{}MCPサーバー設定または設定ファイルへのパス
    permission_modePermissionMode | NoneNoneツール使用の権限モード
    continue_conversationboolFalse最新の会話を続ける
    resumestr | NoneNone再開するセッションID
    max_turnsint | NoneNone最大会話ターン数
    disallowed_toolslist[str][]許可されていないツール名のリスト
    enable_file_checkpointingboolFalseファイル変更追跡を有効にして巻き戻します。ファイルチェックポイント を参照
    modelstr | NoneNone使用するClaudeモデル
    output_formatOutputFormat | NoneNoneエージェント結果の出力形式を定義します。詳細は 構造化出力 を参照
    permission_prompt_tool_namestr | NoneNone権限プロンプト用のMCPツール名
    cwdstr | Path | NoneNone現在の作業ディレクトリ
    settingsstr | NoneNone設定ファイルへのパス
    add_dirslist[str | Path][]Claudeがアクセスできる追加ディレクトリ
    envdict[str, str]{}環境変数
    extra_argsdict[str, str | None]{}CLIに直接渡す追加のCLI引数
    max_buffer_sizeint | NoneNoneCLI stdoutをバッファリングする場合の最大バイト数
    debug_stderrAnysys.stderr廃止予定 - デバッグ出力用のファイルのようなオブジェクト。代わりに stderr コールバックを使用
    stderrCallable[[str], None] | NoneNoneCLIからのstderr出力用のコールバック関数
    can_use_toolCanUseTool | NoneNoneツール権限コールバック関数
    hooksdict[HookEvent, list[HookMatcher]] | NoneNoneイベント傍受用のフック設定
    userstr | NoneNoneユーザー識別子
    include_partial_messagesboolFalse部分的なメッセージストリーミングイベントを含める
    fork_sessionboolFalseresume で再開する場合、元のセッションを続ける代わりに新しいセッションIDにフォークします
    agentsdict[str, AgentDefinition] | NoneNoneプログラムで定義されたサブエージェント
    pluginslist[SdkPluginConfig][]ローカルパスからカスタムプラグインを読み込みます。詳細は プラグイン を参照
    sandboxSandboxSettings | NoneNoneサンドボックス動作をプログラムで設定します。詳細は サンドボックス設定 を参照
    setting_sourceslist[SettingSource] | NoneNone(設定なし)どのファイルシステム設定を読み込むかを制御します。省略した場合、設定は読み込まれません。注: CLAUDE.mdファイルを読み込むには "project" を含める必要があります

    OutputFormat

    構造化出力検証の設定。

    class OutputFormat(TypedDict):
        type: Literal["json_schema"]
        schema: dict[str, Any]
    フィールド必須説明
    typeはいJSON Schema検証の場合は "json_schema" である必要があります
    schemaはい出力検証用のJSON Schema定義

    SystemPromptPreset

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

    class SystemPromptPreset(TypedDict):
        type: Literal["preset"]
        preset: Literal["claude_code"]
        append: NotRequired[str]
    フィールド必須説明
    typeはいプリセットシステムプロンプトを使用するには "preset" である必要があります
    presetはいClaude Codeのシステムプロンプトを使用するには "claude_code" である必要があります
    appendいいえプリセットシステムプロンプトに追加する追加の指示

    SettingSource

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

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

    デフォルト動作

    setting_sources が 省略 または None の場合、SDKはファイルシステム設定を 読み込みません。これはSDKアプリケーションの分離を提供します。

    setting_sources を使用する理由

    すべてのファイルシステム設定を読み込む(レガシー動作):

    # SDK v0.0.x のようにすべての設定を読み込む
    from claude_agent_sdk import query, ClaudeAgentOptions
    
    async for message in query(
        prompt="Analyze this code",
        options=ClaudeAgentOptions(
            setting_sources=["user", "project", "local"]  # Load all settings
        )
    ):
        print(message)

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

    # プロジェクト設定のみを読み込み、ユーザーとローカルを無視
    async for message in query(
        prompt="Run CI checks",
        options=ClaudeAgentOptions(
            setting_sources=["project"]  # Only .claude/settings.json
        )
    ):
        print(message)

    テストとCI環境:

    # ローカル設定を除外してCI内で一貫した動作を確保
    async for message in query(
        prompt="Run tests",
        options=ClaudeAgentOptions(
            setting_sources=["project"],  # Only team-shared settings
            permission_mode="bypassPermissions"
        )
    ):
        print(message)

    SDK専用アプリケーション:

    # すべてをプログラムで定義(デフォルト動作)
    # ファイルシステムの依存関係なし - setting_sources はデフォルトで None
    async for message in query(
        prompt="Review this PR",
        options=ClaudeAgentOptions(
            # setting_sources=None is the default, no need to specify
            agents={ /* ... */ },
            mcp_servers={ /* ... */ },
            allowed_tools=["Read", "Grep", "Glob"]
        )
    ):
        print(message)

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

    # プロジェクト設定を読み込んでプロジェクトからCLAUDE.mdファイルを含める
    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"],  # Required to load CLAUDE.md from project
            allowed_tools=["Read", "Write", "Edit"]
        )
    ):
        print(message)

    設定の優先順位

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

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

    プログラマティックオプション(agents、allowed_tools など)は常にファイルシステム設定をオーバーライドします。

    AgentDefinition

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

    @dataclass
    class AgentDefinition:
        description: str
        prompt: str
        tools: list[str] | None = None
        model: Literal["sonnet", "opus", "haiku", "inherit"] | None = None
    フィールド必須説明
    descriptionはいこのエージェントを使用する場合の自然言語説明
    toolsいいえ許可されたツール名の配列。省略した場合、すべてのツールを継承
    promptはいエージェントのシステムプロンプト
    modelいいえこのエージェント用のモデルオーバーライド。省略した場合、メインモデルを使用

    PermissionMode

    ツール実行を制御するための権限モード。

    PermissionMode = Literal[
        "default",           # Standard permission behavior
        "acceptEdits",       # Auto-accept file edits
        "plan",              # Planning mode - no execution
        "bypassPermissions"  # Bypass all permission checks (use with caution)
    ]

    McpSdkServerConfig

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

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

    McpServerConfig

    MCPサーバー設定の共用体型。

    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]]

    SdkPluginConfig

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

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

    例:

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

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

    メッセージ型

    Message

    すべての可能なメッセージの共用体型。

    Message = UserMessage | AssistantMessage | SystemMessage | ResultMessage

    UserMessage

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

    @dataclass
    class UserMessage:
        content: str | list[ContentBlock]

    AssistantMessage

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

    @dataclass
    class AssistantMessage:
        content: list[ContentBlock]
        model: str

    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
        total_cost_usd: float | None = None
        usage: dict[str, Any] | None = None
        result: str | None = None

    コンテンツブロックタイプ

    ContentBlock

    すべてのコンテンツブロックの共用体型。

    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):
        """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: エラーメッセージ(デフォルト: "Claude Code not found")
                cli_path: 見つからなかったCLIへのオプションパス
            """

    CLIConnectionError

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

    class CLIConnectionError(ClaudeSDKError):
        """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: パースに失敗した行
                original_error: 元のJSONデコード例外
            """
            self.line = line
            self.original_error = original_error

    フックタイプ

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

    HookEvent

    サポートされているフックイベントタイプ。セットアップの制限により、Python SDKはSessionStart、SessionEnd、およびNotificationフックをサポートしていません。

    HookEvent = Literal[
        "PreToolUse",      # ツール実行前に呼び出される
        "PostToolUse",     # ツール実行後に呼び出される
        "UserPromptSubmit", # ユーザーがプロンプトを送信したときに呼び出される
        "Stop",            # 実行を停止するときに呼び出される
        "SubagentStop",    # サブエージェントが停止したときに呼び出される
        "PreCompact"       # メッセージコンパクト前に呼び出される
    ]

    HookCallback

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

    HookCallback = Callable[
        [dict[str, Any], str | None, HookContext],
        Awaitable[dict[str, Any]]
    ]

    パラメータ:

    • input_data: フック固有の入力データ(フックガイドを参照)
    • tool_use_id: オプションのツール使用識別子(ツール関連フック用)
    • context: 追加情報を含むフックコンテキスト

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

    • decision: アクションをブロックするには"block"
    • systemMessage: トランスクリプトに追加するシステムメッセージ
    • hookSpecificOutput: フック固有の出力データ

    HookContext

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

    @dataclass
    class HookContext:
        signal: Any | None = None  # 将来: 中止シグナルサポート

    HookMatcher

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

    @dataclass
    class HookMatcher:
        matcher: str | None = None        # マッチするツール名またはパターン(例:"Bash"、"Write|Edit")
        hooks: list[HookCallback] = field(default_factory=list)  # 実行するコールバックのリスト
        timeout: float | None = None        # このマッチャーのすべてのフックのタイムアウト(秒単位)(デフォルト: 60)

    フック使用例

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

    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]:
        """危険なbashコマンドを検証し、ブロックする可能性があります。"""
        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]:
        """監査のためにすべてのツール使用をログします。"""
        print(f"Tool used: {input_data.get('tool_name')}")
        return {}
    
    options = ClaudeAgentOptions(
        hooks={
            'PreToolUse': [
                HookMatcher(matcher='Bash', hooks=[validate_bash_command], timeout=120),  # 検証用2分
                HookMatcher(hooks=[log_tool_use])  # すべてのツールに適用(デフォルト60秒タイムアウト)
            ],
            'PostToolUse': [
                HookMatcher(hooks=[log_tool_use])
            ]
        }
    )
    
    async for message in query(
        prompt="Analyze this codebase",
        options=options
    ):
        print(message)

    ツール入出力タイプ

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

    Task

    ツール名: 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         # ミリ秒単位の実行時間
    }

    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
    }

    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,       # ファイルをマッチングするglobパターン
        "path": str | None    # 検索するディレクトリ(デフォルトはcwd)
    }

    出力:

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

    Grep

    ツール名: Grep

    入力:

    {
        "pattern": str,                    # 正規表現パターン
        "path": str | None,                # 検索するファイルまたはディレクトリ
        "glob": str | None,                # ファイルをフィルタリングするglobパターン
        "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   # 取得したコンテンツで実行するプロンプト
    }

    出力:

    {
        "response": str,           # プロンプトに対するAIモデルの応答
        "url": str,                # 取得されたURL
        "final_url": str | None,   # リダイレクト後の最終URL
        "status_code": int | None  # HTTPステータスコード
    }

    WebSearch

    ツール名: WebSearch

    入力:

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

    出力:

    {
        "results": [
            {
                "title": str,
                "url": str,
                "snippet": str,
                "metadata": dict | None
            }
        ],
        "total_results": int,
        "query": str
    }

    TodoWrite

    ツール名: TodoWrite

    入力:

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

    出力:

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

    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:
        """Claudeとの単一の会話セッションを維持します。"""
    
        def __init__(self, options: ClaudeAgentOptions = 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':
                    # 新しいセッションのために切断して再接続
                    await self.client.disconnect()
                    await self.client.connect()
                    self.turn_count = 0
                    print("Started new conversation session (previous context cleared)")
                    continue
    
                # メッセージを送信 - Claudeはこのセッション内のすべての前のメッセージを覚えています
                await self.client.query(user_input)
                self.turn_count += 1
    
                # 応答を処理
                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()  # 応答後の新しい行
    
            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()
    
    # 会話例:
    # 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..." (覚えている!)
    # Turn 3 - You: "Add a main function to it"
    # Turn 3 - Claude: "I'll add a main function to hello.py..." (どのファイルかわかっている!)
    
    asyncio.run(main())

    動作修正のためのフックの使用

    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]:
        """実行前にすべてのツール使用をログします。"""
        tool_name = input_data.get('tool_name', 'unknown')
        print(f"[PRE-TOOL] About to use: {tool_name}")
    
        # ここでツール実行を修正またはブロックできます
        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]:
        """ツール実行後に結果をログします。"""
        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]:
        """ユーザープロンプトにコンテキストを追加します。"""
        original_prompt = input_data.get('prompt', '')
    
        # すべてのプロンプトにタイムスタンプを追加
        from datetime import datetime
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
        return {
            'hookSpecificOutput': {
                'hookEventName': 'UserPromptSubmit',
                'updatedPrompt': f"[{timestamp}] {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():
                # フックは自動的にツール使用をログします
                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"
            )
    
            # リアルタイムで進捗を監視
            files_created = []
            async for message in client.receive_messages():
                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(f"✅ Completed tool execution")
                        elif isinstance(block, TextBlock):
                            print(f"💭 Claude says: {block.text[:100]}...")
    
                # 最終結果を受け取ったかどうかを確認
                if hasattr(message, 'subtype') and message.subtype in ['success', 'error']:
                    print(f"\n🎯 Task completed!")
                    break
    
    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("Please install Claude Code: npm install -g @anthropic-ai/claude-code")
    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:
            # 初期メッセージを送信
            await client.query("What's the weather like?")
    
            # 応答を処理
            async for msg in client.receive_response():
                print(msg)
    
            # フォローアップを送信
            await client.query("Tell me more about that")
    
            # フォローアップ応答を処理
            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
    
    # @toolデコレータでカスタムツールを定義
    @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():
        # カスタムツールを使用してSDK MCPサーバーを作成
        my_server = create_sdk_mcp_server(
            name="utilities",
            version="1.0.0",
            tools=[calculate, get_time]
        )
    
        # サーバーを使用してオプションを設定
        options = ClaudeAgentOptions(
            mcp_servers={"utils": my_server},
            allowed_tools=[
                "mcp__utils__calculate",
                "mcp__utils__get_time"
            ]
        )
    
        # インタラクティブなツール使用のためにClaudeSDKClientを使用
        async with ClaudeSDKClient(options=options) as client:
            await client.query("What's 123 * 456?")
    
            # 計算応答を処理
            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}")
    
            # 時刻クエリでフォローアップ
            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
    プロパティ型デフォルト説明
    enabledboolFalseコマンド実行のサンドボックスモードを有効化
    autoAllowBashIfSandboxedboolFalseサンドボックスが有効な場合、bashコマンドを自動承認
    excludedCommandslist[str][]常にサンドボックス制限をバイパスするコマンド(例:["docker"])。これらはモデルの関与なしに自動的にサンドボックス外で実行されます
    allowUnsandboxedCommandsboolFalseモデルがサンドボックス外でコマンドを実行するようリクエストすることを許可。Trueの場合、モデルはツール入力でdangerouslyDisableSandboxを設定でき、これはパーミッションシステムにフォールバックします
    networkSandboxNetworkConfigNoneネットワーク固有のサンドボックス設定
    ignoreViolationsSandboxIgnoreViolationsNone無視するサンドボックス違反を設定
    enableWeakerNestedSandboxboolFalse互換性のための弱いネストされたサンドボックスを有効化

    ファイルシステムとネットワークアクセス制限はサンドボックス設定では設定されません。代わりに、パーミッションルールから派生します:

    • ファイルシステム読み取り制限: 読み取り拒否ルール
    • ファイルシステム書き込み制限: 編集許可/拒否ルール
    • ネットワーク制限: WebFetch許可/拒否ルール

    コマンド実行サンドボックスにはサンドボックス設定を使用し、ファイルシステムとネットワークアクセス制御にはパーミッションルールを使用します。

    使用例

    from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings
    
    sandbox_settings: SandboxSettings = {
        "enabled": True,
        "autoAllowBashIfSandboxed": True,
        "excludedCommands": ["docker"],
        "network": {
            "allowLocalBinding": True,
            "allowUnixSockets": ["/var/run/docker.sock"]
        }
    }
    
    async for message in query(
        prompt="Build and test my project",
        options=ClaudeAgentOptions(sandbox=sandbox_settings)
    ):
        print(message)

    SandboxNetworkConfig

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

    class SandboxNetworkConfig(TypedDict, total=False):
        allowLocalBinding: bool
        allowUnixSockets: list[str]
        allowAllUnixSockets: bool
        httpProxyPort: int
        socksProxyPort: int
    プロパティ型デフォルト説明
    allowLocalBindingboolFalseプロセスがローカルポートにバインドすることを許可(例:開発サーバー用)
    allowUnixSocketslist[str][]プロセスがアクセスできるUnixソケットパス(例:Dockerソケット)
    allowAllUnixSocketsboolFalseすべてのUnixソケットへのアクセスを許可
    httpProxyPortintNoneネットワークリクエスト用のHTTPプロキシポート
    socksProxyPortintNoneネットワークリクエスト用のSOCKSプロキシポート

    SandboxIgnoreViolations

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

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

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

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

    excludedCommands vs allowUnsandboxedCommands:

    • excludedCommands: 常に自動的にサンドボックスをバイパスするコマンドの静的リスト(例:["docker"])。モデルはこれを制御できません。
    • allowUnsandboxedCommands: モデルが実行時にツール入力でdangerouslyDisableSandbox: Trueを設定することでサンドボックス外実行をリクエストするかどうかを決定できます。
    from claude_agent_sdk import query, ClaudeAgentOptions
    
    async def can_use_tool(tool: str, input: dict) -> bool:
        # モデルがサンドボックスをバイパスするようリクエストしているかを確認
        if tool == "Bash" and input.get("dangerouslyDisableSandbox"):
            # モデルはこのコマンドをサンドボックス外で実行したい
            print(f"Unsandboxed command requested: {input.get('command')}")
    
            # 許可する場合はTrue、拒否する場合はFalseを返す
            return is_command_authorized(input.get("command"))
        return True
    
    async def main():
        async for message in query(
            prompt="Deploy my application",
            options=ClaudeAgentOptions(
                sandbox={
                    "enabled": True,
                    "allowUnsandboxedCommands": True  # モデルはサンドボックス外実行をリクエストできます
                },
                permission_mode="default",
                can_use_tool=can_use_tool
            )
        ):
            print(message)

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

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

    dangerouslyDisableSandbox: Trueで実行されるコマンドはシステム全体へのアクセスを持ちます。can_use_toolハンドラがこれらのリクエストを慎重に検証することを確認してください。

    関連項目

    • Python SDKガイド - チュートリアルと例
    • SDKの概要 - 一般的なSDKコンセプト
    • TypeScript SDKリファレンス - TypeScript SDKドキュメント
    • CLIリファレンス - コマンドラインインターフェース
    • 一般的なワークフロー - ステップバイステップガイド