当前位置: 首页 > news >正文

Fastmcp 案例二(SSe)

参考博客:https://blog.csdn.net/lingding_cn/article/details/147355620

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")

4、执行  python server-sse.py  (注意端口是3001)

/home/gz06401/miniforge3/envs/mcp/lib/python3.10/site-packages/fastmcp/server/server.py:213: DeprecationWarning: Providing `port` when creating a server is deprecated. Provide it when calling `run` or as a global setting instead.self._handle_deprecated_settings(╭─ FastMCP 2.0 ──────────────────────────────────────────────────────────────╮
│                                                                            │
│        _ __ ___ ______           __  __  _____________    ____    ____     │
│       _ __ ___ / ____/___ ______/ /_/  |/  / ____/ __ \  |___ \  / __ \    │
│      _ __ ___ / /_  / __ `/ ___/ __/ /|_/ / /   / /_/ /  ___/ / / / / /    │
│     _ __ ___ / __/ / /_/ (__  ) /_/ /  / / /___/ ____/  /  __/_/ /_/ /     │
│    _ __ ___ /_/    \__,_/____/\__/_/  /_/\____/_/      /_____(_)____/      │
│                                                                            │
│                                                                            │
│                                                                            │
│    🖥️  Server name:     Weather Service                                     │
│    📦 Transport:       SSE                                                 │
│    🔗 Server URL:      http://127.0.0.1:3001/sse/                          │
│                                                                            │
│    📚 Docs:            https://gofastmcp.com                               │
│    🚀 Deploy:          https://fastmcp.cloud                               │
│                                                                            │
│    🏎️  FastMCP version: 2.10.6                                              │
│    🤝 MCP version:     1.12.2                                              │
│                                                                            │
╰────────────────────────────────────────────────────────────────────────────╯[07/29/25 09:28:43] INFO     Starting MCP server 'Weather Service' with transport 'sse' on http://127.0.0.1:3001/sse/                                                                                          server.py:1448
INFO:     Started server process [1457209]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:3001 (Press CTRL+C to quit)
INFO:     127.0.0.1:57208 - "GET /sse HTTP/1.1" 307 Temporary Redirect

5、修改端口为3002,执行 fastmcp dev server-sse.py 

/home/gz06401/miniforge3/envs/mcp/lib/python3.10/site-packages/fastmcp/server/server.py:213: DeprecationWarning: Providing `port` when creating a server is deprecated. Provide it when calling `run` or as a global setting instead.self._handle_deprecated_settings(
Starting MCP inspector...
⚙️ Proxy server listening on localhost:6277
🔑 Session token: 159c96486bf1e5cc19ef10d230f55db377f5d17010ea9dd58be8f7e36387559cUse this token to authenticate requests or set DANGEROUSLY_OMIT_AUTH=true to disable auth🚀 MCP Inspector is up and running at:http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=159c96486bf1e5cc19ef10d230f55db377f5d17010ea9dd58be8f7e36387559c🌐 Opening browser...
New StreamableHttp connection request
Query parameters: {"url":"http://localhost:3001/sse","transportType":"streamable-http"}
Created StreamableHttp server transport
Created StreamableHttp client transport
Client <-> Proxy  sessionId: d6f4c93d-eaca-4c83-b71a-ccf783b4a991
Error from MCP server: Error: Error POSTing to endpoint (HTTP 405): Method Not Allowedat StreamableHTTPClientTransport.send (file:///home/gz06401/.npm/_npx/5a9d879542beca3a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js:284:23)at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
New SSE connection request. NOTE: The sse transport is deprecated and has been replaced by StreamableHttp
Query parameters: {"url":"http://localhost:3001/sse","transportType":"sse"}
SSE transport: url=http://localhost:3001/sse, headers={"Accept":"text/event-stream"}

打开调式页面: http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=159c96486bf1e5cc19ef10d230f55db377f5d17010ea9dd58be8f7e36387559c

image

 

http://www.vanclimg.com/news/1343.html

相关文章:

  • Anaconda历史版本
  • 输入未知数目的数据
  • 常见的结构光编解码算法
  • 七月
  • HCIE学习之路:一个NAT实验
  • HCIE学习之路:配置基于静态路由的GRE隧道
  • TOP10迪士尼动画电影下载_公主系列迪士尼电影大全列表在线观看
  • python中pandas包的基本用法
  • 如何用两年时间面试一个人(by jobleap.cn)
  • 2025年PLM合规性管理,6大策略,确保项目合法合规!
  • 如果你还有一些困惑 / 请贴着我的心倾听 - Urd
  • 【IEEE出版】第五届计算机应用、视觉与算法国际学术会议(CVAA 2025)
  • 【SPIE出版】第二届生物医药和智能技术国际学术会议(ICBIT 2025)
  • AI 赋能的云原生应用:技术趋势与实践
  • 移远EC800K, EG800AK的 openSDK 编译
  • V-Ray 7 安装图解教程 | 支持3ds Max 2021-2026 含语言补丁配置
  • 门店
  • 自定义控件----流动线条
  • 2023年八大最佳Codecademy替代平台
  • CF2018D 题解
  • Apple MagicKeyboard
  • 剑指offer-16、合并两个有序链表
  • 区分引用变量和内表变量
  • 线程
  • 进程
  • 进程API函数
  • 〆250729〆Windows 系统中 C:\ProgramData 目录说明
  • .NET 10 中的新增功能系列文章1——运行时中的新增功能
  • cv2安装测试的一个案例-面部检测
  • gitlab重置管理员root密码