先决条件

  • Node.js 18+

安装

从 NPM 安装 @anthropic-ai/claude-code

npm install -g @anthropic-ai/claude-code

要查看 TypeScript SDK 源代码,请访问 NPM 上的 @anthropic-ai/claude-code 页面

基本用法

通过 TypeScript SDK 的主要接口是 query 函数,它返回一个异步迭代器,在消息到达时流式传输消息:

import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "分析系统性能",
  abortController: new AbortController(),
  options: {
    maxTurns: 5,
    systemPrompt: "你是一名性能工程师",
    allowedTools: ["Bash", "Read", "WebSearch"]
  }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}

配置选项

参数类型描述默认值
abortControllerAbortController用于取消操作的中止控制器new AbortController()
additionalDirectoriesstring[]要包含在会话中的附加目录undefined
allowedToolsstring[]Claude 允许使用的工具列表默认启用所有工具
appendSystemPromptstring要附加到默认系统提示的文本undefined
canUseToolCanUseTool工具使用的自定义权限函数undefined
continueboolean继续最近的会话false
customSystemPromptstring完全替换默认系统提示undefined
cwdstring当前工作目录process.cwd()
disallowedToolsstring[]Claude 不允许使用的工具列表undefined
envDict<string>要设置的环境变量undefined
executable'bun' | 'deno' | 'node'要使用的 JavaScript 运行时使用 Node.js 运行时为 node,使用 Bun 运行时为 bun
executableArgsstring[]传递给可执行文件的参数[]
fallbackModelstring主模型失败时使用的模型undefined
maxThinkingTokensnumberClaude 思考过程的最大令牌数undefined
maxTurnsnumber对话轮次的最大数量undefined
mcpServersRecord<string, McpServerConfig>MCP 服务器配置undefined
modelstring要使用的 Claude 模型使用 CLI 配置的默认值
pathToClaudeCodeExecutablestringClaude Code 可执行文件的路径@anthropic-ai/claude-code 一起提供的可执行文件
permissionModePermissionMode会话的权限模式"default"(选项:"default""acceptEdits""bypassPermissions""plan"
permissionPromptToolNamestring权限提示的 MCP 工具名称undefined
resumestring要恢复的会话 IDundefined
stderr(data: string) => voidstderr 输出的回调undefined
strictMcpConfigboolean强制严格的 MCP 配置验证undefined

多轮对话

对于多轮对话,你有两个选项。

你可以生成响应并恢复它们,或者你可以使用流式输入模式,该模式接受消息数组的异步/生成器。目前,流式输入模式是通过消息附加图像的唯一方式。

使用会话管理恢复

import { query } from "@anthropic-ai/claude-code";

// 继续最近的对话
for await (const message of query({
  prompt: "现在重构这个以获得更好的性能",
  options: { continue: true }
})) {
  if (message.type === "result") console.log(message.result);
}

// 恢复特定会话
for await (const message of query({
  prompt: "更新测试",
  options: {
    resume: "550e8400-e29b-41d4-a716-446655440000",
    maxTurns: 3
  }
})) {
  if (message.type === "result") console.log(message.result);
}

流式输入模式

流式输入模式允许你将消息作为异步可迭代对象提供,而不是单个字符串。这使得多轮对话、图像附件和动态消息生成成为可能:

import { query } from "@anthropic-ai/claude-code";

// 创建用于流式消息的异步生成器
async function* generateMessages() {
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "开始分析这个代码库"
    }
  };
  
  // 等待某些条件或用户输入
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "现在专注于身份验证模块"
    }
  };
}

// 使用流式输入
for await (const message of query({
  prompt: generateMessages(),
  options: {
    maxTurns: 5,
    allowedTools: ["Read", "Grep", "Bash"]
  }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}

带图像的流式输入

流式输入模式是通过消息附加图像的唯一方式:

import { query } from "@anthropic-ai/claude-code";
import { readFileSync } from "fs";

async function* messagesWithImage() {
  // 发送带有文本的图像
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: [
        {
          type: "text",
          text: "分析这个截图并建议改进"
        },
        {
          type: "image",
          source: {
            type: "base64",
            media_type: "image/png",
            data: readFileSync("screenshot.png", "base64")
          }
        }
      ]
    }
  };
}

for await (const message of query({
  prompt: messagesWithImage()
})) {
  if (message.type === "result") console.log(message.result);
}

自定义系统提示

系统提示定义你的代理的角色、专业知识和行为:

import { query } from "@anthropic-ai/claude-code";

// SRE 事件响应代理
for await (const message of query({
  prompt: "API 宕机了,调查一下",
  options: {
    systemPrompt: "你是一名 SRE 专家。系统性地诊断问题并提供可行的解决方案。",
    maxTurns: 3
  }
})) {
  if (message.type === "result") console.log(message.result);
}

// 附加到默认系统提示
for await (const message of query({
  prompt: "重构这个函数",
  options: {
    appendSystemPrompt: "始终包含全面的错误处理和单元测试。",
    maxTurns: 2
  }
})) {
  if (message.type === "result") console.log(message.result);
}

通过 MCP 使用自定义工具

模型上下文协议(MCP)让你为代理提供自定义工具和功能:

import { query } from "@anthropic-ai/claude-code";

// 带有监控工具的 SRE 代理
for await (const message of query({
  prompt: "调查支付服务中断",
  options: {
    mcpConfig: "sre-tools.json",
    allowedTools: ["mcp__datadog", "mcp__pagerduty", "mcp__kubernetes"],
    systemPrompt: "你是一名 SRE。使用监控数据来诊断问题。",
    maxTurns: 4
  }
})) {
  if (message.type === "result") console.log(message.result);
}

使用 MCP 的自定义工具

你可以使用 MCP 实现自定义工具,例如,这里是如何创建自定义权限处理工具。

const server = new McpServer({
  name: "Test permission prompt MCP Server",
  version: "0.0.1",
});

server.tool(
  "approval_prompt",
  '模拟权限检查 - 如果输入包含"allow"则批准,否则拒绝',
  {
    tool_name: z.string().describe("请求权限的工具名称"),
    input: z.object({}).passthrough().describe("工具的输入"),
    tool_use_id: z.string().optional().describe("唯一的工具使用请求 ID"),
  },
  async ({ tool_name, input }) => {
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(
            JSON.stringify(input).includes("allow")
              ? {
                  behavior: "allow",
                  updatedInput: input,
                }
              : {
                  behavior: "deny",
                  message: "测试 approval_prompt 工具拒绝权限",
                }
          ),
        },
      ],
    };
  }
);

// 在 SDK 中使用
import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "分析代码库",
  options: {
    permissionPromptTool: "mcp__test-server__approval_prompt",
    mcpConfig: "my-config.json",
    allowedTools: ["Read", "Grep"]
  }
})) {
  if (message.type === "result") console.log(message.result);
}

输出格式

文本输出(默认)

// 默认文本输出
for await (const message of query({
  prompt: "解释文件 src/components/Header.tsx"
})) {
  if (message.type === "result") {
    console.log(message.result);
    // 输出:这是一个显示...的 React 组件
  }
}

JSON 输出

// 收集所有消息以进行类似 JSON 的访问
const messages = [];
for await (const message of query({
  prompt: "数据层是如何工作的?"
})) {
  messages.push(message);
}

// 访问带有元数据的结果消息
const result = messages.find(m => m.type === "result");
console.log({
  result: result.result,
  cost: result.total_cost_usd,
  duration: result.duration_ms
});

输入格式

// 直接提示
for await (const message of query({
  prompt: "解释这段代码"
})) {
  if (message.type === "result") console.log(message.result);
}

// 从变量
const userInput = "解释这段代码";
for await (const message of query({ prompt: userInput })) {
  if (message.type === "result") console.log(message.result);
}

代理集成示例

SRE 事件响应代理

import { query } from "@anthropic-ai/claude-code";

