mcpField
C
claude-agent-sdk

claude-agent-sdk

github.com/rysweetAgent 工作流76124 次安装22 周前更新
代码仓库

关于 claude-agent-sdk

Anthropic 的 Claude Agent SDK 使用指南,面向构建工具驱动型 AI Agent 的开发者,介绍 Python 和 TypeScript 用法。它涵盖 Agent 循环、上下文管理、子 Agent、权限、钩子及 MCP 集成。

主要功能

  1. 01自动管理 Agent 循环与工具调用
  2. 02支持 Python 和 TypeScript
  3. 03管理对话上下文与压缩
  4. 04创建隔离上下文的子 Agent
  5. 05通过权限和钩子控制工具
  6. 06集成 MCP 服务端

适用场景

  1. 01构建迭代调用工具的 Agent
  2. 02将复杂任务委派给子 Agent
  3. 03为工具执行添加校验与日志
  4. 04将 MCP 工具接入 Agent 工作流

MCP 相关

SDK 可连接 MCP 服务端,并将其作为 Agent 的工具提供方。指南展示了通过 MCPClient 配置连接的方式。

安装

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

$npx skills add https://github.com/rysweet/amplihack --skill claude-agent-sdk

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

包含的文件

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

README.md
VALIDATION_REPORT.md
drift-detection.md
examples.md
patterns.md
reference.md
scripts/
check_drift.py

详细介绍

Claude Agent SDK - 综合指南

概述

Claude Agent SDK 是 Anthropic 官方推出的框架,用于构建基于 Claude 的生产级 AI Agent。它在 Messages API 之上提供了高级抽象层,可自动处理 Agent 循环、工具编排、上下文管理和扩展思考模式。

何时使用 Agent SDK

以下情况适合使用 Agent SDK:

  • 构建需要反复使用工具的自主 Agent
  • 实现包含验证和迭代的 Agent 工作流
  • 为复杂任务分解创建子 Agent 层级
  • 集成 MCP(Model Context Protocol)服务,以使用标准化工具
  • 需要钩子、权限和上下文管理等生产级模式

以下情况不适合使用:

  • 简单的单轮 API 调用即可满足需求(直接使用 Messages API)
  • 无需使用工具(标准聊天)
  • 需要自定义 Agent 循环逻辑(SDK 的循环机制有其特定设计)
语言支持
  • Python:claude-agents 包(推荐用于大多数场景)
  • TypeScript:@anthropics/agent-sdk 包(Node.js 环境)

两种实现共享相同的核心概念和 API 模式。

快速入门

安装

Python:

pip install claude-agents

TypeScript:

npm install @anthropics/agent-sdk
身份验证

将 API 密钥设置为环境变量:

export ANTHROPIC_API_KEY="your-api-key-here"  # pragma: allowlist secret

也可以在代码中显式传入:

from claude_agents import Agent

agent = Agent(api_key="your-api-key-here")
创建基础 Agent

Python 示例:

from claude_agents import Agent

# Create agent with default settings
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 示例:

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);
第一个工具示例

工具通过外部函数扩展 Agent 的能力:

Python:

from claude_agents import Agent
from claude_agents.tools import Tool

# Define 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
)

# Agent with custom tool
agent = Agent(
    model="claude-sonnet-4-5-20250929",
    tools=[weather_tool]
)

result = agent.run("What's the weather in San Francisco?")
print(result.response)

核心概念参考

Agent 循环

SDK 会自动管理完整的 Agent 循环:

  1. 输入处理:用户消息 + 系统提示词 + 工具
  2. 模型调用:Claude 生成响应(文本或工具调用)
  3. 工具执行:SDK 执行请求的工具并处理结果
  4. 迭代:将结果反馈给模型,持续运行直至完成
  5. 输出:包含完整对话历史的最终响应

主要特性:

  • 自动迭代,直至任务完成或达到最大轮数
  • 内置错误处理和重试逻辑
  • 上下文管理,支持自动压缩选项
  • 跟踪和优化令牌预算
上下文管理

SDK 会自动管理对话上下文:

上下文组件:

  • 系统提示词(持久指令)
  • 对话历史(用户消息 + 助手响应)
  • 工具定义(可用能力)
  • 工具结果(执行输出)

用于隔离上下文的子 Agent:

# Spawn subagent with isolated context
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: ...")

# Subagent context doesn't pollute parent

上下文压缩: 接近令牌限制时,SDK 可以自动总结较早的对话轮次,同时保留关键信息。

工具系统

工具是 Agent 连接外部能力的接口。

内置工具:

  • bash:执行 shell 命令
  • read_file:读取文件内容
  • write_file:将数据写入文件
  • edit_file:修改现有文件
  • glob:按文件模式匹配文件
  • grep:搜索内容

自定义工具架构:

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 集成: SDK 可以使用 Model Context Protocol(MCP)服务作为工具提供方:

from claude_agents import Agent
from claude_agents.mcp import MCPClient

# Connect to MCP server
mcp_client = MCPClient("npx", ["-y", "@modelcontextprotocol/server-filesystem"])

agent = Agent(
    model="claude-sonnet-4-5-20250929",
    mcp_clients=[mcp_client]
)
权限系统

控制 Agent 可以访问哪些工具:

允许的工具(白名单):

agent = Agent(
    model="claude-sonnet-4-5-20250929",
    tools=[tool1, tool2, tool3, tool4],
    allowed_tools=["tool1", "tool2"]  # Only these can be used
)

禁止的工具(黑名单):

agent = Agent(
    model="claude-sonnet-4-5-20250929",
    tools=[tool1, tool2, tool3],
    disallowed_tools=["tool3"]  # All except tool3
)

权限模式:

  • "strict":Agent 使用工具前必须获得许可(通过钩子)
  • "permissive":Agent 可自由使用获准的工具(默认)
钩子系统

钩子可拦截生命周期事件,用于可观测性、验证和控制。

可用钩子:

  • PreToolUseHook:工具执行前(验证、日志记录、拦截)
  • PostToolUseHook:工具执行后(日志记录、结果修改)
  • PreSubagentStartHook:子 Agent 启动前(上下文设置)
  • PostSubagentStopHook:子 Agent 完成后(结果处理)

基础钩子示例:

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()]
)

拦截工具使用:

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

常见模式

文件操作
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"
)
代码执行
agent = Agent(
    model="claude-sonnet-4-5-20250929",
    allowed_tools=["bash"]
)

result = agent.run(
    "Run the test suite and analyze any failures"
)
Agentic 搜索(Gather-Act 模式)
# Agent automatically gathers information iteratively
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"
)
子 Agent 委派
main_agent = Agent(model="claude-sonnet-4-5-20250929")

# Delegate specialized task to subagent
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")

# Results available to main agent
main_agent.run(f"Based on this analysis: {analysis.response}, what actions should we take?")
错误处理
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."
)

导航指南

何时阅读辅助文件

reference.md - 在以下情况下阅读:

  • 深入了解 Agent 循环的内部机制
  • 查阅所有 SDK 功能的完整 API 参考
  • 了解详细的工具架构规范
  • 了解权限和安全配置选项
  • 查阅包含所有事件类型的完整钩子参考
  • 了解技能系统的实现细节

examples.md - 在以下情况下阅读:

  • 查找特定模式的可运行代码示例
  • 查找工具实现模板
  • 查找钩子实现示例
  • 了解高级模式(子 Agent、验证、错误恢复)
  • 查找与现有系统的集成示例

patterns.md - 在以下情况下阅读:

  • 了解适用于生产环境的架构模式
  • 了解 Agent 循环优化策略(Gather、Act、Verify、Iterate)
  • 了解上下文管理最佳实践
  • 了解工具设计原则
  • 了解安全模式和反模式
  • 了解性能优化技术

drift-detection.md - 在以下情况下阅读:

  • 了解此技能如何保持最新
  • 为其他技能实现漂移检测
  • 了解更新工作流和验证流程
  • 了解自验证机制
与 Amplihack 集成

Agent SDK 技能与 Amplihack 框架集成:

使用 SDK 创建 Amplihack Agent:

# In .claude/agents/amplihack/specialized/my_agent.md
# 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
    )

在 Amplihack 中使用 MCP 服务:

# Integrate MCP tools into Amplihack workflow
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]
)

# Agent can now use GitHub MCP tools
result = agent.run("Create a GitHub issue for the bug we just found")

用于 Amplihack 可观测性的钩子:

# Log all agent actions to Amplihack runtime logs
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

快速参考

常用命令
# Basic agent
agent = Agent(model="claude-sonnet-4-5-20250929")
result = agent.run("task")

# With tools
agent = Agent(model="...", tools=[tool1, tool2])

# With permissions
agent = Agent(model="...", allowed_tools=["tool1"])

# With hooks
agent = Agent(model="...", hooks=[LogHook()])

# Subagent
with agent.subagent(system="...") as sub:
    result = sub.run("subtask")

# MCP integration
from claude_agents.mcp import MCPClient
mcp = MCPClient("npx", ["-y", "mcp-server-name"])
agent = Agent(model="...", mcp_clients=[mcp])
常见工具模式
# File operations
tools=["read_file", "write_file", "glob"]

# Code execution
tools=["bash"]

# All built-in
tools=["bash", "read_file", "write_file", "edit_file", "glob", "grep"]
Token 预算建议
  • 简单任务:4K-8K 个 token
  • 复杂任务:16K-32K 个 token
  • 研究/分析:64K-128K 个 token
  • 最大上下文:200K 个 token(取决于模型)

后续步骤

  1. 从简单开始:使用内置工具创建基础 Agent
  2. 添加自定义工具:为特定领域实现工具
  3. 添加钩子:实现日志记录和验证
  4. 使用子 Agent:委派专业任务
  5. 集成 MCP:使用标准化的工具服务
  6. 优化:调整上下文、权限和验证模式

完整的 API 详情请参阅 reference.md。 可运行的代码请参阅 examples.md。 生产环境模式请参阅 patterns.md。

评论

支持 Markdown