Skip to main content
Glama
nyalamrithwik-oss

Weather MCP Server

README.md
# Weather MCP Server - Day 10

## Overview

Day 10 of the 30-Day RAG Learning Journey focuses on building a **Weather MCP Server** that integrates with real-time weather APIs. This project combines RAG (Retrieval-Augmented Generation) principles with Location-Based Context Synthesis (LBCS) systems.

## Project Structure

```
day10-weather-mcp/
├── weather_mcp_server.py    # Main MCP server with weather tools
├── test_weather.py          # Test client for API validation
├── requirements.txt         # Python dependencies
├── .env                     # Environment variables (API keys)
├── .env.example            # Template for environment setup
├── README.md               # This file
└── venv/                   # Virtual environment
```

## Features - 5 Weather Tools

### 1. **get_current_weather** (location: str)
Returns comprehensive current weather data:
- Temperature
- Feels Like temperature
- Humidity percentage
- Weather description
- Wind speed
- Pressure
- Cloud coverage

```python
# Example usage
location = "London"
units = "metric"  # or "imperial", "standard"
```

### 2. **get_forecast** (location: str, days: int)
Returns 5-day weather forecast with daily highs/lows:
- Daily high temperatures
- Daily low temperatures
- Weather conditions
- Configurable forecast days (1-5)

```python
# Example usage
location = "Paris"
days = 5
```

### 3. **get_weather_alerts** (location: str)
Returns severe weather warnings and alerts (if any):
- Alert event type
- Start/end times
- Alert descriptions
- Severity indicators

```python
# Example usage
location = "New York"
```

### 4. **compare_locations** (location1: str, location2: str)
Returns side-by-side weather comparison:
- Temperature comparison
- Humidity levels
- Wind speeds
- Weather conditions
- Pressure readings

```python
# Example usage
location1 = "London"
location2 = "New York"
```

### 5. **get_weather_by_coords** (lat: float, lon: float)
Returns weather for specific latitude/longitude:
- Temperature at coordinates
- Location name (reverse geocoding)
- All weather parameters
- Pressure, humidity, wind

```python
# Example usage
lat = 51.5074
lon = -0.1278
```

## Tech Stack

- **Python 3.11**: Core programming language
- **MCP 1.25.0**: Model Context Protocol for Claude integration
- **httpx 0.28.1**: Async HTTP client for API calls
- **OpenWeatherMap API**: Real-time weather data provider
- **python-dotenv**: Environment variable management
- **Async/await patterns**: Non-blocking I/O operations

## Setup Instructions

### 1. Prerequisites

- Python 3.8+
- OpenWeather API key (free tier available)
- Virtual environment (recommended)

### 2. Get API Key

