Skip to content

Sample MCP Server - Python (weather-data-server) #921

@crivetimihai

Description

@crivetimihai

Overview

Create a simple MCP Server in Python that provides weather data and forecasting using public APIs, perfect for demonstrating API integration patterns and practical utility.

Server Specifications

Server Details

  • Name: weather-data-server
  • Language: Python 3.11+
  • Location: mcp-servers/python/weather_data_server/
  • Complexity: ⭐⭐ Beginner to Intermediate
  • Purpose: Demonstrate API integration and data aggregation via MCP

Core Features

  • Current weather conditions lookup
  • Weather forecasting (5-day, 7-day, extended)
  • Weather alerts and warnings
  • Historical weather data
  • Multiple location formats (city, coordinates, ZIP)
  • Support for multiple weather APIs

Supported Weather APIs

  • OpenWeatherMap: Free tier with current + 5-day forecast
  • WeatherAPI.com: Free tier with current + 3-day forecast
  • National Weather Service (US): Free US weather data
  • MeteoBlue: Free tier with basic forecasting
  • Weatherbit: Free tier with 16-day forecast

Tools Provided

1. get_current_weather

Get current weather conditions for a location

@dataclass
class CurrentWeatherRequest:
    location: str  # City name, coordinates, or ZIP code
    api_provider: str = "openweathermap"  # openweathermap, weatherapi, nws
    units: str = "metric"  # metric, imperial, kelvin
    language: str = "en"
    include_details: bool = True  # Extended weather details

2. get_weather_forecast

Get weather forecast for specified time range

@dataclass
class WeatherForecastRequest:
    location: str
    api_provider: str = "openweathermap"
    forecast_days: int = 5  # 1-16 depending on provider
    units: str = "metric"
    include_hourly: bool = False
    include_alerts: bool = True

3. get_weather_alerts

Get weather alerts and warnings for a region

@dataclass
class WeatherAlertsRequest:
    location: str
    api_provider: str = "nws"  # National Weather Service best for US alerts
    alert_types: List[str] = ["all"]  # severe, watch, warning, advisory
    active_only: bool = True
    include_descriptions: bool = True

4. get_historical_weather

Retrieve historical weather data

@dataclass
class HistoricalWeatherRequest:
    location: str
    start_date: str  # YYYY-MM-DD format
    end_date: str
    api_provider: str = "openweathermap"
    data_points: List[str] = ["temperature", "humidity", "precipitation"]
    aggregation: str = "daily"  # hourly, daily, monthly

5. compare_locations

Compare weather conditions across multiple locations

@dataclass
class LocationComparisonRequest:
    locations: List[str]
    api_provider: str = "openweathermap"
    comparison_metrics: List[str] = ["temperature", "humidity", "wind_speed"]
    units: str = "metric"
    include_forecast: bool = False

6. weather_analytics

Analyze weather patterns and trends

@dataclass
class WeatherAnalyticsRequest:
    location: str
    api_provider: str = "weatherapi"
    analysis_type: str = "trend"  # trend, seasonal, extreme, average
    time_period: str = "30_days"  # 7_days, 30_days, 90_days, 1_year
    metrics: List[str] = ["temperature", "precipitation", "humidity"]

Implementation Requirements

Directory Structure

mcp-servers/python/weather_data_server/
├── src/
│   └── weather_data_server/
│       ├── __init__.py
│       ├── server.py
│       ├── providers/
│       │   ├── __init__.py
│       │   ├── openweathermap.py
│       │   ├── weatherapi.py
│       │   ├── national_weather_service.py
│       │   ├── meteo_blue.py
│       │   └── base_provider.py
│       ├── tools/
│       │   ├── __init__.py
│       │   ├── current_weather.py
│       │   ├── forecast.py
│       │   ├── alerts.py
│       │   ├── historical.py
│       │   └── analytics.py
│       ├── utils/
│       │   ├── __init__.py
│       │   ├── location_resolver.py
│       │   ├── unit_converter.py
│       │   └── data_formatter.py
│       └── config.py
├── tests/
│   ├── __init__.py
│   ├── test_providers.py
│   ├── test_tools.py
│   └── fixtures/
│       └── sample_responses/
├── requirements.txt
├── requirements-dev.txt
├── README.md
├── examples/
│   ├── basic_weather.py
│   ├── forecast_analysis.py
│   └── weather_alerts.py
└── .env.example

Dependencies

# requirements.txt
mcp>=1.0.0
httpx>=0.25.0
aiohttp>=3.9.0
pydantic>=2.5.0
python-dotenv>=1.0.0
geopy>=2.4.0  # Location geocoding
pytz>=2023.3  # Timezone handling
requests>=2.31.0

Configuration

