14_weather_mcp_server.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. """天气查询 MCP 服务器"""
  3. import json
  4. import requests
  5. import os
  6. from datetime import datetime
  7. from typing import Dict, Any
  8. from hello_agents.protocols import MCPServer
  9. # 创建 MCP 服务器
  10. weather_server = MCPServer(name="weather-server", description="真实天气查询服务")
  11. CITY_MAP = {
  12. "北京": "Beijing", "上海": "Shanghai", "广州": "Guangzhou",
  13. "深圳": "Shenzhen", "杭州": "Hangzhou", "成都": "Chengdu",
  14. "重庆": "Chongqing", "武汉": "Wuhan", "西安": "Xi'an",
  15. "南京": "Nanjing", "天津": "Tianjin", "苏州": "Suzhou"
  16. }
  17. def get_weather_data(city: str) -> Dict[str, Any]:
  18. """从 wttr.in 获取天气数据"""
  19. city_en = CITY_MAP.get(city, city)
  20. url = f"https://wttr.in/{city_en}?format=j1"
  21. response = requests.get(url, timeout=10)
  22. response.raise_for_status()
  23. data = response.json()
  24. current = data["current_condition"][0]
  25. return {
  26. "city": city,
  27. "temperature": float(current["temp_C"]),
  28. "feels_like": float(current["FeelsLikeC"]),
  29. "humidity": int(current["humidity"]),
  30. "condition": current["weatherDesc"][0]["value"],
  31. "wind_speed": round(float(current["windspeedKmph"]) / 3.6, 1),
  32. "visibility": float(current["visibility"]),
  33. "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  34. }
  35. # 定义工具函数
  36. def get_weather(city: str) -> str:
  37. """获取指定城市的当前天气"""
  38. try:
  39. weather_data = get_weather_data(city)
  40. return json.dumps(weather_data, ensure_ascii=False, indent=2)
  41. except Exception as e:
  42. return json.dumps({"error": str(e), "city": city}, ensure_ascii=False)
  43. def list_supported_cities() -> str:
  44. """列出所有支持的中文城市"""
  45. result = {"cities": list(CITY_MAP.keys()), "count": len(CITY_MAP)}
  46. return json.dumps(result, ensure_ascii=False, indent=2)
  47. def get_server_info() -> str:
  48. """获取服务器信息"""
  49. info = {
  50. "name": "Weather MCP Server",
  51. "version": "1.0.0",
  52. "tools": ["get_weather", "list_supported_cities", "get_server_info"]
  53. }
  54. return json.dumps(info, ensure_ascii=False, indent=2)
  55. # 注册工具到服务器
  56. weather_server.add_tool(get_weather)
  57. weather_server.add_tool(list_supported_cities)
  58. weather_server.add_tool(get_server_info)
  59. if __name__ == "__main__":
  60. weather_server.run()