Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    入門
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.6 新功能遷移指南模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API處理停止原因提示詞最佳實踐
    上下文管理
    上下文視窗壓縮上下文編輯
    功能
    提示詞快取延伸思考自適應思考思考力度串流訊息批次處理引用多語言支援Token 計數嵌入視覺PDF 支援Files API搜尋結果結構化輸出
    工具
    概覽如何實作工具使用細粒度工具串流Bash 工具程式碼執行工具程式化工具呼叫電腦使用工具文字編輯器工具網頁擷取工具網頁搜尋工具記憶工具工具搜尋工具
    Agent Skills
    概覽快速開始最佳實踐企業級 Skills透過 API 使用 Skills
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2(預覽版)Python SDK遷移指南
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示詞工程
    概覽提示詞產生器使用提示詞範本提示詞改進器清晰直接使用範例(多範例提示)讓 Claude 思考(CoT)使用 XML 標籤賦予 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 參考 - 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 型別)

    回傳值

    回傳一個 Query 物件,它擴展了 AsyncGenerator<SDKMessage, void> 並提供額外的方法。

    tool()

    建立型別安全的 MCP 工具定義,用於 SDK 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 schema
    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主要模型失敗時使用的模型
    forkSessionbooleanfalse使用 resume 恢復時,分叉到新的工作階段 ID 而不是繼續原始工作階段
    hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>{}事件的 Hook 回呼
    includePartialMessagesbooleanfalse包含部分訊息事件
    maxBudgetUsdnumberundefined查詢的最大預算(美元)
    maxThinkingTokensnumberundefined思考過程的最大 token 數
    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[][](無設定)控制要載入哪些檔案系統設定。省略時不載入任何設定。**注意:**必須包含 'project' 才能載入 CLAUDE.md 檔案
    stderr(data: string) => voidundefinedstderr 輸出的回呼
    strictMcpConfigbooleanfalse強制嚴格的 MCP 驗證
    systemPromptstring | { type: 'preset'; preset: 'claude_code'; append?: string }undefined(最小提示)系統提示配置。傳入字串作為自訂提示,或傳入 { type: 'preset', preset: 'claude_code' } 以使用 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()變更最大思考 token 數(僅在串流輸入模式下可用)
    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'本地專案設定(gitignored).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;
    }

    Hook 型別

    有關使用 Hook 的完整指南,包括範例和常見模式,請參閱 Hook 指南。

    HookEvent

    可用的 Hook 事件。

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

    HookCallback

    Hook 回呼函式型別。

    type HookCallback = (
      input: HookInput, // 所有 Hook 輸入型別的聯合
      toolUseID: string | undefined,
      options: { signal: AbortSignal }
    ) => Promise<HookJSONOutput>;

    HookCallbackMatcher

    帶有可選匹配器的 Hook 配置。

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

    HookInput

    所有 Hook 輸入型別的聯合型別。

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

    BaseHookInput

    所有 Hook 輸入型別擴展的基礎介面。

    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

    Hook 回傳值。

    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 工具的輸入 schema 文件。這些型別從 @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 個選項)。系統會自動提供
         * "Other" 選項。
         */
        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;
    }

    在持久的 shell 工作階段中執行 bash 命令,支援可選的逾時和背景執行。

    BashOutput

    工具名稱: BashOutput

    interface BashOutputInput {
      /**
       * 要擷取輸出的背景 shell ID
       */
      bash_id: string;
      /**
       * 可選的正規表達式用於過濾輸出行
       */
      filter?: string;
    }

    從正在執行或已完成的背景 bash shell 擷取輸出。

    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 notebook。

    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 {
      /**
       * 要終止的背景 shell ID
       */
      shell_id: string;
    }

    透過 ID 終止正在執行的背景 bash shell。

    NotebookEdit

    工具名稱: NotebookEdit

    interface NotebookEditInput {
      /**
       * Jupyter notebook 檔案的絕對路徑
       */
      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 notebook 檔案中的儲存格。

    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 {
      /**
       * 更新後的待辦事項列表
       */
      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 工具的輸出 schema 文件。這些型別代表每個工具回傳的實際回應資料。

    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;
      /**
       * Token 使用統計
       */
      usage?: {
        input_tokens: number;
        output_tokens: number;
        cache_creation_input_tokens?: number;
        cache_read_input_tokens?: number;
      };
      /**
       * 總費用(美元)
       */
      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;
      /**
       * 背景程序的 Shell ID
       */
      shellId?: string;
    }

    回傳帶有退出狀態的命令輸出。背景命令會立即回傳並附帶 shellId。

    BashOutput

    工具名稱: BashOutput

    interface BashOutputToolOutput {
      /**
       * 自上次檢查以來的新輸出
       */
      output: string;
      /**
       * 目前的 shell 狀態
       */
      status: 'running' | 'completed' | 'failed';
      /**
       * 退出碼(完成時)
       */
      exitCode?: number;
    }

    回傳背景 shell 的增量輸出。

    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 notebook 儲存格
       */
      cells: Array<{
        cell_type: 'code' | 'markdown';
        source: string;
        outputs?: any[];
        execution_count?: number;
      }>;
      /**
       * Notebook 中繼資料
       */
      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;
      /**
       * 被終止的 shell 的 ID
       */
      shell_id: string;
    }

    終止背景 shell 後返回確認訊息。

    NotebookEdit

    工具名稱: NotebookEdit

    interface NotebookEditOutput {
      /**
       * 成功訊息
       */
      message: string;
      /**
       * 執行的編輯類型
       */
      edit_type: 'replaced' | 'inserted' | 'deleted';
      /**
       * 受影響的儲存格 ID
       */
      cell_id?: string;
      /**
       * 編輯後 notebook 中的儲存格總數
       */
      total_cells: number;
    }

    修改 Jupyter notebook 後返回確認訊息。

    WebFetch

    工具名稱: WebFetch

    interface WebFetchOutput {
      /**
       * AI 模型對提示的回應
       */
      response: string;
      /**
       * 被擷取的 URL
       */
      url: string;
      /**
       * 重新導向後的最終 URL
       */
      final_url?: string;
      /**
       * HTTP 狀態碼
       */
      status_code?: number;
    }

    返回 AI 對擷取的網頁內容的分析。

    WebSearch

    工具名稱: WebSearch

    interface WebSearchOutput {
      /**
       * 搜尋結果
       */
      results: Array<{
        title: string;
        url: string;
        snippet: string;
        /**
         * 可用的額外中繼資料
         */
        metadata?: Record<string, any>;
      }>;
      /**
       * 結果總數
       */
      total_results: number;
      /**
       * 搜尋的查詢
       */
      query: string;
    }

    返回來自網路的格式化搜尋結果。

    TodoWrite

    工具名稱: TodoWrite

    interface TodoWriteOutput {
      /**
       * 成功訊息
       */
      message: string;
      /**
       * 目前的待辦事項統計
       */
      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 選項啟用的可用測試版功能。更多資訊請參閱 Beta 標頭。

    type SdkBeta = 'context-1m-2025-08-07';
    值描述相容模型
    'context-1m-2025-08-07'啟用 100 萬 token 上下文視窗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

    Usage 的一個版本,所有可為空的欄位都變為不可為空。

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

    Usage

    Token 使用統計(來自 @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啟用較弱的巢狀沙箱以提高相容性

    檔案系統和網路存取限制不是透過沙箱設定來配置的。相反,它們是從權限規則衍生的:

    • 檔案系統讀取限制:讀取拒絕規則
    • 檔案系統寫入限制:編輯允許/拒絕規則
    • 網路限制:WebFetch 允許/拒絕規則

    使用沙箱設定進行命令執行沙箱化,使用權限規則進行檔案系統和網路存取控制。

    使用範例

    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 socket 安全性:allowUnixSockets 選項可以授予對強大系統服務的存取權限。例如,允許 /var/run/docker.sock 實際上會透過 Docker API 授予完整的主機系統存取權限,繞過沙箱隔離。僅允許嚴格必要的 Unix socket,並了解每個 socket 的安全影響。

    NetworkSandboxSettings

    沙箱模式的網路特定配置。

    type NetworkSandboxSettings = {
      allowLocalBinding?: boolean;
      allowUnixSockets?: string[];
      allowAllUnixSockets?: boolean;
      httpProxyPort?: number;
      socksProxyPort?: number;
    }
    屬性類型預設值描述
    allowLocalBindingbooleanfalse允許程序綁定到本地連接埠(例如用於開發伺服器)
    allowUnixSocketsstring[][]程序可以存取的 Unix socket 路徑(例如 Docker socket)
    allowAllUnixSocketsbooleanfalse允許存取所有 Unix socket
    httpProxyPortnumberundefined用於網路請求的 HTTP 代理連接埠
    socksProxyPortnumberundefined用於網路請求的 SOCKS 代理連接埠

    SandboxIgnoreViolations

    忽略特定沙箱違規的配置。

    type SandboxIgnoreViolations = {
      file?: string[];
      network?: string[];
    }
    屬性類型預設值描述
    filestring[][]要忽略違規的檔案路徑模式
    networkstring[][]要忽略違規的網路模式

    非沙箱命令的權限回退

    當 allowUnsandboxedCommands 啟用時,模型可以透過在工具輸入中設定 dangerouslyDisableSandbox: true 來請求在沙箱外執行命令。這些請求會回退到現有的權限系統,這意味著您的 canUseTool 處理程式將被呼叫,允許您實作自訂授權邏輯。

    excludedCommands 與 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
    • Hook 型別
    • 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