# config.yaml
api_providers:
  openweathermap:
    base_url: "https://api.openweathermap.org/data/2.5"
    api_key_env: "OPENWEATHERMAP_API_KEY"
    rate_limit: 1000  # requests per hour
    free_tier_limit: true
    
  weatherapi:
    base_url: "https://api.weatherapi.com/v1"
    api_key_env: "WEATHERAPI_KEY"
    rate_limit: 1000
    
  nws:
    base_url: "https://api.weather.gov"
    rate_limit: 300  # No API key required
    
default_settings:
  provider: "openweathermap"
  units: "metric"
  language: "en"
  cache_ttl: 600  # 10 minutes
  timeout: 30

location_services:
  enable_geocoding: true
  cache_coordinates: true
  default_country: "US"

Environment Variables

# .env.example
# OpenWeatherMap (free tier: 1000 calls/hour)
OPENWEATHERMAP_API_KEY=your_api_key_here

# WeatherAPI.com (free tier: 1M calls/month)  
WEATHERAPI_KEY=your_api_key_here

# Optional: Additional providers
METEO_BLUE_API_KEY=your_api_key_here
WEATHERBIT_API_KEY=your_api_key_here

# Server configuration
WEATHER_SERVER_PORT=8000
WEATHER_CACHE_ENABLED=true
WEATHER_DEFAULT_PROVIDER=openweathermap

Usage Examples

Current Weather

# Get current weather for a city
echo '{
  "method": "tools/call",
  "params": {
    "name": "get_current_weather",
    "arguments": {
      "location": "San Francisco, CA",
      "api_provider": "openweathermap",
      "units": "metric",
      "include_details": true
    }
  }
}' | weather-data-server

Weather Forecast

# 5-day weather forecast
echo '{
  "method": "tools/call",
  "params": {
    "name": "get_weather_forecast",
    "arguments": {
      "location": "40.7128,-74.0060",
      "forecast_days": 5,
      "include_hourly": true,
      "include_alerts": true
    }
  }
}' | weather-data-server

Weather Alerts

# Check for weather alerts
echo '{
  "method": "tools/call",
  "params": {
    "name": "get_weather_alerts",
    "arguments": {
      "location": "Miami, FL",
      "api_provider": "nws",
      "alert_types": ["warning", "watch"],
      "active_only": true
    }
  }
}' | weather-data-server

Location Comparison

# Compare weather across cities
echo '{
  "method": "tools/call",
  "params": {
    "name": "compare_locations",
    "arguments": {
      "locations": ["New York", "Los Angeles", "Chicago"],
      "comparison_metrics": ["temperature", "humidity", "wind_speed"],
      "include_forecast": true
    }
  }
}' | weather-data-server

Advanced Features

  • Multi-Provider Fallback: Automatic failover between weather APIs
  • Smart Caching: Intelligent caching based on data freshness requirements
  • Location Intelligence: Geocoding and reverse geocoding
  • Data Aggregation: Combine data from multiple sources
  • Custom Alerts: User-defined weather alert conditions

Response Format Examples

{
  "location": {
    "name": "San Francisco",
    "country": "US",
    "coordinates": {"lat": 37.7749, "lon": -122.4194}
  },
  "current": {
    "temperature": 18.5,
    "feels_like": 17.8,
    "humidity": 72,
    "pressure": 1013.2,
    "wind_speed": 3.1,
    "wind_direction": 245,
    "visibility": 16.0,
    "uv_index": 3,
    "condition": "Partly Cloudy"
  },
  "metadata": {
    "provider": "openweathermap",
    "timestamp": "2024-01-15T10:30:00Z",
    "units": "metric"
  }
}

Testing Requirements

  • Unit tests for all weather operations
  • Integration tests with mock API responses
  • Error handling tests for API failures
  • Rate limiting and retry logic tests
  • Location parsing and validation tests

Acceptance Criteria

  • Python MCP server with 6+ weather tools
  • Integration with multiple weather API providers
  • Current weather conditions lookup
  • Weather forecasting capabilities (5-day minimum)
  • Weather alerts and warnings support
  • Historical weather data retrieval
  • Location comparison features
  • Multi-provider fallback and error handling
  • Caching for performance optimization
  • Comprehensive test suite (>90% coverage)
  • Complete documentation with weather API examples

Priority

Low - Great project for learning API integration patterns

Use Cases

  • Weather-aware applications and automation
  • Travel planning and recommendations
  • Agricultural and outdoor activity planning
  • IoT and smart home integration
  • Event planning and scheduling
  • Transportation and logistics optimization
  • Emergency preparedness and alerts
  • Climate research and analysis

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestmcp-serversMCP Server SamplesoicOpen Innovation Community ContributionspythonPython / backend development (FastAPI)

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions