> ## Documentation Index
> Fetch the complete documentation index at: https://mcp.developerdoc.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 工具

<div id="enable-section-numbers" />

Model Context Protocol (MCP) 允许服务器公开可由语言模型调用的工具。
工具使模型能够与外部系统交互，例如查询数据库、调用 API 或执行计算。
每个工具都由名称唯一标识，并包含描述其 schema 的元数据。

## 用户交互模型

MCP 中的工具被设计为**模型控制**，这意味着语言模型可以基于其对上下文和用户提示的理解，
自动发现并调用工具。

不过，实现可以自由地通过任何适合自身需求的界面模式公开工具；
协议本身并不强制规定任何特定的用户交互模型。

<Warning>
  出于信任与安全及安全性考虑，**SHOULD** 始终让人类参与流程，并能够拒绝工具调用。

  应用 **SHOULD**:

  * 提供清楚说明哪些工具会暴露给 AI 模型的 UI
  * 在工具被调用时插入清晰的视觉指示
  * 对操作向用户展示确认提示，确保人类参与流程
</Warning>

## 能力

支持工具的服务器 **MUST** 声明 `tools` 能力：

```json theme={null}
{
  "capabilities": {
    "tools": {
      "listChanged": true
    }
  }
}
```

`listChanged` 表示服务器是否会在可用工具列表变化时发出通知。

## 协议消息

### 列出工具

为了发现可用工具，客户端会发送 `tools/list` 请求。此操作支持[分页](/specification/2025-11-25/server/utilities/pagination)。

**请求：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list",
  "params": {
    "cursor": "optional-cursor-value"
  }
}
```

**响应：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [
      {
        "name": "get_weather",
        "title": "Weather Information Provider",
        "description": "Get current weather information for a location",
        "inputSchema": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "City name or zip code"
            }
          },
          "required": ["location"]
        },
        "icons": [
          {
            "src": "https://example.com/weather-icon.png",
            "mimeType": "image/png",
            "sizes": ["48x48"]
          }
        ],
        "execution": {
          "taskSupport": "optional"
        }
      }
    ],
    "nextCursor": "next-page-cursor"
  }
}
```

### 调用工具

为了调用工具，客户端会发送 `tools/call` 请求：

**请求：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "get_weather",
    "arguments": {
      "location": "New York"
    }
  }
}
```

**响应：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy"
      }
    ],
    "isError": false
  }
}
```

### 列表变化通知

当可用工具列表变化时，已声明 `listChanged` 能力的服务器 **SHOULD** 发送通知：

```json theme={null}
{
  "jsonrpc": "2.0",
  "method": "notifications/tools/list_changed"
}
```

## 消息流

```mermaid theme={null}
sequenceDiagram
    participant LLM
    participant Client
    participant Server

    Note over Client,Server: Discovery
    Client->>Server: tools/list
    Server-->>Client: List of tools

    Note over Client,LLM: Tool Selection
    LLM->>Client: Select tool to use

    Note over Client,Server: Invocation
    Client->>Server: tools/call
    Server-->>Client: Tool result
    Client->>LLM: Process result

    Note over Client,Server: Updates
    Server--)Client: tools/list_changed
    Client->>Server: tools/list
    Server-->>Client: Updated tools
```

## 数据类型

### Tool

工具定义包括：

