weather-mcp-server

kylestahl/weather-mcp-server

3.2

If you are the rightful owner of weather-mcp-server 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 MCP Weather Server provides weather information for cities globally using the Open-Meteo API and OpenStreetMap for geocoding.

Tools
1
Resources
0
Prompts
0

MCP Weather Server

A Model Context Protocol (MCP) server that provides weather information for cities using the Open-Meteo API and OpenStreetMap for geocoding.

Features

  • šŸŒ¤ļø Current weather conditions
  • šŸ“… Multi-day weather forecasts (up to 16 days)
  • šŸŒ Global city support via OpenStreetMap geocoding
  • šŸ”Œ Both stdio and HTTP server modes
  • 🧪 Comprehensive testing capabilities
  • šŸ“ Detailed weather formatting

Quick Start

  1. Setup the environment:

    chmod +x setup.sh
    ./setup.sh setup
    
  2. Run the server (stdio mode for MCP clients):

    ./setup.sh run-stdio
    
  3. Or run in HTTP mode for testing:

    ./setup.sh run-http
    

Usage

MCP Client Integration (stdio mode)

For integration with MCP clients like Claude Desktop:

./setup.sh run-stdio

The server will communicate via JSON-RPC over stdin/stdout following the MCP protocol.

HTTP Mode (for testing)

For manual testing and debugging:

./setup.sh run-http

The server will start on http://localhost:8000 with the following endpoints:

  • GET /weather?city=<city>&forecast_days=<days> - Get weather data
  • GET /health - Health check
  • GET /tools - List available tools
  • GET / - API documentation
HTTP Examples
# Get weather for London with 5-day forecast
curl "http://localhost:8000/weather?city=London&forecast_days=5"

# Get weather for New York with 3-day forecast
curl "http://localhost:8000/weather?city=New%20York&forecast_days=3"

# Health check
curl "http://localhost:8000/health"

Testing

Automated Tests

Run tests for both server modes:

# Test stdio server
./setup.sh test-stdio

# Test HTTP server
./setup.sh test-http

Manual Testing

Testing stdio server with MCP client

You can test the stdio server using any MCP client or by sending JSON-RPC messages:

echo '{"protocolVersion": "2024-11-05","capabilities": {},"clientInfo": {"name": "test-client","version": "1.0.0"}}' | python weather_server.py
Testing HTTP server with curl
# Start the HTTP server
./setup.sh run-http

# In another terminal, test the endpoints
curl "http://localhost:8000/weather?city=Paris&forecast_days=3"
curl "http://localhost:8000/health"
curl "http://localhost:8000/tools"

Available Tools

get_weather

Get current weather conditions and forecast for a specified city.

Parameters:

  • city (string, required): Name of the city to get weather for
  • forecast_days (integer, optional): Number of forecast days (1-16, default: 5)

Example Response:

Weather for London
==================

Current Weather:
  Condition: Partly cloudy
  Temperature: 15.2°C
  Humidity: 73%
  Wind: 12.5 km/h at 245°

Forecast:
  2024-01-15: Partly cloudy, 8°C - 16°C, 0.2mm rain
  2024-01-16: Light rain, 10°C - 14°C, 3.1mm rain
  2024-01-17: Clear sky, 6°C - 18°C, 0.0mm rain
  2024-01-18: Overcast, 9°C - 15°C, 1.2mm rain
  2024-01-19: Mainly clear, 7°C - 17°C, 0.0mm rain

Configuration

Environment Variables

You can customize the server behavior with environment variables:

  • WEATHER_SERVER_PORT: HTTP server port (default: 8000)
  • WEATHER_SERVER_HOST: HTTP server host (default: localhost)
  • LOG_LEVEL: Logging level (default: INFO)

API Integrations

The server respects the rate limits of the external APIs:

  • Open-Meteo API: No API key required, reasonable rate limits
  • OpenStreetMap Nominatim: 1 request per second, includes proper User-Agent

File Structure

mcp-weather-server/
ā”œā”€ā”€ weather_server.py      # Main MCP server (stdio mode)
ā”œā”€ā”€ weather_http_server.py # HTTP server for testing
ā”œā”€ā”€ requirements.txt       # Python dependencies
ā”œā”€ā”€ setup.sh               # Setup and management script
ā”œā”€ā”€ test_mcp_client.py     # Helper script to test the stdio server
└── README.md              # This documentation

Architecture

Components

  1. WeatherServer Class: Core weather functionality

    • Geocoding via OpenStreetMap Nominatim API
    • Weather data retrieval from Open-Meteo API
    • Response formatting and error handling
  2. MCP Server (stdio): Model Context Protocol implementation

    • JSON-RPC communication over stdin/stdout
    • Tool registration and execution
    • MCP protocol compliance
  3. HTTP Server: Testing and debugging interface

    • REST API endpoints
    • JSON response format
    • Health monitoring

