mcpField
C
claude-agent-sdk

claude-agent-sdk

github.com/jackspaceAgent 工作流1646 次安装12 周前更新
代码仓库

关于 claude-agent-sdk

面向 TypeScript 开发者的 Claude Agent SDK 使用指南,介绍以代码调用 Claude Code CLI、配置工具与会话,以及编排子 Agent。还涵盖创建 MCP 服务和连接外部 MCP 服务。

主要功能

  1. 01调用 query() 执行 Agent 请求
  2. 02配置内置工具与访问权限
  3. 03创建和连接 MCP 服务
  4. 04编排专用子 Agent
  5. 05恢复或分叉会话

适用场景

  1. 01以程序方式执行代码审查
  2. 02为 Agent 限制可用工具
  3. 03为任务创建专用子 Agent
  4. 04跨多轮开发恢复会话

MCP 相关

说明如何通过 createSdkMcpServer 创建进程内 MCP 服务,并连接 stdio、HTTP 或 SSE 外部 MCP 服务。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jackspace/claudeskillz --skill claude-agent-sdk

安装后在 Claude Code 中输入/claude-agent-sdk确认已加载。

附带文件README.mdSKILL.json

详细介绍

Claude Agent SDK

状态:已可用于生产环境 最后更新:2025-10-25 依赖项:@anthropic-ai/claude-agent-sdk、zod 最新版本:@anthropic-ai/[email protected]+、[email protected]+


快速入门(5 分钟)

1. 安装 SDK
npm install @anthropic-ai/claude-agent-sdk zod

为什么需要这些软件包:

  • @anthropic-ai/claude-agent-sdk - 主要的 Agent SDK
  • zod - 用于工具的类型安全架构验证
2. 设置 API 密钥
export ANTHROPIC_API_KEY="sk-ant-..."

重要:

  • 所有 Agent 操作都需要 API 密钥
  • 切勿将 API 密钥提交到版本控制系统
  • 使用环境变量
3. 基本查询
import { query } from "@anthropic-ai/claude-agent-sdk";

const response = query({
  prompt: "Analyze the codebase and suggest improvements",
  options: {
    model: "claude-sonnet-4-5",
    workingDirectory: process.cwd(),
    allowedTools: ["Read", "Grep", "Glob"]
  }
});

for await (const message of response) {
  if (message.type === 'assistant') {
    console.log(message.content);
  }
}

Claude Agent SDK 完整参考

目录

  1. 核心查询 API
  2. 工具集成
  3. MCP 服务
  4. 子 Agent 编排
  5. 会话管理
  6. 权限控制
  7. 文件系统设置
  8. 消息类型与流式传输
  9. 错误处理
  10. 已知问题

核心查询 API

query() 函数

以编程方式与 Claude Code CLI 交互的主要接口。

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

const response = query({
  prompt: string | AsyncIterable<SDKUserMessage>,
  options?: Options
});

// Response is AsyncGenerator<SDKMessage, void>
for await (const message of response) {
  // Process streaming messages
}
基本选项
const response = query({
  prompt: "Review this code for bugs",
  options: {
    model: "claude-sonnet-4-5",        // or "haiku", "opus"
    workingDirectory: "/path/to/project",
    systemPrompt: "You are a security-focused code reviewer.",
    allowedTools: ["Read", "Grep", "Glob"],
    disallowedTools: ["Write", "Edit", "Bash"],
    permissionMode: "default"           // or "acceptEdits", "bypassPermissions"
  }
});
模型选择
模型ID最适用场景速度能力
Haiku"haiku"快速任务、监控最快基础
Sonnet"sonnet" 或 "claude-sonnet-4-5"均衡需求中等高
Opus"opus"复杂推理最慢最高
Inherit"inherit"使用父级模型--

默认值:未指定时为 "sonnet"

系统提示词
const response = query({
  prompt: "Implement user authentication",
  options: {
    systemPrompt: `You are an expert backend developer.

Follow these principles:
- Always use TypeScript with strict types
- Implement comprehensive error handling
- Add detailed logging for debugging
- Write unit tests for all functions
- Follow OWASP security guidelines`
  }
});

重要:

  • 系统提示词会为整个会话设定 Agent 的行为
  • 应清晰且具体
  • 可以为 1-10k 个令牌(会影响上下文窗口)
工作目录
const response = query({
  prompt: "Refactor the user service",
  options: {
    workingDirectory: "/Users/dev/projects/my-app",
    // Agent operates within this directory
    // Relative paths resolved from here
  }
});

最佳实践:

  • 使用绝对路径以确保清晰
  • Agent 会将操作限制在此目录范围内
  • 对多项目环境至关重要

工具集成(内置 + 自定义)

内置工具

