TypeScript Agent SDK 参考文档:包含所有函数(query、startup、tool、createSdkMcpServer 等)、配置选项、钩子类型、工具输入输出模式,以及沙箱和权限控制。安装 @anthropic-ai/claude-agent-sdk 后即可通过 API 调用 Claude Code,无需单独安装 CLI。打包为单文件可执行文件时需处理原生二进制路径,否则会抛 Native CLI binary not found 错误。

Claude Code Agent SDK TypeScript 参考:函数、类型与配置

安装

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 二进制路径。

编译为单文件可执行文件

当你用 bun build --compile 将应用编译为单文件可执行文件时,SDK 无法在运行时解析绑定的 CLI 二进制路径。因为 require.resolve 无法在编译后可执行文件的 $bunfs 虚拟文件系统内工作,所以 SDK 会抛出 Native CLI binary for <platform> not found

解决方法是:将平台二进制作为文件资源嵌入,在启动时用 extractFromBunfs() 解压到真实路径,然后将该路径传给 pathToClaudeCodeExecutable

extractFromBunfs() 辅助函数需要 @anthropic-ai/claude-agent-sdk v0.3.144 或更高版本。以下示例针对 macOS Apple Silicon 构建:

import binPath from "@anthropic-ai/claude-agent-sdk-darwin-arm64/claude" with { type: "file" };
import { extractFromBunfs } from "@anthropic-ai/claude-agent-sdk/extract";
import { query } from "@anthropic-ai/claude-agent-sdk";

const cliPath = extractFromBunfs(binPath);

for await (const message of query({
  prompt: "Hello",
  options: { pathToClaudeCodeExecutable: cliPath },
})) {
  console.log(message);
}

extractFromBunfs() 会将嵌入的二进制从编译后可执行文件的虚拟文件系统复制到每个用户的临时目录,并返回真实路径。在编译环境之外,它不修改输入路径,因此同一段代码在开发中直接运行无需修改。

每个编译后的可执行文件只嵌入单一平台的二进制。导入的平台包需要与你的 --target 匹配:

  • 交叉编译时,安装非匹配的平台包,例如 npm install @anthropic-ai/claude-agent-sdk-linux-x64 --force
  • 在 Windows 上,二进制子路径为 claude.exe,例如 @anthropic-ai/claude-agent-sdk-win32-x64/claude.exe

函数

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 子进程:生成进程并完成初始化握手。返回的 WarmQuery 句柄可以在稍后传入提示,直接写入一个已就绪的进程,从而让首次 query() 调用无需等待子进程生成和初始化。

function startup(params?: {
  options?: Options;
  initializeTimeoutMs?: number;
}): Promise<WarmQuery>;

参数

参数 类型 描述
options Options 可选配置对象,与 query()options 参数相同
initializeTimeoutMs number 等待子进程初始化的最大毫秒数,默认 60000。如果初始化未在时间内完成,Promise 会以超时错误拒绝

返回值

返回 Promise<WarmQuery>,在子进程生成并完成初始化握手后 resolve。

示例

在应用启动时尽早调用 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);
}

tool()

创建一个类型安全的 MCP 工具定义,用于 SDK 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 工具注释,提供行为提示给客户端

ToolAnnotations

@modelcontextprotocol/sdk/types.js 重新导出。所有字段都是可选的提示;客户端不应依赖它们进行安全决策。

字段 类型 默认值 描述
title string undefined 工具的人类可读标题
readOnlyHint boolean false 如果为 true,工具不会修改环境
destructiveHint boolean true 如果为 true,工具可能执行破坏性更新(仅在 readOnlyHintfalse 时有意义)
idempotentHint boolean false 如果为 true,相同参数的重复调用不会产生额外效果(仅在 readOnlyHintfalse 时有意义)
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 仓库内时,是否包含所有工作树的会话

返回类型:SDKSessionInfo

属性 类型 描述
sessionId string 唯一会话标识(UUID)
summary string 显示标题:自定义标题、自动生成的摘要或第一条提示
lastModified number 最后修改时间(自 epoch 起的毫秒数)
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 创建时间(自 epoch 起的毫秒数),来自第一条记录的时间戳

示例

打印项目最近的 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 此消息所属的会话 ID
message unknown 原始消息载荷
parent_tool_use_id string | null 子代理消息中,生成此消息的 Agent 工具调用的 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 项目目录路径。省略则搜索所有项目目录

tagSession()

为会话打标签。传 null 清除标签。重复调用是安全的;最新的标签生效。

function tagSession(
  sessionId: string,
  tag: string | null,
  options?: SessionMutationOptions
): Promise<void>;

参数

参数 类型 默认值 描述
sessionId string 必需 要打标签的会话 UUID
tag string | null 必需 标签字符串,或 null 清除
options.dir string undefined 项目目录路径。省略则搜索所有项目目录

resolveSettings()

使用与 CLI 相同的合并引擎解析给定目录的 Claude Code 有效设置,无需启动 Claude CLI。用于在调用 query() 之前检查它会看到什么配置。

此函数为 Alpha 状态,其 API 可能不稳定。它读取 MDM 源(包括 macOS plist 和 Windows HKLM/HKCU)以实现与 CLI 启动的等价性,但不执行管理员配置的 policyHelper 子进程。permissions.defaultMode 字段原样返回自所有层级(包括项目设置)。CLI 在应用权限模式升级前应用的信任过滤不会被应用。

function resolveSettings(
  options?: ResolveSettingsOptions
): Promise<ResolvedSettings>;

参数

resolveSettings() 接受一个选项对象。所有字段都是可选的。

参数 类型 默认值 描述
options.cwd string process.cwd() 用于解析项目和本地设置的工作目录
options.settingSources SettingSource[] 所有来源 要加载的基于文件的设置来源。传 [] 跳过用户、项目和本地设置。托管策略设置始终加载
options.managedSettings Settings undefined 嵌入式宿主提供的限制性策略层级设置。当存在管理员部署的托管层级时被丢弃;当 parentSettingsBehavior"merge" 时在该层级下合并。非限制性键(如 model)会被静默丢弃,因此此选项可以收紧但不可放松托管策略
options.serverManagedSettings Settings undefined 来自 /api/claude_code/settings 的服务器管理设置载荷。非限制性键直接通过

返回类型:ResolvedSettings

resolveSettings() 返回描述合并后设置及每个键来源的对象。

属性 类型 描述
effective Settings 按优先级顺序应用所有启用的来源后的合并设置
provenance Partial<Record<keyof Settings, ProvenanceEntry>> effective 中每个顶层键对应的来源
sources Array<{ source, settings, path?, policyOrigin? }> 每个来源的原始设置,按从低到高的优先级顺序排列

示例

以下示例解析项目目录的设置,并打印控制清理周期的来源。

import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";

const { effective, provenance } = await resolveSettings({
  cwd: "/path/to/project",
  settingSources: ["user", "project", "local"],
});

console.log(`Cleanup period: ${effective.cleanupPeriodDays} days`);
console.log(`Set by: ${provenance.cleanupPeriodDays?.source}`);

类型

Options

query() 函数的配置对象。

