Skip to main content
Glama

Weather lookup

get_weather

Retrieve current weather for any city. Supports optional temperature unit; demo data by default, live data when configured.

Instructions

Get current weather for a city. By default this returns deterministic demo data. Set NANOMCP_LIVE_WEATHER=1 to try wttr.in.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
locationYesCity or place name, for example Shanghai.
unitNoTemperature unit.celsius

Implementation Reference

  • The main handler function for the 'get_weather' tool. Takes location and optional unit arguments, dispatches to live_weather (if NANOMCP_LIVE_WEATHER=1) or offline_weather (deterministic demo data).
    def get_weather(arguments: dict[str, Any]) -> str:
        location = str(arguments.get("location", "")).strip()
        if not location:
            raise ToolError("location is required")
    
        unit = str(arguments.get("unit", "celsius"))
        if unit not in {"celsius", "fahrenheit"}:
            raise ToolError("unit must be celsius or fahrenheit")
    
        if os.environ.get("NANOMCP_LIVE_WEATHER") == "1":
            try:
                return live_weather(location, unit)
            except Exception as exc:
                offline = offline_weather(location, unit)
                return f"Live weather lookup failed ({exc}).\n\n{offline}"
    
        return offline_weather(location, unit)
  • Tool schema definition for 'get_weather' in the TOOLS list, specifying inputSchema with location (required string) and unit (optional enum: celsius/fahrenheit).
    TOOLS: list[dict[str, Any]] = [
        {
            "name": "get_weather",
            "title": "Weather lookup",
            "description": (
                "Get current weather for a city. By default this returns deterministic "
                "demo data. Set NANOMCP_LIVE_WEATHER=1 to try wttr.in."
            ),
            "inputSchema": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City or place name, for example Shanghai.",
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit.",
                        "default": "celsius",
                    },
                },
                "required": ["location"],
                "additionalProperties": False,
            },
        },
  • Registration/dispatch point in call_tool() that routes the 'get_weather' tool name to the get_weather() handler function.
    def call_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
        try:
            if name == "get_weather":
                return tool_result(get_weather(arguments))
  • Helper function that performs live weather lookup via the wttr.in API. Called when NANOMCP_LIVE_WEATHER=1 is set.
    def live_weather(location: str, unit: str) -> str:
        encoded = urllib.parse.quote(location)
        url = f"https://wttr.in/{encoded}?format=j1"
        request = urllib.request.Request(url, headers={"User-Agent": "nanomcp/0.1"})
        with urllib.request.urlopen(request, timeout=5) as response:
            payload = json.loads(response.read().decode("utf-8"))
    
        current = payload["current_condition"][0]
        temp_key = "temp_C" if unit == "celsius" else "temp_F"
        suffix = "C" if unit == "celsius" else "F"
        condition = current["weatherDesc"][0]["value"]
        humidity = current.get("humidity", "unknown")
        wind = current.get("windspeedKmph", "unknown")
        return (
            f"Live weather for {location} from wttr.in:\n"
            f"- Temperature: {current[temp_key]}°{suffix}\n"
            f"- Condition: {condition}\n"
            f"- Humidity: {humidity}%\n"
            f"- Wind: {wind} km/h"
        )
  • Helper function that generates deterministic demo weather data using SHA-256 hash of location + today's date for reproducibility.
    def offline_weather(location: str, unit: str) -> str:
        seed = f"{location.lower()}:{date.today().isoformat()}".encode("utf-8")
        digest = hashlib.sha256(seed).digest()
        celsius = 6 + digest[0] % 29
        humidity = 35 + digest[1] % 55
        conditions = ["sunny", "cloudy", "light rain", "windy", "hazy", "clear"]
        condition = conditions[digest[2] % len(conditions)]
    
        if unit == "fahrenheit":
            temperature = round(celsius * 9 / 5 + 32)
            suffix = "F"
        else:
            temperature = celsius
            suffix = "C"
    
        return (
            f"Demo weather for {location}:\n"
            f"- Temperature: {temperature}°{suffix}\n"
            f"- Condition: {condition}\n"
            f"- Humidity: {humidity}%\n"
            "\nThis is deterministic demo data. Set NANOMCP_LIVE_WEATHER=1 "
            "to try a live wttr.in lookup."
        )
Behavior3/5

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

No annotations exist, so the description carries the burden. It discloses the demo/live behavior and environment variable, but lacks details on return format, error handling, or external API dependencies.

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?

Two sentences efficiently define purpose and critical behavioral context. No superfluous text.

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?

For a simple weather tool, the description covers core purpose and key behavioral nuance. However, it omits return value structure or typical properties, which would help the agent understand the output.

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?

Input schema covers 100% of parameters with descriptions. The description adds no additional parameter meaning beyond what the schema provides, meeting baseline.

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 'Get current weather for a city,' using a specific verb and resource, and distinguishes from siblings like find_files and get_current_datetime.

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?

It explains the default demo mode and how to switch to live data, providing context for when to expect real or synthetic data. No explicit alternatives or exclusions but sufficient for this tool.

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/szfmsmdx/nanomcp'

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