SDK 提供对 Claude Code 内置工具的访问:

工具描述使用场景
Read读取文件内容代码分析
Write创建新文件生成代码
Edit修改现有文件重构
Bash执行 Shell 命令运行测试、Git 操作
Grep搜索文件内容查找模式
Glob按模式查找文件文件发现
WebSearch搜索网页调研
WebFetch获取 URL 内容文档
Task委派给子 Agent编排
允许/禁止工具
// Whitelist approach (recommended)
const response = query({
  prompt: "Analyze code but don't modify anything",
  options: {
    allowedTools: ["Read", "Grep", "Glob"]
    // ONLY these tools can be used
  }
});

// Blacklist approach
const response = query({
  prompt: "Review and fix issues",
  options: {
    disallowedTools: ["Bash"]
    // Everything except Bash allowed
  }
});

// Combination (allowedTools takes precedence)
const response = query({
  prompt: "Safe code review",
  options: {
    allowedTools: ["Read", "Grep", "Glob", "Edit"],
    disallowedTools: ["Edit"]  // Edit still blocked (allowedTools overridden)
  }
});

重要:

  • allowedTools = 允许列表(仅限这些工具)
  • disallowedTools = 禁止列表(除这些工具外的所有工具)
  • 如果两者都指定,则以 allowedTools 为准
自定义工具执行监控
const response = query({
  prompt: "Implement feature X",
  options: {
    allowedTools: ["Read", "Write", "Edit", "Bash"]
  }
});

for await (const message of response) {
  if (message.type === 'tool_call') {
    console.log(`Tool requested: ${message.tool_name}`);
    console.log(`Input:`, message.input);
  } else if (message.type === 'tool_result') {
    console.log(`Tool ${message.tool_name} completed`);
  }
}

MCP 服务(模型上下文协议)

概述

MCP 服务通过自定义工具扩展 Agent 的能力。SDK 支持:

  • 进程内服务(createSdkMcpServer)- 在同一进程中运行
  • 外部服务(stdio、HTTP、SSE)- 独立进程
创建进程内 MCP 服务
import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const weatherServer = createSdkMcpServer({
  name: "weather-service",
  version: "1.0.0",
  tools: [
    tool(
      "get_weather",
      "Get current weather for a location",
      {
        location: z.string().describe("City name or coordinates"),
        units: z.enum(["celsius", "fahrenheit"]).default("celsius")
      },
      async (args) => {
        // Tool implementation
        const response = await fetch(
          `https://api.weather.com/v1/current?location=${args.location}&units=${args.units}`
        );
        const data = await response.json();

        return {
          content: [{
            type: "text",
            text: `Temperature: ${data.temp}° ${args.units}
Conditions: ${data.conditions}
Humidity: ${data.humidity}%`
          }]
        };
      }
    )
  ]
});

// Use in query
const response = query({
  prompt: "What's the weather in San Francisco?",
  options: {
    mcpServers: {
      "weather-service": weatherServer
    },
    allowedTools: ["mcp__weather-service__get_weather"]
  }
});
工具定义模式
tool(
  name: string,                    // Tool identifier
  description: string,             // What the tool does
  inputSchema: ZodSchema,          // Input validation
  handler: async (args) => Result // Implementation
)

输入架构选项:

// Simple object schema
{
  email: z.string().email(),
  limit: z.number().min(1).max(100).default(10),
  enabled: z.boolean().optional()
}

// Complex nested schema
{
  user: z.object({
    name: z.string(),
    age: z.number().min(0)
  }),
  filters: z.array(z.string()).optional()
}

// Enum types
{
  status: z.enum(["pending", "active", "completed"]),
  priority: z.union([z.literal("low"), z.literal("high")])
}

处理程序返回格式:

// Success
return {
  content: [{
    type: "text",
    text: "Result data here"
  }]
};