属性 类型 默认值 描述
abortController AbortController new AbortController() 用于取消操作的控制器
additionalDirectories string[] [] Claude 可以访问的额外目录
agent string undefined 主线程的代理名称。该代理必须在 agents 选项或设置中定义
agents Record<string, [AgentDefinition](#agentdefinition)> undefined 以编程方式定义子代理
agentProgressSummaries boolean false true 时,为子代理生成单行进度摘要,并通过 summary 字段在 task_progress 事件上转发。适用于前台和后台子代理
allowDangerouslySkipPermissions boolean false 允许绕过权限。使用 permissionMode: 'bypassPermissions' 时需要
allowedTools string[] [] 无需提示即自动批准的工具。这不限制 Claude 只能使用这些工具;未列出的工具会回退到 permissionModecanUseTool。使用 disallowedTools 来阻止工具。见权限
betas SdkBeta[] [] 启用测试版功能
canUseTool CanUseTool undefined 自定义工具使用权限函数
continue boolean false 继续最近的对话
cwd string process.cwd() 当前工作目录
debug boolean false 为 Claude Code 进程启用调试模式
debugFile string undefined 将调试日志写入特定文件路径。隐式启用调试模式
disallowedTools string[] [] 拒绝使用的工具。裸名称如 "Bash" 会把该工具从 Claude 的上下文中移除。带作用域的规则如 "Bash(rm *)" 会保留该工具可用,并在所有权限模式下拒绝匹配的调用,包括 bypassPermissions。见权限
effort 'low' | 'medium' | 'high' | 'xhigh' | 'max' 'high' 控制 Claude 在其响应中投入的努力程度。与自适应思维配合使用来指导思维深度
enableFileCheckpointing boolean false 启用文件更改跟踪以便回退。见文件检查点
env Record<string, string | undefined> process.env 环境变量。见环境变量了解底层 CLI 读取的变量,以及处理慢速或停滞的 API 响应了解超时相关变量。设置 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 而不是继续原会话
forwardSubagentText boolean false 将子代理的文本和思维块作为带有 parent_tool_use_id 的 assistant 和 user 消息转发,以便消费者可以渲染嵌套记录。默认情况下,只发出子代理的 tool_usetool_result
hooks Partial<Record<HookEvent, HookCallbackMatcher[]>> {} 事件钩子回调
includeHookEvents boolean false 在消息流中包含钩子生命周期事件,作为 SDKHookStartedMessageSDKHookProgressMessageSDKHookResponseMessage
includePartialMessages boolean false 包含部分消息事件
loadTimeoutMs number 60000 Alpha. 在恢复的具体化过程中,每个 sessionStore.load()sessionStore.listSubkeys() 调用的超时时间(毫秒)。如果适配器未在此窗口内完成,查询将失败而不是挂起。当未设置 sessionStore 时忽略
managedSettings Settings undefined 由父进程提供的策略层级设置。如果机器上已有 IT 控制的托管设置层级,此设置会被丢弃,除非管理员通过 parentSettingsBehavior: 'merge' 启用。无论哪种情况,非限制性键都会被过滤掉
maxBudgetUsd number undefined 当客户端成本估算达到此美元值时停止查询。与 total_cost_usd 使用相同的估算;见跟踪成本和使用了解准确性问题
maxThinkingTokens number undefined 已弃用: 使用 thinking 替代。思维过程的最大令牌数
maxTurns number undefined 最大代理轮次(工具用三角旅行)
mcpServers Record<string, [McpServerConfig](#mcpserverconfig)> {} MCP 服务器配置
model string CLI 默认 要使用的 Claude 模型
onElicitation (request: ElicitationRequest, options: { signal: AbortSignal }) => Promise<ElicitationResult> undefined 处理 MCP 请求的回调。当 MCP 服务器请求用户输入且没有钩子处理时调用。未提供时,未处理的请求会自动拒绝
outputFormat { type: 'json_schema', schema: JSONSchema } undefined 定义代理结果的输出格式。见结构化输出了解详情
outputStyle string undefined 不是 Options 字段。在行内 settings 对象或设置文件中设置 outputStyle。见激活输出风格
pathToClaudeCodeExecutable string 从绑定的原生二进制自动解析 Claude Code 可执行文件的路径。仅在安装时跳过了可选依赖或你的平台不在支持集合中时需要
permissionMode PermissionMode 'default' 会话的权限模式
permissionPromptToolName string undefined 用于权限提示的 MCP 工具名称
persistSession boolean true false 时,禁用会话持久化到磁盘。会话以后无法恢复
planModeInstructions string undefined 计划模式的自定义工作流指令。当 permissionMode'plan' 时,此字符串替换默认的计划模式工作流主体。CLI 仍然会包裹只读执行前序和 ExitPlanMode 协议尾
plugins SdkPluginConfig[] [] 从本地路径加载自定义插件。见插件了解详情
promptSuggestions boolean false 启用提示建议。每轮后发出一个 prompt_suggestion 消息,包含预测的下一个用户提示
resume string undefined 要恢复的会话 ID
resumeSessionAt string undefined 在特定消息 UUID 处恢复会话
sandbox SandboxSettings undefined 以编程方式配置沙箱行为。见沙箱设置了解详情
sessionId string 自动生成 使用特定的会话 UUID 而不是自动生成
sessionStore SessionStore undefined 将会话记录镜像到外部后端,以便任何宿主可以恢复它们。见将会话持久化到外部存储
sessionStoreFlush 'batched' | 'eager' 'batched' Alpha. sessionStore 的刷新模式。当未设置 sessionStore 时忽略
settings string | Settings undefined 行内设置对象或设置文件的路径。填充标志设置层,位于优先级顺序中。运行时可通过 applyFlagSettings() 更改
settingSources SettingSource[] CLI 默认(所有来源) 控制要加载的基于文件的设置。传 [] 禁用用户、项目和本地设置。托管策略设置始终加载。见使用 Claude Code 功能
skills string[] | 'all' undefined 会话可用的技能。传 'all' 启用所有发现的技能,或传递技能名称列表。设置后,SDK 会自动启用 Skill 工具,无需在 allowedTools 中列出。见技能
spawnClaudeCodeProcess (options: SpawnOptions) => SpawnedProcess undefined 用于生成 Claude Code 进程的自定义函数。用于在虚拟机、容器或远程环境中运行 Claude Code
stderr (data: string) => void undefined stderr 输出的回调
strictMcpConfig boolean false 仅使用 mcpServers 中传入的服务器,忽略项目的 .mcp.json、用户设置和插件提供的 MCP 服务器
systemPrompt string | { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean } undefined(最小提示) 系统提示配置。传入字符串用于自定义提示,或使用 { type: 'preset', preset: 'claude_code' } 来使用 Claude Code 的系统提示。使用预设对象形式时,可添加 append 以扩展额外指令,设置 excludeDynamicSections: true 将会话特定上下文移动到第一条用户消息,以改善跨机器的提示缓存重用
taskBudget { total: number } undefined Alpha. API 端的任务预算(令牌数)。设置后,模型会被告知剩余的令牌预算,以便它可以在达到限制前调整工具使用并收尾
thinking ThinkingConfig { type: 'adaptive' }(对于支持的模型) 控制 Claude 的思维/推理行为。见 ThinkingConfig 了解选项
title string undefined 会话的显示标题。当通过 resumecontinue 恢复时,已恢复会话的持久化标题优先;使用 renameSession() 重命名现有会话
toolAliases Record<string, string> undefined 将内置工具名称映射到 MCP 工具名称,以便 Claude 调用你的 MCP 实现代替内置工具。例如 { Bash: 'mcp__workspace__bash' }
toolConfig ToolConfig undefined 内置工具行为的配置。见 ToolConfig 了解详情
tools string[] | { type: 'preset'; preset: 'claude_code' } undefined 工具配置。传递工具名称数组或使用预设来获取 Claude Code 的默认工具

处理慢速或停滞的 API 响应

CLI 子进程读取几个控制 API 超时和停滞检测的环境变量。通过 env 选项传递它们:

const result = query({
  prompt: "Analyze this code",
  options: {
    env: {
      ...process.env,
      API_TIMEOUT_MS: "120000",
      CLAUDE_CODE_MAX_RETRIES: "2",
      CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS: "120000",
    },
  },
});
  • API_TIMEOUT_MS:Anthropic 客户端每个请求的超时时间(毫秒)。默认 600000。应用于主循环和所有子代理。
  • CLAUDE_CODE_MAX_RETRIES:最大 API 重试次数。默认 10。每次重试有自己的 API_TIMEOUT_MS 窗口,因此最坏情况墙钟时间大约为 API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1) 加上退避。
  • CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS:针对 run_in_background 启动的子代理的停滞看门狗。默认 600000。在每次流事件上重置;在停滞时终止子代理,标记任务失败,并将错误(含任何部分结果)抛给父代理。不应用于同步子代理。
  • CLAUDE_ENABLE_STREAM_WATCHDOG=1 配合 CLAUDE_STREAM_IDLE_TIMEOUT_MS:当头部已到达但响应体停止流式传输时终止请求。默认关闭。CLAUDE_STREAM_IDLE_TIMEOUT_MS 默认为 300000 并被限制为该最小值。被终止的请求会进入正常重试路径。

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>;
  applyFlagSettings(settings: { [K in keyof Settings]?: Settings[K] | 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 选项。更改最大思维令牌数
applyFlagSettings(settings) 在运行时将设置合并到会话的标志设置层(仅在流式输入模式下可用)。见 applyFlagSettings()
initializationResult() 返回完整的初始化结果,包括支持的命令、模型、账户信息和输出风格配置
supportedCommands() 返回可用的斜杠命令
supportedModels() 返回可用模型及其显示信息
supportedAgents() 返回可用的子代理作为 AgentInfo[]
mcpServerStatus() 返回已连接的 MCP 服务器的状态
accountInfo() 返回账户信息
reconnectMcpServer(serverName) 按名称重新连接 MCP 服务器
toggleMcpServer(serverName, enabled) 按名称启用或禁用 MCP 服务器
setMcpServers(servers) 动态替换当前会话的 MCP 服务器集合。返回关于哪些服务器被添加、移除以及任何错误的信息
streamInput(stream) 将输入消息流传输到查询,用于多轮对话
stopTask(taskId) 按 ID 停止正在运行的后台任务
close() 关闭查询并终止底层进程。强制结束查询并清理所有资源

applyFlagSettings()

在运行中的会话上更改任何设置,无需重启查询。当没有专用设置器的设置需要在会话中途更改时使用,例如在代理读取不可信输入后收紧 permissionssetModel()setPermissionMode() 是这两个键的专用设置器;applyFlagSettings() 是通用形式,接受任何设置键的子集,传递 model 的效果与 setModel() 相同。

这些值被写入标志设置层,与 query() 启动时行内 settings 选项填充的层级相同。标志设置在设置优先级顺序中位于较高位置:它们覆盖用户、项目和本地设置,只有托管策略设置可以覆盖它们。这就是页面优先级部分称为程序化选项的层级。

连续调用会对顶层键进行浅合并。第二次调用时传递 { permissions: {...} } 会替换前一次调用的整个 permissions 对象,而不是深合并。要从标志层清除某个键并回退到较低优先级的来源,传递 null 作为该键的值。传递 undefined 没有效果,因为 JSON 序列化会忽略它。

仅在流式输入模式下可用,与 setModel()setPermissionMode() 具有相同的约束。

以下示例在会话中途切换活跃模型,然后清除覆盖,使模型退回到用户或项目设置。

const q = query({ prompt: messageStream });

// 覆盖会话剩余部分的模型
await q.applyFlagSettings({ model: "claude-opus-4-6" });

// 稍后:清除覆盖,回退到较低优先级的设置
await q.applyFlagSettings({ model: null });

applyFlagSettings() 仅适用于 TypeScript。Python SDK 不公开等效方法。

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?: string;
  mcpServers?: AgentMcpServerSpec[];
  skills?: string[];
  initialPrompt?: string;
  maxTurns?: number;
  background?: boolean;
  memory?: "user" | "project" | "local";
  effort?: "low" | "medium" | "high" | "xhigh" | "max" | number;
  permissionMode?: PermissionMode;
  criticalSystemReminder_EXPERIMENTAL?: string;
};
字段 必需 描述
description 何时使用此代理的自然语言描述
tools 允许的工具名称数组。如果省略,则继承父级的所有工具。要将技能预加载到代理的上下文中,请使用 skills 字段,而不是在此处列出 'Skill'
disallowedTools 明确不允许该代理使用的工具名称数组
prompt 代理的系统提示
model 此代理的模型覆盖。接受别名如 'sonnet''opus''haiku''inherit' 或完整模型 ID。如果省略或为 'inherit',则使用主模型
mcpServers 此代理的 MCP 服务器规范
skills 要预加载到代理上下文中的技能名称数组
initialPrompt 当此代理作为主线程代理运行时,自动作为第一条用户轮次提交
maxTurns 在停止前允许的最大代理轮次(API 往返)
background 调用时将该代理作为非阻塞后台任务运行
memory 此代理的记忆来源:'user''project''local'
effort 此代理的推理努力级别。接受命名级别或整数
permissionMode 此代理内工具执行的权限模式。见 PermissionMode
criticalSystemReminder_EXPERIMENTAL 实验性:添加到系统提示中的关键提醒

AgentMcpServerSpec

指定子代理可用的 MCP 服务器。可以是服务器名称(引用父级 mcpServers 配置中的字符串)或行内服务器配置记录(将服务器名称映射到配置)。

type AgentMcpServerSpec = string | Record<string, McpServerConfigForProcessTransport>;

其中 McpServerConfigForProcessTransportMcpStdioServerConfig | 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"]
  }
});

