Python23-MCP-PostMan调试-SSE
1-使用postman手动拼装MCP请求参数,让理解更充分;先不推荐SSE这种方式,翻来覆去才能看清楚输出,推荐Streamable方式
2-Python-MCP代码编写:https://blog.csdn.net/2301_77717148/article/details/170049418
3-Python-MCPInspector调试:https://blog.csdn.net/2301_77717148/article/details/147881127
4-Python22-MCP-PostMan调试-Streamable:https://blog.csdn.net/2301_77717148/article/details/170346745

1-SSE编写MCP代码
import logging
from fastmcp import FastMCP
from python_mcp_demo_new3.service.CityWeatherService import CityWeatherService
"""
MCP Demo Server (Python)
基于 mcp Python SDK 实现,支持 Tools、Resources、Prompts 三大核心能力。
"""
# 配置日志打印级别
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
PORT = 7001
# 初始化 MCP 服务器
mcp = FastMCP("CityWeatherMcp2_FastMcp_SSE")
# 初始化城市信息服务器
city_service = CityWeatherService()
# ============================================
# 1. 注册工具能力:天气查询、时间获取
# ============================================
# 获取天气信息的工具
@mcp.tool()
async def get_city_weather(city: str) -> str:
"""获取指定城市的天气信息。
参数:
city (str): 城市名称
返回:
str: 天气信息描述
"""
city_weather_info = await city_service.get_city_weather(city)
logger.info(f"获取指定城市的天气信息: {city_weather_info}")
return city_weather_info
@mcp.tool()
# 获取所有城市列表
async def get_city_list():
"""获取所有城市列表。
返回:
str: 所有城市列表
"""
city_list = await city_service.get_city_list()
logger.info(f"获取所有城市列表: {city_list}")
return city_list
@mcp.tool()
# 获取指定城市的信息
async def get_city_detail(city: str):
"""获取指定城市的信息。
参数:
city (str): 城市名称
返回:
str: 指定城市的信息
"""
city_info = await city_service.get_city_detail(city)
logger.info(f"指定城市的信息: {city_info}")
return city_info
@mcp.tool()
async def get_current_time() -> str:
"""获取当前系统时间"""
from datetime import datetime
now = datetime.now()
return now.strftime("%Y-%m-%d %H:%M:%S")
# ============================================
# 2. 注册资源能力:应用配置读取、本地文件读取
# ============================================
@mcp.resource("config://app/settings")
async def app_settings() -> str:
"""获取应用配置信息"""
import json
config = {
"app_name": "Demo MCP Server",
"version": "1.0.0",
"features": {"weather": True, "calculator": True, "file_reader": True},
"max_file_size_mb": 10,
}
return json.dumps(config, indent=2, ensure_ascii=False)
@mcp.resource("file://docs/readme")
async def readme() -> str:
"""项目说明文档"""
return "这是一个基于 MCP 协议的演示服务端(Python版),支持天气查询、数学计算、代码审查等功能。"
# ============================================
# 3. 注册提示词模板:代码审查、错误分析
# ============================================
@mcp.prompt()
def code_review(code: str, language: str = "python") -> str:
"""代码审查提示词
Args:
code: 待审查的代码
language: 编程语言,默认为 python
"""
return (
f"请对以下 {language} 代码进行审查,"
f"从代码质量、潜在Bug、性能、安全性、最佳实践五个维度给出评价和优化建议:\n"
f"```{language}\n{code}\n```"
)
@mcp.prompt()
def error_analysis(error: str, context: str = "") -> str:
"""错误分析提示词
Args:
error: 错误信息或堆栈跟踪
context: 相关上下文代码
"""
prompt = f"请分析以下错误信息,给出可能的原因和解决方案:\n\n错误信息:\n```\n{error}\n```"
if context:
prompt += f"\n\n相关代码:\n```\n{context}\n```"
return prompt
# 主程序
if __name__ == "__main__":
# 打印transport模式
logger.info(f"运行MCP客户端,使用sse作为传输协议" +
f"->城市航班服务器监听 http://0.0.0.0:{PORT}/sse")
# 运行sse模式
mcp.run(transport="sse", port=PORT, host="0.0.0.0")
2-PostMan调用MCP总结-SSE
1-推荐使用官方的inspector进行调试 -> 可视化,但是会让你看不到具体的细节
2-使用postman进行原生JSON-RPC的API调用 -> 自己从0到1进行请求参数的拼接,知道更具体的业务请求细节
1-常用API请求
1-完整流程速查
除了【initialize】方法没有添加mcp-session-id,其他所有的请求都要在Header中添加【mcp-session-id】的业务参数
| 步骤 | method | 是否带 id | 是否带 mcp-session-id |
|---|---|---|---|
| 1 初始化 | initialize | ✅ id: 1 | ❌(从这步的响应头获取) |
| 2 通知就绪 | notifications/initialized | ❌ | ✅ |
| 3 获取工具列表 | tools/list | ✅ id: 2 | ✅ |
| 4 调用工具 | tools/call | ✅ id: 3 | ✅ |
| 5 获取Prompt列表 | prompts/list | ✅ id: 4 | ✅ |
| 6 获取Prompt | prompts/get | ✅ id: 5 | ✅ |
| 7 获取资源列表 | resources/list | ✅ id: 6 | ✅ |
| 8 读取资源 | resources/read | ✅ id: 7 | ✅ |
2-方法速查表
| 用途 | method | 关键参数 |
|---|---|---|
| 工具列表 | tools/list | 无 |
| 调用工具 | tools/call | name + arguments |
| Prompt 列表 | prompts/list | 无 |
| 获取 Prompt | prompts/get | name + arguments |
| 资源列表 | resources/list | 无 |
| 读取资源 | resources/read | uri |
| 资源模板列表 | resources/templates/list | 无(带参数的动态 URI 模板才用) |
2-具体请求参数
1-sse连接
1-注意:这个窗口不能关闭掉,后续请求的结果都会在这个请求中返回
2-注意:response会返回一个地址,这个地址会用来做后续的请求
curl --location --request GET 'http://0.0.0.0:7003/sse' \
--header 'Accept: application/json, text/event-stream' \
--header 'Content-Type: application/json'

