Skip to main content
Glama
test_trip_recommendations.py12.7 kB
""" Test script for the get_trip_recommendations tool Run this to verify the tool works with real API data """ import os import sys from dotenv import load_dotenv # Load environment variables first load_dotenv() # Add src to path sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src')) # We need to import the actual function logic, not the decorated MCP tool # So we'll create a direct caller or import the implementation import httpx import json from datetime import datetime, timedelta def get_trip_recommendations( location: str, start_date: str = None, end_date: str = None, num_people: int = 1, preferences: str = None, budget_per_person: float = None ) -> str: """ Direct implementation of trip recommendations for testing. This mirrors the logic from mcp_server.py """ # If preferences not provided, use default if not preferences: preferences = "sightseeing, culture, food" # If dates not provided, use upcoming weekend if not start_date: today = datetime.now() days_until_friday = (4 - today.weekday()) % 7 start_date = (today + timedelta(days=days_until_friday)).strftime("%Y-%m-%d") if not end_date: end_date = (datetime.strptime(start_date, "%Y-%m-%d") + timedelta(days=2)).strftime("%Y-%m-%d") result = { "location": location, "trip_details": { "start_date": start_date, "end_date": end_date, "duration_days": (datetime.strptime(end_date, "%Y-%m-%d") - datetime.strptime(start_date, "%Y-%m-%d")).days + 1, "num_people": num_people, "preferences": preferences.split(",") if isinstance(preferences, str) else preferences, "budget_per_person": budget_per_person }, "weather_forecast": None, "recommendations": [], "tips": [] } try: # Get weather data from OpenWeatherMap api_key = os.getenv("OPENWEATHER_API_KEY") if api_key: with httpx.Client(timeout=10.0) as client: # Use the forecast API directly with city name - it will find coordinates automatically weather_url = f"http://api.openweathermap.org/data/2.5/forecast?q={location}&appid={api_key}&units=metric" weather_response = client.get(weather_url) if weather_response.status_code == 200: weather_data = weather_response.json() # Extract city info (includes coordinates) city_info = weather_data.get("city", {}) lat = city_info.get("coord", {}).get("lat") lon = city_info.get("coord", {}).get("lon") country = city_info.get("country") city_name = city_info.get("name", location) # Parse weather forecasts forecasts = [] for item in weather_data.get("list", [])[:8]: # Next 24 hours forecasts.append({ "datetime": item.get("dt_txt"), "temp": f"{item['main']['temp']}°C", "feels_like": f"{item['main']['feels_like']}°C", "weather": item['weather'][0]['description'], "humidity": f"{item['main']['humidity']}%", "wind_speed": f"{item['wind']['speed']} m/s" }) result["weather_forecast"] = { "location": f"{city_name}, {country}" if country else city_name, "coordinates": {"lat": lat, "lon": lon}, "forecasts": forecasts, "summary": f"Weather in {city_name}: {forecasts[0]['weather']}, {forecasts[0]['temp']}" } elif weather_response.status_code == 404: result["weather_forecast"] = { "error": f"Could not find location: {location}", "suggestion": "Try adding country name (e.g., 'Udaipur, India' or 'Paris, France')", "status_code": 404 } elif weather_response.status_code == 401: result["weather_forecast"] = { "error": "Invalid API key", "message": "Please check your OPENWEATHER_API_KEY in .env file", "status_code": 401 } else: result["weather_forecast"] = { "error": f"Weather API error: {weather_response.status_code}", "message": "Could not reach weather service" } else: result["weather_forecast"] = { "note": "Weather data unavailable. Set OPENWEATHER_API_KEY environment variable.", "instructions": "Get free API key from https://openweathermap.org/api" } except Exception as e: result["weather_forecast"] = {"error": f"Failed to fetch weather: {str(e)}"} # Generate recommendations based on preferences pref_list = [p.strip().lower() for p in preferences.split(",")] if isinstance(preferences, str) else [] recommendations = [] # General recommendations recommendations.append({ "category": "Getting Started", "suggestions": [ f"Research local customs and etiquette for {location}", "Book accommodations in advance for better rates", "Check visa requirements and travel insurance", "Download offline maps and translation apps" ] }) # Preference-based recommendations if "adventure" in pref_list or "nature" in pref_list: recommendations.append({ "category": "Adventure & Nature", "suggestions": [ "Look for hiking trails and outdoor activities", "Book adventure sports in advance (if available)", "Check weather conditions for outdoor activities", "Bring appropriate gear (hiking shoes, water bottles)" ] }) if "food" in pref_list or "culture" in pref_list: recommendations.append({ "category": "Food & Culture", "suggestions": [ "Try local street food and traditional restaurants", "Join food walking tours to discover hidden gems", "Visit local markets and food halls", "Check Tripadvisor or Google reviews for top-rated restaurants" ] }) if "sightseeing" in pref_list or "culture" in pref_list: recommendations.append({ "category": "Sightseeing & Culture", "suggestions": [ "Book skip-the-line tickets for popular attractions", "Consider guided tours for historical context", "Visit museums on free entry days (if available)", "Plan visits to main attractions early morning to avoid crowds" ] }) if "relaxation" in pref_list: recommendations.append({ "category": "Relaxation", "suggestions": [ "Look for spa services and wellness centers", "Find peaceful parks or waterfront areas", "Book accommodations with relaxation amenities", "Schedule downtime between activities" ] }) if "shopping" in pref_list: recommendations.append({ "category": "Shopping", "suggestions": [ "Visit local markets for authentic souvenirs", "Check opening hours of shopping districts", "Research tax refund policies for tourists", "Bring reusable bags for shopping" ] }) result["recommendations"] = recommendations # Budget tips if budget_per_person: result["tips"].append(f"With a budget of {budget_per_person} per person, prioritize free attractions and local eateries") # Group travel tips if num_people > 1: result["tips"].extend([ f"Traveling with {num_people} people - consider group discounts for activities", "Book group accommodations like vacation rentals for better value", "Use group transportation (minibus/van) for cost efficiency" ]) # Weather-based tips if result.get("weather_forecast") and "forecasts" in result["weather_forecast"]: first_forecast = result["weather_forecast"]["forecasts"][0] if "rain" in first_forecast["weather"].lower(): result["tips"].append("Pack rain gear and plan indoor activities") temp = float(first_forecast["temp"].replace("°C", "")) if temp > 30: result["tips"].append("Hot weather expected - stay hydrated and use sun protection") elif temp < 10: result["tips"].append("Cold weather expected - pack warm clothing") # External resources result["useful_resources"] = { "weather": f"https://openweathermap.org/city/{location.replace(' ', '-')}", "tripadvisor": f"https://www.tripadvisor.com/Search?q={location.replace(' ', '+')}", "google_maps": f"https://www.google.com/maps/search/?api=1&query={location.replace(' ', '+')}", "booking": f"https://www.booking.com/searchresults.html?ss={location.replace(' ', '+')}", "wikitravel": f"https://wikitravel.org/en/{location.replace(' ', '_')}" } return json.dumps(result, indent=2, default=str) def test_basic_trip(): """Test 1: Basic trip with minimal parameters""" print("\n" + "="*80) print("TEST 1: Basic Trip to Paris (minimal input)") print("="*80) result = get_trip_recommendations(location="Paris") print(result) print("\n") def test_detailed_trip(): """Test 2: Detailed trip with all parameters""" print("\n" + "="*80) print("TEST 2: Detailed Trip to Udaipur, India") print("="*80) result = get_trip_recommendations( location="Udaipur, India", start_date="2025-12-20", end_date="2025-12-25", num_people=4, preferences="adventure, nature, food", budget_per_person=5000 ) print(result) print("\n") def test_group_trip(): """Test 3: Group trip with specific interests""" print("\n" + "="*80) print("TEST 3: Group Trip to Mumbai, India") print("="*80) result = get_trip_recommendations( location="Mumbai, India", start_date="2026-01-15", end_date="2026-01-22", num_people=8, preferences="food, shopping, culture" ) print(result) print("\n") def test_without_api_key(): """Test 4: Verify graceful handling when API key is missing""" print("\n" + "="*80) print("TEST 4: Testing without API key (should show instructions)") print("="*80) # Temporarily remove API key api_key_backup = os.environ.get("OPENWEATHER_API_KEY") if "OPENWEATHER_API_KEY" in os.environ: del os.environ["OPENWEATHER_API_KEY"] result = get_trip_recommendations(location="Tokyo") print(result) # Restore API key if api_key_backup: os.environ["OPENWEATHER_API_KEY"] = api_key_backup print("\n") def main(): print("\n" + "="*80) print("TRIP RECOMMENDATIONS TOOL - TEST SUITE") print("="*80) # Check if API key is set api_key = os.getenv("OPENWEATHER_API_KEY") if api_key: print(f"✅ OPENWEATHER_API_KEY is set (length: {len(api_key)})") else: print("⚠️ OPENWEATHER_API_KEY is not set - weather data will be unavailable") print(" Get free API key from: https://openweathermap.org/api") print(" Add to .env file: OPENWEATHER_API_KEY=your_key_here") print("\nRunning tests...\n") try: # Run all tests test_basic_trip() test_detailed_trip() test_group_trip() test_without_api_key() print("\n" + "="*80) print("✅ ALL TESTS COMPLETED") print("="*80) except Exception as e: print(f"\n❌ ERROR: {str(e)}") import traceback traceback.print_exc() if __name__ == "__main__": main()

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/SUSHRUTH3002/MCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server