mcp-weather

dennisonbertram/mcp-weather

3.2

If you are the rightful owner of mcp-weather 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.

OpenWeatherMap MCP Server provides comprehensive access to weather data through a Model Context Protocol server.

Tools
5
Resources
0
Prompts
0

OpenWeatherMap MCP Server

A comprehensive Model Context Protocol (MCP) server for accessing OpenWeatherMap weather data. This server provides current weather, forecasts, air quality data, and geocoding services through 15 specialized tools and 4 resource endpoints.

๐ŸŒฆ๏ธ Features

Weather Tools (15 total)

  • Current Weather: Get real-time weather by location name or coordinates
  • Forecasting: 5-day forecasts, hourly data, and weather summaries
  • Air Quality: Current pollution data, forecasts, and historical analysis
  • Geocoding: Convert between location names and coordinates
  • One Call API: Comprehensive weather data with government alerts

Resources (4 total)

  • Weather Parameters: Reference data for temperature, wind, pressure units
  • Condition Codes: Complete mapping of OpenWeatherMap weather conditions
  • API Status: Dynamic monitoring of service availability
  • Languages: Supported language codes for international queries

Production Features

  • โœ… Rate Limiting: 60 calls/minute with queue management
  • โœ… Error Handling: Comprehensive retry logic and user-friendly messages
  • โœ… Input Validation: Zod schema validation for all inputs
  • โœ… Structured Logging: JSON formatted logs with configurable levels
  • โœ… Type Safety: Full TypeScript implementation
  • โœ… Test Coverage: 174 comprehensive tests with realistic fixtures
  • โœ… Multiple Transports: STDIO, HTTP, and SSE transport support

๐Ÿ“‹ Prerequisites

  • Node.js 18 or higher
  • OpenWeatherMap API key (free tier available)

๐Ÿš€ Installation

1. Get OpenWeatherMap API Key

  1. Sign up at OpenWeatherMap
  2. Verify your email address
  3. Generate a free API key from your dashboard
  4. Wait 1-2 hours for key activation (if newly created)

2. Setup Environment

# Clone and install
git clone <repository-url>
cd mcp-weather
npm install

# Create environment file
cp .env.example .env

3. Configure API Key

Edit .env file:

# OpenWeatherMap API Configuration
OPENWEATHER_API_KEY=your_api_key_here
OPENWEATHER_BASE_URL=https://api.openweathermap.org/data/2.5

4. Build and Test

# Build the server
npm run build

# Run tests to verify setup
npm test

# Start the server
npm start

๐Ÿ”ง Usage

The OpenWeatherMap MCP Server supports multiple transport protocols for different deployment scenarios:

๐Ÿš€ Transport Options

1. STDIO Transport (Default - MCP Clients)

Perfect for MCP client integration (Claude Code, etc.)

# Default STDIO mode
npm start

# Explicit STDIO mode
npm start -- --stdio

Claude Code Configuration:

{
  "mcp": {
    "servers": {
      "openweathermap": {
        "command": "node",
        "args": ["/path/to/mcp-weather/dist/index.js"],
        "env": {
          "OPENWEATHER_API_KEY": "your_api_key_here"
        }
      }
    }
  }
}
2. HTTP Transport (REST API + Streaming)

Ideal for web applications and direct API access

# Start HTTP server on port 3000
npm run start:http

# Custom port and host
npm start -- --http --port 8080 --host localhost

API Endpoints:

  • POST /mcp - MCP JSON-RPC requests
  • GET /mcp - Server-Sent Events for streaming
  • DELETE /mcp - Session termination
  • GET /health - Health check

Example HTTP Request:

curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
      "name": "get_current_weather",
      "arguments": {
        "location": "London"
      }
    },
    "id": 1
  }'
3. SSE Transport (Server-Sent Events)

Best for real-time web applications requiring push notifications

# Start SSE server on port 3001
npm run start:sse

# Custom configuration
npm start -- --sse --port 3002 --host 0.0.0.0

SSE Connection:

const eventSource = new EventSource('http://localhost:3001/sse');
eventSource.onmessage = (event) => {
  const response = JSON.parse(event.data);
  console.log('Weather update:', response);
};
4. Development & Testing
# Development with auto-reload
npm run dev

# Test different transports
npm run test:transport

# MCP protocol testing
npm run test:mcp

๐ŸŒ Web Integration Examples

JavaScript/TypeScript Client
// HTTP Transport Client
async function getWeather(location: string) {
  const response = await fetch('http://localhost:3000/mcp', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'mcp-session-id': 'my-session-123'
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      method: 'tools/call',
      params: {
        name: 'get_current_weather',
        arguments: { location }
      },
      id: Date.now()
    })
  });
  
  return response.json();
}

// SSE Transport Client
function subscribeToWeatherUpdates() {
  const eventSource = new EventSource('http://localhost:3001/sse');
  
  eventSource.addEventListener('weather-update', (event) => {
    const data = JSON.parse(event.data);
    updateWeatherDisplay(data);
  });
  
  return eventSource;
}
Python Client
import requests
import json

# HTTP Transport
def get_weather(location):
    url = "http://localhost:3000/mcp"
    payload = {
        "jsonrpc": "2.0",
        "method": "tools/call",
        "params": {
            "name": "get_current_weather",
            "arguments": {
                "location": location
            }
        },
        "id": 1
    }
    
    response = requests.post(url, json=payload)
    return response.json()

# Usage
weather = get_weather("Tokyo")
print(json.dumps(weather, indent=2))

๐Ÿ”’ Security Configuration

HTTP Transport Security
# Enable CORS restrictions
npm start -- --http --cors-origins="https://myapp.com,https://admin.myapp.com"

# Enable security headers
npm start -- --http --enable-security

# Custom session timeout (1 hour = 3600000ms)
npm start -- --http --session-timeout=3600000
Environment Variables
# Security settings
CORS_ORIGINS=https://myapp.com,https://localhost:3000
ENABLE_COMPRESSION=true
ENABLE_SECURITY=true
SESSION_TIMEOUT=3600000
MAX_SESSIONS=100

# OpenWeatherMap API
OPENWEATHER_API_KEY=your_api_key_here
OPENWEATHER_BASE_URL=https://api.openweathermap.org/data/2.5

๐Ÿณ Docker Deployment

Docker Compose for HTTP Transport
version: '3.8'

services:
  mcp-weather-http:
    build: .
    ports:
      - "3000:3000"
    environment:
      - OPENWEATHER_API_KEY=your_api_key_here
      - NODE_ENV=production
    command: ["npm", "start", "--", "--http", "--host", "0.0.0.0"]
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3

  mcp-weather-sse:
    build: .
    ports:
      - "3001:3001"
    environment:
      - OPENWEATHER_API_KEY=your_api_key_here
      - NODE_ENV=production
    command: ["npm", "start", "--", "--sse", "--host", "0.0.0.0"]

๐Ÿ› ๏ธ Available Tools

Current Weather

  • get_current_weather(location) - Get current weather for any location
  • get_weather_by_coordinates(lat, lon) - Weather by precise coordinates

Forecasting

  • get_5day_forecast(location) - 5-day forecast with 3-hour intervals
  • get_hourly_forecast(location) - Detailed hourly predictions
  • get_forecast_summary(location) - Human-readable weather summary

Geocoding

  • geocode_location(location) - Convert location name to coordinates
  • reverse_geocode(lat, lon) - Convert coordinates to location name
  • search_cities(query) - Find cities matching search terms

Air Quality

  • get_air_pollution(lat, lon) - Current air quality and pollutant levels
  • get_air_pollution_forecast(lat, lon) - 5-day air quality forecast
  • get_air_pollution_history(lat, lon, start, end) - Historical pollution data

One Call API

  • get_onecall_weather(lat, lon) - Comprehensive weather data
  • get_weather_timemachine(lat, lon, date) - Historical weather data
  • get_weather_day_summary(lat, lon, date) - Daily weather aggregation