// Error
return {
  content: [{
    type: "text",
    text: "Error description"
  }],
  isError: true
};
在一个服务中使用多个工具
const databaseServer = createSdkMcpServer({
  name: "database",
  version: "1.0.0",
  tools: [
    tool(
      "query_users",
      "Query user records from database",
      {
        email: z.string().email().optional(),
        limit: z.number().min(1).max(100).default(10)
      },
      async (args) => {
        const results = await db.query("SELECT * FROM users WHERE...");
        return {
          content: [{ type: "text", text: JSON.stringify(results, null, 2) }]
        };
      }
    ),
    tool(
      "create_user",
      "Create a new user record",
      {
        email: z.string().email(),
        name: z.string(),
        role: z.enum(["admin", "user", "guest"])
      },
      async (args) => {
        const user = await db.insert("users", args);
        return {
          content: [{ type: "text", text: `User created: ${user.id}` }]
        };
      }
    ),
    tool(
      "delete_user",
      "Delete a user by ID",
      { userId: z.string().uuid() },
      async (args) => {
        await db.delete("users", args.userId);
        return {
          content: [{ type: "text", text: "User deleted" }]
        };
      }
    )
  ]
});
外部 MCP 服务(stdio)
const response = query({
  prompt: "List files and analyze Git history",
  options: {
    mcpServers: {
      // Filesystem server
      "filesystem": {
        command: "npx",
        args: ["@modelcontextprotocol/server-filesystem"],
        env: {
          ALLOWED_PATHS: "/Users/developer/projects:/tmp"
        }
      },
      // Git operations server
      "git": {
        command: "npx",
        args: ["@modelcontextprotocol/server-git"],
        env: {
          GIT_REPO_PATH: "/Users/developer/projects/my-repo"
        }
      }
    },
    allowedTools: [
      "mcp__filesystem__list_files",
      "mcp__filesystem__read_file",
      "mcp__git__log",
      "mcp__git__diff"
    ]
  }
});
外部 MCP 服务(HTTP/SSE)
const response = query({
  prompt: "Analyze data from remote service",
  options: {
    mcpServers: {
      "remote-service": {
        url: "https://api.example.com/mcp",
        headers: {
          "Authorization": "Bearer your-token-here",
          "Content-Type": "application/json"
        }
      }
    },
    allowedTools: ["mcp__remote-service__analyze"]
  }
});
MCP 工具命名约定

格式:mcp__<server-name>__<tool-name>

示例:

  • mcp__weather-service__get_weather
  • mcp__database__query_users
  • mcp__filesystem__read_file
  • mcp__git__log

重要:

  • 服务名称和工具名称必须与配置一致
  • 使用双下划线(__)作为分隔符
  • 将其包含在 allowedTools 数组中

子 Agent 编排

什么是子 Agent?

专用 Agent 具备以下特点:

  • 特定领域的专业知识——专注于某个领域
  • 自定义工具——仅使用所需的工具
  • 不同的模型——根据任务匹配能力
  • 专用提示词——量身定制的指令
定义子 Agent
const response = query({
  prompt: "Deploy the application to production",
  options: {
    model: "claude-sonnet-4-5",
    agents: {
      "test-runner": {
        description: "Run test suites and verify coverage",
        prompt: "You run tests. Always verify 100% pass before approving deployment. Report failures clearly.",
        tools: ["Bash", "Read", "Grep"],
        model: "haiku"  // Fast, cost-effective for testing
      },
      "security-checker": {
        description: "Security validation and vulnerability scanning",
        prompt: "You check security. Verify no secrets committed, dependencies updated, OWASP compliance.",
        tools: ["Read", "Grep", "Bash"],
        model: "sonnet"  // Balance for security analysis
      },
      "deployer": {
        description: "Handle deployments and rollbacks",
        prompt: "You deploy. Deploy to staging first, verify health checks, then production. Always have rollback plan.",
        tools: ["Bash", "Read"],
        model: "sonnet"  // Reliable for critical operations
      }
    }
  }
});
AgentDefinition 类型
type AgentDefinition = {
  description: string;        // When to use this agent
  prompt: string;             // System prompt for agent
  tools?: string[];           // Allowed tools (optional)
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';  // Model (optional)
}

字段详情:

  • description:说明何时使用该 Agent 的自然语言描述

    • 主 Agent 根据此描述决定调用哪个子 Agent
    • 应清晰具体
    • 示例:“处理数据库查询”“部署到生产环境”
  • prompt:子 Agent 的系统提示词

    • 定义 Agent 的角色和行为
    • 可包含指令、约束和格式要求
    • 继承主 Agent 的上下文
  • tools:允许使用的工具名称数组

    • 如果省略,则继承主 Agent 的所有工具
    • 用于将 Agent 限定为使用特定工具
    • 示例:只读 Agent 可使用 ["Read", "Grep"]
  • model:覆盖默认模型

    • "haiku"——适用于快速、经济高效的任务
    • "sonnet"——能力均衡
    • "opus"——具备最强推理能力
    • "inherit"——使用主 Agent 的模型
    • 如果省略,则继承主 Agent 的模型
