Spaces:
Sleeping
Sleeping
File size: 1,610 Bytes
fb07b17 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | from mcp.server.fastmcp import FastMCP
# Create server
mcp = FastMCP(
name="Weather MCP Server",
description="A basic MCP server for HTTP client demonstration.",
stateless_http=True, # Makes the server treat each HTTP request independently
json_response=True, # Allows single JSON responses for non-streaming calls (optimization)
port=8001,
host="0.0.0.0",
)
@mcp.tool("get_weather")
def get_weather(city: str) -> dict:
"""
Get current weather data for a specified city using wttr.in API.
Args:
city (str): Name of the city to get weather for
Returns:
dict: Weather data including temperature, humidity, description etc.
"""
import requests
# API endpoint
base_url = f"https://wttr.in/{city}?format=j1"
try:
# Make API request
response = requests.get(base_url)
response.raise_for_status()
# Parse response
weather_data = response.json()
current = weather_data["current_condition"][0]
# Extract relevant information
result = {
"city": city,
"temperature": float(current["temp_C"]),
"feels_like": float(current["FeelsLikeC"]),
"humidity": int(current["humidity"]),
"description": current["weatherDesc"][0]["value"],
"wind_speed": float(current["windspeedKmph"]),
}
return result
except requests.exceptions.RequestException as e:
return {"error": f"Failed to fetch weather data: {str(e)}"}
if __name__ == "__main__":
mcp.run(transport="streamable-http")
|