Data Flow

  1. City Input → Geocoding → Weather API → Formatted Response
  2. Client requests weather for a city
  3. Server geocodes city to lat/lon coordinates
  4. Server fetches weather data from Open-Meteo
  5. Server formats and returns human-readable weather information

External APIs

  • OpenStreetMap Nominatim: Free geocoding service

    • Endpoint: https://nominatim.openstreetmap.org/search
    • No API key required
    • Rate limit: ~1 request/second
  • Open-Meteo: Free weather API

    • Endpoint: https://api.open-meteo.com/v1/forecast
    • No API key required
    • Supports current weather and forecasts

Troubleshooting

Common Issues

"Module not found" errors
# Ensure virtual environment is activated
source venv/bin/activate

# Reinstall dependencies
pip install -r requirements.txt
Geocoding failures
  • Check internet connectivity
  • Verify city name spelling
  • Some very small towns might not be found
  • Try with state/country: "Paris, France" instead of just "Paris"
Weather API timeouts
  • Check internet connectivity
  • Open-Meteo API might be temporarily unavailable
  • Server includes retry logic for transient failures
HTTP server won't start
# Check if port is already in use
lsof -i :8000

# Use different port
WEATHER_SERVER_PORT=8001 ./setup.sh run-http

Debug Mode

Enable detailed logging:

# Set log level to DEBUG
export LOG_LEVEL=DEBUG
./setup.sh run-stdio

Network Issues

If you're behind a corporate firewall:

  1. Ensure access to:

    • https://nominatim.openstreetmap.org
    • https://api.open-meteo.com
  2. Configure proxy if needed:

    export HTTP_PROXY=http://your-proxy:port
    export HTTPS_PROXY=https://your-proxy:port
    

MCP Client Integration

Claude Desktop

Add to your Claude Desktop configuration:

{
  "mcpServers": {
    "weather": {
      "command": "/path/to/venv/python",
      "args": ["/path/to/weather_server.py"],
      "env": {}
    }
  }
}

Custom MCP Clients

The server implements MCP protocol version 2024-11-05:

# Example client interaction
import json
import subprocess

# Start server process
proc = subprocess.Popen(
    ['python', 'weather_server.py'],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    text=True
)

# Send initialize request
init_request = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
        "protocolVersion": "2024-11-05",
        "capabilities": {},
        "clientInfo": {"name": "my-client", "version": "1.0.0"}
    }
}

proc.stdin.write(json.dumps(init_request) + '\n')
proc.stdin.flush()

# Read response
response = proc.stdout.readline()
print(json.loads(response))

API Reference

MCP Methods

tools/list

Lists available tools.

Request:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list"
}

Response:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [
      {
        "name": "get_weather",
        "description": "Get current weather and forecast for a city",
        "inputSchema": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "Name of the city"},
            "forecast_days": {"type": "integer", "minimum": 1, "maximum": 16}
          },
          "required": ["city"]
        }
      }
    ]
  }
}
tools/call

Execute a tool.

Request:

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "get_weather",
    "arguments": {
      "city": "Tokyo",
      "forecast_days": 7
    }
  }
}

Response:

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Weather for Tokyo\n==================\n\nCurrent Weather:\n  Condition: Clear sky\n  Temperature: 22.5°C\n  ..."
      }
    ]
  }
}

HTTP Endpoints

GET /weather

Get weather information for a city.

Parameters:

  • city (required): City name
  • forecast_days (optional): Number of forecast days (1-16, default: 5)

Example:

curl "http://localhost:8000/weather?city=Berlin&forecast_days=5"

Response:

{
  "city": "Berlin",
  "coordinates": {"latitude": 52.5200, "longitude": 13.4050},
  "formatted_weather": "Weather for Berlin\n==================\n...",
  "raw_data": { /* Open-Meteo API response */ }
}
GET /health

Health check endpoint.

Response:

{
  "status": "healthy",
  "service": "weather-server"
}
GET /tools

List available tools and usage information.

Response:

{
  "tools": [
    {
      "name": "get_weather",
      "description": "Get current weather and forecast for a city",
      "parameters": {
        "city": "Name of the city (required)",
        "forecast_days": "Number of forecast days (1-16, default: 5)"
      },
      "example": "/weather?city=London&forecast_days=3"
    }
  ]
}

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite
  6. Submit a pull request

License

CC0 1.0 CC0 1.0 Universal (CC0 1.0) Public Domain Dedication