weather.py•2.86 kB
import os
import requests
from typing import Dict, Any, List
from mcp_handler import Tool
class WeatherTool(Tool):
"""Tool for getting weather information"""
def __init__(self):
# Define parameters for the weather tool
parameters = [
{
"name": "location",
"type": "string",
"description": "The city and state, e.g., San Francisco, CA",
"required": True
},
{
"name": "unit",
"type": "string",
"description": "Temperature unit (celsius or fahrenheit)",
"enum": ["celsius", "fahrenheit"],
"required": False
}
]
super().__init__(
name="get_weather",
description="Get the current weather in a specific location",
parameters=parameters
)
# API key for weather service
self.api_key = os.environ.get("WEATHER_API_KEY")
self.api_url = "https://api.weatherservice.com/v1/current" # Example URL
def execute(self, location: str, unit: str = "fahrenheit") -> Dict[str, Any]:
"""Get weather information for the specified location"""
# In a real implementation, you would call an actual weather API
# This is a simplified example
try:
# Make the API request
response = self._call_weather_api(location, unit)
# Process the response
return {
"location": location,
"temperature": response["temp"],
"unit": unit,
"conditions": response["conditions"],
"humidity": response["humidity"],
"wind_speed": response["wind_speed"]
}
except Exception as e:
return {
"error": f"Failed to get weather data: {str(e)}"
}
def _call_weather_api(self, location: str, unit: str) -> Dict[str, Any]:
"""Call the weather API (simulated for this example)"""
# In a real implementation, make an HTTP request to the weather API
# This is a mock implementation
# Simulate API call for demo purposes
# In a real implementation, you would use:
# response = requests.get(
# self.api_url,
# params={
# "q": location,
# "units": "metric" if unit == "celsius" else "imperial",
# "appid": self.api_key
# }
# )
# return response.json()
# Mock response
return {
"temp": 72 if unit == "fahrenheit" else 22,
"conditions": "Partly Cloudy",
"humidity": 68,
"wind_speed": 5.8
}