1. Visit [OpenWeather API](https://openweathermap.org/api)
2. Sign up for a free account
3. Get your API key from the account dashboard
4. Copy your API key

### 3. Install Dependencies

```bash
# Navigate to directory
cd week2-mcp/day10-weather-mcp

# Create and activate virtual environment
python -m venv venv

# Windows
venv\Scripts\activate

# macOS/Linux
source venv/bin/activate

# Install packages
pip install -r requirements.txt
```

### 4. Configure Environment

```bash
# Copy template
cp .env.example .env

# Edit .env and add your API key
# WEATHER_API_KEY=your_actual_api_key_here
```

### 5. Run Server

```bash
python weather_mcp_server.py
```

### 6. Test Integration

```bash
python test_weather.py
```

## API Response Examples

### Current Weather (London)
```
Current Weather in London, GB:

Description: Partly Cloudy
Temperature: 8.5°C
Feels Like: 6.2°C
Humidity: 72%
Wind Speed: 4.5 m/s
Pressure: 1013 hPa
Cloudiness: 40%
```

### Weather Forecast (5-Day)
```
5-Day Weather Forecast for London:

Date: 2025-12-28
High: 10.2°C | Low: 5.3°C
Conditions: Rainy
--------------------------------------------------

Date: 2025-12-29
High: 9.1°C | Low: 4.8°C
Conditions: Cloudy
--------------------------------------------------
```

### Weather Comparison
```
Weather Comparison: London vs Paris
============================================================
London               | Paris
------------------------------------------------------------
Temperature:    8.5°C | 9.2°C
Feels Like:     6.2°C | 7.1°C
Humidity:       72%   | 65%
Conditions:     Cloudy| Clear
Wind Speed:     4.5   | 3.2 m/s
```

## Integration with Claude Desktop

To use this MCP server with Claude Desktop:

1. Edit your Claude Desktop configuration file:
   - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
   - **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`

2. Add the weather server:
```json
{
  "mcpServers": {
    "weather": {
      "command": "python",
      "args": ["C:\\path\\to\\weather_mcp_server.py"]
    }
  }
}
```

3. Restart Claude Desktop

## Learning Concepts

### RAG & LBCS Integration

This project demonstrates:

1. **Context-Aware Retrieval**: Using location data to retrieve relevant weather information
2. **Real-time Data Processing**: Async handling of API calls
3. **MCP Protocol**: Integrating external tools with LLMs
4. **Error Handling**: Graceful degradation when APIs fail
5. **Data Formatting**: Structured output for LLM consumption

### Key Technologies

- **asyncio**: Asynchronous Python for concurrent requests
- **httpx**: Async HTTP client for API calls
- **OpenWeather API**: Real-time weather data provider
- **MCP Protocol**: Tool integration with Claude
- **Type Hints**: Full Python type annotations

## Usage Examples

### Ask Claude

> "What's the weather like in Tokyo right now?"

Claude uses `get_current_weather` tool to retrieve current conditions.

> "Compare the weather between London, Paris, and New York"

Claude uses `compare_locations` tool for side-by-side analysis.

> "What will the weather be like in Sydney over the next 5 days?"

Claude uses `get_forecast` tool to get daily predictions.

> "Get the weather at coordinates 51.5074, -0.1278"

Claude uses `get_weather_by_coords` for precise location weather.

> "Are there any weather alerts for Los Angeles?"

Claude uses `get_weather_alerts` to check for severe weather.

## Troubleshooting

### API Key Not Working
- Verify your API key is correct in `.env`
- Check if your OpenWeather account is activated
- Ensure you have enough API call quota
- Wait 10 minutes after creating account before first use

### Connection Errors
- Check your internet connection
- Verify OpenWeather API is accessible
- Check firewall settings
- Verify the domain isn't blocked in your region

### Import Errors
- Ensure virtual environment is activated
- Reinstall requirements: `pip install -r requirements.txt`
- Check Python version (3.8+ required)

### Tool Not Found Errors
- Restart Claude Desktop after adding server config
- Verify server config JSON is valid
- Check file paths are absolute, not relative

## File Descriptions

### weather_mcp_server.py
Main MCP server implementation with:
- Tool registration (`list_tools`)
- Tool execution (`call_tool`)
- Handler functions for each weather tool
- Async HTTP client setup
- Error handling and logging

### test_weather.py
Test client for validating:
- Server startup
- Tool execution
- API connectivity
- Response formatting

### requirements.txt
Python package dependencies:
- mcp==1.25.0
- aiosqlite==0.21.0
- python-dotenv==1.0.0
- httpx>=0.27.1
- requests==2.31.0

### .env / .env.example
Environment configuration:
- WEATHER_API_KEY: Your OpenWeather API key
- SERVER_PORT: Server port (default 8000)
- LOG_LEVEL: Logging level (INFO, DEBUG, etc.)

## Next Steps (Day 11)

- [ ] Add air quality index (AQI) integration
- [ ] Implement weather history retrieval
- [ ] Add UV index and visibility data
- [ ] Create weather-based activity recommendations
- [ ] Build predictive models for weather patterns
- [ ] Add support for severe weather notifications
- [ ] Integrate multiple weather providers
- [ ] Create weather analytics dashboard

## Performance Metrics

- **Average Response Time**: ~500-800ms per API call
- **Concurrent Requests**: Supports multiple simultaneous queries
- **API Rate Limit**: Depends on OpenWeather plan (1000/day free)
- **Server Memory**: ~100MB baseline
- **Database**: Currently stateless (can add persistent cache)

## Resources

- [OpenWeather API Documentation](https://openweathermap.org/api)
- [MCP Specification](https://modelcontextprotocol.io)
- [Python asyncio Guide](https://docs.python.org/3/library/asyncio.html)
- [httpx Documentation](https://www.python-httpx.org/)
- [Claude API Documentation](https://claude.ai/docs)

## Contributing

To extend this project:

1. Add new weather tools in `list_tools()`
2. Create handler functions in `weather_mcp_server.py`
3. Add tool calls in `call_tool()` function
4. Test with `test_weather.py`
5. Update documentation

## Author

Rithwik Nyalam  
Date: December 28, 2025  
Part of: 30-Day RAG Learning Journey - Week 2

---

**Last Updated**: December 28, 2025  
**Status**: Production Ready  
**Version**: 1.0.0