๐Ÿ“Š Example Responses

Current Weather

{
  "location": "London, GB",
  "temperature": {
    "current": 20.1,
    "feels_like": 19.8,
    "min": 18.2,
    "max": 22.4,
    "unit": "celsius"
  },
  "condition": {
    "main": "Rain", 
    "description": "light rain",
    "icon": "10d"
  },
  "wind": {
    "speed": 7.72,
    "direction": 230,
    "unit": "meter/sec"
  },
  "humidity": 68,
  "pressure": 1001
}

Air Quality

{
  "location": "Tokyo, JP",
  "coordinates": [35.68, 139.76],
  "air_quality_index": 2,
  "status": "Good",
  "pollutants": {
    "pm2_5": 9.91,
    "pm10": 19.97,
    "o3": 76.95,
    "no2": 6.29,
    "so2": 8.71,
    "co": 131.88
  },
  "health_recommendations": [
    "Air quality is satisfactory for most people",
    "Enjoy outdoor activities"
  ]
}

๐Ÿงช Testing

# Run all tests
npm test

# Run specific test suites
npm run test:unit
npm run test:integration

# Test with coverage
npm run test:coverage

# Test specific transport
npm run test:http
npm run test:sse

๐Ÿ”’ Security

  • โœ… No hardcoded secrets - All credentials via environment variables
  • โœ… Input sanitization - Zod validation prevents malicious inputs
  • โœ… Rate limiting - Prevents API abuse
  • โœ… Error boundaries - No sensitive data in error messages
  • โœ… Secure logging - API keys never logged
  • โœ… CORS protection - Configurable origin restrictions
  • โœ… Security headers - Helmet.js integration for HTTP transport
  • โœ… Session management - Configurable timeouts and limits

๐Ÿ“ˆ Rate Limits

Free Tier (Default):

  • 60 calls per minute
  • 1,000,000 calls per month

Built-in Management:

  • Automatic queuing when limits approached
  • Exponential backoff on rate limit errors
  • Clear error messages when limits exceeded

๐Ÿ› Troubleshooting

API Key Issues

# Test your API key directly
curl "https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_KEY"

# Should return weather data, not 401 error

Common solutions:

  • Wait 1-2 hours for new key activation
  • Verify email address in OpenWeatherMap account
  • Check key isn't expired or suspended
  • Ensure no extra spaces when copying key

Transport Issues

STDIO Transport
# Enable debug logging
DEBUG=true npm start

# Check server health
echo '{"jsonrpc":"2.0","method":"ping","id":1}' | node dist/index.js
HTTP Transport
# Test HTTP health endpoint
curl http://localhost:3000/health

# Test MCP endpoint
curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"tools/list","id":1}'
SSE Transport
# Test SSE connection
curl -N http://localhost:3001/sse

# Test with browser console
const es = new EventSource('http://localhost:3001/sse');
es.onmessage = console.log;

Test Mode

# Run with test fixtures (no API calls)
NODE_ENV=test npm start
NODE_ENV=test npm start -- --http
NODE_ENV=test npm start -- --sse

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add comprehensive tests
  4. Follow TypeScript and ESLint guidelines
  5. Submit a pull request

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ”— Links

๐Ÿ“‹ API Coverage

This MCP server implements the following OpenWeatherMap APIs:

APIEndpointsStatusFree Tier
Current Weather/weatherโœ…Yes
5-day Forecast/forecastโœ…Yes
Geocoding/geo/1.0/direct, /geo/1.0/reverseโœ…Yes
Air Pollution/air_pollution/*โœ…Yes
One Call 3.0/onecallโœ…Premium*

*One Call API 3.0 requires subscription but gracefully degrades on free tier.

๐Ÿš€ Transport Comparison

TransportUse CaseProsCons
STDIOMCP ClientsNative MCP support, secureCLI/desktop only
HTTPWeb APIsREST-like, widely supportedStateless, no push
SSEReal-time appsServer push, live updatesBrowser-specific

Built with โค๏ธ for the MCP ecosystem