agent-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClaude Agent SDK - Comprehensive Skill
Claude Agent SDK - 全能技能
Overview
概述
The Claude Agent SDK is Anthropic's official framework for building production-ready AI agents with Claude. It provides a high-level abstraction over the Messages API, handling the agent loop, tool orchestration, context management, and extended-thinking patterns automatically.
Claude Agent SDK是Anthropic推出的官方框架,用于基于Claude构建可投入生产的AI Agent。它在Messages API之上提供了高层抽象,可自动处理Agent循环、工具编排、上下文管理以及扩展思维模式。
When to Use the Agent SDK
何时使用Agent SDK
Use the Agent SDK when:
- Building autonomous agents that need to use tools iteratively
- Implementing agentic workflows with verification and iteration
- Creating subagent hierarchies for complex task decomposition
- Integrating MCP (Model Context Protocol) servers for standardized tools
- Need production patterns like hooks, permissions, and context management
Don't use when:
- Simple single-turn API calls suffice (use Messages API directly)
- No tool use required (standard chat)
- Custom agent loop logic needed (SDK loop is opinionated)
推荐使用Agent SDK的场景:
- 构建需要迭代使用工具的自主Agent
- 实现包含验证与迭代流程的Agent工作流
- 创建用于复杂任务分解的子Agent层级结构
- 集成MCP(Model Context Protocol)服务器以使用标准化工具
- 需要钩子、权限控制和上下文管理等生产级模式
不推荐使用的场景:
- 简单的单轮API调用即可满足需求(直接使用Messages API)
- 无需使用工具的场景(标准聊天功能)
- 需要自定义Agent循环逻辑的场景(SDK的循环实现具有较强的主观性)
Language Support
语言支持
- Python: package (recommended for most use cases)
claude-agents - TypeScript: package (Node.js environments)
@anthropics/agent-sdk
Both implementations share the same core concepts and API patterns.
- Python:包(大多数场景推荐使用)
claude-agents - TypeScript:包(适用于Node.js环境)
@anthropics/agent-sdk
两种实现共享相同的核心概念和API模式。
Quick Start
快速开始
Installation
安装
Python:
bash
pip install claude-agentsTypeScript:
bash
npm install @anthropics/agent-sdkPython:
bash
pip install claude-agentsTypeScript:
bash
npm install @anthropics/agent-sdkAuthentication
身份验证
Set your API key as an environment variable:
bash
export ANTHROPIC_API_KEY="your-api-key-here"Or pass it explicitly in code:
python
from claude_agents import Agent
agent = Agent(api_key="your-api-key-here")将API密钥设置为环境变量:
bash
export ANTHROPIC_API_KEY="your-api-key-here"或在代码中显式传入:
python
from claude_agents import Agent
agent = Agent(api_key="your-api-key-here")Basic Agent Creation
基础Agent创建
Python Example:
python
from claude_agents import AgentPython示例:
python
from claude_agents import AgentCreate agent with default settings
使用默认设置创建Agent
agent = Agent(
model="claude-sonnet-4-5-20250929",
system="You are a helpful assistant focused on accuracy."
)
agent = Agent(
model="claude-sonnet-4-5-20250929",
system="You are a helpful assistant focused on accuracy."
)
Run simple task
运行简单任务
result = agent.run("What is 2+2?")
print(result.response)
**TypeScript Example:**
```typescript
import { Agent } from "@anthropics/agent-sdk";
const agent = new Agent({
model: "claude-sonnet-4-5-20250929",
system: "You are a helpful assistant focused on accuracy.",
});
const result = await agent.run("What is 2+2?");
console.log(result.response);result = agent.run("What is 2+2?")
print(result.response)
**TypeScript示例:**
```typescript
import { Agent } from "@anthropics/agent-sdk";
const agent = new Agent({
model: "claude-sonnet-4-5-20250929",
system: "You are a helpful assistant focused on accuracy.",
});
const result = await agent.run("What is 2+2?");
console.log(result.response);First Tool Example
首个工具示例
Tools extend agent capabilities with external functions:
Python:
python
from claude_agents import Agent
from claude_agents.tools import Tool工具可通过外部功能扩展Agent的能力:
Python:
python
from claude_agents import Agent
from claude_agents.tools import ToolDefine custom tool
定义自定义工具
def get_weather(location: str) -> dict:
"""Get weather for a location."""
return {"location": location, "temp": 72, "condition": "sunny"}
weather_tool = Tool(
name="get_weather",
description="Get current weather for a location",
input_schema={
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
},
function=get_weather
)
def get_weather(location: str) -> dict:
"""Get weather for a location."""
return {"location": location, "temp": 72, "condition": "sunny"}
weather_tool = Tool(
name="get_weather",
description="Get current weather for a location",
input_schema={
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
},
function=get_weather
)
Agent with custom tool
带有自定义工具的Agent
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[weather_tool]
)
result = agent.run("What's the weather in San Francisco?")
print(result.response)
undefinedagent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[weather_tool]
)
result = agent.run("What's the weather in San Francisco?")
print(result.response)
undefinedCore Concepts Reference
核心概念参考
The Agent Loop
Agent循环
The SDK manages a complete agent loop automatically:
- Input Processing: User message + system prompt + tools
- Model Invocation: Claude generates response (text or tool calls)
- Tool Execution: SDK executes requested tools, handles results
- Iteration: Results fed back to model, continues until completion
- Output: Final response with full conversation history
Key Properties:
- Automatic iteration until task completion or max turns
- Built-in error handling and retry logic
- Context management with automatic compaction options
- Token budget tracking and optimization
SDK会自动管理完整的Agent循环:
- 输入处理:用户消息 + 系统提示词 + 工具
- 模型调用:Claude生成响应(文本或工具调用指令)
- 工具执行:SDK执行请求的工具,处理结果
- 迭代:将结果反馈给模型,持续循环直到任务完成
- 输出:包含完整对话历史的最终响应
关键特性:
- 自动迭代直到任务完成或达到最大轮次限制
- 内置错误处理与重试逻辑
- 带有自动压缩选项的上下文管理
- Token预算跟踪与优化
Context Management
上下文管理
The SDK manages conversation context automatically:
Context Components:
- System prompt (persistent instructions)
- Conversation history (user messages + assistant responses)
- Tool definitions (available capabilities)
- Tool results (execution outputs)
Subagents for Context Isolation:
python
undefinedSDK会自动管理对话上下文:
上下文组件:
- 系统提示词(持久化指令)
- 对话历史(用户消息 + 助手响应)
- 工具定义(可用能力)
- 工具执行结果(输出内容)
Spawn subagent with isolated context
子Agent实现上下文隔离
with agent.subagent(
system="You are a code reviewer focused on security.",
tools=[security_scan_tool]
) as reviewer:
review = reviewer.run("Review this code for vulnerabilities: ...")
python
undefinedSubagent context doesn't pollute parent
生成具有隔离上下文的子Agent
**Context Compaction:**
When approaching token limits, the SDK can automatically summarize earlier conversation turns while preserving critical information.with agent.subagent(
system="You are a code reviewer focused on security.",
tools=[security_scan_tool]
) as reviewer:
review = reviewer.run("Review this code for vulnerabilities: ...")
Tools System
子Agent的上下文不会污染父Agent
Tools are the agent's interface to external capabilities.
Built-in Tools:
- : Execute shell commands
bash - : Read file contents
read_file - : Write data to files
write_file - : Modify existing files
edit_file - : File pattern matching
glob - : Content search
grep
Custom Tool Schema:
python
Tool(
name="tool_name", # Unique identifier
description="What it does", # Clear capability description
input_schema={ # JSON Schema for parameters
"type": "object",
"properties": {...},
"required": [...]
},
function=callable # Python function or async function
)MCP Integration:
The SDK can use Model Context Protocol (MCP) servers as tool providers:
python
from claude_agents import Agent
from claude_agents.mcp import MCPClient
**上下文压缩:**
当接近Token限制时,SDK可自动总结早期对话轮次,同时保留关键信息。Connect to MCP server
工具系统
mcp_client = MCPClient("npx", ["-y", "@modelcontextprotocol/server-filesystem"])
agent = Agent(
model="claude-sonnet-4-5-20250929",
mcp_clients=[mcp_client]
)
undefined工具是Agent与外部能力交互的接口。
内置工具:
- :执行Shell命令
bash - :读取文件内容
read_file - :写入数据到文件
write_file - :修改现有文件
edit_file - :文件模式匹配
glob - :内容搜索
grep
自定义工具 Schema:
python
Tool(
name="tool_name", # 唯一标识符
description="What it does", # 清晰的能力描述
input_schema={ # 参数的JSON Schema
"type": "object",
"properties": {...},
"required": [...]
},
function=callable # Python函数或异步函数
)MCP集成:
SDK可将Model Context Protocol(MCP)服务器作为工具提供者:
python
from claude_agents import Agent
from claude_agents.mcp import MCPClientPermissions System
连接到MCP服务器
Control which tools agents can access:
Allowed Tools (Whitelist):
python
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[tool1, tool2, tool3, tool4],
allowed_tools=["tool1", "tool2"] # Only these can be used
)Disallowed Tools (Blacklist):
python
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[tool1, tool2, tool3],
disallowed_tools=["tool3"] # All except tool3
)Permission Modes:
- : Agent MUST get permission before tool use (via hooks)
"strict" - : Agent can use allowed tools freely (default)
"permissive"
mcp_client = MCPClient("npx", ["-y", "@modelcontextprotocol/server-filesystem"])
agent = Agent(
model="claude-sonnet-4-5-20250929",
mcp_clients=[mcp_client]
)
undefinedHooks System
权限系统
Hooks provide lifecycle event interception for observability, validation, and control.
Available Hooks:
- : Before tool execution (validation, logging, blocking)
PreToolUseHook - : After tool execution (logging, result modification)
PostToolUseHook - : Before subagent spawns (context setup)
PreSubagentStartHook - : After subagent completes (result processing)
PostSubagentStopHook
Basic Hook Example:
python
from claude_agents.hooks import PreToolUseHook
class LoggingHook(PreToolUseHook):
async def execute(self, context):
print(f"Tool: {context.tool_name}")
print(f"Args: {context.tool_input}")
return context # Allow execution
agent = Agent(
model="claude-sonnet-4-5-20250929",
hooks=[LoggingHook()]
)Blocking Tool Use:
python
class ValidationHook(PreToolUseHook):
async def execute(self, context):
if context.tool_name == "bash" and "rm -rf" in context.tool_input.get("command", ""):
raise PermissionError("Destructive command blocked")
return context控制Agent可访问的工具:
允许的工具(白名单):
python
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[tool1, tool2, tool3, tool4],
allowed_tools=["tool1", "tool2"] # 仅可使用这些工具
)禁止的工具(黑名单):
python
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[tool1, tool2, tool3],
disallowed_tools=["tool3"] # 除tool3外均可使用
)权限模式:
- :Agent在使用工具前必须获得权限(通过钩子实现)
"strict" - :Agent可自由使用允许的工具(默认模式)
"permissive"
Common Patterns
钩子系统
File Operations
—
python
from claude_agents import Agent
agent = Agent(
model="claude-sonnet-4-5-20250929",
allowed_tools=["read_file", "write_file", "glob"]
)
result = agent.run(
"Read all Python files in ./src and create a summary in summary.md"
)钩子提供生命周期事件拦截功能,用于可观测性、验证和控制。
可用钩子:
- :工具执行前(验证、日志记录、拦截)
PreToolUseHook - :工具执行后(日志记录、结果修改)
PostToolUseHook - :子Agent生成前(上下文设置)
PreSubagentStartHook - :子Agent完成后(结果处理)
PostSubagentStopHook
基础钩子示例:
python
from claude_agents.hooks import PreToolUseHook
class LoggingHook(PreToolUseHook):
async def execute(self, context):
print(f"Tool: {context.tool_name}")
print(f"Args: {context.tool_input}")
return context # 允许执行
agent = Agent(
model="claude-sonnet-4-5-20250929",
hooks=[LoggingHook()]
)拦截工具使用:
python
class ValidationHook(PreToolUseHook):
async def execute(self, context):
if context.tool_name == "bash" and "rm -rf" in context.tool_input.get("command", ""):
raise PermissionError("Destructive command blocked")
return contextCode Execution
常见模式
—
文件操作
python
agent = Agent(
model="claude-sonnet-4-5-20250929",
allowed_tools=["bash"]
)
result = agent.run(
"Run the test suite and analyze any failures"
)python
from claude_agents import Agent
agent = Agent(
model="claude-sonnet-4-5-20250929",
allowed_tools=["read_file", "write_file", "glob"]
)
result = agent.run(
"Read all Python files in ./src and create a summary in summary.md"
)Agentic Search (Gather-Act Pattern)
代码执行
python
undefinedpython
agent = Agent(
model="claude-sonnet-4-5-20250929",
allowed_tools=["bash"]
)
result = agent.run(
"Run the test suite and analyze any failures"
)Agent automatically gathers information iteratively
Agent式搜索(收集-执行模式)
search_agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[web_search_tool, read_url_tool]
)
result = search_agent.run(
"Research the latest developments in quantum computing and summarize key papers"
)
undefinedpython
undefinedSubagent Delegation
Agent会自动迭代收集信息
python
main_agent = Agent(model="claude-sonnet-4-5-20250929")search_agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[web_search_tool, read_url_tool]
)
result = search_agent.run(
"Research the latest developments in quantum computing and summarize key papers"
)
undefinedDelegate specialized task to subagent
子Agent委托
with main_agent.subagent(
system="You are an expert data analyzer.",
tools=[analyze_csv_tool, plot_tool]
) as analyzer:
analysis = analyzer.run("Analyze sales_data.csv and create visualizations")
python
main_agent = Agent(model="claude-sonnet-4-5-20250929")Results available to main agent
将专业任务委托给子Agent
main_agent.run(f"Based on this analysis: {analysis.response}, what actions should we take?")
undefinedwith main_agent.subagent(
system="You are an expert data analyzer.",
tools=[analyze_csv_tool, plot_tool]
) as analyzer:
analysis = analyzer.run("Analyze sales_data.csv and create visualizations")
Error Handling
结果可被主Agent使用
python
from claude_agents import Agent, AgentError
agent = Agent(model="claude-sonnet-4-5-20250929")
try:
result = agent.run("Your task here", max_turns=10)
except AgentError as e:
print(f"Agent failed: {e}")
print(f"Turns completed: {e.turns_completed}")
print(f"Last message: {e.last_message}")main_agent.run(f"Based on this analysis: {analysis.response}, what actions should we take?")
undefinedVerification Pattern
错误处理
python
undefinedpython
from claude_agents import Agent, AgentError
agent = Agent(model="claude-sonnet-4-5-20250929")
try:
result = agent.run("Your task here", max_turns=10)
except AgentError as e:
print(f"Agent failed: {e}")
print(f"Turns completed: {e.turns_completed}")
print(f"Last message: {e.last_message}")Agent can self-verify results
验证模式
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[calculator_tool, verify_tool]
)
result = agent.run(
"Calculate the compound interest for $10000 at 5% for 10 years. "
"Verify your calculation by computing it a second way."
)
undefinedpython
undefinedNavigation Guide
Agent可自我验证结果
When to Read Supporting Files
—
reference.md - Read when you need:
- Deep understanding of agent loop internals
- Complete API reference for all SDK features
- Detailed tool schema specifications
- Permission and security configuration options
- Comprehensive hooks reference with all event types
- Skills system implementation details
examples.md - Read when you need:
- Working code examples for specific patterns
- Tool implementation templates
- Hook implementation examples
- Advanced patterns (subagents, verification, error recovery)
- Integration examples with existing systems
patterns.md - Read when you need:
- Production-ready architectural patterns
- Agent loop optimization strategies (Gather, Act, Verify, Iterate)
- Context management best practices
- Tool design principles
- Security patterns and anti-patterns
- Performance optimization techniques
drift-detection.md - Read when you need:
- Understanding how this skill stays current
- Implementing drift detection for other skills
- Update workflow and validation processes
- Self-validation mechanisms
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[calculator_tool, verify_tool]
)
result = agent.run(
"Calculate the compound interest for $10000 at 5% for 10 years. "
"Verify your calculation by computing it a second way."
)
undefinedIntegration with Amplihack
导航指南
—
何时阅读配套文件
The Agent SDK skill integrates with the Amplihack framework:
Creating Amplihack Agents with SDK:
python
undefinedreference.md - 当你需要以下内容时阅读:
- 深入理解Agent循环的内部机制
- 所有SDK功能的完整API参考
- 详细的工具Schema规范
- 权限与安全配置选项
- 包含所有事件类型的全面钩子参考
- 技能系统的实现细节
examples.md - 当你需要以下内容时阅读:
- 针对特定模式的可运行代码示例
- 工具实现模板
- 钩子实现示例
- 高级模式(子Agent、验证、错误恢复)
- 与现有系统的集成示例
patterns.md - 当你需要以下内容时阅读:
- 可投入生产的架构模式
- Agent循环优化策略(收集、执行、验证、迭代)
- 上下文管理最佳实践
- 工具设计原则
- 安全模式与反模式
- 性能优化技巧
drift-detection.md - 当你需要以下内容时阅读:
- 了解本技能如何保持时效性
- 为其他技能实现漂移检测
- 更新工作流与验证流程
- 自我验证机制
In .claude/agents/amplihack/specialized/my_agent.md
与Amplihack集成
Use Agent SDK patterns for tool-using agents
—
from claude_agents import Agent
from claude_agents.tools import Tool
def create_specialized_agent():
return Agent(
model="claude-sonnet-4-5-20250929",
system="<agent_role_from_md>",
tools=[...], # Custom tools for this agent
hooks=[...] # Logging, validation hooks
)
**Using MCP Servers in Amplihack:**
```pythonAgent SDK技能可与Amplihack框架集成:
使用SDK创建Amplihack Agent:
python
undefinedIntegrate MCP tools into Amplihack workflow
In .claude/agents/amplihack/specialized/my_agent.md
—
针对使用工具的Agent采用Agent SDK模式
from claude_agents.mcp import MCPClient
mcp_client = MCPClient("npx", ["-y", "@modelcontextprotocol/server-github"])
agent = Agent(
model="claude-sonnet-4-5-20250929",
mcp_clients=[mcp_client]
)
from claude_agents import Agent
from claude_agents.tools import Tool
def create_specialized_agent():
return Agent(
model="claude-sonnet-4-5-20250929",
system="<agent_role_from_md>",
tools=[...], # 该Agent的自定义工具
hooks=[...] # 日志、验证钩子
)
**在Amplihack中使用MCP服务器:**
```pythonAgent can now use GitHub MCP tools
将MCP工具集成到Amplihack工作流
result = agent.run("Create a GitHub issue for the bug we just found")
**Hooks for Amplihack Observability:**
```pythonfrom claude_agents.mcp import MCPClient
mcp_client = MCPClient("npx", ["-y", "@modelcontextprotocol/server-github"])
agent = Agent(
model="claude-sonnet-4-5-20250929",
mcp_clients=[mcp_client]
)
Log all agent actions to Amplihack runtime logs
Agent现在可使用GitHub MCP工具
class AmplihackLoggingHook(PreToolUseHook):
async def execute(self, context):
log_to_amplihack_runtime(
session_id=get_current_session(),
tool=context.tool_name,
input=context.tool_input
)
return context
undefinedresult = agent.run("Create a GitHub issue for the bug we just found")
**用于Amplihack可观测性的钩子:**
```pythonQuick Reference
将所有Agent操作记录到Amplihack运行时日志
Essential Commands
—
python
undefinedclass AmplihackLoggingHook(PreToolUseHook):
async def execute(self, context):
log_to_amplihack_runtime(
session_id=get_current_session(),
tool=context.tool_name,
input=context.tool_input
)
return context
undefinedBasic agent
快速参考
—
核心命令
agent = Agent(model="claude-sonnet-4-5-20250929")
result = agent.run("task")
python
undefinedWith tools
基础Agent
agent = Agent(model="...", tools=[tool1, tool2])
agent = Agent(model="claude-sonnet-4-5-20250929")
result = agent.run("task")
With permissions
带有工具的Agent
agent = Agent(model="...", allowed_tools=["tool1"])
agent = Agent(model="...", tools=[tool1, tool2])
With hooks
带有权限控制的Agent
agent = Agent(model="...", hooks=[LogHook()])
agent = Agent(model="...", allowed_tools=["tool1"])
Subagent
带有钩子的Agent
with agent.subagent(system="...") as sub:
result = sub.run("subtask")
agent = Agent(model="...", hooks=[LogHook()])
MCP integration
子Agent
from claude_agents.mcp import MCPClient
mcp = MCPClient("npx", ["-y", "mcp-server-name"])
agent = Agent(model="...", mcp_clients=[mcp])
undefinedwith agent.subagent(system="...") as sub:
result = sub.run("subtask")
Common Tool Patterns
MCP集成
python
undefinedfrom claude_agents.mcp import MCPClient
mcp = MCPClient("npx", ["-y", "mcp-server-name"])
agent = Agent(model="...", mcp_clients=[mcp])
undefinedFile operations
常见工具模式
tools=["read_file", "write_file", "glob"]
python
undefinedCode execution
文件操作
tools=["bash"]
tools=["read_file", "write_file", "glob"]
All built-in
代码执行
tools=["bash", "read_file", "write_file", "edit_file", "glob", "grep"]
undefinedtools=["bash"]
Token Budget Recommendations
所有内置工具
- Simple tasks: 4K-8K tokens
- Complex tasks: 16K-32K tokens
- Research/analysis: 64K-128K tokens
- Maximum context: 200K tokens (model dependent)
tools=["bash", "read_file", "write_file", "edit_file", "glob", "grep"]
undefinedNext Steps
Token预算建议
- Start Simple: Create a basic agent with built-in tools
- Add Custom Tools: Implement tools for your specific domain
- Add Hooks: Implement logging and validation
- Use Subagents: Delegate specialized tasks
- Integrate MCP: Use standardized tool servers
- Optimize: Tune context, permissions, and verification patterns
For complete API details, see .
For working code, see .
For production patterns, see .
reference.mdexamples.mdpatterns.md- 简单任务:4K-8K Token
- 复杂任务:16K-32K Token
- 研究/分析任务:64K-128K Token
- 最大上下文:200K Token(取决于模型)
—
下一步行动
—
- 从简开始:使用内置工具创建基础Agent
- 添加自定义工具:针对你的特定领域实现工具
- 添加钩子:实现日志记录与验证功能
- 使用子Agent:将专业任务委托给子Agent
- 集成MCP:使用标准化工具服务器
- 优化:调整上下文、权限与验证模式
如需完整API细节,请查看。
如需可运行代码,请查看。
如需生产级模式,请查看。
reference.mdexamples.mdpatterns.md