MCP Weather Server

MCP Weather Server

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.

Category
Visit Server

README

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:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

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.)

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured