#!/usr/bin/env python3
"""
Simple usage examples for Weather MCP.
"""
import os
import sys
from pathlib import Path
# Load .env file if exists
try:
from dotenv import load_dotenv
env_path = Path(__file__).parent.parent / ".env"
if env_path.exists():
load_dotenv(env_path)
print(f"✅ Loaded environment variables from {env_path}")
except ImportError:
print("⚠️ python-dotenv not installed. Run: pip install python-dotenv")
print(" Or manually export environment variables")
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from weather_mcp import WeatherMCPClient, WeatherAgent, create_visualizer
from weather_mcp.visualization import plot_weather_trends_horizontal
def basic_client_example():
"""Example using basic MCP client."""
print("🔧 Basic MCP Client Example")
print("-" * 40)
# Create client
client = WeatherMCPClient()
# Geocode a city
print("📍 Geocoding Tokyo...")
geo_result = client.geocode_city("Tokyo")
print(f"Result: {geo_result}")
if "coord" in geo_result:
lat, lon = geo_result["coord"]["lat"], geo_result["coord"]["lon"]
# Get weather
print(f"\n🌤️ Getting weather for {lat}, {lon}...")
weather_result = client.get_weather(lat, lon, hours=6)
print(f"Temperature range: {min(weather_result['hourly']['temperature_2m']):.1f}°C - {max(weather_result['hourly']['temperature_2m']):.1f}°C")
# Combined city weather
print(f"\n🏙️ Getting combined city weather...")
combined_result = client.get_city_weather("London", hours=8)
if "weather" in combined_result:
weather = combined_result["weather"]["hourly"]
print(f"London weather: {len(weather['time'])} hours of forecast")
def agent_example():
"""Example using LangChain agent (requires API key)."""
print("\n🤖 LangChain Agent Example")
print("-" * 40)
import os
if not os.getenv("GOOGLE_API_KEY"):
print("⚠️ Skipping agent example - GOOGLE_API_KEY not set")
return
try:
# Create agent
agent = WeatherAgent()
# Ask weather questions
questions = [
"What's the weather like in Tokyo for the next 6 hours?",
"日本明天早上會下雨嗎?",
"Compare the temperature between London and Paris"
]
for question in questions:
print(f"\n❓ Question: {question}")
answer = agent.ask_weather(question)
print(f"✅ Answer: {answer[:150]}...")
except Exception as e:
print(f"❌ Agent example failed: {e}")
def visualization_example():
"""Example of weather data visualization."""
print("\n📊 Visualization Example")
print("-" * 40)
try:
# Get weather data
client = WeatherMCPClient()
result = client.get_city_weather("Tokyo", hours=12)
if "weather" in result:
weather_data = result["weather"]
city_name = result.get("display_name", "Tokyo")
print(f"📈 Creating visualization for {city_name}...")
# Method 1: Quick plot
plot_weather_trends_horizontal(weather_data, f"Weather in {city_name}")
# Method 2: Using visualizer object
visualizer = create_visualizer()
# Get summary statistics
summary = visualizer.get_weather_summary(weather_data)
print(f"\n📋 Weather Summary:")
print(f" Temperature: {summary['temperature']['min']:.1f}°C - {summary['temperature']['max']:.1f}°C")
print(f" Average humidity: {summary['humidity']['mean']:.1f}%")
print(f" Max precipitation chance: {summary['precipitation']['max']:.0f}%")
print(f" Forecast period: {summary['period']['hours']} hours")
# Create different types of plots
temp_fig = visualizer.plot_temperature_trend(weather_data, f"Temperature in {city_name}")
temp_fig.savefig("temperature_trend.png", dpi=150, bbox_inches='tight')
print("💾 Temperature chart saved as: temperature_trend.png")
overview_fig = visualizer.plot_all_metrics(weather_data, city_name)
overview_fig.savefig("weather_overview.png", dpi=150, bbox_inches='tight')
print("💾 Overview chart saved as: weather_overview.png")
else:
print("❌ Failed to get weather data")
except Exception as e:
print(f"❌ Visualization example failed: {e}")
def advanced_client_example():
"""Advanced client usage with error handling."""
print("\n🔧 Advanced Client Example")
print("-" * 40)
client = WeatherMCPClient(timeout=10.0)
cities = ["Tokyo", "London", "Invalid_City_Name", "Paris"]
for city in cities:
print(f"\n🏙️ Processing {city}...")
try:
result = client.get_city_weather(city, hours=3)
if "error" in result:
print(f"❌ Error for {city}: {result['error']}")
elif "weather" in result:
weather = result["weather"]["hourly"]
temps = weather["temperature_2m"]
print(f"✅ {result['display_name']}: {min(temps):.1f}°C - {max(temps):.1f}°C")
else:
print(f"⚠️ Unexpected result format for {city}")
except Exception as e:
print(f"❌ Exception for {city}: {e}")
def server_info_example():
"""Example of getting server information."""
print("\n🛠️ Server Information Example")
print("-" * 40)
try:
client = WeatherMCPClient()
# This will internally connect to server and list tools
result = client.geocode_city("test") # Simple call to trigger connection
print("✅ Successfully connected to MCP server")
# Test all available tools
tools_to_test = [
("geocode_city", {"city": "Tokyo"}),
("get_alerts", {"lat": 35.6895, "lon": 139.6917})
]
for tool_name, args in tools_to_test:
print(f"\n🧰 Testing tool: {tool_name}")
result = client.arun(client.call_tool(tool_name, args))
if "error" in result:
print(f" ❌ Error: {result['error']}")
else:
print(f" ✅ Success: {type(result)} response")
except Exception as e:
print(f"❌ Server info example failed: {e}")
if __name__ == "__main__":
print("🌤️ Weather MCP - Usage Examples")
print("=" * 50)
# Run all examples
basic_client_example()
agent_example()
visualization_example()
advanced_client_example()
server_info_example()
print("\n✅ All examples completed!")
print("\nNext steps:")
print("1. Set GOOGLE_API_KEY for agent features")
print("2. Run: python main.py --mode interactive")
print("3. Try: python main.py --mode viz")