MCP 协议详细分析 二 Sampling
基于Java mcp 客户端请求 Python mcp 服务端的一个例子,展示了MCP协议中Sampling功能的完整通信流程。
·
MCP Sampling 协议分析
基于Java mcp 客户端请求 Python mcp 服务端,展示了MCP协议中Sampling功能的完整通信流程。
简化版泳道图
流程说明
1. 初始化阶段
- 客户端初始化: Java客户端建立与MCP服务器的SSE连接
- 协议协商: 客户端发送初始化请求,包含sampling能力声明
- 服务器响应: 服务器返回支持的协议版本和功能列表
- 连接确认: 客户端发送initialized通知确认连接建立
2. Sampling测试阶段
- 工具调用: 客户端调用
echo-real-sampling工具 - 参数传递: 传递提示词、系统提示词、最大令牌数和温度参数
- 服务器处理: 服务器接收请求并开始处理
3. Sampling核心阶段
- 请求转发: 服务器将工具调用转换为sampling/createMessage请求
- 客户端处理: Java客户端接收sampling请求并生成响应
- 响应返回: 客户端返回生成的文本内容
- 结果封装: 服务器将sampling结果封装为工具调用响应
4. 日志记录
整个过程中,服务器通过notifications/message发送详细的调试和状态日志,包括:
- 开始处理通知
- 提示词和参数信息
- 处理进度更新
- 完成状态和结果统计
5. 连接清理
- 客户端优雅关闭连接
- 传输层清理资源
关键特性
- 双向通信: 使用SSE实现客户端与服务器的双向实时通信
- 异步处理: 支持异步消息处理和响应
- 详细日志: 完整的调试和状态日志记录
- 错误处理: 包含错误处理和连接管理
- 协议兼容: 遵循MCP协议规范进行通信
技术要点
- 传输协议: HTTP Server-Sent Events (SSE)
- 消息格式: JSON-RPC 2.0
- 认证方式: Bearer Token认证
- 内容类型: application/json
- 连接管理: 长连接,支持双向通信
详细日志记录
1. 初始化阶段日志
客户端初始化
20:29:15.093 [main] DEBUG i.m.client.McpAsyncClient - Initialization process started
=== ESTABLISHING MCP CONNECTION ===
Target Server URL: http://localhost:8080
SSE Endpoint: http://localhost:8080/sse/
Setting up SSE connection for MCP communication
Handler configured for bidirectional message processing
=====================================
发送初始化请求
20:29:15.194 [main] DEBUG i.m.spec.McpClientSession - Sending message for method initialize
=== SENDING MCP MESSAGE ===
Target URL: http://localhost:8080/sse/
HTTP Method: POST
Content-Type: application/json
User-Agent: MCP-Java-SDK-Debug/1.0
Authorization: Bearer D95A2765AA6B7202E5B6B57C10850C5A
Message type: JSONRPCRequest
Message content: {
"jsonrpc": "2.0",
"method": "initialize",
"id": "1f4d975d-0",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"sampling": {}
},
"clientInfo": {
"name": "Spring AI MCP Client",
"version": "0.3.1"
}
}
}
===========================
服务器初始化响应
20:29:15.283 [HttpClient-1-Worker-0] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCResponse
Message content: {
"jsonrpc": "2.0",
"id": "1f4d975d-0",
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"experimental": {},
"prompts": {"listChanged": true},
"resources": {"subscribe": false, "listChanged": true},
"tools": {"listChanged": true}
},
"serverInfo": {
"name": "Python Mcp Server",
"version": "1.10.1"
}
}
}
============================
发送初始化完成通知
20:29:15.641 [HttpClient-1-Worker-0] INFO i.m.client.McpAsyncClient - Server response with Protocol: 2024-11-05
=== SENDING MCP MESSAGE ===
Target URL: http://localhost:8080/sse/
HTTP Method: POST
Content-Type: application/json
User-Agent: MCP-Java-SDK-Debug/1.0
Authorization: Bearer D95A2765AA6B7202E5B6B57C10850C5A
Message type: JSONRPCNotification
Message content: {
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
===========================
2. Sampling测试阶段日志
发送工具调用请求
20:29:15.735 [main] DEBUG i.m.client.McpAsyncClient - Joining previous initialization
20:29:15.738 [main] DEBUG i.m.spec.McpClientSession - Sending message for method tools/call
=== SENDING MCP MESSAGE ===
Target URL: http://localhost:8080/sse/
HTTP Method: POST
Content-Type: application/json
User-Agent: MCP-Java-SDK-Debug/1.0
Authorization: Bearer D95A2765AA6B7202E5B6B57C10850C5A
Message type: JSONRPCRequest
Message content: {
"jsonrpc": "2.0",
"method": "tools/call",
"id": "1f4d975d-1",
"params": {
"name": "echo-real-sampling",
"arguments": {
"max_tokens": 100,
"system_prompt": "你是一个技术专家",
"prompt": "请简单介绍一下 MCP 协议",
"temperature": 0.7
}
}
}
===========================
3. 服务器处理日志
开始处理通知
20:29:15.820 [HttpClient-1-Worker-0] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCNotification
Message content: {
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "info",
"data": "开始真实MCP Sampling请求..."
}
}
============================
调试信息日志
20:29:16.017 [HttpClient-1-Worker-0] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCNotification
Message content: {
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "debug",
"data": "发送提示词: 请简单介绍一下 MCP 协议"
}
}
============================
20:29:16.021 [HttpClient-1-Worker-0] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCNotification
Message content: {
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "info",
"data": "构建MCP sampling请求..."
}
}
============================
20:29:16.025 [HttpClient-1-Worker-0] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCNotification
Message content: {
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "debug",
"data": "系统提示词: 你是一个技术专家"
}
}
============================
20:29:16.054 [HttpClient-1-Worker-0] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCNotification
Message content: {
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "debug",
"data": "参数: max_tokens=100, temperature=0.7"
}
}
============================
4. Sampling核心阶段日志
服务器发送Sampling请求
20:29:16.072 [HttpClient-1-Worker-0] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCRequest
Message content: {
"jsonrpc": "2.0",
"method": "sampling/createMessage",
"id": 0,
"params": {
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "请简单介绍一下 MCP 协议"
}
}
],
"systemPrompt": "你是一个技术专家",
"temperature": 0.7,
"maxTokens": 100
}
}
============================
客户端处理Sampling请求
20:29:16.103 [HttpClient-1-Worker-0] DEBUG i.m.spec.McpClientSession - Received request: JSONRPCRequest
🤖 收到采样请求!
提示词: 请简单介绍一下 MCP 协议
系统提示: 你是一个技术专家
最大令牌: 100
温度: 0.7
客户端发送Sampling响应
=== SENDING MCP MESSAGE ===
Target URL: http://localhost:8080/sse/
HTTP Method: POST
Content-Type: application/json
User-Agent: MCP-Java-SDK-Debug/1.0
Authorization: Bearer D95A2765AA6B7202E5B6B57C10850C5A
Message type: JSONRPCResponse
Message content: {
"jsonrpc": "2.0",
"id": 0,
"result": {
"role": "assistant",
"content": {
"type": "text",
"text": "MCP (Model Context Protocol) 是一个开放协议,用于AI应用程序与外部数据源和工具的安全连接。"
},
"model": "java-test-llm",
"stopReason": "endTurn"
}
}
===========================
5. 完成阶段日志
服务器完成通知
20:29:16.273 [HttpClient-1-Worker-3] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCNotification
Message content: {
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "info",
"data": "MCP Sampling请求成功完成!"
}
}
============================
20:29:16.294 [HttpClient-1-Worker-3] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCNotification
Message content: {
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "debug",
"data": "生成的内容长度: 106字符"
}
}
============================
最终工具调用响应
20:29:16.321 [HttpClient-1-Worker-3] DEBUG i.m.spec.McpSchema - Received JSON message
=== INCOMING MCP MESSAGE ===
Received from: http://localhost:8080/sse/
Message type: JSONRPCResponse
Message content: {
"jsonrpc": "2.0",
"id": "1f4d975d-1",
"result": {
"content": [
{
"type": "text",
"text": "{\"result\": true, \"message\": \"MCP Sampling成功完成\", \"timestamp\": \"2025-07-19T20:29:16.265238Z\", \"tool_name\": \"echo_real_sampling\", \"data\": {\"prompt\": \"请简单介绍一下 MCP 协议\", \"system_prompt\": \"你是一个技术专家\", \"generated_content\": \"type='text' text='MCP (Model Context Protocol) 是一个开放协议,用于AI应用程序与外部数据源和工具的安全连接。' annotations=None meta=None\", \"parameters\": {\"max_tokens\": 100, \"temperature\": 0.7}, \"sampling_status\": \"真实MCP sampling完成\", \"implementation_note\": \"使用FastMCP的ctx.sample()方法实现\"}}"
}
],
"structuredContent": {
"result": "{\"result\": true, \"message\": \"MCP Sampling成功完成\", \"timestamp\": \"2025-07-19T20:29:16.265238Z\", \"tool_name\": \"echo_real_sampling\", \"data\": {\"prompt\": \"请简单介绍一下 MCP 协议\", \"system_prompt\": \"你是一个技术专家\", \"generated_content\": \"type='text' text='MCP (Model Context Protocol) 是一个开放协议,用于AI应用程序与外部数据源和工具的安全连接。' annotations=None meta=None\", \"parameters\": {\"max_tokens\": 100, \"temperature\": 0.7}, \"sampling_status\": \"真实MCP sampling完成\", \"implementation_note\": \"使用FastMCP的ctx.sample()方法实现\"}}"
},
"isError": false
}
}
============================
客户端处理最终响应
20:29:16.333 [HttpClient-1-Worker-3] DEBUG i.m.spec.McpClientSession - Received Response: JSONRPCResponse
工具响应: {
"result": true,
"message": "MCP Sampling成功完成",
"timestamp": "2025-07-19T20:29:16.265238Z",
"tool_name": "echo_real_sampling",
"data": {
"prompt": "请简单介绍一下 MCP 协议",
"system_prompt": "你是一个技术专家",
"generated_content": "type='text' text='MCP (Model Context Protocol) 是一个开放协议,用于AI应用程序与外部数据源和工具的安全连接。' annotations=None meta=None",
"parameters": {
"max_tokens": 100,
"temperature": 0.7
},
"sampling_status": "真实MCP sampling完成",
"implementation_note": "使用FastMCP的ctx.sample()方法实现"
}
}
关键消息类型
- JSONRPCRequest: 客户端发起的请求
- JSONRPCResponse: 服务器返回的响应
- JSONRPCNotification: 服务器发送的通知消息
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)