tool-design

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tool Design Skill

工具设计技能

Create custom tools for domain-specific agents using the @tool decorator.
使用@tool装饰器为特定领域的Agent创建自定义工具。

Purpose

用途

Design and implement custom tools that give agents specialized capabilities for domain-specific operations.
设计并实现自定义工具,为Agent赋予针对特定领域操作的专属能力。

When to Use

适用场景

  • Agent needs capabilities beyond default tools
  • Domain requires specialized operations
  • Building focused, efficient agents
  • Creating reusable tool libraries
  • Agent需要默认工具之外的能力
  • 特定领域需要专属操作
  • 构建专注、高效的Agent
  • 创建可复用的工具库

Prerequisites

前置条件

  • Understanding of @tool decorator syntax
  • Knowledge of MCP server creation
  • Clear definition of tool purpose
  • 了解@tool装饰器的语法
  • 具备MCP服务器创建的相关知识
  • 明确工具的用途定义

Design Process

设计流程

Step 1: Define Tool Purpose

步骤1:定义工具用途

Answer:
  • What operation does this tool perform?
  • What inputs does it need?
  • What output does it produce?
  • When should the agent use this tool?
请回答:
  • 该工具执行什么操作?
  • 它需要哪些输入?
  • 它会产生什么输出?
  • Agent应在何时使用该工具?

Step 2: Design Tool Interface

步骤2:设计工具接口

Tool Signature:
python
@tool(
    "tool_name",                    # Unique identifier
    "Description for agent",        # How agent knows when to use
    {"param1": type, "param2": type}  # Parameter schema
)
async def tool_implementation(args: dict) -> dict:
    pass
Naming Convention:
  • Use snake_case for tool names
  • Be descriptive:
    calculate_compound_interest
    not
    calc
  • Prefix with domain:
    db_query
    ,
    api_call
Description Guidelines:
  • Explain WHEN to use the tool
  • Explain WHAT it does
  • Include any constraints
工具签名:
python
@tool(
    "tool_name",                    # Unique identifier
    "Description for agent",        # How agent knows when to use
    {"param1": type, "param2": type}  # Parameter schema
)
async def tool_implementation(args: dict) -> dict:
    pass
命名规范:
  • 工具名称使用蛇形命名法(snake_case)
  • 名称需具有描述性:使用
    calculate_compound_interest
    而非
    calc
  • 可添加领域前缀:
    db_query
    ,
    api_call
描述指南:
  • 说明工具的使用时机
  • 说明工具的功能
  • 包含任何约束条件

Step 3: Define Parameters

步骤3:定义参数

Parameter Types:
python
{
    "text_param": str,      # String
    "number_param": int,    # Integer
    "decimal_param": float, # Float
    "flag_param": bool,     # Boolean
}
Required vs Optional:
python
async def my_tool(args: dict) -> dict:
    # Required - must exist
    required = args["required_param"]

    # Optional - with default
    optional = args.get("optional_param", "default")
参数类型:
python
{
    "text_param": str,      # String
    "number_param": int,    # Integer
    "decimal_param": float, # Float
    "flag_param": bool,     # Boolean
}
必填与可选参数:
python
async def my_tool(args: dict) -> dict:
    # Required - must exist
    required = args["required_param"]

    # Optional - with default
    optional = args.get("optional_param", "default")

Step 4: Implement Tool Logic

步骤4:实现工具逻辑

Basic Template:
python
@tool(
    "tool_name",
    "Description",
    {"param1": str, "param2": int}
)
async def tool_name(args: dict) -> dict:
    try:
        # 1. Extract and validate inputs
        param1 = args["param1"]
        param2 = args.get("param2", 10)

        # 2. Perform operation
        result = perform_operation(param1, param2)

        # 3. Return success
        return {
            "content": [{"type": "text", "text": str(result)}]
        }

    except Exception as e:
        # 4. Handle errors
        return {
            "content": [{"type": "text", "text": f"Error: {str(e)}"}],
            "is_error": True
        }
基础模板:
python
@tool(
    "tool_name",
    "Description",
    {"param1": str, "param2": int}
)
async def tool_name(args: dict) -> dict:
    try:
        # 1. Extract and validate inputs
        param1 = args["param1"]
        param2 = args.get("param2", 10)

        # 2. Perform operation
        result = perform_operation(param1, param2)

        # 3. Return success
        return {
            "content": [{"type": "text", "text": str(result)}]
        }

    except Exception as e:
        # 4. Handle errors
        return {
            "content": [{"type": "text", "text": f"Error: {str(e)}"}],
            "is_error": True
        }

Step 5: Add Error Handling

步骤5:添加错误处理

Validation Pattern:
python
async def my_tool(args: dict) -> dict:
    # Validate required params
    if "required" not in args:
        return error_response("Missing required parameter")

    # Validate types
    if not isinstance(args["required"], str):
        return error_response("Parameter must be string")

    # Validate values
    if args.get("limit", 0) < 0:
        return error_response("Limit cannot be negative")

    # Security validation
    if is_dangerous(args["input"]):
        return error_response("Security: Operation blocked")
