当前位置: 首页 > 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.sczhlp.com/news/376.html

相关文章:

  • 编译安装 pg_stat_statements
  • Anaconda历史版本
  • 输入未知数目的数据
  • 常见的结构光编解码算法
  • 七月
  • 【UNR #3】配对树 题解
  • 基于Java+Springboot+Vue开发的美容院-美甲店预约管理系统源码+运行步骤
  • 基于YOLOv8的狗狗品种(多达60种常见犬类)品种鉴别识别项目|完整源码数据集+PyQt5界面+完整训练流程+开箱即用!
  • 公钥和私钥的部分作用
  • 从0开始构建技术
  • Solon 集成 LiteFlow:轻量级工作流引擎的极简实践指南
  • 街道【概念】
  • 解决 EXSI 意外断电后虚拟机无法启动,提示对象类型需要托管的 I/O - 清风
  • P3412 仓鼠找sugar II 题解
  • 中国科学院院士夏培肃|学术成长历程的关键事件、重要节点、师承关系
  • 【深度解析】文件安全传输网关解决方案,安全合规哪家强?
  • 非常棒的unity插件——体素世界
  • 开源新旗舰 GLM-4.5:不想刷榜,只想干活儿
  • Nodejs安装笔记
  • 「中望CAD机械版2025最新版下载+浮动许可激活教程」
  • 2025最新文件摆渡系统评测:这5大功能让跨网传输更高效
  • Fastmcp 案例三(DeepChat调式 ,结合案例二)
  • webdriver中的三种等待
  • Python 操作 PDF 文档:主流库选型指南 - E
  • claudecode使用mcp
  • 服务器数据同步:安全高效方案看这里!
  • 微软云(Windows Azure)计算平台的结构及分析
  • 大师 - 杯酒
  • 常用网址
  • 教师资格证考试面试报名流程