第三十三章: MCP HTTP消息传输方式介绍

1. MCP HTTP消息传输方式

⻓期以来,MCP⼯具的异地通信主要是以SSE传输⽅式为主,这种通信⽅法既没有多通道并发同时也不够稳定,很难真正的适⽤于企业级应⽤场景。因此,在2⽉初,在MCP官⽅GitHub项⽬主⻚上,就有开发者提出了采⽤更先进的流式HTTP传输⽅法代替SSE传输的技术⽅案,相⽐SSE传输,HTTP流式传输并发更⾼、通信更加稳定,同时也更容易集成和部署,这也是当代服务器与客⼾端异地通信的最佳解决⽅案。

但流式HTTP MCP服务器功能复杂,相关SDK的研发难度也很⾼,因此在2025年的3⽉,MCP官⽅⾸先发布了MCP的流式HTTP通信协议,其中详细说明了HTTP流式传输的基本协议。

地址:https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/basic/transports.mdx#streamable-http

然后在2025年5⽉9号的1.8.0版本更新中,正式在SDK中加⼊了HTTP流式MCP服务器的相关功能⽀持。⾃ 此开发者就可以通过MCP SDK,⾼效快速开发流式HTTP MCP服务器,并顺利进⾏多通道并发的企业 级MCP⼯具部署。毫⽆疑问,这将是MCP技术迈向企业级应⽤的⾄关重要的⼀步。

地址:https://github.com/modelcontextprotocol/python-sdk/releases/tag/v1.8.0

2. 基于HTTP的MCP服务器创建

创建项⽬⽂件:

bash 复制代码
 # cd /root/autodl-tmp/mcp/mcp-http 
 uv init mcp-weather-http-xigua
 cd mcp-weather-http-xigua
 #  创建虚拟环境   
 uv venv  
 #  激活虚拟环境   
 source .venv/bin/activate  
 uv add mcp httpx 

这⾥我们采⽤src_layer的⻛格进⾏项⽬⽂件编排,因此需要删除main.py,并创建 mcp_weather_http_xigua⽬录。

bash 复制代码
mkdir -p ./src/mcp_weather_http_xigua
cd ./src/mcp_weather_http_xigua

并在 init.py 中写⼊

bash 复制代码
 from .server import main

⽽在 main.py 中写⼊

bash 复制代码
 from mcp_weather_http_xigua import main
 main()

server.py 文件中写如下代码:

bash 复制代码
import contextlib
import logging
import os
from collections.abc import AsyncIterator

import anyio
import click
import httpx
import mcp.types as types
from mcp.server.lowlevel import Server
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.types import Receive, Scope, Send

# ---------------------------------------------------------------------------
# Weather helpers
# ---------------------------------------------------------------------------
OPENWEATHER_URL = "https://api.openweathermap.org/data/2.5/weather"
DEFAULT_UNITS = "metric"  # use Celsius by default
DEFAULT_LANG = "zh_cn"  # Chinese descriptions

async def fetch_weather(city: str, api_key: str) -> dict[str, str]:
    """Call OpenWeather API and return a simplified weather dict.

    Raises:
        httpx.HTTPStatusError: if the response has a non-2xx status.
    """
    params = {
        "q": city,
        "appid": api_key,
        "units": DEFAULT_UNITS,
        "lang": DEFAULT_LANG,
    }
    async with httpx.AsyncClient(timeout=10) as client:
        r = await client.get(OPENWEATHER_URL, params=params)
        r.raise_for_status()
        data = r.json()
    # Extract a concise summary
    weather_main = data["weather"][0]["main"]
    description = data["weather"][0]["description"]
    temp = data["main"]["temp"]
    feels_like = data["main"]["feels_like"]
    humidity = data["main"]["humidity"]
    return {
        "city": city,
        "weather": weather_main,
        "description": description,
        "temp": f"{temp}°C",
        "feels_like": f"{feels_like}°C",
        "humidity": f"{humidity}%",
    }

