Sponsored by Deepsite.site

🌦️ Weather-MCP

Created By
brunolnetto7 months ago
A MCP server for weather forecast
Content

🌦️ Weather-MCP

Weather-MCP is a FastAPI server that integrates with FastMCP and Pydantic AI to provide real-time weather alerts and forecasts. Users can interact with the server through natural language prompts, enabling seamless access to weather information.


📋 Table of Contents


🚀 Features

  • Fetch active weather alerts for U.S. states.
  • Retrieve detailed weather forecasts based on geographic coordinates.
  • Natural language interaction powered by Pydantic AI.
  • Extensible toolset via FastMCP.

🛠️ Installation

Prerequisites

  • Python 3.8 or higher
  • An OpenAI API key (OPENAI_API_KEY): To obtain an OpenAI API key, please visit the OpenAI API Keys page

Ensure you have these prerequisites in place before proceeding with the setup.

Steps

  1. Clone the repository:

    git clone https://github.com/yourusername/weather-mcp.git
    cd weather-mcp
    
  2. Create and activate a virtual environment:

    pip install uv
    uv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  3. Install dependencies:

    uv sync
    
  4. Set the OpenAI API Key

To securely use OpenAI services, set the OPENAI_API_KEY environment variable.([DEV Community][1])

On Unix/Linux/macOS:

export OPENAI_API_KEY="your-api-key-here"

To make this change permanent, add the above line to your shell's configuration file (e.g., ~/.bashrc, ~/.zshrc) and reload the shell:([Hacker News][2])

source ~/.bashrc  # or source ~/.zshrc

On Windows (Command Prompt):

setx OPENAI_API_KEY "your-api-key-here"

After setting the variable, restart your Command Prompt to apply the changes.

On Windows (PowerShell):

$env:OPENAI_API_KEY = "your-api-key-here"
  1. Start the server:

    python weather_server.py
    

The server will be accessible at http://localhost:8000/sse.


💡 Usage

Interacting via Pydantic AI

You can interact with the server using natural language prompts through Pydantic AI.([YouTube][1])

Example:

import asyncio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerHTTP

# Define the MCP server connection
mcp_server = MCPServerHTTP(url="http://localhost:8000/sse")

# Create the Pydantic AI agent
agent = Agent(
    model="openai:gpt-4o-mini",
    mcp_servers=[mcp_server],
    system_prompt="You are a helpful assistant that provides weather information."
)

async def main():
    prompt = "Are there any weather alerts for California?"
    async with agent.run_mcp_servers():
        result = await agent.run(prompt)
        print(result.output)

if __name__ == "__main__":
    asyncio.run(main())

Direct Tool Invocation

Alternatively, you can directly invoke the tools using FastMCP's client.

Example:

import asyncio
from fastmcp import Client

async def main():
    async with Client("http://localhost:8000/sse") as client:
        tools = await client.list_tools()
        print("Available tools:")
        for tool in tools:
            print(f"- {tool.name}: {tool.description}")

        # Call the get_weather_alerts tool
        state_code = "CA"
        alerts_result = await client.call_tool("get_weather_alerts", {"state": state_code})
        print(f"\nWeather alerts for {state_code}:\n{alerts_result[0].text}")

        # Call the get_weather_forecast tool
        latitude = 34.05
        longitude = -118.25
        forecast_result = await client.call_tool("get_weather_forecast", {
            "latitude": latitude,
            "longitude": longitude
        })
        print(f"\nWeather forecast for ({latitude}, {longitude}):\n{forecast_result[0].text}")

if __name__ == "__main__":
    asyncio.run(main())

📡 API Endpoints

The server exposes the following tools via the MCP protocol:

  • get_weather_alerts(state: str) -> str Fetches active weather alerts for the specified U.S. state.

  • get_weather_forecast(latitude: float, longitude: float) -> str Retrieves the weather forecast for the given geographic coordinates.


🤝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository.
  2. Create a new branch: git checkout -b feature-name.
  3. Make your changes and commit them: git commit -m 'Add feature'.
  4. Push to the branch: git push origin feature-name.
  5. Open a pull request.([GitHub][2])

For major changes, please open an issue first to discuss what you would like to change.([Make a README][3])


📄 License

This project is licensed under the MIT License.

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Amap Maps高德地图官方 MCP Server
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
ChatWiseThe second fastest AI chatbot™
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Playwright McpPlaywright MCP server
WindsurfThe new purpose-built IDE to harness magic
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
CursorThe AI Code Editor
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
DeepChatYour AI Partner on Desktop
Tavily Mcp
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Serper MCP ServerA Serper MCP Server