Skip to main content
Glama
sun873087

MCP Weather Sample

by sun873087

get_forecast

Retrieve weather forecast data for specific geographic coordinates by providing latitude and longitude values.

Instructions

獲取特定位置的預報資料

Args:
    latitude (float): 緯度
    longitude (float): 經度

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
latitudeYes
longitudeYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main handler for get_forecast tool in stdio transport - fetches weather forecast data from NOAA NWS API and formats it for display. Takes latitude and longitude parameters, fetches grid points endpoint, then retrieves and formats forecast periods.
    async def get_forecast(latitude: float, longitude: float) -> str:
        """
        獲取特定位置的預報資料
    
        Args:
            latitude (float): 緯度
            longitude (float): 經度
        """
        # 首先取得預測網格端點
        points_url = f"{NWS_API_BASE_URL}/points/{latitude},{longitude}"
        points_data = await make_nws_request(points_url)
    
        if not points_data:
            return "Unable to fetch forecast data for this location."
        
        # 從端點取得詳細預報
        forecast_url = points_data["properties"]["forecast"]
        forecast_data = await make_nws_request(forecast_url)
    
        if not forecast_data:
            return "Unable to fetch detailed forecast."
        
        periods = forecast_data["properties"]["periods"]
        forecasts = []
    
        for period in periods[:5]:
            forecast = f"""
    {period['name']}:
    Temperature: {period['temperature']}°{period['temperatureUnit']}
    Wind: {period['windSpeed']} {period['windDirection']}
    Forecast: {period['detailedForecast']}
    """
            forecasts.append(forecast)
    
        return "\n\n".join(forecasts)
  • Main handler for get_forecast tool in streamable-http transport - similar to stdio version but includes Context parameter for logging via ctx.info(). Uses '\n---\n' separator between forecast periods.
    async def get_forecast(latitude: float, longitude: float, ctx: Context) -> str:
        """Get weather forecast for a location.
    
        Args:
            latitude: Latitude of the location
            longitude: Longitude of the location
        """
        # First get the forecast grid endpoint
        points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
        points_data = await make_nws_request(points_url)
    
        await ctx.info(f"Received data: {points_data}")
    
        if not points_data:
            return "Unable to fetch forecast data for this location."
    
        # Get the forecast URL from the points response
        forecast_url = points_data["properties"]["forecast"]
        forecast_data = await make_nws_request(forecast_url)
    
        if not forecast_data:
            return "Unable to fetch detailed forecast."
    
        # Format the periods into a readable forecast
        periods = forecast_data["properties"]["periods"]
        forecasts = []
        for period in periods[:5]:  # Only show next 5 periods
            forecast = f"""
    {period['name']}:
    Temperature: {period['temperature']}°{period['temperatureUnit']}
    Wind: {period['windSpeed']} {period['windDirection']}
    Forecast: {period['detailedForecast']}
    """
            forecasts.append(forecast)
    
        return "\n---\n".join(forecasts)
  • Main handler for get_forecast tool in SSE transport - nearly identical to streamable-http version with Context parameter and logging capability. Fetches forecast from NOAA NWS API and returns formatted weather periods.
    async def get_forecast(latitude: float, longitude: float, ctx: Context) -> str:
        """Get weather forecast for a location.
    
        Args:
            latitude: Latitude of the location
            longitude: Longitude of the location
        """
        # First get the forecast grid endpoint
        points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
        points_data = await make_nws_request(points_url)
    
        await ctx.info(f"Received data: {points_data}")
    
        if not points_data:
            return "Unable to fetch forecast data for this location."
    
        # Get the forecast URL from the points response
        forecast_url = points_data["properties"]["forecast"]
        forecast_data = await make_nws_request(forecast_url)
    
        if not forecast_data:
            return "Unable to fetch detailed forecast."
    
        # Format the periods into a readable forecast
        periods = forecast_data["properties"]["periods"]
        forecasts = []
        for period in periods[:5]:  # Only show next 5 periods
            forecast = f"""
    {period['name']}:
    Temperature: {period['temperature']}°{period['temperatureUnit']}
    Wind: {period['windSpeed']} {period['windDirection']}
    Forecast: {period['detailedForecast']}
    """
            forecasts.append(forecast)
    
        return "\n---\n".join(forecasts)
  • Helper function make_nws_request - performs HTTP requests to NOAA National Weather Service API with proper headers, error handling, and timeout configuration. Returns parsed JSON or None on error.
    async def make_nws_request(url: str) -> dict[str, Any] | None:
        """
        發送 HTTP 請求到 NOAA 天氣 API 並返回 JSON 響應
        """
        headers = {
            "User-Agent": USER_AGENT,
            "Accept": "application/geo+json",
        }
    
        async with httpx.AsyncClient() as client:
            try:
                response = await client.get(url, headers=headers, timeout=30.0)
                response.raise_for_status()
                return response.json()
            except httpx.HTTPStatusError as e:
                print(f"HTTP error occurred: {e}")
                return None
  • Helper function make_nws_request (streamable-http version) - performs HTTP requests to NOAA NWS API with User-Agent and Accept headers, 30-second timeout, and exception handling. Returns JSON response or None.
    async def make_nws_request(url: str) -> dict[str, Any] | None:
        """Make a request to the NWS API with proper error handling."""
        headers = {
            "User-Agent": USER_AGENT,
            "Accept": "application/geo+json"
        }
        async with httpx.AsyncClient() as client:
            try:
                response = await client.get(url, headers=headers, timeout=30.0)
                response.raise_for_status()
                return response.json()
            except Exception:
                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. The description only states what the tool does at a high level ('get forecast data') without explaining what the response contains, whether there are rate limits, authentication requirements, data freshness, or any other behavioral characteristics. This is inadequate for a tool with no annotation coverage.

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 concise with a clear purpose statement followed by parameter documentation. The two-sentence structure is efficient with no wasted words. However, the front-loading could be improved as the parameter documentation immediately follows the purpose statement without additional context.

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 that there's an output schema (which handles return values) and only 2 simple parameters, the description provides the minimum viable information. However, with no annotations and a sibling tool present, the description should do more to distinguish this tool and explain its behavioral characteristics. The description is adequate but has clear gaps in contextual information.

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 includes parameter information in the Args section, documenting both latitude and longitude parameters with their types. However, with 0% schema description coverage, the description compensates by providing this parameter documentation. The parameter documentation is minimal but covers the basics, meeting the baseline expectation when schema coverage is low.

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

Purpose3/5

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

The description states the purpose ('獲取特定位置的預報資料' - 'Get forecast data for a specific location') which is clear but somewhat vague. It specifies the action (get/retrieve) and resource (forecast data) but doesn't distinguish from the sibling 'get_alerts' tool or provide details about what type of forecast data (weather, temperature, precipitation, etc.).

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?

No guidance is provided about when to use this tool versus alternatives. The description doesn't mention the sibling 'get_alerts' tool or provide any context about when this forecast tool is appropriate versus other tools that might exist. There's no information about prerequisites or constraints.

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/sun873087/mcp-sample'

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