MCP Hub
Back to servers

MCP Weather Server

A production-grade Model Context Protocol server that provides real-time weather data and 5-day forecasts using the Open-Meteo API. It offers comprehensive meteorological metrics supported by Redis caching and built-in performance monitoring tools.

glama
Updated
Mar 30, 2026

🌤️ MCP Weather Server

A production-grade Model Context Protocol (MCP) server providing comprehensive real-time weather data using the free Open-Meteo API.

Tests License Node.js

✨ Features

🌦️ Weather Data

  • Current Weather: Real-time conditions with 20+ meteorological parameters
  • 5-Day Forecast: Detailed daily predictions with solar, UV, and precipitation data
  • Comprehensive Metrics: Temperature, humidity, wind, pressure, UV index, visibility, cloud cover
  • Solar Data: Sunshine duration, daylight hours, solar radiation, evapotranspiration

🚀 Performance & Reliability

  • Redis Caching: Intelligent caching with configurable TTL (15min current, 1h forecast)
  • Metrics & Monitoring: Real-time performance tracking and error logging
  • Graceful Degradation: Continues working without Redis/cache if unavailable
  • Type-Safe: Full Zod validation for all inputs and API responses

🏗️ Architecture

  • Multiple Transports: Stdio (MCP Inspector) + HTTP/SSE streaming
  • Factory Pattern: Isolated server instances per session
  • Layered Design: Services, Tools, Server separation
  • ESM Modules: Modern JavaScript with full ES2022 support

🔧 Developer Experience

  • 64 Unit Tests: Comprehensive Jest test suite
  • Hot Reload: Development mode with file watching
  • Debug Support: Integrated debugging for both transports
  • Rich Logging: Structured logs with performance metrics

📊 Data Sources

Open-Meteo API (Free Tier)

  • No API Key Required - Unlimited calls for non-commercial use
  • Global Coverage - Weather models for every location worldwide
  • Multiple Models - ECMWF, NOAA GFS, Météo-France, DWD ICON, and more
  • Real-time Updates - 15-minute to hourly resolution

Available Weather Variables

Current Conditions

  • Temperature & "Feels Like" (2m & apparent)
  • Humidity, Dew Point, Vapour Pressure Deficit
  • Wind Speed/Direction/Gusts (10m, 80m, 120m, 180m altitudes)
  • Pressure (MSL & Surface), Cloud Cover (Total/Low/Mid/High)
  • Visibility, UV Index, Precipitation
  • Evapotranspiration & Reference ET₀

Forecast Data

  • Daily min/max temperatures (actual & apparent)
  • Precipitation (total, rain, showers, snow)
  • Wind (speed, gusts, dominant direction)
  • Solar (sunrise/sunset, sunshine/daylight duration, UV index)
  • Radiation (shortwave solar radiation sum)

🏛️ Architecture

src/
├── index.js                    # Entry point & transport orchestration
├── server/
│   ├── weatherMcpFactory.js    # Server factory with cache init
│   └── streamableHttpServer.js # HTTP/SSE transport server
├── services/
│   ├── weatherApi.js          # Open-Meteo API client with caching
│   ├── weatherCodes.js        # WMO weather code mappings
│   ├── cache.js               # Redis cache service
│   └── metrics.js             # Performance monitoring
└── tools/
    ├── schemas.js             # Zod validation schemas
    ├── getWeatherTool.js      # Current weather MCP tool
    ├── getWeatherForecast5DaysTool.js # Forecast MCP tool
    └── getServerStatsTool.js  # Server metrics tool

Design Patterns

PatternImplementationPurpose
FactorycreateWeatherMcpServer()Isolated server instances per session
StrategyStdio vs HTTP transport strategiesMultiple deployment modes
AdapterMCP SDK transport wrappingUnified interface for different transports
DecoratorResponse formatting with emojisEnhanced user experience
ObserverMetrics collectionPerformance monitoring
ProxyCache layerAPI call optimization

📋 Installation

Prerequisites

  • Node.js ≥16.0.0 (with --experimental-vm-modules for Jest)
  • Redis (optional, for caching) - Install from redis.io

Setup

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

# Install dependencies
npm install

# Run tests
npm test

# Start server (stdio mode)
npm start

Environment Variables

# Redis configuration (optional)
REDIS_URL=redis://localhost:6379

# HTTP server configuration
MCP_HTTP_PORT=3333
MCP_HTTP_HOST=127.0.0.1

🚀 Usage

MCP Inspector (Recommended)

# Start in stdio mode for MCP Inspector
npm start

# Then open MCP Inspector and connect to the server

HTTP/SSE Mode

# Start HTTP server with SSE transport
npm run start:http

