Claude代理工具包
统一平台架构的Claude Code Agent框架
一个完整的平台,用于构建、管理和运行Claude Code agents。提供统一配置、依赖池管理、模型抽象、沙箱执行和事件观测等企业级功能。
🚀 快速开始 - 完整流程
1. 安装依赖
pip install claude-agent-toolkit2. 创建配置文件
# config.yaml
meta:
environment: dev
version: 1
logging:
level: INFO
forward_events: true
model_providers:
openrouter_primary:
type: openrouter
api_key: ${OPENROUTER_KEY}
base_url: https://openrouter.ai/api/v1
pricing:
input_token_usd: 0.0000015
output_token_usd: 0.000002
agents:
code_analyzer:
model_provider: openrouter_primary
dependency_pools: [filesystem_pool]
dependency_pools:
filesystem_pool:
type: filesystem
paths: [/tmp, /workspace]3. 设置环境变量
export OPENROUTER_KEY="your_api_key_here"4. 运行完整流程演示
python full_flow_example.py这个演示展示了完整的系统功能:配置加载、依赖池管理、沙箱执行和事件观测。
📖 详细文档
______________________________________________________________________
claude代码sdk包装器,使用Docker轻松设置和运行时隔离,增强开发人员体验
一个Python框架,封装了claude代码sdk,通过基于装饰器的工具、运行时隔离和简化的代理开发提供更好的开发人员体验。Docker容器专为生产安全而构建,可确保在所有环境中受控的工具执行和一致的行为。
目录
为什么选择Claude Agent Toolkit?
问题
直接使用claude代码sdk会带来两大挑战:
- 复杂工具集成 -手动MCP服务器设置、连接处理和工具注册
- 运行时安全 -需要在干净、隔离的环境中控制工具的执行
解决方案
Claude Agent Toolkit通过以下方式解决了这些问题:
- 🎯 基于装饰器的工具 -简单
@tooldecorator将任何Python函数转换为与Claude兼容的工具 - 🐳 运行时隔离 -Docker容器仅使用您指定的工具提供安全、受控的执行
- ⚡ 零配置 -自动MCP服务器管理和工具发现
*“类似于谷歌ADK的直观稳定的开发体验”*
看出差异
之前(直接claude代码sdk):
# Manual tool naming and complex schema definition required
@tool("greet", "Greet a user", {"name": str})
async def greet_user(args):
return {
"content": [
{"type": "text", "text": f"Hello, {args['name']}!"}
]
}
# Tool functions and MCP server are decoupled - difficult to maintain at scale
server = create_sdk_mcp_server(
name="my-tools",
version="1.0.0",
tools=[greet_user]
)
# At Runtime:
# ❌ Subprocess can access system tools (Read, LS, Grep)
# ❌ Manual environment configuration required
# ❌ No control over Claude Code's tool access
# ❌ Risk of unintended system interactions之后(Claude Agent Toolkit):
# Intuitive class-based tool definition with integrated MCP server
class CalculatorTool(BaseTool):
@tool()
async def add(self, a: float, b: float) -> dict:
"""Adds two numbers together"""
return {"result": a + b}
# Single line agent creation with controlled tool access
agent = Agent(tools=[CalculatorTool()])
# At Runtime:
# ✅ Docker container runs only your defined tools
# ✅ No access to system tools (Read, LS, Grep)
# ✅ Clean, isolated, predictable execution environment
# ✅ Complete control over Claude Code's capabilities对比表
| 功能 | 克劳德代码sdk | 克劳德代理工具包 |
|---|---|---|
| 自定义工具 | 手动模式定义,不支持并行执行 | 简单直观的基于类的定义 @tool 装饰器,内置并行执行 parallel=True |
| 运行时隔离 | 无内置隔离 | |
| 默认情况下,你需要设计自己的 | Docker | |
| 仅允许您明确添加的工具 | ||
| 环境一致性 | 手动环境设置 | |
| 需要明确的工具/选项配置 | 需要零设置 | |
| 开箱即用 | ||
| 设置复杂性 | 约20行仅用于ClaudeCodeOptions配置 | 约25行用于带计算器的完整代理 |
Agent.run(verbose=True) 显示所有响应 | ||
| 内置工具 | 从头开始构建所有内容 | 具有权限控制的FileSystemTool |
| 用于格式化输出处理的DataTransferTool | ||
| 最适合 | 按原样使用Claude代码 | |
| 仅需最小依赖 | 快速开发 | |
| 使用Claude Code作为推理引擎(如LangGraph代理) |
快速开始
from claude_agent_toolkit import Agent, BaseTool, tool
# 1. Create a custom tool with @tool decorator
class CalculatorTool(BaseTool):
@tool()
async def add(self, a: float, b: float) -> dict:
"""Adds two numbers together"""
result = a + b
return {
"operation": f"{a} + {b}",
"result": result,
"message": f"The result of adding {a} and {b} is {result}"
}
# 2. Create and run an agent
async def main():
agent = Agent(
system_prompt="You are a helpful calculator assistant",
tools=[CalculatorTool()],
model="sonnet" # haiku, sonnet, or opus
)
result = await agent.run("What is 15 + 27?")
print(result) # Claude will use your tool and return the answer
if __name__ == "__main__":
import asyncio
asyncio.run(main())安装和设置
先决条件
- Python 3.12+ 随着
uv包管理器 - Docker 桌面版 (Docker executor需要,推荐)
- 克劳德代码OAuth令牌 -从 克劳德代码
安装软件包
# Using pip
pip install claude-agent-toolkit
# Using uv (recommended)
uv add claude-agent-toolkit
# Using poetry
poetry add claude-agent-toolkit设置您的OAuth令牌
通过运行获取令牌 claude setup-token 在您的终端中,然后:
export CLAUDE_CODE_OAUTH_TOKEN='your-token-here'快速验证
# Clone examples (optional)
git clone https://github.com/yuping322/claude-agent-toolkit.git
cd claude-agent-toolkit/src/examples/calculator
python main.py用法示例
带有自定义工具的基本代理
from claude_agent_toolkit import Agent, BaseTool, tool, ExecutorType
class MyTool(BaseTool):
def __init__(self):
super().__init__()
self.counter = 0 # Explicit data management
@tool()
async def increment(self) -> dict:
"""Increment counter and return value"""
self.counter += 1
return {"value": self.counter}
# Docker executor (default, production-ready)
agent = Agent(tools=[MyTool()])
# Subprocess executor (faster startup, development)
agent = Agent(tools=[MyTool()], executor=ExecutorType.SUBPROCESS)
result = await agent.run("Increment the counter twice")模型选择
# Fast and efficient for simple tasks
weather_agent = Agent(
tools=[weather_tool],
model="haiku"
)
# Balanced performance (default)
general_agent = Agent(
tools=[calc_tool, weather_tool],
model="sonnet"
)
# Most capable for complex reasoning
analysis_agent = Agent(
tools=[analysis_tool],
model="opus"
)
# Override per query
result = await weather_agent.run(
"Complex weather pattern analysis",
model="opus"
)CPU密集型操作
class HeavyComputeTool(BaseTool):
@tool(parallel=True, timeout_s=120)
def process_data(self, data: str) -> dict:
"""Heavy computation"""
# Sync function - runs in separate process
import time
time.sleep(5) # Simulate heavy work
return {"processed": f"result_{data}"}错误处理
from claude_agent_toolkit import (
Agent, BaseTool,
ConfigurationError, ConnectionError, ExecutionError
)
try:
agent = Agent(tools=[MyTool()])
result = await agent.run("Process my request")
except ConfigurationError as e:
print(f"Setup issue: {e}") # Missing token, invalid config
except ConnectionError as e:
print(f"Connection failed: {e}") # Docker, network issues
except ExecutionError as e:
print(f"Execution failed: {e}") # Tool failures, timeouts核心功能
- 🎯 基于装饰器的工具 -使用简单的工具将任何Python函数转换为Claude工具
@tool装饰器 - 🔌 外部MCP集成 -通过stdio和HTTP传输连接到现有的MCP服务器
- 🐳 独立执行 -Docker容器确保所有环境中的行为一致
- ⚡ 零配置 -自动MCP服务器管理、端口选择和工具发现
- 🔧 灵活的执行模式 -选择Docker隔离(生产)或子流程(开发)
- 📝 显式数据管理 -您无需隐藏状态即可控制数据持久性
- ⚙️ CPU受限操作 -用于并行处理的繁重计算的进程池
- 🎭 多工具协调 -Claude Code智能地编排多个工具
- 🏗️ 生产就绪 -专为可扩展、可靠的代理部署而构建
建筑
执行模式
| 特性 | Docker(默认) | 子进程 |
|---|---|---|
| 隔离 | 全容器隔离 | 仅用于进程隔离 |
| 设置时间 | 约3秒 | 约0.5秒 |
| 用例 | 生产、测试 | 开发、CI/CD |
| 需求 | Docker桌面 | 无 |
组件概述
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Your Tools │ │ Agent │ │ Claude Code │
│ (MCP Servers) │◄──►│ (Orchestrator) │◄──►│ (Reasoning) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Host Process │ │ Docker Container │ │ Claude Code API │
│ (localhost) │ │ or Subprocess │ │ (claude.ai) │
└─────────────────┘ └──────────────────┘ └─────────────────┘外部MCP服务器集成
连接到现有MCP服务器
使用stdio或HTTP传输与任何现有的MCP服务器集成:
from claude_agent_toolkit import Agent
from claude_agent_toolkit.tool.mcp import StdioMCPTool, HttpMCPTool
# Connect to an MCP server via command execution
everything_server = StdioMCPTool(
command="npx",
args=["-y", "@modelcontextprotocol/server-everything"],
name="everything"
)
# Connect to an HTTP MCP server
http_server = HttpMCPTool(
url="http://localhost:3001/mcp",
name="my-http-server"
)
# Mix with your custom tools
agent = Agent(
system_prompt="You can use both custom and external tools",
tools=[MyCustomTool(), everything_server, http_server]
)
result = await agent.run("Use the everything server to echo 'Hello World'")何时使用外部MCP集成
- 现有MCP生态系统:利用社区MCP服务器和工具
- 语言多样性:使用用Node.js、Python、Go等编写的MCP服务器。
- 专用工具:集成特定领域的工具,无需重新实现
- 快速原型制作:在构建自定义等效服务器之前,快速测试MCP服务器
- 服务体系结构:连接到作为微服务运行的MCP服务器
支持的交通工具
| 运输 | 用例 | 示例 |
|---|---|---|
| 工作室 | 命令行工具、npm包 | npx 服务器、Python脚本 |
| 超文本传输协议 | Web服务、微服务 | REST API、容器化服务器 |
内置工具
FileSystemTool-安全文件操作
精确控制您的代理可以使用基于模式的权限访问哪些文件。
from claude_agent_toolkit.tools import FileSystemTool
# Define access patterns
permissions = [
("*.txt", "read"), # Read all text files
("data/**", "write"), # Write to data directory
("logs/*.log", "read"), # Read log files only
]
fs_tool = FileSystemTool(
permissions=permissions,
root_dir="/path/to/workspace" # Restrict to directory
)
agent = Agent(
system_prompt="You are a file manager assistant",
tools=[fs_tool]
)
result = await agent.run(
"List all text files and create a summary in data/report.txt"
)数据传输工具-类型安全数据传输
使用Pydantic模型在Claude代理和应用程序之间传输结构化数据。
from claude_agent_toolkit.tools import DataTransferTool
from pydantic import BaseModel, Field
from typing import List
class UserProfile(BaseModel):
name: str = Field(..., description="Full name")
age: int = Field(..., ge=0, le=150, description="Age in years")
interests: List[str] = Field(default_factory=list)
# Create tool for specific model
user_tool = DataTransferTool.create(UserProfile, "UserProfileTool")
agent = Agent(
system_prompt="You handle user profile data transfers",
tools=[user_tool]
)
# Transfer data through Claude
await agent.run(
"Transfer user: Alice Johnson, age 28, interests programming and hiking"
)
# Retrieve validated data
user_data = user_tool.get()
if user_data:
print(f"Retrieved: {user_data.name}, age {user_data.age}")创建自定义工具
基本工具模式
from claude_agent_toolkit import BaseTool, tool
class MyTool(BaseTool):
def __init__(self):
super().__init__() # Server starts automatically
self.data = {} # Explicit data management
@tool()
async def process_async(self, data: str) -> dict:
"""Async operation"""
# Async operations for I/O, API calls
return {"result": f"processed_{data}"}
@tool(parallel=True, timeout_s=60)
def process_heavy(self, data: str) -> dict:
"""CPU-intensive operation"""
# Sync function - runs in separate process
# Note: New instance created, self.data won't persist
import time
time.sleep(2)
return {"result": f"heavy_{data}"}上下文管理器支持
# Single tool with guaranteed cleanup
with MyTool() as tool:
agent = Agent(tools=[tool])
result = await agent.run("Process my data")
# Server automatically cleaned up
# Multiple tools
with MyTool() as calc_tool, WeatherTool() as weather_tool:
agent = Agent(tools=[calc_tool, weather_tool])
result = await agent.run("Calculate and check weather")
# Both tools cleaned up automatically常见问题解答
什么是Claude Agent Toolkit?
一个Python框架,允许您使用Claude Code和自定义工具构建AI代理。与通用代理框架不同,这特别利用了Claude Code在现有订阅中的高级推理能力。
这与其他代理框架有何不同?
- 使用克劳德代码:利用Claude的生产基础设施和推理
- MCP协议:行业标准工具集成,而非专有API
- 显式数据:您控制数据持久性,没有隐藏的状态管理
- 生产重点:专为实际部署而设计,而不仅仅是实验
我需要Docker吗?
Docker建议用于生产,但不是必需的。使用 ExecutorType.SUBPROCESS 对于子流程执行:
agent = Agent(tools=[my_tool], executor=ExecutorType.SUBPROCESS)它还运行在一个隔离的目录中,以确保最大程度的隔离。
我应该使用哪种型号?
- 俳句:快速、经济高效,操作简单
- 十四行诗:性能均衡,默认选择良好
- 作品:复杂推理的最大能力
我该如何处理错误?
该框架提供了特定的异常类型:
from claude_agent_toolkit import ConfigurationError, ConnectionError, ExecutionError
try:
result = await agent.run("task")
except ConfigurationError:
# Missing OAuth token, invalid config
except ConnectionError:
# Docker/network issues
except ExecutionError:
# Tool failures, timeouts我可以同时使用多种工具吗?
对!Claude Code智能地编排多个工具:
agent = Agent(tools=[calc_tool, weather_tool, file_tool])
result = await agent.run(
"Calculate the average temperature and save results to report.txt"
)测试
该框架通过综合示例而不是传统的单元测试进行验证。每个示例都演示了特定的功能,并作为文档和验证。
运行示例
# Clone the repository
git clone https://github.com/yuping322/claude-agent-toolkit.git
cd claude-agent-toolkit
# Set your OAuth token
export CLAUDE_CODE_OAUTH_TOKEN='your-token-here'
# Run different examples
cd src/examples/calculator && python main.py # Stateful operations, parallel processing
cd src/examples/weather && python main.py # External API integration
cd src/examples/subprocess && python main.py # No Docker required
cd src/examples/filesystem && python main.py # Permission-based file access
cd src/examples/datatransfer && python main.py # Type-safe data transfer
cd src/examples/mcp && python main.py # External MCP server integration示例结构
src/examples/
├── calculator/ # Mathematical operations with state management
├── weather/ # External API integration (OpenWeatherMap)
├── subprocess/ # Subprocess executor demonstration
├── filesystem/ # FileSystemTool with permissions
├── datatransfer/ # DataTransferTool with Pydantic models
├── mcp/ # External MCP server integration (stdio, HTTP)
└── README.md # Detailed example documentationDocker验证
示例可以在两个执行器上运行:
# Docker executor (default)
python main.py
# Subprocess executor (faster startup)
# Examples automatically use subprocess when Docker unavailable贡献
- 分叉存储库
- 创建要素分支:
git checkout -b feature-name - 进行更改并用示例进行验证
- 运行示例以验证功能
- 提交拉取请求
开发环境设置
git clone https://github.com/yuping322/claude-agent-toolkit.git
cd claude-agent-toolkit
uv sync --group dev
# Validate your changes by running examples
export CLAUDE_CODE_OAUTH_TOKEN='your-token'
cd src/examples/calculator && python main.py许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
______________________________________________________________________
