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
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 states the tool retrieves alerts but doesn't describe behavioral traits such as data freshness (e.g., real-time vs. cached), rate limits, error handling (e.g., for invalid state codes), or output format. The description is minimal and lacks essential context for safe and effective use.

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?

The description is appropriately sized and front-loaded: the first sentence states the purpose clearly, and the second provides parameter details in a structured 'Args:' format. There is no wasted text, and every sentence adds value. It efficiently communicates essential information without redundancy.

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 low complexity (one parameter) and the presence of an output schema (which handles return values), the description is minimally complete. It covers purpose and parameter semantics adequately but lacks behavioral context (e.g., permissions, rate limits) and usage guidelines. With no annotations, it should do more to compensate, but the output schema reduces the burden slightly.

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

Parameters4/5

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

The description adds significant meaning beyond the input schema, which has 0% description coverage. It explains that 'state' is a 'Two-letter US state code (e.g. CA, NY)', providing crucial semantics and examples that the schema's generic string type lacks. With only one parameter, this compensation is effective, though it doesn't cover edge cases like case sensitivity or invalid codes.

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 alerts for a US state.' It specifies the verb ('Get') and resource ('weather alerts') with geographic scope ('US state'), making it distinct from sibling tools like 'get_forecast' (which likely provides forecasts rather than alerts) and 'server_info' (which is unrelated). However, it doesn't explicitly differentiate from 'get_forecast' in terms of alert vs. forecast data, which prevents 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. It doesn't mention 'get_forecast' as an alternative for non-alert weather data or specify scenarios where alerts are preferred over forecasts. The geographic constraint ('US state') is stated, but this is part of the purpose rather than usage context. No exclusions or prerequisites are provided.

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