get_weather_forecast
Fetch accurate weather forecasts for any city up to 5 days ahead. Specify city, duration, and units ('metric' or 'imperial') to retrieve detailed weather data using OpenWeatherMap.
Instructions
Get weather forecast for a city using OpenWeatherMap.
Args:
city: City name (e.g. 'London', 'New York')
days: Number of days (1-5)
units: Units of measurement ('metric' or 'imperial')
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| city | Yes | ||
| days | No | ||
| units | No | metric |
Implementation Reference
- weather.py:259-288 (handler)The primary handler for the 'get_weather_forecast' tool. This async function, decorated with @mcp.tool(), takes a city name, number of days (default 3), and units (default metric). It fetches the 5-day forecast from OpenWeatherMap API, limits to requested days, formats the data using format_forecast helper, and returns JSON string.@mcp.tool() async def get_weather_forecast(city: str, days: int = 3, units: str = "metric") -> str: """Get weather forecast for a city using OpenWeatherMap. Args: city: City name (e.g. 'London', 'New York') days: Number of days (1-5) units: Units of measurement ('metric' or 'imperial') """ print(f"get_weather_forecast called with city: {city}, days: {days}, units: {units}", file=sys.stderr) if not OPENWEATHER_API_KEY: return "OpenWeatherMap API key not configured. Please set OPENWEATHER_API_KEY environment variable." if days < 1 or days > 5: return "Days must be between 1 and 5." url = f"{OPENWEATHER_API_BASE}/forecast" params = { "q": city, "units": units } data = await make_openweather_request(url, params) if not data: return "Unable to fetch forecast data." result = format_forecast(data, days, units) return json.dumps(result, indent=2)
- weather.py:118-172 (helper)Key helper function format_forecast used by get_weather_forecast to process raw API forecast data into a structured daily forecast dictionary with weather details per time slot, limited to the requested number of days.def format_forecast(data: dict, days: int, units: str) -> dict: """Format forecast data from OpenWeatherMap.""" temp_unit = "°C" if units == "metric" else "°F" speed_unit = "m/s" if units == "metric" else "mph" try: city_data = data.get("city", {}) forecast_list = data.get("list", []) daily_forecasts = {} for item in forecast_list: date = item.get("dt_txt", "").split(" ")[0] if date not in daily_forecasts: daily_forecasts[date] = [] daily_forecasts[date].append({ "time": item.get("dt_txt", "").split(" ")[1], "temperature": f"{item.get('main', {}).get('temp', 0)}{temp_unit}", "feels_like": f"{item.get('main', {}).get('feels_like', 0)}{temp_unit}", "min_temp": f"{item.get('main', {}).get('temp_min', 0)}{temp_unit}", "max_temp": f"{item.get('main', {}).get('temp_max', 0)}{temp_unit}", "humidity": f"{item.get('main', {}).get('humidity', 0)}%", "pressure": f"{item.get('main', {}).get('pressure', 0)} hPa", "weather": { "main": item.get('weather', [{}])[0].get('main', "Unknown"), "description": item.get('weather', [{}])[0].get('description', "Unknown"), "icon": item.get('weather', [{}])[0].get('icon', "Unknown") }, "wind": { "speed": f"{item.get('wind', {}).get('speed', 0)} {speed_unit}", "direction": item.get('wind', {}).get('deg', 0) }, "cloudiness": f"{item.get('clouds', {}).get('all', 0)}%" }) forecast_dates = list(daily_forecasts.keys())[:days] limited_forecasts = {date: daily_forecasts[date] for date in forecast_dates if date in daily_forecasts} return { "location": { "name": city_data.get("name", "Unknown"), "country": city_data.get("country", "Unknown"), "coordinates": { "latitude": city_data.get("coord", {}).get("lat", 0), "longitude": city_data.get("coord", {}).get("lon", 0) } }, "forecast": limited_forecasts } except Exception as e: print(f"Error formatting forecast data: {e}", file=sys.stderr) return {"error": "Error formatting forecast data"}
- weather.py:39-55 (helper)Helper function make_openweather_request used to make authenticated HTTP requests to OpenWeatherMap API endpoints.async def make_openweather_request(url: str, params: dict) -> dict[str, Any] | None: """Make a request to OpenWeatherMap API with proper error handling.""" if not OPENWEATHER_API_KEY: print("OpenWeatherMap API key not found", file=sys.stderr) return None params["appid"] = OPENWEATHER_API_KEY async with httpx.AsyncClient() as client: try: response = await client.get(url, params=params, timeout=30.0) response.raise_for_status() return response.json() except Exception as e: print(f"OpenWeatherMap API error: {e}", file=sys.stderr) return None
- weather.py:259-259 (registration)The @mcp.tool() decorator registers the get_weather_forecast function as an MCP tool.@mcp.tool()