模型上下文协议(MCP)建立在灵活且可扩展的架构之上,实现了大语言模型应用(LLM Applications)与各种集成(Integretions)之间的无缝通信。
本文将详细介绍MCP的核心架构组件和基本概念,了解MCP如何连接客户端(Client)、服务器(Server)和大语言模型(LLM)。
架构概览
MCP采用客户端-服务器架构模式:
- 宿主应用(Hosts):指大语言模型应用程序(如各种基于大模型的Chat应用例如Cherry Studio或各类IDE例如Cursor),负责发起连接
- 客户端:在宿主应用内部运行,与服务器维持一对一的连接关系
- 服务器:向客户端提供上下文信息(Context)、工具(Tools)和提示(Prompts)。
核心组件
协议层(Protocol layer)
协议层负责处理消息帧、请求/响应链接以及高级通信模式。
class Protocol<Request, Notification, Result> {
// Handle incoming requests
setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void
// Handle incoming notifications
setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void
// Send requests and await responses
request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>
// Send one-way notifications
notification(notification: Notification): Promise<void>
}class Session(BaseSession[RequestT, NotificationT, ResultT]):
async def send_request(
self,
request: RequestT,
result_type: type[Result]
) -> Result:
"""Send request and wait for response. Raises McpError if response contains error."""
# Request handling implementation
async def send_notification(
self,
notification: NotificationT
) -> None:
"""Send one-way notification that doesn't expect response."""
# Notification handling implementation
async def _received_request(
self,
responder: RequestResponder[ReceiveRequestT, ResultT]
) -> None:
"""Handle incoming request from other side."""
# Request handling implementation
async def _received_notification(
self,
notification: ReceiveNotificationT
) -> None:
"""Handle incoming notification from other side."""
# Notification handling implementation传输层(Transport layer)
传输层处理客户端和服务器之间的实际通信。MCP支持多种传输机制:
- Stdio transport(标准输入输出传输)
- 使用标准输入/输出进行通信
- 适用于本地进程
- SSE transport(HTTP with SSE transport)
- 使用服务器发送事件(Server-Sent Events)实现服务器到客户端的消息传递
- 使用HTTP POST实现客户端到服务器的消息传递
- 所有传输机制都使用JSON-RPC 2.0来交换消息。有关模型上下文协议(Model Context Protocol)消息格式的详细信息,请参阅规范。
消息类型(Message types)
MCP主要有以下4种类型的消息:
- Request: 请求另外一端,并期望其响应
- Result: Result对应Request的成功响应
- Errors: 表示Request失败
- Notification: 不需要回应(response)的单向消息
连接生命周期(Connection lifecycle)
1.初始化(Initialization)
- 客户端发送带有协议版本和功能(capabilities)的initialize请求
- 服务器响应其协议版本和功能(capabilities)
- 客户端发送initialized通知(notification)作为确认(ack)
- 开始正常的消息交换
2.消息交换(Message exchange)
初始化之后,支持以下消息交换模式:
- 请求-响应(Request-Response):客户端或服务器发送请求,另一方进行响应
- 通知(Notifications):任何一方发送单向消息
3.终止(Termination)
任何一方都可以终止连接:
- 通过
close()进行优雅的关闭 - 传输(Transport)断开连接
- 出错的情况(Error conditions)
错误处理
MCP定义了一些标准的错误码:
enum ErrorCode {
// Standard JSON-RPC error codes
ParseError = -32700,
InvalidRequest = -32600,
MethodNotFound = -32601,
InvalidParams = -32602,
InternalError = -32603
}SDK和应用程序可在-32000以上自定义错误代码。
错误通过以下途径传递:
- 对请求的错误响应
- 传输通道的错误事件
- 协议级的错误处理程序