TypeScript SDK 的主要入口是 query() 函数,返回 Query 对象(扩展自 AsyncGenerator<SDKMessage>)。还提供 startup() 预热函数和 tool() 工具定义函数。

核心机制

三个主要函数:

  • query():主入口,创建 async generator 流式接收消息
  • startup():预热 CLI 子进程,减少首次 query 的启动延迟
  • tool():创建类型安全的 MCP 工具定义(配合 Zod schema)

Options 核心字段(camelCase):

  • allowedTools:预批准工具列表
  • permissionMode:权限模式
  • systemPrompt:系统提示(字符串或 preset 对象)
  • settingSources:文件系统配置来源
  • maxTurns:最大工具调用轮次
  • maxBudgetUsd:费用上限
  • effort:推理深度
  • model:模型 ID
  • cwd:工作目录
  • mcpServers:MCP 服务器配置
  • hooks:Hook 回调配置
  • agents:子 Agent 定义
  • resume:恢复的 session ID
  • forkSession:是否 fork 会话
  • outputFormat:结构化输出 Schema
  • skills:可用 Skills 控制
  • plugins:插件列表
  • env:环境变量(完全替换继承环境,需包含 ...process.env)
  • canUseTool:工具审批回调
  • includePartialMessages:启用流式输出
  • persistSession:是否持久化会话(false = 纯内存)

关键细节

query() 函数签名:

function query({
  prompt,
  options
}: {
  prompt: string | AsyncIterable<SDKUserMessage>;
  options?: Options;
}): Query;

startup() 预热:

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

消息类型判断:

for await (const message of query({ prompt: "..." })) {
    if (message.type === "system" && message.subtype === "init") { ... }
    if (message.type === "assistant") {
        // 注意:内容在 message.message.content,不是 message.content
        for (const block of message.message.content) { ... }
    }
    if (message.type === "result") { ... }
    if (message.type === "stream_event") { ... }  // 需启用 includePartialMessages
}

tool() 函数:

import { tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
 
const myTool = tool(
    "tool_name",
    "Tool description",
    { param: z.string().describe("Parameter description") },
    async (args) => ({ content: [{ type: "text", text: "result" }] }),
    { annotations: { readOnlyHint: true } }  // 可选注解
);

与其他概念的关联

实践要点

  • TypeScript SDK 内置 Claude Code 二进制,无需单独安装 CLI
  • env 字段完全替换继承环境,必须包含 ...process.env 保留 PATH 等变量
  • AssistantMessage 内容在 message.message.content(有额外嵌套层),与 Python 不同
  • TypeScript SDK 支持更多 Hook 事件(SessionStart、SessionEnd、TeammateIdle 等)
  • startup() 适合需要低延迟响应的场景(如 Web 服务器),在请求到来前预热进程