# Server runs on http://127.0.0.1:3333
# MCP endpoint: http://127.0.0.1:3333/mcp

Development Mode

# With hot reload
npm run dev

# With debugging
npm run debug:http  # HTTP mode
npm run debug       # Stdio mode

🔧 API Reference

Tools

get_weather

Get current weather conditions for coordinates.

Input:

{
  "latitude": 48.8566,
  "longitude": 2.3522
}

Output:

🌤️ Current Weather

📍 Location: 48.8566, 2.3522
🌡️ Temperature: 22.5°C (feels like 24.1°C)
💧 Humidity: 65%
🌫️ Dew Point: 15.8°C
💨 Wind: 12 km/h from WSW
🌪️ Wind Gusts: 18 km/h
☁️ Conditions: Partly cloudy
☁️ Cloud Cover: 45% (Low: 20%, Mid: 15%, High: 10%)
👁️ Visibility: 24 km
🧭 Pressure: 1013 hPa (MSL) / 1011 hPa (Surface)
☀️ UV Index: 6
💧 Evapotranspiration: 0.15 mm/h
🌱 Reference ET₀: 0.22 mm/h
🌡️ Vapor Pressure Deficit: 0.85 kPa
🌍 Timezone: Europe/Paris
🕐 Updated: 2024-03-29T14:30:00Z

get_weather_forecast

Get 5-day weather forecast for coordinates.

Input:

{
  "latitude": 48.8566,
  "longitude": 2.3522
}

Output:

📅 5-Day Forecast

📍 Coordinates : 48.8566, 2.3522
🌍 Timezone    : Europe/Paris

📅 2024-03-29
   🌡️  18°C – 24°C (feels 16°C – 26°C)
   ☁️  Partly cloudy
   💧 Precipitation: 0.2 mm (0 rain + 0.1 showers + 0 snow)
   🌧️ Chance: 15% over 0.5h
   🌅 Sunrise: 06:45 | Sunset: 19:32
   ☀️  Sunshine: 8.2h / Daylight: 12.8h
   ☀️  UV Index: 6 (Clear sky: 7)
   💨 Wind: 15 km/h gusts to 22 km/h from W
   ⚡ Solar Radiation: 18.5 MJ/m²
   🌱 Reference ET₀: 4.2 mm

get_server_stats

Get server performance metrics and cache statistics.

Input: (no parameters required)

Output:

📊 Server Statistics

⏱️  Uptime: 45 minutes
🔄 API Calls: 127
💾 Cache Hits: 89 (70.1%)
❌ Errors: 2
⚡ Avg Response Time: 245ms

🔧 Tool Usage:
   • get_weather: 95 calls
   • get_weather_forecast: 32 calls

📋 Cache Status:
   • Connected: ✅
   • Keys: 23
   • Memory: 2.4MB

🧪 Testing

Run Test Suite

# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Run in watch mode
npm run test:watch

Test Architecture

  • 64 unit tests covering all services and server components
  • Mocked API calls for reliable testing without network dependencies
  • Cache testing with Redis mock
  • Schema validation testing with Zod
  • Error handling coverage

Test Files

tests/
├── services/
│   ├── weatherApi.test.js     # API client tests
│   └── weatherCodes.test.js   # Weather code mapping tests
└── server/
    └── weatherMcpFactory.test.js # Server factory tests

📈 Monitoring & Metrics

Built-in Metrics

  • API Call Tracking: Count, response times, cache hit rates
  • Tool Usage: Per-tool invocation counts
  • Error Tracking: Error types and frequencies
  • Cache Performance: Hit rates, memory usage, connection status
  • Server Health: Uptime, active sessions

Logs

Structured logging with:

  • Request/response timing
  • Cache operations
  • API call details
  • Error context
  • Performance metrics

Cache Configuration

// Current weather: 15 minutes TTL
// Forecasts: 1 hour TTL
// Automatic expiration and cleanup

🔒 Security & Reliability

Data Validation

  • Zod schemas for all inputs
  • Coordinate bounds checking (-90/+90, -180/+180)
  • API response validation
  • Error sanitization (no sensitive data leakage)

Error Handling

  • Graceful degradation (continues without cache)
  • Structured error responses with appropriate HTTP codes
  • Timeout handling for API calls
  • Connection retry logic for Redis

Performance

  • Connection pooling for Redis
  • Request deduplication via caching
  • Memory-efficient data structures
  • Background cleanup of expired cache entries

🤝 Contributing

Development Setup

# Install dependencies
npm install

# Run tests
npm test

# Start development server
npm run dev

# Debug mode
npm run debug

Code Quality

  • ESLint configuration for code style
  • Prettier for consistent formatting
  • Jest for comprehensive testing
  • TypeScript definitions for better IDE support

