Loading...
    • 開発者ガイド
    • API リファレンス
    • MCP
    • リソース
    • リリースノート
    Search...
    ⌘K
    はじめに
    Claude の紹介クイックスタート
    モデルと料金
    モデル概要モデルの選び方Claude 4.6 の新機能移行ガイドモデルの廃止料金
    Claude で構築する
    機能概要Messages API の使用停止理由の処理プロンプトのベストプラクティス
    コンテキスト管理
    コンテキストウィンドウコンパクションコンテキスト編集
    機能
    プロンプトキャッシング拡張思考適応型思考エフォートメッセージのストリーミングバッチ処理引用多言語サポートトークンカウントエンベディングビジョンPDF サポートFiles API検索結果構造化出力
    ツール
    概要ツール使用の実装方法きめ細かいツールストリーミングBash ツールコード実行ツールプログラムによるツール呼び出しコンピュータ使用ツールテキストエディタツールWeb フェッチツールWeb 検索ツールメモリツールツール検索ツール
    Agent Skills
    概要クイックスタートベストプラクティスエンタープライズ向け SkillsAPI での Skills の使用
    Agent SDK
    概要クイックスタートTypeScript SDKTypeScript V2(プレビュー)Python SDK移行ガイド
    API での MCP
    MCP コネクタリモート MCP サーバー
    サードパーティプラットフォームの Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    プロンプトエンジニアリング
    概要プロンプトジェネレータープロンプトテンプレートの使用プロンプト改善ツール明確かつ直接的に例を使う(マルチショットプロンプティング)Claude に考えさせる(CoT)XML タグを使うClaude に役割を与える(システムプロンプト)複雑なプロンプトを連鎖させる長文コンテキストのヒント拡張思考のヒント
    テストと評価
    成功基準の定義テストケースの開発評価ツールの使用レイテンシの削減
    ガードレールの強化
    ハルシネーションの削減出力の一貫性を高めるジェイルブレイクの軽減ストリーミング拒否プロンプト漏洩の防止Claude をキャラクターに保つ
    管理とモニタリング
    Admin API 概要データレジデンシーワークスペースUsage and Cost 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リファレンス - TypeScript

    TypeScript Agent SDKの完全なAPIリファレンス。すべての関数、型、インターフェースを含みます。

    新しいV2インターフェース(プレビュー)をお試しください: send() と receive() パターンを備えた簡素化されたインターフェースが利用可能になり、マルチターン会話がより簡単になりました。TypeScript V2プレビューの詳細

    インストール

    npm install @anthropic-ai/claude-agent-sdk

    関数

    query()

    Claude Codeとやり取りするための主要な関数です。メッセージが到着するたびにストリーミングする非同期ジェネレーターを作成します。

    function query({
      prompt,
      options
    }: {
      prompt: string | AsyncIterable<SDKUserMessage>;
      options?: Options;
    }): Query

    パラメーター

    パラメーター型説明
    promptstring | AsyncIterable<SDKUserMessage>文字列としての入力プロンプト、またはストリーミングモード用の非同期イテラブル
    optionsOptionsオプションの設定オブジェクト(以下のOptions型を参照)

    戻り値

    追加メソッドを持つ AsyncGenerator<SDKMessage, void> を拡張した Query オブジェクトを返します。

    tool()

    SDK MCPサーバーで使用するための型安全なMCPツール定義を作成します。

    function tool<Schema extends ZodRawShape>(
      name: string,
      description: string,
      inputSchema: Schema,
      handler: (args: z.infer<ZodObject<Schema>>, extra: unknown) => Promise<CallToolResult>
    ): SdkMcpToolDefinition<Schema>

    パラメーター

    パラメーター型説明
    namestringツールの名前
    descriptionstringツールの機能の説明
    inputSchemaSchema extends ZodRawShapeツールの入力パラメーターを定義するZodスキーマ
    handler(args, extra) => Promise<CallToolResult>ツールのロジックを実行する非同期関数

    createSdkMcpServer()

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

    function createSdkMcpServer(options: {
      name: string;
      version?: string;
      tools?: Array<SdkMcpToolDefinition<any>>;
    }): McpSdkServerConfigWithInstance

    パラメーター

    パラメーター型説明
    options.namestringMCPサーバーの名前
    options.versionstringオプションのバージョン文字列
    options.toolsArray<SdkMcpToolDefinition>tool() で作成されたツール定義の配列

    型

    Options

    query() 関数の設定オブジェクト。

    プロパティ型デフォルト説明
    abortControllerAbortControllernew AbortController()操作をキャンセルするためのコントローラー
    additionalDirectoriesstring[][]Claudeがアクセスできる追加ディレクトリ
    agentsRecord<string, [AgentDefinition](#agentdefinition)>undefinedプログラムでサブエージェントを定義
    allowDangerouslySkipPermissionsbooleanfalseパーミッションのバイパスを有効にする。permissionMode: 'bypassPermissions' 使用時に必須
    allowedToolsstring[]全ツール許可されたツール名のリスト
    betasSdkBeta[][]ベータ機能を有効にする(例:['context-1m-2025-08-07'])
    canUseToolCanUseToolundefinedツール使用のカスタムパーミッション関数
    continuebooleanfalse最新の会話を続行
    cwdstringprocess.cwd()現在の作業ディレクトリ
    disallowedToolsstring[][]禁止されたツール名のリスト
    enableFileCheckpointingbooleanfalse巻き戻し用のファイル変更追跡を有効にする。ファイルチェックポイントを参照
    envDict<string>process.env環境変数
    executable'bun' | 'deno' | 'node'自動検出使用するJavaScriptランタイム
    executableArgsstring[][]実行ファイルに渡す引数
    extraArgsRecord<string, string | null>{}追加の引数
    fallbackModelstringundefinedプライマリが失敗した場合に使用するモデル
    forkSessionbooleanfalseresume で再開する際、元のセッションを続行する代わりに新しいセッションIDにフォークする
    hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>{}イベント用のフックコールバック
    includePartialMessagesbooleanfalse部分メッセージイベントを含める
    maxBudgetUsdnumberundefinedクエリの最大予算(USD)
    maxThinkingTokensnumberundefined思考プロセスの最大トークン数
    maxTurnsnumberundefined最大会話ターン数
    mcpServersRecord<string, [McpServerConfig](#mcpserverconfig)>{}MCPサーバーの設定
    modelstringCLIのデフォルト使用するClaudeモデル
    outputFormat{ type: 'json_schema', schema: JSONSchema }undefinedエージェント結果の出力フォーマットを定義。詳細は構造化出力を参照
    pathToClaudeCodeExecutablestring組み込み実行ファイルを使用Claude Code実行ファイルへのパス
    permissionModePermissionMode'default'セッションのパーミッションモード
    permissionPromptToolNamestringundefinedパーミッションプロンプト用のMCPツール名
    pluginsSdkPluginConfig[][]ローカルパスからカスタムプラグインを読み込む。詳細はプラグインを参照
    resumestringundefined再開するセッションID
    resumeSessionAtstringundefined特定のメッセージUUIDでセッションを再開
    sandboxSandboxSettingsundefinedサンドボックスの動作をプログラムで設定。詳細はサンドボックス設定を参照
    settingSourcesSettingSource[][](設定なし)読み込むファイルシステム設定を制御。省略時は設定は読み込まれません。注意: CLAUDE.mdファイルを読み込むには 'project' を含める必要があります
    stderr(data: string) => voidundefinedstderr出力のコールバック
    strictMcpConfigbooleanfalse厳密なMCPバリデーションを強制
    systemPromptstring | { type: 'preset'; preset: 'claude_code'; append?: string }undefined(最小限のプロンプト)システムプロンプトの設定。カスタムプロンプトには文字列を渡すか、Claude Codeのシステムプロンプトを使用するには { type: 'preset', preset: 'claude_code' } を使用。プリセットオブジェクト形式を使用する場合、append を追加して追加の指示でシステムプロンプトを拡張可能
    toolsstring[] | { type: 'preset'; preset: 'claude_code' }undefinedツールの設定。ツール名の配列を渡すか、プリセットを使用してClaude Codeのデフォルトツールを取得

    Query

    query() 関数が返すインターフェース。

    interface Query extends AsyncGenerator<SDKMessage, void> {
      interrupt(): Promise<void>;
      rewindFiles(userMessageUuid: string): Promise<void>;
      setPermissionMode(mode: PermissionMode): Promise<void>;
      setModel(model?: string): Promise<void>;
      setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;
      supportedCommands(): Promise<SlashCommand[]>;
      supportedModels(): Promise<ModelInfo[]>;
      mcpServerStatus(): Promise<McpServerStatus[]>;
      accountInfo(): Promise<AccountInfo>;
    }

    メソッド

    メソッド説明
    interrupt()クエリを中断する(ストリーミング入力モードでのみ利用可能)
    rewindFiles(userMessageUuid)指定されたユーザーメッセージ時点の状態にファイルを復元する。enableFileCheckpointing: true が必要。ファイルチェックポイントを参照
    setPermissionMode()パーミッションモードを変更する(ストリーミング入力モードでのみ利用可能)
    setModel()モデルを変更する(ストリーミング入力モードでのみ利用可能)
    setMaxThinkingTokens()最大思考トークン数を変更する(ストリーミング入力モードでのみ利用可能)
    supportedCommands()利用可能なスラッシュコマンドを返す
    supportedModels()表示情報付きの利用可能なモデルを返す
    mcpServerStatus()接続されたMCPサーバーのステータスを返す
    accountInfo()アカウント情報を返す

    AgentDefinition

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

    type AgentDefinition = {
      description: string;
      tools?: string[];
      prompt: string;
      model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
    }
    フィールド必須説明
    descriptionはいこのエージェントをいつ使用するかの自然言語による説明
    toolsいいえ許可されたツール名の配列。省略時はすべてのツールを継承
    promptはいエージェントのシステムプロンプト
    modelいいえこのエージェントのモデルオーバーライド。省略時はメインモデルを使用

    SettingSource

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

    type SettingSource = 'user' | 'project' | 'local';
    値説明場所
    'user'グローバルユーザー設定~/.claude/settings.json
    'project'共有プロジェクト設定(バージョン管理対象).claude/settings.json
    'local'ローカルプロジェクト設定(gitignore対象).claude/settings.local.json

    デフォルトの動作

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

    settingSourcesを使用する理由

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

    // SDK v0.0.xと同様にすべての設定を読み込む
    const result = query({
      prompt: "Analyze this code",
      options: {
        settingSources: ['user', 'project', 'local']  // すべての設定を読み込む
      }
    });

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

    // プロジェクト設定のみを読み込み、ユーザーとローカルは無視
    const result = query({
      prompt: "Run CI checks",
      options: {
        settingSources: ['project']  // .claude/settings.jsonのみ
      }
    });

    テストおよびCI環境:

    // ローカル設定を除外してCIでの一貫した動作を確保
    const result = query({
      prompt: "Run tests",
      options: {
        settingSources: ['project'],  // チーム共有設定のみ
        permissionMode: 'bypassPermissions'
      }
    });

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

    // すべてをプログラムで定義(デフォルトの動作)
    // ファイルシステム依存なし - settingSourcesのデフォルトは[]
    const result = query({
      prompt: "Review this PR",
      options: {
        // settingSources: [] がデフォルト、指定不要
        agents: { /* ... */ },
        mcpServers: { /* ... */ },
        allowedTools: ['Read', 'Grep', 'Glob']
      }
    });

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

    // CLAUDE.mdファイルを含めるためにプロジェクト設定を読み込む
    const result = query({
      prompt: "Add a new feature following project conventions",
      options: {
        systemPrompt: {
          type: 'preset',
          preset: 'claude_code'  // CLAUDE.mdを使用するために必須
        },
        settingSources: ['project'],  // プロジェクトディレクトリからCLAUDE.mdを読み込む
        allowedTools: ['Read', 'Write', 'Edit']
      }
    });

    設定の優先順位

    複数のソースが読み込まれた場合、設定は以下の優先順位(高い順)でマージされます:

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

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

    PermissionMode

    type PermissionMode =
      | 'default'           // 標準のパーミッション動作
      | 'acceptEdits'       // ファイル編集を自動承認
      | 'bypassPermissions' // すべてのパーミッションチェックをバイパス
      | 'plan'              // 計画モード - 実行なし

    CanUseTool

    ツール使用を制御するためのカスタムパーミッション関数型。

    type CanUseTool = (
      toolName: string,
      input: ToolInput,
      options: {
        signal: AbortSignal;
        suggestions?: PermissionUpdate[];
      }
    ) => Promise<PermissionResult>;

    PermissionResult

    パーミッションチェックの結果。

    type PermissionResult = 
      | {
          behavior: 'allow';
          updatedInput: ToolInput;
          updatedPermissions?: PermissionUpdate[];
        }
      | {
          behavior: 'deny';
          message: string;
          interrupt?: boolean;
        }

    McpServerConfig

    MCPサーバーの設定。

    type McpServerConfig = 
      | McpStdioServerConfig
      | McpSSEServerConfig
      | McpHttpServerConfig
      | McpSdkServerConfigWithInstance;

    McpStdioServerConfig

    type McpStdioServerConfig = {
      type?: 'stdio';
      command: string;
      args?: string[];
      env?: Record<string, string>;
    }

    McpSSEServerConfig

    type McpSSEServerConfig = {
      type: 'sse';
      url: string;
      headers?: Record<string, string>;
    }

    McpHttpServerConfig

    type McpHttpServerConfig = {
      type: 'http';
      url: string;
      headers?: Record<string, string>;
    }

    McpSdkServerConfigWithInstance

    type McpSdkServerConfigWithInstance = {
      type: 'sdk';
      name: string;
      instance: McpServer;
    }

    SdkPluginConfig

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

    type SdkPluginConfig = {
      type: 'local';
      path: string;
    }
    フィールド型説明
    type'local''local' でなければならない(現在ローカルプラグインのみサポート)
    pathstringプラグインディレクトリへの絶対パスまたは相対パス

    例:

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

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

    メッセージ型

    SDKMessage

    クエリが返すすべての可能なメッセージのユニオン型。

    type SDKMessage = 
      | SDKAssistantMessage
      | SDKUserMessage
      | SDKUserMessageReplay
      | SDKResultMessage
      | SDKSystemMessage
      | SDKPartialAssistantMessage
      | SDKCompactBoundaryMessage;

    SDKAssistantMessage

    アシスタントの応答メッセージ。

    type SDKAssistantMessage = {
      type: 'assistant';
      uuid: UUID;
      session_id: string;
      message: APIAssistantMessage; // Anthropic SDKから
      parent_tool_use_id: string | null;
    }

    SDKUserMessage

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

    type SDKUserMessage = {
      type: 'user';
      uuid?: UUID;
      session_id: string;
      message: APIUserMessage; // Anthropic SDKから
      parent_tool_use_id: string | null;
    }

    SDKUserMessageReplay

    必須UUIDを持つリプレイされたユーザーメッセージ。

    type SDKUserMessageReplay = {
      type: 'user';
      uuid: UUID;
      session_id: string;
      message: APIUserMessage;
      parent_tool_use_id: string | null;
    }

    SDKResultMessage

    最終結果メッセージ。

    type SDKResultMessage =
      | {
          type: 'result';
          subtype: 'success';
          uuid: UUID;
          session_id: string;
          duration_ms: number;
          duration_api_ms: number;
          is_error: boolean;
          num_turns: number;
          result: string;
          total_cost_usd: number;
          usage: NonNullableUsage;
          modelUsage: { [modelName: string]: ModelUsage };
          permission_denials: SDKPermissionDenial[];
          structured_output?: unknown;
        }
      | {
          type: 'result';
          subtype:
            | 'error_max_turns'
            | 'error_during_execution'
            | 'error_max_budget_usd'
            | 'error_max_structured_output_retries';
          uuid: UUID;
          session_id: string;
          duration_ms: number;
          duration_api_ms: number;
          is_error: boolean;
          num_turns: number;
          total_cost_usd: number;
          usage: NonNullableUsage;
          modelUsage: { [modelName: string]: ModelUsage };
          permission_denials: SDKPermissionDenial[];
          errors: string[];
        }

    SDKSystemMessage

    システム初期化メッセージ。

    type SDKSystemMessage = {
      type: 'system';
      subtype: 'init';
      uuid: UUID;
      session_id: string;
      apiKeySource: ApiKeySource;
      cwd: string;
      tools: string[];
      mcp_servers: {
        name: string;
        status: string;
      }[];
      model: string;
      permissionMode: PermissionMode;
      slash_commands: string[];
      output_style: string;
    }

    SDKPartialAssistantMessage

    ストリーミング部分メッセージ(includePartialMessages がtrueの場合のみ)。

    type SDKPartialAssistantMessage = {
      type: 'stream_event';
      event: RawMessageStreamEvent; // Anthropic SDKから
      parent_tool_use_id: string | null;
      uuid: UUID;
      session_id: string;
    }

    SDKCompactBoundaryMessage

    会話コンパクション境界を示すメッセージ。

    type SDKCompactBoundaryMessage = {
      type: 'system';
      subtype: 'compact_boundary';
      uuid: UUID;
      session_id: string;
      compact_metadata: {
        trigger: 'manual' | 'auto';
        pre_tokens: number;
      };
    }

    SDKPermissionDenial

    拒否されたツール使用に関する情報。

    type SDKPermissionDenial = {
      tool_name: string;
      tool_use_id: string;
      tool_input: ToolInput;
    }

    フック型

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

    HookEvent

    利用可能なフックイベント。

    type HookEvent =
      | 'PreToolUse'
      | 'PostToolUse'
      | 'PostToolUseFailure'
      | 'Notification'
      | 'UserPromptSubmit'
      | 'SessionStart'
      | 'SessionEnd'
      | 'Stop'
      | 'SubagentStart'
      | 'SubagentStop'
      | 'PreCompact'
      | 'PermissionRequest';

    HookCallback

    フックコールバック関数型。

    type HookCallback = (
      input: HookInput, // すべてのフック入力型のユニオン
      toolUseID: string | undefined,
      options: { signal: AbortSignal }
    ) => Promise<HookJSONOutput>;

    HookCallbackMatcher

    オプションのマッチャーを持つフック設定。

    interface HookCallbackMatcher {
      matcher?: string;
      hooks: HookCallback[];
    }

    HookInput

    すべてのフック入力型のユニオン型。

    type HookInput =
      | PreToolUseHookInput
      | PostToolUseHookInput
      | PostToolUseFailureHookInput
      | NotificationHookInput
      | UserPromptSubmitHookInput
      | SessionStartHookInput
      | SessionEndHookInput
      | StopHookInput
      | SubagentStartHookInput
      | SubagentStopHookInput
      | PreCompactHookInput
      | PermissionRequestHookInput;

    BaseHookInput

    すべてのフック入力型が拡張するベースインターフェース。

    type BaseHookInput = {
      session_id: string;
      transcript_path: string;
      cwd: string;
      permission_mode?: string;
    }

    PreToolUseHookInput

    type PreToolUseHookInput = BaseHookInput & {
      hook_event_name: 'PreToolUse';
      tool_name: string;
      tool_input: unknown;
    }

    PostToolUseHookInput

    type PostToolUseHookInput = BaseHookInput & {
      hook_event_name: 'PostToolUse';
      tool_name: string;
      tool_input: unknown;
      tool_response: unknown;
    }

    PostToolUseFailureHookInput

    type PostToolUseFailureHookInput = BaseHookInput & {
      hook_event_name: 'PostToolUseFailure';
      tool_name: string;
      tool_input: unknown;
      error: string;
      is_interrupt?: boolean;
    }

    NotificationHookInput

    type NotificationHookInput = BaseHookInput & {
      hook_event_name: 'Notification';
      message: string;
      title?: string;
    }

    UserPromptSubmitHookInput

    type UserPromptSubmitHookInput = BaseHookInput & {
      hook_event_name: 'UserPromptSubmit';
      prompt: string;
    }

    SessionStartHookInput

    type SessionStartHookInput = BaseHookInput & {
      hook_event_name: 'SessionStart';
      source: 'startup' | 'resume' | 'clear' | 'compact';
    }

    SessionEndHookInput

    type SessionEndHookInput = BaseHookInput & {
      hook_event_name: 'SessionEnd';
      reason: ExitReason;  // EXIT_REASONS配列からの文字列
    }

    StopHookInput

    type StopHookInput = BaseHookInput & {
      hook_event_name: 'Stop';
      stop_hook_active: boolean;
    }

    SubagentStartHookInput

    type SubagentStartHookInput = BaseHookInput & {
      hook_event_name: 'SubagentStart';
      agent_id: string;
      agent_type: string;
    }

    SubagentStopHookInput

    type SubagentStopHookInput = BaseHookInput & {
      hook_event_name: 'SubagentStop';
      stop_hook_active: boolean;
    }

    PreCompactHookInput

    type PreCompactHookInput = BaseHookInput & {
      hook_event_name: 'PreCompact';
      trigger: 'manual' | 'auto';
      custom_instructions: string | null;
    }

    PermissionRequestHookInput

    type PermissionRequestHookInput = BaseHookInput & {
      hook_event_name: 'PermissionRequest';
      tool_name: string;
      tool_input: unknown;
      permission_suggestions?: PermissionUpdate[];
    }

    HookJSONOutput

    フックの戻り値。

    type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;

    AsyncHookJSONOutput

    type AsyncHookJSONOutput = {
      async: true;
      asyncTimeout?: number;
    }

    SyncHookJSONOutput

    type SyncHookJSONOutput = {
      continue?: boolean;
      suppressOutput?: boolean;
      stopReason?: string;
      decision?: 'approve' | 'block';
      systemMessage?: string;
      reason?: string;
      hookSpecificOutput?:
        | {
            hookEventName: 'PreToolUse';
            permissionDecision?: 'allow' | 'deny' | 'ask';
            permissionDecisionReason?: string;
            updatedInput?: Record<string, unknown>;
          }
        | {
            hookEventName: 'UserPromptSubmit';
            additionalContext?: string;
          }
        | {
            hookEventName: 'SessionStart';
            additionalContext?: string;
          }
        | {
            hookEventName: 'PostToolUse';
            additionalContext?: string;
          };
    }

    ツール入力型

    すべての組み込みClaude Codeツールの入力スキーマのドキュメント。これらの型は @anthropic-ai/claude-agent-sdk からエクスポートされ、型安全なツールインタラクションに使用できます。

    ToolInput

    注意: これは明確さのためのドキュメント専用の型です。すべてのツール入力型のユニオンを表します。

    type ToolInput =
      | AgentInput
      | AskUserQuestionInput
      | BashInput
      | BashOutputInput
      | FileEditInput
      | FileReadInput
      | FileWriteInput
      | GlobInput
      | GrepInput
      | KillShellInput
      | NotebookEditInput
      | WebFetchInput
      | WebSearchInput
      | TodoWriteInput
      | ExitPlanModeInput
      | ListMcpResourcesInput
      | ReadMcpResourceInput;

    Task

    ツール名: Task

    interface AgentInput {
      /**
       * タスクの短い(3〜5語の)説明
       */
      description: string;
      /**
       * エージェントが実行するタスク
       */
      prompt: string;
      /**
       * このタスクに使用する特殊エージェントのタイプ
       */
      subagent_type: string;
    }

    複雑なマルチステップタスクを自律的に処理する新しいエージェントを起動します。

    AskUserQuestion

    ツール名: AskUserQuestion

    interface AskUserQuestionInput {
      /**
       * ユーザーに尋ねる質問(1〜4問)
       */
      questions: Array<{
        /**
         * ユーザーに尋ねる完全な質問。明確で具体的であり、
         * 疑問符で終わる必要があります。
         */
        question: string;
        /**
         * チップ/タグとして表示される非常に短いラベル(最大12文字)。
         * 例:"Auth method"、"Library"、"Approach"
         */
        header: string;
        /**
         * 利用可能な選択肢(2〜4オプション)。「その他」オプションは
         * 自動的に提供されます。
         */
        options: Array<{
          /**
           * このオプションの表示テキスト(1〜5語)
           */
          label: string;
          /**
           * このオプションの意味の説明
           */
          description: string;
        }>;
        /**
         * 複数選択を許可する場合はtrueに設定
         */
        multiSelect: boolean;
      }>;
      /**
       * パーミッションシステムによって入力されるユーザーの回答。
       * 質問テキストを選択されたオプションラベルにマッピング。
       * 複数選択の回答はカンマ区切り。
       */
      answers?: Record<string, string>;
    }

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

    Bash

    ツール名: Bash

    interface BashInput {
      /**
       * 実行するコマンド
       */
      command: string;
      /**
       * オプションのタイムアウト(ミリ秒、最大600000)
       */
      timeout?: number;
      /**
       * このコマンドが何をするかの明確で簡潔な説明(5〜10語)
       */
      description?: string;
      /**
       * このコマンドをバックグラウンドで実行する場合はtrueに設定
       */
      run_in_background?: boolean;
    }

    オプションのタイムアウトとバックグラウンド実行を備えた永続的なシェルセッションでbashコマンドを実行します。

    BashOutput

    ツール名: BashOutput

    interface BashOutputInput {
      /**
       * 出力を取得するバックグラウンドシェルのID
       */
      bash_id: string;
      /**
       * 出力行をフィルタリングするオプションの正規表現
       */
      filter?: string;
    }

    実行中または完了したバックグラウンドbashシェルから出力を取得します。

    Edit

    ツール名: Edit

    interface FileEditInput {
      /**
       * 変更するファイルの絶対パス
       */
      file_path: string;
      /**
       * 置換するテキスト
       */
      old_string: string;
      /**
       * 置換後のテキスト(old_stringと異なる必要があります)
       */
      new_string: string;
      /**
       * old_stringのすべての出現を置換(デフォルトfalse)
       */
      replace_all?: boolean;
    }

    ファイル内で正確な文字列置換を実行します。

    Read

    ツール名: Read

    interface FileReadInput {
      /**
       * 読み取るファイルの絶対パス
       */
      file_path: string;
      /**
       * 読み取りを開始する行番号
       */
      offset?: number;
      /**
       * 読み取る行数
       */
      limit?: number;
    }

    テキスト、画像、PDF、Jupyterノートブックを含むローカルファイルシステムからファイルを読み取ります。

    Write

    ツール名: Write

    interface FileWriteInput {
      /**
       * 書き込むファイルの絶対パス
       */
      file_path: string;
      /**
       * ファイルに書き込む内容
       */
      content: string;
    }

    ローカルファイルシステムにファイルを書き込みます。既存の場合は上書きします。

    Glob

    ツール名: Glob

    interface GlobInput {
      /**
       * ファイルとマッチさせるglobパターン
       */
      pattern: string;
      /**
       * 検索するディレクトリ(デフォルトはcwd)
       */
      path?: string;
    }

    あらゆるサイズのコードベースで動作する高速なファイルパターンマッチング。

    Grep

    ツール名: Grep

    interface GrepInput {
      /**
       * 検索する正規表現パターン
       */
      pattern: string;
      /**
       * 検索するファイルまたはディレクトリ(デフォルトはcwd)
       */
      path?: string;
      /**
       * ファイルをフィルタリングするglobパターン(例:"*.js")
       */
      glob?: string;
      /**
       * 検索するファイルタイプ(例:"js"、"py"、"rust")
       */
      type?: string;
      /**
       * 出力モード:"content"、"files_with_matches"、または"count"
       */
      output_mode?: 'content' | 'files_with_matches' | 'count';
      /**
       * 大文字小文字を区別しない検索
       */
      '-i'?: boolean;
      /**
       * 行番号を表示(contentモード用)
       */
      '-n'?: boolean;
      /**
       * 各マッチの前に表示する行数
       */
      '-B'?: number;
      /**
       * 各マッチの後に表示する行数
       */
      '-A'?: number;
      /**
       * 各マッチの前後に表示する行数
       */
      '-C'?: number;
      /**
       * 出力を最初のN行/エントリに制限
       */
      head_limit?: number;
      /**
       * マルチラインモードを有効にする
       */
      multiline?: boolean;
    }

    正規表現サポートを備えたripgrepベースの強力な検索ツール。

    KillBash

    ツール名: KillBash

    interface KillShellInput {
      /**
       * 終了するバックグラウンドシェルのID
       */
      shell_id: string;
    }

    IDで指定された実行中のバックグラウンドbashシェルを終了します。

    NotebookEdit

    ツール名: NotebookEdit

    interface NotebookEditInput {
      /**
       * Jupyterノートブックファイルの絶対パス
       */
      notebook_path: string;
      /**
       * 編集するセルのID
       */
      cell_id?: string;
      /**
       * セルの新しいソース
       */
      new_source: string;
      /**
       * セルのタイプ(codeまたはmarkdown)
       */
      cell_type?: 'code' | 'markdown';
      /**
       * 編集のタイプ(replace、insert、delete)
       */
      edit_mode?: 'replace' | 'insert' | 'delete';
    }

    Jupyterノートブックファイルのセルを編集します。

    WebFetch

    ツール名: WebFetch

    interface WebFetchInput {
      /**
       * コンテンツを取得するURL
       */
      url: string;
      /**
       * 取得したコンテンツに対して実行するプロンプト
       */
      prompt: string;
    }

    URLからコンテンツを取得し、AIモデルで処理します。

    WebSearch

    ツール名: WebSearch

    interface WebSearchInput {
      /**
       * 使用する検索クエリ
       */
      query: string;
      /**
       * これらのドメインからの結果のみを含める
       */
      allowed_domains?: string[];
      /**
       * これらのドメインからの結果を含めない
       */
      blocked_domains?: string[];
    }

    ウェブを検索し、フォーマットされた結果を返します。

    TodoWrite

    ツール名: TodoWrite

    interface TodoWriteInput {
      /**
       * 更新されたTodoリスト
       */
      todos: Array<{
        /**
         * タスクの説明
         */
        content: string;
        /**
         * タスクのステータス
         */
        status: 'pending' | 'in_progress' | 'completed';
        /**
         * タスク説明の能動態形式
         */
        activeForm: string;
      }>;
    }

    進捗追跡のための構造化されたタスクリストを作成・管理します。

    ExitPlanMode

    ツール名: ExitPlanMode

    interface ExitPlanModeInput {
      /**
       * ユーザーの承認のために実行する計画
       */
      plan: string;
    }

    計画モードを終了し、ユーザーに計画の承認を求めます。

    ListMcpResources

    ツール名: ListMcpResources

    interface ListMcpResourcesInput {
      /**
       * リソースをフィルタリングするオプションのサーバー名
       */
      server?: string;
    }

    接続されたサーバーから利用可能なMCPリソースを一覧表示します。

    ReadMcpResource

    ツール名: ReadMcpResource

    interface ReadMcpResourceInput {
      /**
       * MCPサーバー名
       */
      server: string;
      /**
       * 読み取るリソースURI
       */
      uri: string;
    }

    サーバーから特定のMCPリソースを読み取ります。

    ツール出力型

    すべての組み込みClaude Codeツールの出力スキーマのドキュメント。これらの型は各ツールが返す実際のレスポンスデータを表します。

    ToolOutput

    注意: これは明確さのためのドキュメント専用の型です。すべてのツール出力型のユニオンを表します。

    type ToolOutput =
      | TaskOutput
      | AskUserQuestionOutput
      | BashOutput
      | BashOutputToolOutput
      | EditOutput
      | ReadOutput
      | WriteOutput
      | GlobOutput
      | GrepOutput
      | KillBashOutput
      | NotebookEditOutput
      | WebFetchOutput
      | WebSearchOutput
      | TodoWriteOutput
      | ExitPlanModeOutput
      | ListMcpResourcesOutput
      | ReadMcpResourceOutput;

    Task

    ツール名: Task

    interface TaskOutput {
      /**
       * サブエージェントからの最終結果メッセージ
       */
      result: string;
      /**
       * トークン使用統計
       */
      usage?: {
        input_tokens: number;
        output_tokens: number;
        cache_creation_input_tokens?: number;
        cache_read_input_tokens?: number;
      };
      /**
       * 合計コスト(USD)
       */
      total_cost_usd?: number;
      /**
       * 実行時間(ミリ秒)
       */
      duration_ms?: number;
    }

    委任されたタスクの完了後にサブエージェントからの最終結果を返します。

    AskUserQuestion

    ツール名: AskUserQuestion

    interface AskUserQuestionOutput {
      /**
       * 尋ねられた質問
       */
      questions: Array<{
        question: string;
        header: string;
        options: Array<{
          label: string;
          description: string;
        }>;
        multiSelect: boolean;
      }>;
      /**
       * ユーザーが提供した回答。
       * 質問テキストを回答文字列にマッピング。
       * 複数選択の回答はカンマ区切り。
       */
      answers: Record<string, string>;
    }

    尋ねられた質問とユーザーの回答を返します。

    Bash

    ツール名: Bash

    interface BashOutput {
      /**
       * stdoutとstderrの結合出力
       */
      output: string;
      /**
       * コマンドの終了コード
       */
      exitCode: number;
      /**
       * タイムアウトによりコマンドが終了されたかどうか
       */
      killed?: boolean;
      /**
       * バックグラウンドプロセスのシェルID
       */
      shellId?: string;
    }

    終了ステータス付きのコマンド出力を返します。バックグラウンドコマンドはshellIdとともに即座に返されます。

    BashOutput

    ツール名: BashOutput

    interface BashOutputToolOutput {
      /**
       * 前回のチェック以降の新しい出力
       */
      output: string;
      /**
       * 現在のシェルステータス
       */
      status: 'running' | 'completed' | 'failed';
      /**
       * 終了コード(完了時)
       */
      exitCode?: number;
    }

    バックグラウンドシェルからの増分出力を返します。

    Edit

    ツール名: Edit

    interface EditOutput {
      /**
       * 確認メッセージ
       */
      message: string;
      /**
       * 実行された置換の数
       */
      replacements: number;
      /**
       * 編集されたファイルパス
       */
      file_path: string;
    }

    置換数付きの成功した編集の確認を返します。

    Read

    ツール名: Read

    type ReadOutput = 
      | TextFileOutput
      | ImageFileOutput
      | PDFFileOutput
      | NotebookFileOutput;
    
    interface TextFileOutput {
      /**
       * 行番号付きのファイル内容
       */
      content: string;
      /**
       * ファイルの総行数
       */
      total_lines: number;
      /**
       * 実際に返された行数
       */
      lines_returned: number;
    }
    
    interface ImageFileOutput {
      /**
       * Base64エンコードされた画像データ
       */
      image: string;
      /**
       * 画像のMIMEタイプ
       */
      mime_type: string;
      /**
       * ファイルサイズ(バイト)
       */
      file_size: number;
    }
    
    interface PDFFileOutput {
      /**
       * ページ内容の配列
       */
      pages: Array<{
        page_number: number;
        text?: string;
        images?: Array<{
          image: string;
          mime_type: string;
        }>;
      }>;
      /**
       * 総ページ数
       */
      total_pages: number;
    }
    
    interface NotebookFileOutput {
      /**
       * Jupyterノートブックのセル
       */
      cells: Array<{
        cell_type: 'code' | 'markdown';
        source: string;
        outputs?: any[];
        execution_count?: number;
      }>;
      /**
       * ノートブックのメタデータ
       */
      metadata?: Record<string, any>;
    }

    ファイルタイプに適した形式でファイル内容を返します。

    Write

    ツール名: Write

    interface WriteOutput {
      /**
       * 成功メッセージ
       */
      message: string;
      /**
       * 書き込まれたバイト数
       */
      bytes_written: number;
      /**
       * 書き込まれたファイルパス
       */
      file_path: string;
    }

    ファイルの書き込みが成功した後に確認を返します。

    Glob

    ツール名: Glob

    interface GlobOutput {
      /**
       * 一致するファイルパスの配列
       */
      matches: string[];
      /**
       * 見つかった一致数
       */
      count: number;
      /**
       * 使用された検索ディレクトリ
       */
      search_path: string;
    }

    globパターンに一致するファイルパスを、更新日時順にソートして返します。

    Grep

    ツール名: Grep

    type GrepOutput = 
      | GrepContentOutput
      | GrepFilesOutput
      | GrepCountOutput;
    
    interface GrepContentOutput {
      /**
       * コンテキスト付きの一致行
       */
      matches: Array<{
        file: string;
        line_number?: number;
        line: string;
        before_context?: string[];
        after_context?: string[];
      }>;
      /**
       * 一致の総数
       */
      total_matches: number;
    }
    
    interface GrepFilesOutput {
      /**
       * 一致を含むファイル
       */
      files: string[];
      /**
       * 一致を含むファイル数
       */
      count: number;
    }
    
    interface GrepCountOutput {
      /**
       * ファイルごとの一致数
       */
      counts: Array<{
        file: string;
        count: number;
      }>;
      /**
       * 全ファイルの一致総数
       */
      total: number;
    }

    output_modeで指定された形式で検索結果を返します。

    KillBash

    ツール名: KillBash

    interface KillBashOutput {
      /**
       * 成功メッセージ
       */
      message: string;
      /**
       * 終了されたシェルのID
       */
      shell_id: string;
    }

    バックグラウンドシェルの終了後に確認を返します。

    NotebookEdit

    ツール名: NotebookEdit

    interface NotebookEditOutput {
      /**
       * 成功メッセージ
       */
      message: string;
      /**
       * 実行された編集の種類
       */
      edit_type: 'replaced' | 'inserted' | 'deleted';
      /**
       * 影響を受けたセルID
       */
      cell_id?: string;
      /**
       * 編集後のノートブックの総セル数
       */
      total_cells: number;
    }

    Jupyterノートブックの変更後に確認を返します。

    WebFetch

    ツール名: WebFetch

    interface WebFetchOutput {
      /**
       * プロンプトに対するAIモデルの応答
       */
      response: string;
      /**
       * フェッチされたURL
       */
      url: string;
      /**
       * リダイレクト後の最終URL
       */
      final_url?: string;
      /**
       * HTTPステータスコード
       */
      status_code?: number;
    }

    フェッチされたWebコンテンツのAI分析結果を返します。

    WebSearch

    ツール名: WebSearch

    interface WebSearchOutput {
      /**
       * 検索結果
       */
      results: Array<{
        title: string;
        url: string;
        snippet: string;
        /**
         * 利用可能な場合の追加メタデータ
         */
        metadata?: Record<string, any>;
      }>;
      /**
       * 結果の総数
       */
      total_results: number;
      /**
       * 検索されたクエリ
       */
      query: string;
    }

    Webからフォーマットされた検索結果を返します。

    TodoWrite

    ツール名: TodoWrite

    interface TodoWriteOutput {
      /**
       * 成功メッセージ
       */
      message: string;
      /**
       * 現在のTodo統計
       */
      stats: {
        total: number;
        pending: number;
        in_progress: number;
        completed: number;
      };
    }

    現在のタスク統計とともに確認を返します。

    ExitPlanMode

    ツール名: ExitPlanMode

    interface ExitPlanModeOutput {
      /**
       * 確認メッセージ
       */
      message: string;
      /**
       * ユーザーがプランを承認したかどうか
       */
      approved?: boolean;
    }

    プランモード終了後に確認を返します。

    ListMcpResources

    ツール名: ListMcpResources

    interface ListMcpResourcesOutput {
      /**
       * 利用可能なリソース
       */
      resources: Array<{
        uri: string;
        name: string;
        description?: string;
        mimeType?: string;
        server: string;
      }>;
      /**
       * リソースの総数
       */
      total: number;
    }

    利用可能なMCPリソースのリストを返します。

    ReadMcpResource

    ツール名: ReadMcpResource

    interface ReadMcpResourceOutput {
      /**
       * リソースの内容
       */
      contents: Array<{
        uri: string;
        mimeType?: string;
        text?: string;
        blob?: string;
      }>;
      /**
       * リソースを提供したサーバー
       */
      server: string;
    }

    リクエストされたMCPリソースの内容を返します。

    パーミッションタイプ

    PermissionUpdate

    パーミッションを更新するための操作。

    type PermissionUpdate = 
      | {
          type: 'addRules';
          rules: PermissionRuleValue[];
          behavior: PermissionBehavior;
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'replaceRules';
          rules: PermissionRuleValue[];
          behavior: PermissionBehavior;
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'removeRules';
          rules: PermissionRuleValue[];
          behavior: PermissionBehavior;
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'setMode';
          mode: PermissionMode;
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'addDirectories';
          directories: string[];
          destination: PermissionUpdateDestination;
        }
      | {
          type: 'removeDirectories';
          directories: string[];
          destination: PermissionUpdateDestination;
        }

    PermissionBehavior

    type PermissionBehavior = 'allow' | 'deny' | 'ask';

    PermissionUpdateDestination

    type PermissionUpdateDestination = 
      | 'userSettings'     // グローバルユーザー設定
      | 'projectSettings'  // ディレクトリごとのプロジェクト設定
      | 'localSettings'    // Gitignoreされたローカル設定
      | 'session'          // 現在のセッションのみ

    PermissionRuleValue

    type PermissionRuleValue = {
      toolName: string;
      ruleContent?: string;
    }

    その他のタイプ

    ApiKeySource

    type ApiKeySource = 'user' | 'project' | 'org' | 'temporary';

    SdkBeta

    betasオプションで有効にできる利用可能なベータ機能。詳細についてはベータヘッダーを参照してください。

    type SdkBeta = 'context-1m-2025-08-07';
    値説明互換モデル
    'context-1m-2025-08-07'100万トークンのコンテキストウィンドウを有効にするClaude Opus 4.6、Claude Sonnet 4.5、Claude Sonnet 4

    SlashCommand

    利用可能なスラッシュコマンドに関する情報。

    type SlashCommand = {
      name: string;
      description: string;
      argumentHint: string;
    }

    ModelInfo

    利用可能なモデルに関する情報。

    type ModelInfo = {
      value: string;
      displayName: string;
      description: string;
    }

    McpServerStatus

    接続されたMCPサーバーのステータス。

    type McpServerStatus = {
      name: string;
      status: 'connected' | 'failed' | 'needs-auth' | 'pending';
      serverInfo?: {
        name: string;
        version: string;
      };
    }

    AccountInfo

    認証済みユーザーのアカウント情報。

    type AccountInfo = {
      email?: string;
      organization?: string;
      subscriptionType?: string;
      tokenSource?: string;
      apiKeySource?: string;
    }

    ModelUsage

    結果メッセージで返されるモデルごとの使用統計。

    type ModelUsage = {
      inputTokens: number;
      outputTokens: number;
      cacheReadInputTokens: number;
      cacheCreationInputTokens: number;
      webSearchRequests: number;
      costUSD: number;
      contextWindow: number;
    }

    ConfigScope

    type ConfigScope = 'local' | 'user' | 'project';

    NonNullableUsage

    すべてのnullableフィールドをnon-nullableにしたUsageのバージョン。

    type NonNullableUsage = {
      [K in keyof Usage]: NonNullable<Usage[K]>;
    }

    Usage

    トークン使用統計(@anthropic-ai/sdkより)。

    type Usage = {
      input_tokens: number | null;
      output_tokens: number | null;
      cache_creation_input_tokens?: number | null;
      cache_read_input_tokens?: number | null;
    }

    CallToolResult

    MCPツール結果タイプ(@modelcontextprotocol/sdk/types.jsより)。

    type CallToolResult = {
      content: Array<{
        type: 'text' | 'image' | 'resource';
        // 追加フィールドはタイプによって異なります
      }>;
      isError?: boolean;
    }

    AbortError

    中止操作用のカスタムエラークラス。

    class AbortError extends Error {}

    サンドボックス設定

    SandboxSettings

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

    type SandboxSettings = {
      enabled?: boolean;
      autoAllowBashIfSandboxed?: boolean;
      excludedCommands?: string[];
      allowUnsandboxedCommands?: boolean;
      network?: NetworkSandboxSettings;
      ignoreViolations?: SandboxIgnoreViolations;
      enableWeakerNestedSandbox?: boolean;
    }
    プロパティタイプデフォルト説明
    enabledbooleanfalseコマンド実行のサンドボックスモードを有効にする
    autoAllowBashIfSandboxedbooleanfalseサンドボックスが有効な場合にbashコマンドを自動承認する
    excludedCommandsstring[][]サンドボックス制限を常にバイパスするコマンド(例:['docker'])。これらはモデルの関与なしに自動的にサンドボックス外で実行されます
    allowUnsandboxedCommandsbooleanfalseモデルがサンドボックス外でのコマンド実行をリクエストすることを許可する。trueの場合、モデルはツール入力でdangerouslyDisableSandboxを設定でき、パーミッションシステムにフォールバックします
    networkNetworkSandboxSettingsundefinedネットワーク固有のサンドボックス設定
    ignoreViolationsSandboxIgnoreViolationsundefined無視するサンドボックス違反の設定
    enableWeakerNestedSandboxbooleanfalse互換性のためにより弱いネストされたサンドボックスを有効にする

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

    • ファイルシステム読み取り制限: Read denyルール
    • ファイルシステム書き込み制限: Edit allow/denyルール
    • ネットワーク制限: WebFetch allow/denyルール

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

    使用例

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    const result = await query({
      prompt: "Build and test my project",
      options: {
        sandbox: {
          enabled: true,
          autoAllowBashIfSandboxed: true,
          network: {
            allowLocalBinding: true
          }
        }
      }
    });

    Unixソケットのセキュリティ: allowUnixSocketsオプションは強力なシステムサービスへのアクセスを許可する可能性があります。例えば、/var/run/docker.sockを許可すると、Docker APIを通じて実質的にホストシステムへの完全なアクセスが許可され、サンドボックスの分離がバイパスされます。厳密に必要なUnixソケットのみを許可し、各ソケットのセキュリティへの影響を理解してください。

    NetworkSandboxSettings

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

    type NetworkSandboxSettings = {
      allowLocalBinding?: boolean;
      allowUnixSockets?: string[];
      allowAllUnixSockets?: boolean;
      httpProxyPort?: number;
      socksProxyPort?: number;
    }
    プロパティタイプデフォルト説明
    allowLocalBindingbooleanfalseプロセスがローカルポートにバインドすることを許可する(例:開発サーバー用)
    allowUnixSocketsstring[][]プロセスがアクセスできるUnixソケットパス(例:Dockerソケット)
    allowAllUnixSocketsbooleanfalseすべてのUnixソケットへのアクセスを許可する
    httpProxyPortnumberundefinedネットワークリクエスト用のHTTPプロキシポート
    socksProxyPortnumberundefinedネットワークリクエスト用のSOCKSプロキシポート

    SandboxIgnoreViolations

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

    type SandboxIgnoreViolations = {
      file?: string[];
      network?: string[];
    }
    プロパティタイプデフォルト説明
    filestring[][]違反を無視するファイルパスパターン
    networkstring[][]違反を無視するネットワークパターン

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

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

    excludedCommands vs allowUnsandboxedCommands:

    • excludedCommands: 常にサンドボックスを自動的にバイパスするコマンドの静的リスト(例:['docker'])。モデルはこれを制御できません。
    • allowUnsandboxedCommands: モデルがツール入力でdangerouslyDisableSandbox: trueを設定することで、実行時にサンドボックス外での実行をリクエストするかどうかを決定できるようにします。
    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    const result = await query({
      prompt: "Deploy my application",
      options: {
        sandbox: {
          enabled: true,
          allowUnsandboxedCommands: true  // モデルがサンドボックス外実行をリクエスト可能
        },
        permissionMode: "default",
        canUseTool: async (tool, input) => {
          // モデルがサンドボックスのバイパスをリクエストしているか確認
          if (tool === "Bash" && input.dangerouslyDisableSandbox) {
            // モデルはこのコマンドをサンドボックス外で実行したい
            console.log(`Unsandboxed command requested: ${input.command}`);
    
            // trueを返して許可、falseを返して拒否
            return isCommandAuthorized(input.command);
          }
          return true;
        }
      }
    });

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

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

    dangerouslyDisableSandbox: trueで実行されるコマンドは完全なシステムアクセスを持ちます。canUseToolハンドラーでこれらのリクエストを慎重に検証してください。

    permissionModeがbypassPermissionsに設定され、allowUnsandboxedCommandsが有効な場合、モデルは承認プロンプトなしにサンドボックス外でコマンドを自律的に実行できます。この組み合わせは、モデルがサンドボックスの分離をサイレントにエスケープすることを実質的に許可します。

    関連項目

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

    Was this page helpful?

    • query()
    • tool()
    • createSdkMcpServer()
    • Options
    • Query
    • AgentDefinition
    • SettingSource
    • PermissionMode
    • CanUseTool
    • PermissionResult
    • McpServerConfig
    • SdkPluginConfig
    • SDKMessage
    • SDKAssistantMessage
    • SDKUserMessage
    • SDKUserMessageReplay
    • SDKResultMessage
    • SDKSystemMessage
    • SDKPartialAssistantMessage
    • SDKCompactBoundaryMessage
    • SDKPermissionDenial
    • HookEvent
    • HookCallback
    • HookCallbackMatcher
    • HookInput
    • BaseHookInput
    • HookJSONOutput
    • ToolInput
    • Task
    • AskUserQuestion
    • Bash
    • BashOutput
    • Edit
    • Read
    • Write
    • Glob
    • Grep
    • KillBash
    • NotebookEdit
    • WebFetch
    • WebSearch
    • TodoWrite
    • ExitPlanMode
    • ListMcpResources
    • ReadMcpResource
    • ToolOutput
    • Task
    • AskUserQuestion
    • Bash
    • BashOutput
    • Edit
    • Read
    • Write
    • Glob
    • Grep
    • KillBash
    • NotebookEdit
    • WebFetch
    • WebSearch
    • TodoWrite
    • ExitPlanMode
    • ListMcpResources
    • ReadMcpResource
    • PermissionUpdate
    • PermissionBehavior
    • PermissionUpdateDestination
    • PermissionRuleValue
    • ApiKeySource
    • SdkBeta
    • SlashCommand
    • ModelInfo
    • McpServerStatus
    • AccountInfo
    • ModelUsage
    • ConfigScope
    • NonNullableUsage
    • Usage
    • CallToolResult
    • AbortError
    • SandboxSettings
    • NetworkSandboxSettings
    • SandboxIgnoreViolations