@click.command()
@click.option("--port", default=3000, help="Port to listen on for HTTP")
@click.option(
    "--api-key",
    envvar="OPENWEATHER_API_KEY",
    required=True,
    help="OpenWeather API key (or set OPENWEATHER_API_KEY env var)",
)
@click.option(
    "--log-level",
    default="INFO",
    help="Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)",
)
@click.option(
    "--json-response",
    is_flag=True,
    default=False,
    help="Enable JSON responses instead of SSE streams",
)
def main(port: int, api_key: str, log_level: str, json_response: bool) -> int:
    """Run an MCP weather server using Streamable HTTP transport."""

    # ---------------------- Configure logging ----------------------
    logging.basicConfig(
        level=getattr(logging, log_level.upper()),
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    )
    logger = logging.getLogger("weather-server")

    # ---------------------- Create MCP Server ----------------------
    app = Server("mcp-streamable-http-weather")

    # ---------------------- Tool implementation -------------------
    @app.call_tool()
    async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
        """Handle the 'get-weather' tool call."""
        ctx = app.request_context
        city = arguments.get("location")
        if not city:
            raise ValueError("'location' is required in arguments")

        # Send an initial log message so the client sees streaming early.
        await ctx.session.send_log_message(
            level="info",
            data=f"Fetching weather for {city}...",
            logger="weather",
            related_request_id=ctx.request_id,
        )

        try:
            weather = await fetch_weather(city, api_key)
        except Exception as err:
            # Stream the error to the client and re-raise so MCP returns error.
            await ctx.session.send_log_message(
                level="error",
                data=str(err),
                logger="weather",
                related_request_id=ctx.request_id,
            )
            raise

        # Stream a success notification (optional)
        await ctx.session.send_log_message(
            level="info",
            data="Weather data fetched successfully!",
            logger="weather",
            related_request_id=ctx.request_id,
        )

        # Compose human-readable summary for the final return value.
        summary = (
            f"{weather['city']}:{weather['description']},温度 {weather['temp']},"
            f"体感 {weather['feels_like']},湿度 {weather['humidity']}。"
        )

        return [
            types.TextContent(type="text", text=summary),
        ]

    # ---------------------- Tool registry -------------------------
    @app.list_tools()
    async def list_tools() -> list[types.Tool]:
        """Expose available tools to the LLM."""
        return [
            types.Tool(
                name="get-weather",
                description="查询指定城市的实时天气(OpenWeather 数据)",
                inputSchema={
                    "type": "object",
                    "required": ["location"],
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "城市的英文名称,如 'Beijing'",
                        }
                    },
                },
            )
        ]

    # ---------------------- 流式会话管理器配置 -----------------------
    session_manager = StreamableHTTPSessionManager(
        app=app,
        event_store=None,  # 无状态;不保存历史事件
        json_response=json_response,
        stateless=True,
    )

    async def handle_streamable_http(scope: Scope, receive: Receive, send: Send) -> None:  # noqa: D401,E501
        await session_manager.handle_request(scope, receive, send)

    # ---------------------- Lifespan Management --------------------
    @contextlib.asynccontextmanager
    async def lifespan(app: Starlette) -> AsyncIterator[None]:
        async with session_manager.run():
            logger.info("Weather MCP server started! 🚀")
            try:
                yield
            finally:
                logger.info("Weather MCP server shutting down...")

    # ---------------------- ASGI app + Uvicorn ---------------------
    ## 构建Starlette Web应用
    ## 这是将MCP服务挂载到你的⽹站 /mcp
    ## ⽤⼾访问这个路径时,就会进⼊刚才创建的MCP会话管理器
    starlette_app = Starlette(
        debug=False,
        routes=[Mount("/mcp", app=handle_streamable_http)],
        lifespan=lifespan,
    )

    import uvicorn
    ## 启动HTTP 服务器
    uvicorn.run(starlette_app, host="0.0.0.0", port=port)

    return 0

if __name__ == "__main__":
    main()
  1. 代码解释:
bash 复制代码
import contextlib
import logging
import os
from collections.abc import AsyncIterator

import anyio
import click
import httpx
import mcp.types as types
from mcp.server.lowlevel import Server
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.types import Receive, Scope, Send

这些都是"⼯具箱",你可以理解为在写⼀个天⽓⼩程序之前,先导⼊⼀些现成的功能组件:

  • httpx :⽤来联⽹查天⽓。
  • hmcp :提供了让⼤模型调⽤⼯具的能⼒。
  • hstarlette :帮你搭建HTTP⽹络服务。
  • hclick :帮你写命令⾏参数,⽐如 --api-key=xxx 。
  • h其它模块则帮助你处理异步任务、打印⽇志、读取环境变量等。
  1. 代码解释
bash 复制代码
async def fetch_weather(city: str, api_key: str) -> dict[str, str]:

解释:

这个函数是你天⽓服务器的核⼼功能⸺根据城市名去OpenWeather⽹站查询天⽓。

它⽤httpx.AsyncClient 这个⼯具联⽹发请求,返回的结果包括:天⽓情况、⽓温、湿度等。

  1. 代码解释
bash 复制代码
@click.command()  
@click.option("--port", default=3000, ...)  
@click.option("--api-key", envvar="OPENWEATHER_API_KEY", ...)  
def main(port, api_key, ...):

这是你运⾏服务器的"⼊⼝",你以后运⾏时只需要:

bash 复制代码
python weather_mcp_streamable_http_server.py --port 3000 --api-key xxxx
  1. 代码解释

MCP⼯具注册:让⼤模型能调⽤ get-weather

bash 复制代码
 @app.call_tool()  
 async def call_tool(name: str, arguments: dict):

这就是你注册给⼤语⾔模型⽤的"⼯具",名字叫 get-weather 。

当模型说"我需要查北京的天⽓",MCP就会触发这个函数。

你在⾥⾯解析出 "location" 字段,然后调⽤上⾯那个 fetch_weather() 函数拿数据。

它还有⼀个亮点功能:会实时往客⼾端推送消息:

bash 复制代码
 await ctx.session.send_log_message(...)

这些就是所谓的"流式⽇志通知"(⽐如"正在查询..."、"成功了!")。

  1. 代码解释

