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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mcp.server.fastmcp import FastMCP
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
import random
|
| 4 |
+
import urllib.parse
|
| 5 |
+
|
| 6 |
+
# Initialize FastMCP server for Flights
|
| 7 |
+
mcp = FastMCP("FlightsAgent")
|
| 8 |
+
|
| 9 |
+
# Real airline data for realistic results
|
| 10 |
+
REAL_AIRLINES = [
|
| 11 |
+
{"name": "Emirates", "code": "EK", "hub": "DXB"},
|
| 12 |
+
{"name": "British Airways", "code": "BA", "hub": "LHR"},
|
| 13 |
+
{"name": "Qatar Airways", "code": "QR", "hub": "DOH"},
|
| 14 |
+
{"name": "Turkish Airlines", "code": "TK", "hub": "IST"},
|
| 15 |
+
{"name": "Lufthansa", "code": "LH", "hub": "FRA"},
|
| 16 |
+
{"name": "Air France", "code": "AF", "hub": "CDG"},
|
| 17 |
+
{"name": "KLM", "code": "KL", "hub": "AMS"},
|
| 18 |
+
{"name": "Etihad Airways", "code": "EY", "hub": "AUH"},
|
| 19 |
+
{"name": "Swiss", "code": "LX", "hub": "ZRH"},
|
| 20 |
+
{"name": "Singapore Airlines", "code": "SQ", "hub": "SIN"},
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
# Common layover cities
|
| 24 |
+
LAYOVER_CITIES = {
|
| 25 |
+
"DOH": "Doha", "IST": "Istanbul", "FRA": "Frankfurt",
|
| 26 |
+
"CDG": "Paris", "AMS": "Amsterdam", "DXB": "Dubai",
|
| 27 |
+
"AUH": "Abu Dhabi", "ZRH": "Zurich", "MUC": "Munich"
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
def generate_realistic_price(origin: str, destination: str, passengers: int, cabin_class: str = "economy") -> int:
|
| 31 |
+
"""Generate realistic flight prices based on route."""
|
| 32 |
+
# Base prices for common routes (economy, per person)
|
| 33 |
+
base_prices = {
|
| 34 |
+
"short": (150, 350), # < 3 hours
|
| 35 |
+
"medium": (350, 700), # 3-7 hours
|
| 36 |
+
"long": (600, 1500), # > 7 hours
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
# Estimate distance category based on common routes
|
| 40 |
+
long_haul_dests = ["dubai", "tokyo", "sydney", "new york", "los angeles", "singapore", "bangkok", "bali"]
|
| 41 |
+
medium_dests = ["paris", "rome", "barcelona", "amsterdam", "berlin", "madrid", "lisbon", "athens"]
|
| 42 |
+
|
| 43 |
+
dest_lower = destination.lower()
|
| 44 |
+
if any(d in dest_lower for d in long_haul_dests):
|
| 45 |
+
min_p, max_p = base_prices["long"]
|
| 46 |
+
elif any(d in dest_lower for d in medium_dests):
|
| 47 |
+
min_p, max_p = base_prices["medium"]
|
| 48 |
+
else:
|
| 49 |
+
min_p, max_p = base_prices["short"]
|
| 50 |
+
|
| 51 |
+
base = random.randint(min_p, max_p)
|
| 52 |
+
|
| 53 |
+
# Cabin class multipliers
|
| 54 |
+
if cabin_class == "business":
|
| 55 |
+
base = int(base * 3.5)
|
| 56 |
+
elif cabin_class == "first":
|
| 57 |
+
base = int(base * 6)
|
| 58 |
+
|
| 59 |
+
return base * passengers
|
| 60 |
+
|
| 61 |
+
@mcp.tool()
|
| 62 |
+
def search_flights(origin: str, destination: str, date: str, passengers: int = 1, return_date: str = "") -> str:
|
| 63 |
+
"""Search for flights between two cities. Returns a list of available flight options with booking links."""
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
flight_date = datetime.strptime(date, "%Y-%m-%d")
|
| 67 |
+
formatted_date = flight_date.strftime("%B %d, %Y")
|
| 68 |
+
except ValueError:
|
| 69 |
+
return "Error: Date must be in YYYY-MM-DD format."
|
| 70 |
+
|
| 71 |
+
# Calculate return date if not provided (default 7 days)
|
| 72 |
+
if not return_date:
|
| 73 |
+
from datetime import timedelta
|
| 74 |
+
return_dt = flight_date + timedelta(days=7)
|
| 75 |
+
return_date = return_dt.strftime("%Y-%m-%d")
|
| 76 |
+
|
| 77 |
+
# URL encode for booking links - clean city names
|
| 78 |
+
origin_clean = origin.split(",")[0].strip()
|
| 79 |
+
dest_clean = destination.split(",")[0].strip()
|
| 80 |
+
|
| 81 |
+
# Different encoding formats for different sites
|
| 82 |
+
origin_encoded = urllib.parse.quote(origin_clean) # "San%20Francisco"
|
| 83 |
+
dest_encoded = urllib.parse.quote(dest_clean) # "Tokyo"
|
| 84 |
+
origin_lower = origin_clean.lower().replace(" ", "-") # "san-francisco"
|
| 85 |
+
dest_lower = dest_clean.lower().replace(" ", "-") # "tokyo"
|
| 86 |
+
|
| 87 |
+
results = []
|
| 88 |
+
results.append(f"✈️ **Flight Search: {origin} → {destination}**")
|
| 89 |
+
results.append(f"📅 {formatted_date} | 👥 {passengers} passenger{'s' if passengers > 1 else ''}")
|
| 90 |
+
results.append("")
|
| 91 |
+
results.append("---")
|
| 92 |
+
|
| 93 |
+
# Generate 4 realistic flight options
|
| 94 |
+
used_airlines = random.sample(REAL_AIRLINES, min(4, len(REAL_AIRLINES)))
|
| 95 |
+
|
| 96 |
+
flight_times = [
|
| 97 |
+
(6, 30), (9, 15), (14, 45), (19, 20), (22, 10)
|
| 98 |
+
]
|
| 99 |
+
random.shuffle(flight_times)
|
| 100 |
+
|
| 101 |
+
for i, airline in enumerate(used_airlines[:4]):
|
| 102 |
+
dep_hour, dep_min = flight_times[i]
|
| 103 |
+
|
| 104 |
+
# Determine if direct or with layover
|
| 105 |
+
is_direct = random.random() > 0.6 # 40% direct flights
|
| 106 |
+
|
| 107 |
+
if is_direct:
|
| 108 |
+
duration_h = random.randint(6, 8)
|
| 109 |
+
duration_m = random.choice([0, 15, 30, 45])
|
| 110 |
+
total_mins = duration_h * 60 + duration_m
|
| 111 |
+
arr_hour = (dep_hour + duration_h + (dep_min + duration_m) // 60) % 24
|
| 112 |
+
arr_min = (dep_min + duration_m) % 60
|
| 113 |
+
next_day = "⁺¹" if dep_hour + duration_h >= 24 else ""
|
| 114 |
+
stops_text = "Direct"
|
| 115 |
+
layover_text = ""
|
| 116 |
+
else:
|
| 117 |
+
# Flight with layover
|
| 118 |
+
layover_code = random.choice(list(LAYOVER_CITIES.keys()))
|
| 119 |
+
layover_city = LAYOVER_CITIES[layover_code]
|
| 120 |
+
layover_duration = random.randint(1, 3)
|
| 121 |
+
layover_mins = random.choice([0, 15, 30, 45])
|
| 122 |
+
|
| 123 |
+
leg1_duration = random.randint(3, 5)
|
| 124 |
+
leg2_duration = random.randint(3, 5)
|
| 125 |
+
total_duration_h = leg1_duration + layover_duration + leg2_duration
|
| 126 |
+
total_mins = total_duration_h * 60 + layover_mins
|
| 127 |
+
|
| 128 |
+
arr_hour = (dep_hour + total_duration_h) % 24
|
| 129 |
+
arr_min = (dep_min + layover_mins) % 60
|
| 130 |
+
next_day = "⁺¹" if dep_hour + total_duration_h >= 24 else ""
|
| 131 |
+
stops_text = "1 stop"
|
| 132 |
+
layover_text = f" via {layover_city} ({layover_duration}h {layover_mins}m layover)"
|
| 133 |
+
|
| 134 |
+
# Price
|
| 135 |
+
price = generate_realistic_price(origin, destination, passengers)
|
| 136 |
+
flight_num = f"{airline['code']}{random.randint(100, 999)}"
|
| 137 |
+
|
| 138 |
+
# CO2 estimate
|
| 139 |
+
co2 = random.randint(400, 900)
|
| 140 |
+
|
| 141 |
+
# Build booking URL for this specific flight - DON'T include airline name
|
| 142 |
+
# Use simple city search for best results
|
| 143 |
+
google_url = f"https://www.google.com/travel/flights?q={origin_encoded}%20to%20{dest_encoded}%20{date}%20to%20{return_date}"
|
| 144 |
+
skyscanner_url = f"https://www.skyscanner.com/transport/flights/{origin_lower}/{dest_lower}/{date}/{return_date}/?adults={passengers}&cabinclass=economy"
|
| 145 |
+
|
| 146 |
+
results.append("")
|
| 147 |
+
results.append(f"### ✈️ Option {i+1}: {airline['name']}")
|
| 148 |
+
results.append(f"**{flight_num}** • {stops_text}{layover_text}")
|
| 149 |
+
results.append(f"🕐 {dep_hour:02d}:{dep_min:02d} → {arr_hour:02d}:{arr_min:02d}{next_day} ({total_mins // 60}h {total_mins % 60}m)")
|
| 150 |
+
results.append(f"💰 **${price:,}** total for {passengers} passenger{'s' if passengers > 1 else ''}")
|
| 151 |
+
results.append(f"🌱 {co2} kg CO₂")
|
| 152 |
+
results.append(f"🔗 [Book on Google Flights]({google_url}) | [Book on Skyscanner]({skyscanner_url})")
|
| 153 |
+
results.append("")
|
| 154 |
+
|
| 155 |
+
results.append("---")
|
| 156 |
+
results.append("")
|
| 157 |
+
results.append("💡 **Tip:** Prices shown are estimates. Click booking links for live prices and availability.")
|
| 158 |
+
|
| 159 |
+
return "\n".join(results)
|
| 160 |
+
|
| 161 |
+
@mcp.tool()
|
| 162 |
+
def get_flight_details(flight_number: str) -> str:
|
| 163 |
+
"""Get detailed information about a specific flight."""
|
| 164 |
+
airline_code = flight_number[:2].upper()
|
| 165 |
+
airline_name = next((a["name"] for a in REAL_AIRLINES if a["code"] == airline_code), "Unknown Airline")
|
| 166 |
+
|
| 167 |
+
return f"""✈️ **Flight {flight_number} Details**
|
| 168 |
+
|
| 169 |
+
🛩️ **Airline:** {airline_name}
|
| 170 |
+
✈️ **Aircraft:** Boeing 787-9 Dreamliner
|
| 171 |
+
🚪 **Terminal:** {random.randint(1, 5)} | Gate: {random.choice(['A', 'B', 'C', 'D'])}{random.randint(1, 30)}
|
| 172 |
+
✅ **Status:** On Time
|
| 173 |
+
|
| 174 |
+
**Included Amenities:**
|
| 175 |
+
• 🧳 Checked baggage: 23kg
|
| 176 |
+
• 🎒 Carry-on: 7kg
|
| 177 |
+
• 🍽️ Meal service included
|
| 178 |
+
• 📺 In-flight entertainment
|
| 179 |
+
• 🔌 USB charging ports
|
| 180 |
+
|
| 181 |
+
**Check-in:** Opens 24 hours before departure"""
|
| 182 |
+
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
+
mcp.run()
|