Skip to main content
Glama
MinhHieu-Nguyen-dn

Weather MCP Server

get_alerts

Retrieve active weather alerts for any US state using two-letter state codes to monitor severe conditions and stay informed about local warnings.

Instructions

Get weather alerts for a US state.

Args:
    state: Two-letter US state code (e.g. CA, NY)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
stateYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main execution logic for the 'get_alerts' tool. Fetches active weather alerts for a given US state using the NWS API, validates input, handles errors, processes multiple alerts with progress reporting, and formats the output using helper functions.
    @mcp.tool()
    async def get_alerts(state: str, ctx: Context[ServerSession, None]) -> str:
        """Get weather alerts for a US state.
    
        Args:
            state: Two-letter US state code (e.g. CA, NY)
        """
        await ctx.info(f"Fetching weather alerts for state: {state}")
        logger.info(f"Processing alerts request for state: {state}")
        
        # Validate state code
        if len(state) != 2:
            error_msg = f"Invalid state code format: {state}. Expected 2-letter code."
            await ctx.warning(error_msg)
            logger.warning(error_msg)
            return "Error: State code must be exactly 2 letters (e.g., CA, NY)"
        
        state = state.upper()
        url = f"{NWS_API_BASE}/alerts/active/area/{state}"
        
        await ctx.debug(f"Requesting alerts from URL: {url}")
        data = await make_nws_request(url, ctx)
    
        if not data:
            error_msg = f"Unable to fetch alerts for state: {state}"
            await ctx.error(error_msg)
            logger.error(error_msg)
            return "Unable to fetch alerts or no alerts found."
    
        if "features" not in data:
            error_msg = f"Invalid response format for state: {state}"
            await ctx.error(error_msg)
            logger.error(error_msg)
            return "Invalid response format from weather service."
    
        if not data["features"]:
            await ctx.info(f"No active alerts found for state: {state}")
            logger.info(f"No active alerts for state: {state}")
            return "No active alerts for this state."
    
        alert_count = len(data["features"])
        await ctx.info(f"Processing {alert_count} alerts for state: {state}")
        logger.info(f"Found {alert_count} alerts for state: {state}")
        
        # Process alerts with progress reporting
        alerts = []
        for i, feature in enumerate(data["features"]):
            progress = (i + 1) / alert_count
            await ctx.report_progress(
                progress=progress,
                total=1.0,
                message=f"Processing alert {i + 1}/{alert_count}"
            )
            
            formatted_alert = await format_alert(feature, ctx)
            alerts.append(formatted_alert)
        
        await ctx.info(f"Successfully processed {alert_count} alerts for state: {state}")
        logger.info(f"Successfully processed {alert_count} alerts for state: {state}")
        
        return "\n---\n".join(alerts)
  • Helper function to format an individual weather alert feature into a human-readable string, extracting key properties like event, area, severity, description, and instructions.
    async def format_alert(feature: dict, ctx: Context[ServerSession, None] | None = None) -> str:
        """Format an alert feature into a readable string."""
        try:
            props = feature["properties"]
            alert_event = props.get('event', 'Unknown')
            
            if ctx:
                await ctx.debug(f"Formatting alert for event: {alert_event}")
            logger.debug(f"Formatting alert for event: {alert_event}")
            
            formatted_alert = f"""
    Event: {alert_event}
    Area: {props.get('areaDesc', 'Unknown')}
    Severity: {props.get('severity', 'Unknown')}
    Description: {props.get('description', 'No description available')}
    Instructions: {props.get('instruction', 'No specific instructions provided')}
    """
            return formatted_alert
            
        except KeyError as e:
            error_msg = f"Missing required field in alert data: {e}"
            if ctx:
                await ctx.warning(error_msg)
            logger.warning(error_msg)
            return "Error: Invalid alert data format"
            
        except Exception:
            error_msg = "Unexpected error while formatting alert"
            if ctx:
                await ctx.error(error_msg)
            logger.exception("Unexpected error while formatting alert")
            return "Error: Could not format alert"
  • Shared helper function for making HTTP requests to the NWS API, with comprehensive error handling for timeouts, HTTP errors, network issues, and logging via MCP context.
    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

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.3/5.0
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It doesn't mention return format, pagination, whether alerts are current or historical, severity levels, or any rate limits or auth requirements. For a read-type tool the lack of annotations leaves significant gaps.

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

Conciseness5/5

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

Extremely concise and well-scoped. The description is two lines with an args docstring for the single parameter. Every word is functional with zero waste.

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?

An output schema exists, which reduces the burden for explaining return values. However, with 0% schema description coverage, 1 single param (already covered in the args), no annotations, and no behavioral details (alert types, severity, expiration, update frequency), the description is minimal. For a weather alert tool, agents would benefit from knowing what constitutes an alert return vs. a no-alert return.

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 single parameter 'state' is described in the argument docstring as a two-letter US state code with examples (CA, NY), which adds meaning beyond the bare schema. However, it doesn't specify case sensitivity, whether territories are included (e.g., DC, PR), or what happens for invalid state codes. The examples help but full semantics aren't covered.

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 gets weather alerts for a US state, with a specific verb ('get') and resource ('weather alerts') and a geographic scope ('US state'). It distinguishes from the sibling tool 'get_forecast' by the resource type, though it doesn't explicitly name the sibling.

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

Usage Guidelines3/5

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

The description implies usage context ('for a US state') but provides no when-to-use guidance, no exclusions, and no comparison to the sibling get_forecast tool. The intent is reasonably clear but the agent doesn't know when alerts vs forecast is more appropriate.

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

Deploy Server

Other Tools