Skip to main content
Glama
adhikasp

MCP Weather Server

by adhikasp

get_hourly_weather

Retrieve hourly weather forecasts for specific locations to plan activities and prepare for changing conditions throughout the day.

Instructions

Get hourly weather forecast for a location.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
locationYes

Implementation Reference

  • The handler function for 'get_hourly_weather' tool. It uses AccuWeather API to search for location (with caching), fetch current conditions, and 12-hour hourly forecast. Formats and returns structured data including current and hourly info.
    @mcp.tool()
    async def get_hourly_weather(location: str) -> Dict:
        """Get hourly weather forecast for a location."""
        api_key = os.getenv("ACCUWEATHER_API_KEY")
        base_url = "http://dataservice.accuweather.com"
        
        # Try to get location key from cache first
        location_key = get_cached_location_key(location)
        
        async with ClientSession() as session:
            if not location_key:
                location_search_url = f"{base_url}/locations/v1/cities/search"
                params = {
                    "apikey": api_key,
                    "q": location,
                }
                async with session.get(location_search_url, params=params) as response:
                    locations = await response.json()
                    if response.status != 200:
                        raise Exception(f"Error fetching location data: {response.status}, {locations}")
                    if not locations or len(locations) == 0:
                        raise Exception("Location not found")
                
                location_key = locations[0]["Key"]
                # Cache the location key for future use
                cache_location_key(location, location_key)
            
            # Get current conditions
            current_conditions_url = f"{base_url}/currentconditions/v1/{location_key}"
            params = {
                "apikey": api_key,
            }
            async with session.get(current_conditions_url, params=params) as response:
                current_conditions = await response.json()
                
            # Get hourly forecast
            forecast_url = f"{base_url}/forecasts/v1/hourly/12hour/{location_key}"
            params = {
                "apikey": api_key,
                "metric": "true",
            }
            async with session.get(forecast_url, params=params) as response:
                forecast = await response.json()
            
            # Format response
            hourly_data = []
            for i, hour in enumerate(forecast, 1):
                hourly_data.append({
                    "relative_time": f"+{i} hour{'s' if i > 1 else ''}",
                    "temperature": {
                        "value": hour["Temperature"]["Value"],
                        "unit": hour["Temperature"]["Unit"]
                    },
                    "weather_text": hour["IconPhrase"],
                    "precipitation_probability": hour["PrecipitationProbability"],
                    "precipitation_type": hour.get("PrecipitationType"),
                    "precipitation_intensity": hour.get("PrecipitationIntensity"),
                })
            
            # Format current conditions
            if current_conditions and len(current_conditions) > 0:
                current = current_conditions[0]
                current_data = {
                    "temperature": {
                        "value": current["Temperature"]["Metric"]["Value"],
                        "unit": current["Temperature"]["Metric"]["Unit"]
                    },
                    "weather_text": current["WeatherText"],
                    "relative_humidity": current.get("RelativeHumidity"),
                    "precipitation": current.get("HasPrecipitation", False),
                    "observation_time": current["LocalObservationDateTime"]
                }
            else:
                current_data = "No current conditions available"
            
            return {
                "location": locations[0]["LocalizedName"],
                "location_key": location_key,
                "country": locations[0]["Country"]["LocalizedName"],
                "current_conditions": current_data,
                "hourly_forecast": hourly_data
            } 
  • The @mcp.tool() decorator registers the get_hourly_weather function as an MCP tool.
    @mcp.tool()
  • Helper function to retrieve cached AccuWeather location key for a given location string.
    def get_cached_location_key(location: str) -> Optional[str]:
        """Get location key from cache."""
        if not LOCATION_CACHE_FILE.exists():
            return None
        
        try:
            with open(LOCATION_CACHE_FILE, "r") as f:
                cache = json.load(f)
                return cache.get(location)
        except (json.JSONDecodeError, FileNotFoundError):
            return None
  • Helper function to cache AccuWeather location key for a given location string in JSON file.
    def cache_location_key(location: str, location_key: str):
        """Cache location key for future use."""
        CACHE_DIR.mkdir(parents=True, exist_ok=True)
        
        try:
            if LOCATION_CACHE_FILE.exists():
                with open(LOCATION_CACHE_FILE, "r") as f:
                    cache = json.load(f)
            else:
                cache = {}
            
            cache[location] = location_key
            
            with open(LOCATION_CACHE_FILE, "w") as f:
                json.dump(cache, f, indent=2)
        except Exception as e:
            print(f"Warning: Failed to cache location key: {e}")
  • Function signature and docstring defining input (location: str) and output (Dict), serving as the tool schema.
    async def get_hourly_weather(location: str) -> Dict:
        """Get hourly weather forecast for a location."""
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 mentions 'Get' which implies a read operation, but fails to describe any behavioral traits such as rate limits, authentication needs, error handling, or what the forecast includes. This leaves significant gaps for a tool that likely interacts with external data.

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 a single, efficient sentence that directly states the tool's function without any wasted words. It is appropriately sized and front-loaded, making it easy to parse quickly.

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

Completeness2/5

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

Given the tool's complexity (weather forecasting likely involves external APIs), lack of annotations, no output schema, and incomplete parameter documentation, the description is insufficient. It doesn't explain return values, error cases, or operational constraints, leaving the agent poorly informed.

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 meaning beyond the input schema, which has 0% coverage. It implies the 'location' parameter is used to specify where to get the forecast, but doesn't clarify format (e.g., city name, coordinates) or constraints. With one parameter and low schema coverage, the description provides some context but doesn't fully compensate.

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 action ('Get') and resource ('hourly weather forecast for a location'), making the tool's purpose immediately understandable. It doesn't need to differentiate from siblings since none exist, but it could be more specific about what 'hourly weather forecast' entails (e.g., temperature, precipitation).

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 on when to use this tool versus alternatives or in what context. The description states what it does but offers no information about prerequisites, timing, or limitations, leaving the agent without usage direction.

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/adhikasp/mcp-weather'

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