Skip to main content
Glama
tranducthai

MCP Weather SSE Server

by tranducthai

get_weather_by_coordinates

Retrieve current weather data for specific geographic coordinates using latitude and longitude inputs with configurable measurement units.

Instructions

Get current weather by coordinates using OpenWeatherMap.

Args:
    latitude: Latitude of the location
    longitude: Longitude of the location
    units: Units of measurement ('metric' or 'imperial')

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
latitudeYes
longitudeYes
unitsNometric

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function decorated with @mcp.tool(), which registers and implements the get_weather_by_coordinates tool. It fetches current weather data from OpenWeatherMap API using provided latitude, longitude, and units, formats it using helper functions, and returns JSON.
    @mcp.tool()
    async def get_weather_by_coordinates(latitude: float, longitude: float, units: str = "metric") -> str:
        """Get current weather by coordinates using OpenWeatherMap.
    
        Args:
            latitude: Latitude of the location
            longitude: Longitude of the location
            units: Units of measurement ('metric' or 'imperial')
        """
        print(f"get_weather_by_coordinates called with lat: {latitude}, lon: {longitude}, 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 = {
            "lat": latitude,
            "lon": longitude,
            "units": units
        }
        
        data = await make_openweather_request(url, params)
        
        if not data:
            return "Unable to fetch weather data by coordinates."
        
        result = format_current_weather(data, units)
        return json.dumps(result, indent=2)
  • Helper function used by the tool 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 to make HTTP requests to OpenWeatherMap API, handling API key and errors.
    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
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. It mentions the data source ('OpenWeatherMap') but doesn't cover critical aspects like rate limits, authentication needs, error handling, or what the output contains. For a tool with no annotations, this leaves significant gaps in understanding its behavior.

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 front-loaded with the core purpose in the first sentence, followed by a concise list of args. Every sentence earns its place by providing essential information without redundancy, making it efficient and well-structured.

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 (3 parameters, no annotations, but has an output schema), the description is partially complete. It covers the purpose and parameters but lacks behavioral details and usage guidelines. The presence of an output schema means return values are documented elsewhere, so the description doesn't need to explain them, but overall it's adequate with clear gaps.

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 meaningful semantics beyond the input schema, which has 0% description coverage. It explains that latitude and longitude are for the location and specifies that units can be 'metric' or 'imperial', clarifying their purpose. This compensates well for the lack of schema descriptions, though it doesn't detail ranges or formats for coordinates.

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: 'Get current weather by coordinates using OpenWeatherMap.' It specifies the verb ('Get'), resource ('current weather'), and method ('by coordinates'), distinguishing it from siblings like get_alerts or get_forecast. However, it doesn't explicitly differentiate from get_current_weather, which might be similar, so it's not a perfect 5.

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_current_weather or get_forecast. It lacks context about prerequisites, such as needing valid coordinates, and doesn't mention any exclusions or specific scenarios where this tool is preferred over siblings.

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