多 Agent 工作流示例
async function runDevOpsAgent(task: string) {
  const response = query({
    prompt: task,
    options: {
      model: "claude-sonnet-4-5",
      workingDirectory: process.cwd(),
      systemPrompt: `You are a DevOps orchestrator.
Coordinate specialized agents to:
- Run tests (test-runner agent)
- Check security (security-checker agent)
- Deploy application (deployer agent)
- Monitor systems (monitoring-agent agent)`,

      agents: {
        "test-runner": {
          description: "Run automated test suites",
          prompt: "You run tests. Execute test commands, parse results, report coverage. Fail if any tests fail.",
          tools: ["Bash", "Read"],
          model: "haiku"
        },
        "security-checker": {
          description: "Security audits and vulnerability scanning",
          prompt: "You check security. Scan for secrets, check dependencies, validate permissions, verify OWASP compliance.",
          tools: ["Read", "Grep", "Bash"],
          model: "sonnet"
        },
        "deployer": {
          description: "Application deployment and rollbacks",
          prompt: "You deploy. Deploy to staging, verify health checks, deploy to production, have rollback ready.",
          tools: ["Bash", "Read"],
          model: "sonnet"
        },
        "monitoring-agent": {
          description: "System monitoring and alerting",
          prompt: "You monitor. Check metrics, detect anomalies, alert on issues, track SLAs.",
          tools: ["Bash", "Read"],
          model: "haiku"
        }
      }
    }
  });

  for await (const message of response) {
    if (message.type === 'assistant') {
      console.log('Orchestrator:', message.content);
    }
  }
}

// Usage
await runDevOpsAgent("Deploy version 2.5.0 to production with full validation");
何时使用子 Agent

✅ 适合使用子 Agent 的情况:

  • 任务需要不同领域的专业知识
  • 某些子任务需要使用不同模型(优化成本)
  • 需要按角色限制工具访问权限
  • 需要明确划分职责
  • 任务包含多个需要专业知识的步骤

❌ 不适合使用子 Agent 的情况:

  • 任务简单直接
  • 所有工作都能由一个 Agent 完成
  • 编排开销大于收益
  • 工具或权限没有差异

会话管理

概述

会话支持:

  • 持久对话——从上次中断处继续
  • 保留上下文——Agent 会记住之前的交互
  • 探索替代路径——通过分叉探索不同方案
开始会话
import { query } from "@anthropic-ai/claude-agent-sdk";

let sessionId: string | undefined;

const response = query({
  prompt: "Build a REST API with user authentication",
  options: {
    model: "claude-sonnet-4-5"
  }
});

for await (const message of response) {
  if (message.type === 'system' && message.subtype === 'init') {
    sessionId = message.session_id;
    console.log(`Session started: ${sessionId}`);
  } else if (message.type === 'assistant') {
    console.log(message.content);
  }
}

// Save sessionId for later use
恢复会话
// Continue the conversation
const resumed = query({
  prompt: "Now add rate limiting to the API endpoints",
  options: {
    resume: sessionId,  // Resume previous session
    model: "claude-sonnet-4-5"
  }
});

for await (const message of resumed) {
  // Agent has full context from previous session
  if (message.type === 'assistant') {
    console.log(message.content);
  }
}
分叉会话
// Explore alternative approach without modifying original
const forked = query({
  prompt: "Actually, let's redesign this as a GraphQL API instead",
  options: {
    resume: sessionId,
    forkSession: true,  // Creates new branch
    model: "claude-sonnet-4-5"
  }
});

for await (const message of forked) {
  // New conversation path
  // Original session unchanged
}
会话管理模式

模式 1:顺序开发

// Step 1: Initial implementation
let session = await startSession("Create user authentication system");

// Step 2: Add feature
session = await resumeSession(session, "Add OAuth support");

// Step 3: Add tests
session = await resumeSession(session, "Write integration tests");

// Step 4: Deploy
session = await resumeSession(session, "Deploy to production");

模式 2:探索与决策

// Start main conversation
let mainSession = await startSession("Design payment processing system");

// Explore option A
let optionA = await forkSession(mainSession, "Use Stripe integration");

// Explore option B
let optionB = await forkSession(mainSession, "Use PayPal integration");

// Choose winner and continue
let chosenSession = optionA;  // Decision made
await resumeSession(chosenSession, "Implement the chosen approach");

模式 3:多用户协作

// Developer A starts work
let sessionA = await startSession("Implement user profile page");

// Developer B forks for different feature
let sessionB = await forkSession(sessionA, "Add avatar upload");

// Both can work independently
// Sessions don't interfere

权限控制

权限模式
type PermissionMode =
  | "default"             // Standard permission checks
  | "acceptEdits"         // Auto-approve file edits
  | "bypassPermissions";  // Skip ALL checks (use with caution)