Architecture Guidelines

  • Layer separation: Services, Tools, Server layers
  • Dependency injection: Injectable fetch/cache for testing
  • Error boundaries: Comprehensive error handling
  • Logging standards: Structured logging throughout

📄 License

MIT License - Free for personal and commercial use.

Open-Meteo Terms

  • Non-commercial use: Unlimited API calls
  • Commercial use: Contact Open-Meteo for licensing
  • Attribution required for public deployments

🙏 Acknowledgments

  • Open-Meteo for providing free, high-quality weather data
  • Anthropic for the Model Context Protocol specification
  • Weather model providers: ECMWF, NOAA, Météo-France, DWD, and others

📞 Support

Issues & Bugs

  • GitHub Issues: Report bugs and request features
  • Documentation: Check this README first

Community

  • MCP Discord: Join the Model Context Protocol community
  • Open-Meteo Forum: Weather API discussions

Built with ❤️ using the Model Context Protocol

Stdio Mode (Default)

npm start
# or: node src/index.js

Perfect for direct MCP client integration (Claude Desktop, IDEs, etc.)

HTTP/SSE Mode

# Via CLI flag
npm run start:http
# or: node src/index.js --http

# Via environment variables
TRANSPORT=http PORT=8080 node src/index.js

# Default HTTP port: 3001

HTTP Endpoints:

  • GET /health - Health check endpoint
  • GET /sse - Server-Sent Events stream
  • POST /messages - Tool request endpoint

Demo Script

node demo.js

Shows real-world example calls to weather service for multiple cities.

Run Tests

npm test

Validates input schemas and weather code mappings.

🛠️ Available Tools

Tool: get_weather

Get current weather for a location.

Parameters:

{
  "latitude": -90 to 90,
  "longitude": -180 to 180
}

Example:

# Request current weather for Paris
{
  "latitude": 48.8566,
  "longitude": 2.3522
}

Response Example:

☀️ **CURRENT WEATHER**

📍 Location: 48.8566°N, 2.3522°E
🌡️  Temperature: 15°C
☁️  Condition: Partly cloudy
💧 Humidity: 65%
💨 Wind Speed: 12 km/h
🕐 Time: 2024-03-29T10:30:00Z
🌍 Timezone: Europe/Paris

Tool: get_forecast

Get 5-day weather forecast.

Parameters:

{
  "latitude": -90 to 90,
  "longitude": -180 to 180
}

Response Example:

📅 **5-DAY WEATHER FORECAST**

📍 Location: 48.8566°N, 2.3522°E
🌍 Timezone: Europe/Paris

**Day 1** - 2024-03-29
☁️ Partly cloudy
🔺 Max: 18°C | 🔻 Min: 12°C

**Day 2** - 2024-03-30
🌧️ Slight rain
🔺 Max: 16°C | 🔻 Min: 10°C

...

🌍 Popular Coordinates

CityLatitudeLongitude
Paris48.85662.3522
London51.5074-0.1278
New York40.7128-74.0060
Tokyo35.6762139.6503
Sydney-33.8688151.2093
Berlin52.520013.4050
Los Angeles34.0522-118.2437

🔗 Data Source

📦 Module System

Uses ES Modules (ESM) with "type": "module" for modern JavaScript features:

  • Clean import/export syntax
  • Top-level await support
  • Better tree-shaking compatibility

🧪 Testing

npm test

Test Coverage:

  • Input coordinate validation (bounds checking)
  • Weather code mapping (WMO codes)
  • Schema validation with Zod
  • Edge cases and error handling

📝 Project Structure

MCP-Weather/
├── src/
│   ├── index.js           # Main entry point
│   ├── server.js          # MCP server factory
│   ├── weatherService.js  # Weather API service
│   └── weatherTools.js    # MCP tools
├── package.json
├── demo.js                # Demo script
├── test.js                # Test suite
├── README.md
└── .env.example

🔧 Environment Variables

VariableValuesDefaultPurpose
TRANSPORTstdio, httpstdioTransport mode
PORT1-655353001HTTP server port (HTTP mode only)

Example:

# Run in HTTP mode on custom port
TRANSPORT=http PORT=8080 npm start

🐛 Troubleshooting

IssueSolution
MODULE_NOT_FOUNDEnsure "type": "module" in package.json
Port 3001 in useSet custom port: PORT=3002 npm run start:http
Invalid coordinates errorCheck bounds: latitude [-90, 90], longitude [-180, 180]
"Unknown weather condition"WMO code mapping - check Open-Meteo documentation
ESM import errorsVerify all imports have .js file extension

📜 License

ISC

🤝 Contributing

This project follows the MCP specification and best practices for Node.js server development.

Reviews

No reviews yet

Sign in to write a review