Skip to main content
Glama
tranducthai

MCP Weather SSE Server

by tranducthai

get_current_weather

Retrieve current weather conditions for any city using OpenWeatherMap data, with options for metric or imperial units.

Instructions

Get current weather for a city using OpenWeatherMap.

Args:
    city: City name (e.g. 'London', 'New York')
    units: Units of measurement ('metric' or 'imperial')

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cityYes
unitsNometric

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 'get_current_weather' MCP tool. Decorated with @mcp.tool() for automatic registration and schema inference from type hints and docstring. Fetches current weather data from OpenWeatherMap API, formats it, and returns as JSON.
    @mcp.tool()
    async def get_current_weather(city: str, units: str = "metric") -> str:
        """Get current weather for a city using OpenWeatherMap.
    
        Args:
            city: City name (e.g. 'London', 'New York')
            units: Units of measurement ('metric' or 'imperial')
        """
        print(f"get_current_weather called with city: {city}, units: {units}", file=sys.stderr)
        
        if not OPENWEATHER_API_KEY:
            return "OpenWeatherMap API key not configured. Please set OPENWEATHER_API_KEY environment variable."
        
        url = f"{OPENWEATHER_API_BASE}/weather"
        params = {
            "q": city,
            "units": units
        }
        
        data = await make_openweather_request(url, params)
        
        if not data:
            return "Unable to fetch current weather data."
        
        result = format_current_weather(data, units)
        return json.dumps(result, indent=2)
  • Helper function used by get_current_weather to format the raw API response into a structured dictionary with location and current weather details.
    def format_current_weather(data: dict, units: str) -> dict:
        """Format current weather data from OpenWeatherMap."""
        temp_unit = "°C" if units == "metric" else "°F"
        speed_unit = "m/s" if units == "metric" else "mph"
        
        try:
            weather = {
                "location": {
                    "name": data.get("name", "Unknown"),
                    "country": data.get("sys", {}).get("country", "Unknown"),
                    "coordinates": {
                        "latitude": data.get("coord", {}).get("lat", 0),
                        "longitude": data.get("coord", {}).get("lon", 0)
                    }
                },
                "current": {
                    "temperature": f"{data.get('main', {}).get('temp', 0)}{temp_unit}",
                    "feels_like": f"{data.get('main', {}).get('feels_like', 0)}{temp_unit}",
                    "humidity": f"{data.get('main', {}).get('humidity', 0)}%",
                    "pressure": f"{data.get('main', {}).get('pressure', 0)} hPa",
                    "wind": {
                        "speed": f"{data.get('wind', {}).get('speed', 0)} {speed_unit}",
                        "direction": data.get('wind', {}).get('deg', 0)
                    },
                    "weather": {
                        "main": data.get('weather', [{}])[0].get('main', "Unknown"),
                        "description": data.get('weather', [{}])[0].get('description', "Unknown"),
                        "icon": data.get('weather', [{}])[0].get('icon', "Unknown")
                    },
                    "visibility": f"{data.get('visibility', 0) / 1000} km",
                    "cloudiness": f"{data.get('clouds', {}).get('all', 0)}%",
                    "sunrise": data.get('sys', {}).get('sunrise', 0),
                    "sunset": data.get('sys', {}).get('sunset', 0)
                }
            }
            
            if 'rain' in data:
                weather['current']['rain'] = {
                    "1h": f"{data['rain'].get('1h', 0)} mm"
                }
            
            if 'snow' in data:
                weather['current']['snow'] = {
                    "1h": f"{data['snow'].get('1h', 0)} mm"
                }
            
            return weather
        except Exception as e:
            print(f"Error formatting weather data: {e}", file=sys.stderr)
            return {"error": "Error formatting weather data"}
  • Helper function used by get_current_weather to make HTTP requests to the OpenWeatherMap API, including API key handling and error management.
    async def make_openweather_request(url: str, params: dict) -> dict[str, Any] | None:
        """Make a request to OpenWeatherMap API with proper error handling."""
        if not OPENWEATHER_API_KEY:
            print("OpenWeatherMap API key not found", file=sys.stderr)
            return None
        
        params["appid"] = OPENWEATHER_API_KEY
        
        async with httpx.AsyncClient() as client:
            try:
                response = await client.get(url, params=params, timeout=30.0)
                response.raise_for_status()
                return response.json()
            except Exception as e:
                print(f"OpenWeatherMap API error: {e}", file=sys.stderr)
                return None
  • weather.py:232-232 (registration)
    The @mcp.tool() decorator on the get_current_weather function registers it as an MCP tool and defines its schema based on function signature and documentation.
    @mcp.tool()
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 the external service (OpenWeatherMap) but doesn't cover critical aspects like rate limits, authentication needs, error handling, or response format. The description lacks transparency on operational constraints.

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 with a clear purpose statement followed by parameter details. The 'Args:' section is well-structured, but the first sentence could be slightly more front-loaded by integrating key details. Overall, it's efficient with minimal waste.

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 moderate complexity (2 parameters, external API), no annotations, but an output schema exists, the description is partially complete. It covers the purpose and parameters well but lacks behavioral context like rate limits or error handling. The output schema mitigates some gaps, but more disclosure would improve completeness.

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

Parameters5/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 'city' expects names like 'London' or 'New York' and 'units' accepts 'metric' or 'imperial', providing concrete examples and constraints not present in the schema's minimal titles.

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

Purpose5/5

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

The description clearly states the specific action ('Get current weather') and resource ('for a city using OpenWeatherMap'), distinguishing it from siblings like get_forecast (future predictions) and get_weather_by_coordinates (different input method). It explicitly mentions the data source, which adds clarity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by specifying 'current weather' and 'city', suggesting it's for real-time data in urban areas, but doesn't explicitly state when to use alternatives like get_weather_by_coordinates for non-city locations or get_forecast for future data. No misleading guidance is present.

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/tranducthai/mcp_protocol_weather'

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