MCP - 在 Streamable HTTP 传输模式下启动并测试 MCP Serverr (二)

上一篇文章 初始化 MCP 环境 & 创建 MCP Server (一) 讲的是如何在 SSE 传输模式下启动 MCP Server。但官方计划废弃 SSE,推荐用 Streamable HTTP 替代。

下文将讲解如何在 Streamable HTTP 传输模式下启动 MCP Server。

1、Server 代码修改

  将  mcp.run(transport="sse")  改为  mcp.run(transport="http", path="/weather") 

  其中:

    1. 其中 transport="http" 是改成 Streamable HTTP 传输模
    2. path="/weather" 是 MCP 端点路径。如果不设置 path 默认是 /mcp
# -*- coding: utf-8 -*-
# @Time : 2025/7/28 17:09
# @Author : yangwenjie
# @Email : 邮箱
# @File : server-sse.py
# @Project : fastmcp
# weather_sse.py
from fastmcp import FastMCP
import random

# 创建MCP服务器实例,指定端口
mcp = FastMCP("Weather Service", port=3002)

# 模拟的天气数据
weather_data = {
    "New York": {"temp": range(10, 25), "conditions": ["sunny", "cloudy", "rainy"]},
    "London": {"temp": range(5, 20), "conditions": ["cloudy", "rainy", "foggy"]},
    "Tokyo": {"temp": range(15, 30), "conditions": ["sunny", "cloudy", "humid"]},
    "Sydney": {"temp": range(20, 35), "conditions": ["sunny", "clear", "hot"]},
}


@mcp.tool()
def get_weather(city: str) -> dict:
    """获取指定城市的当前天气"""
    if city not in weather_data:
        return {"error": f"无法找到城市 {city} 的天气数据"}

    data = weather_data[city]
    temp = random.choice(list(data["temp"]))
    condition = random.choice(data["conditions"])

    return {
        "city": city,
        "temperature": temp,
        "condition": condition,
        "unit": "celsius"
    }


@mcp.resource("weather://cities")
def get_available_cities() -> list:
    """获取所有可用的城市列表"""
    return list(weather_data.keys())


@mcp.resource("weather://forecast/{city}")
def get_forecast(city: str) -> dict:
    """获取指定城市的天气预报资源"""
    if city not in weather_data:
        return {"error": f"无法找到城市 {city} 的天气预报"}

    forecast = []
    for i in range(5):  # 5天预报
        data = weather_data[city]
        temp = random.choice(list(data["temp"]))
        condition = random.choice(data["conditions"])
        forecast.append({
            "day": i + 1,
            "temperature": temp,
            "condition": condition
        })

    return {
        "city": city,
        "forecast": forecast,
        "unit": "celsius"
    }


if __name__ == "__main__":
    # 使用SSE传输方式启动服务器
    mcp.run(transport="http", path="/weather")

2、启动 mcp server

  启动命令不变,还是

python server.py

3、命令行测试 mcp server

A)执行初始化

  Streamable HTTP 的初始化需要发送两个命令 initialize  d  notifications/initialized :

  • initialize :是客户端向服务器发起的第一个请求,目的是“握手”和“协商”。
  • notifications/initialized :是客户端在收到服务器对 initialize 的响应后,向服务器发送的一个确认通知,告知服务器“我已准备好,我们可以开始正式通信了”。

A.1)initialize

  执行如下命令

curl -i POST 'http://127.0.0.1:3002/weather' \
-H 'Accept: application/json, text/event-stream' \
-H 'Content-Type: application/json' \
-d '{
	"method":"initialize",
	"params":{
		"protocolVersion":"2025-06-18",
		"capabilities":{},
		"clientInfo":{
			"name":"mcp",
			"version":"0.1.0"
		}
	},
	"jsonrpc":"2.0",
	"id":0
}'

注意:

  • 其中  url 中的  weather   就是在代码中修改的 MCP 端点路径,也就是 path="/weather"。也可以在下图找到这个端点路径
  • curl 命令需要增加 -i 参数
  • 记录响应头中的  mcp-session-id 值,后面所有请求需要这个 id 做校验

image 

A.1)notifications/initialized

  执行如下命令

curl POST 'http://127.0.0.1:3002/weather' \
-H 'Accept: application/json, text/event-stream' \
-H 'Content-Type: application/json' \
-H 'Mcp-Session-Id: 78c703e2fc2744d78e7630c4b2ed6ebe' \
-d '{
	"method":"notifications/initialized",
	"jsonrpc":"2.0"
}'

  注意:78c703e2fc2744d78e7630c4b2ed6ebe 就是在上一步 initialize 返回 head 中得到的

image 

B)链接 MCP 服务器监听端点

  执行如下命令

curl GET 'http://127.0.0.1:3002/weather' \
-H 'Accept: application/json, text/event-stream' \
-H 'Accept: text/event-stream' \
-H 'Content-Type: application/json' \
-H 'Mcp-Session-Id: 78c703e2fc2744d78e7630c4b2ed6ebe'

  运行后如下图,多等一会可以看到 ping 消息。

image

C)列出 mcp sever 提供的所有 tools 列表

  同样如果想要保持 ping 不断,需要新开一个命令行,执行如下命令

curl POST 'http://127.0.0.1:3002/weather' \
-H 'Accept: application/json, text/event-stream' \
-H 'Content-Type: application/json' \
-H 'Mcp-Session-Id: 78c703e2fc2744d78e7630c4b2ed6ebe' \
-d '{
	"method":"tools/list",
	"jsonrpc":"2.0",
	"id":1
}'

  运行后如下图:

  1. 最右边是请求与服务器返回

image

   将 mcp 响应的 tools 列表格式化后如下:

{
	"jsonrpc": "2.0",
	"id": 1,
	"result": {
		"tools": [{
			"name": "get_weather",
			"description": "获取指定城市的当前天气",
			"inputSchema": {
				"properties": {
					"city": {
						"title": "City",
						"type": "string"
					}
				},
				"required": ["city"],
				"type": "object"
			},
			"outputSchema": {
				"additionalProperties": true,
				"type": "object"
			},
			"_meta": {
				"_fastmcp": {
					"tags": []
				}
			}
		}]
	}
}

 

 

 其它的 执行 tools、查询 resource 等就不在这里详写了,感兴趣的同学可以自行试试~~~

 

源代码: mcp_server_http.zip

 

 

  

posted @ 2025-09-15 14:16  rslai  阅读(235)  评论(0)    收藏  举报