本页目录17
- 核心入口是 query({ prompt, options }),返回实现 AsyncGenerator<SDKMessage, void> 的 Query 对象,可用于流式获取消息
- startup() 可在拿到 prompt 之前预热 CLI 子进程,返回 WarmQuery,适合降低首次响应延迟
- tool() 用 Zod schema 定义类型安全的 MCP 工具,配合 createSdkMcpServer() 组装进程内 MCP 服务器
- Options 对象有 50+ 配置项,覆盖权限模式、hooks、MCP 服务器、系统提示词、思考(thinking)、沙箱等
- Query 对象暴露 interrupt()/setPermissionMode()/setModel()/rewindFiles() 等运行时控制方法,部分方法仅在流式输入模式下可用
- 会话管理函数(listSessions/getSessionMessages/getSessionInfo/renameSession/tagSession)可在不启动完整会话的情况下读写历史会话元数据
本文是对官方 Agent SDK TypeScript 参考页的中文整理,完整与最新内容以原文为准:https://code.claude.com/docs/en/agent-sdk/typescript
安装
npm install @anthropic-ai/claude-agent-sdk
关于原生二进制文件的说明: SDK 将平台专属的 Claude Code 二进制文件作为可选依赖(optional dependencies)打包。SDK 版本号与其打包的 Claude Code 版本对应(例如 SDK v0.3.191 打包 Claude Code v2.1.191)。如果可选依赖被跳过安装,需要将 pathToClaudeCodeExecutable 设置为一个单独安装好的 claude 可执行文件路径。
用 Bun 编译为单一可执行文件
使用 bun build --compile 时,需要用 extractFromBunfs() 辅助函数:
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);
}
函数
query()
与 Claude Code 交互的主函数,创建一个流式返回消息的 async generator。
function query({
prompt,
options
}: {
prompt: string | AsyncIterable<SDKUserMessage>;
options?: Options;
}): Query;
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
prompt | string | AsyncIterable<SDKUserMessage> | 输入的提示词;流式模式下传入 async iterable |
options | Options | 可选配置 |
返回值: Query 对象,继承自 AsyncGenerator<SDKMessage, void>
startup()
在拿到 prompt 之前预热 CLI 子进程。
function startup(params?: {
options?: Options;
initializeTimeoutMs?: number;
}): Promise<WarmQuery>;
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
options | Options | 与 query() 的 options 相同 | |
initializeTimeoutMs | number | 60000 | 等待初始化完成的最长毫秒数 |
返回值: Promise<WarmQuery>,子进程初始化完成后 resolve
示例:
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 工具定义。
function tool<Schema extends AnyZodRawShape>(
name: string,
description: string,
inputSchema: Schema,
handler: (args: InferShape<Schema>, extra: unknown) => Promise<CallToolResult>,
extras?: { annotations?: ToolAnnotations; searchHint?: string; alwaysLoad?: boolean }
): SdkMcpToolDefinition<Schema>;
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
name | string | 工具名称 |
description | string | 工具的功能描述 |
inputSchema | Zod schema | 工具的输入参数(支持 Zod 3 与 Zod 4) |
handler | async function | 执行工具逻辑 |
extras(可选) | 见下 |
extras 可选字段:
annotations: MCP 行为提示(从@modelcontextprotocol/sdk/types.js重新导出)searchHint: 一行描述工具能力的短语,用于延迟加载工具列表alwaysLoad: 让该工具的完整 schema 始终出现在初始 prompt 中,而不是被延迟加载
ToolAnnotations(均为可选字段):
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
title | string | undefined | 人类可读的标题 |
readOnlyHint | boolean | false | 该工具不修改环境 |
destructiveHint | boolean | true | 该工具可能执行破坏性更新 |
idempotentHint | boolean | false | 重复调用不会产生额外效果 |
openWorldHint | boolean | true | 与外部实体交互 |
示例:
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()
创建一个进程内(in-process)MCP 服务器实例。
function createSdkMcpServer(options: {
name: string;
version?: string;
instructions?: string;
tools?: Array<SdkMcpToolDefinition<any>>;
alwaysLoad?: boolean;
}): McpSdkServerConfigWithInstance;
参数:
| 参数 | 类型 | 说明 |
|---|---|---|
name | string | 服务器名称 |
version | string | 可选版本号 |
instructions | string | 可选的服务器说明 |
tools | array | 用 tool() 创建的工具定义列表 |
alwaysLoad | boolean | 让所有工具始终留在初始 prompt 中,不被延迟加载 |
listSessions()
发现并列出过往会话及其轻量元数据。
function listSessions(options?: ListSessionsOptions): Promise<SDKSessionInfo[]>;
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
options.dir | string | undefined | 要列出会话的目录(不传则列出所有项目) |
options.limit | number | undefined | 返回的最大会话数 |
options.includeWorktrees | boolean | true | 是否包含来自 git worktree 路径的会话 |
返回类型 SDKSessionInfo:
| 属性 | 类型 | 说明 |
|---|---|---|
sessionId | string | 唯一 UUID |
summary | string | 展示标题 |
lastModified | number | 最后修改时间(自纪元起的毫秒数) |
fileSize | number | undefined | 会话文件大小(字节) |
customTitle | string | undefined | 用户设置的标题 |
firstPrompt | string | undefined | 第一条有意义的用户 prompt |
gitBranch | string | undefined | 结束时所在的 git 分支 |
cwd | string | undefined | 工作目录 |
tag | string | undefined | 用户设置的会话标签 |
createdAt | number | undefined | 创建时间(自纪元起的毫秒数) |
示例:
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()
读取过往会话记录(transcript)中的用户与助手消息。
function getSessionMessages(
sessionId: string,
options?: GetSessionMessagesOptions
): Promise<SessionMessage[]>;
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
sessionId | string | 必填 | 会话 UUID |
options.dir | string | undefined | 项目目录(不传则搜索所有项目) |
options.limit | number | undefined | 返回的最大消息数 |
options.offset | number | undefined | 从开头跳过的消息数 |
返回类型 SessionMessage:
| 属性 | 类型 | 说明 |
|---|---|---|
type | "user" | "assistant" | 消息角色 |
uuid | string | 唯一消息 ID |
session_id | string | 所属会话 |
message | unknown | 原始消息 payload |
parent_tool_use_id | string | null | 子代理(subagent)消息对应的产生该消息的工具调用 ID |
parent_agent_id | string | null | 嵌套子代理场景下,产生该消息的子代理 ID(需要 v2.1.202+) |
示例:
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 | 必填 | 新标题(trim 后不能为空) |
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 设置。
function resolveSettings(
options?: ResolveSettingsOptions
): Promise<ResolvedSettings>;
参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
options.cwd | string | process.cwd() | 解析所依据的目录 |
options.settingSources | SettingSource[] | 全部来源 | 要加载哪些设置来源 |
options.managedSettings | Settings | undefined | 来自宿主(embedding host)的策略层(policy-tier)设置 |
options.serverManagedSettings | Settings | undefined | 服务端管理的设置 payload |
返回类型 ResolvedSettings:
| 属性 | 类型 | 说明 |
|---|---|---|
effective | Settings | 应用所有来源后合并出的最终设置 |
provenance | Partial<Record<keyof Settings, ProvenanceEntry>> | 每个顶层字段对应的来源 |
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 | 主线程使用的 agent 名称 |
agents | Record<string, AgentDefinition> | undefined | 以编程方式定义子代理(subagents) |
agentProgressSummaries | boolean | false | 为子代理生成一行进度摘要 |
allowDangerouslySkipPermissions | boolean | false | 启用绕过权限检查(bypassPermissions 模式需要它) |
allowedTools | string[] | [] | 自动批准、无需提示的工具 |
betas | SdkBeta[] | [] | 启用 beta 功能 |
canUseTool | CanUseTool | undefined | 自定义权限判断函数 |
continue | boolean | false | 继续最近的一次对话 |
cwd | string | process.cwd() | 当前工作目录 |
debug | boolean | false | 启用调试模式 |
debugFile | string | undefined | 将调试日志写入的文件路径 |
disallowedTools | string[] | [] | 要禁止使用的工具 |
effort | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 模型默认值 | 响应的努力程度(effort level) |
enableFileCheckpointing | boolean | false | 启用文件变更跟踪,以支持回退(rewind) |
env | Record<string, string | undefined> | process.env | 环境变量 |
executable | 'bun' | 'deno' | 'node' | 自动检测 | 使用的 JavaScript 运行时 |
executableArgs | string[] | [] | 传给可执行文件的参数 |
extraArgs | Record<string, string | null> | {} | 额外参数 |
fallbackModel | string | undefined | 主模型失败时使用的备用模型 |
forkSession | boolean | false | 复制(fork)出一个新的会话 ID,而不是延续原会话 |
forwardSubagentText | boolean | false | 转发子代理的文本/思考(thinking)内容块作为消息 |
hooks | Partial<Record<HookEvent, HookCallbackMatcher[]>> | {} | Hook 回调 |
includeHookEvents | boolean | false | 在消息流中包含 hook 生命周期事件 |
includePartialMessages | boolean | false | 包含部分消息(partial message)事件 |
loadTimeoutMs | number | 60000 | sessionStore.load() 调用的超时时间 |
managedSettings | Settings | undefined | 来自宿主(embedding host)的策略层设置 |
maxBudgetUsd | number | undefined | 当预估花费(美元)达到该值时停止 |
maxThinkingTokens | number | undefined | 已废弃:改用 thinking |
maxTurns | number | undefined | 最大 agentic 轮次 |
mcpServers | Record<string, McpServerConfig> | {} | MCP 服务器配置 |
model | string | CLI 的默认值 | Claude 模型别名或完整名称 |
onElicitation | (request, options) => Promise<ElicitationResult> | undefined | MCP elicitation 请求的回调函数 |
outputFormat | { type: 'json_schema', schema: JSONSchema } | undefined | 定义结构化输出格式 |
outputStyle | string | undefined | 不是 Options 的字段:应在 settings 或配置文件中设置 |
pathToClaudeCodeExecutable | string | 自动解析 | Claude Code 可执行文件路径 |
permissionMode | PermissionMode | 'default' | 会话的权限模式 |
permissionPromptToolName | string | undefined | 用于权限提示的 MCP 工具名 |
persistSession | boolean | true | 是否将会话持久化到磁盘 |
planModeInstructions | string | undefined | plan 模式下的自定义工作流说明 |
plugins | SdkPluginConfig[] | [] | 从本地路径加载自定义插件 |
promptSuggestions | boolean | false | 启用 prompt 建议 |
resume | string | undefined | 要恢复的会话 ID |
resumeDropsTurn | string | undefined | 截断式恢复(truncating resume)时要丢弃的那一轮对应的 prompt UUID |
resumeSessionAt | string | undefined | 从指定的消息 UUID 处恢复会话 |
sandbox | SandboxSettings | undefined | 配置沙箱行为 |
sessionId | string | 自动生成 | 使用指定的 UUID,而不是自动生成 |
sessionStore | SessionStore | undefined | 将会话记录镜像到外部存储后端 |
sessionStoreFlush | 'batched' | 'eager' | 'batched' | sessionStore 的写入(flush)模式 |
settings | string | Settings | undefined | 内联设置对象,或设置文件的路径 |
settingSources | SettingSource[] | CLI 默认值 | 加载哪些文件系统来源的设置 |
skills | string[] | 'all' | undefined | 会话可用的技能(skills) |
spawnClaudeCodeProcess | (options: SpawnOptions) => SpawnedProcess | undefined | 自定义的子进程启动函数 |
stderr | (data: string) => void | undefined | stderr 输出的回调函数 |
strictMcpConfig | boolean | false | 仅使用传入的 mcpServers,忽略项目/用户级来源 |
systemPrompt | string | { type: 'preset'; preset: 'claude_code'; ... } | undefined | 系统提示词配置 |
taskBudget | { total: number } | undefined | Alpha 特性:API 侧的任务 token 预算 |
thinking | ThinkingConfig | { type: 'adaptive' } | 控制思考(thinking/reasoning)行为 |
title | string | undefined | 会话的展示标题 |
toolAliases | Record<string, string> | undefined | 将内置工具映射到 MCP 实现 |
toolConfig | ToolConfig | undefined | 内置工具行为的配置 |
tools | string[] | { type: 'preset'; preset: 'claude_code' } | undefined | 工具配置 |
注:原文中对
SdkBeta、CanUseTool、PermissionMode、SandboxSettings、ThinkingConfig、ToolConfig、SettingSource、SdkPluginConfig等子类型仅给出了跳转链接,未在本页展开完整定义,因此本整理未编造这些类型的具体结构,请以原文对应子页面为准。
处理缓慢或卡住的 API 响应
import { query } from "@anthropic-ai/claude-agent-sdk";
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 | 单次请求超时(毫秒) | 600000 |
CLAUDE_CODE_MAX_RETRIES | 最大重试次数 | 10,上限 15 |
CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS | 后台子代理的卡住(stall)看门狗超时 | 600000 |
CLAUDE_ENABLE_STREAM_WATCHDOG | 启用流空闲超时检测 | 默认启用 |
CLAUDE_STREAM_IDLE_TIMEOUT_MS | 流空闲超时时间 | 默认 300000,最小 300000 |
Query 对象
query() 函数返回的接口。
interface Query extends AsyncGenerator<SDKMessage, void> {
interrupt(): Promise<SDKControlInterruptResponse | undefined>;
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>;
reinitialize(): Promise<SDKControlInitializeResponse>;
supportedCommands(): Promise<SlashCommand[]>;
supportedModels(): Promise<ModelInfo[]>;
supportedAgents(): Promise<AgentInfo[]>;
mcpServerStatus(): Promise<McpServerStatus[]>;
getContextUsage(): Promise<SDKControlGetContextUsageResponse>;
readFile(
path: string,
options?: { maxBytes?: number; encoding?: 'utf-8' | 'base64' }
): Promise<SDKControlReadFileResponse | null>;
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() | 中断查询(仅流式输入模式下可用)。若 CLI 为 v2.1.205+,返回带有排队消息的 SDKControlInterruptResponse,否则返回 undefined |
rewindFiles(userMessageId, options?) | 将文件恢复到指定用户消息时的状态。传入 { dryRun: true } 可预览而不实际执行;需要 enableFileCheckpointing: true |
setPermissionMode() | 更改权限模式(仅流式输入模式下可用) |
setModel() | 更改模型(仅流式输入模式下可用)。传入 undefined 或 "default" 可重置 |
setMaxThinkingTokens() | 已废弃:改用 thinking 选项 |
applyFlagSettings(settings) | 在运行时将设置合并进会话的 flag 层(仅流式输入模式下可用) |
initializationResult() | 返回完整的初始化结果,包含命令列表、模型列表、账户信息、输出样式等 |
reinitialize() | 重新发送 initialize 控制请求,返回最新结果。用于传输中断后的恢复;需要 v2.1.195+ |
supportedCommands() | 返回可用的斜杠命令。从 v0.3.216 起,能反映会话过程中的变化 |
supportedModels() | 返回可用模型及其展示信息 |
supportedAgents() | 返回可用的 agent |
mcpServerStatus() | 返回 MCP 服务器状态 |
getContextUsage() | 返回上下文用量信息 |
readFile(path, options?) | 从会话目录读取文件,默认最大 50MB,支持 utf-8 或 base64 编码 |
accountInfo() | 返回账户信息 |
reconnectMcpServer(serverName) | 重新连接 MCP 服务器 |
toggleMcpServer(serverName, enabled) | 启用/禁用 MCP 服务器 |
setMcpServers(servers) | 设置 MCP 服务器配置 |
streamInput(stream) | 向运行中的会话发送一个消息的 async iterable |
stopTask(taskId) | 停止一个正在运行的任务 |
close() | 关闭该查询 |
小结
TypeScript Agent SDK 提供以下方面的 API:
- 通过
query()查询 Claude Code,支持流式返回结果 - 用
startup()预热会话 - 用类型安全的
tool()函数定义工具 - 创建与配置 MCP 服务器
- 会话管理(列出、获取、重命名、打标签)
- 不启动 CLI 即可解析设置
- 通过
Options对象进行丰富的配置(50+ 项设置) - 通过
Query对象方法进行运行时控制
所有函数均为异步,并支持流式输入/输出,用于交互式多轮对话。