English ← MyDocs

文档索引

在此获取完整文档索引:https://code.claude.com/docs/llms.txt 使用此文件发现所有可用页面,然后再进一步探索。

Agent SDK 参考 - TypeScript

TypeScript Agent SDK 的完整 API 参考,包括所有函数、类型和接口。

安装

npm install @anthropic-ai/claude-agent-sdk
Note

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 或更高版本。以下示例为 Apple Silicon 上的 macOS 构建:

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;

参数

参数类型描述
promptstring | AsyncIterable<SDKUserMessage>输入提示词,可以是字符串或用于流式模式的异步可迭代对象
optionsOptions可选配置对象(见下方 Options 类型)

返回值

返回一个 Query 对象,该对象扩展了 AsyncGenerator<SDKMessage, void>,并包含额外的方法。

startup()

通过派生 CLI 子进程并完成初始化握手来预热,使子进程在提示词准备好之前就已就绪。返回的 WarmQuery 句柄稍后接受提示词并将其写入已准备好的进程,因此第一次 query() 调用无需支付子进程派生和初始化的开销。

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

参数

参数类型描述
optionsOptions可选配置对象。与 query()options 参数相同
initializeTimeoutMsnumber等待子进程初始化的最大时间(毫秒)。默认为 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);
}

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

参数

参数类型描述
namestring工具名称
descriptionstring工具功能的描述
inputSchemaSchema extends AnyZodRawShape定义工具输入参数的 Zod 模式(支持 Zod 3 和 Zod 4)
handler(args, extra) => Promise<CallToolResult>执行工具逻辑的异步函数
extras{ annotations?: ToolAnnotations }可选的 MCP 工具注解,为客户端提供行为提示

ToolAnnotations

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

字段类型默认值描述
titlestringundefined工具的人类可读标题
readOnlyHintbooleanfalse如果为 true,工具不会修改其环境
destructiveHintbooleantrue如果为 true,工具可能执行破坏性更新(仅在 readOnlyHintfalse 时有意义)
idempotentHintbooleanfalse如果为 true,使用相同参数重复调用不会产生额外效果(仅在 readOnlyHintfalse 时有意义)
openWorldHintbooleantrue如果为 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.namestringMCP 服务器名称
options.versionstring可选版本字符串
options.toolsArray<SdkMcpToolDefinition>使用 tool() 创建的工具定义数组

listSessions()

发现并列出过去的会话及其轻量元数据。按项目目录过滤或列出所有项目的会话。

function listSessions(options?: ListSessionsOptions): Promise<SDKSessionInfo[]>;

参数

参数类型默认值描述
options.dirstringundefined要列出会话的目录。省略时返回所有项目的会话
options.limitnumberundefined要返回的最大会话数
options.includeWorktreesbooleantruedir 在 git 仓库内时,包含所有 worktree 路径的会话

返回类型:SDKSessionInfo

