先決條件

  • 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 中取得。

相關資源