2-initialize
1-注意:这个窗口不能关闭掉,后续请求的结果都会在这个请求中返回
2-注意:response会返回一个session_id,后续要塞入到Header中
curl --location --request POST 'http://0.0.0.0:7003/messages/?session_id=29a07a79992b46f691fb1ccbeca368d4' \
--header 'Accept: application/json, text/event-stream' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": { "name": "postman", "version": "1.0" }
}
}'

2-notifications/initialized
curl --location --request POST 'http://0.0.0.0:7003/messages/?session_id=06a8da16c5554171b6618cbddb109747' \
--header 'Accept: application/json, text/event-stream' \
--header 'Content-Type: application/json' \
--data-raw '{"jsonrpc":"2.0","method":"notifications/initialized"}'

3-ping
curl --location --request POST 'http://0.0.0.0:7003/mcp' \
--header 'Accept: application/json, text/event-stream' \
--header 'mcp-session-id: 80028fa0848245748eabfab76a1ecf38' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"id": 99,
"method": "ping",
"params": {}
}'
4-tools/list
curl --location --request POST 'http://0.0.0.0:7003/messages?session_id=8cca83ea30364b248ee47978019b330a' \
--header 'Accept: application/json, text/event-stream' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}'

5-tools/call
curl --location --request POST 'http://0.0.0.0:7003/messages?session_id=06a8da16c5554171b6618cbddb109747' \
--header 'Accept: application/json, text/event-stream' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_city_weather",
"arguments": {
"city": "北京"
}
}
}'

6-prompts/list
curl --location --request POST 'http://0.0.0.0:7003/messages?session_id=06a8da16c5554171b6618cbddb109747' \
--header 'Accept: application/json, text/event-stream' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"id": 4,
"method": "prompts/list",
"params": {}
}'
7-prompts/get
curl --location --request POST 'http://0.0.0.0:7003/messages?session_id=06a8da16c5554171b6618cbddb109747' \
--header 'Accept: application/json, text/event-stream' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"id": 5,
"method": "prompts/get",
"params": {
"name": "code_review",
"arguments": {
"code": "def add(a,b): return a+b",
"language": "python"
}
}
}'
8-resources/list
curl --location --request POST 'http://0.0.0.0:7003/messages?session_id=06a8da16c5554171b6618cbddb109747' \
--header 'Accept: application/json, text/event-stream' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"id": 6,
"method": "resources/list",
"params": {}
}'
9-resources/read
curl --location --request POST 'http://0.0.0.0:7003/mcp' \
--header 'Accept: application/json, text/event-stream' \
--header 'mcp-session-id: 80028fa0848245748eabfab76a1ecf38' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"id": 7,
"method": "resources/read",
"params": {
"uri": "config://app/settings"
}
}'
转载自 CSDN-专业IT技术社区
原文链接:https://blog.csdn.net/2301_77717148/article/details/170428665




