先决条件

  • 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: "分析系统性能",
  options: {
    maxTurns: 5,
    appendSystemPrompt: "你是一名性能工程师",
    allowedTools: ["Bash", "Read", "WebSearch"],
    abortController: new AbortController(),
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

配置选项

参数类型描述默认值
abortControllerAbortController用于取消操作的中止控制器new AbortController()
additionalDirectoriesstring[]要包含在会话中的附加目录undefined
allowedToolsstring[]Claude 被允许使用的工具列表默认启用所有工具
appendSystemPromptstring要附加到默认系统提示的文本undefined
canUseTool(toolName: string, input: any) => Promise<ToolPermissionResult>工具使用的自定义权限函数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
hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>用于自定义的生命周期钩子undefined
includePartialMessagesboolean在消息流中包含部分流式事件false
maxThinkingTokensnumberClaude 思考过程的最大令牌数undefined
maxTurnsnumber对话轮次的最大数量undefined
mcpServersRecord<string, McpServerConfig>MCP 服务器配置undefined
modelstring要使用的 Claude 模型使用 CLI 配置的默认值
pathToClaudeCodeExecutablestringClaude Code 可执行文件的路径@anthropic-ai/claude-code 一起提供的可执行文件
permissionModePermissionMode会话的权限模式"default" (选项:"default", "acceptEdits", "bypassPermissions", "plan")
resumestring要恢复的会话 IDundefined
stderr(data: string) => voidstderr 输出的回调undefined
strictMcpConfigboolean强制严格的 MCP 配置验证undefined

部分消息流式传输

当启用 includePartialMessages 时,SDK 将发出包含来自 Claude API 的原始流式事件的 stream_event 消息。这允许您在内容生成时访问部分内容,对于实现实时 UI 更新或进度指示器很有用。

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

for await (const message of query({
  prompt: "写一篇关于人工智能的长文章",
  options: {
    includePartialMessages: true,
    maxTurns: 1
  }
})) {
  // 处理部分流式事件
  if (message.type === "stream_event") {
    const event = message.event;
    
    // 在流式传输时访问部分文本
    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
      process.stdout.write(event.delta.text);
    }
    
    // 跟踪思考进度
    if (event.type === "content_block_start" && event.content_block.type === "thinking") {
      console.log("\n[Claude 正在思考...]");
    }
  }
  
  // 仍然获得最终结果
  if (message.type === "result" && message.subtype === "success") {
    console.log("\n最终结果:", message.result);
  }
}

每个 stream_event 消息包括:

  • event:来自 API 的原始流式事件
  • session_id:当前会话标识符
  • parent_tool_use_id:正在执行的工具的 ID(如果适用)
  • uuid:此事件的唯一标识符

部分消息流式传输主要对需要对流式响应进行精细控制的高级用例有用。对于大多数应用程序,默认行为(等待完整消息)就足够了。

多轮对话

对于多轮对话,您有两个选择。

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

使用会话管理恢复

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

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

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

自定义系统提示

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

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

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

