Skip to main content
Glama
gitPratikSingh

Weather MCP Server

get_current_weather

Retrieve current weather conditions for any city or location to check temperature, precipitation, and atmospheric data for immediate planning.

Instructions

Get current weather conditions for a specific location

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
locationYesCity name or location (e.g., 'New York', 'London')

Implementation Reference

  • Core implementation of the get_current_weather tool. Fetches current weather from OpenWeatherMap API with caching, mock data fallback, and comprehensive data formatting.
    async def get_current_weather(self, location: str) -> Dict:
        """
        Get current weather for a location.
        
        Args:
            location: City name or location string
            
        Returns:
            Dictionary with weather data
        """
        location = self._normalize_location(location)
        
        # Check cache first
        cached = self._get_from_cache(f"current_{location}")
        if cached:
            return cached
        
        # If no API key, return mock data
        if not self.api_key:
            return self._get_mock_current_weather(location)
        
        try:
            async with httpx.AsyncClient() as client:
                url = f"{self.base_url}/weather"
                params = {
                    "q": location,
                    "appid": self.api_key,
                    "units": "metric"
                }
                response = await client.get(url, params=params, timeout=10.0)
                response.raise_for_status()
                data = response.json()
                
                # Format the response
                result = {
                    "location": data.get("name", location),
                    "country": data.get("sys", {}).get("country", ""),
                    "temperature": data.get("main", {}).get("temp", 0),
                    "feels_like": data.get("main", {}).get("feels_like", 0),
                    "humidity": data.get("main", {}).get("humidity", 0),
                    "pressure": data.get("main", {}).get("pressure", 0),
                    "description": data.get("weather", [{}])[0].get("description", ""),
                    "wind_speed": data.get("wind", {}).get("speed", 0),
                    "wind_direction": data.get("wind", {}).get("deg", 0),
                    "visibility": data.get("visibility", 0) / 1000 if data.get("visibility") else None,
                    "clouds": data.get("clouds", {}).get("all", 0),
                    "timestamp": datetime.now().isoformat()
                }
                
                self._cache_data(f"current_{location}", result)
                return result
                
        except httpx.HTTPError as e:
            # Fallback to mock data on API error
            return self._get_mock_current_weather(location)
  • main.py:30-43 (registration)
    Registers the get_current_weather tool with the MCP server, including name, description, and input schema.
    Tool(
        name="get_current_weather",
        description="Get current weather conditions for a specific location",
        inputSchema={
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City name or location (e.g., 'New York', 'London')"
                }
            },
            "required": ["location"]
        }
    ),
  • main.py:33-42 (schema)
    Defines the input schema for the get_current_weather tool, specifying the required 'location' parameter.
    inputSchema={
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "City name or location (e.g., 'New York', 'London')"
            }
        },
        "required": ["location"]
    }
  • main.py:85-97 (handler)
    MCP server handler dispatch for get_current_weather tool call, validates input and delegates to WeatherAPI instance.
    if name == "get_current_weather":
        location = arguments.get("location", "")
        if not location:
            return [TextContent(
                type="text",
                text="Error: location parameter is required"
            )]
        
        weather_data = await weather_api.get_current_weather(location)
        return [TextContent(
            type="text",
            text=json.dumps(weather_data, indent=2)
        )]
  • Helper function providing mock weather data when API key is missing or on API errors.
    def _get_mock_current_weather(self, location: str) -> Dict:
        """Return mock current weather data for demo purposes."""
        import random
        return {
            "location": location,
            "country": "US",
            "temperature": round(random.uniform(15, 30), 1),
            "feels_like": round(random.uniform(14, 29), 1),
            "humidity": random.randint(40, 80),
            "pressure": random.randint(1000, 1020),
            "description": random.choice(["clear sky", "few clouds", "scattered clouds", "broken clouds", "shower rain", "rain", "thunderstorm", "snow", "mist"]),
            "wind_speed": round(random.uniform(0, 15), 1),
            "wind_direction": random.randint(0, 360),
            "visibility": round(random.uniform(5, 10), 1),
            "clouds": random.randint(0, 100),
            "timestamp": datetime.now().isoformat(),
            "note": "Mock data - set WEATHER_API_KEY in .env for real data"
        }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states what the tool does but reveals nothing about permissions, rate limits, error handling, or response format. For a tool with zero annotation coverage, this is a significant gap in transparency.

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 purpose without any wasted words. It's appropriately sized and front-loaded, making it easy for an agent 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 lack of annotations and output schema, the description is incomplete. It doesn't address behavioral aspects like authentication needs, rate limits, or what the return values look like. For a tool with no structured safety or output information, the description should provide more context.

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 schema description coverage is 100%, with the single parameter 'location' fully documented in the schema. The description adds no additional parameter details beyond what's in the schema, so it meets the baseline score of 3 where the schema does the heavy lifting.

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 current weather conditions') and resource ('for a specific location'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'get_weather_forecast' (current vs. forecast) or 'search_locations' (weather vs. location search), 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 like 'get_weather_forecast' or 'search_locations'. It lacks any mention of prerequisites, exclusions, or contextual cues, leaving the agent to infer usage based on tool names alone.

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/gitPratikSingh/weather_mcp_server'

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