Skip to main content
Glama
aitiwari

Weather MCP Server

by aitiwari

Model Context Protocol (MCP)

🚀 Why Is Everyone – Suddenly! – Obsessed With MCP/Servers? (Spoiler: It’s Redefining AI Orchestration)

Model Context Protocol (MCP) is an open standard developed by Anthropic in late 2024 to address a critical challenge in AI integration: connecting AI assistants with real-world data sources and systems[1][3]. MCP serves as a standardized interface for AI models to interact with external tools, databases, and APIs, similar to how USB-C functions as a universal port for devices[4][7].

Key Features and Benefits

  1. Standardized Integration: MCP eliminates the need for custom integrations, allowing developers to connect AI models to various data sources using a single protocol.

  2. Dynamic Discovery: AI agents can automatically detect and utilize available MCP servers and their capabilities without hard-coded integration.

  3. Enhanced Security: MCP enables developers to implement security measures within servers, ensuring AI agents only access permitted data or actions.

  4. Flexibility: The protocol is model-agnostic, allowing any AI model (e.g., Claude, GPT-4, open-source LLMs) to use MCP-enabled tools.

  5. Ecosystem Growth: Since its introduction, MCP has gained significant traction, with over 1,000 community-built MCP servers available by February 2025.

Related MCP server: Weather MCP Server

Impact on AI Development

MCP is transforming the AI landscape by:

  1. Simplifying Integration: Reducing the complexity of connecting AI models to external systems from an "N×M" problem to an "N+M" problem.

  2. Enabling Complex Workflows: Facilitating multi-step, cross-system operations for AI agents, such as event planning that involves multiple platforms.

  3. Fostering Collaboration: Providing a shared workspace for multi-agent systems, allowing specialized AI agents to coordinate tasks efficiently.

  4. Enhancing Personalization: Enabling secure integration of personal AI assistants with users' data and applications.

  5. Improving Enterprise Governance: Standardizing AI access to internal tools and enabling better monitoring and control of AI interactions.

As of March 2025, MCP has become a significant topic in the AI community, with many viewing it as a crucial component for developing more integrated and context-aware AI systems. Its open nature and backing by a major AI player have contributed to its rapid adoption and evolution, positioning MCP as a potential de facto standard for AI-world integration.


Model Context Protocol (MCP) - weather quick start :

Overview

This document provides a comprehensive guide to building a simple Model Context Protocol (MCP) weather server and connecting it to a host, Claude for Desktop. The server exposes two tools: get-alerts and get-forecast, which fetch weather alerts and forecasts using the National Weather Service API.

Table of Contents

  1. Introduction

  2. Prerequisites

  3. System Requirements

  4. Setup

  5. Building the Server

  6. Testing with Claude for Desktop

  7. Under the Hood

  8. Troubleshooting

Introduction

This guide walks you through creating an MCP server to enhance LLMs (like Claude) with real-time weather data. The server utilizes the MCP framework to expose tools for fetching weather alerts and forecasts, addressing the LLM's lack of native environmental awareness.

Prerequisites

Before starting, ensure you have:

  • Familiarity with Python

  • Understanding of LLMs like Claude

System Requirements

  • Python 3.10 or higher

  • MCP SDK 1.2.0 or higher

Setup

  1. Install uv:

    window

    powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

    macos/linux

    curl -LsSf https://astral.sh/uv/install.sh | sh

    Restart your terminal to ensure the uv command is recognized.

  2. Create and Set Up Project:

    window(cd to your dev repo_path run below command in powershell/..)

    # Create a new directory for our project
      uv init weather
      cd weather
    
      # Create virtual environment and activate it
      uv venv
      .venv\Scripts\activate
    
      # Install dependencies
      uv add mcp[cli] httpx
    
      # Create our server file
      new-item weather.py

    macos/linux

    # Create a new directory for our project
    uv init weather
    cd weather
    
    # Create virtual environment and activate it
    uv venv
    source .venv/bin/activate
    
    # Install dependencies
    uv add "mcp[cli]" httpx
    
    # Create our server file
    touch weather.py
    

Building the Server

Importing Packages and Setting Up the Instance

Add the following code to the top of your weather.py file:

from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP


# Initialize FastMCP server
mcp = FastMCP("weather")

# Constants
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"


#helper function
async def make_nws_request(url: str) -> dict[str, Any] | None:
    """Make a request to the NWS API with proper error handling."""
    headers = {
        "User-Agent": USER_AGENT,
        "Accept": "application/geo+json"
    }
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except Exception:
            return None

def format_alert(feature: dict) -> str:
    """Format an alert feature into a readable string."""
    props = feature["properties"]
    return f"""
Event: {props.get('event', 'Unknown')}
Area: {props.get('areaDesc', 'Unknown')}
Severity: {props.get('severity', 'Unknown')}
Description: {props.get('description', 'No description available')}
Instructions: {props.get('instruction', 'No specific instructions provided')}
"""


@mcp.tool()
async def get_alerts(state: str) -> str:
    """Get weather alerts for a US state.

    Args:
        state: Two-letter US state code (e.g. CA, NY)
    """
    url = f"{NWS_API_BASE}/alerts/active/area/{state}"
    data = await make_nws_request(url)

    if not data or "features" not in data:
        return "Unable to fetch alerts or no alerts found."

    if not data["features"]:
        return "No active alerts for this state."

    alerts = [format_alert(feature) for feature in data["features"]]
    return "\n---\n".join(alerts)

@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
    """Get weather forecast for a location.

    Args:
        latitude: Latitude of the location
        longitude: Longitude of the location
    """
    # First get the forecast grid endpoint
    points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
    points_data = await make_nws_request(points_url)

    if not points_data:
        return "Unable to fetch forecast data for this location."

    # Get the forecast URL from the points response
    forecast_url = points_data["properties"]["forecast"]
    forecast_data = await make_nws_request(forecast_url)

    if not forecast_data:
        return "Unable to fetch detailed forecast."

    # Format the periods into a readable forecast
    periods = forecast_data["properties"]["periods"]
    forecasts = []
    for period in periods[:5]:  # Only show next 5 periods
        forecast = f"""
                    {period['name']}:
                    Temperature: {period['temperature']}°{period['temperatureUnit']}
                    Wind: {period['windSpeed']} {period['windDirection']}
                    Forecast: {period['detailedForecast']}
                    """
        forecasts.append(forecast)

    return "\n---\n".join(forecasts)


if __name__ == "__main__":
    # Initialize and run the server
    mcp.run(transport='stdio')

Running the Server

To verify your server, run:

uv run weather.py

Testing Your Server with Claude for Desktop

Configuration

  1. Install/Update Claude for Desktop: Ensure you have the latest version installed.

  2. Configure MCP Servers: Open or create the configuration file at ~/Library/Application Support/Claude/claude_desktop_config.json.

alt text

-> RESTART THE SYSTEM IF NOT WORKS

  1. Add Server Configuration:

    {
      "mcpServers": {
        "weather": {
          "command": "uv",
          "args": [
            "--directory",
            "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",# S:\\Dev\\weather
            "run",
            "weather.py"
          ]
        }
      }
    }

    Replace /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather with the correct absolute path to your project directory. You may need to provide the full path to the uv executable in the command field (use which uv on MacOS/Linux or where uv on Windows to find it).

  2. Restart Claude for Desktop.

Test with Commands

  1. Verify Tool Detection: Look for the hammer icon in Claude for Desktop. Clicking it should list the get_alerts and get_forecast tools.

alt text 2. Run Test Queries:

- "What’s the weather in Sacramento?"
- "What are the active weather alerts in Texas?"

Note: These queries work for US locations only, as they use the US National Weather Service.

What’s Happening Under the Hood

  1. The client sends your question to Claude.

  2. Claude analyzes available tools and decides which to use.

  3. The client executes the chosen tool(s) through the MCP server.

  4. Results are sent back to Claude.

  5. Claude formulates and displays a natural language response.

Troubleshooting

  • Getting logs from Claude for Desktop

    • mcp.log: General MCP connections and failures.

    • mcp-server-SERVERNAME.log: Error logs from the named server.

    tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
  • Server not showing up in Claude

    • Check claude_desktop_config.json file syntax.

    • Ensure the project path is absolute.

    • Restart Claude for Desktop completely.

  • Tool calls failing silently

    • Check Claude’s logs for errors.

    • Verify your server builds and runs without errors.

    • Try restarting Claude for Desktop.

  • None of this is working. What do I do?

  • Error: Failed to retrieve grid point data

    • Coordinates outside the US

    • NWS API issues

    • Rate limiting

    Fix:

  • Error: No active alerts for [STATE]

    • No current weather alerts for that state. Try a different state.

For more advanced troubleshooting, check out the Debugging MCP guide.

MCP Inspector

npx @modelcontextprotocol/inspector uv run weather.py

alt text

alt text

done with local test

Published in Github