// 附加到默认系统提示
for await (const message of query({
  prompt: "重构这个函数",
  options: {
    appendSystemPrompt: "始终包含全面的错误处理和单元测试。",
    maxTurns: 2
  }
})) {
  if (message.type === "result" && message.subtype === "success") 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"],
    appendSystemPrompt: "你是一名 SRE。使用监控数据诊断问题。",
    maxTurns: 4
  }
})) {
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

使用进程内 MCP 服务器的自定义工具

SDK MCP 服务器允许您创建直接在应用程序进程中运行的自定义工具,提供类型安全的工具执行,而无需单独进程或网络通信的开销。

创建自定义工具

使用 createSdkMcpServertool 辅助函数定义类型安全的自定义工具:

import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-code";
import { z } from "zod";

// 使用自定义工具创建 SDK MCP 服务器
const customServer = createSdkMcpServer({
  name: "my-custom-tools",
  version: "1.0.0",
  tools: [
    tool(
      "calculate_compound_interest",
      "计算投资的复利",
      {
        principal: z.number().describe("初始投资金额"),
        rate: z.number().describe("年利率(作为小数,例如 0.05 表示 5%)"),
        time: z.number().describe("投资期限(年)"),
        n: z.number().default(12).describe("每年复利频率")
      },
      async (args) => {
        const amount = args.principal * Math.pow(1 + args.rate / args.n, args.n * args.time);
        const interest = amount - args.principal;
        
        return {
          content: [{
            type: "text",
            text: `最终金额:$${amount.toFixed(2)}\n赚取利息:$${interest.toFixed(2)}`
          }]
        };
      }
    ),
    tool(
      "fetch_user_data",
      "从您的应用程序数据库获取用户数据",
      {
        userId: z.string().describe("要获取的用户 ID"),
        fields: z.array(z.string()).optional().describe("要返回的特定字段")
      },
      async (args) => {
        // 直接访问您的应用程序数据层
        const userData = await myDatabase.getUser(args.userId, args.fields);
        
        return {
          content: [{
            type: "text",
            text: JSON.stringify(userData, null, 2)
          }]
        };
      }
    )
  ]
});

// 在查询中使用自定义工具
for await (const message of query({
  prompt: "计算 10,000 美元在 5% 利率下 10 年的复利",
  options: {
    mcpServers: {
      "my-custom-tools": customServer
    },
    maxTurns: 3
  }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}

使用 Zod 的类型安全

tool 辅助函数从您的 Zod 模式提供完整的 TypeScript 类型推断:

tool(
  "process_data",
  "使用类型安全处理结构化数据",
  {
    // Zod 模式定义运行时验证和 TypeScript 类型
    data: z.object({
      name: z.string(),
      age: z.number().min(0).max(150),
      email: z.string().email(),
      preferences: z.array(z.string()).optional()
    }),
    format: z.enum(["json", "csv", "xml"]).default("json")
  },
  async (args) => {
    // args 基于模式完全类型化
    // TypeScript 知道:args.data.name 是字符串,args.data.age 是数字,等等。
    console.log(`${args.data.name} 的数据处理为 ${args.format}`);
    
    // 您的处理逻辑在这里
    return {
      content: [{
        type: "text",
        text: `已处理 ${args.data.name} 的数据`
      }]
    };
  }
)

钩子

钩子允许您通过在代理生命周期的各个点运行自定义回调来自定义和扩展 Claude Code 的行为。与执行 bash 命令的 CLI 钩子不同,SDK 钩子是在进程内运行的 JavaScript/TypeScript 函数。

定义钩子

钩子按事件类型组织,具有可选的匹配器来过滤它们何时运行:

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

for await (const message of query({
  prompt: "分析代码库",
  options: {
    hooks: {
      PreToolUse: [
        {
          matcher: "Write",
          hooks: [
            async (input, toolUseId, { signal }) => {
              console.log(`即将写入文件:${input.tool_input.file_path}`);
              
              // 验证操作
              if (input.tool_input.file_path.includes('.env')) {
                return {
                  decision: 'block',
                  stopReason: '无法写入环境文件'
                };
              }
              
              // 允许操作
              return { continue: true };
            }
          ]
        }
      ],
      PostToolUse: [
        {
          matcher: "Write|Edit",
          hooks: [
            async (input, toolUseId, { signal }) => {
              console.log(`文件已修改:${input.tool_response.filePath}`);
              // 运行您的自定义格式化或验证
              return { continue: true };
            }
          ]
        }
      ]
    }
  }
})) {
  if (message.type === "result") console.log(message.result);
}

可用的钩子事件

  • PreToolUse:在工具执行之前运行。可以阻止工具或提供反馈。
  • PostToolUse:在成功的工具执行之后运行。
  • UserPromptSubmit:当用户提交提示时运行。
  • SessionStart:当会话开始时运行。
  • SessionEnd:当会话结束时运行。
  • Stop:当 Claude 即将停止响应时运行。
  • SubagentStop:当子代理即将停止时运行。
  • PreCompact:在对话压缩之前运行。
  • Notification:当发送通知时运行。

钩子输入类型

每个钩子根据事件接收类型化输入:

// PreToolUse 输入
type PreToolUseHookInput = {
  hook_event_name: 'PreToolUse';
  session_id: string;
  transcript_path: string;
  cwd: string;
  permission_mode?: string;
  tool_name: string;
  tool_input: unknown;
}

// PostToolUse 输入
type PostToolUseHookInput = {
  hook_event_name: 'PostToolUse';
  session_id: string;
  transcript_path: string;
  cwd: string;
  permission_mode?: string;
  tool_name: string;
  tool_input: unknown;
  tool_response: unknown;
}

钩子输出

钩子返回控制执行流程的输出:

interface HookJSONOutput {
  // 继续执行(默认:true)
  continue?: boolean;
  
  // 抑制向用户输出
  suppressOutput?: boolean;
  
  // 停止原因(显示给模型)
  stopReason?: string;
  
  // PreToolUse 钩子的决定
  decision?: 'approve' | 'block';
  
  // 要显示的系统消息
  systemMessage?: string;
  
  // 钩子特定输出
  hookSpecificOutput?: {
    // 对于 PreToolUse
    permissionDecision?: 'allow' | 'deny' | 'ask';
    permissionDecisionReason?: string;
    
    // 对于 UserPromptSubmit 或 PostToolUse
    additionalContext?: string;
  };
}

实际示例

日志记录和监控

const hooks = {
  PreToolUse: [
    {
      hooks: [
        async (input) => {
          // 记录所有工具使用
          await logToMonitoring({
            event: 'tool_use',
            tool: input.tool_name,
            input: input.tool_input,
            session: input.session_id
          });
          
          return { continue: true };
        }
      ]
    }
  ]
};

文件操作验证

const hooks = {
  PreToolUse: [
    {
      matcher: "Write|Edit",
      hooks: [
        async (input) => {
          const filePath = input.tool_input.file_path;
          
          // 阻止敏感文件
          const sensitivePatterns = ['.env', '.git/', 'secrets/', '*.key'];
          
          for (const pattern of sensitivePatterns) {
            if (filePath.includes(pattern)) {
              return {
                decision: 'block',
                stopReason: `无法修改匹配 ${pattern} 的敏感文件`
              };
            }
          }
          
          return { continue: true };
        }
      ]
    }
  ]
};

自动格式化代码

import { exec } from 'child_process';
import { prom isify } from 'util';

const execAsync = promisify(exec);

const hooks = {
  PostToolUse: [
    {
      matcher: "Write|Edit|MultiEdit",
      hooks: [
        async (input) => {
          const filePath = input.tool_response.filePath;
          
          // 根据文件类型自动格式化
          if (filePath.endsWith('.ts') || filePath.endsWith('.tsx')) {
            await execAsync(`prettier --write "${filePath}"`);
          } else if (filePath.endsWith('.py')) {
            await execAsync(`black "${filePath}"`);
          }
          
          return { continue: true };
        }
      ]
    }
  ]
};

提示增强

const hooks = {
  UserPromptSubmit: [
    {
      hooks: [
        async (input) => {
          // 向提示添加上下文
          const projectContext = await loadProjectContext();
          
          return {
            continue: true,
            hookSpecificOutput: {
              hookEventName: 'UserPromptSubmit',
              additionalContext: `项目上下文:${projectContext}`
            }
          };
        }
      ]
    }
  ]
};

自定义压缩指令

const hooks = {
  PreCompact: [
    {
      hooks: [
        async (input) => {
          const trigger = input.trigger; // 'manual' 或 'auto'
          
          return {
            continue: true,
            systemMessage: '专注于保留实现细节和错误解决方案'
          };
        }
      ]
    }
  ]
};

钩子执行行为

  • 并行化:所有匹配的钩子并行运行
  • 超时:钩子遵守选项中的中止信号
  • 错误处理:钩子错误被记录但不会停止执行
  • 匹配器:支持正则表达式模式(例如,"Write|Edit"

将钩子与 canUseTool 结合

虽然 canUseTool 提供权限控制,但钩子提供更广泛的生命周期集成:

for await (const message of query({
  prompt: "构建功能",
  options: {
    // 细粒度权限控制
    canUseTool: async (toolName, input) => {
      // 根据运行时条件修改输入或拒绝
      return { behavior: "allow", updatedInput: input };
    },
    
    // 用于监控和自动化的生命周期钩子
    hooks: {
      PreToolUse: [
        {
          hooks: [
            async (input) => {
              // 记录、验证或准备
              return { continue: true };
            }
          ]
        }
      ]
    }
  }
})) {
  // 处理消息
}

使用 canUseTool 进行权限控制

canUseTool 回调提供对工具执行的细粒度控制。它在每次工具使用之前被调用,可以允许、拒绝或修改工具输入:

type ToolPermissionResult = 
  | { behavior: "allow"; updatedInput?: any }
  | { behavior: "deny"; message?: string };

for await (const message of query({
  prompt: "分析用户行为并计算指标",
  options: {
    mcpServers: {
      "analytics": analyticsServer
    },
    canUseTool: async (toolName: string, input: any) => {
      // 控制可以使用哪些工具
      if (toolName.startsWith("mcp__analytics__")) {
        // 检查分析工具的权限
        const hasPermission = await checkUserPermissions(toolName);
        
        return hasPermission
          ? { behavior: "allow", updatedInput: input }
          : { behavior: "deny", message: "权限不足" };
      }
      
      // 修改某些工具的输入
      if (toolName === "Bash") {
        // 添加安全检查或修改命令
        const safeInput = sanitizeBashCommand(input);
        return { behavior: "allow", updatedInput: safeInput };
      }
      
      // 默认允许其他工具
      return { behavior: "allow", updatedInput: input };
    }
  }
})) {
  if (message.type === "result") console.log(message.result);
}

canUseTool 的用例

  • 权限管理:在允许工具执行之前检查用户权限
  • 输入验证:在执行之前验证或清理工具输入
  • 速率限制:为昂贵的操作实施速率限制
  • 审计日志:记录工具使用以进行合规或调试
  • 动态权限:根据运行时条件启用/禁用工具
// 示例:网络爬取速率限制器
const rateLimits = new Map<string, { count: number; resetTime: number }>();

const canUseTool = async (toolName: string, input: any) => {
  // 对网络爬取进行速率限制以防止 IP 禁令和 API 配额问题
  if (toolName === "WebFetch" || toolName === "WebSearch") {
    const now = Date.now();
    const limit = rateLimits.get(toolName) || { count: 0, resetTime: now + 60000 };
    
    // 每分钟重置计数器
    if (now > limit.resetTime) {
      limit.count = 0;
      limit.resetTime = now + 60000;
    }
    
    // 每分钟最多允许 10 个请求
    if (limit.count >= 10) {
      return { 
        behavior: "deny", 
        message: `速率限制超出:每分钟最多 10 个 ${toolName} 请求。在 ${Math.ceil((limit.resetTime - now) / 1000)}s 后重置` 
      };
    }
    
    limit.count++;
    rateLimits.set(toolName, limit);
    
    // 记录爬取活动以进行监控
    console.log(`${toolName} 请求 ${limit.count}/10 到:${input.url || input.query}`);
  }
  
  // 防止 bash 脚本中的意外无限循环
  if (toolName === "Bash" && input.command?.includes("while true")) {
    return { 
      behavior: "deny", 
      message: "不允许无限循环" 
    };
  }
  
  return { behavior: "allow", updatedInput: input };
};

输出格式

文本输出(默认)

// 默认文本输出
for await (const message of query({
  prompt: "解释文件 src/components/Header.tsx"
})) {
  if (message.type === "result" && message.subtype === "success") {
    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" && message.subtype === "success");
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" && message.subtype === "success") console.log(message.result);
}

// 来自变量
const userInput = "解释这段代码";
for await (const message of query({ prompt: userInput })) {
  if (message.type === "result" && message.subtype === "success") 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: {
      appendSystemPrompt: "你是一名 SRE 专家。诊断问题,评估影响,并提供即时行动项目。",
      maxTurns: 6,
      allowedTools: ["Bash", "Read", "WebSearch", "mcp__datadog"],
      mcpConfig: "monitoring-tools.json"
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result" && message.subtype === "success");
}

// 用法
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: {
      appendSystemPrompt: "你是一名安全工程师。审查此 PR 的漏洞、不安全模式和合规问题。",
      maxTurns: 3,
      allowedTools: ["Read", "Grep", "WebSearch"]
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result" && message.subtype === "success");
}

// 用法
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" && message.subtype === "success") {
        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 中可用。

相关资源