设置优先级

当加载多个来源时,设置按以下优先级合并(从高到低):

  1. 本地设置(.claude/settings.local.json
  2. 项目设置(.claude/settings.json
  3. 用户设置(~/.claude/settings.json

程序化选项如 agentsallowedToolssettings 会覆盖用户、项目和本地文件系统设置。托管策略设置优先于程序化选项。

PermissionMode

type PermissionMode =
  | "default" // 标准权限行为
  | "acceptEdits" // 自动接受文件编辑
  | "bypassPermissions" // 绕过所有权限检查
  | "plan" // 计划模式 - 仅只读工具
  | "dontAsk" // 不弹出权限提示,若未预先批准则拒绝
  | "auto"; // 使用模型分类器批准或拒绝每个工具调用

CanUseTool

用于控制工具使用权限的自定义权限函数类型。

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[] 建议的权限更新,以使用户不再为此工具被提示。Bash 提示包含一个带有 localSettings destination 的建议,因此在 updatedPermissions 中返回它会将规则写入 .claude/settings.local.json 并跨会话持久化。
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;
    };

ToolConfig

内置工具行为的配置。

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
  | SDKTaskUpdatedMessage
  | SDKSessionStateChangedMessage
  | SDKNotificationMessage
  | SDKFilesPersistedEvent
  | SDKToolUseSummaryMessage
  | SDKMemoryRecallMessage
  | SDKRateLimitEvent
  | SDKElicitationCompleteMessage
  | SDKPermissionDeniedMessage
  | SDKPromptSuggestionMessage
  | SDKAPIRetryMessage
  | SDKMirrorErrorMessage;

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。它包含 idcontentmodelstop_reasonusage 等字段。

SDKAssistantMessageError 是以下之一:'authentication_failed''oauth_org_not_allowed''billing_error''rate_limit''invalid_request''model_not_found''server_error''max_output_tokens''unknown''model_not_found' 表示所选模型不存在或对你的账户/部署不可用。

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;
  origin?: SDKMessageOrigin;
};

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;
  origin?: SDKMessageOrigin;
  isReplay: true;
};

SDKResultMessage

最终结果消息。

