> 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 Servers。

典型流程：

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 浏览器回调，它不会由你直接调用。
* **认证：** 将你的 API 密钥放在 `CONVAI-API-KEY` 请求头中。每个请求都限定在你的账户范围内：你只能查看和修改你自己的服务器和角色。
* **错误** 会返回一个带有相应状态码的 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": "面向支持角色的订单状态工具",
  "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": "...", ...要更改的字段 }`.

部分更新：省略的字段保持不变。 `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 仅可使用一次，并会在几分钟内过期；再次调用 `/mcp/oauth/start` 可获取新的 URL。流程失败（例如提供方拒绝自动注册）会以 `{ "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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