默认模式
const response = query({
  prompt: "Analyze and modify code",
  options: {
    permissionMode: "default"
    // User prompted for:
    // - File writes/edits
    // - Potentially dangerous bash commands
    // - Sensitive operations
  }
});
接受编辑模式
const response = query({
  prompt: "Refactor the user service to use async/await",
  options: {
    permissionMode: "acceptEdits"
    // Automatically approves:
    // - File edits
    // - File writes
    // Still prompts for:
    // - Dangerous bash commands
    // - Sensitive operations
  }
});
绕过权限模式
const response = query({
  prompt: "Run comprehensive test suite and fix all failures",
  options: {
    permissionMode: "bypassPermissions"
    // ⚠️ CAUTION: Skips ALL permission checks
    // Use only in:
    // - Trusted environments
    // - CI/CD pipelines
    // - Sandboxed containers
  }
});
自定义权限逻辑
const response = query({
  prompt: "Deploy application to production",
  options: {
    permissionMode: "default",
    canUseTool: async (toolName, input) => {
      // Allow read-only operations
      if (['Read', 'Grep', 'Glob'].includes(toolName)) {
        return { behavior: "allow" };
      }

      // Deny destructive bash commands
      if (toolName === 'Bash') {
        const dangerous = ['rm -rf', 'dd if=', 'mkfs', '> /dev/'];
        if (dangerous.some(pattern => input.command.includes(pattern))) {
          return {
            behavior: "deny",
            message: "Destructive command blocked for safety"
          };
        }
      }

      // Require confirmation for deployments
      if (input.command?.includes('deploy') || input.command?.includes('kubectl apply')) {
        return {
          behavior: "ask",
          message: "Confirm deployment to production?"
        };
      }

      // Allow by default
      return { behavior: "allow" };
    }
  }
});
canUseTool 回调
type CanUseToolCallback = (
  toolName: string,
  input: any
) => Promise<PermissionDecision>;

type PermissionDecision =
  | { behavior: "allow" }
  | { behavior: "deny"; message?: string }
  | { behavior: "ask"; message?: string };

示例:

// Block all file writes
canUseTool: async (toolName, input) => {
  if (toolName === 'Write' || toolName === 'Edit') {
    return { behavior: "deny", message: "No file modifications allowed" };
  }
  return { behavior: "allow" };
}

// Require confirmation for specific files
canUseTool: async (toolName, input) => {
  const sensitivePaths = ['/etc/', '/root/', '.env', 'credentials.json'];
  if ((toolName === 'Write' || toolName === 'Edit') &&
      sensitivePaths.some(path => input.file_path?.includes(path))) {
    return {
      behavior: "ask",
      message: `Modify sensitive file ${input.file_path}?`
    };
  }
  return { behavior: "allow" };
}

// Log all tool usage
canUseTool: async (toolName, input) => {
  console.log(`Tool requested: ${toolName}`, input);
  await logToDatabase(toolName, input);
  return { behavior: "allow" };
}

文件系统设置

设置来源
type SettingSource = 'user' | 'project' | 'local';
  • user:~/.claude/settings.json(全局用户设置)
  • project:.claude/settings.json(团队共享,并纳入版本控制)
  • local:.claude/settings.local.json(本地覆盖设置,由 gitignore 忽略)
默认行为
// By default, NO filesystem settings loaded (isolated)
const response = query({
  prompt: "Review code",
  options: {
    // settingSources: [] is default (no files loaded)
  }
});
加载所有设置
const response = query({
  prompt: "Build feature with project conventions",
  options: {
    settingSources: ["user", "project", "local"]
    // Loads all settings files
    // Priority (highest first):
    // 1. local (overrides everything)
    // 2. project (team settings)
    // 3. user (global defaults)
  }
});
仅加载项目设置
const response = query({
  prompt: "Run CI checks",
  options: {
    settingSources: ["project"]
    // Only .claude/settings.json
    // Useful for CI/CD (consistent behavior)
    // Ignores user and local settings
  }
});
加载 CLAUDE.md
const response = query({
  prompt: "Implement feature according to project guidelines",
  options: {
    settingSources: ["project"],  // Reads CLAUDE.md from project
    systemPrompt: {
      type: 'preset',
      preset: 'claude_code'         // Required to use CLAUDE.md
    }
  }
});
设置优先级

加载多个来源时,设置按以下顺序合并(优先级从高到低):

  1. 编程选项(传递给 query())——始终优先
  2. 本地设置(.claude/settings.local.json)
  3. 项目设置(.claude/settings.json)
  4. 用户设置(~/.claude/settings.json)

示例:

// .claude/settings.json
{
  "allowedTools": ["Read", "Write", "Edit"]
}

// .claude/settings.local.json
{
  "allowedTools": ["Read"]  // Overrides project settings
}

// Programmatic
const response = query({
  options: {
    settingSources: ["project", "local"],
    allowedTools: ["Read", "Grep"]  // ← This wins
  }
});

// Actual allowedTools: ["Read", "Grep"]
使用场景

CI/CD 环境:

const response = query({
  prompt: "Run automated tests",
  options: {
    settingSources: ["project"],      // Only team-shared settings
    permissionMode: "bypassPermissions"  // No interactive prompts
  }
});

仅使用 SDK 的应用:

const response = query({
  prompt: "Analyze code snippet",
  options: {
    settingSources: [],               // No filesystem dependencies
    workingDirectory: "/tmp/sandbox",
    allowedTools: ["Read", "Grep"],
    systemPrompt: "You are a code analyzer."
  }
});

混合方案:

const response = query({
  prompt: "Implement authentication",
  options: {
    settingSources: ["project"],      // Load CLAUDE.md and settings
    systemPrompt: "Follow security best practices.",
    agents: {                         // Add programmatic agents
      "security-checker": { /* ... */ }
    }
  }
});

消息类型与流式传输

消息类型
type SDKMessage =
  | SystemMessage
  | AssistantMessage
  | ToolCallMessage
  | ToolResultMessage
  | ErrorMessage;
系统消息
type SystemMessage = {
  type: 'system';
  subtype: 'init' | 'completion';
  uuid: string;
  session_id: string;
  apiKeySource?: 'user' | 'project' | 'org' | 'temporary';
  cwd?: string;
  tools?: string[];
  mcp_servers?: { name: string; status: string }[];
  model?: string;
  permissionMode?: string;
  slash_commands?: string[];
  output_style?: string;
};

用法:

for await (const message of response) {
  if (message.type === 'system') {
    if (message.subtype === 'init') {
      console.log(`Session ID: ${message.session_id}`);
      console.log(`Model: ${message.model}`);
      console.log(`Available tools: ${message.tools.join(', ')}`);
    } else if (message.subtype === 'completion') {
      console.log('Task completed');
    }
  }
}
助手消息
type AssistantMessage = {
  type: 'assistant';
  content: string | ContentBlock[];
  model?: string;
};

type ContentBlock =
  | { type: 'text'; text: string }
  | { type: 'tool_use'; id: string; name: string; input: any };

用法:

for await (const message of response) {
  if (message.type === 'assistant') {
    if (typeof message.content === 'string') {
      console.log('Assistant:', message.content);
    } else {
      message.content.forEach(block => {
        if (block.type === 'text') {
          console.log('Text:', block.text);
        } else if (block.type === 'tool_use') {
          console.log(`Tool request: ${block.name}`, block.input);
        }
      });
    }
  }
}
工具调用消息
type ToolCallMessage = {
  type: 'tool_call';
  tool_name: string;
  input: any;
};

用法:

for await (const message of response) {
  if (message.type === 'tool_call') {
    console.log(`Executing tool: ${message.tool_name}`);
    console.log(`Input:`, JSON.stringify(message.input, null, 2));
  }
}
工具结果消息
type ToolResultMessage = {
  type: 'tool_result';
  tool_name: string;
  result: any;
};

用法:

for await (const message of response) {
  if (message.type === 'tool_result') {
    console.log(`Tool ${message.tool_name} completed`);
    console.log(`Result:`, message.result);
  }
}
错误消息
type ErrorMessage = {
  type: 'error';
  error: {
    type: string;
    message: string;
    tool?: string;
  };
};

用法:

for await (const message of response) {
  if (message.type === 'error') {
    console.error('Error:', message.error.message);
    if (message.error.type === 'permission_denied') {
      console.log('Permission was denied for:', message.error.tool);
    }
  }
}
完整消息处理
async function processAgent(prompt: string) {
  const response = query({ prompt, options: { model: "sonnet" } });

  try {
    for await (const message of response) {
      switch (message.type) {
        case 'system':
          if (message.subtype === 'init') {
            console.log(`Session: ${message.session_id}`);
          }
          break;

        case 'assistant':
          if (typeof message.content === 'string') {
            console.log('Assistant:', message.content);
          }
          break;

        case 'tool_call':
          console.log(`Executing: ${message.tool_name}`);
          break;

        case 'tool_result':
          console.log(`Completed: ${message.tool_name}`);
          break;

        case 'error':
          console.error('Error:', message.error.message);
          break;
      }
    }
  } catch (error) {
    console.error('Fatal error:', error);
  }
}

错误处理

SDK 错误
import { query } from "@anthropic-ai/claude-agent-sdk";

