Content
# Weather MCP Server (@philschmid/weather-mcp)
A simple Model Context Protocol (MCP) server that provides weather forecast information.
## Description
This server implements the Model Context Protocol to expose a single tool: `get_weather_forecast`.
When called, this tool:
1. Takes a location (e.g., "London, UK") and a date (e.g., "2024-07-26") as input.
2. Uses `node-geocoder` with the OpenStreetMap provider to find the latitude and longitude for the given location.
3. Fetches the hourly temperature forecast for the specified date from the [Open-Meteo API](https://open-meteo.com/).
4. Returns the forecast as a JSON object mapping timestamps to temperatures (in Celsius).
## Installation & Running
This server is designed to be run directly using `npx`. Ensure you have Node.js and npm installed.
```bash
npx -y @philschmid/weather-mcp
```
This command will download (if necessary) and run the server, making it available for MCP clients to connect to via standard input/output (stdio).
## Usage with an MCP Client (Python Example)
You can interact with this server using any MCP-compatible client. Here's an example using Python with the `mcp` library and Google's Generative AI SDK to utilize the server's tool via function calling:
```python
import asyncio
import os
from datetime import datetime
from google import genai
from google.genai import types
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
# Configure Gemini client (replace with your API key setup)
client = genai.Client(
api_key=os.getenv("GEMINI_API_KEY")
)
# Server parameters for stdio connection
server_params = StdioServerParameters(
command="npx", # Executable
args=[
"-y",
"@philschmid/weather-mcp", # The published npm package
],
env=None, # Optional environment variables
)
async def run():
# Connect to the server via stdio
async with stdio_client(server_params) as (read, write):
# Start an MCP client session
async with ClientSession(
read,
write,
) as session:
prompt = f"What is the weather in London, UK for {datetime.now().strftime('%Y-%m-%d')}?"
# Initialize the connection
await session.initialize()
print(f"MCP Session Initialized with server: {session.server_info.name} v{session.server_info.version}")
# Get tools from the server
mcp_tools = await session.list_tools()
# Convert MCP tools to Gemini Tool format
gemini_tools = [
types.Tool(
function_declarations=[
types.FunctionDeclaration(
name=tool.name,
description=tool.description,
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
k: types.Schema(
type=types.Type.STRING, # Simplified for example
description=v.get('description', '')
)
for k, v in tool.inputSchema.get('properties', {}).items()
},
required=tool.inputSchema.get('required', [])
)
)
]
)
for tool in mcp_tools.tools
]
print(f"Tools registered: {[t.function_declarations[0].name for t in gemini_tools]}")
# Send prompt to Gemini, making it aware of the server's tools
print(f"Sending prompt to Gemini: '{prompt}'")
response = client.models.generate_content(
model="gemini-pro", # Or another suitable Gemini model
contents=[prompt],
generation_config=types.GenerateContentConfig(
temperature=0,
),
tools=gemini_tools,
)
# Check if Gemini decided to call the weather tool
if response.candidates[0].content.parts[0].function_call:
function_call = response.candidates[0].content.parts[0].function_call
print(f"Gemini Function Call: {function_call.name}({function_call.args})")
# Execute the function call using the MCP server
result = await session.call_tool(
function_call.name, arguments=dict(function_call.args)
)
weather_data = result.content[0].text
print(f"Weather Server Response: {weather_data}")
# (Optional) Send the result back to Gemini to get a natural language response
# ...
else:
# Gemini responded directly without using the tool
print("Gemini response (no function call):")
print(response.text)
# Run the asynchronous function
if __name__ == "__main__":
# Make sure to set your GEMINI_API_KEY environment variable
if not os.getenv("GEMINI_API_KEY"):
print("Error: GEMINI_API_KEY environment variable not set.")
else:
try:
asyncio.run(run())
except Exception as e:
print(f"An error occurred: {e}")
```
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
Connection Info
You Might Also Like
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
markitdown
Python tool for converting files and office documents to Markdown.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.
Sequential Thinking
A structured MCP server for dynamic problem-solving and reflective thinking.
Fetch
Retrieve and process content from web pages by converting HTML into markdown format.
TrendRadar
TrendRadar: Your hotspot assistant for real news in just 30 seconds.