MCP Weather Server

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.

Category
访问服务器

README

🌤️ 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

Pattern Implementation Purpose
Factory createWeatherMcpServer() Isolated server instances per session
Strategy Stdio vs HTTP transport strategies Multiple deployment modes
Adapter MCP SDK transport wrapping Unified interface for different transports
Decorator Response formatting with emojis Enhanced user experience
Observer Metrics collection Performance monitoring
Proxy Cache layer API 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

City Latitude Longitude
Paris 48.8566 2.3522
London 51.5074 -0.1278
New York 40.7128 -74.0060
Tokyo 35.6762 139.6503
Sydney -33.8688 151.2093
Berlin 52.5200 13.4050
Los Angeles 34.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

Variable Values Default Purpose
TRANSPORT stdio, http stdio Transport mode
PORT 1-65535 3001 HTTP server port (HTTP mode only)

Example:

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

🐛 Troubleshooting

Issue Solution
MODULE_NOT_FOUND Ensure "type": "module" in package.json
Port 3001 in use Set custom port: PORT=3002 npm run start:http
Invalid coordinates error Check bounds: latitude [-90, 90], longitude [-180, 180]
"Unknown weather condition" WMO code mapping - check Open-Meteo documentation
ESM import errors Verify all imports have .js file extension

📜 License

ISC

🤝 Contributing

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

推荐服务器

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 模型以安全和受控的方式获取实时的网络信息。

官方
精选