try {
  const response = query({
    prompt: "Analyze code",
    options: { model: "sonnet" }
  });

  for await (const message of response) {
    // Process messages
  }
} catch (error) {
  // Handle SDK errors
  if (error.code === 'AUTHENTICATION_FAILED') {
    console.error('Invalid API key');
  } else if (error.code === 'RATE_LIMIT_EXCEEDED') {
    console.error('Rate limit exceeded, retry after delay');
  } else if (error.code === 'CONTEXT_LENGTH_EXCEEDED') {
    console.error('Context too large, use session compaction');
  } else if (error.code === 'CLI_NOT_FOUND') {
    console.error('Claude Code CLI not installed');
  }
}
常见错误代码
错误代码原因解决方案
CLI_NOT_FOUND未安装 Claude Code安装:npm install -g @anthropic-ai/claude-code
AUTHENTICATION_FAILEDAPI 密钥无效检查 ANTHROPIC_API_KEY 环境变量
RATE_LIMIT_EXCEEDED请求过多实现带退避的重试机制
CONTEXT_LENGTH_EXCEEDED提示词过长使用会话压缩,减少上下文
PERMISSION_DENIED工具被阻止检查 permissionMode、canUseTool
TOOL_EXECUTION_FAILED工具错误检查工具实现
SESSION_NOT_FOUND会话 ID 无效验证会话 ID
MCP_SERVER_FAILED服务错误检查服务配置
错误处理模式
async function safeAgentExecution(prompt: string) {
  try {
    const response = query({
      prompt,
      options: {
        model: "sonnet",
        permissionMode: "default"
      }
    });

    const results: string[] = [];

    for await (const message of response) {
      if (message.type === 'assistant') {
        results.push(message.content);
      } else if (message.type === 'error') {
        console.warn('Agent error:', message.error);
        if (message.error.type === 'permission_denied') {
          // Handle permission errors gracefully
          console.log('Skipping restricted operation');
        }
      }
    }

    return results;
  } catch (error) {
    console.error('Fatal error:', error);

    // Specific error handling
    if (error.code === 'CLI_NOT_FOUND') {
      throw new Error('Please install Claude Code CLI first');
    } else if (error.code === 'AUTHENTICATION_FAILED') {
      throw new Error('Invalid API key. Check ANTHROPIC_API_KEY');
    } else if (error.code === 'RATE_LIMIT_EXCEEDED') {
      // Retry with exponential backoff
      await delay(5000);
      return safeAgentExecution(prompt);  // Retry
    } else {
      throw error;
    }
  }
}

关键规则

始终执行

✅ 使用 SDK 前先安装 Claude Code CLI ✅ 设置 ANTHROPIC_API_KEY 环境变量 ✅ 从 system 消息中获取 session_id,以便恢复会话 ✅ 使用 allowedTools 限制 Agent 的能力 ✅ 使用 canUseTool 实现自定义权限逻辑 ✅ 在流式循环中处理所有消息类型 ✅ 使用 Zod 模式验证工具输入 ✅ 在多项目环境中设置 workingDirectory ✅ 集成前单独测试 MCP 服务 ✅ 在 CI/CD 中使用 settingSources: ["project"] ✅ 使用 tool_call 消息监控工具执行 ✅ 为所有查询实现错误处理

绝不执行

❌ 将 API 密钥提交到版本控制系统 ❌ 在生产环境中使用 bypassPermissions(除非在沙盒中) ❌ 假设工具已执行(检查 tool_result 消息) ❌ 忽略流中的错误消息 ❌ 如果计划恢复会话,不要跳过会话 ID 的获取 ❌ 在不同 MCP 服务之间使用重复的工具名称 ❌ 不使用 canUseTool 就允许不受限制的 Bash 访问 ❌ 在 CI/CD 中从用户加载设置(settingSources: ["user"]) ❌ 不经验证就信任工具结果 ❌ 对文件路径进行硬编码(使用 workingDirectory) ❌ 对不可信提示词使用 acceptEdits 模式 ❌ 跳过对工具输入的 Zod 验证


预防已知问题

此技能可预防已记录的 12 个问题:

问题 #1:找不到 CLI 错误

错误:"Claude Code CLI not installed" 来源:SDK 需要 Claude Code CLI 发生原因:未全局安装 CLI 预防措施:使用 SDK 前先安装:npm install -g @anthropic-ai/claude-code

问题 #2:身份验证失败

错误:"Invalid API key" 来源:缺少或错误的 ANTHROPIC_API_KEY 发生原因:未设置环境变量 预防措施:始终设置 export ANTHROPIC_API_KEY="sk-ant-..."

问题 #3:权限被拒绝错误

错误:工具执行被阻止 来源:permissionMode 限制 发生原因:权限不允许使用该工具 预防措施:使用 allowedTools 或自定义 canUseTool 回调

问题 #4:上下文长度超出限制

错误:"Prompt too long" 来源:输入超出模型上下文窗口 发生原因:代码库庞大、对话过长 预防措施:SDK 会自动压缩上下文,但必要时请减少上下文

问题 #5:工具执行超时

错误:工具无响应 来源:工具执行时间过长 发生原因:工具耗时过久(默认超过 5 分钟) 预防措施:在工具实现中加入超时处理

