Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

feat: add multi-city CLI command (#107)

Omar Shahine5bf4db9fb85c
diff --git a/README.md b/README.md
index 2e83c44..ae5b509 100644
--- a/README.md
+++ b/README.md
@@ -103,6 +103,7 @@ fli --help
* 🔍 **Powerful Search**
* One-way flight searches
+ * Multi-city flight searches
* Flexible departure times
* Multi-airline support
* Cabin class selection
@@ -173,6 +174,21 @@ fli dates JFK LHR \
> fli dates JFK LHR --from 2026-01-01 --to 2026-02-01 --format json
> ```
+### Multi-city Search
+
+```bash
+# Two-leg multi-city trip
+fli multi --leg SEA,HKG,2026-12-26 --leg PEK,SEA,2027-01-02
+
+# Three-leg multi-city trip with filters
+fli multi \
+ -l SEA,NRT,2026-12-26 \
+ -l NRT,HKG,2026-12-30 \
+ -l HKG,SEA,2027-01-05 \
+ --class BUSINESS \
+ --stops 0
+```
+
### CLI Options
#### Flights Command (`fli flights`)
@@ -203,6 +219,17 @@ fli dates JFK LHR \
| `--[day]` | Day filters | `--monday`, `--friday` |
| `--format` | Output format | `text`, `json` |
+#### Multi Command (`fli multi`)
+
+| Option | Description | Example |
+|------------------|--------------------------------------|--------------------------------|
+| `--leg, -l` | Flight leg (ORIGIN,DEST,DATE format) | `SEA,HKG,2026-12-26` |
+| `--time, -t` | Departure time window | `6-20` |
+| `--airlines, -a` | Airline IATA codes | `DL CX` |
+| `--class, -c` | Cabin class | `ECONOMY`, `BUSINESS` |
+| `--stops, -s` | Maximum stops | `NON_STOP`, `ONE_STOP` |
+| `--sort, -o` | Sort results by | `CHEAPEST`, `DURATION` |
+
## MCP Server Integration
Fli includes a Model Context Protocol (MCP) server that allows AI assistants like Claude to search for flights directly.
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
index 9307f17..59b11ae 100644
--- a/fli/cli/commands/flights.py
+++ b/fli/cli/commands/flights.py
@@ -175,7 +175,7 @@ def _search_flights_core(
)
return
- display_flight_results(results, default_currency=currency)
+ display_flight_results(results, trip_type=trip_type, default_currency=currency)
except ParseError as e:
if output_format == OutputFormat.JSON:
diff --git a/fli/cli/commands/multi.py b/fli/cli/commands/multi.py
new file mode 100644
index 0000000..36c6fae
--- /dev/null
+++ b/fli/cli/commands/multi.py
@@ -0,0 +1,167 @@
+"""Multi-city flight search CLI command."""
+
+import re
+from typing import Annotated
+
+import typer
+
+from fli.cli.utils import display_flight_results, validate_time_range
+from fli.core import (
+ build_multi_city_segments,
+ normalize_date,
+ parse_airlines,
+ parse_cabin_class,
+ parse_max_stops,
+ parse_sort_by,
+ resolve_airport,
+)
+from fli.core.parsers import ParseError
+from fli.models import (
+ FlightSearchFilters,
+ PassengerInfo,
+ TimeRestrictions,
+)
+from fli.search import SearchFlights
+
+LEG_PATTERN = re.compile(r"^([A-Za-z]{3}),([A-Za-z]{3}),(\d{4}-\d{1,2}-\d{1,2})$")
+
+
+def _parse_leg(value: str) -> tuple[str, str, str]:
+ """Parse a leg string in ORIGIN,DEST,DATE format.
+
+ Returns:
+ Tuple of (origin, destination, date).
+
+ Raises:
+ typer.BadParameter: If the format is invalid.
+
+ """
+ match = LEG_PATTERN.match(value)
+ if not match:
+ raise typer.BadParameter(
+ f"Invalid leg format: '{value}'. Expected ORIGIN,DEST,DATE (e.g., SEA,HKG,2026-12-26)"
+ )
+ return match.group(1).upper(), match.group(2).upper(), match.group(3)
+
+
+def multi(
+ legs: Annotated[
+ list[str],
+ typer.Option(
+ "--leg",
+ "-l",
+ help="Flight leg in ORIGIN,DEST,DATE format (repeatable, minimum 2)",
+ ),
+ ],
+ departure_window: Annotated[
+ str | None,
+ typer.Option(
+ "--time",
+ "-t",
+ help="Departure time window in 24h format (e.g., 6-20)",
+ callback=validate_time_range,
+ ),
+ ] = None,
+ airlines: Annotated[
+ list[str] | None,
+ typer.Option(
+ "--airlines",
+ "-a",
+ help="List of airline IATA codes (e.g., BA KL)",
+ ),
+ ] = None,
+ cabin_class: Annotated[
+ str,
+ typer.Option(
+ "--class",
+ "-c",
+ help="Cabin class (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
+ ),
+ ] = "ECONOMY",
+ max_stops: Annotated[
+ str,
+ typer.Option(
+ "--stops",
+ "-s",
+ help="Maximum stops (ANY, 0 for non-stop, 1 for one stop, 2+ for two stops)",
+ ),
+ ] = "ANY",
+ sort_by: Annotated[
+ str,
+ typer.Option(
+ "--sort",
+ "-o",
+ help="Sort results by (CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME)",
+ ),
+ ] = "CHEAPEST",
+):
+ """Search for multi-city flights with multiple legs.
+
+ Each leg specifies an origin, destination, and date. At least two legs are required.
+
+ Example:
+ fli multi --leg SEA,HKG,2026-12-26 --leg PEK,SEA,2027-01-02
+ fli multi -l SEA,NRT,2026-12-26 -l NRT,HKG,2026-12-30 -l HKG,SEA,2027-01-05 -c BUSINESS
+
+ """
+ try:
+ if len(legs) < 2:
+ typer.echo("Error: multi-city search requires at least 2 legs")
+ raise typer.Exit(1)
+
+ # Parse and validate each leg
+ parsed_legs = []
+ for leg_str in legs:
+ origin, destination, date = _parse_leg(leg_str)
+ date = normalize_date(date)
+ origin_airport = resolve_airport(origin)
+ destination_airport = resolve_airport(destination)
+ parsed_legs.append((origin_airport, destination_airport, date))
+
+ # Parse shared filter parameters
+ seat_type = parse_cabin_class(cabin_class)
+ stops = parse_max_stops(max_stops)
+ parsed_airlines = parse_airlines(airlines)
+ sort = parse_sort_by(sort_by)
+
+ # Build time restrictions
+ time_restrictions = None
+ if departure_window:
+ time_restrictions = TimeRestrictions(
+ earliest_departure=departure_window[0],
+ latest_departure=departure_window[1],
+ )
+
+ # Build multi-city segments using shared builder
+ segments, trip_type = build_multi_city_segments(
+ legs=parsed_legs,
+ time_restrictions=time_restrictions,
+ )
+
+ # Create search filters
+ filters = FlightSearchFilters(
+ trip_type=trip_type,
+ passenger_info=PassengerInfo(adults=1),
+ flight_segments=segments,
+ stops=stops,
+ seat_type=seat_type,
+ airlines=parsed_airlines,
+ sort_by=sort,
+ )
+
+ # Perform search
+ search_client = SearchFlights()
+ results = search_client.search(filters)
+
+ if not results:
+ typer.echo("No flights found.")
+ raise typer.Exit(1)
+
+ display_flight_results(results, trip_type=trip_type)
+
+ except ParseError as e:
+ typer.echo(f"Error: {str(e)}")
+ raise typer.Exit(1) from e
+ except (AttributeError, ValueError) as e:
+ typer.echo(f"Error: {str(e)}")
+ raise typer.Exit(1) from e
diff --git a/fli/cli/main.py b/fli/cli/main.py
index 68025a7..6b83e85 100644
--- a/fli/cli/main.py
+++ b/fli/cli/main.py
@@ -8,6 +8,7 @@ import typer
from fli.cli.commands.airports import airports
from fli.cli.commands.dates import dates
from fli.cli.commands.flights import flights
+from fli.cli.commands.multi import multi
app = typer.Typer(
help="Search for flights using Google Flights data",
@@ -15,9 +16,10 @@ app = typer.Typer(
)
# Register commands
-app.command(name="flights")(flights)
-app.command(name="dates")(dates)
app.command(name="airports")(airports)
+app.command(name="dates")(dates)
+app.command(name="flights")(flights)
+app.command(name="multi")(multi)
@app.callback(invoke_without_command=True)
@@ -39,7 +41,7 @@ def cli():
args.append("--help")
# If the first argument isn't a command, treat as flights search
- if args[0] not in ["flights", "dates", "airports", "--help", "-h"]:
+ if args[0] not in ["airports", "dates", "flights", "multi", "--help", "-h"]:
sys.argv.insert(1, "flights")
app()
diff --git a/fli/cli/utils.py b/fli/cli/utils.py
index 1088d79..043cc18 100644
--- a/fli/cli/utils.py
+++ b/fli/cli/utils.py
@@ -313,12 +313,15 @@ def emit_json(payload: dict[str, Any]) -> None:
typer.echo(json.dumps(payload, indent=2))
-def display_flight_results(flights: list, default_currency: str = "USD"):
+def display_flight_results(
+ flights: list, trip_type: TripType = TripType.ONE_WAY, default_currency: str = "USD"
+):
"""Display flight results in a beautiful format.
Args:
flights: List of either FlightResult objects (one-way)
- or tuples of (outbound, return) FlightResults (round-trip)
+ or tuples of FlightResults (round-trip or multi-city)
+ trip_type: The trip type to correctly interpret pricing.
default_currency: Fallback currency code when Google does not return one.
"""
@@ -326,6 +329,8 @@ def display_flight_results(flights: list, default_currency: str = "USD"):
console.print(Panel("No flights found matching your criteria", style="red"))
return
+ is_multi_city = trip_type == TripType.MULTI_CITY
+
for i, flight_data in enumerate(flights, 1):
is_multi_leg = isinstance(flight_data, tuple)
flight_segments = list(flight_data) if is_multi_leg else [flight_data]
@@ -338,7 +343,7 @@ def display_flight_results(flights: list, default_currency: str = "USD"):
# Google Flights returns the full trip price on the outbound leg for round-trips,
# and on the final leg for multi-city trips.
- price_segment = flight_segments[-1] if num_legs > 2 else flight_segments[0]
+ price_segment = flight_segments[-1] if is_multi_city else flight_segments[0]
total_price = price_segment.price
table.add_row(
"Total Price", format_price(total_price, price_segment.currency or default_currency)
@@ -354,10 +359,10 @@ def display_flight_results(flights: list, default_currency: str = "USD"):
for idx, flight in enumerate(flight_segments):
if num_legs == 1:
direction = ""
- elif num_legs == 2:
- direction = "Outbound" if idx == 0 else "Return"
- else:
+ elif is_multi_city:
direction = f"Leg {idx + 1}"
+ else:
+ direction = "Outbound" if idx == 0 else "Return"
segments = Table(
title=(f"{direction} Flight Segments" if direction else "Flight Segments"),
box=box.ROUNDED,
@@ -380,7 +385,7 @@ def display_flight_results(flights: list, default_currency: str = "USD"):
all_segments.extend([segments, Text("")])
# Display in a panel
- if num_legs > 2:
+ if is_multi_city:
title = "Multi-city Flight"
elif num_legs == 2:
title = "Round-trip Flight"
diff --git a/fli/core/__init__.py b/fli/core/__init__.py
index d1d9cc5..645a690 100644
--- a/fli/core/__init__.py
+++ b/fli/core/__init__.py
@@ -10,6 +10,7 @@ from .builders import (
build_flight_segments,
build_multi_city_segments,
build_time_restrictions,
+ normalize_date,
)
from .currency import extract_currency_from_price_token, format_price, format_price_axis_label
from .parsers import (
@@ -38,6 +39,7 @@ __all__ = [
"build_flight_segments",
"build_multi_city_segments",
"build_time_restrictions",
+ "normalize_date",
"search_airports",
# Currency
"extract_currency_from_price_token",
diff --git a/fli/core/builders.py b/fli/core/builders.py
index 22e6dc2..a85e32e 100644
--- a/fli/core/builders.py
+++ b/fli/core/builders.py
@@ -135,6 +135,7 @@ def build_multi_city_segments(
limitations of the Google Flights API endpoint. Round-trip-style
multi-city (same origin and final destination) works reliably.
+
"""
segments = [
FlightSegment(
diff --git a/tests/cli/test_multi.py b/tests/cli/test_multi.py
new file mode 100644
index 0000000..5742947
--- /dev/null
+++ b/tests/cli/test_multi.py
@@ -0,0 +1,275 @@
+"""Tests for the multi-city CLI command."""
+
+from datetime import datetime, timedelta
+
+import pytest
+from typer.testing import CliRunner
+
+from fli.cli.main import app
+from fli.models import Airline, Airport, FlightLeg, FlightResult
+from fli.models.google_flights.base import TripType
+
+
+def runner():
+ """Return a CliRunner instance."""
+ return CliRunner()
+
+
+def _future_date(days_ahead: int = 30) -> str:
+ """Return a future date string in YYYY-MM-DD format."""
+ return (datetime.now() + timedelta(days=days_ahead)).strftime("%Y-%m-%d")
+
+
+def _make_multi_city_results():
+ """Create mock multi-city results (3-tuple of FlightResults)."""
+ now = datetime.now()
+ return [
+ (
+ FlightResult(
+ price=0.0,
+ duration=600,
+ stops=0,
+ legs=[
+ FlightLeg(
+ airline=Airline.DL,
+ flight_number="DL100",
+ departure_airport=Airport.SEA,
+ arrival_airport=Airport.HKG,
+ departure_datetime=now,
+ arrival_datetime=now + timedelta(hours=10),
+ duration=600,
+ )
+ ],
+ ),
+ FlightResult(
+ price=0.0,
+ duration=300,
+ stops=0,
+ legs=[
+ FlightLeg(
+ airline=Airline.CX,
+ flight_number="CX200",
+ departure_airport=Airport.HKG,
+ arrival_airport=Airport.PEK,
+ departure_datetime=now + timedelta(days=4),
+ arrival_datetime=now + timedelta(days=4, hours=5),
+ duration=300,
+ )
+ ],
+ ),
+ FlightResult(
+ price=2499.99,
+ duration=660,
+ stops=1,
+ legs=[
+ FlightLeg(
+ airline=Airline.CA,
+ flight_number="CA300",
+ departure_airport=Airport.PEK,
+ arrival_airport=Airport.NRT,
+ departure_datetime=now + timedelta(days=7),
+ arrival_datetime=now + timedelta(days=7, hours=4),
+ duration=240,
+ ),
+ FlightLeg(
+ airline=Airline.DL,
+ flight_number="DL400",
+ departure_airport=Airport.NRT,
+ arrival_airport=Airport.SEA,
+ departure_datetime=now + timedelta(days=7, hours=6),
+ arrival_datetime=now + timedelta(days=7, hours=13),
+ duration=420,
+ ),
+ ],
+ ),
+ )
+ ]
+
+
+class TestMultiCityCommand:
+ """Tests for the multi command."""
+
+ def test_basic_two_leg_search(self, runner, mock_search_flights, mock_console):
+ """Test basic multi-city search with two legs."""
+ date1 = _future_date(30)
+ date2 = _future_date(37)
+
+ result = runner.invoke(
+ app,
+ ["multi", "--leg", f"SEA,HKG,{date1}", "--leg", f"HKG,SEA,{date2}"],
+ )
+ assert result.exit_code == 0
+ mock_search_flights.search.assert_called_once()
+
+ def test_three_leg_search(self, runner, mock_search_flights, mock_console):
+ """Test multi-city search with three legs."""
+ mock_search_flights.search.return_value = _make_multi_city_results()
+
+ date1 = _future_date(30)
+ date2 = _future_date(34)
+ date3 = _future_date(37)
+
+ result = runner.invoke(
+ app,
+ [
+ "multi",
+ "--leg",
+ f"SEA,HKG,{date1}",
+ "--leg",
+ f"HKG,PEK,{date2}",
+ "--leg",
+ f"PEK,SEA,{date3}",
+ ],
+ )
+ assert result.exit_code == 0
+ mock_search_flights.search.assert_called_once()
+ args, _ = mock_search_flights.search.call_args
+ assert args[0].trip_type == TripType.MULTI_CITY
+ assert len(args[0].flight_segments) == 3
+
+ def test_with_cabin_class(self, runner, mock_search_flights, mock_console):
+ """Test multi-city search with cabin class filter."""
+ date1 = _future_date(30)
+ date2 = _future_date(37)
+
+ result = runner.invoke(
+ app,
+ [
+ "multi",
+ "--leg",
+ f"SEA,HKG,{date1}",
+ "--leg",
+ f"HKG,SEA,{date2}",
+ "--class",
+ "BUSINESS",
+ ],
+ )
+ assert result.exit_code == 0
+
+ def test_with_stops_filter(self, runner, mock_search_flights, mock_console):
+ """Test multi-city search with stops filter."""
+ date1 = _future_date(30)
+ date2 = _future_date(37)
+
+ result = runner.invoke(
+ app,
+ [
+ "multi",
+ "--leg",
+ f"SEA,HKG,{date1}",
+ "--leg",
+ f"HKG,SEA,{date2}",
+ "--stops",
+ "NON_STOP",
+ ],
+ )
+ assert result.exit_code == 0
+
+ def test_with_airlines_filter(self, runner, mock_search_flights, mock_console):
+ """Test multi-city search with airline filter."""
+ date1 = _future_date(30)
+ date2 = _future_date(37)
+
+ result = runner.invoke(
+ app,
+ [
+ "multi",
+ "--leg",
+ f"SEA,HKG,{date1}",
+ "--leg",
+ f"HKG,SEA,{date2}",
+ "-a",
+ "DL",
+ "-a",
+ "CX",
+ ],
+ )
+ assert result.exit_code == 0
+
+ def test_with_time_filter(self, runner, mock_search_flights, mock_console):
+ """Test multi-city search with departure time window."""
+ date1 = _future_date(30)
+ date2 = _future_date(37)
+
+ result = runner.invoke(
+ app,
+ [
+ "multi",
+ "--leg",
+ f"SEA,HKG,{date1}",
+ "--leg",
+ f"HKG,SEA,{date2}",
+ "--time",
+ "6-20",
+ ],
+ )
+ assert result.exit_code == 0
+
+ def test_short_flag(self, runner, mock_search_flights, mock_console):
+ """Test multi-city search using -l short flag."""
+ date1 = _future_date(30)
+ date2 = _future_date(37)
+
+ result = runner.invoke(
+ app,
+ ["multi", "-l", f"SEA,HKG,{date1}", "-l", f"HKG,SEA,{date2}"],
+ )
+ assert result.exit_code == 0
+
+
+class TestMultiCityValidation:
+ """Tests for multi-city command validation and error handling."""
+
+ def test_single_leg_rejected(self, runner, mock_search_flights, mock_console):
+ """Test that a single leg is rejected."""
+ date1 = _future_date(30)
+
+ result = runner.invoke(
+ app,
+ ["multi", "--leg", f"SEA,HKG,{date1}"],
+ )
+ assert result.exit_code == 1
+ assert "at least 2 legs" in result.stdout
+
+ def test_invalid_leg_format(self, runner, mock_search_flights, mock_console):
+ """Test that invalid leg format is rejected."""
+ result = runner.invoke(
+ app,
+ ["multi", "--leg", "SEA-HKG-2026-12-26", "--leg", "HKG-SEA-2027-01-02"],
+ )
+ assert result.exit_code != 0
+
+ def test_invalid_airport_code(self, runner, mock_search_flights, mock_console):
+ """Test that invalid airport codes are rejected."""
+ date1 = _future_date(30)
+ date2 = _future_date(37)
+
+ result = runner.invoke(
+ app,
+ ["multi", "--leg", f"XXX,HKG,{date1}", "--leg", f"HKG,SEA,{date2}"],
+ )
+ assert result.exit_code == 1
+ assert "Error" in result.stdout
+
+ def test_invalid_date(self, runner, mock_search_flights, mock_console):
+ """Test that invalid dates are rejected."""
+ result = runner.invoke(
+ app,
+ ["multi", "--leg", "SEA,HKG,2026-13-45", "--leg", "HKG,SEA,2027-01-02"],
+ )
+ assert result.exit_code != 0
+
+ def test_no_results(self, runner, mock_search_flights, mock_console):
+ """Test multi-city search with no results."""
+ mock_search_flights.search.return_value = []
+
+ date1 = _future_date(30)
+ date2 = _future_date(37)
+
+ result = runner.invoke(
+ app,
+ ["multi", "--leg", f"SEA,HKG,{date1}", "--leg", f"HKG,SEA,{date2}"],
+ )
+ assert result.exit_code == 1
+ assert "No flights found" in result.stdout
diff --git a/tests/cli/test_utils.py b/tests/cli/test_utils.py
index 62593c0..b4321f4 100644
--- a/tests/cli/test_utils.py
+++ b/tests/cli/test_utils.py
@@ -21,8 +21,7 @@ from fli.cli.utils import (
validate_date,
validate_time_range,
)
-from fli.models import Airline, Airport, FlightLeg, FlightResult, MaxStops
-from fli.models.google_flights.base import TripType
+from fli.models import Airline, Airport, FlightLeg, FlightResult, MaxStops, TripType
from fli.search.dates import DatePrice
@@ -244,12 +243,12 @@ def _make_flight_result(
)
-def _capture_display(flights: list) -> str:
+def _capture_display(flights: list, trip_type: TripType = TripType.ONE_WAY) -> str:
"""Run display_flight_results and capture the rendered text."""
buf = StringIO()
test_console = Console(file=buf, width=120, force_terminal=True)
with patch("fli.cli.utils.console", test_console):
- display_flight_results(flights)
+ display_flight_results(flights, trip_type=trip_type)
return buf.getvalue()
@@ -285,7 +284,7 @@ def test_display_multi_city_three_legs():
leg2 = _make_flight_result(price=0.0, flight_number="DL200")
leg3 = _make_flight_result(price=800.0, flight_number="UA300")
- output = _capture_display([(leg1, leg2, leg3)])
+ output = _capture_display([(leg1, leg2, leg3)], trip_type=TripType.MULTI_CITY)
assert "$800.00" in output
assert "Multi-city Flight" in output
diff --git a/uv.lock b/uv.lock
index 31cc929..e3fb2d4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -637,7 +637,7 @@ wheels = [
[[package]]
name = "flights"
-version = "0.8.2"
+version = "0.8.4"
source = { editable = "." }
dependencies = [
{ name = "babel" },