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

# 工具

> 通过 MCP 协议发现和调用智能体工具 —— 含附件、幂等键、流式。

<Info>
  MCP host 的鉴权、端点布局以及 vs 其他协议的选择指引，从
  [MCP 概览](/zh/mcp/overview) 开始。本页是 `tools/*` 方法的逐字段参考。
</Info>

MCP 工具让外部 AI 平台发现智能体能干什么、调用具体能力。BeeOS 智能体
自动把已注册技能暴露为 MCP 工具。

## 附件

`tools/call` 在工具参数里接受 `attachments` 数组 —— 每个元素是
`{ file_id, filename?, content_type? }`。MCP Gateway 把 `file_id`
解析成签名下载 URL，作为 [`chat_message`](/zh/architecture/public-overview)
信封的一部分转发给智能体（与 OpenAPI `invokeAgent` 和 A2A `FilePart`
形状一致）。先用 `openapi.beeos.ai` 上的
`POST /api/v1/files/presign-upload`（或 TypeScript SDK 的 `FilesApi`）
上传文件。

## 幂等

工具参数里传 `idempotency_key` 让 `tools/call` 可安全重试。同一个 key
在 TTL 窗口内重复
（[ADR 0021](https://github.com/beeos-ai/openagent/blob/main/backend/docs/adr/0021-idempotency-key-ttl.md)）
会拿缓存的响应、不会重新 invoke 智能体。

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 42,
  "method": "tools/call",
  "params": {
    "name": "summarize_pdf",
    "arguments": {
      "attachments": [{ "file_id": "file_abc123", "filename": "q3.pdf" }],
      "idempotency_key": "user_7:q3_summary"
    }
  }
}
```

## HMAC 签名回调

工具 invocation 触发 webhook 时（例如长任务），投递按 webhook 上注册
的 secret 做 HMAC-SHA256 签名。规范签名契约见
[Webhooks § HMAC 签名](/zh/guides/webhooks#6-hmac-签名) ——
OpenAPI、A2A、MCP 三个面完全一致。

## tools/list

发现智能体提供的所有工具。

**请求:**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list"
}
```

**响应:**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [
      {
        "name": "web_search",
        "description": "Search the web for current information on any topic.",
        "inputSchema": {
          "type": "object",
          "properties": {
            "query": {
              "type": "string",
              "description": "The search query"
            },
            "max_results": {
              "type": "integer",
              "description": "Maximum number of results to return",
              "default": 5
            }
          },
          "required": ["query"]
        }
      },
      {
        "name": "screenshot",
        "description": "Take a screenshot of the current browser or desktop view.",
        "inputSchema": {
          "type": "object",
          "properties": {}
        }
      }
    ]
  }
}
```

### 工具 schema

响应里每个工具遵循此结构：

| 字段            | 类型     | 说明                    |
| ------------- | ------ | --------------------- |
| `name`        | string | 工具唯一标识                |
| `description` | string | 工具做什么的人类可读描述          |
| `inputSchema` | object | 描述工具输入参数的 JSON Schema |

## tools/call

在智能体上调用特定工具。

**请求:**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "web_search",
    "arguments": {
      "query": "BeeOS AI agent platform",
      "max_results": 3
    }
  }
}
```

**响应:**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Here are the top 3 results for 'BeeOS AI agent platform':\n\n1. ..."
      }
    ]
  }
}
```

### tools/call params

| 字段          | 类型     | 必填 | 说明                     |
| ----------- | ------ | -- | ---------------------- |
| `name`      | string | 是  | `tools/list` 给的工具名     |
| `arguments` | object | 是  | 匹配工具 `inputSchema` 的参数 |

### 结果 content 类型

`result.content` 数组可以含：

| 类型         | 说明                    |
| ---------- | --------------------- |
| `text`     | 纯文本结果                 |
| `image`    | base64 编码图像 + MIME 类型 |
| `resource` | 资源 URI 引用             |

## tools/call 怎么工作

底层 `tools/call` 是同步聊天 round-trip：

1. MCP Gateway 把工具调用转成 `chat_message` 信封
2. 消息通过 Message Service 发到 IM 通道
3. Gateway 调 `POST /channels/{id}/wait`、`in_reply_to` 匹配
4. 智能体处理工具调用、发布 `agent_reply`
5. Gateway 提取回复文本、作为 MCP content 返回

```mermaid theme={null}
flowchart LR
    Client["MCP Client"] -->|"tools/call"| GW["MCP Gateway"]
    GW -->|"chat_message"| MS["Message Service"]
    MS -->|"deliver"| Agent["Agent Pod"]
    Agent -->|"agent_reply"| MS
    MS -->|"wait match"| GW
    GW -->|"result"| Client
```

## 多轮上下文

默认每次 `tools/call` 都创建新 IM 通道。跨多次工具调用维持会话上下文，
MCP Gateway 跟踪 MCP spec 定义的 `Mcp-Session-Id` header。同一 session
里的调用共享底层同一 IM 通道，让智能体能访问之前的会话历史。

## 超时

`tools/call` 默认超时 **60 秒**。智能体在窗内没回 gateway 返回
JSON-RPC error：

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 2,
  "error": {
    "code": -32003,
    "message": "Agent reply timeout"
  }
}
```

## 错误处理

| 错误码      | 含义                    |
| -------- | --------------------- |
| `-32601` | 工具未找到（查 `tools/list`） |
| `-32602` | 非法参数（查 `inputSchema`） |
| `-32003` | 智能体超时                 |
| `-32603` | 内部错误                  |

## 示例：完整流程

```bash theme={null}
# 1. 列工具
curl -s -X POST "https://mcp.beeos.ai/${AGENT_ID}/mcp" \
  -H "X-Agent-API-Key: bak_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jq '.result.tools[].name'

# 2. 调一个工具
curl -s -X POST "https://mcp.beeos.ai/${AGENT_ID}/mcp" \
  -H "X-Agent-API-Key: bak_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc":"2.0",
    "id":2,
    "method":"tools/call",
    "params":{
      "name":"web_search",
      "arguments":{"query":"BeeOS"}
    }
  }' | jq '.result.content[0].text'
```
