Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Claude Agent SDK 提供強大的權限控制,讓您可以管理 Claude 在您的應用程式中如何使用工具。
本指南涵蓋如何使用 canUseTool 回調、鉤子和 settings.json 權限規則來實現權限系統。如需完整的 API 文件,請參閱 TypeScript SDK 參考。
Claude Agent SDK 提供四種互補的方式來控制工具使用:
每種方法的使用案例:
canUseTool - 針對未涵蓋情況的動態批准,提示使用者權限處理順序: PreToolUse Hook → 拒絕規則 → 允許規則 → 詢問規則 → 權限模式檢查 → canUseTool 回調 → PostToolUse Hook
權限模式提供對 Claude 如何使用工具的全域控制。您可以在呼叫 query() 時設定權限模式,或在串流會話期間動態更改它。
SDK 支援四種權限模式,每種都有不同的行為:
| 模式 | 描述 | 工具行為 |
|---|---|---|
default | 標準權限行為 | 適用正常權限檢查 |
plan | 規劃模式 - 不執行 | Claude 只能使用唯讀工具;在執行前呈現計劃 (SDK 目前不支援) |
acceptEdits | 自動接受檔案編輯 | 檔案編輯和檔案系統操作會自動批准 |
bypassPermissions | 繞過所有權限檢查 | 所有工具都不需權限提示即可執行(請謹慎使用) |
您可以透過兩種方式設定權限模式:
在建立查詢時設定模式:
import { query } from "@anthropic-ai/claude-agent-sdk";
const result = await query({
prompt: "幫我重構這段程式碼",
options: {
permissionMode: 'default' // 標準權限模式
}
});在串流會話期間變更模式:
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)在接受編輯模式中:
自動批准的操作:
bypassPermissions)在繞過權限模式中:
權限模式在權限流程中的特定點進行評估:
bypassPermissions 模式 - 如果啟用,允許所有剩餘工具canUseTool 回調canUseTool 回調 - 處理剩餘情況這意味著:
bypassPermissions 模式中bypassPermissions 模式會覆蓋未符合工具的 canUseTool 回調模式進展範例:
// 以預設模式開始進行受控執行
permissionMode: 'default'
// 切換到 acceptEdits 進行快速迭代
await q.setPermissionMode('acceptEdits')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);
}
}
});