属性类型描述
sessionIdstring唯一会话标识符(UUID)
summarystring显示标题:自定义标题、自动生成的摘要或第一个提示词
lastModifiednumber最后修改时间,自纪元以来的毫秒数
fileSizenumber | undefined会话文件大小(字节)。仅对本地 JSONL 存储填充
customTitlestring | undefined用户设置的会话标题(通过 /rename
firstPromptstring | undefined会话中第一个有意义的用户提示词
gitBranchstring | undefined会话结束时的 Git 分支
cwdstring | undefined会话的工作目录
tagstring | undefined用户设置的会话标签(参见 tagSession()
createdAtnumber | 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[]>;

参数

参数类型默认值描述
sessionIdstring必填要读取的会话 UUID(参见 listSessions()
options.dirstringundefined查找会话的项目目录。省略时搜索所有项目
options.limitnumberundefined要返回的最大消息数
options.offsetnumberundefined从开头跳过的消息数

返回类型:SessionMessage

属性类型描述
type"user" | "assistant"消息角色
uuidstring唯一消息标识符
session_idstring此消息所属的会话
messageunknown来自记录的原始消息负载
parent_tool_use_idstring | 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>;

参数

参数类型默认值描述
sessionIdstring必填要查找的会话 UUID
options.dirstringundefined项目目录路径。省略时搜索所有项目目录

返回 SDKSessionInfo,如果会话未找到则返回 undefined

renameSession()

通过追加自定义标题条目来重命名会话。重复调用是安全的;最新的标题生效。

function renameSession(
  sessionId: string,
  title: string,
  options?: SessionMutationOptions
): Promise<void>;

参数

参数类型默认值描述
sessionIdstring必填要重命名的会话 UUID
titlestring必填新标题。去除空白后必须非空
options.dirstringundefined项目目录路径。省略时搜索所有项目目录

tagSession()

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

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

参数

参数类型默认值描述
sessionIdstring必填要添加标签的会话 UUID
tagstring | null必填标签字符串,或 null 以清除
options.dirstringundefined项目目录路径。省略时搜索所有项目目录

resolveSettings()

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

Note

此函数处于 alpha 阶段,其 API 在稳定之前可能会更改。它读取 MDM 源(包括 macOS plist 和 Windows HKLM/HKCU),以与 CLI 启动保持一致,但不会执行管理员配置的 policyHelper 子进程。permissions.defaultMode 字段从所有层级(包括项目设置)原样返回。CLI 在执行升级权限模式之前应用的信任过滤器不会被应用。

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

参数

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

参数类型默认值描述
options.cwdstringprocess.cwd()解析项目和本地设置时相对的目录
options.settingSourcesSettingSource[]所有源要加载的文件系统源。传递 [] 可跳过用户、项目和本地设置。托管策略设置在所有情况下都会加载
options.managedSettingsSettingsundefined由嵌入宿主提供的限制性策略层设置。默认情况下,当存在管理员部署的托管层时会被丢弃;当 parentSettingsBehavior"merge" 时,会合并到该层之下。非限制性键(如 model)会被静默丢弃,因此此选项可以收紧托管策略但不能放松
options.serverManagedSettingsSettingsundefined来自 /api/claude_code/settings 的服务器托管设置负载。非限制性键会原样通过

返回类型:ResolvedSettings

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

属性类型描述
effectiveSettings按优先级顺序应用所有启用源后的合并设置
provenancePartial<Record<keyof Settings, ProvenanceEntry>>对于 effective 中的每个顶级键,哪个源提供了值
sourcesArray<{ 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() 函数的配置对象。

属性类型默认值描述
abortControllerAbortControllernew AbortController()用于取消操作的控制器
additionalDirectoriesstring[][]Claude 可以访问的额外目录
agentstringundefined主线程的代理名称。代理必须在 agents 选项或设置中定义
agentsRecord<string, [AgentDefinition](#agentdefinition)>undefined以编程方式定义子代理
agentProgressSummariesbooleanfalsetrue 时,为子代理生成单行进度摘要,并通过 task_progress 事件的 summary 字段转发。适用于前台和后台子代理
allowDangerouslySkipPermissionsbooleanfalse启用绕过权限。使用 permissionMode: 'bypassPermissions' 时必需
allowedToolsstring[][]无需提示即可自动批准的工具。这不会将 Claude 限制为仅这些工具;未列出的工具会回退到 permissionModecanUseTool。使用 disallowedTools 来阻止工具。参见 权限
betasSdkBeta[][]启用 beta 功能
canUseToolCanUseToolundefined用于工具使用的自定义权限函数
continuebooleanfalse继续最近的对话
cwdstringprocess.cwd()当前工作目录
debugbooleanfalse为 Claude Code 进程启用调试模式
debugFilestringundefined将调试日志写入特定文件路径。隐式启用调试模式
disallowedToolsstring[][]要拒绝的工具。裸名称(如 "Bash")会从 Claude 的上下文中移除该工具。带范围的规则(如 "Bash(rm *)")保留工具可用,但在每种权限模式下(包括 bypassPermissions)拒绝匹配的调用。参见 权限
effort'low' | 'medium' | 'high' | 'xhigh' | 'max''high'控制 Claude 在响应中投入的精力。与自适应思维配合使用以引导思维深度
enableFileCheckpointingbooleanfalse启用文件更改跟踪以支持回退。参见 文件检查点
envRecord<string, string | undefined>process.env环境变量。设置时,这会替换子进程环境而不是与 process.env 合并,因此传递 { ...process.env, YOUR_VAR: 'value' } 以保留继承的变量如 PATH。参见 处理缓慢或停滞的 API 响应 了解此模式的示例,以及 环境变量 了解底层 CLI 读取的变量。设置 CLAUDE_AGENT_SDK_CLIENT_APP 以在 User-Agent 头中标识您的应用
executable'bun' | 'deno' | 'node'自动检测要使用的 JavaScript 运行时
executableArgsstring[][]传递给可执行文件的参数
extraArgsRecord<string, string | null>{}额外参数
fallbackModelstringundefined主模型失败时使用的模型
forkSessionbooleanfalse使用 resume 恢复时,分叉到新的会话 ID 而不是继续原始会话
forwardSubagentTextbooleanfalse将子代理文本和思维块作为助手和用户消息转发,并设置 parent_tool_use_id,以便消费者可以渲染嵌套记录。默认情况下只发出子代理的 tool_usetool_result
hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>{}事件的钩子回调
includeHookEventsbooleanfalse在消息流中包含钩子生命周期事件,作为 SDKHookStartedMessageSDKHookProgressMessageSDKHookResponseMessage
includePartialMessagesbooleanfalse包含部分消息事件
loadTimeoutMsnumber60000Alpha。 恢复物化期间每个 sessionStore.load()sessionStore.listSubkeys() 调用的超时时间(毫秒)。如果适配器在此窗口内未完成,查询将失败而不是挂起。未设置 sessionStore 时忽略
managedSettingsSettingsundefined由派生父进程提供的策略层设置。当机器上已存在 IT 控制的托管设置层时会被丢弃,除非管理员通过 parentSettingsBehavior: 'merge' 选择合并。无论何种情况都会过滤为仅限制性键
maxBudgetUsdnumberundefined当客户端成本估算达到此美元值时停止查询。与 total_cost_usd 使用相同的估算进行比较;参见 跟踪成本和使用量 了解准确性注意事项
maxThinkingTokensnumberundefined已弃用: 请改用 thinking。思维过程的最大 token 数
maxTurnsnumberundefined最大代理轮次(工具使用往返)
mcpServersRecord<string, [McpServerConfig](#mcpserverconfig)>{}MCP 服务器配置
modelstringCLI 默认值要使用的 Claude 模型
onElicitation(request: ElicitationRequest, options: { signal: AbortSignal }) => Promise<ElicitationResult>undefined处理 MCP 引出请求的回调。当 MCP 服务器请求用户输入且没有钩子首先处理时调用。未提供时,未处理的引出请求会被自动拒绝
outputFormat{ type: 'json_schema', schema: JSONSchema }undefined定义代理结果的输出格式。参见 结构化输出 了解详情
outputStylestringundefined不是 Options 字段。请在内联 settings 对象或设置文件中设置 outputStyle。参见 激活输出样式
pathToClaudeCodeExecutablestring从捆绑的原生二进制文件自动解析Claude Code 可执行文件路径。仅在安装期间跳过了可选依赖项或您的平台不在支持集中时需要
permissionModePermissionMode'default'会话的权限模式
permissionPromptToolNamestringundefined用于权限提示的 MCP 工具名称
persistSessionbooleantruefalse 时,禁用会话持久化到磁盘。会话无法稍后恢复
planModeInstructionsstringundefined计划模式的自定义工作流指令。当 permissionMode'plan' 时,此字符串替换默认的计划模式工作流正文。CLI 仍会用只读执行前言和 ExitPlanMode 协议页脚包装它
pluginsSdkPluginConfig[][]从本地路径加载自定义插件。参见 插件 了解详情
promptSuggestionsbooleanfalse启用提示建议。在每轮之后发出 prompt_suggestion 消息,包含预测的下一个用户提示词
resumestringundefined要恢复的会话 ID
resumeSessionAtstringundefined在特定消息 UUID 处恢复会话
sandboxSandboxSettingsundefined以编程方式配置沙箱行为。参见 沙箱设置 了解详情
sessionIdstring自动生成使用特定 UUID 而不是自动生成
sessionStoreSessionStoreundefined将会话记录镜像到外部后端,以便任何宿主都可以恢复它们。参见 将会话持久化到外部存储
sessionStoreFlush'batched' | 'eager''batched'Alpha。 sessionStore 的刷新模式。未设置 sessionStore 时忽略
settingsstring | Settingsundefined内联 设置 对象或设置文件路径。填充 优先级顺序 中的标志设置层。使用 applyFlagSettings() 在运行时更改
settingSourcesSettingSource[]CLI 默认值(所有源)控制加载哪些文件系统设置。传递 [] 可禁用用户、项目和本地设置。托管策略设置无论如何都会加载。参见 使用 Claude Code 功能
skillsstring[] | 'all'undefined会话可用的技能。传递 'all' 以启用所有发现的技能,或传递技能名称列表。设置时,SDK 自动启用 Skill 工具而无需在 allowedTools 中列出。参见 技能
spawnClaudeCodeProcess(options: SpawnOptions) => SpawnedProcessundefined用于派生 Claude Code 进程的自定义函数。用于在 VM、容器或远程环境中运行 Claude Code
stderr(data: string) => voidundefinedstderr 输出的回调
strictMcpConfigbooleanfalse仅使用 mcpServers 中传入的服务器,忽略项目 .mcp.json、用户设置和插件提供的 MCP 服务器
systemPromptstring | { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean }undefined(最小提示词)系统提示词配置。传递字符串用于自定义提示词,或 { type: 'preset', preset: 'claude_code' } 以使用 Claude Code 的系统提示词。使用预设对象形式时,添加 append 以扩展附加指令,并设置 excludeDynamicSections: true 将每会话上下文移至第一条用户消息,以获得 跨机器更好的提示缓存复用
taskBudget{ total: number }undefinedAlpha。 API 侧的任务 token 预算。设置时,模型会被告知其剩余 token 预算,以便它可以控制工具使用并在限制之前完成
thinkingThinkingConfig受支持模型为 { type: 'adaptive' }控制 Claude 的思维/推理行为。参见 ThinkingConfig 了解选项
titlestringundefined会话的显示标题。通过 resumecontinue 恢复时,恢复会话的持久化标题优先;使用 renameSession() 重命名现有会话
toolAliasesRecord<string, string>undefined将内置工具名称映射到 MCP 工具名称,以便 Claude 调用您的 MCP 实现代替内置工具。例如 { Bash: 'mcp__workspace__bash' }
toolConfigToolConfigundefined内置工具行为的配置。参见 ToolConfig 了解详情
toolsstring[] | { 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_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 选项。更改最大思维 token 数
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() 是接受任何设置键子集的通用形式,在此传递 modelsetModel() 行为相同。

值被写入标志设置层,与 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 });
Note

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'本地项目设置(gitignore).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>;
选项类型描述
signalAbortSignal如果操作应被中止则发出信号
suggestionsPermissionUpdate[]建议的权限更新,以便不会再次提示用户此工具。Bash 提示包含带有 localSettings 目标 的建议,因此在 updatedPermissions 中返回它会将规则写入 .claude/settings.local.json 并跨会话持久化
blockedPathstring触发权限请求的文件路径(如适用)
decisionReasonstring解释为什么触发了此权限请求
toolUseIDstring助手消息中此特定工具调用的唯一标识符
agentIDstring如果在子代理内运行,表示子代理的 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'(目前仅支持本地插件)
pathstring插件目录的绝对或相对路径

示例:

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:首个 token 的时间(毫秒)。仅在成功分支上存在。
  • 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_namestring被拒绝的工具名称
tool_use_idstring此拒绝回应的 tool_use 块的 ID
agent_idstring当被拒绝的调用源自子代理内部时的子代理 ID。镜像 can_use_tool 上的字段以用于宿主侧路由
decision_reason_typestring决策组件的区分符,如 "rule""mode""classifier""asyncAgent"
decision_reasonstring来自决策组件的人类可读原因(如可用)
messagestringtool_result 中返回给模型的拒绝消息

SDKPermissionDenial

被拒绝的工具使用信息。

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

SDKMessageOrigin

用户角色消息的来源。这出现在 SDKUserMessageorigin 上,并被转发到相应的 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;
  }>;
};

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

Note

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

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

Note

从 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" // gitignore 的本地设置
  | "session" // 仅当前会话
  | "cliArg"; // CLI 参数

PermissionRuleValue

type PermissionRuleValue = {
  toolName: string;
  ruleContent?: string;
};

其他类型

ApiKeySource

type ApiKeySource = "user" | "project" | "org" | "temporary" | "oauth";

SdkBeta

可通过 betas 选项启用的可用 beta 功能。参见 Beta 头 了解更多信息。

type SdkBeta = "context-1m-2025-08-07";
Warning

context-1m-2025-08-07 beta 已于 2026 年 4 月 30 日退役。对 Claude Sonnet 4.5 或 Sonnet 4 传递此值无效,超过标准 200k token 上下文窗口的请求会返回错误。要使用 1M token 上下文窗口,请迁移到 Claude Sonnet 4.6、Claude Opus 4.6 或 Claude Opus 4.7,它们以标准价格包含 1M 上下文,无需 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;
};
字段类型描述
namestring代理类型标识符(例如 "Explore""general-purpose"
descriptionstring何时使用此代理的描述
modelstring | 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

Token 使用统计。这是来自 @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 是可以与 content 一起返回的 JSON 对象,包括图像块。参见 返回结构化数据

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 } // 固定思维 token 预算
  | { 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

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

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

signal 字段告诉您的派生函数何时拆除进程。将其作为 signal 选项传递给 Node 的 spawn(),或传递给您的 VM 或容器拆除处理器。

此信号不会在 Options.abortController 中止的瞬间触发。SDK 首先关闭进程的 stdin 并等待约两秒以便 CLI 可以干净地关闭,然后中止此信号。要在调用者中止的瞬间做出反应,请监听您自己的 Options.abortController.signal,您的派生函数可以从其封闭作用域引用它。

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

子代理或后台任务运行期间定期发出。summary 字段仅在启用 agentProgressSummaries 时填充。

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[] };
};
属性类型默认值描述
enabledbooleanfalse为命令执行启用沙箱模式
autoAllowBashIfSandboxedbooleantrue启用沙箱时自动批准 bash 命令
excludedCommandsstring[][]始终绕过沙箱限制的命令(例如 ['docker'])。这些命令无需模型参与自动以非沙箱方式运行
allowUnsandboxedCommandsbooleantrue允许模型请求在沙箱外运行命令。为 true 时,模型可以在工具输入中设置 dangerouslyDisableSandbox,这会回退到 权限系统
networkSandboxNetworkConfigundefined网络特定的沙箱配置
filesystemSandboxFilesystemConfigundefined文件系统特定的沙箱配置,用于读写限制
ignoreViolationsRecord<string, string[]>undefined违规类别到忽略模式的映射(例如 { file: ['/tmp/*'], network: ['localhost'] }
enableWeakerNestedSandboxbooleanfalse启用较弱的嵌套沙箱以提高兼容性
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);
}
Warning

