1. 什么是分页? #
分页(Pagination)是 MCP 对可能返回大量结果的列表操作采用的分批返回机制。服务器每次只返回一「页」数据,客户端如需更多,则用游标继续请求下一页,避免一次性加载过多数据。
协议版本:2025-11-25
| 通俗理解 | 说明 |
|---|---|
| 分批返回 | 不一次性返回全部,而是按页返回 |
| 游标驱动 | 用不透明字符串(cursor)表示「当前位置」,无页码 |
| 页大小由服务器定 | 客户端不得假定每页固定条数 |
2. 本章你将学到 #
- 分页的请求与响应格式
- 游标(cursor)的含义与用法
- 支持分页的操作列表
- 实现要点与错误处理
3. 典型流程 #
客户端发 tools/list(无 cursor)→ 服务器返回前 20 个工具 + nextCursor: "abc123" → 客户端发 tools/list,params: { cursor: "abc123" } → 服务器返回下一批 + 新的 nextCursor → 若某次响应无 nextCursor,表示已到最后一页,分页结束。
4. 分页模型 #
| 概念 | 说明 |
|---|---|
| 游标(cursor) | 不透明字符串,表示结果集中的位置,客户端不得解析或修改 |
| 页大小 | 由服务器决定,客户端不得假定固定值 |
| nextCursor | 响应中若有此字段,表示还有下一页;无则表示结束 |
5. 请求格式 #
首次请求(无游标):
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
}继续请求(带游标):
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {
"cursor": "eyJwYWdlIjogMn0="
}
}6. 响应格式 #
有下一页:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [ { "name": "get_weather", ... }, ... ],
"nextCursor": "eyJwYWdlIjogMn0="
}
}最后一页(无 nextCursor):
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"tools": [ { "name": "send_email", ... } ]
}
}| 字段 | 说明 |
|---|---|
| 结果数组 | 如 tools、resources、prompts 等,依操作而定 |
nextCursor |
可选;存在则表示还有下一页,客户端可继续请求 |
7. 流程示意 #
sequenceDiagram
participant C as 客户端
participant S as 服务器
C->>S: tools/list (无 cursor)
S-->>C: 第 1 页 + nextCursor
C->>S: tools/list (cursor=...)
S-->>C: 第 2 页 + nextCursor
C->>S: tools/list (cursor=...)
S-->>C: 第 3 页(无 nextCursor,结束)
8. 支持分页的操作 #
| 操作 | 说明 |
|---|---|
resources/list |
列出 资源 |
resources/templates/list |
列出资源模板 |
prompts/list |
列出 提示 |
tools/list |
列出 工具 |
9. 实现要点 #
| 角色 | 要点 |
|---|---|
| 服务器 | 提供稳定的游标;妥善处理无效游标 |
| 客户端 | 无 nextCursor 视为结束;同时支持分页与非分页;必须将游标视为不透明令牌:不解析、不修改、不跨会话持久化 |
10. 错误处理 #
无效游标应返回 -32602(参数无效):
{
"jsonrpc": "2.0",
"id": 3,
"error": {
"code": -32602,
"message": "Invalid cursor"
}
}