Sponsored by Deepsite.site

MCP Server Weather

Created By
michaelwybraniec6 months ago
Content

MCP Server Weather

Python License: MIT

A simple weather microservice built with FastMCP, providing weather forecasts and current weather data using the Open-Meteo API.


Table of Contents


Features

  • Get weather forecast for any location (latitude/longitude)
  • Get current weather for any location (latitude/longitude)
  • Asynchronous HTTP requests for fast responses
  • Easy integration as an MCP tool

Requirements

  • Python >= 3.13
  • httpx >= 0.28.1
  • mcp[cli] >= 1.9.2

Installation

  1. Clone the repository:
    git clone https://github.com/yourusername/mcp-server-weather.git
    cd mcp-server-weather
    
  2. (Optional) Create and activate a virtual environment:
    python3 -m venv .venv
    source .venv/bin/activate
    
  3. Install dependencies:
    pip install -r requirements.txt
    # or, if using pyproject.toml
    pip install .
    

Usage

Run the server:

python server.py

The server exposes two main tools:

1. Get Forecast

Fetches a daily weather forecast for a given latitude and longitude.

@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str
  • Returns: Formatted string with daily max/min temperature, precipitation, and weather code.

Example Output:

Date: 2024-06-01
Max Temperature: 22°C
Min Temperature: 14°C
Precipitation: 0.5 mm
Weather Code: 2
---
Date: 2024-06-02
Max Temperature: 20°C
Min Temperature: 13°C
Precipitation: 1.2 mm
Weather Code: 3

2. Get Current Weather

Fetches current weather data for a given latitude and longitude.

@mcp.tool()
async def get_current_weather(latitude: float, longitude: float) -> str
  • Returns: JSON string with current weather details (temperature, wind, humidity, etc.)

Example Output:

{
  "current": {
    "temperature_2m": 21.3,
    "is_day": 1,
    "showers": 0.0,
    "cloud_cover": 45,
    "wind_speed_10m": 5.2,
    "wind_direction_10m": 180,
    "pressure_msl": 1012.3,
    "snowfall": 0.0,
    "precipitation": 0.0,
    "relative_humidity_2m": 60,
    "apparent_temperature": 21.0,
    "rain": 0.0,
    "weather_code": 2,
    "surface_pressure": 1012.3,
    "wind_gusts_10m": 8.0
  }
}

API & Tool Schema

get_forecast

  • Input:
    • latitude (float)
    • longitude (float)
  • Output:
    • Formatted string with daily weather data (see example above)

get_current_weather

  • Input:
    • latitude (float)
    • longitude (float)
  • Output:
    • JSON object with current weather data (see example above)

Project Structure

.
├── server.py           # Main server code, defines weather tools
├── pyproject.toml      # Project metadata and dependencies
├── README.md           # Project documentation
├── project.md          # Project code summary
├── .gitignore          # Git ignore file
├── .python-version     # Python version file
├── uv.lock             # Lock file for uv package manager
├── .venv/              # Virtual environment (not committed)
└── __pycache__/        # Python cache files

Architecture

graph TD;
    A[Client (Claude Desktop, etc)] -- stdio --> B(MCP Server: server.py)
    B -- HTTPX async requests --> C(Open-Meteo API)
    B -- Exposes tools --> D[LLM/Client]
    B -- Returns weather data --> A
  • Client: Connects to the MCP server via stdio (e.g., Claude Desktop)
  • MCP Server: Handles requests, exposes tools, fetches data from Open-Meteo
  • Open-Meteo API: Provides weather and forecast data
  • LLM/Client: Consumes the data and generates responses

Tutorial

Creating an MCP Server Using Python and the Open-Meteo API

MCP servers extend the capabilities of language models by connecting them to data sources and services.

MCP servers expose three main primitives:

Resources (client-controlled)

  • Exposes data to be used as context to clients on request.
  • Use a resource when you want to passively expose data or content to an MCP client and let the client choose when to access it.

Tools (model-controlled)

  • Exposes executable functionality to client models.
  • Use a tool when you want the client to perform an action, for example to request content from an API, transform data, or send an email.

Prompts (user-controlled)

  • Exposes reusable prompts and workflows to users.
  • Use a prompt when you want the client to surface prompts and workflows to the user, for example to streamline interaction with a resource or tool.

Example: Weather Data to Natural Language

LLMs are great for transforming data into natural language. For example, they can translate weather data like temperature, wind speed, dew point, etc. into descriptions of what the weather will feel like and recommendations on what type of clothing to wear.

Step-by-Step Tutorial

0. Requirements

  • Claude.ai account (MCP support is available for all account types)
  • Claude Desktop app (macOS/Windows)
  • Code editor (e.g., VS Code)
  • uv (Rust-based Python package manager)
    • macOS: brew install uv
    • Windows: winget install --id=astral-sh.uv -e

1. Setting up the project

To set up your project, open your code editor to the folder you want to add your project. Then follow these steps to set up your project:

Create a new folder called mcp-server-weather using the editor tools or terminal:

mkdir mcp-server-weather

Navigate to the folder in terminal:

cd mcp-server-weather

Initiate a new uv project:

uv init

Create a virtual environment using uv:

uv venv

Start the virtual environment:

source .venv/bin/activate

Note: To stop the virtual environment, run deactivate in terminal.

Install the Python MCP SDK with the CLI extension and additional Python dependencies in the virtual environment:

uv add "mcp[cli]" httpx

2. Building the weather MCP server

Create server.py and add the following scaffolding:

from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("weather")

# ... your code here ...

if __name__ == "__main__":
    mcp.run(transport='stdio')

Add constants and helper function

OPENMETEO_API_BASE = "https://api.open-meteo.com/v1"
USER_AGENT = "weather-app/1.0"

# Helper function to make a request to the Open-Meteo API
async def make_openmeteo_request(url: str) -> dict[str, Any] | None:
    """Make a request to the Open-Meteo API with proper error handling."""
    headers = {
        "User-Agent": USER_AGENT,
        "Accept": "application/json"
    }
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except Exception:
            return None

Add tools

@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
    # ...

@mcp.tool()
async def get_current_weather(latitude: float, longitude: float) -> str:
    """Get current weather for a location.

    Args:
        latitude: Latitude of the location
        longitude: Longitude of the location
    """
    
    url = f"{OPENMETEO_API_BASE}/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m,is_day,showers,cloud_cover,wind_speed_10m,wind_direction_10m,pressure_msl,snowfall,precipitation,relative_humidity_2m,apparent_temperature,rain,weather_code,surface_pressure,wind_gusts_10m"
    
    data = await make_openmeteo_request(url)

    if not data:
        return "Unable to fetch current weather data for this location."

    return data

3. Testing and running the MCP server

mcp dev server.py

4. Extending the MCP server

  • Add more tools (e.g., get_location)
  • Use the Open-Meteo Geocoding API for location search

Contributing

Contributions are welcome! Please open an issue or submit a pull request for improvements, bug fixes, or new features.

License

MIT

Author

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Tavily Mcp
ChatWiseThe second fastest AI chatbot™
WindsurfThe new purpose-built IDE to harness magic
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
CursorThe AI Code Editor
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Serper MCP ServerA Serper MCP Server
Playwright McpPlaywright MCP server
Amap Maps高德地图官方 MCP Server
DeepChatYour AI Partner on Desktop
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.