MCP Weather Server
README.md
# ๐ค๏ธ MCP Weather Server
A production-grade Model Context Protocol (MCP) server providing comprehensive real-time weather data using the free **Open-Meteo API**.
[](https://github.com/your-repo/mcp-weather)
[](LICENSE)
[](package.json)
## โจ 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](https://redis.io)
### Setup
```bash
# 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
```bash
# 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)
```bash
# Start in stdio mode for MCP Inspector
npm start
# Then open MCP Inspector and connect to the server
```
### HTTP/SSE Mode
```bash
# 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
```bash
# 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:**
```json
{
"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:**
```json
{
"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
```bash
# 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
```javascript
// 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
```bash
# 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)
```bash
npm start
# or: node src/index.js
```
Perfect for direct MCP client integration (Claude Desktop, IDEs, etc.)
### HTTP/SSE Mode
```bash
# 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
```bash
node demo.js
```
Shows real-world example calls to weather service for multiple cities.
### Run Tests
```bash
npm test
```
Validates input schemas and weather code mappings.
## ๐ ๏ธ Available Tools
### Tool: `get_weather`
Get current weather for a location.
**Parameters:**
```json
{
"latitude": -90 to 90,
"longitude": -180 to 180
}
```
**Example:**
```bash
# 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:**
```json
{
"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
- **API**: [Open-Meteo](https://open-meteo.com/) - Free, open-source weather API
- **Documentation**: https://open-meteo.com/en/docs
- **Weather Codes**: [WMO Weather Interpretation Codes](https://www.noaa.gov/media/e1906d56-9acc-4ea6-a60c-4e214a01b47f/WMO-Weather-interpretation-codes.pdf)
## ๐ฆ 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
```bash
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:**
```bash
# 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.This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo issues