天气数据服务

一个基于MCP协议的天气数据服务,提供实时天气、天气预报和历史天气数据的查询功能。

  • by anuj-kumar-30
  • Jupyter Notebook
  • 本地部署
  • 更新于
在 GitHub 查看 anuj-kumar-30/llm_model_weather_info

使用说明

LLM_模型_死亡_信息


构建一个简单的MCP服务器,获取实时天气数据,为您提供最新预报,甚至允许您探索历史天气模式


备注
模型上下文协议(MCP)就像我们人工智能的USB端口。它允许我们的语言模型轻松插入现实世界的工具和API。
无论是获取天气数据、提取财务记录还是自动化任务管理,MCP都规范了LLM与这些工具的交互方式


分步教程

  1. 使用MCP设置python环境。
  2. 连接到天气API。
  3. 公开有用的工具,如当前天气、预报和历史数据。
  4. 使用MCP检查器测试和检查服务器。

1.建立环境

  • 创建 weather_mcp 说 。
  • cd 进入它
  • 创建 weather_server.py 文件。

2.编写MCP服务器代码

  • 天气MCP服务器将公开用于记录当前天气、预报天气和检索历史天气数据的工具。
from mcp.server.fastmcp import FastMCP
import requests
import json

# OpenWeatherMap API key
API_KEY = "162c5a92ddcc4822bfc66352c54b5deb"
BASE_URL = "http://api.openweathermap.org/data/3.0"

# Create an MCP server with a custom name
mcp = FastMCP("Weather Data Server")

# Function to fetch current weather data
@mcp.tool()
def get_current_weather(city: str) -> str:
    """
    Fetches the current weather for a given city
    """
    try:
        url = f"{BASE_URL}/weather?q={city}&appid={API_KEY}&units=metric"
        response = requests.get(url)
        data = response.json()
        if data.get("cod") != 200:
            return f"Error: {data.get('message')}"
        main_data = data['main']
        weather = data['weather'][0]['description']
        temperature = main_data['temp']
        humidity = main_data['humidity']
        return f"The current weather in {city} is {weather} with a temperature of {temperature}C and humidity of {humidity}%"

    except Exception as e:
        return f"Error fetching weather data: {str(e)}"
# Function to fetch historical weather data (last 5 days)
@mcp.tool()
def get_historical_waether(city: str):
    """
    Fetches historical weather data for a given city (last 5 days).
    """
    try:
        url = f"{BASE_URL}/forecast?q={city}&appid={API_KEY}&units=metric"
        response = requests.get(url)
        if data.get("cod") != "200":
            return f"Error: