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
访问服务器

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

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选