Error Response Helper:
python
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}]
    }
验证模式:
python
async def my_tool(args: dict) -> dict:
    # Validate required params
    if "required" not in args:
        return error_response("Missing required parameter")

    # Validate types
    if not isinstance(args["required"], str):
        return error_response("Parameter must be string")

    # Validate values
    if args.get("limit", 0) < 0:
        return error_response("Limit cannot be negative")

    # Security validation
    if is_dangerous(args["input"]):
        return error_response("Security: Operation blocked")
错误响应辅助函数:
python
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}]
    }

Step 6: Create MCP Server

步骤6:创建MCP服务器

python
from claude_agent_sdk import create_sdk_mcp_server
python
from claude_agent_sdk import create_sdk_mcp_server

Create server with tools

Create server with tools

my_server = create_sdk_mcp_server( name="my_domain", version="1.0.0", tools=[ tool_one, tool_two, tool_three, ] )
undefined
my_server = create_sdk_mcp_server( name="my_domain", version="1.0.0", tools=[ tool_one, tool_two, tool_three, ] )
undefined

Step 7: Configure Agent

步骤7:配置Agent

python
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",
    ],
    # Disable unused default tools
    disallowed_tools=["WebFetch", "WebSearch", "TodoWrite"],
    system_prompt=system_prompt,
    model="opus",
)
python
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",
    ],
    # Disable unused default tools
    disallowed_tools=["WebFetch", "WebSearch", "TodoWrite"],
    system_prompt=system_prompt,
    model="opus",
)

Tool Categories

工具分类

Data Processing Tools

数据处理工具

python
@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})
python
@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})

Domain Operation Tools

领域操作工具

python
@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})
python
@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})

Integration Tools

集成工具

python
@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})
python
@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})

Output Format

输出格式

When designing a tool:
markdown
undefined
设计工具时,请遵循以下格式:
markdown
undefined

Tool Design

Tool Design

Name: [tool_name] Purpose: [what it does] Domain: [where it's used]
Name: [tool_name] Purpose: [what it does] Domain: [where it's used]

Interface

Interface


@tool(
    "tool_name",
    "Description for agent usage",
    {"param1": str, "param2": int}
)

```markdown

@tool(
    "tool_name",
    "Description for agent usage",
    {"param1": str, "param2": int}
)

```markdown

Parameters

Parameters

NameTypeRequiredDescription
param1strYes[description]
param2intNo[description], default: 10
NameTypeRequiredDescription
param1strYes[description]
param2intNo[description], default: 10

Return Format

Return Format

Success:

{"content": [{"type": "text", "text": "[result format]"}]}

```markdown

**Error:**
{"content": [{"type": "text", "text": "Error: [message]"}], "is_error": true}
markdown
undefined
Success:

{"content": [{"type": "text", "text": "[result format]"}]}

```markdown

**Error:**
{"content": [{"type": "text", "text": "Error: [message]"}], "is_error": true}
markdown
undefined

Implementation

Implementation


[Full implementation code]

```markdown

[Full implementation code]

```markdown

Usage Example

Usage Example

Agent prompt: "[example prompt that uses tool]" Tool call: tool_name(param1="value", param2=20) Result: "[expected result]"
undefined
Agent prompt: "[example prompt that uses tool]" Tool call: tool_name(param1="value", param2=20) Result: "[expected result]"
undefined

Design Checklist

设计检查清单

  • Tool name is descriptive
  • Description explains when to use
  • Parameter types are defined
  • Required vs optional is clear
  • Input validation is complete
  • Error handling is robust
  • Security checks are in place
  • Return format is consistent
  • 工具名称具有描述性
  • 描述明确了使用时机
  • 已定义参数类型
  • 清晰区分必填与可选参数
  • 输入验证完整
  • 错误处理机制完善
  • 已添加安全检查
  • 返回格式统一

Critical: Client vs Query

重要提示:Client vs Query

Warning: Custom tools require
ClaudeSDKClient
, not
query()
python
undefined
警告:自定义工具需使用
ClaudeSDKClient
,而非
query()
python
undefined

WRONG

WRONG

async for message in query(prompt, options=options): pass
async for message in query(prompt, options=options): pass

CORRECT

CORRECT

async with ClaudeSDKClient(options=options) as client: await client.query(prompt) async for message in client.receive_response(): pass
undefined
async with ClaudeSDKClient(options=options) as client: await client.query(prompt) async for message in client.receive_response(): pass
undefined

Cross-References

交叉引用

  • @custom-tool-patterns.md - Tool creation patterns
  • @core-four-custom.md - Tools in Core Four
  • @custom-agent-design skill - Agent design workflow
  • @custom-tool-patterns.md - 工具创建模式
  • @core-four-custom.md - Core Four中的工具
  • @custom-agent-design skill - Agent设计工作流

Version History

版本历史

  • v1.0.0 (2025-12-26): Initial release

  • v1.0.0 (2025-12-26): 初始版本

Last Updated

最后更新

Date: 2025-12-26 Model: claude-opus-4-5-20251101
日期: 2025-12-26 模型: claude-opus-4-5-20251101