* `name`：工具的唯一标识符
* `title`：用于显示的可选人类可读工具名称。
* `description`：对功能的人类可读描述
* `icons`：用于在用户界面中显示的可选图标数组
* `inputSchema`：定义预期参数的 JSON Schema
  * 遵循 [JSON Schema 使用指南](/specification/2025-11-25/basic#json-schema-usage)
  * 如果不存在 `$schema` 字段，则默认为 2020-12
  * **MUST** 是有效的 JSON Schema 对象（不是 `null`）
  * 对于没有参数的工具，请使用以下有效方式之一：
    * `{ "type": "object", "additionalProperties": false }` - **推荐**：明确只接受空对象
    * `{ "type": "object" }` - 接受任何对象（包括带有属性的对象）
* `outputSchema`：定义预期输出结构的可选 JSON Schema
  * 遵循 [JSON Schema 使用指南](/specification/2025-11-25/basic#json-schema-usage)
  * 如果不存在 `$schema` 字段，则默认为 2020-12
* `annotations`：描述工具行为的可选属性
* `execution`：描述执行相关属性的可选对象
  * `taskSupport`：表示此工具是否支持[任务增强执行](/specification/2025-11-25/basic/utilities/tasks#tool-level-negotiation)。取值为 `"forbidden"`（默认）、`"optional"` 或 `"required"`

<Warning>
  出于信任与安全及安全性考虑，除非工具 annotations 来自受信任服务器，
  否则客户端 **MUST** 将其视为不可信。
</Warning>

#### 工具名称

* 工具名称长度 **SHOULD** 在 1 到 128 个字符之间（含边界）。
* 工具名称 **SHOULD** 被视为区分大小写。
* **SHOULD** 仅允许以下字符：ASCII 大写和小写字母（A-Z、a-z）、数字（0-9）、下划线（\_）、连字符（-）和点（.）
* 工具名称 **SHOULD NOT** 包含空格、逗号或其他特殊字符。
* 工具名称 **SHOULD** 在服务器内唯一。
* 有效工具名称示例：
  * getUser
  * DATA\_EXPORT\_v2
  * admin.tools.list

### Tool Result

工具结果可以包含[**结构化**](#structured-content)内容或**非结构化**内容。

**非结构化**内容会在结果的 `content` 字段中返回，并且可以包含多个不同类型的内容项：

<Note>
  所有内容类型（文本、图像、音频、资源链接和嵌入式资源）都支持可选的
  [annotations](/specification/2025-11-25/server/resources#annotations)，用于提供受众、优先级和修改时间等元数据。
  这与资源和提示使用的 annotation 格式相同。
</Note>

#### 文本内容

```json theme={null}
{
  "type": "text",
  "text": "Tool result text"
}
```

#### 图像内容

```json theme={null}
{
  "type": "image",
  "data": "base64-encoded-data",
  "mimeType": "image/png",
  "annotations": {
    "audience": ["user"],
    "priority": 0.9
  }
}
```

#### 音频内容

```json theme={null}
{
  "type": "audio",
  "data": "base64-encoded-audio-data",
  "mimeType": "audio/wav"
}
```

#### 资源链接

工具 **MAY** 返回指向[资源](/specification/2025-11-25/server/resources)的链接，以提供额外上下文或数据。
在这种情况下，工具会返回一个可由客户端订阅或获取的 URI：

```json theme={null}
{
  "type": "resource_link",
  "uri": "file:///project/src/main.rs",
  "name": "main.rs",
  "description": "Primary application entry point",
  "mimeType": "text/x-rust"
}
```

资源链接支持与常规资源相同的[资源 annotations](/specification/2025-11-25/server/resources#annotations)，以帮助客户端理解如何使用它们。

<Info>
  工具返回的资源链接不保证会出现在 `resources/list` 请求的结果中。
</Info>

#### 嵌入式资源

[资源](/specification/2025-11-25/server/resources) **MAY** 使用合适的 [URI 方案](./resources#common-uri-schemes) 以内嵌方式提供额外上下文或数据。
使用嵌入式资源的服务器 **SHOULD** 实现 `resources` 能力：

```json theme={null}
{
  "type": "resource",
  "resource": {
    "uri": "file:///project/src/main.rs",
    "mimeType": "text/x-rust",
    "text": "fn main() {\n    println!(\"Hello world!\");\n}",
    "annotations": {
      "audience": ["user", "assistant"],
      "priority": 0.7,
      "lastModified": "2025-05-03T14:30:00Z"
    }
  }
}
```

嵌入式资源支持与常规资源相同的[资源 annotations](/specification/2025-11-25/server/resources#annotations)，以帮助客户端理解如何使用它们。

#### Structured Content

**结构化**内容会作为 JSON 对象在结果的 `structuredContent` 字段中返回。

为了向后兼容，返回结构化内容的工具 SHOULD 同时在 TextContent 块中返回序列化后的 JSON。

#### 输出 Schema

工具也可以提供输出 schema，用于验证结构化结果。
如果提供了输出 schema：

* 服务器 **MUST** 提供符合此 schema 的结构化结果。
* 客户端 **SHOULD** 根据此 schema 验证结构化结果。

带输出 schema 的工具示例：

```json theme={null}
{
  "name": "get_weather_data",
  "title": "Weather Data Retriever",
  "description": "Get current weather data for a location",
  "inputSchema": {
    "type": "object",
    "properties": {
      "location": {
        "type": "string",
        "description": "City name or zip code"
      }
    },
    "required": ["location"]
  },
  "outputSchema": {
    "type": "object",
    "properties": {
      "temperature": {
        "type": "number",
        "description": "Temperature in celsius"
      },
      "conditions": {
        "type": "string",
        "description": "Weather conditions description"
      },
      "humidity": {
        "type": "number",
        "description": "Humidity percentage"
      }
    },
    "required": ["temperature", "conditions", "humidity"]
  }
}
```

此工具的有效响应示例：

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 5,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"temperature\": 22.5, \"conditions\": \"Partly cloudy\", \"humidity\": 65}"
      }
    ],
    "structuredContent": {
      "temperature": 22.5,
      "conditions": "Partly cloudy",
      "humidity": 65
    }
  }
}
```

提供输出 schema 有助于客户端和 LLM 通过以下方式理解并正确处理结构化工具输出：

* 启用对响应的严格 schema 验证
* 提供类型信息，以便更好地与编程语言集成
* 指导客户端和 LLM 正确解析和使用返回的数据
* 支持更好的文档和开发者体验

### Schema 示例

#### 使用默认 2020-12 schema 的工具：

```json theme={null}
{
  "name": "calculate_sum",
  "description": "Add two numbers",
  "inputSchema": {
    "type": "object",
    "properties": {
      "a": { "type": "number" },
      "b": { "type": "number" }
    },
    "required": ["a", "b"]
  }
}
```

#### 使用显式 draft-07 schema 的工具：

```json theme={null}
{
  "name": "calculate_sum",
  "description": "Add two numbers",
  "inputSchema": {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
      "a": { "type": "number" },
      "b": { "type": "number" }
    },
    "required": ["a", "b"]
  }
}
```

#### 无参数工具：

```json theme={null}
{
  "name": "get_current_time",
  "description": "Returns the current server time",
  "inputSchema": {
    "type": "object",
    "additionalProperties": false
  }
}
```

## 错误处理

工具使用两种错误报告机制：

1. **协议错误**：用于以下问题的标准 JSON-RPC 错误：
   * 未知工具
   * 格式错误的请求（不满足 [CallToolRequest schema](/specification/2025-11-25/schema#calltoolrequest) 的请求）
   * 服务器错误

2. **工具执行错误**：在工具结果中以 `isError: true` 报告：
   * API 失败
   * 输入验证错误（例如日期格式错误、值超出范围）
   * 业务逻辑错误

**工具执行错误**包含可操作反馈，语言模型可用其自我修正并使用调整后的参数重试。
**协议错误**表示请求结构本身存在问题，模型通常不太可能修复。
客户端 **SHOULD** 将工具执行错误提供给语言模型，以支持自我修正。
客户端 **MAY** 将协议错误提供给语言模型，但这类错误不太可能成功恢复。

协议错误示例：

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 3,
  "error": {
    "code": -32602,
    "message": "Unknown tool: invalid_tool_name"
  }
}
```

工具执行错误示例（输入验证）：

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 4,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Invalid departure date: must be in the future. Current date is 08/08/2025."
      }
    ],
    "isError": true
  }
}
```

## 安全注意事项

1. 服务器 **MUST**:
   * 验证所有工具输入
   * 实现适当的访问控制
   * 对工具调用进行速率限制
   * 清理工具输出

2. 客户端 **SHOULD**:
   * 对敏感操作提示用户确认
   * 在调用服务器前向用户显示工具输入，以避免恶意或意外的数据外泄
   * 在传递给 LLM 前验证工具结果
   * 为工具调用实现超时
   * 出于审计目的记录工具使用情况
