claude-agent-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClaude Agent SDK
Claude Agent SDK
Status: Production Ready
Last Updated: 2025-11-21
Dependencies: @anthropic-ai/claude-code, zod
Latest Versions: @anthropic-ai/claude-code@2.0.49+, zod@3.23.0+
状态: 生产就绪
最后更新时间: 2025-11-21
依赖项: @anthropic-ai/claude-code, zod
最新版本: @anthropic-ai/claude-code@2.0.49+, zod@3.23.0+
Quick Start (5 Minutes)
快速开始(5分钟)
1. Install SDK
1. 安装SDK
bash
bun add @anthropic-ai/claude-agent-sdk zodWhy these packages:
- - Main Agent SDK
@anthropic-ai/claude-agent-sdk - - Type-safe schema validation for tools
zod
bash
bun add @anthropic-ai/claude-agent-sdk zod为何选择这些包:
- - 核心Agent SDK
@anthropic-ai/claude-agent-sdk - - 用于工具的类型安全 schema 验证
zod
2. Set API Key
2. 设置API密钥
bash
export ANTHROPIC_API_KEY="sk-ant-..."CRITICAL:
- API key required for all agent operations
- Never commit API keys to version control
- Use environment variables
bash
export ANTHROPIC_API_KEY="sk-ant-..."重要提示:
- 所有代理操作均需API密钥
- 切勿将API密钥提交至版本控制系统
- 使用环境变量存储
3. Basic Query
3. 基础查询
typescript
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);
}
}typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
const response = query({
prompt: "分析代码库并提出改进建议",
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);
}
}Secure Installation
安全安装
Agent SDK packages provide system-level capabilities — verify before installing to prevent unauthorized agent access. Follow supply chain security best practices:
- Block post-install scripts — (or Bun: disabled by default)
npm config set ignore-scripts true - Cooldown period — Wait 7 days for new package versions to be vetted by the community
- Audit before installing — Run or use
socket package score npm <pkg>to check packagessocket npm install <pkg>
Load the skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement.
dependency-upgradeAgent SDK包具备系统级能力——安装前请进行验证,防止未授权代理访问。遵循供应链安全最佳实践:
- 阻止安装后脚本 — (Bun默认已禁用)
npm config set ignore-scripts true - 冷却期 — 等待7天,让社区审核新版本包
- 安装前审计 — 运行 或使用
socket package score npm <pkg>检查包安全性socket npm install <pkg>
加载技能以获取完整安全配置,包括Socket CLI集成、冷却期设置、锁文件验证和CI强制执行。
dependency-upgradeThe Complete Claude Agent SDK Reference
Claude Agent SDK完整参考文档
Table of Contents
目录
When to Load References
何时加载参考文档
The skill includes comprehensive reference files for deep dives. Load these when needed:
- - Load when configuring query() options, working with message types, understanding filesystem settings, or debugging API behavior
references/query-api-reference.md - - Load when creating custom tools, integrating external MCP servers, or debugging server connections
references/mcp-servers-guide.md - - Load when designing multi-agent systems, orchestrating specialized agents, or optimizing agent workflows
references/subagents-patterns.md - - Load when implementing persistent conversations, forking sessions, or managing long-running interactions
references/session-management.md - - Load when implementing custom permission logic, securing agent capabilities, or controlling tool access
references/permissions-guide.md - - Load when encountering errors, debugging issues, or implementing error handling
references/top-errors.md
本技能包含全面的参考文件,供深入学习使用。按需加载:
- - 配置query()选项、处理消息类型、理解文件系统设置或调试API行为时加载
references/query-api-reference.md - - 创建自定义工具、集成外部MCP服务器或调试服务器连接时加载
references/mcp-servers-guide.md - - 设计多代理系统、编排专业代理或优化代理工作流时加载
references/subagents-patterns.md - - 实现持久对话、会话分支或管理长期交互时加载
references/session-management.md - - 实现自定义权限逻辑、保障代理能力安全或控制工具访问时加载
references/permissions-guide.md - - 遇到错误、调试问题或实现错误处理时加载
references/top-errors.md
Core Query API
核心查询API
The function is the primary interface for interacting with Claude Code CLI programmatically. It returns an AsyncGenerator that streams messages as the agent works.
query()For complete API details, options, and advanced patterns: Load when working with advanced configurations, message streaming, or filesystem settings.
references/query-api-reference.mdquery()如需完整API细节、选项和高级模式:处理高级配置、消息流式传输或文件系统设置时,加载。
references/query-api-reference.mdBasic Usage
基础用法
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
const response = query({
prompt: "Review this code for bugs",
options: {
model: "claude-sonnet-4-5", // or "haiku", "opus"
workingDirectory: "/path/to/project",
allowedTools: ["Read", "Grep", "Glob"],
permissionMode: "default"
}
});
for await (const message of response) {
// Process streaming messages
}typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
const response = query({
prompt: "检查此代码中的bug",
options: {
model: "claude-sonnet-4-5", // 或 "haiku", "opus"
workingDirectory: "/path/to/project",
allowedTools: ["Read", "Grep", "Glob"],
permissionMode: "default"
}
});
for await (const message of response) {
// 处理流式消息
}Model Selection
模型选择
| Model | ID | Best For | Speed | Capability |
|---|---|---|---|---|
| Haiku | | Fast tasks, monitoring | Fastest | Basic |
| Sonnet | | Balanced | Medium | High |
| Opus | | Complex reasoning | Slowest | Highest |
| 模型 | ID | 最佳适用场景 | 速度 | 能力 |
|---|---|---|---|---|
| Haiku | | 快速任务、监控 | 最快 | 基础 |
| Sonnet | | 平衡型任务 | 中等 | 高级 |
| Opus | | 复杂推理任务 | 最慢 | 顶级 |
Tool Integration (Built-in + Custom)
工具集成(内置+自定义)
Claude Code provides built-in tools (Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task) that can be controlled via and options.
allowedToolsdisallowedToolsFor complete tool configuration, custom monitoring, and advanced patterns: Load when implementing tool restrictions or monitoring.
references/query-api-reference.mdClaude Code提供内置工具(Read、Write、Edit、Bash、Grep、Glob、WebSearch、WebFetch、Task),可通过和选项进行控制。
allowedToolsdisallowedTools如需完整工具配置、自定义监控和高级模式:实现工具限制或监控时,加载。
references/query-api-reference.mdAllowing/Disallowing Tools
允许/禁用工具
typescript
// 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
}
});CRITICAL: = whitelist (only these tools), = blacklist (everything except these). If both specified, wins.
allowedToolsdisallowedToolsallowedToolstypescript
// 白名单方式(推荐)
const response = query({
prompt: "分析代码但不要进行任何修改",
options: {
allowedTools: ["Read", "Grep", "Glob"]
// 仅允许使用这些工具
}
});
// 黑名单方式
const response = query({
prompt: "审查并修复问题",
options: {
disallowedTools: ["Bash"]
// 除Bash外允许所有工具
}
});重要提示: = 白名单(仅允许这些工具), = 黑名单(除这些外都允许)。若同时指定,优先级更高。
allowedToolsdisallowedToolsallowedToolsMCP Servers (Model Context Protocol)
MCP服务器(模型上下文协议)
MCP servers extend agent capabilities with custom tools via (in-process) or external servers (stdio, HTTP, SSE).
createSdkMcpServer()For complete MCP server implementation guide: Load when creating custom tools or integrating MCP servers.
references/mcp-servers-guide.mdQuick Example: Create server with , use with option and
tool(name, description, zodSchema, handler)mcpServersallowedTools: ["mcp__<server>__<tool>"]MCP服务器通过(进程内)或外部服务器(stdio、HTTP、SSE)扩展代理的自定义工具能力。
createSdkMcpServer()如需完整MCP服务器实现指南:创建自定义工具或集成MCP服务器时,加载。
references/mcp-servers-guide.md快速示例:使用创建服务器,通过选项和使用
tool(name, description, zodSchema, handler)mcpServersallowedTools: ["mcp__<server>__<tool>"]Subagent Orchestration
子代理编排
Specialized agents with focused expertise, custom tools, different models, and dedicated prompts for multi-agent workflows.
For complete subagent patterns and orchestration strategies: Load when designing multi-agent systems.
references/subagents-patterns.mdAgentDefinition: Use option with objects containing , , (optional), (optional)
agentsdescriptionprompttoolsmodel具备专业技能的专用代理,拥有自定义工具、不同模型和专用提示词,适用于多代理工作流。
如需完整子代理模式和编排策略:设计多代理系统时,加载。
references/subagents-patterns.mdAgentDefinition:使用选项,传入包含、、(可选)、(可选)的对象
agentsdescriptionprompttoolsmodelSession Management
会话管理
Sessions enable persistent conversations, context preservation, and alternative exploration paths (forking).
For complete session patterns and workflows: Load when implementing persistent conversations.
references/session-management.mdUsage: Capture from system init message, resume with option, fork with
session_idresume: sessionIdforkSession: true会话支持持久对话、上下文保留和探索替代路径(分支)。
如需完整会话模式和工作流:实现持久对话时,加载。
references/session-management.md用法:从系统初始化消息中捕获,使用选项恢复会话,使用创建会话分支
session_idresume: sessionIdforkSession: truePermission Control
权限控制
Control agent capabilities with permission modes: (standard checks), (auto-approve edits), (skip all checks - use with caution).
"default""acceptEdits""bypassPermissions"For complete permission patterns and security policies: Load when implementing custom permission logic.
references/permissions-guide.mdCustom Logic: Use callback
canUseTool: async (toolName, input) => ({ behavior: "allow" | "deny" | "ask", message?: string })通过权限模式控制代理能力:(标准检查)、(自动批准编辑)、(跳过所有检查 - 谨慎使用)。
"default""acceptEdits""bypassPermissions"如需完整权限模式和安全策略:实现自定义权限逻辑时,加载。
references/permissions-guide.md自定义逻辑:使用回调函数
canUseTool: async (toolName, input) => ({ behavior: "allow" | "deny" | "ask", message?: string })Filesystem Settings
文件系统设置
Control which settings files load via array: (~/.claude/settings.json), (.claude/settings.json), (.claude/settings.local.json).
settingSources"user""project""local"For complete configuration and priority rules: Load when configuring settings sources.
references/query-api-reference.mdDefault: (no settings loaded). Priority: Programmatic > local > project > user
[]通过数组控制加载哪些配置文件: (~/.claude/settings.json)、 (.claude/settings.json)、 (.claude/settings.local.json)。
settingSources"user""project""local"如需完整配置和优先级规则:配置设置源时,加载。
references/query-api-reference.md默认值:(不加载任何设置)。优先级:编程配置 > local > project > user
[]Message Types & Streaming
消息类型与流式传输
The SDK streams messages: (init/completion), (responses), (tool requests), (tool outputs), (failures).
systemassistanttool_calltool_resulterrorFor complete message type reference and streaming patterns: Load when implementing advanced message handling.
references/query-api-reference.mdUsage: Process messages in loop, switch on
for await (const message of response)message.typeSDK流式传输的消息类型包括:(初始化/完成)、(响应)、(工具请求)、(工具输出)、(失败)。
systemassistanttool_calltool_resulterror如需完整消息类型参考和流式传输模式:实现高级消息处理时,加载。
references/query-api-reference.md用法:在循环中处理消息,根据进行分支处理
for await (const message of response)message.typeError Handling
错误处理
Common errors: , , , , .
CLI_NOT_FOUNDAUTHENTICATION_FAILEDRATE_LIMIT_EXCEEDEDCONTEXT_LENGTH_EXCEEDEDPERMISSION_DENIEDFor complete error catalog with solutions: Load when encountering errors or implementing error handling.
references/top-errors.mdPattern: Wrap query in try/catch, check , handle in streaming loop
error.codemessage.type === 'error'常见错误:、、、、。
CLI_NOT_FOUNDAUTHENTICATION_FAILEDRATE_LIMIT_EXCEEDEDCONTEXT_LENGTH_EXCEEDEDPERMISSION_DENIED如需完整错误目录及解决方案:遇到错误或实现错误处理时,加载。
references/top-errors.md模式:将query包裹在try/catch中,检查,在流式循环中处理的情况
error.codemessage.type === 'error'Known Issues Prevention
已知问题与预防
This skill prevents 12 documented issues. The top 3 most common:
本技能可预防12个已记录的问题。最常见的3个问题:
Issue #1: CLI Not Found Error
问题#1:CLI未找到错误
Error:
Prevention: Install before using SDK:
"Claude Code CLI not installed"bun add -g @anthropic-ai/claude-code错误信息:
预防方案:使用SDK前先安装:
"Claude Code CLI not installed"bun add -g @anthropic-ai/claude-codeIssue #2: Authentication Failed
问题#2:认证失败
Error:
Prevention: Always set
"Invalid API key"export ANTHROPIC_API_KEY="sk-ant-..."错误信息:
预防方案:始终设置
"Invalid API key"export ANTHROPIC_API_KEY="sk-ant-..."Issue #3: Permission Denied Errors
问题#3:权限拒绝错误
Error: Tool execution blocked
Prevention: Use or custom callback
allowedToolscanUseToolFor all 12 errors with complete solutions: Load when debugging or implementing error prevention.
references/top-errors.md错误信息:工具执行被阻止
预防方案:使用或自定义回调函数
allowedToolscanUseTool如需全部12个错误的完整解决方案:调试或实现错误预防时,加载。
references/top-errors.mdCritical Rules
关键规则
Always Do
必须执行
✅ Install Claude Code CLI before using SDK
✅ Set environment variable
✅ Capture from messages for resuming
✅ Use to restrict agent capabilities
✅ Implement for custom permission logic
✅ Handle all message types in streaming loop
✅ Use Zod schemas for tool input validation
✅ Set for multi-project environments
✅ Test MCP servers in isolation before integration
✅ Use in CI/CD
✅ Monitor tool execution with messages
✅ Implement error handling for all queries
ANTHROPIC_API_KEYsession_idsystemallowedToolscanUseToolworkingDirectorysettingSources: ["project"]tool_call✅ 使用SDK前安装Claude Code CLI
✅ 设置环境变量
✅ 从消息中捕获用于恢复会话
✅ 使用限制代理能力
✅ 实现自定义权限逻辑
✅ 在流式循环中处理所有消息类型
✅ 使用Zod schema进行工具输入验证
✅ 为多项目环境设置
✅ 集成前单独测试MCP服务器
✅ 在CI/CD中使用
✅ 通过消息监控工具执行
✅ 为所有查询实现错误处理
ANTHROPIC_API_KEYsystemsession_idallowedToolscanUseToolworkingDirectorysettingSources: ["project"]tool_callNever Do
禁止操作
❌ Commit API keys to version control
❌ Use in production (unless sandboxed)
❌ Assume tools executed (check messages)
❌ Ignore error messages in stream
❌ Skip session ID capture if planning to resume
❌ Use duplicate tool names across MCP servers
❌ Allow unrestricted Bash access without
❌ Load settings from user in CI/CD ()
❌ Trust tool results without validation
❌ Hardcode file paths (use )
❌ Use mode with untrusted prompts
❌ Skip Zod validation for tool inputs
bypassPermissionstool_resultcanUseToolsettingSources: ["user"]workingDirectoryacceptEdits❌ 将API密钥提交至版本控制系统
❌ 在生产环境中使用(除非处于沙箱环境)
❌ 假设工具已执行(需检查消息)
❌ 忽略流中的错误消息
❌ 若计划恢复会话,请勿跳过会话ID捕获
❌ 在MCP服务器间使用重复的工具名称
❌ 未配置时允许无限制的Bash访问
❌ 在CI/CD中加载用户设置 ()
❌ 未经验证就信任工具结果
❌ 硬编码文件路径(使用)
❌ 对不可信提示词使用模式
❌ 跳过工具输入的Zod验证
bypassPermissionstool_resultcanUseToolsettingSources: ["user"]workingDirectoryacceptEditsDependencies
依赖项
Required:
- - Agent SDK
@anthropic-ai/claude-agent-sdk@0.1.0+ - - Schema validation
zod@3.23.0+
Optional:
- - TypeScript types
@types/node@20.0.0+ - - MCP server development
@modelcontextprotocol/sdk@latest
System Requirements:
- Node.js 18.0.0+
- Claude Code CLI (install: )
bun add -g @anthropic-ai/claude-code - Valid ANTHROPIC_API_KEY
必填:
- - Agent SDK
@anthropic-ai/claude-agent-sdk@0.1.0+ - - Schema验证
zod@3.23.0+
可选:
- - TypeScript类型定义
@types/node@20.0.0+ - - MCP服务器开发
@modelcontextprotocol/sdk@latest
系统要求:
- Node.js 18.0.0+
- Claude Code CLI(安装命令:)
bun add -g @anthropic-ai/claude-code - 有效的ANTHROPIC_API_KEY
Official Documentation
官方文档
- Agent SDK Overview: https://docs.claude.com/en/api/agent-sdk/overview
- TypeScript API: https://docs.claude.com/en/api/agent-sdk/typescript
- Python API: https://docs.claude.com/en/api/agent-sdk/python
- Model Context Protocol: https://modelcontextprotocol.io/
- GitHub (TypeScript): https://github.com/anthropics/claude-agent-sdk-typescript
- GitHub (Python): https://github.com/anthropics/claude-agent-sdk-python
- Context7 Library ID: /anthropics/claude-agent-sdk-typescript
- Agent SDK概述: https://docs.claude.com/en/api/agent-sdk/overview
- TypeScript API: https://docs.claude.com/en/api/agent-sdk/typescript
- Python API: https://docs.claude.com/en/api/agent-sdk/python
- 模型上下文协议: https://modelcontextprotocol.io/
- GitHub(TypeScript): https://github.com/anthropics/claude-agent-sdk-typescript
- GitHub(Python): https://github.com/anthropics/claude-agent-sdk-python
- Context7库ID: /anthropics/claude-agent-sdk-typescript
Package Versions (Verified 2025-10-25)
包版本(2025-10-25验证)
json
{
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.1.0",
"zod": "^3.23.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.3.0"
}
}json
{
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.1.0",
"zod": "^3.23.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.3.0"
}
}Production Examples
生产示例
This skill is based on official Anthropic documentation and SDK patterns:
- Documentation: https://docs.claude.com/en/api/agent-sdk/
- Validation: ✅ All patterns tested with SDK 0.1.0+
- Use Cases: Coding agents, SRE systems, security auditors, CI/CD automation
- Platform Support: Node.js 18+, TypeScript 5.3+
本技能基于Anthropic官方文档和SDK模式:
- 文档来源: https://docs.claude.com/en/api/agent-sdk/
- 验证: ✅ 所有模式均通过SDK 0.1.0+测试
- 使用场景: 编码代理、SRE系统、安全审计、CI/CD自动化
- 平台支持: Node.js 18+, TypeScript 5.3+
Complete Setup Checklist
完整设置清单
- Node.js 18.0.0+ installed
- Claude Code CLI installed ()
bun add -g @anthropic-ai/claude-code - SDK installed ()
bun add @anthropic-ai/claude-agent-sdk zod - ANTHROPIC_API_KEY environment variable set
- workingDirectory set for project
- allowedTools configured (or using default)
- permissionMode chosen (default recommended)
- Error handling implemented
- Session management (if needed)
- MCP servers configured (if using custom tools)
- Subagents defined (if needed)
Questions? Issues?
- Check references/query-api-reference.md for complete API details
- Review references/mcp-servers-guide.md for custom tools
- See references/subagents-patterns.md for orchestration
- Check references/session-management.md for persistent conversations
- Review references/permissions-guide.md for security policies
- Check references/top-errors.md for common issues
- Consult official docs: https://docs.claude.com/en/api/agent-sdk/
Token Efficiency: ~65% savings vs manual Agent SDK integration (estimated)
Error Prevention: 100% (all 12 documented issues prevented)
Development Time: 30 minutes with skill vs 3-4 hours manual
- 已安装Node.js 18.0.0+
- 已安装Claude Code CLI ()
bun add -g @anthropic-ai/claude-code - 已安装SDK ()
bun add @anthropic-ai/claude-agent-sdk zod - 已设置ANTHROPIC_API_KEY环境变量
- 已为项目设置workingDirectory
- 已配置allowedTools(或使用默认值)
- 已选择permissionMode(推荐使用default)
- 已实现错误处理
- 已配置会话管理(如需)
- 已配置MCP服务器(如需使用自定义工具)
- 已定义子代理(如需)
有疑问?遇到问题?
- 查看references/query-api-reference.md获取完整API细节
- 查阅references/mcp-servers-guide.md了解自定义工具
- 参考references/subagents-patterns.md学习编排策略
- 查看references/session-management.md了解持久对话
- 查阅references/permissions-guide.md了解安全策略
- 查看references/top-errors.md了解常见问题
- 咨询官方文档: https://docs.claude.com/en/api/agent-sdk/
Token效率: 相比手动集成Agent SDK,节省约65%的Token消耗(估算值)
错误预防: 100%(所有12个已记录问题均可预防)
开发时间: 使用本技能需30分钟,手动集成需3-4小时