MCP协议入门
官方协议文档: https://modelcontextprotocol.io/docs
分为数据层data layer和传输层transport layer
data layer
使用 JSONRPC2.0作为通讯协议, 包括生命周期管理和原语.
生命周期管理
MCP是有状态的协议, 所以需要生命周期管理, 目的是客户端和服务器协商彼此支持的能力(原语).
原语 primitives
包括服务器暴露的原语和客户端暴露的原语, 以及跨领域功能原语.
服务器原语包括:
| - | 工具 Tools | 资源 Resources | 提示词 Prompts |
|---|---|---|---|
| 控制者 | 大模型 | 应用 | 用户 |
工具 tools
包括 tools/list 和 tools/call
示例:
{
name: "searchFlights",
description: "Search for available flights",
inputSchema: {
type: "object",
properties: {
origin: { type: "string", description: "Departure city" },
destination: { type: "string", description: "Arrival city" },
date: { type: "string", format: "date", description: "Travel date" }
},
required: ["origin", "destination", "date"]
}
}
工具调用在必要时通过User Interaction Model用户交互模型让用户确认.
资源 resources
每个资源都有一个唯一的 URI(例如, file:///path/to/document.md ),并声明其 MIME 类型以进行适当的内容处理。
资源支持两种发现模式:
- 直接资源Direct Resources- 指向特定数据的固定 URI。示例: calendar://events/2024 - 返回 2024 年的日历可用性
- 资源模板Resource Templates - 带参数的动态 URI,用于灵活查询。如: travel://activities/{city}/{category} - 按城市和类别返回活动, 或者: travel://activities/barcelona/museums - 返回巴塞罗那的所有博物馆
操作包括:resources/list,resources/templates/list,resources/read,resources/subscribe
资源模板示例:{ "uriTemplate": "weather://forecast/{city}/{date}", "name": "weather-forecast", "title": "Weather Forecast", "description": "Get weather forecast for any city and date", "mimeType": "application/json" }
{
"uriTemplate": "travel://flights/{origin}/{destination}",
"name": "flight-search",
"title": "Flight Search",
"description": "Search available flights between cities",
"mimeType": "application/json"
}
支持参数补全和用户交互模型.
Prompts 提示系统
提示提供可重用的模板。它们允许 MCP 服务器作者为特定领域提供参数化提示,或展示如何最佳使用 MCP 服务器。
支持方法: prompts/list, prompts/get
示例:
{
"name": "plan-vacation",
"title": "Plan a vacation",
"description": "Guide through vacation planning process",
"arguments": [
{ "name": "destination", "type": "string", "required": true },
{ "name": "duration", "type": "number", "description": "days" },
{ "name": "budget", "type": "number", "required": false },
{ "name": "interests", "type": "array", "items": { "type": "string" } }
]
}
#### 客户端原语包括:
##### 采样 `sampling/complete`
采样允许服务器通过客户端请求 LLM 补全而不需要重复内建对LLM的调用,从而实现代理式工作流程。这种方法将客户端置于对用户权限和安全措施的完全控制之下。
##### 提取 `elicitation/requestInput`
提取使服务器能够在交互过程中请求特定信息,为服务器按需收集信息提供了一种结构化方式。
提示是结构化的模板,定义了预期的输入和交互模式。它们由用户控制,需要显式调用而非自动触发。提示可以感知上下文,引用可用的资源和工具以创建全面的流程。类似于资源,提示支持参数完成,以帮助用户发现有效的参数值。
支持方法: `prompts/list` 和 `prompts/get`
##### 根 Roots
根允许客户端指定服务器应关注的目录,通过协调机制传达预期范围。主要用作AI操作文件服务.
结构样式:
```json
{
"uri": "file:///Users/agent/travel-planning",
"name": "Travel Planning Workspace"
}
日志 logging
跨领域的功能原语 utility primitives
前有1个
- Tasks 支持延迟结果获取和状态跟踪
transport layer
支持 stdio和treamable HTTP两种传输机制. 使用 HTTP POST 进行客户端到服务器的消息传递,并可选使用 Server-Sent Events 实现流式功能. 该传输支持远程服务器通信,并支持标准 HTTP 认证方法,包括授权令牌、API 密钥和自定义头信息。MCP 推荐使用 OAuth 获取认证令牌。