Unix socket 安全: allowUnixSockets 选项可以授予对强大系统服务的访问权限。例如,允许 /var/run/docker.sock 实际上通过 Docker API 授予完整的宿主系统访问权限,绕过沙箱隔离。仅允许严格必要的 Unix socket,并了解每个的安全影响。

SandboxNetworkConfig

沙箱模式的网络特定配置。

type SandboxNetworkConfig = {
  allowedDomains?: string[];
  deniedDomains?: string[];
  allowManagedDomainsOnly?: boolean;
  allowLocalBinding?: boolean;
  allowUnixSockets?: string[];
  allowAllUnixSockets?: boolean;
  httpProxyPort?: number;
  socksProxyPort?: number;
};
属性类型默认值描述
allowedDomainsstring[][]沙箱进程可以访问的域名
deniedDomainsstring[][]沙箱进程无法访问的域名。优先于 allowedDomains
allowManagedDomainsOnlybooleanfalse仅限托管设置。在 托管设置 中设置时,仅遵循托管设置中的 allowedDomains 条目,忽略用户、项目或本地设置中的条目。通过 SDK 选项设置时无效
allowLocalBindingbooleanfalse允许进程绑定到本地端口(例如用于开发服务器)
allowUnixSocketsstring[][]进程可以访问的 Unix socket 路径(例如 Docker socket)
allowAllUnixSocketsbooleanfalse允许访问所有 Unix socket
httpProxyPortnumberundefined用于网络请求的 HTTP 代理端口
socksProxyPortnumberundefined用于网络请求的 SOCKS 代理端口
Note

内置沙箱代理基于请求的主机名强制执行 allowedDomains,不终止或检查 TLS 流量,因此 域前置 等技术可能绕过它。参见 沙箱安全限制 了解详情,以及 安全部署 了解配置 TLS 终止代理。

SandboxFilesystemConfig

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

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

非沙箱命令的权限回退

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

Note

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

此模式使您能够:

  • 审计模型请求: 记录模型请求非沙箱执行的时间
  • 实现允许列表: 仅允许特定命令以非沙箱方式运行
  • 添加审批工作流: 为特权操作要求显式授权
Warning

使用 dangerouslyDisableSandbox: true 运行的命令具有完整的系统访问权限。确保您的 canUseTool 处理器仔细验证这些请求。

如果 permissionMode 设置为 bypassPermissions 且启用了 allowUnsandboxedCommands,模型可以在没有任何审批提示的情况下自主执行沙箱外的命令。此组合实际上允许模型静默逃逸沙箱隔离。

另请参阅