LLM_Model_Weather_Info

anuj-kumar-30/LLM_Model_Weather_Info

3.2

If you are the rightful owner of LLM_Model_Weather_Info and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

The Model Context Protocol (MCP) server is designed to facilitate seamless interaction between language models and real-world tools and APIs, such as weather data services.

Tools
2
Resources
0
Prompts
0

LLM_Model_Weather_Info


Building a simple MCP server that fetches real-time weather data, gives you the latest forecasts, and even allows you to explore historical weather patterns


NOTE
Model Context Protocol(MCP) is like a USB port for our AI. It allows our language models to plug into real-world tools and APIs with ease.
Be it fetching weather data, pulling financial records, or automating task management, MCP standardizes how LLMs interact with these tools


Step-By-Step Tutorial

  1. Set up a python environment with MCP.
  2. Connect to a weather API.
  3. Expose useful tools like current weather, forecast, and historical data.
  4. Test and inspect the server using MCP inspector.

1. Setting up the Environment

  • create weather_mcp dir.
  • cd into it
  • create weather_server.py file.

2. Writing the MCP Server Code

  • The weather MCP server, will expose tools for featching current weather, forecasting weather, and retrieving historical weather data.
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: