mcpField
C
claude-agent-sdk

claude-agent-sdk

github.com/ovachieverAgent 工作流5652 次安装48 周前更新
代码仓库

关于 claude-agent-sdk

claude-agent-sdk 是一份 Claude Agent SDK 使用指南,面向构建 TypeScript Agent 应用的开发者。它说明结构化输出、工具权限、会话管理、子 Agent 协作及 MCP 服务配置。

主要功能

  1. 01按 JSON Schema 验证结构化输出
  2. 02配置内置工具与权限规则
  3. 03定义并调用子 Agent
  4. 04恢复或分叉会话
  5. 05连接进程内及外部 MCP 服务

适用场景

  1. 01要求 Agent 返回符合模式的结果
  2. 02限制 Agent 可调用的工具
  3. 03为不同任务配置子 Agent
  4. 04通过 MCP 服务扩展 Agent 可用工具

MCP 相关

指南说明如何配置进程内 MCP 服务,以及通过 stdio、HTTP 或 SSE 连接外部 MCP 服务,并将其工具提供给 Agent。

安装

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

$npx skills add https://github.com/ovachiever/droid-tings --skill claude-agent-sdk

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

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
.claude-plugin/
plugin.json
references/
mcp-servers-guide.md
permissions-guide.md
query-api-reference.md
session-management.md
subagents-patterns.md
top-errors.md
scripts/
check-versions.sh
templates/
basic-query.ts
custom-mcp-server.ts
error-handling.ts
filesystem-settings.ts
multi-agent-workflow.ts
package.json
permission-control.ts
query-with-tools.ts
session-management.ts
subagents-orchestration.ts
tsconfig.json

详细介绍

Claude Agent SDK - 结构化输出与错误预防指南

软件包:@anthropic-ai/[email protected](2025 年 11 月 21 日) 重大变更:v0.1.45 - 结构化输出(2025 年 11 月),v0.1.0 - 无默认系统提示词,必须设置 settingSources


v0.1.45+ 新增内容(2025 年 11 月)

主要功能:

1. 结构化输出(v0.1.45,2025 年 11 月 14 日)
  • JSON schema 验证 - 确保响应符合精确的 schema
  • outputFormat 参数 - 使用 JSON schema 或 Zod 定义输出结构
  • 访问经过验证的结果 - 通过 message.structured_output
  • 必需的 Beta 标头:structured-outputs-2025-11-13
  • 类型安全 - 使用 Zod schema 实现完整的 TypeScript 类型推断

示例:

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

const schema = z.object({
  summary: z.string(),
  sentiment: z.enum(['positive', 'neutral', 'negative']),
  confidence: z.number().min(0).max(1)
});

const response = query({
  prompt: "Analyze this code review feedback",
  options: {
    model: "claude-sonnet-4-5",
    outputFormat: {
      type: "json_schema",
      json_schema: {
        name: "AnalysisResult",
        strict: true,
        schema: zodToJsonSchema(schema)
      }
    }
  }
});

for await (const message of response) {
  if (message.type === 'result' && message.structured_output) {
    // Guaranteed to match schema
    const validated = schema.parse(message.structured_output);
    console.log(`Sentiment: ${validated.sentiment}`);
  }
}
2. 插件系统(v0.1.27)
  • plugins 数组 - 加载本地插件路径
  • 自定义插件支持 - 扩展 Agent 功能
3. Hooks 系统(v0.1.0+)
  • 事件驱动的回调 - PreToolUse、PostToolUse、Notification、UserPromptSubmit
  • 会话事件 hooks - 监控并控制 Agent 行为
4. 其他选项
  • fallbackModel - 在失败时自动切换备用模型
  • maxThinkingTokens - 控制扩展思考的预算
  • strictMcpConfig - 严格验证 MCP 配置
  • continue - 使用新提示词继续(与 resume 不同)
  • permissionMode: 'plan' - 用于规划工作流的新权限模式

📚 文档:https://platform.claude.com/docs/en/agent-sdk/structured-outputs


Claude Agent SDK 完整参考

目录

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

核心 Query API

关键签名:

query(prompt: string | AsyncIterable<SDKUserMessage>, options?: Options)
  -> AsyncGenerator<SDKMessage>

重要选项:

  • outputFormat - 结构化 JSON schema 验证(v0.1.45+)
  • settingSources - 加载文件系统设置('user'|'project'|'local')
  • canUseTool - 自定义权限逻辑回调
  • agents - 以编程方式定义子 Agent
  • mcpServers - MCP 服务配置
  • permissionMode - 'default'|'acceptEdits'|'bypassPermissions'|'plan'

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