type SDKResultMessage =
  | {
      type: "result";
      subtype: "success";
      uuid: UUID;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      api_error_status?: number | null;
      num_turns: number;
      result: string;
      stop_reason: string | null;
      ttft_ms?: number;
      total_cost_usd: number;
      usage: NonNullableUsage;
      modelUsage: { [modelName: string]: ModelUsage };
      permission_denials: SDKPermissionDenial[];
      structured_output?: unknown;
      deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> };
      terminal_reason?: TerminalReason;
      fast_mode_state?: FastModeState;
      origin?: SDKMessageOrigin;
    }
  | {
      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[];
      terminal_reason?: TerminalReason;
      fast_mode_state?: FastModeState;
      origin?: SDKMessageOrigin;
    };

结果上的几个字段提供超出 subtype 的诊断细节:

  • api_error_status:终止对话的 API 错误的 HTTP 状态码。当轮次正常结束而无 API 错误时,缺失或为 null
  • ttft_ms:到第一个令牌的时间(毫秒)。仅出现在成功分支上。
  • terminal_reason:循环结束的原因。值为 "completed""max_turns""tool_deferred""aborted_streaming""aborted_tools""hook_stopped""stop_hook_prevented""blocking_limit""rapid_refill_breaker""prompt_too_long""image_error""model_error"
  • fast_mode_state:值为 "on""off""cooldown"

origin 字段转发触发此结果的用户消息的 SDKMessageOrigin。当后台任务完成且 SDK 注入一个合成的后续轮次时,生成的 SDKResultMessage 携带 origin: { kind: "task-notification" }。检查此字段以区分直接回答你的提示的结果与后台任务后续产生的结果,以便你路由或抑制后者。在第一条用户轮次之前发出的结果(如启动错误)中,此字段缺失。

PreToolUse 钩子返回 permissionDecision: "defer" 时,结果具有 stop_reason: "tool_deferred",并且 deferred_tool_use 携带待处理工具的 idnameinput。读取此字段以在你的 UI 中展示请求,然后使用相同的 session_id 恢复以继续。见延迟工具调用了解完整往返。

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 应用在第一个轮次之前跟踪市场插件安装。startedcompleted 状态括起整个安装过程。installedfailed 状态报告单个市场并包含 name

type SDKPluginInstallMessage = {
  type: "system";
  subtype: "plugin_install";
  status: "started" | "installed" | "failed" | "completed";
  name?: string;
  error?: string;
  uuid: UUID;
  session_id: string;
};

SDKPermissionDeniedMessage

权限系统自动拒绝工具调用而不弹出交互式提示时发出的流事件。用于在 UI 中实时渲染拒绝信息,而不是等待后续的 is_error 工具结果。交互式询问路径通过 canUseTool 回调单独到达你的应用程序。PreToolUse 钩子发出的拒绝不会通过此事件报告。

此事件需要 Claude Code v2.1.136 或更高版本。

type SDKPermissionDeniedMessage = {
  type: "system";
  subtype: "permission_denied";
  tool_name: string;
  tool_use_id: string;
  agent_id?: string;
  decision_reason_type?: string;
  decision_reason?: string;
  message: string;
  uuid: UUID;
  session_id: string;
};
字段 类型 描述
tool_name string 被拒绝的工具名称
tool_use_id string 此拒绝响应的 tool_use 块的 ID
agent_id string 当拒绝调用源自子代理时,子代理 ID。镜像 can_use_tool 上的字段用于宿主端路由
decision_reason_type string 决策组件的区分符,例如 "rule""mode""classifier""asyncAgent"
decision_reason string 决策组件提供的人类可读原因(如果可用)
message string tool_result 中返回给模型的拒绝消息

SDKPermissionDenial

关于被拒绝的工具使用的信息。

type SDKPermissionDenial = {
  tool_name: string;
  tool_use_id: string;
  tool_input: Record<string, unknown>;
};

SDKMessageOrigin

用户角色消息的溯源信息。作为 origin 出现在 SDKUserMessage 上,并转发到对应的 SDKResultMessage,以便你知道什么触发了该轮次。

type SDKMessageOrigin =
  | { kind: "human" }
  | { kind: "channel"; server: string }
  | { kind: "peer"; from: string; name?: string }
  | { kind: "task-notification" }
  | { kind: "coordinator" };
kind 含义
human 终端用户的直接输入。在用户消息上,缺失 origin 也表示人类输入。
channel 通过频道到达的消息。server 是源 MCP 服务器名称。
peer 通过 SendMessage 来自另一个代理会话的消息。from 是发送者地址;name 是发送者的显示名称(如果可用)。
task-notification 后台任务完成后注入的合成轮次。见 SDKTaskNotificationMessage
coordinator 来自团队协调器的消息。

钩子类型

关于使用钩子的完整指南和常见模式,见钩子指南

HookEvent

可用的钩子事件。

type HookEvent =
  | "PreToolUse"
  | "PostToolUse"
  | "PostToolUseFailure"
  | "PostToolBatch"
  | "Notification"
  | "UserPromptSubmit"
  | "SessionStart"
  | "SessionEnd"
  | "Stop"
  | "SubagentStart"
  | "SubagentStop"
  | "PreCompact"
  | "PermissionRequest"
  | "Setup"
  | "TeammateIdle"
  | "TaskCompleted"
  | "ConfigChange"
  | "WorktreeCreate"
  | "WorktreeRemove";

HookCallback

钩子回调函数类型。

type HookCallback = (
  input: HookInput, // 所有钩子输入类型的联合
  toolUseID: string | undefined,
  options: { signal: AbortSignal }
) => Promise<HookJSONOutput>;

HookCallbackMatcher

带有可选匹配器的钩子配置。

interface HookCallbackMatcher {
  matcher?: string;
  hooks: HookCallback[];
  timeout?: number; // 此匹配器中所有钩子的超时时间(秒)
}

HookInput

所有钩子输入类型的联合。

