Skip to main content
Glama

MCP Weather Server

by ramonbnuezjr
  • Apple
  • Linux

MCP Weather Server

Project Overview

This project implements a Model Context Protocol (MCP) server designed to provide current weather information for a given location. It acts as a standardized interface, enabling AI agents or other client applications to fetch weather data without needing to interact directly with various external weather APIs. The core idea is to abstract the complexities of external services, offering a consistent protocol for data retrieval and error handling.

The server is built using Python with the FastAPI framework and currently retrieves weather data from the OpenWeatherMap API. While this project focuses on a weather tool, the MCP architecture is designed to be extensible, serving as a standardized gateway for an AI agent to access various tools and APIs (both internal and external) through a consistent protocol.

Key Features:

  • Standardized MCP Interface: Adheres to a defined request/response structure (using Pydantic models) for easy integration.
  • Weather Data Retrieval: Fetches current temperature, conditions, humidity, wind speed, and pressure.
  • Abstraction of External API: Shields the client from the specifics of the OpenWeatherMap API.
  • Error Handling: Provides clear, standardized MCP error messages for issues like invalid locations or API key problems.
  • Asynchronous Operations: Uses httpx for non-blocking calls to the external weather API.
  • Data Validation: Leverages Pydantic for request and response data validation.
  • Configuration Management: Loads sensitive configurations (like API keys) from a .env file.
  • Comprehensive Testing: Includes a client simulation script and a pytest suite for unit and integration tests.
  • Simple Agent CLI: A command-line interface (weather_agent_cli.py) demonstrates how an agent can interact with this MCP server.

Architecture

The server facilitates communication as follows:

  1. Client (AI Agent/Test Script) sends an MCP-formatted JSON request to the /mcp/weather endpoint.
  2. MCP Weather Server (this application) parses the request and extracts necessary parameters (e.g., location).
  3. The MCP server's "weather tool" handler calls the OpenWeatherMap API with the location and its configured API key.
  4. OpenWeatherMap returns the raw weather data.
  5. The MCP server transforms this raw data into the standardized MCP response format.
  6. The MCP server sends the MCP-formatted JSON response back to the client.
sequenceDiagram participant Client as AI Agent / Test Script participant MCPServer as MCP Weather Server (FastAPI) participant ExtWeatherAPI as OpenWeatherMap API Client->>+MCPServer: 1. Request Weather (MCP Format via HTTP POST) MCPServer->>+ExtWeatherAPI: 2. Fetch Weather Data (HTTP GET with API Key) ExtWeatherAPI-->>-MCPServer: 3. Weather Data Response (JSON) MCPServer-->>-Client: 4. Weather Information (MCP Format via HTTP Response)

Prerequisites

  • Python 3.8+ (Python 3.13 used during development)
  • An API key from OpenWeatherMap (for the "Current Weather Data" API).

Setup and Installation

  1. Clone the repository (if applicable):
    git clone <your-repository-url> cd mcp-weather-server
  2. Create and activate a virtual environment:
    python3 -m venv venv source venv/bin/activate # On macOS/Linux # For Windows (Command Prompt): venv\Scripts\activate.bat # For Windows (PowerShell): venv\Scripts\Activate.ps1
  3. Install dependencies: Ensure you have a requirements.txt file (see "Project Structure" below for typical contents). Then run:
    pip install -r requirements.txt
  4. Configure API Key:
    • Create a .env file in the root of the project directory (e.g., mcp-weather-server/.env).
    • Add your OpenWeatherMap API key to it:
      # .env OPENWEATHERMAP_API_KEY="YOUR_ACTUAL_API_KEY_HERE"
    • Important: Ensure .env is listed in your .gitignore file to prevent committing your API key to version control.

Running the MCP Server

  1. Ensure your virtual environment is activated.
  2. Navigate to the project root directory (mcp-weather-server).
  3. Start the server using Uvicorn:
    uvicorn app.main:app --reload --port 8000
    • app.main:app: Points to the app FastAPI instance in app/main.py.
    • -reload: Enables auto-reloading during development. The server will restart if code changes are detected.
    • -port 8000: Specifies the port on which the server will listen.

The server will be accessible at http://localhost:8000.

API Documentation (Auto-Generated)

FastAPI automatically generates interactive API documentation:

These interfaces allow you to view detailed endpoint information, schemas, and try out the API directly from your browser.

API Endpoint

Get Current Weather

  • URL: /mcp/weather
  • Method: POST
  • Request Body (JSON - MCP Format):
    { "protocol_version": "1.0", "tool_id": "weather_tool", "method": "get_current_weather", "parameters": { "location": "CityName,CountryCode" // e.g., "London,UK" or "Paris" } }
  • Success Response (HTTP 200 OK - MCP Format):
    { "protocol_version": "1.0", "tool_id": "weather_tool", "status": "success", "data": { "location": "London", "temperature_celsius": 15.5, "temperature_fahrenheit": 59.9, "condition": "Clouds", "description": "Broken clouds", "humidity_percent": 75.0, "wind_kph": 10.8, "pressure_hpa": 1012.0 }, "error_message": null }
  • Application Error Response (HTTP 200 OK with error status - MCP Format): (The MCP server returns HTTP 200 even for application-level errors, with the error details in the payload)
    { "protocol_version": "1.0", "tool_id": "weather_tool", "status": "error", "data": null, "error_message": "Weather data not found for location: InvalidCity." }

Testing

This project includes multiple ways to test the application:

1. Manual Testing with curl or API Clients

You can send POST requests to the /mcp/weather endpoint using curl or tools like Postman or Insomnia. Example curl command:

curl -X POST "http://localhost:8000/mcp/weather" \ -H "Content-Type: application/json" \ -d '{ "protocol_version": "1.0", "tool_id": "weather_tool", "method": "get_current_weather", "parameters": { "location": "Berlin,DE" } }'

2. End-to-End Client Simulation (test_mcp_client.py)

A Python script (test_mcp_client.py) located in the project root simulates a client making various requests to the running MCP server. This is useful for quick end-to-end checks.

  • To Run:
    1. Ensure your MCP server is running (see "Running the MCP Server").
    2. Activate your virtual environment.
    3. In a separate terminal, from the project root, run:
      python3 test_mcp_client.py

3. Automated Tests with pytest

The project uses pytest for unit and integration tests of the server's components. These tests are located in the tests/ directory and cover API endpoints (with mocked services) and service layer logic (with mocked external HTTP calls).

  • Setup:pytest and pytest-asyncio should be listed in your requirements.txt and installed during the initial setup.
  • To Run:
    1. Activate your virtual environment.
    2. From the project root, run:
      pytest
      Or for more verbose output:
      pytest -v

Simple AI Agent CLI (weather_agent_cli.py)

A command-line interface (CLI) agent (weather_agent_cli.py) is provided in the project root to demonstrate how an agent can interact with the MCP Weather Server. It takes simple text commands to fetch and display weather information.

  • To Run:
    1. Ensure your MCP server is running (see "Running the MCP Server").
    2. Activate your virtual environment.
    3. In a separate terminal, from the project root, run:
      python3 weather_agent_cli.py
    4. Follow the prompts. Example commands: weather in London, weather Tokyo, quit.

Project Structure

mcp-weather-server/ ├── .vscode/ # VS Code specific settings (optional) │ └── settings.json ├── app/ # Main application source code │ ├── __init__.py │ ├── main.py # FastAPI app instance, MCP endpoint(s) │ ├── models.py # Pydantic models for MCP & data structures │ ├── services.py # Business logic (e.g., calling weather API) │ └── core/ │ ├── __init__.py │ └── config.py # Configuration management (e.g., API keys) ├── tests/ # Automated pytest tests │ ├── __init__.py │ ├── test_main.py # Tests for API endpoints (app.main) │ └── test_services.py # Unit tests for service logic (app.services) ├── .env # Local environment variables (API_KEY) - NOT COMMITTED ├── .gitignore # Specifies intentionally untracked files by Git ├── CHANGELOG.md # Log of notable project changes ├── requirements.txt # Python dependencies for the project ├── README.md # This file (main project documentation) ├── weather_agent_cli.py # Simple CLI agent for demonstration ├── test_mcp_client.py # End-to-end client simulation script └── venv/ # Python virtual environment directory

Future Enhancements (Potential Ideas)

  • Support for more weather data points (e.g., multi-day forecasts, UV index).
  • Add more tools to the MCP server (e.g., news, calculator, calendar).
  • Implement more sophisticated error handling and detailed logging.
  • Dockerize the application for easier deployment and portability.
  • Develop a more advanced AI agent with better NLP capabilities.
  • Add authentication/authorization to the MCP server if it were to be exposed.

License

(Specify a license for your project here, e.g., MIT License. If unsure, you can add "To be determined" or research common open-source licenses.)

-
security - not tested
F
license - not found
-
quality - not tested

A standardized API server that enables AI agents and client applications to fetch current weather information for any location without directly interacting with external weather APIs.

  1. Project Overview
    1. Architecture
      1. Prerequisites
        1. Setup and Installation
          1. Running the MCP Server
            1. API Documentation (Auto-Generated)
              1. API Endpoint
                1. Get Current Weather
              2. Testing
                1. Manual Testing with curl or API Clients
                2. End-to-End Client Simulation (test_mcp_client.py)
                3. Automated Tests with pytest
              3. Simple AI Agent CLI (weather_agent_cli.py)
                1. Project Structure
                  1. Future Enhancements (Potential Ideas)
                    1. License

                      Related MCP Servers

                      • -
                        security
                        A
                        license
                        -
                        quality
                        A lightweight, modular API service that provides useful tools like weather, date/time, calculator, search, email, and task management through a RESTful interface, designed for integration with AI agents and automated workflows.
                        Last updated -
                        Python
                        MIT License
                      • -
                        security
                        A
                        license
                        -
                        quality
                        A Model Context Protocol server that retrieves current weather information for specified cities using the Open-Meteo API, requiring no API key.
                        Last updated -
                        4
                        Python
                        Apache 2.0
                        • Linux
                        • Apple
                      • A
                        security
                        F
                        license
                        A
                        quality
                        A Model Context Protocol server that provides AI agents with tools to retrieve weather alerts and detailed forecasts for US locations using the National Weather Service API.
                        Last updated -
                        2
                        75
                        TypeScript
                      • -
                        security
                        -
                        license
                        -
                        quality
                        A Model Context Protocol server that provides current weather information and 3-day forecasts for specified cities using the Open-Meteo API.
                        Last updated -
                        Python

                      View all related MCP servers

                      MCP directory API

                      We provide all the information about MCP servers via our MCP API.

                      curl -X GET 'https://glama.ai/api/mcp/v1/servers/ramonbnuezjr/mcp-weather-server'

                      If you have feedback or need assistance with the MCP directory API, please join our Discord server