问题 #6:找不到会话

错误:"Invalid session ID" 来源:会话已过期或无效 发生原因:会话 ID 不正确或过期太久 预防措施:从 system 初始化消息中获取 session_id

问题 #7:MCP 服务连接失败

错误:服务无响应 来源:服务未运行或配置错误 发生原因:命令/URL 不正确,或服务崩溃 预防措施:单独测试 MCP 服务,并验证命令/URL

问题 #8:子 Agent 定义错误

错误:AgentDefinition 无效 来源:缺少必需字段 发生原因:缺少 description 或 prompt 预防措施:始终包含 description 和 prompt 字段

问题 #9:找不到设置文件

错误:"Cannot read settings" 来源:设置文件不存在 原因:settingSources 包含不存在的文件 预防措施:将文件添加到 sources 前,先检查文件是否存在

问题 #10:工具名称冲突

错误:工具名称重复 来源:多个工具使用相同名称 原因:两个 MCP 服务定义了相同的工具名称 预防措施:使用唯一的工具名称,并以服务名称作为前缀

问题 #11:Zod 架构验证错误

错误:工具输入无效 来源:输入与 Zod 架构不匹配 原因:Agent 提供了错误的数据类型 预防措施:使用带有 .describe() 的描述性 Zod 架构

问题 #12:文件系统权限被拒绝

错误:无法访问路径 来源:文件系统访问受限 原因:路径位于 workingDirectory 之外,或没有相应权限 预防措施:设置正确的 workingDirectory,并检查文件权限


依赖项

必需:

可选:

  • @types/[email protected]+ - TypeScript 类型
  • @modelcontextprotocol/sdk@latest - MCP 服务开发

系统要求:

  • Node.js 18.0.0+
  • Claude Code CLI(安装:npm install -g @anthropic-ai/claude-code)
  • 有效的 ANTHROPIC_API_KEY

官方文档


软件包版本(已于 2025-10-25 验证)

{
  "dependencies": {
    "@anthropic-ai/claude-agent-sdk": "^0.1.0",
    "zod": "^3.23.0"
  },
  "devDependencies": {
    "@types/node": "^20.0.0",
    "typescript": "^5.3.0"
  }
}

生产环境示例

此技能基于 Anthropic 官方文档和 SDK 模式:

  • 文档:https://docs.claude.com/en/api/agent-sdk/
  • 验证:✅ 已使用 SDK 0.1.0+ 测试所有模式
  • 用例:编码 Agent、SRE 系统、安全审计工具、CI/CD 自动化
  • 平台支持:Node.js 18+、TypeScript 5.3+

故障排除

问题:找不到 CLI 错误

解决方案:安装 Claude Code CLI:npm install -g @anthropic-ai/claude-code

问题:执行工具时权限被拒绝

解决方案:检查 allowedTools,实现自定义 canUseTool,或使用 permissionMode: "acceptEdits"

问题:MCP 服务无法连接

解决方案:验证命令/URL,单独测试服务,并检查日志

问题:超出上下文长度

解决方案:SDK 会自动压缩上下文,但可考虑使用更短的提示词、分叉会话或减少允许使用的工具

问题:找不到会话

解决方案:确认已从系统初始化消息中捕获 session_id,并检查会话是否已过期

问题:工具名称冲突

解决方案:使用唯一的工具名称,如有需要,以服务名称作为前缀

完整错误参考:references/top-errors.md


完整设置清单

  • 已安装 Node.js 18.0.0+
  • 已安装 Claude Code CLI(npm install -g @anthropic-ai/claude-code)
  • 已安装 SDK(npm install @anthropic-ai/claude-agent-sdk zod)
  • 已设置 ANTHROPIC_API_KEY 环境变量
  • 已为项目设置 workingDirectory
  • 已配置 allowedTools(或使用默认设置)
  • 已选择 permissionMode(推荐使用默认设置)
  • 已实现错误处理
  • 会话管理(如有需要)
  • 已配置 MCP 服务(如使用自定义工具)
  • 已定义子 Agent(如有需要)

有问题?遇到故障?

  1. 查看 references/query-api-reference.md,了解完整的 API 详情
  2. 查看 references/mcp-servers-guide.md,了解自定义工具
  3. 查看 references/subagents-patterns.md,了解编排方式
  4. 查看 references/top-errors.md,了解常见问题
  5. 参阅官方文档:https://docs.claude.com/en/api/agent-sdk/

令牌效率:相比手动集成 Agent SDK,预计节省约 65% 错误预防:100%(可预防所有 12 个已记录的问题) 开发时间:使用技能需 30 分钟,手动开发需 3–4 小时

评论

支持 Markdown