1
0

weather_mcp.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """
  2. 自定义MCP服务器示例
  3. 这是一个简单的MCP服务器,提供天气信息查询。
  4. 用于演示如何创建自己的MCP服务器。
  5. 运行方式:
  6. python my_mcp_server.py
  7. 或者作为MCP服务器被客户端调用:
  8. MCPClient(["python", "weather_mcp.py"])
  9. """
  10. from fastmcp import FastMCP
  11. from weather import Weather
  12. # 创建MCP服务器实例
  13. mcp = FastMCP("WeatherServer")
  14. # ==================== 数学工具 ====================
  15. @mcp.tool()
  16. def query_wearher(city_name: str):
  17. """
  18. 查询天气
  19. Args:
  20. city_name: 城市名称
  21. Returns:
  22. 天气信息
  23. """
  24. weather = Weather()
  25. # 查询天气详细信息(字典格式)
  26. weather_details = weather.get_weather_details(city_name)
  27. # 如果查询成功,返回详细信息
  28. if "error" not in weather_details:
  29. return weather_details
  30. else:
  31. # 如果查询失败,返回格式化字符串
  32. return weather.get_weather(city_name)
  33. @mcp.tool()
  34. def get_weather_details(city_name: str):
  35. """
  36. 获取详细的天气数据(结构化格式)
  37. Args:
  38. city_name: 城市名称
  39. Returns:
  40. 包含详细天气数据的字典
  41. """
  42. weather = Weather()
  43. return weather.get_weather_details(city_name)
  44. @mcp.resource("info://capabilities")
  45. def get_capabilities() -> str:
  46. """
  47. 获取指定城市的天气信息
  48. Returns:
  49. 能力列表的文本描述
  50. """
  51. capabilities = """
  52. 服务器能力列表:
  53. 天气查询能力:
  54. - query_weather: 获取指定城市的天气信息(结构化数据)
  55. - get_weather_details: 获取详细的天气数据(字典格式)
  56. """
  57. return capabilities.strip()
  58. # ==================== 提示词模板 ====================
  59. @mcp.prompt()
  60. def weather_helper() -> str:
  61. """
  62. 天气信息查询提示词
  63. Returns:
  64. 提示词模板
  65. """
  66. return """你是一个天气查询助手。你可以使用以下工具:
  67. - query_weather(city_name): 获取指定城市的天气信息
  68. 请根据用户的问题选择合适的工具进行任务执行。"""
  69. # ==================== 主程序 ====================
  70. if __name__ == "__main__":
  71. # 运行MCP服务器
  72. # FastMCP会自动处理stdio传输
  73. mcp.run()