工具控制:

  • allowedTools - 允许列表(优先级更高)
  • disallowedTools - 禁止列表
  • canUseTool - 自定义权限回调(参见“权限控制”部分)

**内置工具:**Read、Write、Edit、Bash、Grep、Glob、WebSearch、WebFetch、Task、NotebookEdit、BashOutput、KillBash、ListMcpResources、ReadMcpResource


MCP 服务(Model Context Protocol)

服务类型:

  • 进程内 - 使用 createSdkMcpServer() 和 tool() 定义
  • 外部 - stdio、HTTP、SSE 传输

工具定义:

tool(name: string, description: string, zodSchema, handler)

处理程序返回值:

{ content: [{ type: "text", text: "..." }], isError?: boolean }
外部 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>

重要:

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

示例:mcp__weather-service__get_weather、mcp__filesystem__read_file


子 Agent 编排

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 用其进行任务委派)
  • prompt:系统提示词(定义角色,并继承主上下文)
  • tools:允许使用的工具(省略时继承主 Agent 的设置)
  • model:覆盖模型(haiku/sonnet/opus/inherit)

用法:

agents: {
  "security-checker": {
    description: "Security audits and vulnerability scanning",
    prompt: "You check security. Scan for secrets, verify OWASP compliance.",
    tools: ["Read", "Grep", "Bash"],
    model: "sonnet"
  }
}

会话管理

选项:

  • resume: sessionId - 继续之前的会话
  • forkSession: true - 从会话创建新分支
  • continue: prompt - 使用新提示词恢复(与 resume 不同)

会话分支模式(独有功能):

// Explore alternative without modifying original
const forked = query({
  prompt: "Try GraphQL instead of REST",
  options: {
    resume: sessionId,
    forkSession: true  // Creates new branch, original session unchanged
  }
});

捕获会话 ID:

for await (const message of response) {
  if (message.type === 'system' && message.subtype === 'init') {
    sessionId = message.session_id;  // Save for later resume/fork
  }
}

权限控制

权限模式:

type PermissionMode = "default" | "acceptEdits" | "bypassPermissions" | "plan";
  • default - 标准权限检查
  • acceptEdits - 自动批准文件编辑
  • bypassPermissions - 跳过所有检查(仅用于 CI/CD)
  • plan - 规划模式(v0.1.45+)
自定义权限逻辑
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(被 git 忽略的覆盖设置)

默认值: 不加载任何设置(settingSources: [])

设置优先级

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

  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 中使用 settingSources: ["project"],以确保行为一致。


消息类型与流式传输

消息类型:

  • system - 会话初始化/完成(包含 session_id)
  • assistant - Agent 响应
  • tool_call - 工具执行请求
  • tool_result - 工具执行结果
  • error - 错误消息
  • result - 最终结果(v0.1.45+ 包含 structured_output)

流式传输模式:

for await (const message of response) {
  if (message.type === 'system' && message.subtype === 'init') {
    sessionId = message.session_id;  // Capture for resume/fork
  }
  if (message.type === 'result' && message.structured_output) {
    // Structured output available (v0.1.45+)
    const validated = schema.parse(message.structured_output);
  }
}

错误处理

错误代码:

错误代码原因解决方案
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服务错误检查服务配置

预防已知问题

此技能可预防已记录的 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 包含不存在的文件 预防:将文件添加到来源之前,先检查文件是否存在

问题 #10:工具名称冲突

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

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

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

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

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


官方文档


Token 效率:

  • 不使用 skill:约 12,000 个 token(MCP 设置、权限模式、会话分叉、结构化输出、错误处理)
  • 使用 skill:约 3,600 个 token(专注于 v0.1.45+ 功能、错误预防和高级模式)
  • 节省:约 70%(约 8,400 个 token)

已预防的错误:12 个有精确解决方案的已记录问题 核心价值:结构化输出(v0.1.45+)、会话分叉、canUseTool 模式、settingSources 优先级、MCP 命名、错误代码


上次验证:2025-11-22 | Skill 版本:2.0.0 | 变更:新增 v0.1.45 结构化输出、插件、钩子和新选项。移除教程/基础示例(约 750 行)。专注于知识缺口、错误预防和高级模式。

评论

支持 Markdown