🔗 Github - aitiwari/weather

Available Tools

2 tools
get_alertsB

Get weather alerts for a US state.

Args:
    state: Two-letter US state code (e.g. CA, NY)
ParametersJSON Schema
NameRequiredDescriptionDefault
stateYes

TDQS

B3.2/5.0
Behavior2/5

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

No annotations are provided, so the description must carry the full burden of behavioral disclosure. While 'Get' implies read-only access, the description omits whether the data is real-time or cached, what types of alerts are returned (severe weather, advisories, etc.), and the response format structure.

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 optimally concise at two sentences with no wasted words. The purpose is front-loaded in the first sentence, followed by the Args section that precisely documents the single parameter.

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 single-parameter tool without output schema or annotations, the description adequately covers the essential input requirements. However, it could improve by mentioning the return value structure (e.g., list of active alerts) and distinguishing its use case from 'get_forecast' to achieve higher completeness.

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?

With 0% schema description coverage (the 'state' property has no description field), the description provides crucial format specification that the schema lacks: it clarifies the two-letter code requirement and provides examples (CA, NY). This significantly aids correct parameter construction.

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 verb (Get), resource (weather alerts), and scope (US state). However, it does not explicitly differentiate from sibling tool 'get_forecast', which could help clarify when to use alerts versus forecasts.

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, nor does it mention any prerequisites such as API keys or location validation. No 'when-not' or exclusion criteria are provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_forecastC

Get weather forecast for a location.

Args:
    latitude: Latitude of the location
    longitude: Longitude of the location
ParametersJSON Schema
NameRequiredDescriptionDefault
latitudeYes
longitudeYes

TDQS

C2.9/5.0
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 fails to specify the forecast timeframe (e.g., 5-day, hourly), units (metric/imperial), data freshness, or what the return value contains. 'Get weather forecast' is too generic for an agent to predict the operation's scope or output format.

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 the purpose stated immediately in the first sentence. The Args section is structured and necessary given the empty schema descriptions. No extraneous text is present, though the parameter descriptions are minimal.

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 low complexity (2 primitive parameters, no nested objects) and lack of output schema, the description meets minimum viability but has clear gaps. It omits the forecast time range, output data structure, and units—information essential for an agent to utilize the results effectively. With no annotations to clarify behavior, the description should provide more operational 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?

With 0% schema description coverage, the description must compensate for the lack of parameter documentation. The Args block provides basic semantic mapping ('Latitude of the location'), which is minimally sufficient but tautological. It lacks coordinate format details, valid ranges, or examples that would help an agent construct valid inputs.

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 states a clear specific verb ('Get') and resource ('weather forecast') with scope ('for a location'). However, it does not explicitly differentiate from the sibling tool 'get_alerts' (forecast vs. alerts), which would help an agent select the correct tool when both weather conditions and alerts are relevant.

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 the sibling 'get_alerts' or other alternatives. There are no prerequisites, conditions, or exclusion criteria mentioned.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 2 tool updatesv0.1.0
    • First observedget_alerts
    • First observedget_forecast

TDQS

B3.1/5.0
Disambiguation5/5

The two tools have clearly distinct purposes: get_alerts retrieves weather alerts for a US state, while get_forecast provides weather forecasts for a specific geographic location. There is no overlap in functionality or confusion about which tool to use for different weather-related queries.

Naming Consistency5/5

Both tools follow a consistent verb_noun naming pattern (get_alerts, get_forecast) with identical verb usage and snake_case formatting. This makes the tool set predictable and easy to understand at a glance.

Tool Count2/5

With only two tools, this server feels under-scoped for a weather domain. While alerts and forecasts are core functions, there are obvious gaps like current conditions, historical data, or radar imagery that would be expected from a weather service. The tool count is too low for comprehensive weather coverage.

Completeness2/5

The tool surface is severely incomplete for a weather server. It lacks fundamental operations like getting current weather conditions, accessing radar or satellite imagery, retrieving historical data, or supporting international locations. Agents will encounter dead ends when trying to perform basic weather queries beyond these two specific functions.

Maintenance

ActivityInactive
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    D
    maintenance
    Enables AI assistants to access real-time US weather forecasts and alerts through the National Weather Service API.
    2
    21
    MIT
  • F
    license
    B
    quality
    D
    maintenance
    Provides real-time weather forecasts and alerts for US locations using the National Weather Service API. Supports querying forecasts by coordinates and retrieving active weather alerts by state.
    2
    -

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/aitiwari/weather'

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