FastMCP 案例七(Http请求验证)

参考:MCP协议_io.modelcontextprotocol.spec.mcperror: failed to w-CSDN博客

1、首先安装python环境

conda create -n mcp python=3.10

2、安装依赖

pip install fastmcp

3、编写一个server-sse.py

# -*- 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="sse")
View Code

4、启动程序

python server-sse.py
instead.
  self._handle_deprecated_settings(


╭─ FastMCP 2.0 ──────────────────────────────────────────────────────────────╮
│                                                                            │
│        _ __ ___ ______           __  __  _____________    ____    ____     │
│       _ __ ___ / ____/___ ______/ /_/  |/  / ____/ __ \  |___ \  / __ \    │
│      _ __ ___ / /_  / __ `/ ___/ __/ /|_/ / /   / /_/ /  ___/ / / / / /    │
│     _ __ ___ / __/ / /_/ (__  ) /_/ /  / / /___/ ____/  /  __/_/ /_/ /     │
│    _ __ ___ /_/    \__,_/____/\__/_/  /_/\____/_/      /_____(_)____/      │
│                                                                            │
│                                                                            │
│                                                                            │
│    🖥️  Server name:     Weather Service                                     │
│    📦 Transport:       SSE                                                 │
│    🔗 Server URL:      http://127.0.0.1:3002/sse/                          │
│                                                                            │
│    📚 Docs:            https://gofastmcp.com                               │
│    🚀 Deploy:          https://fastmcp.cloud                               │
│                                                                            │
│    🏎️  FastMCP version: 2.10.6                                              │
│    🤝 MCP version:     1.12.2                                              │
│                                                                            │
╰────────────────────────────────────────────────────────────────────────────╯


[07/30/25 17:32:39] INFO     Starting MCP server 'Weather Service' with transport 'sse' on http://127.0.0.1:3002/sse/                                                                                          server.py:1448
INFO:     Started server process [977638]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:3002 (Press CTRL+C to quit)

5、Curl验证Mcp

问题: Invalid request parameters 

解决方案:https://github.com/jlowin/fastmcp/issues?q=Invalid%20request%20parameters

  5.1 请求sse

curl http://localhost:3002/sse/

image

   5.2 拿到data ,拼接到地址,并进行初始化

curl -v -X POST http://localhost:3002/messages/?session_id=56610ae4668547dc91f49e58c834b8ce \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "mcp-session-id: your-session-id" \
  -d '{
        "jsonrpc": "2.0",
        "method": "notifications/initialized"
      }'

image

   5.3 查看mcp工具

curl http://localhost:3002/messages/?session_id=56610ae4668547dc91f49e58c834b8ce \
-H 'Content-Type: application/json' \
-d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list"
}'

image

   5.4 调用mcp 工具

curl http://localhost:3002/messages/?session_id=56610ae4668547dc91f49e58c834b8ce \
-H 'Content-Type: application/json' \
-d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": { "name": "get_weather", "arguments": {"city": "London"} }
}'

image

 

posted @ 2025-07-31 14:27  小白啊小白,Fighting  阅读(184)  评论(0)    收藏  举报