名称: 工具设计 描述: 使用@tool装饰器为领域特定代理创建自定义工具。在构建代理特定工具、实现MCP服务器或使用代理SDK创建内存工具时使用。 允许的工具: Read, Grep, Glob
工具设计技能
使用@tool装饰器为领域特定代理创建自定义工具。
目的
设计和实现自定义工具,为代理提供领域特定操作的专门能力。
何时使用
- 代理需要超越默认工具的能力
- 领域需要专门操作
- 构建专注、高效的代理
- 创建可重用的工具库
先决条件
- 理解@tool装饰器语法
- MCP服务器创建知识
- 工具目的的明确定义
设计过程
步骤 1: 定义工具目的
回答:
- 这个工具执行什么操作?
- 它需要什么输入?
- 它产生什么输出?
- 代理应该在什么时候使用这个工具?
步骤 2: 设计工具接口
工具签名:
@tool(
"tool_name", # 唯一标识符
"Description for agent", # 代理如何知道何时使用
{"param1": type, "param2": type} # 参数模式
)
async def tool_implementation(args: dict) -> dict:
pass
命名约定:
- 使用蛇形命名法命名工具
- 描述性:
calculate_compound_interest而不是calc - 前缀加上领域:
db_query,api_call
描述指南:
- 解释何时使用该工具
- 解释它做什么
- 包括任何约束
步骤 3: 定义参数
参数类型:
{
"text_param": str, # 字符串
"number_param": int, # 整数
"decimal_param": float, # 浮点数
"flag_param": bool, # 布尔值
}
必选 vs 可选:
async def my_tool(args: dict) -> dict:
# 必选 - 必须存在
required = args["required_param"]
# 可选 - 带默认值
optional = args.get("optional_param", "default")
步骤 4: 实现工具逻辑
基本模板:
@tool(
"tool_name",
"Description",
{"param1": str, "param2": int}
)
async def tool_name(args: dict) -> dict:
try:
# 1. 提取和验证输入
param1 = args["param1"]
param2 = args.get("param2", 10)
# 2. 执行操作
result = perform_operation(param1, param2)
# 3. 返回成功
return {
"content": [{"type": "text", "text": str(result)}]
}
except Exception as e:
# 4. 处理错误
return {
"content": [{"type": "text", "text": f"Error: {str(e)}"}],
"is_error": True
}
步骤 5: 添加错误处理
验证模式:
async def my_tool(args: dict) -> dict:
# 验证必选参数
if "required" not in args:
return error_response("Missing required parameter")
# 验证类型
if not isinstance(args["required"], str):
return error_response("Parameter must be string")
# 验证值
if args.get("limit", 0) < 0:
return error_response("Limit cannot be negative")
# 安全验证
if is_dangerous(args["input"]):
return error_response("Security: Operation blocked")
错误响应助手:
def error_response(message: str) -> dict:
return {
"content": [{"type": "text", "text": message}],
"is_error": True
}
def success_response(result: str) -> dict:
return {
"content": [{"type": "text", "text": result}]
}
步骤 6: 创建 MCP 服务器
from claude_agent_sdk import create_sdk_mcp_server
# 创建带有工具的服务器
my_server = create_sdk_mcp_server(
name="my_domain",
version="1.0.0",
tools=[
tool_one,
tool_two,
tool_three,
]
)
步骤 7: 配置代理
options = ClaudeAgentOptions(
mcp_servers={"my_domain": my_server},
allowed_tools=[
"mcp__my_domain__tool_one",
"mcp__my_domain__tool_two",
"mcp__my_domain__tool_three",
],
# 禁用未使用的默认工具
disallowed_tools=["WebFetch", "WebSearch", "TodoWrite"],
system_prompt=system_prompt,
model="opus",
)
工具类别
数据处理工具
@tool("parse_json", "Parse JSON string", {"json_str": str})
@tool("transform_data", "Transform data format", {"data": str, "format": str})
@tool("validate_schema", "Validate against schema", {"data": str, "schema": str})
领域操作工具
@tool("calculate_metric", "Calculate business metric", {"values": str, "metric": str})
@tool("lookup_reference", "Look up reference data", {"key": str})
@tool("process_record", "Process domain record", {"record": str})
集成工具
@tool("query_database", "Execute DB query", {"query": str})
@tool("call_api", "Call external API", {"endpoint": str, "method": str})
@tool("send_notification", "Send notification", {"channel": str, "message": str})
输出格式
设计工具时:
## 工具设计
**名称:** [tool_name]
**目的:** [what it does]
**领域:** [where it's used]
### 接口
@tool( “tool_name”, “Description for agent usage”, {“param1”: str, “param2”: int} )
### 参数
| 名称 | 类型 | 必选 | 描述 |
| --- | --- | --- | --- |
| param1 | str | 是 | [description] |
| param2 | int | 否 | [description], 默认: 10 |
### 返回格式
**成功:**
{“content”: [{“type”: “text”, “text”: “[result format]”}]}
**错误:**
{“content”: [{“type”: “text”, “text”: “Error: [message]”}], “is_error”: true}
### 实现
[Full implementation code]
### 使用示例
代理提示: "[example prompt that uses tool]"
工具调用: tool_name(param1="value", param2=20)
结果: "[expected result]"
设计检查清单
- [ ] 工具名称具有描述性
- [ ] 描述解释了何时使用
- [ ] 参数类型已定义
- [ ] 必选 vs 可选清晰
- [ ] 输入验证完整
- [ ] 错误处理健壮
- [ ] 安全检查到位
- [ ] 返回格式一致
关键: 客户端 vs 查询
警告: 自定义工具需要
ClaudeSDKClient, 而不是query()
# 错误
async for message in query(prompt, options=options):
pass
# 正确
async with ClaudeSDKClient(options=options) as client:
await client.query(prompt)
async for message in client.receive_response():
pass
交叉引用
- @custom-tool-patterns.md - 工具创建模式
- @core-four-custom.md - Core Four 中的工具
- @custom-agent-design skill - 代理设计工作流
版本历史
- v1.0.0 (2025-12-26): 初始发布
最后更新
日期: 2025-12-26 模型: claude-opus-4-5-20251101