> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/character-crafting-apis/mcp-server-api.md).

# MCP 服务器 API

注册 MCP 服务器，使用静态请求头或 OAuth 将其连接，并以编程方式将它们附加到角色上。

以编程方式管理 MCP 服务器。Playground 的 MCP 选项卡中提供的所有功能也都可通过 HTTP 使用：注册服务器、测试连接、连接 OAuth 账户，以及将服务器附加到角色。

有关 MCP 服务器是什么以及角色如何使用它们，请参阅 MCP 服务器。

典型流程：

1. 使用 `/mcp/servers/test`
2. 注册时使用 `/mcp/servers/create`
3. 对于 OAuth 服务器： `/mcp/oauth/start`，在浏览器中打开返回的 URL，然后轮询 `/mcp/oauth/status`
4. 使用以下接口将其附加到角色： `/mcp/characters/attach`

## 约定

* **基础 URL：** `https://api.convai.com/mcp`
* 所有端点都使用 **POST** 并携带 JSON 请求体（`Content-Type: application/json`），包括读取操作。唯一的例外是 OAuth 浏览器回调，你无需直接调用它。
* **身份验证：** 在 `CONVAI-API-KEY` 请求头中传入 API 密钥。每个请求都限定在你的账户范围内：你只能查看和修改自己的服务器和角色。
* **错误** 会返回带有相应状态码的 JSON 封装：

```json
{ "ERROR": "name: Field required" }
```

| 状态  | 含义                       |
| --- | ------------------------ |
| 400 | 请求体无效。消息会指出出错的字段。        |
| 401 | 缺少或无效的 API 密钥。           |
| 404 | 引用的服务器或角色不存在（或不属于你）。     |
| 429 | 超出速率限制（每个端点每分钟 100 个请求）。 |
| 500 | 内部错误。可以安全重试。             |

## 服务器对象

```json
{
  "server_id": "15e08050-2952-4380-8dfa-41242edbbcfe",
  "name": "order-lookup",
  "description": "Order status tools for support characters",
  "url": "https://mcp.example.com/mcp",
  "transport": "streamable_http",
  "auth_type": "headers",
  "auth_headers": { "Authorization": "Bearer sk-..." },
  "header_names": ["Authorization"],
  "tools_allowlist": ["lookup_order", "cancel_order"],
  "timeout_s": 30,
  "result_max_chars": null,
  "enabled": true,
  "created_at": "2026-08-19T09:18:44.783437"
}
```

* `auth_type`: `headers` （静态标头，默认）或 `oauth` （请参阅 [OAuth 连接](#oauth-connections)).
* `auth_headers` 包含已存储的标头值，仅返回给所属账户。 `header_names` 是相同的名称集合，仅保留名称以实现兼容性。OAuth 令牌 **绝不会** 由任何端点返回。
* `tools_allowlist`: `null` = 服务器提供的所有工具；列表 = 仅包含列出的工具； `[]` = 不提供任何工具。
* `timeout_s` / `result_max_chars`: `null` = 平台默认值（30 秒 / 4,000 个字符）。

## 服务器端点

### 列出服务器

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/mcp/servers/list` ，请求正文为 `{}`。返回账户中的所有服务器，按创建时间从新到旧排列。

```json
{ "servers": [ { ...server object... } ] }
```

### 创建服务器

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/mcp/servers/create`

| 字段                 | 必填 | 约束                                                |
| ------------------ | -- | ------------------------------------------------- |
| `name`             | 是  | 1–120 个字符                                         |
| `url`              | 是  | HTTPS，≤ 2048 个字符，完整的 MCP 端点路径（通常以 `/mcp`)         |
| `description`      | 否  | ≤ 2000 个字符                                        |
| `transport`        | 否  | `streamable_http` （默认）或 `sse`                     |
| `auth_type`        | 否  | `headers` （默认）或 `oauth`                           |
| `auth_headers`     | 否  | 由标头名称 → 值组成的对象；≤ 20 个标头，名称 ≤ 120 个字符，值 ≤ 8192 个字符 |
| `tools_allowlist`  | 否  | 工具名称数组；≤ 200 项，每个名称 ≤ 128 个字符；省略则表示允许所有工具         |
| `timeout_s`        | 否  | 整数，范围为 1–300                                      |
| `result_max_chars` | 否  | 整数，范围为 100–100000                                 |

返回 `{ "server": { ... } }`。标头值会以加密形式静态存储。

### 更新服务器

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/mcp/servers/update` ，请求正文为 `{ "server_id": "...", ...fields to change }`.

部分更新：未提供的字段保持不变。 `enabled: false` 会在所有位置禁用该服务器，但不会解除关联。返回更新后的 `{ "server": { ... } }`.

**标头保留标记：** 在 `auth_headers`中，空字符串值表示“保留此标头已存储的值”。若要移除某个标头，请在请求中省略该标头；若要清除所有标头，请发送 `auth_headers` 不包含该标头的请求；若要清除所有标头，请发送 `auth_headers: null`.

将 `auth_type` 设为 `headers` 会断开已连接 OAuth 的服务器：已存储的令牌会在提供方处撤销并删除。

### 删除服务器

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/mcp/servers/delete` ，请求正文为 `{ "server_id": "..." }`。此操作会移除服务器及其所有角色关联。对于 OAuth 服务器，已存储的令牌会在提供方处撤销并删除。返回 `{ "status": "success" }`.

### 测试连接

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/mcp/servers/test` 有两种互斥模式：

* **创建前探测：** `{ "url": "...", "transport"?, "auth_headers"? }`
* **已保存的服务器：** `{ "server_id": "..." }`。使用已存储的 URL、传输方式和凭据。使用已连接账户的有效令牌探测 OAuth 服务器。

返回发现的工具，或返回诊断信息：

```json
{ "ok": true, "tools": [ { "name": "lookup_order", "description": "..." } ] }
{ "ok": false, "error": "HTTP 401 on initialize (check URL and auth)" }
```

连接失败会通过 `ok: false` 响应正文报告，HTTP 状态码为 200；非 200 状态码表示请求本身失败，而非被探测的服务器失败。

## OAuth 连接

使用 `auth_type: "oauth"` 通过连接账户进行身份验证，而不是存储标头值。此流程包含一个浏览器步骤：账户所有者在服务提供商处登录；其余操作均为 API 调用：

1. 创建服务器时使用 `auth_type: "oauth"` 且不设置 `auth_headers`.
2. 调用 `/mcp/oauth/start`。它会返回一个 `authorize_url`.
3. 在浏览器中打开 `authorize_url` ，登录并批准所请求的访问权限。服务提供商会重定向回 Convai，随后由服务器端完成连接。
4. 轮询 `/mcp/oauth/status` ，直到 `status` 为 `connected`.

Convai 会自动向大多数服务提供商注册。令牌会经过加密存储并自动刷新；任何端点都不会返回令牌。

### 发起连接

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/mcp/oauth/start`

| 字段              | 必填 | 备注                            |
| --------------- | -- | ----------------------------- |
| `server_id`     | 是  | 必须是 `streamable_http` 服务器。    |
| `client_id`     | 否  | 仅用于不允许自动注册的服务提供商；见下文。         |
| `client_secret` | 否  | 同上；公共客户端可省略。                  |
| `scopes`        | 否  | 以空格分隔的权限范围字符串。省略时使用服务提供商的默认值。 |

```json
{ "ok": true, "authorize_url": "https://mcp.notion.com/authorize?client_id=..." }
```

该 URL 只能使用一次，并会在几分钟后过期；如需获取新的 URL，请再次调用 `/mcp/oauth/start` 。流程失败时（例如服务提供商拒绝自动注册），响应会是 `{ "ok": false, "error": "..." }` ，HTTP 状态码为 200。

