Skip to main content
Glama
MinhHieu-Nguyen-dn

Weather MCP Server

get_forecast

Retrieve weather forecasts for specific locations using latitude and longitude coordinates. This tool provides detailed weather predictions to help plan activities and prepare for conditions.

Instructions

Get weather forecast for a location.

Args:
    latitude: Latitude of the location
    longitude: Longitude of the location

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
latitudeYes
longitudeYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The @mcp.tool()-decorated handler function that implements the core logic for fetching and formatting the weather forecast from the National Weather Service (NWS) API using latitude and longitude coordinates.
    @mcp.tool()
    async def get_forecast(latitude: float, longitude: float, ctx: Context[ServerSession, None]) -> str:
        """Get weather forecast for a location.
    
        Args:
            latitude: Latitude of the location
            longitude: Longitude of the location
        """
        await ctx.info(f"Fetching weather forecast for coordinates: {latitude}, {longitude}")
        logger.info(f"Processing forecast request for coordinates: {latitude}, {longitude}")
        
        # Validate coordinates
        if not (-90 <= latitude <= 90):
            error_msg = f"Invalid latitude: {latitude}. Must be between -90 and 90."
            await ctx.warning(error_msg)
            logger.warning(error_msg)
            return "Error: Latitude must be between -90 and 90 degrees."
        
        if not (-180 <= longitude <= 180):
            error_msg = f"Invalid longitude: {longitude}. Must be between -180 and 180."
            await ctx.warning(error_msg)
            logger.warning(error_msg)
            return "Error: Longitude must be between -180 and 180 degrees."
        
        # Step 1: Get the forecast grid endpoint
        await ctx.debug("Step 1: Getting forecast grid endpoint from NWS points API")
        points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
        
        await ctx.report_progress(
            progress=0.3,
            total=1.0,
            message="Getting grid information..."
        )
        
        points_data = await make_nws_request(points_url, ctx)
    
        if not points_data:
            error_msg = f"Unable to fetch forecast grid data for coordinates: {latitude}, {longitude}"
            await ctx.error(error_msg)
            logger.error(error_msg)
            return "Unable to fetch forecast data for this location."
    
        try:
            # Get the forecast URL from the points response
            forecast_url = points_data["properties"]["forecast"]
            await ctx.debug(f"Retrieved forecast URL: {forecast_url}")
            logger.debug(f"Forecast URL: {forecast_url}")
            
        except KeyError:
            error_msg = f"Invalid points response format for coordinates: {latitude}, {longitude}"
            await ctx.error(error_msg)
            logger.error(error_msg)
            return "Invalid response format from weather service points API."
    
        # Step 2: Get the detailed forecast
        await ctx.debug("Step 2: Getting detailed forecast data")
        await ctx.report_progress(
            progress=0.6,
            total=1.0,
            message="Fetching detailed forecast..."
        )
        
        forecast_data = await make_nws_request(forecast_url, ctx)
    
        if not forecast_data:
            error_msg = f"Unable to fetch detailed forecast for coordinates: {latitude}, {longitude}"
            await ctx.error(error_msg)
            logger.error(error_msg)
            return "Unable to fetch detailed forecast."
    
        try:
            # Format the periods into a readable forecast
            periods = forecast_data["properties"]["periods"]
            if not periods:
                await ctx.warning(f"No forecast periods available for coordinates: {latitude}, {longitude}")
                logger.warning(f"No forecast periods for coordinates: {latitude}, {longitude}")
                return "No forecast periods available for this location."
            
            period_count = min(len(periods), 5)  # Only show next 5 periods
            await ctx.info(f"Processing {period_count} forecast periods")
            logger.info(f"Processing {period_count} forecast periods")
            
            await ctx.report_progress(
                progress=0.8,
                total=1.0,
                message=f"Formatting {period_count} forecast periods..."
            )
            
            forecasts = []
            for i, period in enumerate(periods[:5]):
                forecast = f"""
    {period['name']}:
    Temperature: {period['temperature']}°{period['temperatureUnit']}
    Wind: {period['windSpeed']} {period['windDirection']}
    Forecast: {period['detailedForecast']}
    """
                forecasts.append(forecast)
                
                # Report progress for each period processed
                progress = 0.8 + (0.2 * (i + 1) / period_count)
                await ctx.report_progress(
                    progress=progress,
                    total=1.0,
                    message=f"Processed period {i + 1}/{period_count}"
                )
    
            await ctx.info(f"Successfully processed forecast for coordinates: {latitude}, {longitude}")
            logger.info(f"Successfully processed forecast for coordinates: {latitude}, {longitude}")
            
            return "\n---\n".join(forecasts)
            
        except KeyError as e:
            error_msg = f"Missing required field in forecast data: {e}"
            await ctx.error(error_msg)
            logger.exception("Missing required field in forecast data")
            return "Error: Invalid forecast data format."
            
        except Exception:
            error_msg = f"Unexpected error processing forecast for coordinates: {latitude}, {longitude}"
            await ctx.error(error_msg)
            logger.exception("Unexpected error processing forecast")
            return "Error: Could not process forecast data."
  • Shared helper function used by get_forecast (and get_alerts) to make authenticated HTTP requests to the NWS API with comprehensive error handling and MCP context logging.
    async def make_nws_request(url: str, ctx: Context[ServerSession, None] | None = None) -> dict[str, Any] | None:
        """Make a request to the NWS API with proper error handling."""
        headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
        
        if ctx:
            await ctx.debug(f"Making NWS API request to: {url}")
        logger.debug(f"Making request to NWS API: {url}")
        
        async with httpx.AsyncClient(follow_redirects=True) as client:
            try:
                response = await client.get(url, headers=headers, timeout=30.0)
                response.raise_for_status()
                
                if ctx:
                    await ctx.debug(f"NWS API request successful, status: {response.status_code}")
                logger.debug(f"NWS API request successful: {response.status_code}")
                
                return response.json()
                
            except httpx.TimeoutException:
                error_msg = f"Request timeout for URL: {url}"
                if ctx:
                    await ctx.error(error_msg)
                logger.exception("Request timeout occurred")
                return None
                
            except httpx.HTTPStatusError as e:
                error_msg = f"HTTP error {e.response.status_code} for URL: {url}"
                if ctx:
                    await ctx.error(error_msg)
                logger.exception("HTTP status error occurred")
                return None
                
            except httpx.RequestError:
                error_msg = f"Network error for URL: {url}"
                if ctx:
                    await ctx.error(error_msg)
                logger.exception("Network request error occurred")
                return None
                
            except Exception:
                error_msg = f"Unexpected error for URL: {url}"
                if ctx:
                    await ctx.error(error_msg)
                logger.exception("Unexpected error during NWS API request")
                return None
  • weather.py:307-307 (registration)
    List of available tools including get_forecast, exposed via the server_info tool.
    "available_tools": ["get_alerts", "get_forecast", "server_info"],
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states what the tool does but doesn't explain key behaviors: it doesn't specify the forecast timeframe (e.g., hourly, daily), data source, accuracy, rate limits, error handling, or authentication needs. This leaves significant gaps for an agent to understand how to use it effectively.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded, with the main purpose stated first followed by parameter details. It avoids unnecessary fluff, but the parameter section could be more integrated into the flow rather than a separate list, slightly affecting structure.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (2 required parameters) and the presence of an output schema, the description is somewhat complete but has gaps. It covers the basic purpose and parameters but lacks behavioral details and usage guidelines. The output schema likely handles return values, so the description doesn't need to explain those, but it should still address other contextual aspects like when to use it.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds minimal parameter semantics beyond the input schema. It lists 'latitude' and 'longitude' as arguments but doesn't explain their format (e.g., decimal degrees), valid ranges, or units. Since schema description coverage is 0%, the description partially compensates by naming the parameters, but it doesn't provide enough detail to fully understand their usage, aligning with the baseline for moderate coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Get weather forecast for a location.' It specifies the verb ('Get') and resource ('weather forecast') with the target ('location'). However, it doesn't differentiate from sibling tools like 'get_alerts' which might also provide weather-related information, preventing a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'get_alerts' or other weather-related tools. It lacks context about prerequisites, such as needing valid coordinates, and doesn't mention any exclusions or specific scenarios for usage.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/MinhHieu-Nguyen-dn/weather-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server