type HookInput =
  | PreToolUseHookInput
  | PostToolUseHookInput
  | PostToolUseFailureHookInput
  | PostToolBatchHookInput
  | NotificationHookInput
  | UserPromptSubmitHookInput
  | SessionStartHookInput
  | SessionEndHookInput
  | StopHookInput
  | SubagentStartHookInput
  | SubagentStopHookInput
  | PreCompactHookInput
  | PermissionRequestHookInput
  | SetupHookInput
  | TeammateIdleHookInput
  | TaskCompletedHookInput
  | ConfigChangeHookInput
  | WorktreeCreateHookInput
  | WorktreeRemoveHookInput;

BaseHookInput

所有钩子输入类型扩展的基础接口。

type BaseHookInput = {
  session_id: string;
  transcript_path: string;
  cwd: string;
  permission_mode?: string;
  effort?: { level: string };
  agent_id?: string;
  agent_type?: string;
};

PreToolUseHookInput

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;
  duration_ms?: number;
};

PostToolUseFailureHookInput

type PostToolUseFailureHookInput = BaseHookInput & {
  hook_event_name: "PostToolUseFailure";
  tool_name: string;
  tool_input: unknown;
  tool_use_id: string;
  error: string;
  is_interrupt?: boolean;
  duration_ms?: number;
};

PostToolBatchHookInput

在批次中的每个工具调用都已解析后,在下一次模型请求之前触发一次。tool_response 携带模型看到的序列化 tool_result 内容;其形状与 PostToolUseHookInput 的结构化 Output 对象不同。

type PostToolBatchHookInput = BaseHookInput & {
  hook_event_name: "PostToolBatch";
  tool_calls: PostToolBatchToolCall[];
};

type PostToolBatchToolCall = {
  tool_name: string;
  tool_input: unknown;
  tool_use_id: string;
  tool_response?: unknown;
};

NotificationHookInput

type NotificationHookInput = BaseHookInput & {
  hook_event_name: "Notification";
  message: string;
  title?: string;
  notification_type: string;
};

UserPromptSubmitHookInput

type UserPromptSubmitHookInput = BaseHookInput & {
  hook_event_name: "UserPromptSubmit";
  prompt: string;
};

SessionStartHookInput

type SessionStartHookInput = BaseHookInput & {
  hook_event_name: "SessionStart";
  source: "startup" | "resume" | "clear" | "compact";
  agent_type?: string;
  model?: string;
};

SessionEndHookInput

type SessionEndHookInput = BaseHookInput & {
  hook_event_name: "SessionEnd";
  reason: ExitReason; // 来自 EXIT_REASONS 数组的字符串
};

StopHookInput

type StopHookInput = BaseHookInput & {
  hook_event_name: "Stop";
  stop_hook_active: boolean;
  last_assistant_message?: string;
  background_tasks?: BackgroundTaskSummary[];
  session_crons?: SessionCronSummary[];
};

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;
  agent_id: string;
  agent_transcript_path: string;
  agent_type: string;
  last_assistant_message?: string;
  background_tasks?: BackgroundTaskSummary[];
  session_crons?: SessionCronSummary[];
};

type BackgroundTaskSummary = {
  id: string;
  type: string;
  status: string;
  description: string;
  command?: string;
  agent_type?: string;
  server?: string;
  tool?: string;
  name?: string;
};

type SessionCronSummary = {
  id: string;
  schedule: string;
  recurring: boolean;
  prompt: string;
};

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[];
};

SetupHookInput

type SetupHookInput = BaseHookInput & {
  hook_event_name: "Setup";
  trigger: "init" | "maintenance";
};

TeammateIdleHookInput

type TeammateIdleHookInput = BaseHookInput & {
  hook_event_name: "TeammateIdle";
  teammate_name: string;
  team_name: string;
};

TaskCompletedHookInput

type TaskCompletedHookInput = BaseHookInput & {
  hook_event_name: "TaskCompleted";
  task_id: string;
  task_subject: string;
  task_description?: string;
  teammate_name?: string;
  team_name?: string;
};

ConfigChangeHookInput

type ConfigChangeHookInput = BaseHookInput & {
  hook_event_name: "ConfigChange";
  source:
    | "user_settings"
    | "project_settings"
    | "local_settings"
    | "policy_settings"
    | "skills";
  file_path?: string;
};

WorktreeCreateHookInput

type WorktreeCreateHookInput = BaseHookInput & {
  hook_event_name: "WorktreeCreate";
  name: string;
};

WorktreeRemoveHookInput

type WorktreeRemoveHookInput = BaseHookInput & {
  hook_event_name: "WorktreeRemove";
  worktree_path: string;
};

HookJSONOutput

钩子返回值。

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" | "defer";
        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;
        updatedToolOutput?: unknown;
        /** @deprecated 使用 `updatedToolOutput`,它适用于所有工具。 */
        updatedMCPToolOutput?: unknown;
      }
    | {
        hookEventName: "PostToolUseFailure";
        additionalContext?: string;
      }
    | {
        hookEventName: "PostToolBatch";
        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 导出,可用于类型安全的工具交互。

ToolInputSchemas

所有工具输入类型的联合,从 @anthropic-ai/claude-agent-sdk 导出。

type ToolInputSchemas =
  | AgentInput
  | AskUserQuestionInput
  | BashInput
  | TaskOutputInput
  | EnterWorktreeInput
  | ExitPlanModeInput
  | FileEditInput
  | FileReadInput
  | FileWriteInput
  | GlobInput
  | GrepInput
  | ListMcpResourcesInput
  | McpInput
  | MonitorInput
  | NotebookEditInput
  | ReadMcpResourceInput
  | SubscribeMcpResourceInput
  | SubscribePollingInput
  | TaskCreateInput
  | TaskGetInput
  | TaskListInput
  | TaskStopInput
  | TaskUpdateInput
  | 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 笔记本。使用 pages 指定 PDF 页面范围(例如 "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;
  }>;
};

创建并管理结构化任务列表以跟踪进度。

自 TypeScript Agent SDK 0.3.142 起,TodoWrite 默认禁用。请改用 TaskCreateTaskGetTaskUpdateTaskList。见迁移到 Task 工具更新你的监控代码,或设置 CLAUDE_CODE_ENABLE_TASKS=0 以回退到 TodoWrite

TaskCreate

工具名称: TaskCreate

type TaskCreateInput = {
  subject: string;
  description: string;
  activeForm?: string;
  metadata?: Record<string, unknown>;
};

创建单个任务并返回其分配的 ID。

TaskUpdate

工具名称: TaskUpdate

type TaskUpdateInput = {
  taskId: string;
  status?: "pending" | "in_progress" | "completed" | "deleted";
  subject?: string;
  description?: string;
  activeForm?: string;
  addBlocks?: string[];
  addBlockedBy?: string[];
  owner?: string;
  metadata?: Record<string, unknown>;
};

按 ID 修补一个任务。设置 status"deleted" 以删除它。

TaskGet

工具名称: TaskGet

type TaskGetInput = {
  taskId: string;
};

返回一个任务的完整细节,如果 ID 未找到则返回 null

TaskList

工具名称: TaskList

type TaskListInput = {};

返回当前列表中所有任务的快照。

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 资源。

EnterWorktree

工具名称: EnterWorktree

type EnterWorktreeInput = {
  name?: string;
  path?: string;
};

创建并进入一个临时的 git worktree 用于隔离工作。传递 path 切换到当前仓库的现有 worktree,而不是创建新的。namepath 互斥。

工具输出类型

所有内置 Claude Code 工具的输出模式文档。这些类型从 @anthropic-ai/claude-agent-sdk 导出,表示每个工具返回的实际响应数据。

ToolOutputSchemas

所有工具输出类型的联合。

type ToolOutputSchemas =
  | AgentOutput
  | AskUserQuestionOutput
  | BashOutput
  | EnterWorktreeOutput
  | ExitPlanModeOutput
  | FileEditOutput
  | FileReadOutput
  | FileWriteOutput
  | GlobOutput
  | GrepOutput
  | ListMcpResourcesOutput
  | MonitorOutput
  | NotebookEditOutput
  | ReadMcpResourceOutput
  | TaskCreateOutput
  | TaskGetOutput
  | TaskListOutput
  | TaskStopOutput
  | TaskUpdateOutput
  | 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;
  }>;
};

返回之前和更新后的任务列表。

自 TypeScript Agent SDK 0.3.142 起,TodoWrite 默认禁用。请改用 TaskCreateTaskGetTaskUpdateTaskList。见迁移到 Task 工具更新你的监控代码,或设置 CLAUDE_CODE_ENABLE_TASKS=0 以回退到 TodoWrite

TaskCreate

工具名称: TaskCreate

type TaskCreateOutput = {
  task: {
    id: string;
    subject: string;
  };
};

返回创建的任务及其分配的 ID。

TaskUpdate

工具名称: TaskUpdate

type TaskUpdateOutput = {
  success: boolean;
  taskId: string;
  updatedFields: string[];
  error?: string;
  statusChange?: {
    from: string;
    to: string;
  };
};

返回更新结果,包括哪些字段已更改。

TaskGet

工具名称: TaskGet

type TaskGetOutput = {
  task: {
    id: string;
    subject: string;
    description: string;
    status: "pending" | "in_progress" | "completed";
    blocks: string[];
    blockedBy: string[];
  } | null;
};

返回完整的任务记录,如果 ID 未找到则返回 null

TaskList

工具名称: TaskList

type TaskListOutput = {
  tasks: Array<{
    id: string;
    subject: string;
    status: "pending" | "in_progress" | "completed";
    owner?: string;
    blockedBy: 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 资源的内容。

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";

context-1m-2025-08-07 beta 已于 2026 年 4 月 30 日退役。将此值传递给 Claude Sonnet 4.5 或 Sonnet 4 不会有任何效果,超出标准 200k 令牌上下文窗口的请求将返回错误。要使用 100 万令牌上下文窗口,请迁移到 Claude Sonnet 4.6、Claude Opus 4.6 或 Claude Opus 4.7,它们包含 100 万上下文,标准定价,无需 beta 标头。

SlashCommand

关于可用斜杠命令的信息。

type SlashCommand = {
  name: string;
  description: string;
  argumentHint: string;
  aliases?: 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

mcpServerStatus() 报告的 MCP 服务器配置。这是所有 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/sdkBetaUsage 类型。

type Usage = {
  input_tokens: number;
  output_tokens: number;
  cache_creation_input_tokens: number | null;
  cache_read_input_tokens: number | null;
  cache_creation: {
    ephemeral_5m_input_tokens: number;
    ephemeral_1h_input_tokens: number;
  } | null;
  server_tool_use: BetaServerToolUsage | null;
  service_tier: "standard" | "priority" | "batch" | null;
  speed: "standard" | "fast" | null;
  inference_geo: string | null;
  iterations: BetaIterationsUsage | null;
};

BetaServerToolUsageBetaIterationsUsage@anthropic-ai/sdk 中定义。

CallToolResult

MCP 工具结果类型(来自 @modelcontextprotocol/sdk/types.js)。structuredContent 是一个 JSON 对象,可以随 content 一起返回,包括图像块。见返回结构化数据

type CallToolResult = {
  content: Array<{
    type: "text" | "image" | "resource";
    // 其他字段因类型而异
  }>;
  structuredContent?: Record<string, unknown>;
  isError?: boolean;
};

ThinkingConfig

控制 Claude 的思维/推理行为。优先于已弃用的 maxThinkingTokens

type ThinkingDisplay = "summarized" | "omitted";

type ThinkingConfig =
  | { type: "adaptive"; display?: ThinkingDisplay } // 模型决定何时推理以及推理多少(Opus 4.6+)
  | { type: "enabled"; budgetTokens?: number; display?: ThinkingDisplay } // 固定思维令牌预算
  | { type: "disabled" }; // 无扩展思维

可选的 display 字段控制思维文本是返回 "summarized" 还是 "omitted"。在 Claude Opus 4.7 及更高版本上,API 默认为 "omitted",因此设置 "summarized" 以在 thinking 块中接收思维内容。

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

传递给自定义 spawn 函数的选项。

interface SpawnOptions {
  command: string;
  args: string[];
  cwd?: string;
  env: Record<string, string | undefined>;
  signal: AbortSignal;
}

signal 字段告诉你的 spawn 函数何时终止进程。将其作为 signal 选项传递给 Node 的 spawn(),或传递给虚拟机或容器拆卸处理器。

此信号不会在 Options.abortController 中止时立即触发。SDK 首先关闭进程的 stdin 并等待大约两秒,以便 CLI 可以正常关闭,然后触发此信号。要立即在调用者中止时做出反应,请监听你自己的 Options.abortController.signal,你的 spawn 函数可以从其封闭作用域引用它。

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;
};

SDKToolUseSummaryMessage

对话中工具使用的摘要。

type SDKToolUseSummaryMessage = {
  type: "tool_use_summary";
  summary: string;
  preceding_tool_use_ids: string[];
  uuid: UUID;
  session_id: string;
};

SDKHookStartedMessage

当钩子开始执行时发出。

type SDKHookStartedMessage = {
  type: "system";
  subtype: "hook_started";
  hook_id: string;
  hook_name: string;
  hook_event: string;
  uuid: UUID;
  session_id: string;
};

SDKHookProgressMessage

当钩子正在运行时发出,包含 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

当钩子完成执行时发出。

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;
};

SDKToolProgressMessage

在工具执行期间定期发出,指示进度。

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 字段对于后台 Bash 命令和 Monitor 监视器为 "local_bash",对于子代理为 "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

在子代理或后台任务运行时定期发出。仅当启用了 agentProgressSummaries 时,summary 字段才会被填充。

type SDKTaskProgressMessage = {
  type: "system";
  subtype: "task_progress";
  task_id: string;
  tool_use_id?: string;
  description: string;
  subagent_type?: string;
  usage: {
    total_tokens: number;
    tool_uses: number;
    duration_ms: number;
  };
  last_tool_name?: string;
  summary?: string;
  uuid: UUID;
  session_id: string;
};

SDKTaskUpdatedMessage

当后台任务的状态发生变化时发出,例如从 running 变为 completed。将 patch 合并到以 task_id 为键的本地任务映射中。end_time 字段是以毫秒为单位的 Unix 纪元时间戳,可与 Date.now() 比较。

type SDKTaskUpdatedMessage = {
  type: "system";
  subtype: "task_updated";
  task_id: string;
  patch: {
    status?: "pending" | "running" | "completed" | "failed" | "killed";
    description?: string;
    end_time?: number;
    total_paused_ms?: number;
    error?: string;
    is_backgrounded?: boolean;
  };
  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

本地斜杠命令(例如 /voice/usage)的输出。在记录中以助手样式文本显示。

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 套接字安全: allowUnixSockets 选项可以授予对强大系统服务的访问权限。例如,允许 /var/run/docker.sock 实际上可以通过 Docker API 授予完整的主机系统访问权限,绕过沙箱隔离。只允许严格必要的 Unix 套接字,并了解每个套接字的安全影响。

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 条目被处理,来自用户、项目或本地设置的条目被忽略。通过 SDK 选项设置时无效
allowLocalBinding boolean false 允许进程绑定到本地端口(例如用于开发服务器)
allowUnixSockets string[] [] 进程可以访问的 Unix 套接字路径(例如 Docker 套接字)
allowAllUnixSockets boolean false 允许访问所有 Unix 套接字
httpProxyPort number undefined 网络请求的 HTTP 代理端口
socksProxyPort number undefined 网络请求的 SOCKS 代理端口

内置沙箱代理根据请求的主机名强制执行 allowedDomains,并且不会终止或检查 TLS 流量,因此诸如域名前端之类的技术可能绕过它。见沙箱安全限制了解详情,以及安全部署以配置 TLS 终止代理。

SandboxFilesystemConfig

沙箱模式的文件系统特定配置。

type SandboxFilesystemConfig = {
  allowWrite?: string[];
  denyWrite?: string[];
  denyRead?: string[];
};
属性 类型 默认值 描述
allowWrite string[] [] 允许写入访问的文件路径模式
denyWrite string[] [] 拒绝写入访问的文件路径模式
denyRead string[] [] 拒绝读取访问的文件路径模式

非沙箱命令的权限回退

当启用 allowUnsandboxedCommands 时,模型可以通过在工具输入中设置 dangerouslyDisableSandbox: true 来请求在沙箱外运行命令。这些请求会回退到现有的权限系统,这意味着你的 canUseTool 处理程序被调用,从而允许你实现自定义授权逻辑。

excludedCommandsallowUnsandboxedCommands 的对比:

  • 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 已启用,模型可以自主地在沙箱外执行命令,无需任何批准提示。这种组合有效地允许模型静默地逃离沙箱隔离。

另请参见

常见问题

安装 Agent SDK 后找不到 claude 二进制怎么办?

如果包管理器跳过了可选依赖,SDK 会抛出 Native CLI binary for <platform> not found。可以通过在 query()options 中设置 pathToClaudeCodeExecutable 指向一个单独安装的 claude 二进制路径来解决。

startup() 函数有什么用?

startup() 允许在用户准备好提示之前预先生成并初始化 CLI 子进程,从而消除首次 query() 调用时的子进程生成和初始化延迟。适用于需要在应用启动时减少关键路径延迟的场景。

如何在 SDK 中启用沙箱模式?

query()options 中设置 sandbox: { enabled: true }。可以进一步配置网络限制(allowedDomainsdeniedDomains)、文件系统读写白名单和非沙箱命令回退等。沙箱默认关闭。