Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K

    第一步

    Claude 介紹快速入門

    模型與定價

    模型概覽選擇模型Claude 4.5 的新功能遷移到 Claude 4.5模型棄用定價

    使用 Claude 建構

    功能概覽使用 Messages API上下文視窗提示詞最佳實踐

    功能

    提示詞快取上下文編輯延伸思考串流訊息批次處理引用多語言支援Token 計數嵌入向量視覺PDF 支援Files API搜尋結果Google Sheets 附加元件

    工具

    概述如何實現工具使用代幣高效工具使用細粒度工具串流Bash 工具代碼執行工具電腦使用工具文字編輯工具網頁擷取工具網路搜尋工具記憶工具

    代理技能

    概述在 API 中開始使用 Agent Skills技能編寫最佳實踐使用 Agent Skills 與 API

    Agent SDK

    概述Agent SDK 參考 - TypeScriptPython SDK

    指南

    串流輸入處理權限會話管理託管 Agent SDK修改系統提示SDK 中的 MCP自訂工具SDK 中的子代理SDK 中的斜線命令SDK 中的代理技能追蹤成本和使用量待辦事項清單SDK 中的外掛程式

    API 中的 MCP

    MCP 連接器遠端 MCP 伺服器

    Claude 在第三方平台上

    Amazon BedrockVertex AI

    提示工程

    概述提示詞生成器使用提示模板提示詞改進器保持清晰和直接使用範例(多樣提示)讓 Claude 思考(思維鏈)使用 XML 標籤給 Claude 分配角色(系統提示詞)預填 Claude 的回應串接複雜提示長文本技巧延伸思考技巧

    測試與評估

    定義成功標準開發測試案例使用評估工具降低延遲

    加強防護措施

    減少幻覺提高輸出一致性防範越獄handle-streaming-refusals減少提示詞洩漏保持 Claude 的角色特性

    管理和監控

    Admin API 概述使用量和成本 APIClaude Code 分析 API
    Console
    指南

    處理權限

    在 Claude Agent SDK 中控制工具使用和權限

    SDK 權限

    Claude Agent SDK 提供強大的權限控制,讓您可以管理 Claude 在您的應用程式中如何使用工具。

    本指南涵蓋如何使用 canUseTool 回調、鉤子和 settings.json 權限規則來實現權限系統。如需完整的 API 文件,請參閱 TypeScript SDK 參考。

    概述

    Claude Agent SDK 提供四種互補的方式來控制工具使用:

    1. 權限模式 - 影響所有工具的全域權限行為設定
    2. canUseTool 回調 - 針對其他規則未涵蓋的情況的執行時權限處理器
    3. 鉤子 - 使用自訂邏輯對每個工具執行進行細粒度控制
    4. 權限規則 (settings.json) - 具有整合 bash 命令解析的宣告式允許/拒絕規則

    每種方法的使用案例:

    • 權限模式 - 設定整體權限行為(規劃、自動接受編輯、繞過檢查)
    • canUseTool - 針對未涵蓋情況的動態批准,提示使用者權限
    • 鉤子 - 對所有工具執行的程式化控制
    • 權限規則 - 具有智慧 bash 命令解析的靜態政策

    權限流程圖

    %%{init: {"theme": "base", "themeVariables": {"edgeLabelBackground": "#F0F0EB", "lineColor": "#91918D"}, "flowchart": {"edgeLabelMarginX": 12, "edgeLabelMarginY": 8}}}%%
    flowchart TD
        Start([工具請求]) --> PreHook(PreToolUse Hook)
    
        PreHook -->|  允許  | Execute(執行工具)
        PreHook -->|  拒絕  | Denied(拒絕)
        PreHook -->|  詢問  | Callback(canUseTool 回調)
        PreHook -->|  繼續  | Deny(檢查拒絕規則)
    
        Deny -->|  符合  | Denied
        Deny -->|  不符合  | Allow(檢查允許規則)
    
        Allow -->|  符合  | Execute
        Allow -->|  不符合  | Ask(檢查詢問規則)
    
        Ask -->|  符合  | Callback
        Ask -->|  不符合  | Mode{權限模式?}
    
        Mode -->|  bypassPermissions  | Execute
        Mode -->|  其他模式  | Callback
    
        Callback -->|  允許  | Execute
        Callback -->|  拒絕  | Denied
    
        Denied --> DeniedResponse([回饋給代理])
    
        Execute --> PostHook(PostToolUse Hook)
        PostHook --> Done([工具回應])
    
        style Start fill:#F0F0EB,stroke:#D9D8D5,color:#191919
    
        style Denied fill:#BF4D43,color:#fff
        style DeniedResponse fill:#BF4D43,color:#fff
        style Execute fill:#DAAF91,color:#191919
        style Done fill:#DAAF91,color:#191919
    
        classDef hookClass fill:#CC785C,color:#fff
        class PreHook,PostHook hookClass
    
        classDef ruleClass fill:#EBDBBC,color:#191919
        class Deny,Allow,Ask ruleClass
    
        classDef modeClass fill:#A8DAEF,color:#191919
        class Mode modeClass
    
        classDef callbackClass fill:#D4A27F,color:#191919
        class Callback callbackClass

    處理順序: PreToolUse Hook → 拒絕規則 → 允許規則 → 詢問規則 → 權限模式檢查 → canUseTool 回調 → PostToolUse Hook

    權限模式

    權限模式提供對 Claude 如何使用工具的全域控制。您可以在呼叫 query() 時設定權限模式,或在串流會話期間動態更改它。

    可用模式

    SDK 支援四種權限模式,每種都有不同的行為:

    模式描述工具行為
    default標準權限行為適用正常權限檢查
    plan規劃模式 - 不執行Claude 只能使用唯讀工具;在執行前呈現計劃 (SDK 目前不支援)
    acceptEdits自動接受檔案編輯檔案編輯和檔案系統操作會自動批准
    bypassPermissions繞過所有權限檢查所有工具都不需權限提示即可執行(請謹慎使用)

    設定權限模式

    您可以透過兩種方式設定權限模式:

    1. 初始配置

    在建立查詢時設定模式:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    const result = await query({
      prompt: "幫我重構這段程式碼",
      options: {
        permissionMode: 'default'  // 標準權限模式
      }
    });

    2. 動態模式變更(僅限串流)

    在串流會話期間變更模式:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // 為串流輸入建立非同步產生器
    async function* streamInput() {
      yield { 
        type: 'user',
        message: { 
          role: 'user', 
          content: "讓我們從預設權限開始" 
        }
      };
      
      // 稍後在對話中...
      yield {
        type: 'user',
        message: {
          role: 'user',
          content: "現在讓我們加速開發"
        }
      };
    }
    
    const q = query({
      prompt: streamInput(),
      options: {
        permissionMode: 'default'  // 以預設模式開始
      }
    });
    
    // 動態變更模式
    await q.setPermissionMode('acceptEdits');
    
    // 處理訊息
    for await (const message of q) {
      console.log(message);
    }

    模式特定行為

    接受編輯模式 (acceptEdits)

    在接受編輯模式中:

    • 所有檔案編輯都會自動批准
    • 檔案系統操作(mkdir、touch、rm 等)會自動批准
    • 其他工具仍需要正常權限
    • 當您信任 Claude 的編輯時可加速開發
    • 適用於快速原型製作和迭代

    自動批准的操作:

    • 檔案編輯(Edit、Write 工具)
    • Bash 檔案系統命令(mkdir、touch、rm、mv、cp)
    • 檔案建立和刪除

    繞過權限模式 (bypassPermissions)

    在繞過權限模式中:

    • 所有工具使用都會自動批准
    • 不會出現權限提示
    • 鉤子仍會執行(仍可阻止操作)
    • 請極度謹慎使用 - Claude 擁有完整系統存取權限
    • 建議僅在受控環境中使用

    權限流程中的模式優先順序

    權限模式在權限流程中的特定點進行評估:

    1. 鉤子首先執行 - 可以允許、拒絕、詢問或繼續
    2. 檢查拒絕規則 - 無論模式如何都會阻止工具
    3. 檢查允許規則 - 如果符合則允許工具
    4. 檢查詢問規則 - 如果符合則提示權限
    5. 評估權限模式:
      • bypassPermissions 模式 - 如果啟用,允許所有剩餘工具
      • 其他模式 - 延遲到 canUseTool 回調
    6. canUseTool 回調 - 處理剩餘情況

    這意味著:

    • 鉤子始終可以控制工具使用,即使在 bypassPermissions 模式中
    • 明確的拒絕規則會覆蓋所有權限模式
    • 詢問規則在權限模式之前評估
    • bypassPermissions 模式會覆蓋未符合工具的 canUseTool 回調

    最佳實踐

    1. 使用預設模式 進行受控執行與正常權限檢查
    2. 使用 acceptEdits 模式 處理隔離的檔案或目錄
    3. 避免在生產環境或敏感資料系統中使用 bypassPermissions
    4. 結合模式與鉤子 進行細粒度控制
    5. 根據任務進度和信心動態切換模式

    模式進展範例:

    // 以預設模式開始進行受控執行
    permissionMode: 'default'
    
    // 切換到 acceptEdits 進行快速迭代
    await q.setPermissionMode('acceptEdits')

    canUseTool

    canUseTool 回調在呼叫 query 函數時作為選項傳遞。它接收工具名稱和輸入參數,並必須回傳決定 - 允許或拒絕。

    當 Claude Code 會向使用者顯示權限提示時,canUseTool 會觸發,例如鉤子和權限規則未涵蓋且不在 acceptEdits 模式中。

    以下是顯示如何實現互動式工具批准的完整範例:

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    async function promptForToolApproval(toolName: string, input: any) {
      console.log("\n🔧 工具請求:");
      console.log(`   工具:${toolName}`);
      
      // 顯示工具參數
      if (input && Object.keys(input).length > 0) {
        console.log("   參數:");
        for (const [key, value] of Object.entries(input)) {
          let displayValue = value;
          if (typeof value === 'string' && value.length > 100) {
            displayValue = value.substring(0, 100) + "...";
          } else if (typeof value === 'object') {
            displayValue = JSON.stringify(value, null, 2);
          }
          console.log(`     ${key}: ${displayValue}`);
        }
      }
      
      // 取得使用者批准(替換為您的 UI 邏輯)
      const approved = await getUserApproval();
      
      if (approved) {
        console.log("   ✅ 已批准\n");
        return {
          behavior: "allow",
          updatedInput: input
        };
      } else {
        console.log("   ❌ 已拒絕\n");
        return {
          behavior: "deny",
          message: "使用者拒絕此工具的權限"
        };
      }
    }
    
    // 使用權限回調
    const result = await query({
      prompt: "幫我分析這個程式碼庫",
      options: {
        canUseTool: async (toolName, input) => {
          return promptForToolApproval(toolName, input);
        }
      }
    });

    相關資源

    • 鉤子指南 - 學習如何實現鉤子以對工具執行進行細粒度控制
    • 設定:權限規則 - 配置具有 bash 命令解析的宣告式允許/拒絕規則
    • canUseTool
    © 2025 ANTHROPIC PBC

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

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

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    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

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

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

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

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

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    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

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    © 2025 ANTHROPIC PBC