npm install @anthropic-ai/claude-agent-sdk
SDK 為您的平台捆綁了一個原生 Claude Code 二進制文件作為可選依賴項,例如 @anthropic-ai/claude-agent-sdk-darwin-arm64。您不需要單獨安裝 Claude Code。如果您的包管理器跳過可選依賴項,SDK 會拋出 Native CLI binary for <platform> not found;改為將 pathToClaudeCodeExecutable 設置為單獨安裝的 claude 二進制文件。
query()
與 Claude Code 互動的主要函數。創建一個異步生成器,在消息到達時流式傳輸消息。
function query({
prompt,
options
}: {
prompt: string | AsyncIterable<SDKUserMessage>;
options?: Options;
}): Query;
| 參數 | 類型 | 描述 |
|---|
prompt | string | AsyncIterable<SDKUserMessage> | 輸入提示,可以是字符串或異步可迭代對象用於流式模式 |
options | Options | 可選配置對象(見下面的 Options 類型) |
返回值
返回一個 Query 對象,它擴展了 AsyncGenerator<SDKMessage, void> 並具有額外的方法。
startup()
通過生成 CLI 子進程並在提示可用之前完成初始化握手來預熱 CLI 子進程。返回的 WarmQuery 句柄稍後接受提示並將其寫入已準備好的進程,因此第一個 query() 調用解析時無需支付子進程生成和初始化成本。
function startup(params?: {
options?: Options;
initializeTimeoutMs?: number;
}): Promise<WarmQuery>;
| 參數 | 類型 | 描述 |
|---|
options | Options | 可選配置對象。與 query() 的 options 參數相同 |
initializeTimeoutMs | number | 等待子進程初始化的最大時間(毫秒)。默認為 60000。如果初始化未在時間內完成,promise 將以超時錯誤拒絕 |
返回值
返回一個 Promise<WarmQuery>,在子進程生成並完成其初始化握手後解析。
早期調用 startup(),例如在應用程序啟動時,然後在提示準備好後在返回的句柄上調用 .query()。這將子進程生成和初始化移出關鍵路徑。
import { startup } from "@anthropic-ai/claude-agent-sdk";
// 提前支付啟動成本
const warm = await startup({ options: { maxTurns: 3 } });
// 稍後,當提示準備好時,這是立即的
for await (const message of warm.query("What files are here?")) {
console.log(message);
}
為與 SDK MCP 服務器一起使用創建類型安全的 MCP 工具定義。
function tool<Schema extends AnyZodRawShape>(
name: string,
description: string,
inputSchema: Schema,
handler: (args: InferShape<Schema>, extra: unknown) => Promise<CallToolResult>,
extras?: { annotations?: ToolAnnotations }
): SdkMcpToolDefinition<Schema>;
| 參數 | 類型 | 描述 |
|---|
name | string | 工具的名稱 |
description | string | 工具功能的描述 |
inputSchema | Schema extends AnyZodRawShape | 定義工具輸入參數的 Zod 架構(支持 Zod 3 和 Zod 4) |
handler | (args, extra) => Promise<CallToolResult> | 執行工具邏輯的異步函數 |
extras | { annotations?: ToolAnnotations } | 可選的 MCP 工具註釋,為客戶端提供行為提示 |
從 @modelcontextprotocol/sdk/types.js 重新導出。所有字段都是可選提示;客戶端不應依賴它們進行安全決策。
| 字段 | 類型 | 默認值 | 描述 |
|---|
title | string | undefined | 工具的人類可讀標題 |
readOnlyHint | boolean | false | 如果為 true,工具不會修改其環境 |
destructiveHint | boolean | true | 如果為 true,工具可能執行破壞性更新(僅在 readOnlyHint 為 false 時有意義) |
idempotentHint | boolean | false | 如果為 true,使用相同參數的重複調用沒有額外效果(僅在 readOnlyHint 為 false 時有意義) |
openWorldHint | boolean | true | 如果為 true,工具與外部實體交互(例如,網絡搜索)。如果為 false,工具的域是封閉的(例如,記憶工具) |
import { tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
const searchTool = tool(
"search",
"Search the web",
{ query: z.string() },
async ({ query }) => {
return { content: [{ type: "text", text: `Results for: ${query}` }] };
},
{ annotations: { readOnlyHint: true, openWorldHint: true } }
);
createSdkMcpServer()
創建在與應用程序相同的進程中運行的 MCP 服務器實例。
function createSdkMcpServer(options: {
name: string;
version?: string;
tools?: Array<SdkMcpToolDefinition<any>>;
}): McpSdkServerConfigWithInstance;
| 參數 | 類型 | 描述 |
|---|
options.name | string | MCP 服務器的名稱 |
options.version | string | 可選版本字符串 |
options.tools | Array<SdkMcpToolDefinition> | 使用 tool() 創建的工具定義數組 |
listSessions()
發現並列出具有輕量級元數據的過去會話。按項目目錄篩選或列出所有項目中的會話。
function listSessions(options?: ListSessionsOptions): Promise<SDKSessionInfo[]>;
| 參數 | 類型 | 默認值 | 描述 |
|---|
options.dir | string | undefined | 列出會話的目錄。省略時,返回所有項目中的會話 |
options.limit | number | undefined | 返回的最大會話數 |
options.includeWorktrees | boolean | true | 當 dir 在 git 存儲庫內時,包括來自所有 worktree 路徑的會話 |
返回類型:SDKSessionInfo
| 屬性 | 類型 | 描述 |
|---|
sessionId | string | 唯一會話標識符(UUID) |
summary | string | 顯示標題:自定義標題、自動生成的摘要或第一個提示 |
lastModified | number | 上次修改時間(自紀元以來的毫秒數) |
fileSize | number | undefined | 會話文件大小(字節)。僅針對本地 JSONL 存儲填充 |
customTitle | string | undefined | 用戶設置的會話標題(通過 /rename) |
firstPrompt | string | undefined | 會話中的第一個有意義的用戶提示 |
gitBranch | string | undefined | 會話結束時的 Git 分支 |
cwd | string | undefined | 會話的工作目錄 |
tag | string | undefined | 用戶設置的會話標籤(見 tagSession()) |
createdAt | number | undefined | 創建時間(自紀元以來的毫秒數),來自第一個條目的時間戳 |
打印項目的 10 個最近會話。結果按 lastModified 降序排序,因此第一項是最新的。省略 dir 以搜索所有項目。
import { listSessions } from "@anthropic-ai/claude-agent-sdk";
const sessions = await listSessions({ dir: "/path/to/project", limit: 10 });
for (const session of sessions) {
console.log(`${session.summary} (${session.sessionId})`);
}
getSessionMessages()
從過去的會話記錄中讀取用戶和助手消息。
function getSessionMessages(
sessionId: string,
options?: GetSessionMessagesOptions
): Promise<SessionMessage[]>;
| 參數 | 類型 | 默認值 | 描述 |
|---|
sessionId | string | 必需 | 要讀取的會話 UUID(見 listSessions()) |
options.dir | string | undefined | 查找會話的項目目錄。省略時,搜索所有項目 |
options.limit | number | undefined | 返回的最大消息數 |
options.offset | number | undefined | 從開始跳過的消息數 |
返回類型:SessionMessage
| 屬性 | 類型 | 描述 |
|---|
type | "user" | "assistant" | 消息角色 |
uuid | string | 唯一消息標識符 |
session_id | string | 此消息所屬的會話 |
message | unknown | 來自記錄的原始消息有效負載 |
parent_tool_use_id | null | 保留 |
import { listSessions, getSessionMessages } from "@anthropic-ai/claude-agent-sdk";
const [latest] = await listSessions({ dir: "/path/to/project", limit: 1 });
if (latest) {
const messages = await getSessionMessages(latest.sessionId, {
dir: "/path/to/project",
limit: 20
});
for (const msg of messages) {
console.log(`[${msg.type}] ${msg.uuid}`);
}
}
getSessionInfo()
按 ID 讀取單個會話的元數據,無需掃描完整項目目錄。
function getSessionInfo(
sessionId: string,
options?: GetSessionInfoOptions
): Promise<SDKSessionInfo | undefined>;
| 參數 | 類型 | 默認值 | 描述 |
|---|
sessionId | string | 必需 | 要查找的會話 UUID |
options.dir | string | undefined | 項目目錄路徑。省略時,搜索所有項目目錄 |
返回 SDKSessionInfo,如果找不到會話則返回 undefined。
renameSession()
通過附加自定義標題條目來重命名會話。重複調用是安全的;最新的標題獲勝。
function renameSession(
sessionId: string,
title: string,
options?: SessionMutationOptions
): Promise<void>;
| 參數 | 類型 | 默認值 | 描述 |
|---|
sessionId | string | 必需 | 要重命名的會話 UUID |
title | string | 必需 | 新標題。修剪空格後必須非空 |
options.dir | string | undefined | 項目目錄路徑。省略時,搜索所有項目目錄 |
標記會話。傳遞 null 以清除標籤。重複調用是安全的;最新的標籤獲勝。
function tagSession(
sessionId: string,
tag: string | null,
options?: SessionMutationOptions
): Promise<void>;
| 參數 | 類型 | 默認值 | 描述 |
|---|
sessionId | string | 必需 | 要標記的會話 UUID |
tag | string | null | 必需 | 標籤字符串,或 null 以清除 |
options.dir | string | undefined | 項目目錄路徑。省略時,搜索所有項目目錄 |
Options
query() 函數的配置對象。
| 屬性 | 類型 | 默認值 | 描述 |
|---|
abortController | AbortController | new AbortController() | 用於取消操作的控制器 |
additionalDirectories | string[] | [] | Claude 可以訪問的其他目錄 |
agent | string | undefined | 主線程的代理名稱。代理必須在 agents 選項或設置中定義 |
agents | Record<string, [AgentDefinition](#agent-definition)> | undefined | 以編程方式定義子代理 |
allowDangerouslySkipPermissions | boolean | false | 啟用繞過權限。使用 permissionMode: 'bypassPermissions' 時需要 |
allowedTools | string[] | [] | 無需提示即可自動批准的工具。這不會將 Claude 限制為僅這些工具;未列出的工具會進入 permissionMode 和 canUseTool。使用 disallowedTools 來阻止工具。見 權限 |
betas | SdkBeta[] | [] | 啟用測試功能 |
canUseTool | CanUseTool | undefined | 工具使用的自定義權限函數 |
continue | boolean | false | 繼續最近的對話 |
cwd | string | process.cwd() | 當前工作目錄 |
debug | boolean | false | 為 Claude Code 進程啟用調試模式 |
debugFile | string | undefined | 將調試日誌寫入特定文件路徑。隱式啟用調試模式 |
disallowedTools | string[] | [] | 始終拒絕的工具。拒絕規則首先檢查並覆蓋 allowedTools 和 permissionMode(包括 bypassPermissions) |
effort | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'high' | 控制 Claude 在其響應中投入多少努力。與自適應思考一起工作以指導思考深度 |
enableFileCheckpointing | boolean | false | 啟用文件更改跟蹤以進行回滾。見 文件檢查點 |
env | Record<string, string | undefined> | process.env | 環境變量。設置 CLAUDE_AGENT_SDK_CLIENT_APP 以在 User-Agent 標頭中標識您的應用程序 |
executable | 'bun' | 'deno' | 'node' | 自動檢測 | 要使用的 JavaScript 運行時 |
executableArgs | string[] | [] | 傳遞給可執行文件的參數 |
extraArgs | Record<string, string | null> | {} | 其他參數 |
fallbackModel | string | undefined | 主模型失敗時使用的模型 |
forkSession | boolean | false | 使用 resume 恢復時,分叉到新會話 ID 而不是繼續原始會話 |
hooks | Partial<Record<HookEvent, HookCallbackMatcher[]>> | {} | 事件的 Hook 回調 |
includePartialMessages | boolean | false | 包括部分消息事件 |
maxBudgetUsd | number | undefined | 當客戶端成本估計達到此 USD 值時停止查詢。與 total_cost_usd 的相同估計進行比較;見 跟蹤成本和使用情況 了解準確性注意事項 |
maxThinkingTokens | number | undefined | 已棄用: 改用 thinking。思考過程的最大令牌數 |
maxTurns | number | undefined | 最大代理轉數(工具使用往返) |
mcpServers | Record<string, [McpServerConfig](#mcp-server-config)> | {} | MCP 服務器配置 |
model | string | CLI 默認值 | 要使用的 Claude 模型 |
outputFormat | { type: 'json_schema', schema: JSONSchema } | undefined | 為代理結果定義輸出格式。見 結構化輸出 了解詳情 |
pathToClaudeCodeExecutable | string | 從捆綁的原生二進制文件自動解析 | Claude Code 可執行文件的路徑。僅在安裝期間跳過可選依賴項或您的平台不在支持的集合中時需要 |
permissionMode | PermissionMode | 'default' | 會話的權限模式 |
permissionPromptToolName | string | undefined | 權限提示的 MCP 工具名稱 |
persistSession | boolean | true | 當為 false 時,禁用會話持久化到磁盤。會話之後無法恢復 |
plugins | SdkPluginConfig[] | [] | 從本地路徑加載自定義插件。見 插件 了解詳情 |
promptSuggestions | boolean | false | 啟用提示建議。在每個轉數後發出 prompt_suggestion 消息,帶有預測的下一個用戶提示 |
resume | string | undefined | 要恢復的會話 ID |
resumeSessionAt | string | undefined | 在特定消息 UUID 處恢復會話 |
sandbox | SandboxSettings | undefined | 以編程方式配置沙箱行為。見 沙箱設置 了解詳情 |
sessionId | string | 自動生成 | 使用特定 UUID 作為會話,而不是自動生成一個 |
settingSources | SettingSource[] | CLI 默認值(所有源) | 控制加載哪些文件系統設置。傳遞 [] 以禁用用戶、項目和本地設置。無論如何都會加載託管策略設置。見 使用 Claude Code 功能 |
spawnClaudeCodeProcess | (options: SpawnOptions) => SpawnedProcess | undefined | 用於生成 Claude Code 進程的自定義函數。用於在 VM、容器或遠程環境中運行 Claude Code |
stderr | (data: string) => void | undefined | stderr 輸出的回調 |
strictMcpConfig | boolean | false | 強制執行嚴格的 MCP 驗證 |
systemPrompt | string | { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean } | undefined(最小提示) | 系統提示配置。傳遞字符串以獲得自定義提示,或 { type: 'preset', preset: 'claude_code' } 以使用 Claude Code 的系統提示。使用預設對象形式時,添加 append 以使用其他指令擴展它,並設置 excludeDynamicSections: true 以將每個會話上下文移到第一個用戶消息中以獲得 跨機器更好的提示緩存重用 |
thinking | ThinkingConfig | 支持的模型為 { type: 'adaptive' } | 控制 Claude 的思考/推理行為。見 ThinkingConfig 了解選項 |
toolConfig | ToolConfig | undefined | 內置工具行為的配置。見 ToolConfig 了解詳情 |
tools | string[] | { type: 'preset'; preset: 'claude_code' } | undefined | 工具配置。傳遞工具名稱數組或使用預設以獲得 Claude Code 的默認工具 |
Query 對象
由 query() 函數返回的介面。
interface Query extends AsyncGenerator<SDKMessage, void> {
interrupt(): Promise<void>;
rewindFiles(
userMessageId: string,
options?: { dryRun?: boolean }
): Promise<RewindFilesResult>;
setPermissionMode(mode: PermissionMode): Promise<void>;
setModel(model?: string): Promise<void>;
setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;
initializationResult(): Promise<SDKControlInitializeResponse>;
supportedCommands(): Promise<SlashCommand[]>;
supportedModels(): Promise<ModelInfo[]>;
supportedAgents(): Promise<AgentInfo[]>;
mcpServerStatus(): Promise<McpServerStatus[]>;
accountInfo(): Promise<AccountInfo>;
reconnectMcpServer(serverName: string): Promise<void>;
toggleMcpServer(serverName: string, enabled: boolean): Promise<void>;
setMcpServers(servers: Record<string, McpServerConfig>): Promise<McpSetServersResult>;
streamInput(stream: AsyncIterable<SDKUserMessage>): Promise<void>;
stopTask(taskId: string): Promise<void>;
close(): void;
}
| 方法 | 描述 |
|---|
interrupt() | 中斷查詢(僅在流式輸入模式下可用) |
rewindFiles(userMessageId, options?) | 將文件恢復到指定用戶消息時的狀態。傳遞 { dryRun: true } 以預覽更改。需要 enableFileCheckpointing: true。見 文件檢查點 |
setPermissionMode() | 更改權限模式(僅在流式輸入模式下可用) |
setModel() | 更改模型(僅在流式輸入模式下可用) |
setMaxThinkingTokens() | 已棄用: 改用 thinking 選項。更改最大思考令牌 |
initializationResult() | 返回完整的初始化結果,包括支持的命令、模型、帳戶信息和輸出樣式配置 |
supportedCommands() | 返回可用的 slash commands |
supportedModels() | 返回具有顯示信息的可用模型 |
supportedAgents() | 返回可通過 Agent 工具調用的可用子代理,作為 AgentInfo[] |
mcpServerStatus() | 返回連接的 MCP 服務器的狀態 |
accountInfo() | 返回帳戶信息 |
reconnectMcpServer(serverName) | 按名稱重新連接 MCP 服務器 |
toggleMcpServer(serverName, enabled) | 按名稱啟用或禁用 MCP 服務器 |
setMcpServers(servers) | 動態替換此會話的 MCP 服務器集。返回有關添加、刪除的服務器和任何錯誤的信息 |
streamInput(stream) | 將輸入消息流式傳輸到查詢以進行多輪對話 |
stopTask(taskId) | 按 ID 停止運行的後台任務 |
close() | 關閉查詢並終止底層進程。強制結束查詢並清理所有資源 |
WarmQuery
由 startup() 返回的句柄。子進程已生成並初始化,因此在此句柄上調用 query() 會直接將提示寫入準備好的進程,無需啟動延遲。
interface WarmQuery extends AsyncDisposable {
query(prompt: string | AsyncIterable<SDKUserMessage>): Query;
close(): void;
}
| 方法 | 描述 |
|---|
query(prompt) | 向預熱的子進程發送提示並返回 Query。每個 WarmQuery 只能調用一次 |
close() | 關閉子進程而不發送提示。使用此方法丟棄不再需要的預熱查詢 |
WarmQuery 實現 AsyncDisposable,因此可以與 await using 一起使用以進行自動清理。
SDKControlInitializeResponse
initializationResult() 的返回類型。包含會話初始化數據。
type SDKControlInitializeResponse = {
commands: SlashCommand[];
agents: AgentInfo[];
output_style: string;
available_output_styles: string[];
models: ModelInfo[];
account: AccountInfo;
fast_mode_state?: "off" | "cooldown" | "on";
};
AgentDefinition
以編程方式定義的子代理的配置。
type AgentDefinition = {
description: string;
tools?: string[];
disallowedTools?: string[];
prompt: string;
model?: "sonnet" | "opus" | "haiku" | "inherit";
mcpServers?: AgentMcpServerSpec[];
skills?: string[];
maxTurns?: number;
criticalSystemReminder_EXPERIMENTAL?: string;
};
| 字段 | 必需 | 描述 |
|---|
description | 是 | 何時使用此代理的自然語言描述 |
tools | 否 | 允許的工具名稱數組。如果省略,從父代理繼承所有工具 |
disallowedTools | 否 | 要為此代理明確禁止的工具名稱數組 |
prompt | 是 | 代理的系統提示 |
model | 否 | 此代理的模型覆蓋。如果省略或 'inherit',使用主模型 |
mcpServers | 否 | 此代理可用的 MCP 服務器規範 |
skills | 否 | 要預加載到代理上下文中的技能名稱數組 |
maxTurns | 否 | 最大代理轉數(API 往返),然後停止 |
criticalSystemReminder_EXPERIMENTAL | 否 | 實驗性:添加到系統提示的關鍵提醒 |
AgentMcpServerSpec
指定子代理可用的 MCP 服務器。可以是服務器名稱(字符串,引用父代理 mcpServers 配置中的服務器)或內聯服務器配置記錄,將服務器名稱映射到配置。
type AgentMcpServerSpec = string | Record<string, McpServerConfigForProcessTransport>;
其中 McpServerConfigForProcessTransport 是 McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig。
SettingSource
控制 SDK 從哪些基於文件系統的配置源加載設置。
type SettingSource = "user" | "project" | "local";
| 值 | 描述 | 位置 |
|---|
'user' | 全局用戶設置 | ~/.claude/settings.json |
'project' | 共享項目設置(版本控制) | .claude/settings.json |
'local' | 本地項目設置(gitignored) | .claude/settings.local.json |
默認行為
當 settingSources 被省略或 undefined 時,query() 加載與 Claude Code CLI 相同的文件系統設置:用戶、項目和本地。託管策略設置在所有情況下都會加載。見 settingSources 不控制什麼 了解無論此選項如何都會讀取的輸入,以及如何禁用它們。
為什麼使用 settingSources
禁用文件系統設置:
// 不從磁盤加載用戶、項目或本地設置
const result = query({
prompt: "Analyze this code",
options: { settingSources: [] }
});
明確加載所有文件系統設置:
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 應用程序:
// 以編程方式定義所有內容。
// 傳遞 [] 以選擇退出文件系統設置源。
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 Code 的系統提示
},
settingSources: ["project"], // 從項目目錄加載 CLAUDE.md
allowedTools: ["Read", "Write", "Edit"]
}
});
設置優先級
加載多個源時,設置按此優先級(最高到最低)合併:
- 本地設置(
.claude/settings.local.json)
- 項目設置(
.claude/settings.json)
- 用戶設置(
~/.claude/settings.json)
編程選項(如 agents 和 allowedTools)覆蓋用戶、項目和本地文件系統設置。託管策略設置優先於編程選項。
PermissionMode
type PermissionMode =
| "default" // 標準權限行為
| "acceptEdits" // 自動接受文件編輯
| "bypassPermissions" // 繞過所有權限檢查
| "plan" // 規劃模式 - 無執行
| "dontAsk" // 不提示權限,如果未預批准則拒絕
| "auto"; // 使用模型分類器批准或拒絕每個工具調用
用於控制工具使用的自定義權限函數類型。
type CanUseTool = (
toolName: string,
input: Record<string, unknown>,
options: {
signal: AbortSignal;
suggestions?: PermissionUpdate[];
blockedPath?: string;
decisionReason?: string;
toolUseID: string;
agentID?: string;
}
) => Promise<PermissionResult>;
| 選項 | 類型 | 描述 |
|---|
signal | AbortSignal | 如果應中止操作則發出信號 |
suggestions | PermissionUpdate[] | 建議的權限更新,以便用戶不會再次被提示此工具 |
blockedPath | string | 觸發權限請求的文件路徑(如果適用) |
decisionReason | string | 解釋為什麼觸發此權限請求 |
toolUseID | string | 此特定工具調用在助手消息中的唯一標識符 |
agentID | string | 如果在子代理中運行,子代理的 ID |
PermissionResult
權限檢查的結果。
type PermissionResult =
| {
behavior: "allow";
updatedInput?: Record<string, unknown>;
updatedPermissions?: PermissionUpdate[];
toolUseID?: string;
}
| {
behavior: "deny";
message: string;
interrupt?: boolean;
toolUseID?: string;
};
內置工具行為的配置。
type ToolConfig = {
askUserQuestion?: {
previewFormat?: "markdown" | "html";
};
};
| 字段 | 類型 | 描述 |
|---|
askUserQuestion.previewFormat | 'markdown' | 'html' | 選擇進入 AskUserQuestion 選項上的 preview 字段並設置其內容格式。未設置時,Claude 不發出預覽 |
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;
};
McpClaudeAIProxyServerConfig
type McpClaudeAIProxyServerConfig = {
type: "claudeai-proxy";
url: string;
id: string;
};
SdkPluginConfig
SDK 中加載插件的配置。
type SdkPluginConfig = {
type: "local";
path: string;
};
| 字段 | 類型 | 描述 |
|---|
type | 'local' | 必須是 'local'(目前僅支持本地插件) |
path | string | 插件目錄的絕對或相對路徑 |
示例:
plugins: [
{ type: "local", path: "./my-plugin" },
{ type: "local", path: "/absolute/path/to/plugin" }
];
有關創建和使用插件的完整信息,見 插件。
消息類型
SDKMessage
查詢返回的所有可能消息的聯合類型。
type SDKMessage =
| SDKAssistantMessage
| SDKUserMessage
| SDKUserMessageReplay
| SDKResultMessage
| SDKSystemMessage
| SDKPartialAssistantMessage
| SDKCompactBoundaryMessage
| SDKStatusMessage
| SDKLocalCommandOutputMessage
| SDKHookStartedMessage
| SDKHookProgressMessage
| SDKHookResponseMessage
| SDKPluginInstallMessage
| SDKToolProgressMessage
| SDKAuthStatusMessage
| SDKTaskNotificationMessage
| SDKTaskStartedMessage
| SDKTaskProgressMessage
| SDKFilesPersistedEvent
| SDKToolUseSummaryMessage
| SDKRateLimitEvent
| SDKPromptSuggestionMessage;
SDKAssistantMessage
助手響應消息。
type SDKAssistantMessage = {
type: "assistant";
uuid: UUID;
session_id: string;
message: BetaMessage; // 來自 Anthropic SDK
parent_tool_use_id: string | null;
error?: SDKAssistantMessageError;
};
message 字段是來自 Anthropic SDK 的 BetaMessage。它包括 id、content、model、stop_reason 和 usage 等字段。
SDKAssistantMessageError 是以下之一:'authentication_failed'、'billing_error'、'rate_limit'、'invalid_request'、'server_error'、'max_output_tokens' 或 'unknown'。
SDKUserMessage
用戶輸入消息。
type SDKUserMessage = {
type: "user";
uuid?: UUID;
session_id: string;
message: MessageParam; // 來自 Anthropic SDK
parent_tool_use_id: string | null;
isSynthetic?: boolean;
shouldQuery?: boolean;
tool_use_result?: unknown;
};
將 shouldQuery 設置為 false 以將消息附加到記錄而不觸發助手轉數。消息被保留並合併到下一個觸發轉數的用戶消息中。使用此方法注入上下文,例如您在帶外運行的命令的輸出,而無需在其上花費模型調用。
SDKUserMessageReplay
帶有必需 UUID 的重放用戶消息。
type SDKUserMessageReplay = {
type: "user";
uuid: UUID;
session_id: string;
message: MessageParam;
parent_tool_use_id: string | null;
isSynthetic?: boolean;
tool_use_result?: unknown;
isReplay: true;
};
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;
stop_reason: string | null;
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;
stop_reason: string | null;
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;
agents?: string[];
apiKeySource: ApiKeySource;
betas?: string[];
claude_code_version: string;
cwd: string;
tools: string[];
mcp_servers: {
name: string;
status: string;
}[];
model: string;
permissionMode: PermissionMode;
slash_commands: string[];
output_style: string;
skills: string[];
plugins: { name: string; path: string }[];
};
SDKPartialAssistantMessage
流式部分消息(僅當 includePartialMessages 為 true 時)。
type SDKPartialAssistantMessage = {
type: "stream_event";
event: BetaRawMessageStreamEvent; // 來自 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;
};
};
SDKPluginInstallMessage
插件安裝進度事件。當設置 CLAUDE_CODE_SYNC_PLUGIN_INSTALL 時發出,以便您的 Agent SDK 應用程序可以在第一個轉數之前跟蹤市場插件安裝。started 和 completed 狀態括起整體安裝。installed 和 failed 狀態報告單個市場並包括 name。
type SDKPluginInstallMessage = {
type: "system";
subtype: "plugin_install";
status: "started" | "installed" | "failed" | "completed";
name?: string;
error?: string;
uuid: UUID;
session_id: string;
};
SDKPermissionDenial
有關被拒絕的工具使用的信息。
type SDKPermissionDenial = {
tool_name: string;
tool_use_id: string;
tool_input: Record<string, unknown>;
};
Hook 類型
有關使用 hooks 的綜合指南,包括示例和常見模式,見 Hooks 指南。
HookEvent
可用的 hook 事件。
type HookEvent =
| "PreToolUse"
| "PostToolUse"
| "PostToolUseFailure"
| "Notification"
| "UserPromptSubmit"
| "SessionStart"
| "SessionEnd"
| "Stop"
| "SubagentStart"
| "SubagentStop"
| "PreCompact"
| "PermissionRequest"
| "Setup"
| "TeammateIdle"
| "TaskCompleted"
| "ConfigChange"
| "WorktreeCreate"
| "WorktreeRemove";
HookCallback
Hook 回調函數類型。
type HookCallback = (
input: HookInput, // 所有 hook 輸入類型的聯合
toolUseID: string | undefined,
options: { signal: AbortSignal }
) => Promise<HookJSONOutput>;
HookCallbackMatcher
帶有可選匹配器的 Hook 配置。
interface HookCallbackMatcher {
matcher?: string;
hooks: HookCallback[];
timeout?: number; // 此匹配器中所有 hooks 的超時時間(秒)
}
所有 hook 輸入類型的聯合類型。
type HookInput =
| PreToolUseHookInput
| PostToolUseHookInput
| PostToolUseFailureHookInput
| NotificationHookInput
| UserPromptSubmitHookInput
| SessionStartHookInput
| SessionEndHookInput
| StopHookInput
| SubagentStartHookInput
| SubagentStopHookInput
| PreCompactHookInput
| PermissionRequestHookInput
| SetupHookInput
| TeammateIdleHookInput
| TaskCompletedHookInput
| ConfigChangeHookInput
| WorktreeCreateHookInput
| WorktreeRemoveHookInput;
所有 hook 輸入類型擴展的基本介面。
type BaseHookInput = {
session_id: string;
transcript_path: string;
cwd: string;
permission_mode?: string;
agent_id?: string;
agent_type?: string;
};
type PreToolUseHookInput = BaseHookInput & {
hook_event_name: "PreToolUse";
tool_name: string;
tool_input: unknown;
tool_use_id: string;
};
PostToolUseHookInput
type PostToolUseHookInput = BaseHookInput & {
hook_event_name: "PostToolUse";
tool_name: string;
tool_input: unknown;
tool_response: unknown;
tool_use_id: string;
};
PostToolUseFailureHookInput
type PostToolUseFailureHookInput = BaseHookInput & {
hook_event_name: "PostToolUseFailure";
tool_name: string;
tool_input: unknown;
tool_use_id: string;
error: string;
is_interrupt?: boolean;
};
type NotificationHookInput = BaseHookInput & {
hook_event_name: "Notification";
message: string;
title?: string;
notification_type: string;
};
type UserPromptSubmitHookInput = BaseHookInput & {
hook_event_name: "UserPromptSubmit";
prompt: string;
};
type SessionStartHookInput = BaseHookInput & {
hook_event_name: "SessionStart";
source: "startup" | "resume" | "clear" | "compact";
agent_type?: string;
model?: string;
};
type SessionEndHookInput = BaseHookInput & {
hook_event_name: "SessionEnd";
reason: ExitReason; // EXIT_REASONS 數組中的字符串
};
type StopHookInput = BaseHookInput & {
hook_event_name: "Stop";
stop_hook_active: boolean;
last_assistant_message?: string;
};
type SubagentStartHookInput = BaseHookInput & {
hook_event_name: "SubagentStart";
agent_id: string;
agent_type: string;
};
type SubagentStopHookInput = BaseHookInput & {
hook_event_name: "SubagentStop";
stop_hook_active: boolean;
agent_id: string;
agent_transcript_path: string;
agent_type: string;
last_assistant_message?: string;
};
type PreCompactHookInput = BaseHookInput & {
hook_event_name: "PreCompact";
trigger: "manual" | "auto";
custom_instructions: string | null;
};
type PermissionRequestHookInput = BaseHookInput & {
hook_event_name: "PermissionRequest";
tool_name: string;
tool_input: unknown;
permission_suggestions?: PermissionUpdate[];
};
type SetupHookInput = BaseHookInput & {
hook_event_name: "Setup";
trigger: "init" | "maintenance";
};
type TeammateIdleHookInput = BaseHookInput & {
hook_event_name: "TeammateIdle";
teammate_name: string;
team_name: string;
};
type TaskCompletedHookInput = BaseHookInput & {
hook_event_name: "TaskCompleted";
task_id: string;
task_subject: string;
task_description?: string;
teammate_name?: string;
team_name?: string;
};
type ConfigChangeHookInput = BaseHookInput & {
hook_event_name: "ConfigChange";
source:
| "user_settings"
| "project_settings"
| "local_settings"
| "policy_settings"
| "skills";
file_path?: string;
};
type WorktreeCreateHookInput = BaseHookInput & {
hook_event_name: "WorktreeCreate";
name: string;
};
type WorktreeRemoveHookInput = BaseHookInput & {
hook_event_name: "WorktreeRemove";
worktree_path: string;
};
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>;
additionalContext?: string;
}
| {
hookEventName: "UserPromptSubmit";
additionalContext?: string;
}
| {
hookEventName: "SessionStart";
additionalContext?: string;
}
| {
hookEventName: "Setup";
additionalContext?: string;
}
| {
hookEventName: "SubagentStart";
additionalContext?: string;
}
| {
hookEventName: "PostToolUse";
additionalContext?: string;
updatedMCPToolOutput?: unknown;
}
| {
hookEventName: "PostToolUseFailure";
additionalContext?: string;
}
| {
hookEventName: "Notification";
additionalContext?: string;
}
| {
hookEventName: "PermissionRequest";
decision:
| {
behavior: "allow";
updatedInput?: Record<string, unknown>;
updatedPermissions?: PermissionUpdate[];
}
| {
behavior: "deny";
message?: string;
interrupt?: boolean;
};
};
};
工具輸入類型
所有內置 Claude Code 工具的輸入架構文檔。這些類型從 @anthropic-ai/claude-agent-sdk 導出,可用於類型安全的工具交互。
所有工具輸入類型的聯合,從 @anthropic-ai/claude-agent-sdk 導出。
type ToolInputSchemas =
| AgentInput
| AskUserQuestionInput
| BashInput
| TaskOutputInput
| ConfigInput
| EnterWorktreeInput
| ExitPlanModeInput
| FileEditInput
| FileReadInput
| FileWriteInput
| GlobInput
| GrepInput
| ListMcpResourcesInput
| McpInput
| MonitorInput
| NotebookEditInput
| ReadMcpResourceInput
| SubscribeMcpResourceInput
| SubscribePollingInput
| TaskStopInput
| TodoWriteInput
| UnsubscribeMcpResourceInput
| UnsubscribePollingInput
| WebFetchInput
| WebSearchInput;
Agent
工具名稱: Agent(之前是 Task,仍然接受作為別名)
type AgentInput = {
description: string;
prompt: string;
subagent_type: string;
model?: "sonnet" | "opus" | "haiku";
resume?: string;
run_in_background?: boolean;
max_turns?: number;
name?: string;
team_name?: string;
mode?: "acceptEdits" | "bypassPermissions" | "default" | "dontAsk" | "plan";
isolation?: "worktree";
};
啟動新代理以自主處理複雜的多步驟任務。
AskUserQuestion
工具名稱: AskUserQuestion
type AskUserQuestionInput = {
questions: Array<{
question: string;
header: string;
options: Array<{ label: string; description: string; preview?: string }>;
multiSelect: boolean;
}>;
};
在執行期間向用戶提出澄清問題。見 處理批准和用戶輸入 了解使用詳情。
Bash
工具名稱: Bash
type BashInput = {
command: string;
timeout?: number;
description?: string;
run_in_background?: boolean;
dangerouslyDisableSandbox?: boolean;
};
在持久 shell 會話中執行 bash 命令,具有可選的超時和後台執行。
Monitor
工具名稱: Monitor
type MonitorInput = {
command: string;
description: string;
timeout_ms?: number;
persistent?: boolean;
};
運行後台腳本並將每個 stdout 行作為事件傳遞給 Claude,以便它可以在不輪詢的情況下做出反應。為會話長度的監視(如日誌尾部)設置 persistent: true。Monitor 遵循與 Bash 相同的權限規則。見 Monitor 工具參考 了解行為和提供商可用性。
TaskOutput
工具名稱: TaskOutput
type TaskOutputInput = {
task_id: string;
block: boolean;
timeout: number;
};
從運行或已完成的後台任務檢索輸出。
Edit
工具名稱: Edit
type FileEditInput = {
file_path: string;
old_string: string;
new_string: string;
replace_all?: boolean;
};
在文件中執行精確字符串替換。
Read
工具名稱: Read
type FileReadInput = {
file_path: string;
offset?: number;
limit?: number;
pages?: string;
};
從本地文件系統讀取文件,包括文本、圖像、PDF 和 Jupyter 筆記本。對 PDF 頁面範圍使用 pages(例如,"1-5")。
Write
工具名稱: Write
type FileWriteInput = {
file_path: string;
content: string;
};
將文件寫入本地文件系統,如果存在則覆蓋。
Glob
工具名稱: Glob
type GlobInput = {
pattern: string;
path?: string;
};
快速文件模式匹配,適用於任何代碼庫大小。
Grep
工具名稱: Grep
type GrepInput = {
pattern: string;
path?: string;
glob?: string;
type?: string;
output_mode?: "content" | "files_with_matches" | "count";
"-i"?: boolean;
"-n"?: boolean;
"-B"?: number;
"-A"?: number;
"-C"?: number;
context?: number;
head_limit?: number;
offset?: number;
multiline?: boolean;
};
基於 ripgrep 的強大搜索工具,支持正則表達式。
TaskStop
工具名稱: TaskStop
type TaskStopInput = {
task_id?: string;
shell_id?: string; // 已棄用:使用 task_id
};
按 ID 停止運行的後台任務或 shell。
NotebookEdit
工具名稱: NotebookEdit
type NotebookEditInput = {
notebook_path: string;
cell_id?: string;
new_source: string;
cell_type?: "code" | "markdown";
edit_mode?: "replace" | "insert" | "delete";
};
編輯 Jupyter 筆記本文件中的單元格。
WebFetch
工具名稱: WebFetch
type WebFetchInput = {
url: string;
prompt: string;
};
從 URL 獲取內容並使用 AI 模型處理它。
WebSearch
工具名稱: WebSearch
type WebSearchInput = {
query: string;
allowed_domains?: string[];
blocked_domains?: string[];
};
搜索網絡並返回格式化結果。
TodoWrite
工具名稱: TodoWrite
type TodoWriteInput = {
todos: Array<{
content: string;
status: "pending" | "in_progress" | "completed";
activeForm: string;
}>;
};
創建和管理結構化任務列表以跟蹤進度。
ExitPlanMode
工具名稱: ExitPlanMode
type ExitPlanModeInput = {
allowedPrompts?: Array<{
tool: "Bash";
prompt: string;
}>;
};
退出規劃模式。可選地指定實施計劃所需的基於提示的權限。
ListMcpResources
工具名稱: ListMcpResources
type ListMcpResourcesInput = {
server?: string;
};
列出來自連接服務器的可用 MCP 資源。
ReadMcpResource
工具名稱: ReadMcpResource
type ReadMcpResourceInput = {
server: string;
uri: string;
};
從服務器讀取特定的 MCP 資源。
Config
工具名稱: Config
type ConfigInput = {
setting: string;
value?: string | boolean | number;
};
獲取或設置配置值。
EnterWorktree
工具名稱: EnterWorktree
type EnterWorktreeInput = {
name?: string;
path?: string;
};
創建並進入臨時 git worktree 以進行隔離工作。傳遞 path 以切換到當前存儲庫的現有 worktree,而不是創建新的。name 和 path 互斥。
工具輸出類型
所有內置 Claude Code 工具的輸出架構文檔。這些類型從 @anthropic-ai/claude-agent-sdk 導出,代表每個工具返回的實際響應數據。
所有工具輸出類型的聯合。
type ToolOutputSchemas =
| AgentOutput
| AskUserQuestionOutput
| BashOutput
| ConfigOutput
| EnterWorktreeOutput
| ExitPlanModeOutput
| FileEditOutput
| FileReadOutput
| FileWriteOutput
| GlobOutput
| GrepOutput
| ListMcpResourcesOutput
| MonitorOutput
| NotebookEditOutput
| ReadMcpResourceOutput
| TaskStopOutput
| TodoWriteOutput
| WebFetchOutput
| WebSearchOutput;
Agent
工具名稱: Agent(之前是 Task,仍然接受作為別名)
type AgentOutput =
| {
status: "completed";
agentId: string;
content: Array<{ type: "text"; text: string }>;
totalToolUseCount: number;
totalDurationMs: number;
totalTokens: number;
usage: {
input_tokens: number;
output_tokens: number;
cache_creation_input_tokens: number | null;
cache_read_input_tokens: number | null;
server_tool_use: {
web_search_requests: number;
web_fetch_requests: number;
} | null;
service_tier: ("standard" | "priority" | "batch") | null;
cache_creation: {
ephemeral_1h_input_tokens: number;
ephemeral_5m_input_tokens: number;
} | null;
};
prompt: string;
}
| {
status: "async_launched";
agentId: string;
description: string;
prompt: string;
outputFile: string;
canReadOutputFile?: boolean;
}
| {
status: "sub_agent_entered";
description: string;
message: string;
};
返回子代理的結果。在 status 字段上區分:"completed" 用於已完成的任務,"async_launched" 用於後台任務,"sub_agent_entered" 用於交互式子代理。
AskUserQuestion
工具名稱: AskUserQuestion
type AskUserQuestionOutput = {
questions: Array<{
question: string;
header: string;
options: Array<{ label: string; description: string; preview?: string }>;
multiSelect: boolean;
}>;
answers: Record<string, string>;
};
返回提出的問題和用戶的答案。
Bash
工具名稱: Bash
type BashOutput = {
stdout: string;
stderr: string;
rawOutputPath?: string;
interrupted: boolean;
isImage?: boolean;
backgroundTaskId?: string;
backgroundedByUser?: boolean;
dangerouslyDisableSandbox?: boolean;
returnCodeInterpretation?: string;
structuredContent?: unknown[];
persistedOutputPath?: string;
persistedOutputSize?: number;
};
返回命令輸出,stdout/stderr 分開。後台命令包括 backgroundTaskId。
Monitor
工具名稱: Monitor
type MonitorOutput = {
taskId: string;
timeoutMs: number;
persistent?: boolean;
};
返回運行監視器的後台任務 ID。使用此 ID 與 TaskStop 一起提前取消監視。
Edit
工具名稱: Edit
type FileEditOutput = {
filePath: string;
oldString: string;
newString: string;
originalFile: string;
structuredPatch: Array<{
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: string[];
}>;
userModified: boolean;
replaceAll: boolean;
gitDiff?: {
filename: string;
status: "modified" | "added";
additions: number;
deletions: number;
changes: number;
patch: string;
};
};
返回編輯操作的結構化差異。
Read
工具名稱: Read
type FileReadOutput =
| {
type: "text";
file: {
filePath: string;
content: string;
numLines: number;
startLine: number;
totalLines: number;
};
}
| {
type: "image";
file: {
base64: string;
type: "image/jpeg" | "image/png" | "image/gif" | "image/webp";
originalSize: number;
dimensions?: {
originalWidth?: number;
originalHeight?: number;
displayWidth?: number;
displayHeight?: number;
};
};
}
| {
type: "notebook";
file: {
filePath: string;
cells: unknown[];
};
}
| {
type: "pdf";
file: {
filePath: string;
base64: string;
originalSize: number;
};
}
| {
type: "parts";
file: {
filePath: string;
originalSize: number;
count: number;
outputDir: string;
};
};
返回適合文件類型的文件內容。在 type 字段上區分。
Write
工具名稱: Write
type FileWriteOutput = {
type: "create" | "update";
filePath: string;
content: string;
structuredPatch: Array<{
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: string[];
}>;
originalFile: string | null;
gitDiff?: {
filename: string;
status: "modified" | "added";
additions: number;
deletions: number;
changes: number;
patch: string;
};
};
返回寫入結果,包含結構化差異信息。
Glob
工具名稱: Glob
type GlobOutput = {
durationMs: number;
numFiles: number;
filenames: string[];
truncated: boolean;
};
返回與 glob 模式匹配的文件路徑,按修改時間排序。
Grep
工具名稱: Grep
type GrepOutput = {
mode?: "content" | "files_with_matches" | "count";
numFiles: number;
filenames: string[];
content?: string;
numLines?: number;
numMatches?: number;
appliedLimit?: number;
appliedOffset?: number;
};
返回搜索結果。形狀因 mode 而異:文件列表、帶匹配的內容或匹配計數。
TaskStop
工具名稱: TaskStop
type TaskStopOutput = {
message: string;
task_id: string;
task_type: string;
command?: string;
};
停止後台任務後返回確認。
NotebookEdit
工具名稱: NotebookEdit
type NotebookEditOutput = {
new_source: string;
cell_id?: string;
cell_type: "code" | "markdown";
language: string;
edit_mode: string;
error?: string;
notebook_path: string;
original_file: string;
updated_file: string;
};
返回筆記本編輯的結果,包含原始和更新的文件內容。
WebFetch
工具名稱: WebFetch
type WebFetchOutput = {
bytes: number;
code: number;
codeText: string;
result: string;
durationMs: number;
url: string;
};
返回獲取的內容,包含 HTTP 狀態和元數據。
WebSearch
工具名稱: WebSearch
type WebSearchOutput = {
query: string;
results: Array<
| {
tool_use_id: string;
content: Array<{ title: string; url: string }>;
}
| string
>;
durationSeconds: number;
};
返回來自網絡的搜索結果。
TodoWrite
工具名稱: TodoWrite
type TodoWriteOutput = {
oldTodos: Array<{
content: string;
status: "pending" | "in_progress" | "completed";
activeForm: string;
}>;
newTodos: Array<{
content: string;
status: "pending" | "in_progress" | "completed";
activeForm: string;
}>;
};
返回之前和更新的任務列表。
ExitPlanMode
工具名稱: ExitPlanMode
type ExitPlanModeOutput = {
plan: string | null;
isAgent: boolean;
filePath?: string;
hasTaskTool?: boolean;
awaitingLeaderApproval?: boolean;
requestId?: string;
};
返回退出規劃模式後的計劃狀態。
ListMcpResources
工具名稱: ListMcpResources
type ListMcpResourcesOutput = Array<{
uri: string;
name: string;
mimeType?: string;
description?: string;
server: string;
}>;
返回可用 MCP 資源的數組。
ReadMcpResource
工具名稱: ReadMcpResource
type ReadMcpResourceOutput = {
contents: Array<{
uri: string;
mimeType?: string;
text?: string;
}>;
};
返回請求的 MCP 資源的內容。
Config
工具名稱: Config
type ConfigOutput = {
success: boolean;
operation?: "get" | "set";
setting?: string;
value?: unknown;
previousValue?: unknown;
newValue?: unknown;
error?: string;
};
返回配置獲取或設置操作的結果。
EnterWorktree
工具名稱: EnterWorktree
type EnterWorktreeOutput = {
worktreePath: string;
worktreeBranch?: string;
message: string;
};
返回有關 git worktree 的信息。
權限類型
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" // Gitignored 本地設置
| "session" // 僅當前會話
| "cliArg"; // CLI 參數
PermissionRuleValue
type PermissionRuleValue = {
toolName: string;
ruleContent?: string;
};
其他類型
ApiKeySource
type ApiKeySource = "user" | "project" | "org" | "temporary" | "oauth";
SdkBeta
可通過 betas 選項啟用的可用測試功能。見 Beta 標頭 了解更多信息。
type SdkBeta = "context-1m-2025-08-07";
SlashCommand
有關可用 slash command 的信息。
type SlashCommand = {
name: string;
description: string;
argumentHint: string;
};
ModelInfo
有關可用模型的信息。
type ModelInfo = {
value: string;
displayName: string;
description: string;
supportsEffort?: boolean;
supportedEffortLevels?: ("low" | "medium" | "high" | "xhigh" | "max")[];
supportsAdaptiveThinking?: boolean;
supportsFastMode?: boolean;
};
AgentInfo
有關可通過 Agent 工具調用的可用子代理的信息。
type AgentInfo = {
name: string;
description: string;
model?: string;
};
| 字段 | 類型 | 描述 |
|---|
name | string | 代理類型標識符(例如,"Explore"、"general-purpose") |
description | string | 何時使用此代理的描述 |
model | string | undefined | 此代理使用的模型別名。如果省略,繼承父代理的模型 |
McpServerStatus
連接的 MCP 服務器的狀態。
type McpServerStatus = {
name: string;
status: "connected" | "failed" | "needs-auth" | "pending" | "disabled";
serverInfo?: {
name: string;
version: string;
};
error?: string;
config?: McpServerStatusConfig;
scope?: string;
tools?: {
name: string;
description?: string;
annotations?: {
readOnly?: boolean;
destructive?: boolean;
openWorld?: boolean;
};
}[];
};
McpServerStatusConfig
MCP 服務器的配置,如 mcpServerStatus() 報告的那樣。這是所有 MCP 服務器傳輸類型的聯合。
type McpServerStatusConfig =
| McpStdioServerConfig
| McpSSEServerConfig
| McpHttpServerConfig
| McpSdkServerConfig
| McpClaudeAIProxyServerConfig;
見 McpServerConfig 了解每種傳輸類型的詳情。
AccountInfo
經過身份驗證的用戶的帳戶信息。
type AccountInfo = {
email?: string;
organization?: string;
subscriptionType?: string;
tokenSource?: string;
apiKeySource?: string;
};
ModelUsage
結果消息中返回的每個模型使用統計。costUSD 值是客戶端估計。見 跟蹤成本和使用情況 了解計費注意事項。
type ModelUsage = {
inputTokens: number;
outputTokens: number;
cacheReadInputTokens: number;
cacheCreationInputTokens: number;
webSearchRequests: number;
costUSD: number;
contextWindow: number;
maxOutputTokens: number;
};
ConfigScope
type ConfigScope = "local" | "user" | "project";
NonNullableUsage
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;
};
MCP 工具結果類型(來自 @modelcontextprotocol/sdk/types.js)。
type CallToolResult = {
content: Array<{
type: "text" | "image" | "resource";
// 其他字段因類型而異
}>;
isError?: boolean;
};
ThinkingConfig
控制 Claude 的思考/推理行為。優先於已棄用的 maxThinkingTokens。
type ThinkingConfig =
| { type: "adaptive" } // 模型確定何時以及多少推理(Opus 4.6+)
| { type: "enabled"; budgetTokens?: number } // 固定思考令牌預算
| { type: "disabled" }; // 無擴展思考
SpawnedProcess
自定義進程生成的介面(與 spawnClaudeCodeProcess 選項一起使用)。ChildProcess 已滿足此介面。
interface SpawnedProcess {
stdin: Writable;
stdout: Readable;
readonly killed: boolean;
readonly exitCode: number | null;
kill(signal: NodeJS.Signals): boolean;
on(
event: "exit",
listener: (code: number | null, signal: NodeJS.Signals | null) => void
): void;
on(event: "error", listener: (error: Error) => void): void;
once(
event: "exit",
listener: (code: number | null, signal: NodeJS.Signals | null) => void
): void;
once(event: "error", listener: (error: Error) => void): void;
off(
event: "exit",
listener: (code: number | null, signal: NodeJS.Signals | null) => void
): void;
off(event: "error", listener: (error: Error) => void): void;
}
SpawnOptions
傳遞給自定義生成函數的選項。
interface SpawnOptions {
command: string;
args: string[];
cwd?: string;
env: Record<string, string | undefined>;
signal: AbortSignal;
}
McpSetServersResult
setMcpServers() 操作的結果。
type McpSetServersResult = {
added: string[];
removed: string[];
errors: Record<string, string>;
};
RewindFilesResult
rewindFiles() 操作的結果。
type RewindFilesResult = {
canRewind: boolean;
error?: string;
filesChanged?: string[];
insertions?: number;
deletions?: number;
};
SDKStatusMessage
狀態更新消息(例如,壓縮)。
type SDKStatusMessage = {
type: "system";
subtype: "status";
status: "compacting" | null;
permissionMode?: PermissionMode;
uuid: UUID;
session_id: string;
};
SDKTaskNotificationMessage
後台任務完成、失敗或停止時的通知。後台任務包括 run_in_background Bash 命令、Monitor 監視和後台子代理。
type SDKTaskNotificationMessage = {
type: "system";
subtype: "task_notification";
task_id: string;
tool_use_id?: string;
status: "completed" | "failed" | "stopped";
output_file: string;
summary: string;
usage?: {
total_tokens: number;
tool_uses: number;
duration_ms: number;
};
uuid: UUID;
session_id: string;
};
對話中工具使用的摘要。
type SDKToolUseSummaryMessage = {
type: "tool_use_summary";
summary: string;
preceding_tool_use_ids: string[];
uuid: UUID;
session_id: string;
};
SDKHookStartedMessage
Hook 開始執行時發出。
type SDKHookStartedMessage = {
type: "system";
subtype: "hook_started";
hook_id: string;
hook_name: string;
hook_event: string;
uuid: UUID;
session_id: string;
};
SDKHookProgressMessage
Hook 運行時發出,帶有 stdout/stderr 輸出。
type SDKHookProgressMessage = {
type: "system";
subtype: "hook_progress";
hook_id: string;
hook_name: string;
hook_event: string;
stdout: string;
stderr: string;
output: string;
uuid: UUID;
session_id: string;
};
SDKHookResponseMessage
Hook 完成執行時發出。
type SDKHookResponseMessage = {
type: "system";
subtype: "hook_response";
hook_id: string;
hook_name: string;
hook_event: string;
output: string;
stdout: string;
stderr: string;
exit_code?: number;
outcome: "success" | "error" | "cancelled";
uuid: UUID;
session_id: string;
};
工具執行時定期發出,以指示進度。
type SDKToolProgressMessage = {
type: "tool_progress";
tool_use_id: string;
tool_name: string;
parent_tool_use_id: string | null;
elapsed_time_seconds: number;
task_id?: string;
uuid: UUID;
session_id: string;
};
SDKAuthStatusMessage
在身份驗證流程中發出。
type SDKAuthStatusMessage = {
type: "auth_status";
isAuthenticating: boolean;
output: string[];
error?: string;
uuid: UUID;
session_id: string;
};
SDKTaskStartedMessage
後台任務開始時發出。task_type 字段是 "local_bash" 用於後台 Bash 命令和 Monitor 監視,"local_agent" 用於子代理,或 "remote_agent"。
type SDKTaskStartedMessage = {
type: "system";
subtype: "task_started";
task_id: string;
tool_use_id?: string;
description: string;
task_type?: string;
uuid: UUID;
session_id: string;
};
SDKTaskProgressMessage
後台任務運行時定期發出。
type SDKTaskProgressMessage = {
type: "system";
subtype: "task_progress";
task_id: string;
tool_use_id?: string;
description: string;
usage: {
total_tokens: number;
tool_uses: number;
duration_ms: number;
};
last_tool_name?: string;
uuid: UUID;
session_id: string;
};
SDKFilesPersistedEvent
文件檢查點持久化到磁盤時發出。
type SDKFilesPersistedEvent = {
type: "system";
subtype: "files_persisted";
files: { filename: string; file_id: string }[];
failed: { filename: string; error: string }[];
processed_at: string;
uuid: UUID;
session_id: string;
};
SDKRateLimitEvent
會話遇到速率限制時發出。
type SDKRateLimitEvent = {
type: "rate_limit_event";
rate_limit_info: {
status: "allowed" | "allowed_warning" | "rejected";
resetsAt?: number;
utilization?: number;
};
uuid: UUID;
session_id: string;
};
SDKLocalCommandOutputMessage
本地 slash command 的輸出(例如,/voice 或 /cost)。在記錄中顯示為助手風格的文本。
type SDKLocalCommandOutputMessage = {
type: "system";
subtype: "local_command_output";
content: string;
uuid: UUID;
session_id: string;
};
SDKPromptSuggestionMessage
啟用 promptSuggestions 時在每個轉數後發出。包含預測的下一個用戶提示。
type SDKPromptSuggestionMessage = {
type: "prompt_suggestion";
suggestion: string;
uuid: UUID;
session_id: string;
};
AbortError
中止操作的自定義錯誤類。
class AbortError extends Error {}
沙箱配置
SandboxSettings
沙箱行為的配置。使用此選項以編程方式啟用命令沙箱和配置網絡限制。
type SandboxSettings = {
enabled?: boolean;
autoAllowBashIfSandboxed?: boolean;
excludedCommands?: string[];
allowUnsandboxedCommands?: boolean;
network?: SandboxNetworkConfig;
filesystem?: SandboxFilesystemConfig;
ignoreViolations?: Record<string, string[]>;
enableWeakerNestedSandbox?: boolean;
ripgrep?: { command: string; args?: string[] };
};
| 屬性 | 類型 | 默認值 | 描述 |
|---|
enabled | boolean | false | 為命令執行啟用沙箱模式 |
autoAllowBashIfSandboxed | boolean | true | 啟用沙箱時自動批准 bash 命令 |
excludedCommands | string[] | [] | 始終繞過沙箱限制的命令(例如,['docker'])。這些自動運行在沙箱外,無需模型參與 |
allowUnsandboxedCommands | boolean | true | 允許模型請求在沙箱外運行命令。當為 true 時,模型可以在工具輸入中設置 dangerouslyDisableSandbox,這會回退到 權限系統 |
network | SandboxNetworkConfig | undefined | 網絡特定的沙箱配置 |
filesystem | SandboxFilesystemConfig | undefined | 文件系統特定的沙箱配置,用於讀/寫限制 |
ignoreViolations | Record<string, string[]> | undefined | 違規類別到要忽略的模式的映射(例如,{ file: ['/tmp/*'], network: ['localhost'] }) |
enableWeakerNestedSandbox | boolean | false | 為兼容性啟用較弱的嵌套沙箱 |
ripgrep | { command: string; args?: string[] } | undefined | 沙箱環境中的自定義 ripgrep 二進制配置 |
示例用法
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Build and test my project",
options: {
sandbox: {
enabled: true,
autoAllowBashIfSandboxed: true,
network: {
allowLocalBinding: true
}
}
}
})) {
if ("result" in message) console.log(message.result);
}
Unix socket 安全性: allowUnixSockets 選項可以授予對強大系統服務的訪問權限。例如,允許 /var/run/docker.sock 實際上通過 Docker API 授予對主機系統的完全訪問權限,繞過沙箱隔離。僅允許絕對必要的 Unix sockets 並了解每個的安全含義。
SandboxNetworkConfig
沙箱模式的網絡特定配置。
type SandboxNetworkConfig = {
allowedDomains?: string[];
deniedDomains?: string[];
allowManagedDomainsOnly?: boolean;
allowLocalBinding?: boolean;
allowUnixSockets?: string[];
allowAllUnixSockets?: boolean;
httpProxyPort?: number;
socksProxyPort?: number;
};
| 屬性 | 類型 | 默認值 | 描述 |
|---|
allowedDomains | string[] | [] | 沙箱進程可以訪問的域名 |
deniedDomains | string[] | [] | 沙箱進程無法訪問的域名。優先於 allowedDomains |
allowManagedDomainsOnly | boolean | false | 將網絡訪問限制為僅 allowedDomains 中的域 |
allowLocalBinding | boolean | false | 允許進程綁定到本地端口(例如,用於開發服務器) |
allowUnixSockets | string[] | [] | 進程可以訪問的 Unix socket 路徑(例如,Docker socket) |
allowAllUnixSockets | boolean | false | 允許訪問所有 Unix sockets |
httpProxyPort | number | undefined | 網絡請求的 HTTP 代理端口 |
socksProxyPort | number | undefined | 網絡請求的 SOCKS 代理端口 |
SandboxFilesystemConfig
沙箱模式的文件系統特定配置。
type SandboxFilesystemConfig = {
allowWrite?: string[];
denyWrite?: string[];
denyRead?: string[];
};
| 屬性 | 類型 | 默認值 | 描述 |
|---|
allowWrite | string[] | [] | 允許寫入訪問的文件路徑模式 |
denyWrite | string[] | [] | 拒絕寫入訪問的文件路徑模式 |
denyRead | string[] | [] | 拒絕讀取訪問的文件路徑模式 |
無沙箱命令的權限回退
啟用 allowUnsandboxedCommands 時,模型可以通過在工具輸入中設置 dangerouslyDisableSandbox: true 來請求在沙箱外運行命令。這些請求回退到現有的權限系統,意味著您的 canUseTool 處理程序被調用,允許您實現自定義授權邏輯。
excludedCommands vs allowUnsandboxedCommands:
excludedCommands:始終自動繞過沙箱的命令的靜態列表(例如,['docker'])。模型對此無控制。
allowUnsandboxedCommands:讓模型在運行時通過在工具輸入中設置 dangerouslyDisableSandbox: true 來決定是否請求無沙箱執行。
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of 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}`);
if (isCommandAuthorized(input.command)) {
return { behavior: "allow" as const, updatedInput: input };
}
return {
behavior: "deny" as const,
message: "Command not authorized for unsandboxed execution"
};
}
return { behavior: "allow" as const, updatedInput: input };
}
}
})) {
if ("result" in message) console.log(message.result);
}
此模式使您能夠:
- 審計模型請求: 記錄模型何時請求無沙箱執行
- 實現允許列表: 僅允許特定命令在沙箱外運行
- 添加批准工作流: 需要對特權操作進行明確授權
使用 dangerouslyDisableSandbox: true 運行的命令具有完整的系統訪問權限。確保您的 canUseTool 處理程序仔細驗證這些請求。如果 permissionMode 設置為 bypassPermissions 且 allowUnsandboxedCommands 啟用,模型可以自主執行沙箱外的命令,無需任何批准提示。此組合實際上允許模型無聲地逃離沙箱隔離。