MCP笔记02: MCP的核心架构
📅 2025-04-01 | 🖱️
🔖 mcp
模型上下文协议(MCP)建立在灵活且可扩展的架构之上,实现了大语言模型应用(LLM Applications)与各种集成(Integretions)之间的无缝通信。
本文将详细介绍MCP的核心架构组件和基本概念,了解MCP如何连接客户端(Client)、服务器(Server)和大语言模型(LLM)。
架构概览 #
MCP采用客户端-服务器架构模式:
- 宿主应用(Hosts):指大语言模型应用程序(如各种基于大模型的Chat应用例如Cherry Studio或各类IDE例如Cursor),负责发起连接
- 客户端:在宿主应用内部运行,与服务器维持一对一的连接关系
- 服务器:向客户端提供上下文信息(Context)、工具(Tools)和提示(Prompts)。
核心组件 #
协议层(Protocol layer) #
协议层负责处理消息帧、请求/响应链接以及高级通信模式。
1class Protocol<Request, Notification, Result> {
2 // Handle incoming requests
3 setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void
4
5 // Handle incoming notifications
6 setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void
7
8 // Send requests and await responses
9 request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>
10
11 // Send one-way notifications
12 notification(notification: Notification): Promise<void>
13}
1class Session(BaseSession[RequestT, NotificationT, ResultT]):
2 async def send_request(
3 self,
4 request: RequestT,
5 result_type: type[Result]
6 ) -> Result:
7 """Send request and wait for response. Raises McpError if response contains error."""
8 # Request handling implementation
9
10 async def send_notification(
11 self,
12 notification: NotificationT
13 ) -> None:
14 """Send one-way notification that doesn't expect response."""
15 # Notification handling implementation
16
17 async def _received_request(
18 self,
19 responder: RequestResponder[ReceiveRequestT, ResultT]
20 ) -> None:
21 """Handle incoming request from other side."""
22 # Request handling implementation
23
24 async def _received_notification(
25 self,
26 notification: ReceiveNotificationT
27 ) -> None:
28 """Handle incoming notification from other side."""
29 # 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定义了一些标准的错误码:
1enum ErrorCode {
2 // Standard JSON-RPC error codes
3 ParseError = -32700,
4 InvalidRequest = -32600,
5 MethodNotFound = -32601,
6 InvalidParams = -32602,
7 InternalError = -32603
8}
SDK和应用程序可在-32000
以上自定义错误代码。
错误通过以下途径传递:
- 对请求的错误响应
- 传输通道的错误事件
- 协议级的错误处理程序