工具(Tools)是模型上下文协议(MCP)中的一个基本元素,它允许服务器向客户端暴露可执行的功能。通过工具,大语言模型(LLMs)可以与外部系统交互、执行计算并在现实世界中采取行动。工具的设计理念是模型控制,即服务器将工具暴露给客户端,目的是让AI模型能够自动调用这些工具。

工具的核心功能

  1. 发现(Discovery):客户端可以通过tools/list端点列出可用的工具。
  2. 调用(Invocation):工具通过tools/call端点被调用,服务器执行请求的操作并返回结果。
  3. 灵活性(Flexibility):工具的范围从简单的计算到复杂的API交互,具有高度的灵活性。

工具与资源(Resources)不同,资源通常是静态的,而工具代表动态操作,可以修改状态或与外部系统交互。

工具的定义结构

每个工具的定义结构如下:

{
  "name": "string",          // 工具的唯一标识符
  "description": "string",   // 工具的人类可读描述
  "inputSchema": {           // 工具参数的JSON Schema
    "type": "object",
    "properties": { ... }    // 工具特定的参数
  }
}

工具的实现示例

以下是一个在MCP服务器中实现基本工具的示例:

const server = new Server({
  name: "example-server",
  version: "1.0.0"
}, {
  capabilities: {
    tools: {}
  }
});

// 定义可用的工具
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [{
      name: "calculate_sum",
      description: "Add two numbers together",
      inputSchema: {
        type: "object",
        properties: {
          a: { type: "number" },
          b: { type: "number" }
        },
        required: ["a", "b"]
      }
    }]
  };
});

// 处理工具执行
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "calculate_sum") {
    const { a, b } = request.params.arguments;
    return {
      toolResult: a + b
    };
  }
  throw new Error("Tool not found");
});

工具的模式示例

系统操作:与本地系统交互的工具。

{
  "name": "execute_command",
  "description": "Run a shell command",
  "inputSchema": {
    "type": "object",
    "properties": {
      "command": { "type": "string" },
      "args": { "type": "array", "items": { "type": "string" } }
    }
  }
}

API集成:封装外部API的工具。

{
  "name": "github_create_issue",
  "description": "Create a GitHub issue",
  "inputSchema": {
    "type": "object",
    "properties": {
      "title": { "type": "string" },
      "body": { "type": "string" },
      "labels": { "type": "array", "items": { "type": "string" } }
    }
  }
}

数据处理:用于数据转换或分析的工具。

{
  "name": "analyze_csv",
  "description": "Analyze a CSV file",
  "inputSchema": {
    "type": "object",
    "properties": {
      "filepath": { "type": "string" },
      "operations": {
        "type": "array",
        "items": {
          "enum": ["sum", "average", "count"]
        }
      }
    }
  }
}

总结

工具(Tools)在MCP中是一个核心概念,它通过服务器暴露可执行功能,使LLMs能够与外部系统交互并执行复杂的操作。工具的设计具有高度的灵活性和可扩展性,能够支持从简单的计算到复杂的API集成。通过定义工具的结构和实现方式,开发者可以轻松地将各种功能集成到LLMs中,从而增强模型的能力。

工具的模型控制特性确保了工具的调用是可控的,可以额外加入人工批准作为限制,这为安全性和可控性提供了保障。工具的发现和调用机制使得LLMs能够动态地与服务器交互,执行各种任务,极大地扩展了模型的应用场景。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