Google Flights MCP, CLI and Python Library
feat: add multi-city flight search support (#57)
Omar Shahine370014df8801
diff --git a/fli/cli/utils.py b/fli/cli/utils.pyindex d561a19..89b57c4 100644--- a/fli/cli/utils.py+++ b/fli/cli/utils.py@@ -288,16 +288,18 @@ def display_flight_results(flights: list):returnfor i, flight_data in enumerate(flights, 1):- is_round_trip = isinstance(flight_data, tuple)- flight_segments = [flight_data] if not is_round_trip else [flight_data[0], flight_data[1]]+ is_multi_leg = isinstance(flight_data, tuple)+ flight_segments = list(flight_data) if is_multi_leg else [flight_data]+ num_legs = len(flight_segments)# Create main flight info tabletable = Table(show_header=False, box=box.SIMPLE)table.add_column("Label", style="blue")table.add_column("Value", style="green")- # Google Flights returns the full round-trip price on the outbound leg- total_price = flight_segments[0].price+ # Google Flights returns the full trip price on the outbound leg for round-trips,+ # and on the final leg for multi-city trips.+ total_price = flight_segments[-1].price if num_legs > 2 else flight_segments[0].pricetable.add_row("Total Price", f"${total_price:,.2f}")total_duration = sum(flight.duration for flight in flight_segments)@@ -308,7 +310,12 @@ def display_flight_results(flights: list):# Create segments tables for each directionall_segments = []for idx, flight in enumerate(flight_segments):- direction = "" if not is_round_trip else ("Outbound" if idx == 0 else "Return")+ if num_legs == 1:+ direction = ""+ elif num_legs == 2:+ direction = "Outbound" if idx == 0 else "Return"+ else:+ direction = f"Leg {idx + 1}"segments = Table(title=(f"{direction} Flight Segments" if direction else "Flight Segments"),box=box.ROUNDED,@@ -332,7 +339,12 @@ def display_flight_results(flights: list):all_segments.extend([segments, Text("")])# Display in a panel- title = "Round-trip Flight" if is_round_trip else "One-way Flight"+ if num_legs > 2:+ title = "Multi-city Flight"+ elif num_legs == 2:+ title = "Round-trip Flight"+ else:+ title = "One-way Flight"console.print(Panel(Group(diff --git a/fli/core/__init__.py b/fli/core/__init__.pyindex a55709f..5b65b79 100644--- a/fli/core/__init__.py+++ b/fli/core/__init__.py@@ -4,7 +4,12 @@ This module provides shared parsing and building utilities used by boththe CLI and MCP interfaces."""-from .builders import build_date_search_segments, build_flight_segments, build_time_restrictions+from .builders import (+ build_date_search_segments,+ build_flight_segments,+ build_multi_city_segments,+ build_time_restrictions,+)from .parsers import (parse_airlines,parse_cabin_class,@@ -27,5 +32,6 @@ __all__ = [# Builders"build_date_search_segments","build_flight_segments",+ "build_multi_city_segments","build_time_restrictions",]diff --git a/fli/core/builders.py b/fli/core/builders.pyindex d9aad65..966d21d 100644--- a/fli/core/builders.py+++ b/fli/core/builders.py@@ -113,6 +113,33 @@ def build_flight_segments(return segments, trip_type+def build_multi_city_segments(+ legs: list[tuple[Airport, Airport, str]],+ time_restrictions: TimeRestrictions | None = None,+) -> tuple[list[FlightSegment], TripType]:+ """Build flight segments for a multi-city search.++ Args:+ legs: List of (origin, destination, date) tuples for each leg+ time_restrictions: Time restrictions to apply to all segments++ Returns:+ Tuple of (list of FlightSegment objects, TripType.MULTI_CITY)++ """+ segments = [+ FlightSegment(+ departure_airport=[[origin, 0]],+ arrival_airport=[[destination, 0]],+ travel_date=normalize_date(date),+ time_restrictions=time_restrictions,+ )+ for origin, destination, date in legs+ ]++ return segments, TripType.MULTI_CITY++def build_date_search_segments(origin: Airport,destination: Airport,diff --git a/fli/models/google_flights/base.py b/fli/models/google_flights/base.pyindex 6894b1e..f44014e 100644--- a/fli/models/google_flights/base.py+++ b/fli/models/google_flights/base.py@@ -46,9 +46,7 @@ class TripType(Enum):ROUND_TRIP = 1ONE_WAY = 2-- # Currently not supported - kept for reference- _MULTI_CITY = 3 # Unsupported+ MULTI_CITY = 3class MaxStops(Enum):diff --git a/fli/models/google_flights/flights.py b/fli/models/google_flights/flights.pyindex 3cda5b5..890a638 100644--- a/fli/models/google_flights/flights.py+++ b/fli/models/google_flights/flights.py@@ -112,9 +112,10 @@ class FlightSearchFilters(BaseModel):self.layover_restrictions.max_duration if self.layover_restrictions else None)- # Selected flight (to fetch return flights)+ # Selected flight (to fetch return/next-leg flights)selected_flights = None- if self.trip_type == TripType.ROUND_TRIP and segment.selected_flight is not None:+ is_multi_leg = self.trip_type in (TripType.ROUND_TRIP, TripType.MULTI_CITY)+ if is_multi_leg and segment.selected_flight is not None:selected_flights = [[serialize(leg.departure_airport.name),diff --git a/fli/search/flights.py b/fli/search/flights.pyindex 0745016..ddc24a1 100644--- a/fli/search/flights.py+++ b/fli/search/flights.py@@ -75,25 +75,34 @@ class SearchFlights:]flights = [self._parse_flights_data(flight) for flight in flights_data]- if (- filters.trip_type == TripType.ONE_WAY- or filters.flight_segments[0].selected_flight is not None- ):+ if filters.trip_type == TripType.ONE_WAY:return flights- # Get the return flights if round-trip- flight_pairs = []- # Call the search again with the return flight data+ # For round-trip and multi-city, iteratively select each leg+ # and fetch the next leg's options with combined pricing.+ num_segments = len(filters.flight_segments)+ selected_count = sum(+ 1 for s in filters.flight_segments if s.selected_flight is not None+ )++ # If all previous segments are selected, we're on the last leg+ if selected_count >= num_segments - 1:+ return flights++ # Select each flight option and fetch the next leg+ flight_combos = []for selected_flight in flights[:top_n]:- selected_flight_filters = deepcopy(filters)- selected_flight_filters.flight_segments[0].selected_flight = selected_flight- return_flights = self.search(selected_flight_filters, top_n=top_n)- if return_flights is not None:- flight_pairs.extend(- (selected_flight, return_flight) for return_flight in return_flights- )-- return flight_pairs+ next_filters = deepcopy(filters)+ next_filters.flight_segments[selected_count].selected_flight = selected_flight+ next_results = self.search(next_filters, top_n=top_n)+ if next_results is not None:+ for next_result in next_results:+ if isinstance(next_result, tuple):+ flight_combos.append((selected_flight,) + next_result)+ else:+ flight_combos.append((selected_flight, next_result))++ return flight_combosexcept Exception as e:raise Exception(f"Search failed: {str(e)}") from e