首页 教程 常见问题

6.5 自定义工具

概述

自定义工具让你扩展 Agent 的能力,使其能够执行特定任务,如访问 API、操作数据库、调用外部服务等。

工具结构

每个工具包含三个部分:

基本示例

const calculatorTool = {
  name: 'calculate',
  description: '执行数学计算,支持加减乘除和括号',
  inputSchema: {
    type: 'object',
    properties: {
      expression: {
        type: 'string',
        description: '数学表达式,如 "2 + 3 * 4"'
      }
    },
    required: ['expression']
  },
  handler: async ({ expression }) => {
    try {
      const result = eval(expression);
      return { result, expression };
    } catch (error) {
      return { error: error.message };
    }
  }
};

const agent = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  tools: [calculatorTool]
});

带上下文的工具

const fileReadTool = {
  name: 'read_file',
  description: '读取文件内容',
  inputSchema: {
    type: 'object',
    properties: {
      path: { type: 'string' },
      lines: { type: 'number', description: '最多读取行数' }
    },
    required: ['path']
  },
  handler: async ({ path, lines }) => {
    const fs = await import('fs/promises');
    const content = await fs.readFile(path, 'utf-8');
    return {
      path,
      content: lines ? content.split('\n').slice(0, lines).join('\n') : content,
      size: content.length
    };
  }
};

异步工具

const weatherTool = {
  name: 'get_weather',
  description: '获取指定城市的天气信息',
  inputSchema: {
    type: 'object',
    properties: {
      city: { type: 'string' },
      unit: { type: 'string', enum: ['celsius', 'fahrenheit'], default: 'celsius' }
    },
    required: ['city']
  },
  handler: async ({ city, unit = 'celsius' }) => {
    const response = await fetch(`https://api.weather.example/${city}?unit=${unit}`);
    const data = await response.json();
    return {
      city,
      temperature: data.temp,
      condition: data.condition,
      humidity: data.humidity
    };
  }
};

MCP 工具

除了自定义工具,SDK 还支持 MCP(Model Context Protocol)协议连接外部工具服务器:

import { ClaudeAgent } from '@anthropic-ai/claude-code-sdk';

const agent = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  mcpServers: [
    {
      url: 'https://mcp.example.com/server',
      auth: { type: 'bearer', token: 'xxx' }
    }
  ]
});

工具搜索

当工具数量很多时,SDK 支持自动工具搜索:

const agent = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  tools: manyTools,  // 100+ 工具
  toolSearch: {
    enabled: true,
    maxResults: 5  // 每次最多返回5个相关工具
  }
});

工具错误处理

const unreliableTool = {
  name: 'fetch_data',
  description: '获取远程数据',
  inputSchema: { /* ... */ },
  handler: async ({ url }) => {
    try {
      const response = await fetch(url);
      return { data: await response.json() };
    } catch (error) {
      // 返回错误信息而不是抛出异常
      return {
        error: true,
        message: `获取失败: ${error.message}`,
        retryable: error.code === 'ECONNRESET'
      };
    }
  }
};

内置工具

SDK 提供常用内置工具: