鱼C论坛

 找回密码
 立即注册
查看: 120|回复: 1

[基础知识] MCP官方示例+Cherry Studio尝试

[复制链接]
发表于 2025-4-29 16:34:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 快速收敛 于 2025-4-29 16:33 编辑

MCP文档Model Context Protocol
按文档一步步安装,并创建以下代码:
  1. from typing import Any
  2. import httpx
  3. from mcp.server.fastmcp import FastMCP

  4. # Initialize FastMCP server
  5. mcp = FastMCP("weather")

  6. # Constants
  7. NWS_API_BASE = "https://api.weather.gov"
  8. USER_AGENT = "weather-app/1.0"


  9. async def make_nws_request(url: str) -> dict[str, Any] | None:
  10.     """Make a request to the NWS API with proper error handling."""
  11.     headers = {
  12.         "User-Agent": USER_AGENT,
  13.         "Accept": "application/geo+json"
  14.     }
  15.     async with httpx.AsyncClient() as client:
  16.         try:
  17.             response = await client.get(url, headers=headers, timeout=30.0)
  18.             response.raise_for_status()
  19.             return response.json()
  20.         except Exception:
  21.             return None

  22. def format_alert(feature: dict) -> str:
  23.     """Format an alert feature into a readable string."""
  24.     props = feature["properties"]
  25.     return f"""
  26. Event: {props.get('event', 'Unknown')}
  27. Area: {props.get('areaDesc', 'Unknown')}
  28. Severity: {props.get('severity', 'Unknown')}
  29. Description: {props.get('description', 'No description available')}
  30. Instructions: {props.get('instruction', 'No specific instructions provided')}
  31. """



  32. @mcp.tool()
  33. async def get_alerts(state: str) -> str:
  34.     """Get weather alerts for a US state.

  35.     Args:
  36.         state: Two-letter US state code (e.g. CA, NY)
  37.     """
  38.     url = f"{NWS_API_BASE}/alerts/active/area/{state}"
  39.     data = await make_nws_request(url)

  40.     if not data or "features" not in data:
  41.         return "Unable to fetch alerts or no alerts found."

  42.     if not data["features"]:
  43.         return "No active alerts for this state."

  44.     alerts = [format_alert(feature) for feature in data["features"]]
  45.     return "\n---\n".join(alerts)

  46. @mcp.tool()
  47. async def get_forecast(latitude: float, longitude: float) -> str:
  48.     """Get weather forecast for a location.

  49.     Args:
  50.         latitude: Latitude of the location
  51.         longitude: Longitude of the location
  52.     """
  53.     # First get the forecast grid endpoint
  54.     points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
  55.     points_data = await make_nws_request(points_url)

  56.     if not points_data:
  57.         return "Unable to fetch forecast data for this location."

  58.     # Get the forecast URL from the points response
  59.     forecast_url = points_data["properties"]["forecast"]
  60.     forecast_data = await make_nws_request(forecast_url)

  61.     if not forecast_data:
  62.         return "Unable to fetch detailed forecast."

  63.     # Format the periods into a readable forecast
  64.     periods = forecast_data["properties"]["periods"]
  65.     forecasts = []
  66.     for period in periods[:5]:  # Only show next 5 periods
  67.         forecast = f"""
  68. {period['name']}:
  69. Temperature: {period['temperature']}°{period['temperatureUnit']}
  70. Wind: {period['windSpeed']} {period['windDirection']}
  71. Forecast: {period['detailedForecast']}
  72. """
  73.         forecasts.append(forecast)

  74.     return "\n---\n".join(forecasts)


  75. if __name__ == "__main__":
  76.     # Initialize and run the server
  77.     mcp.run(transport='stdio')
复制代码

在Cherry Studio添加MCP配置

MCP配置

MCP配置

测试勾选MCP,使用qianwen-max模型,可以看见模型还是很给力识别到了工具,并调用了工具函数get_forecast获取了纽约的天气,总结输出。

测试MCP

测试MCP

有点意思,但是不知道能干嘛!
期待小甲鱼出MCP教程

评分

参与人数 1鱼币 +2 贡献 +2 收起 理由
中英文泡椒 + 2 + 2

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2025-5-4 16:38:11 | 显示全部楼层
不错!!MCP案例欢迎多分享
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-12 19:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表