dennisonbertram/mcp-weather
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.
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
- Sign up at OpenWeatherMap
- Verify your email address
- Generate a free API key from your dashboard
- 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 requestsGET /mcp
- Server-Sent Events for streamingDELETE /mcp
- Session terminationGET /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 locationget_weather_by_coordinates(lat, lon)
- Weather by precise coordinates
Forecasting
get_5day_forecast(location)
- 5-day forecast with 3-hour intervalsget_hourly_forecast(location)
- Detailed hourly predictionsget_forecast_summary(location)
- Human-readable weather summary
Geocoding
geocode_location(location)
- Convert location name to coordinatesreverse_geocode(lat, lon)
- Convert coordinates to location namesearch_cities(query)
- Find cities matching search terms
Air Quality
get_air_pollution(lat, lon)
- Current air quality and pollutant levelsget_air_pollution_forecast(lat, lon)
- 5-day air quality forecastget_air_pollution_history(lat, lon, start, end)
- Historical pollution data
One Call API
get_onecall_weather(lat, lon)
- Comprehensive weather dataget_weather_timemachine(lat, lon, date)
- Historical weather dataget_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
- Fork the repository
- Create a feature branch
- Add comprehensive tests
- Follow TypeScript and ESLint guidelines
- Submit a pull request
๐ License
MIT License - see LICENSE file for details.
๐ Links
๐ API Coverage
This MCP server implements the following OpenWeatherMap APIs:
API | Endpoints | Status | Free 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
Transport | Use Case | Pros | Cons |
---|---|---|---|
STDIO | MCP Clients | Native MCP support, secure | CLI/desktop only |
HTTP | Web APIs | REST-like, widely supported | Stateless, no push |
SSE | Real-time apps | Server push, live updates | Browser-specific |
Built with โค๏ธ for the MCP ecosystem