// 自动化事件响应代理
async function investigateIncident(
  incidentDescription: string,
  severity = "medium"
) {
  const messages = [];

  for await (const message of query({
    prompt: `事件:${incidentDescription}(严重性:${severity}`,
    options: {
      systemPrompt: "你是一名 SRE 专家。诊断问题,评估影响,并提供即时行动项目。",
      maxTurns: 6,
      allowedTools: ["Bash", "Read", "WebSearch", "mcp__datadog"],
      mcpConfig: "monitoring-tools.json"
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result");
}

// 使用
const result = await investigateIncident("支付 API 返回 500 错误", "high");
console.log(result.result);

自动化安全审查

import { query } from "@anthropic-ai/claude-code";
import { execSync } from "child_process";

async function auditPR(prNumber: number) {
  // 获取 PR 差异
  const prDiff = execSync(`gh pr diff ${prNumber}`, { encoding: 'utf8' });

  const messages = [];
  for await (const message of query({
    prompt: prDiff,
    options: {
      systemPrompt: "你是一名安全工程师。审查这个 PR 的漏洞、不安全模式和合规问题。",
      maxTurns: 3,
      allowedTools: ["Read", "Grep", "WebSearch"]
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result");
}

// 使用
const report = await auditPR(123);
console.log(JSON.stringify(report, null, 2));

多轮法律助手

import { query } from "@anthropic-ai/claude-code";

async function legalReview() {
  // 开始法律审查会话
  let sessionId: string;

  for await (const message of query({
    prompt: "开始法律审查会话",
    options: { maxTurns: 1 }
  })) {
    if (message.type === "system" && message.subtype === "init") {
      sessionId = message.session_id;
    }
  }

  // 使用同一会话进行多步骤审查
  const steps = [
    "审查 contract.pdf 的责任条款",
    "检查 GDPR 要求的合规性",
    "生成风险的执行摘要"
  ];

  for (const step of steps) {
    for await (const message of query({
      prompt: step,
      options: { resume: sessionId, maxTurns: 2 }
    })) {
      if (message.type === "result") {
        console.log(`步骤:${step}`);
        console.log(message.result);
      }
    }
  }
}

消息模式

从 JSON API 返回的消息根据以下模式严格类型化:

type SDKMessage =
  // 助手消息
  | {
      type: "assistant";
      uuid: string;
      session_id: string;
      message: Message; // 来自 Anthropic SDK
      parent_tool_use_id: string | null;
    }

  // 用户消息(输入)
  | {
      type: "user";
      uuid?: string;
      session_id: string;
      message: MessageParam; // 来自 Anthropic SDK
      parent_tool_use_id: string | null;
    }

  // 用户消息(输出/重放,需要 UUID)
  | {
      type: "user";
      uuid: string;
      session_id: string;
      message: MessageParam; // 来自 Anthropic SDK
      parent_tool_use_id: string | null;
    }

  // 成功时作为最后一条消息发出
  | {
      type: "result";
      subtype: "success";
      uuid: UUID;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      result: string;
      total_cost_usd: number;
      usage: Usage;
      permission_denials: SDKPermissionDenial[];
    }

  // 错误或达到最大轮次时作为最后一条消息发出
  | {
      type: "result";
      subtype: "error_max_turns" | "error_during_execution";
      uuid: UUID;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      total_cost_usd: number;
      usage: Usage;
      permission_denials: SDKPermissionDenial[];
    }

  // 在对话开始时作为第一条消息发出
  | {
      type: "system";
      subtype: "init";
      uuid: UUID;
      session_id: string;
      apiKeySource: "user" | "project" | "org" | "temporary";
      cwd: string;
      tools: string[];
      mcp_servers: {
        name: string;
        status: string;
      }[];
      model: string;
      permissionMode: "default" | "acceptEdits" | "bypassPermissions" | "plan";
      slash_commands: string[];
      output_style: string;
    };

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

其他支持类型:

MessageMessageParamUsage 类型在 Anthropic TypeScript SDK 中可用。

相关资源