关于 claude-agent-sdk
claude-agent-sdk 是用于构建和配置 Claude Agent 的 SDK 参考技能,面向开发者。内容涵盖结构化输出、工具权限、子 Agent 编排与会话管理,并说明 MCP 服务配置。
主要功能
- 01JSON Schema 结构化输出
- 02工具钩子与权限控制
- 03子 Agent 编排
- 04会话恢复与分支
- 05沙箱执行配置
适用场景
- 01验证 Agent 输出符合指定结构
- 02设置工具调用审批规则
- 03将任务委派给专用子 Agent
- 04从已有会话继续或创建分支
MCP 相关
说明如何为 SDK 配置进程内及外部 MCP 服务,支持 stdio、HTTP 和 SSE 传输,并提供服务工具的命名规则。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jezweb/ claude-skills --skill claude-agent-sdk安装后在 Claude Code 中输入/claude-agent-sdk确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
README.md.claude-plugin/plugin.jsonreferences/mcp-servers-guide.mdpermissions-guide.mdquery-api-reference.mdsession-management.mdsubagents-patterns.mdtop-errors.mdrules/claude-agent-sdk.mdscripts/check-versions.shtemplates/basic-query.tscustom-mcp-server.tserror-handling.tsfilesystem-settings.tsmulti-agent-workflow.tspackage.jsonpermission-control.tsquery-with-tools.tssession-management.tssubagents-orchestration.tstsconfig.json详细介绍
Claude Agent SDK - 结构化输出与错误预防指南
软件包:@anthropic-ai/[email protected] 重大变更: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";
import { zodToJsonSchema } from "zod-to-json-schema";
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}`);
}
}
Zod 兼容性(v0.1.71+): SDK 支持 Zod v3.24.1+ 和 Zod v4.0.0+ 作为 peer dependencies。两个版本的导入方式均为 import { z } from "zod"。
2. 插件系统(v0.1.27)
plugins数组 - 加载本地插件路径- 自定义插件支持 - 扩展 Agent 能力
3. Hooks 系统(v0.1.0+)
全部 12 种 Hook 事件:
| Hook | 触发时机 | 用途 |
|---|---|---|
PreToolUse | 工具执行前 | 验证、修改或阻止工具调用 |
PostToolUse | 工具执行后 | 记录结果、触发副作用 |
Notification | Agent 发送通知时 | 显示状态更新 |
UserPromptSubmit | 收到用户提示词时 | 预处理或验证输入 |
SubagentStart | 子 Agent 启动时 | 跟踪委派、记录上下文 |
SubagentStop | 子 Agent 完成时 | 汇总结果、清理 |
PreCompact | 压缩上下文前 | 截断前保存状态 |
PermissionRequest | 需要权限时 | 自定义审批工作流 |
Stop | Agent 停止时 | 清理、记录最终日志 |
SessionStart | 会话开始时 | 初始化状态 |
SessionEnd | 会话结束时 | 持久化状态、清理 |
Error | 发生错误时 | 自定义错误处理 |
Hook 配置:
const response = query({
prompt: "...",
options: {
hooks: {
PreToolUse: async (input) => {
console.log(`Tool: ${input.toolName}`);
return { allow: true }; // or { allow: false, message: "..." }
},
PostToolUse: async (input) => {
await logToolUsage(input.toolName, input.result);
}
}
}
});
4. 其他选项
fallbackModel- 失败时自动切换模型maxThinkingTokens- 控制扩展思考的预算strictMcpConfig- 严格验证 MCP 配置continue- 使用新提示词继续(与resume不同)permissionMode: 'plan'- 面向规划工作流的新权限模式
📚 文档:https://platform.claude.com/docs/en/agent-sdk/structured-outputs
Claude Agent SDK 完整参考
目录
核心 Query API
关键签名:
query(prompt: string | AsyncIterable<SDKUserMessage>, options?: Options)
-> AsyncGenerator<SDKMessage>
关键选项:
outputFormat- 结构化 JSON schema 验证(v0.1.45+)settingSources- 加载文件系统设置('user'|'project'|'local')canUseTool- 自定义权限逻辑回调agents- 以编程方式定义子 AgentmcpServers- MCP 服务配置permissionMode- 'default'|'acceptEdits'|'bypassPermissions'|'plan'betas- 启用 Beta 功能(例如,1M 上下文窗口)sandbox- 安全执行的沙盒设置enableFileCheckpointing- 启用文件状态快照systemPrompt- 系统提示词(字符串或预设对象)
扩展上下文(1M Tokens)
启用 100 万 Token 上下文窗口:
const response = query({
prompt: "Analyze this large codebase",
options: {
betas: ['context-1m-2025-08-07'], // Enable 1M context
model: "claude-sonnet-4-5"
}
});
系统提示词配置
systemPrompt 的两种形式:
// 1. Simple string
systemPrompt: "You are a helpful coding assistant."
// 2. Preset with optional append (preserves Claude Code defaults)
systemPrompt: {
type: 'preset',
preset: 'claude_code',
append: "\n\nAdditional context: Focus on security."
}
当你希望使用 Claude Code 的默认行为并添加自定义内容时,使用预设形式。
工具集成(内置 + 自定义)
工具控制:
allowedTools- 白名单(优先级更高)disallowedTools- 黑名单canUseTool- 自定义权限回调(参见“权限控制”部分)
内置工具: Read、Write、Edit、Bash、Grep、Glob、WebSearch、WebFetch、Task、NotebookEdit、BashOutput、KillBash、ListMcpResources、ReadMcpResource、AskUserQuestion
AskUserQuestion 工具(v0.1.71+)
在 Agent 执行期间启用用户交互:
const response = query({
prompt: "Review and refactor the codebase",
options: {
allowedTools: ["Read", "Write", "Edit", "AskUserQuestion"]
}
});
// Agent can now ask clarifying questions
// Questions appear in message stream as tool_call with name "AskUserQuestion"
使用场景:
- 在任务执行过程中澄清模糊需求
- 在执行破坏性操作前征得用户批准
- 提供选项并获取用户选择
工具配置(v0.1.57+)
工具配置的三种形式:
// 1. Exact allowlist (string array)
tools: ["Read", "Write", "Grep"]
// 2. Disable all tools (empty array)
tools: []
// 3. Preset with defaults (object form)
tools: { type: 'preset', preset: 'claude_code' }
注意: allowedTools 和 disallowedTools 仍然可用,但 tools 提供了更大的灵活性。
MCP 服务(模型上下文协议)
服务类型:
- 进程内 - 使用
tool()定义,通过createSdkMcpServer()创建 - 外部 - 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)
skills?: string[]; // Skills to load (v0.2.10+)
maxTurns?: number; // Maximum turns before stopping (v0.2.10+)
}
字段详情:
- description:何时使用该 Agent(主 Agent 用于委派任务)
- prompt:系统提示词(定义角色,并继承主上下文)
- tools:允许使用的工具(省略时继承主 Agent 的配置)
- model:模型覆盖(
haiku/sonnet/opus/inherit) - skills:为 Agent 加载的技能(v0.2.10+)
- maxTurns:在返回控制权前,将 Agent 的轮次限制为 N 轮(v0.2.10+)
用法:
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",
skills: ["security-best-practices"], // Load specific skills
maxTurns: 10 // Limit to 10 turns
}
}
⚠️ 子 Agent 清理警告
已知问题:父 Agent 停止后,子 Agent 不会停止(问题 #132)
父 Agent 停止时(通过取消或错误),已启动的子 Agent 会作为孤立进程继续运行。这可能导致:
- 资源泄漏
- 父 Agent 停止后工具仍继续执行
- 递归场景中 RAM 耗尽(Claude Code 问题 #4850)
解决方法:在 Stop 钩子中实现清理:
const response = query({
prompt: "Deploy to production",
options: {
agents: {
"deployer": {
description: "Handle deployments",
prompt: "Deploy the application",
tools: ["Bash"]
}
},
hooks: {
Stop: async (input) => {
// Manual cleanup of spawned processes
console.log("Parent stopped - cleaning up subagents");
// Implement process tracking and termination
}
}
}
});
增强功能跟踪:问题 #142 提议自动终止
会话管理
选项:
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
}
}
V2 会话 API(预览 - v0.1.54+)
更简单的多轮对话模式:
import {
unstable_v2_createSession,
unstable_v2_resumeSession,
unstable_v2_prompt
} from "@anthropic-ai/claude-agent-sdk";
// Create a new session
const session = await unstable_v2_createSession({
model: "claude-sonnet-4-5",
workingDirectory: process.cwd(),
allowedTools: ["Read", "Grep", "Glob"]
});
// Send prompts and stream responses
const stream = unstable_v2_prompt(session, "Analyze the codebase structure");
for await (const message of stream) {
console.log(message);
}
// Continue conversation in same session
const stream2 = unstable_v2_prompt(session, "Now suggest improvements");
for await (const message of stream2) {
console.log(message);
}
// Resume a previous session
const resumedSession = await unstable_v2_resumeSession(session.sessionId);
注意: V2 API 处于预览阶段(带有 unstable_ 前缀)。.receive() 方法在 v0.1.72 中更名为 .stream()。
权限控制
权限模式:
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" };
}
沙盒设置(安全关键)
为 Bash 命令启用沙盒执行:
const response = query({
prompt: "Run system diagnostics",
options: {
sandbox: {
enabled: true,
autoAllowBashIfSandboxed: true, // Auto-approve bash in sandbox
excludedCommands: ["rm", "dd", "mkfs"], // Never auto-approve these
allowUnsandboxedCommands: false // Deny unsandboxable commands
}
}
});
SandboxSettings 类型
type SandboxSettings = {
enabled: boolean;
autoAllowBashIfSandboxed?: boolean; // Default: false
excludedCommands?: string[];
allowUnsandboxedCommands?: boolean; // Default: false
network?: NetworkSandboxSettings;
ignoreViolations?: SandboxIgnoreViolations;
};
type NetworkSandboxSettings = {
enabled: boolean;
proxyUrl?: string; // HTTP proxy for network requests
};
关键选项:
enabled- 启用沙箱隔离autoAllowBashIfSandboxed- 对安全的 bash 命令跳过权限提示excludedCommands- 始终需要权限的命令allowUnsandboxedCommands- 允许无法在沙箱中运行的命令(有风险)network.proxyUrl- 通过代理路由网络流量,以便进行监控
最佳实践: 在处理不可信输入的生产环境 Agent 中,始终使用沙箱。
文件检查点
启用文件状态快照,以便回滚:
const response = query({
prompt: "Refactor the authentication module",
options: {
enableFileCheckpointing: true // Enable file snapshots
}
});
// Later: rewind file changes to a specific point
for await (const message of response) {
if (message.type === 'user' && message.uuid) {
// Can rewind to this point later
const userMessageUuid = message.uuid;
// To rewind (call on Query object)
await response.rewindFiles(userMessageUuid);
}
}
使用场景:
- 撤销失败的重构尝试
- 对代码更改进行 A/B 测试
- 安全地探索其他方案
文件系统设置
设置来源:
type SettingSource = 'user' | 'project' | 'local';
user-~/.claude/settings.json(全局)project-.claude/settings.json(团队共享)local-.claude/settings.local.json(由 git 忽略的覆盖设置)
默认值: 不加载任何设置(settingSources: [])
设置优先级
加载多个来源时,设置按以下顺序合并(优先级从高到低):
- 程序化选项(传递给
query())- 始终优先 - 本地设置(
.claude/settings.local.json) - 项目设置(
.claude/settings.json) - 用户设置(
~/.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"],以确保行为一致。
Query 对象方法
query() 函数会返回一个 Query 对象,其中包含以下方法:
const q = query({ prompt: "..." });
// Async iteration (primary usage)
for await (const message of q) { ... }
// Runtime model control
await q.setModel("claude-opus-4-5"); // Change model mid-session
await q.setMaxThinkingTokens(4096); // Set thinking budget
// Introspection
const models = await q.supportedModels(); // List available models
const commands = await q.supportedCommands(); // List available commands
const account = await q.accountInfo(); // Get account details
// MCP status
const status = await q.mcpServerStatus(); // Check MCP server status
// Returns: { [serverName]: { status: 'connected' | 'failed', error?: string } }
// File operations (requires enableFileCheckpointing)
await q.rewindFiles(userMessageUuid); // Rewind to checkpoint
使用场景:
- 根据任务复杂度动态切换模型
- 监控 MCP 服务的运行状况
- 为推理任务调整思考预算
消息类型与流式传输
消息类型:
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_FAILED | API 密钥无效 | 检查 ANTHROPIC_API_KEY 环境变量 |
RATE_LIMIT_EXCEEDED | 请求过多 | 实现带退避机制的重试 |
CONTEXT_LENGTH_EXCEEDED | 提示词过长 | 使用会话压缩,减少上下文 |
PERMISSION_DENIED | 工具被阻止 | 检查 permissionMode、canUseTool |
TOOL_EXECUTION_FAILED | 工具错误 | 检查工具实现 |
SESSION_NOT_FOUND | 会话 ID 无效 | 验证会话 ID |
MCP_SERVER_FAILED | 服务错误 | 检查服务配置 |
预防已知问题
此技能可预防已记录的 14 个问题:
问题 #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"
来源:输入超出模型上下文窗口(问题 #138)
原因:代码库过大、对话过长
⚠️ 关键行为:会话一旦达到上下文限制:
- 该会话后续所有请求都会返回 "Prompt too long"
/compact命令会因相同错误而失败- 会话将永久损坏,必须弃用
预防策略:
// 1. Proactive session forking (create checkpoints before hitting limit)
const checkpoint = query({
prompt: "Checkpoint current state",
options: {
resume: sessionId,
forkSession: true // Create branch before hitting limit
}
});
// 2. Monitor time and rotate sessions proactively
const MAX_SESSION_TIME = 80 * 60 * 1000; // 80 minutes (before 90-min crash)
let sessionStartTime = Date.now();
function shouldRotateSession() {
return Date.now() - sessionStartTime > MAX_SESSION_TIME;
}
// 3. Start new sessions before hitting context limits
if (shouldRotateSession()) {
const summary = await getSummary(currentSession);
const newSession = query({
prompt: `Continue with context: ${summary}`
});
sessionStartTime = Date.now();
}
注意: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,检查文件权限
问题 #13:MCP 服务配置缺少 type 字段
错误:"Claude Code process exited with code 1"(晦涩且没有上下文)
来源:GitHub 问题 #131
原因:基于 URL 的 MCP 服务需要显式指定 type: "http" 或 type: "sse" 字段
预防措施:始终为基于 URL 的 MCP 服务指定传输类型
// ❌ Wrong - missing type field (causes cryptic exit code 1)
mcpServers: {
"my-server": {
url: "https://api.example.com/mcp"
}
}
// ✅ Correct - type field required for URL-based servers
mcpServers: {
"my-server": {
url: "https://api.example.com/mcp",
type: "http" // or "sse" for Server-Sent Events
}
}
诊断线索:如果看到 "process exited with code 1" 且没有其他上下文,请检查 MCP 服务配置是否缺少 type 字段。
问题 #14:包含 Unicode 行分隔符的 MCP 工具结果
错误:JSON 解析错误,Agent 挂起 来源:GitHub 问题 #137 原因:Unicode U+2028(行分隔符)和 U+2029(段落分隔符)在 JSON 中有效,但会导致 JavaScript 解析失败 预防措施:对 MCP 工具结果中的这些字符进行转义
// MCP tool handler - sanitize external data
tool("fetch_content", "Fetch text content", {}, async (args) => {
const content = await fetchExternalData();
// ✅ Sanitize Unicode line/paragraph separators
const sanitized = content
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
return {
content: [{ type: "text", text: sanitized }]
};
});
适用场景:可能包含这些字符的外部数据源(API、网页抓取、用户输入)
官方文档
- Agent SDK 概览:https://platform.claude.com/docs/en/api/agent-sdk/overview
- TypeScript API:https://platform.claude.com/docs/en/api/agent-sdk/typescript
- 结构化输出:https://platform.claude.com/docs/en/agent-sdk/structured-outputs
- GitHub(TypeScript):https://github.com/anthropics/claude-agent-sdk-typescript
- 更新日志:https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md
Token 效率:
- 不使用技能:约 15,000 个 token(MCP 设置、权限模式、会话 API、沙盒配置、钩子、结构化输出、错误处理)
- 使用技能:约 4,500 个 token(全面覆盖 v0.2.12 + 错误预防 + 高级模式)
- 节省:约 70%(约 10,500 个 token)
可预防的错误:14 个已记录问题,附有确切解决方案(包括 2 个来自社区的注意事项)
核心价值:V2 会话 API、沙盒设置、文件检查点、Query 方法、AskUserQuestion 工具、结构化输出(v0.1.45+)、会话分叉、canUseTool 模式、完整的钩子系统(12 个事件)、Zod v4 支持、子 Agent 清理模式
上次验证时间:2026-01-20 | 技能版本:3.1.0 | 变更:新增 Issue #13(MCP type 字段)、Issue #14(Unicode U+2028/U+2029),扩展 Issue #4(会话中断),新增带有 Stop 钩子模式的子 Agent 清理警告