Skip to main content
Glama

get_forecast_by_city

Retrieve weather forecast data for any US city by providing the city name. This tool accesses National Weather Service APIs to deliver location-specific weather information.

Instructions

Get weather forecast for a city by name.

Args:
    city_name: Name of the city (e.g., "San Francisco", "New York", "Chicago")

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
city_nameYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'get_forecast_by_city' tool. Decorated with @mcp.tool() for automatic registration and schema generation from signature and docstring. Geocodes the city name, retrieves forecast data using helper functions, and returns a formatted string with forecast details for up to 10 periods.
    @mcp.tool()
    async def get_forecast_by_city(city_name: str) -> str:
        """Get weather forecast for a city by name.
    
        Args:
            city_name: Name of the city (e.g., "San Francisco", "New York", "Chicago")
        """
        coords = await geocode_location(city_name)
        
        if not coords:
            return f"Error: Could not find coordinates for '{city_name}'. Please check the city name and try again."
        
        latitude, longitude = coords
        forecast_data = await get_forecast_data(latitude, longitude)
        
        if not forecast_data:
            return f"Unable to fetch forecast data for {city_name}. The location may be outside NWS coverage area (US only)."
    
        periods = forecast_data["properties"]["periods"]
        location = forecast_data.get("_location", {})
        location_str = f"{location.get('city', city_name)}, {location.get('state', 'Unknown')}"
        
        forecasts = []
        for period in periods[:10]:
            forecast = f"""
    {period['name']}:
      Temperature: {period['temperature']}°{period['temperatureUnit']}
      Wind: {period['windSpeed']} {period['windDirection']}
      {f"Humidity: {period.get('relativeHumidity', {}).get('value', 'N/A')}%" if period.get('relativeHumidity') else ""}
      {f"Precipitation: {period.get('probabilityOfPrecipitation', {}).get('value', 0)}%" if period.get('probabilityOfPrecipitation') else ""}
      Forecast: {period['detailedForecast']}
    """
            forecasts.append(forecast)
    
        return f"Weather Forecast for {location_str}:\n" + "\n---\n".join(forecasts)
  • Helper function used by get_forecast_by_city to convert city name to latitude/longitude coordinates, prioritizing US locations using Open-Meteo geocoding API.
    async def geocode_location(city_name: str) -> tuple[float, float] | None:
        """Geocode a city name to latitude and longitude coordinates.
        
        Returns:
            Tuple of (latitude, longitude) or None if geocoding fails
        """
        async with httpx.AsyncClient() as client:
            try:
                # Try to get US results first by adding country code
                # Open-Meteo supports country_code parameter
                params = {
                    "name": city_name,
                    "count": 10,  # Get more results to find US cities
                    "language": "en",
                    "format": "json"
                }
                response = await client.get(
                    GEOCODE_API_BASE,
                    params=params,
                    timeout=10.0
                )
                response.raise_for_status()
                data = response.json()
                
                if data.get("results") and len(data["results"]) > 0:
                    # Prefer US results (country_code == "US")
                    for result in data["results"]:
                        if result.get("country_code") == "US":
                            return (result["latitude"], result["longitude"])
                    # If no US result found, return the first result anyway
                    # (user might be looking for a non-US city, or it might still work)
                    result = data["results"][0]
                    return (result["latitude"], result["longitude"])
                return None
            except httpx.RequestError:
                return None
            except Exception:
                return None
  • Helper function called by get_forecast_by_city to fetch detailed forecast data from the National Weather Service (NWS) API for given coordinates, including location metadata.
    async def get_forecast_data(latitude: float, longitude: float) -> dict[str, Any] | None:
        """Get forecast data for coordinates. Returns None on error."""
        if not validate_coordinates(latitude, longitude):
            return None
        
        points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
        points_data = await make_nws_request(points_url)
    
        if not points_data or "properties" not in points_data:
            return None
    
        forecast_url = points_data["properties"].get("forecast")
        if not forecast_url:
            return None
    
        forecast_data = await make_nws_request(forecast_url)
        if not forecast_data or "properties" not in forecast_data:
            return None
    
        # Add location info to the forecast data
        location_info = points_data["properties"].get("relativeLocation", {})
        forecast_data["_location"] = {
            "city": location_info.get("properties", {}).get("city", "Unknown"),
            "state": location_info.get("properties", {}).get("state", "Unknown")
        }
        
        return forecast_data
  • Utility helper for validating latitude and longitude coordinates used indirectly in forecast retrieval.
    def validate_coordinates(latitude: float, longitude: float) -> bool:
        """Validate that coordinates are within valid ranges."""
        return -90 <= latitude <= 90 and -180 <= longitude <= 180
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 provides no information about rate limits, authentication requirements, error conditions, response format, or whether this is a read-only operation. The description doesn't mention what time period the forecast covers or any other behavioral characteristics.

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 core purpose in the first sentence. The parameter documentation is structured clearly with an 'Args:' section. There's minimal waste, though the formatting could be slightly more polished.

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 has an output schema (which handles return values), the description covers the basic purpose and parameter semantics adequately. However, for a weather forecasting tool with no annotations, it should ideally mention more about what the forecast includes (e.g., temperature, precipitation, timeframe) and any limitations (e.g., city name ambiguity, supported regions).

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 value beyond the input schema, which has 0% description coverage. It explains the 'city_name' parameter with examples ('San Francisco', 'New York', 'Chicago'), clarifying the expected format and providing concrete usage guidance. This compensates well for the schema's lack of documentation.

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 with a specific verb ('Get') and resource ('weather forecast for a city by name'). It distinguishes from some siblings like 'get_alerts' and 'get_current_conditions' by specifying it's for forecasts, but doesn't explicitly differentiate from 'get_forecast' which appears to be a similar tool.

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 when to choose this over 'get_forecast' (the most obvious sibling) or other weather-related tools like 'get_current_conditions' or 'compare_weather'. There's no context about prerequisites, limitations, or appropriate use cases.

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/zayedansari2/MCP_WeatherServer'

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