告诉客户端有哪些工具可以调用

bash 复制代码
 @app.list_tools()  
 async def list_tools() -> list[types.Tool]:

MCP会定期问你:"你这⾥都有哪些⼯具可以⽤?"

你就返回⼀个叫 get-weather 的⼯具描述,告诉模型: 输⼊需要⼀个location,是城市名。

  1. 代码解释

流式会话管理器配置

bash 复制代码
session_manager = StreamableHTTPSessionManager(  
app=app, 
event_store=None, 
json_response=json_response, 
stateless=True,  )

这⼀句创建了MCP的"HTTP会话处理中⼼",负责处理所有 /mcp 路由的请求;

stateless=True 表⽰不保存历史对话,每次都是新请求;

json_response=False 表⽰⽤流式SSE(你也可以改成⼀次性JSON响应)。

  1. 代码解释

构建StarletteWeb应⽤

bash 复制代码
starlette_app = Starlette(  
routes=[Mount("/mcp", app=handle_streamable_http)], 
lifespan=lifespan,  )

这是将MCP服务挂载到你的⽹站/mcp 路径上;

⽤⼾访问这个路径时,就会进⼊刚才创建的MCP会话管理器。

  1. 代码解释

启动服务器

bash 复制代码
import uvicorn  uvicorn.run(starlette_app, host="0.0.0.0", port=port)

这⾏代码启动你的MCPHTTP服务器,监听指定端⼝;

如果你传的是--port 3000 ,访问路径就是:

bash 复制代码
http://localhost:3000/mcp

同时需要回到主⽬录,修改项⽬配置⽂件 pyproject.toml :

bash 复制代码
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "mcp-weather-http-xigua"
version = "1.1.0"
description = "输入OpenWeather-API-KEY,获取天气信息。"
readme = "README.md"
requires-python = ">=3.9"
dependencies = [
    "httpx>=0.28.1",
    "mcp>=1.8.0",
]

[project.scripts]
mcp-weather-http-xigua = "mcp_weather_http_xigua:main"

[tool.setuptools]
package-dir = {"" = "src"}

[tool.setuptools.packages.find]
where = ["src"]

3. 基于HTTP的MCP服务器测试

在创建完 server.py 后,我们可以开启服务并进⾏测试。需要注意的是,我们需要先开启流式 HTTP MCP服务器,然后再开启Inspector。

bash 复制代码
## 安装Inspector
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo bash -
sudo apt install -y nodejs

开启流式HTTP MCP服务器:

bash 复制代码
 
 #  回到项⽬主⽬录   
 # cd /root/autodl-tmp/mcp/mcp-http/mcp-weather-http-xigua
 uv run ./src/mcp_weather_http_xigua/server.py --api-key xxxxxxxxxxxxxxxxxxxxxxxx

开启Inspector

bash 复制代码
 #  回到项⽬主⽬录   
 # cd /root/autodl-tmp/mcp/mcp-http/mcp-weather-http
 # source .venv/bin/activate 
 npx -y @modelcontextprotocol/inspector uv run main.py --api-key xxxxxxxxxxxxxxxxxxxxxxxx

AutlDL ssh工具

然后打开Inspector,并选择HTTP流式模式,选择默认运⾏地址: http://localhost:3000/mcpmcp ,然后点击connect:

4. 基于HTTP的MCP服务器应用

接下来即可在异地环境(也可以是本地)通过HTTP⽅式调⽤MCP服务了。这⾥以本地安装的 Cherry Studio为例,进⾏调⽤演⽰。此处需要保持远程流式HTTP MCP服务器处于开启状态,然后按 照如下流程进⾏调⽤。 ⾸先点击添加服务器:

相关推荐
Danny转行做跨境12 小时前
AI 写崩 3 次后: 5 条铁律 + 单测锁版实录
跨境电商·mcp·sorftime
xrlfreedom13 小时前
MCP 面试高频考点:为服务编写可重复执行的集成测试,如何把 OAuth 2.1 与提示注入防护一起测进去
mcp·oauth 2.1·提示注入防护
Eastmount1 天前
[智能体攻防实战] 四.IDA Pro-MCP和CodeBuddy配置教程与逆向分析实例
智能体·mcp·codebuddy·智能体安全
BruceVan1 天前
别再一张张截图拼效果图了,让 AI 自己做高保真 UI 流程图
ai编程·mcp
xrlfreedom2 天前
MCP 面试高频考点:本地 AI 助手安全访问文件,JSON-RPC 与提示注入防护怎么配合?
mcp·json-rpc·提示注入防护
BruceVan3 天前
逛商店还是让 Agent 帮你挑?两个 DSH 插件市场的真实差别
ai编程·deepseek·mcp
BruceVan3 天前
一句话,DSH 就把架构图画好了,还能接着手改
ai编程·deepseek·mcp
莪_幻尘4 天前
MCP Server 从 0 到 1:134 行代码,把 GitHub API 接成 Agent 的工具
agent·ai编程·mcp
BruceVan4 天前
别再截图贴报错了,让 AI 自己打开 Chrome 查 bug
chrome·ai编程·mcp