**需要注册应用的服务提供商** （Google 和大多数企业身份系统）会拒绝自动注册； `start` 会返回相应错误。在服务提供商的控制台中创建 OAuth 应用，将 `https://api.convai.com/mcp/oauth/callback` 注册为其重定向 URL，然后再次调用，并提供该应用的 `start` 以及应用的 `client_id` （如果已签发，还需提供 `client_secret`）。

### 检查连接状态

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/mcp/oauth/status` 请求正文为 `{ "server_id": "..." }`.

```json
{ "status": "connected", "scope": "default" }
```

| `status`       | 含义                                    |
| -------------- | ------------------------------------- |
| `disconnected` | 未建立连接。使用以下接口启动连接： `/mcp/oauth/start`. |
| `pending`      | 已启动连接，但尚未完成浏览器步骤。                     |
| `connected`    | 已连接；可以使用服务器的工具。 `scope` 表示提供方授予的权限范围。 |
| `needs_reauth` | 提供方已撤销授权。请再次运行 `/mcp/oauth/start` 。   |

### 断开连接

<mark style="color:绿色;">`POST`</mark> `https://api.convai.com/mcp/oauth/disconnect` 请求正文为 `{ "server_id": "..." }`。此操作会撤销提供方授予的授权（尽力而为），并删除已存储的令牌。服务器配置会保留，因此你可以稍后重新连接。返回 `{ "status": "success" }`.

## 角色关联

* <mark style="color:绿色;">`POST`</mark> `/mcp/characters/list` 请求正文为 `{ "character_id": "..." }` 返回 `{ "server_ids": ["..."] }`
* <mark style="color:绿色;">`POST`</mark> `/mcp/characters/attach` 请求正文为 `{ "character_id": "...", "server_id": "..." }` 返回 `{ "status": "success" }`。两者都必须属于你的账户。此操作具有幂等性。
* <mark style="color:绿色;">`POST`</mark> `/mcp/characters/detach` 请求正文为 `{ "character_id": "...", "server_id": "..." }` 返回 `{ "status": "success" }`。此操作具有幂等性。

关联的工具会在角色的下一次对话会话中启用。

## 示例：使用标头身份验证的服务器

```bash
# 先探测，再注册并关联
curl -s https://api.convai.com/mcp/servers/test \
  -H "CONVAI-API-KEY: $CONVAI_API_KEY" -H "Content-Type: application/json" \
  -d '{"url": "https://mcp.example.com/mcp"}'

curl -s https://api.convai.com/mcp/servers/create \
  -H "CONVAI-API-KEY: $CONVAI_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "order-lookup", "url": "https://mcp.example.com/mcp",
       "auth_headers": {"Authorization": "Bearer sk-..."}}'

curl -s https://api.convai.com/mcp/characters/attach \
  -H "CONVAI-API-KEY: $CONVAI_API_KEY" -H "Content-Type: application/json" \
  -d '{"character_id": "<character_id>", "server_id": "<server_id from create>"}'
```

## 示例：OAuth 服务器

```bash
# 注册、启动连接、打开 URL，并轮询直到连接成功
curl -s https://api.convai.com/mcp/servers/create \
  -H "CONVAI-API-KEY: $CONVAI_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "notion", "url": "https://mcp.notion.com/mcp", "auth_type": "oauth"}'

curl -s https://api.convai.com/mcp/oauth/start \
  -H "CONVAI-API-KEY: $CONVAI_API_KEY" -H "Content-Type: application/json" \
  -d '{"server_id": "<server_id>"}'
# -> { "ok": true, "authorize_url": "https://..." }   在浏览器中打开此 URL

curl -s https://api.convai.com/mcp/oauth/status \
  -H "CONVAI-API-KEY: $CONVAI_API_KEY" -H "Content-Type: application/json" \
  -d '{"server_id": "<server_id>"}'
# -> { "status": "connected", "scope": "default" }
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/character-crafting-apis/mcp-server-api.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
