Claude Agent SDK 提供強大的權限控制,讓您能夠管理 Claude 在應用程式中如何使用工具。
本指南涵蓋如何使用 canUseTool 回呼、hooks 和 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: "Help me refactor this code",
options: {
permissionMode: 'default' // Standard permission mode
}
});在串流工作階段期間變更模式:
import { query } from "@anthropic-ai/claude-agent-sdk";
// Create an async generator for streaming input
async function* streamInput() {
yield {
type: 'user',
message: {
role: 'user',
content: "Let's start with default permissions"
}
};
// Later in the conversation...
yield {
type: 'user',
message: {
role: 'user',
content: "Now let's speed up development"
}
};
}
const q = query({
prompt: streamInput(),
options: {
permissionMode: 'default' // Start in default mode
}
});
// Change mode dynamically
await q.setPermissionMode('acceptEdits');
// Process messages
for await (const message of q) {
console.log(message);
}acceptEdits)在接受編輯模式中:
自動核准的操作:
bypassPermissions)在繞過權限模式中:
權限模式在權限流程中的特定點進行評估:
bypassPermissions 模式 - 如果啟用,允許所有剩餘工具canUseTool 回呼canUseTool 回呼 - 處理剩餘情況這意味著:
bypassPermissions 模式中bypassPermissions 模式會覆蓋不符合工具的 canUseTool 回呼模式進度的範例:
// Start in default mode for controlled execution
permissionMode: 'default'
// Switch to acceptEdits for rapid iteration
await q.setPermissionMode('acceptEdits')canUseTool 回呼在呼叫 query 函式時作為選項傳遞。它接收工具名稱和輸入參數,並必須返回決定 - 允許或拒絕。
canUseTool 在 Claude Code 會向使用者顯示權限提示時觸發,例如 hooks 和權限規則未涵蓋它且不在 acceptEdits 模式中。
以下是一個完整的範例,顯示如何實現互動式工具核准:
import { query } from "@anthropic-ai/claude-agent-sdk";
async function promptForToolApproval(toolName: string, input: any) {
console.log("\n🔧 Tool Request:");
console.log(` Tool: ${toolName}`);
// Display tool parameters
if (input && Object.keys(input).length > 0) {
console.log(" Parameters:");
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}`);
}
}
// Get user approval (replace with your UI logic)
const approved = await getUserApproval();
if (approved) {
console.log(" ✅ Approved\n");
return {
behavior: "allow",
updatedInput: input
};
} else {
console.log(" ❌ Denied\n");
return {
behavior: "deny",
message: "User denied permission for this tool"
};
}
}
// Use the permission callback
const result = await query({
prompt: "Help me analyze this codebase",
options: {
canUseTool: async (toolName, input) => {
return promptForToolApproval(toolName, input);
}
}
});AskUserQuestion 工具允許 Claude 在對話期間向使用者提出澄清問題。當呼叫此工具時,您的 canUseTool 回呼會接收問題並必須返回使用者的答案。
當使用 toolName: "AskUserQuestion" 呼叫 canUseTool 時,輸入包含:
{
questions: [
{
question: "Which database should we use?",
header: "Database",
options: [
{ label: "PostgreSQL", description: "Relational, ACID compliant" },
{ label: "MongoDB", description: "Document-based, flexible schema" }
],
multiSelect: false
},
{
question: "Which features should we enable?",
header: "Features",
options: [
{ label: "Authentication", description: "User login and sessions" },
{ label: "Logging", description: "Request and error logging" },
{ label: "Caching", description: "Redis-based response caching" }
],
multiSelect: true
}
]
}在 updatedInput.answers 中返回答案,作為將問題文字對應到所選選項標籤的記錄:
return {
behavior: "allow",
updatedInput: {
questions: input.questions, // Pass through original questions
answers: {
"Which database should we use?": "PostgreSQL",
"Which features should we enable?": "Authentication, Caching"
}
}
}多選答案是逗號分隔的字串(例如 "Authentication, Caching")。