Claude Agent SDK - Structured Outputs & Error Prevention Guide
Package: @anthropic-ai/claude-agent-sdk@0.2.12
Breaking Changes: v0.1.45 - Structured outputs (Nov 2025), v0.1.0 - No default system prompt, settingSources required
What's New in v0.1.45+ (Nov 2025)
Major Features:
1. Structured Outputs (v0.1.45, Nov 14, 2025)
- - JSON schema validation - Guarantees responses match exact schemas
outputFormat parameter - Define output structure with JSON schema or Zod- Access validated results - Via INLINECODE1
- Beta header required: INLINECODE2
- Type safety - Full TypeScript inference with Zod schemas
Example:
CODEBLOCK0
Zod Compatibility (v0.1.71+): SDK supports both Zod v3.24.1+ and Zod v4.0.0+ as peer dependencies. Import remains import { z } from "zod" for either version.
2. Plugins System (v0.1.27)
- -
plugins array - Load local plugin paths - Custom plugin support - Extend agent capabilities
3. Hooks System (v0.1.0+)
All 12 Hook Events:
| Hook | When Fired | Use Case |
|---|
| INLINECODE5 | Before tool execution | Validate, modify, or block tool calls |
| INLINECODE6 |
After tool execution | Log results, trigger side effects |
|
Notification | Agent notifications | Display status updates |
|
UserPromptSubmit | User prompt received | Pre-process or validate input |
|
SubagentStart | Subagent spawned | Track delegation, log context |
|
SubagentStop | Subagent completed | Aggregate results, cleanup |
|
PreCompact | Before context compaction | Save state before truncation |
|
PermissionRequest | Permission needed | Custom approval workflows |
|
Stop | Agent stopping | Cleanup, final logging |
|
SessionStart | Session begins | Initialize state |
|
SessionEnd | Session ends | Persist state, cleanup |
|
Error | Error occurred | Custom error handling |
Hook Configuration:
CODEBLOCK1
4. Additional Options
- -
fallbackModel - Automatic model fallback on failures maxThinkingTokens - Control extended thinking budgetstrictMcpConfig - Strict MCP configuration validationcontinue - Resume with new prompt (differs from resume)permissionMode: 'plan' - New permission mode for planning workflows
📚 Docs: https://platform.claude.com/docs/en/agent-sdk/structured-outputs
The Complete Claude Agent SDK Reference
Table of Contents
- 1. Core Query API
- Tool Integration
- MCP Servers
- Subagent Orchestration
- Session Management
- Permission Control
- Sandbox Settings
- File Checkpointing
- Filesystem Settings
- Query Object Methods
- Message Types & Streaming
- Error Handling
- Known Issues
Core Query API
Key signature:
CODEBLOCK2
Critical Options:
- -
outputFormat - Structured JSON schema validation (v0.1.45+) - INLINECODE24 - Filesystem settings loading ('user'|'project'|'local')
- INLINECODE25 - Custom permission logic callback
- INLINECODE26 - Programmatic subagent definitions
- INLINECODE27 - MCP server configuration
- INLINECODE28 - 'default'|'acceptEdits'|'bypassPermissions'|'plan'
- INLINECODE29 - Enable beta features (e.g., 1M context window)
- INLINECODE30 - Sandbox settings for secure execution
- INLINECODE31 - Enable file state snapshots
- INLINECODE32 - System prompt (string or preset object)
Extended Context (1M Tokens)
Enable 1 million token context window:
CODEBLOCK3
System Prompt Configuration
Two forms of systemPrompt:
CODEBLOCK4
Use preset form when you want Claude Code's default behaviors plus custom additions.
Tool Integration (Built-in + Custom)
Tool Control:
- -
allowedTools - Whitelist (takes precedence) - INLINECODE34 - Blacklist
- INLINECODE35 - Custom permission callback (see Permission Control section)
Built-in Tools: Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource, AskUserQuestion
AskUserQuestion Tool (v0.1.71+)
Enable user interaction during agent execution:
CODEBLOCK5
Use cases:
- - Clarify ambiguous requirements mid-task
- Get user approval before destructive operations
- Present options and get selection
Tools Configuration (v0.1.57+)
Three forms of tool configuration:
CODEBLOCK6
Note: allowedTools and disallowedTools still work but tools provides more flexibility.
MCP Servers (Model Context Protocol)
Server Types:
- - In-process -
createSdkMcpServer() with tool() definitions - External - stdio, HTTP, SSE transport
Tool Definition:
CODEBLOCK7
Handler Return:
CODEBLOCK8
External MCP Servers (stdio)
CODEBLOCK9
External MCP Servers (HTTP/SSE)
CODEBLOCK10
MCP Tool Naming Convention
Format: INLINECODE41
CRITICAL:
- - Server name and tool name MUST match configuration
- Use double underscores (
__) as separators - Include in
allowedTools array
Examples: mcp__weather-service__get_weather, mcp__filesystem__read_file
Subagent Orchestration
AgentDefinition Type
CODEBLOCK11
Field Details:
- - description: When to use agent (used by main agent for delegation)
- prompt: System prompt (defines role, inherits main context)
- tools: Allowed tools (if omitted, inherits from main agent)
- model: Model override (
haiku/sonnet/opus/inherit) - skills: Skills to load for agent (v0.2.10+)
- maxTurns: Limit agent to N turns before returning control (v0.2.10+)
Usage:
CODEBLOCK12
⚠️ Subagent Cleanup Warning
Known Issue: Subagents don't stop when parent agent stops (Issue #132)
When a parent agent is stopped (via cancellation or error), spawned subagents continue running as orphaned processes. This can lead to:
- - Resource leaks
- Continued tool execution after parent stopped
- RAM out-of-memory in recursive scenarios (Claude Code Issue #4850)
Workaround: Implement cleanup in Stop hooks:
CODEBLOCK13
Enhancement Tracking: Issue #142 proposes auto-termination
Session Management
Options:
- -
resume: sessionId - Continue previous session - INLINECODE51 - Create new branch from session
- INLINECODE52 - Resume with new prompt (differs from
resume)
Session Forking Pattern (Unique Capability):
CODEBLOCK14
Capture Session ID:
CODEBLOCK15
V2 Session APIs (Preview - v0.1.54+)
Simpler multi-turn conversation pattern:
CODEBLOCK16
Note: V2 APIs are in preview (unstable_ prefix). The .receive() method was renamed to .stream() in v0.1.72.
Permission Control
Permission Modes:
CODEBLOCK17
- -
default - Standard permission checks - INLINECODE58 - Auto-approve file edits
- INLINECODE59 - Skip ALL checks (use in CI/CD only)
- INLINECODE60 - Planning mode (v0.1.45+)
Custom Permission Logic
CODEBLOCK18
canUseTool Callback
CODEBLOCK19
Examples:
CODEBLOCK20
Sandbox Settings (Security-Critical)
Enable sandboxed execution for Bash commands:
CODEBLOCK21
SandboxSettings Type
CODEBLOCK22
Key Options:
- -
enabled - Activate sandbox isolation - INLINECODE62 - Skip permission prompts for safe bash commands
- INLINECODE63 - Commands that always require permission
- INLINECODE64 - Allow commands that can't be sandboxed (risky)
- INLINECODE65 - Route network through proxy for monitoring
Best Practice: Always use sandbox in production agents handling untrusted input.
File Checkpointing
Enable file state snapshots for rollback capability:
CODEBLOCK23
Use cases:
- - Undo failed refactoring attempts
- A/B test code changes
- Safe exploration of alternatives
Filesystem Settings
Setting Sources:
CODEBLOCK24
- -
user - ~/.claude/settings.json (global) - INLINECODE68 -
.claude/settings.json (team-shared) - INLINECODE70 -
.claude/settings.local.json (gitignored overrides)
Default: NO settings loaded (settingSources: [])
Settings Priority
When multiple sources loaded, settings merge in this order (highest priority first):
- 1. Programmatic options (passed to
query()) - Always win - Local settings (
.claude/settings.local.json) - Project settings (
.claude/settings.json) - User settings (
~/.claude/settings.json)
Example:
CODEBLOCK25
Best Practice: Use settingSources: ["project"] in CI/CD for consistent behavior.
Query Object Methods
The query() function returns a Query object with these methods:
CODEBLOCK26
Use cases:
- - Dynamic model switching based on task complexity
- Monitoring MCP server health
- Adjusting thinking budget for reasoning tasks
Message Types & Streaming
Message Types:
- -
system - Session init/completion (includes session_id) - INLINECODE82 - Agent responses
- INLINECODE83 - Tool execution requests
- INLINECODE84 - Tool execution results
- INLINECODE85 - Error messages
- INLINECODE86 - Final result (includes
structured_output for v0.1.45+)
Streaming Pattern:
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);
}
}
Error Handling
Error Codes:
| Error Code | Cause | Solution |
|---|
| INLINECODE88 | Claude Code not installed | Install: INLINECODE89 |
| INLINECODE90 |
Invalid API key | Check ANTHROPIC
APIKEY env var |
|
RATE_LIMIT_EXCEEDED | Too many requests | Implement retry with backoff |
|
CONTEXT_LENGTH_EXCEEDED | Prompt too long | Use session compaction, reduce context |
|
PERMISSION_DENIED | Tool blocked | Check permissionMode, canUseTool |
|
TOOL_EXECUTION_FAILED | Tool error | Check tool implementation |
|
SESSION_NOT_FOUND | Invalid session ID | Verify session ID |
|
MCP_SERVER_FAILED | Server error | Check server configuration |
Known Issues Prevention
This skill prevents 14 documented issues:
Issue #1: CLI Not Found Error
Error:
"Claude Code CLI not installed"
Source: SDK requires Claude Code CLI
Why It Happens: CLI not installed globally
Prevention: Install before using SDK: INLINECODE98
Issue #2: Authentication Failed
Error:
"Invalid API key"
Source: Missing or incorrect ANTHROPIC
APIKEY
Why It Happens: Environment variable not set
Prevention: Always set INLINECODE100
Issue #3: Permission Denied Errors
Error: Tool execution blocked
Source:
permissionMode restrictions
Why It Happens: Tool not allowed by permissions
Prevention: Use
allowedTools or custom
canUseTool callback
Issue #4: Context Length Exceeded (Session-Breaking)
Error:
"Prompt too long"
Source: Input exceeds model context window (
Issue #138)
Why It Happens: Large codebase, long conversations
⚠️ Critical Behavior: Once a session hits context limit:
- 1. All subsequent requests to that session return "Prompt too long"
- INLINECODE105 command fails with same error
- Session is permanently broken and must be abandoned
Prevention Strategies:
CODEBLOCK28
Note: SDK auto-compacts, but if limit is reached, session becomes unrecoverable
Issue #5: Tool Execution Timeout
Error: Tool doesn't respond
Source: Long-running tool execution
Why It Happens: Tool takes too long (>5 minutes default)
Prevention: Implement timeout handling in tool implementations
Issue #6: Session Not Found
Error:
"Invalid session ID"
Source: Session expired or invalid
Why It Happens: Session ID incorrect or too old
Prevention: Capture
session_id from
system init message
Issue #7: MCP Server Connection Failed
Error: Server not responding
Source: Server not running or misconfigured
Why It Happens: Command/URL incorrect, server crashed
Prevention: Test MCP server independently, verify command/URL
Issue #8: Subagent Definition Errors
Error: Invalid AgentDefinition
Source: Missing required fields
Why It Happens:
description or
prompt missing
Prevention: Always include
description and
prompt fields
Issue #9: Settings File Not Found
Error:
"Cannot read settings"
Source: Settings file doesn't exist
Why It Happens:
settingSources includes non-existent file
Prevention: Check file exists before including in sources
Issue #10: Tool Name Collision
Error: Duplicate tool name
Source: Multiple tools with same name
Why It Happens: Two MCP servers define same tool name
Prevention: Use unique tool names, prefix with server name
Issue #11: Zod Schema Validation Error
Error: Invalid tool input
Source: Input doesn't match Zod schema
Why It Happens: Agent provided wrong data type
Prevention: Use descriptive Zod schemas with INLINECODE115
Issue #12: Filesystem Permission Denied
Error: Cannot access path
Source: Restricted filesystem access
Why It Happens: Path outside
workingDirectory or no permissions
Prevention: Set correct
workingDirectory, check file permissions
Issue #13: MCP Server Config Missing type Field
Error:
"Claude Code process exited with code 1" (cryptic, no context)
Source:
GitHub Issue #131
Why It Happens: URL-based MCP servers require explicit
type: "http" or
type: "sse" field
Prevention: Always specify transport type for URL-based MCP servers
CODEBLOCK29
Diagnostic Clue: If you see "process exited with code 1" with no other context, check your MCP server configuration for missing type fields.
Issue #14: MCP Tool Result with Unicode Line Separators
Error: JSON parse error, agent hangs
Source:
GitHub Issue #137
Why It Happens: Unicode U+2028 (line separator) and U+2029 (paragraph separator) are valid in JSON but break JavaScript parsing
Prevention: Escape these characters in MCP tool results
CODEBLOCK30
When This Matters: External data sources (APIs, web scraping, user input) that may contain these characters
Related: MCP Python SDK Issue #1356
Official Documentation
- - Agent SDK Overview: https://platform.claude.com/docs/en/api/agent-sdk/overview
- TypeScript API: https://platform.claude.com/docs/en/api/agent-sdk/typescript
- Structured Outputs: https://platform.claude.com/docs/en/agent-sdk/structured-outputs
- GitHub (TypeScript): https://github.com/anthropics/claude-agent-sdk-typescript
- CHANGELOG: https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md
Token Efficiency:
- - Without skill: ~15,000 tokens (MCP setup, permission patterns, session APIs, sandbox config, hooks, structured outputs, error handling)
- With skill: ~4,500 tokens (comprehensive v0.2.12 coverage + error prevention + advanced patterns)
- Savings: ~70% (~10,500 tokens)
Errors prevented: 14 documented issues with exact solutions (including 2 community-sourced gotchas)
Key value: V2 Session APIs, Sandbox Settings, File Checkpointing, Query methods, AskUserQuestion tool, structured outputs (v0.1.45+), session forking, canUseTool patterns, complete hooks system (12 events), Zod v4 support, subagent cleanup patterns
Last verified: 2026-01-20 |
Skill version: 3.1.0 |
Changes: Added Issue #13 (MCP type field), Issue #14 (Unicode U+2028/U+2029), expanded Issue #4 (session-breaking), added subagent cleanup warning with Stop hook pattern
Claude Agent SDK - 结构化输出与错误预防指南
包名: @anthropic-ai/claude-agent-sdk@0.2.12
重大变更: 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 类型推断
示例:
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: 分析这段代码审查反馈,
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) {
// 保证与 schema 匹配
const validated = schema.parse(message.structured_output);
console.log(情感分析: ${validated.sentiment});
}
}
Zod 兼容性 (v0.1.71+): SDK 支持 Zod v3.24.1+ 和 Zod v4.0.0+ 作为对等依赖。两种版本都使用 import { z } from zod 导入。
2. 插件系统 (v0.1.27)
- - plugins 数组 - 加载本地插件路径
- 自定义插件支持 - 扩展代理能力
3. 钩子系统 (v0.1.0+)
全部 12 个钩子事件:
| 钩子 | 触发时机 | 使用场景 |
|---|
| PreToolUse | 工具执行前 | 验证、修改或阻止工具调用 |
| PostToolUse |
工具执行后 | 记录结果、触发副作用 |
| Notification | 代理通知 | 显示状态更新 |
| UserPromptSubmit | 收到用户提示 | 预处理或验证输入 |
| SubagentStart | 子代理生成 | 跟踪委派、记录上下文 |
| SubagentStop | 子代理完成 | 汇总结果、清理 |
| PreCompact | 上下文压缩前 | 在截断前保存状态 |
| PermissionRequest | 需要权限 | 自定义审批流程 |
| Stop | 代理停止 | 清理、最终日志记录 |
| SessionStart | 会话开始 | 初始化状态 |
| SessionEnd | 会话结束 | 持久化状态、清理 |
| Error | 发生错误 | 自定义错误处理 |
钩子配置:
typescript
const response = query({
prompt: ...,
options: {
hooks: {
PreToolUse: async (input) => {
console.log(工具: ${input.toolName});
return { allow: true }; // 或 { 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 完整参考
目录
- 1. 核心查询 API
- 工具集成
- MCP 服务器
- 子代理编排
- 会话管理
- 权限控制
- 沙箱设置
- 文件检查点
- 文件系统设置
- 查询对象方法
- 消息类型与流式处理
- 错误处理
- 已知问题
核心查询 API
关键签名:
typescript
query(prompt: string | AsyncIterable, options?: Options)
-> AsyncGenerator
关键选项:
- - outputFormat - 结构化 JSON schema 验证 (v0.1.45+)
- settingSources - 文件系统设置加载 (user|project|local)
- canUseTool - 自定义权限逻辑回调
- agents - 编程式子代理定义
- mcpServers - MCP 服务器配置
- permissionMode - default|acceptEdits|bypassPermissions|plan
- betas - 启用 Beta 功能(例如 1M 上下文窗口)
- sandbox - 安全执行的沙箱设置
- enableFileCheckpointing - 启用文件状态快照
- systemPrompt - 系统提示(字符串或预设对象)
扩展上下文 (1M Token)
启用 100 万 token 上下文窗口:
typescript
const response = query({
prompt: 分析这个大型代码库,
options: {
betas: [context-1m-2025-08-07], // 启用 1M 上下文
model: claude-sonnet-4-5
}
});
系统提示配置
systemPrompt 的两种形式:
typescript
// 1. 简单字符串
systemPrompt: 你是一个有用的编程助手。
// 2. 带可选追加的预设(保留 Claude Code 默认值)
systemPrompt: {
type: preset,
preset: claude_code,
append: \n\n额外上下文: 关注安全性。
}
使用预设形式 当你想保留 Claude Code 的默认行为并添加自定义内容时。
工具集成 (内置 + 自定义)
工具控制:
- - allowedTools - 白名单(优先)
- disallowedTools - 黑名单
- canUseTool - 自定义权限回调(见权限控制部分)
内置工具: Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource, AskUserQuestion
AskUserQuestion 工具 (v0.1.71+)
在代理执行期间启用用户交互:
typescript
const response = query({
prompt: 审查并重构代码库,
options: {
allowedTools: [Read, Write, Edit, AskUserQuestion]
}
});
// 代理现在可以提出澄清问题
// 问题在消息流中显示为 tool_call,名称为 AskUserQuestion
使用场景:
- - 在任务执行中澄清模糊需求
- 在破坏性操作前获取用户批准
- 呈现选项并获取选择
工具配置 (v0.1.57+)
工具配置的三种形式:
typescript
// 1. 精确允许列表(字符串数组)
tools: [Read, Write, Grep]
// 2. 禁用所有工具(空数组)
tools: []
// 3. 带默认值的预设(对象形式)
tools: { type: preset, preset: claude_code }
注意: allowedTools 和 disallowedTools 仍然可用,但 tools 提供了更多灵活性。
MCP 服务器 (模型上下文协议)
服务器类型:
- - 进程内 - 使用 tool() 定义的 createS