Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

feat: add multi-airport support to flights CLI command (#199)

LGull6a702627f066
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
index d801af4..f4bffa6 100644
--- a/fli/cli/commands/flights.py
+++ b/fli/cli/commands/flights.py
@@ -26,6 +26,7 @@ from fli.core import (
parse_max_stops,
parse_sort_by,
resolve_airport,
+ resolve_airports,
)
from fli.core.parsers import ParseError
from fli.models import (
@@ -88,9 +89,8 @@ def _search_flights_core(
f"{departure_window[0]}-{departure_window[1]}" if departure_window else None
)
- # Parse parameters using shared utilities
- origin_airport = resolve_airport(origin)
- destination_airport = resolve_airport(destination)
+ origin_airports = resolve_airports(origin)
+ destination_airports = resolve_airports(destination)
seat_type = parse_cabin_class(cabin_class)
stops = parse_max_stops(max_stops)
parsed_airlines = parse_airlines(airlines)
@@ -124,8 +124,8 @@ def _search_flights_core(
# Create flight segments using shared builder
segments, trip_type = build_flight_segments(
- origin=origin_airport,
- destination=destination_airport,
+ origin=origin_airports,
+ destination=destination_airports,
departure_date=departure_date,
return_date=return_date,
time_restrictions=time_restrictions,
@@ -133,8 +133,8 @@ def _search_flights_core(
# Shareable Google Flights deep link for this search.
booking_url = google_flights_url(
- origin_airport.name.lstrip("_"),
- destination_airport.name.lstrip("_"),
+ origin_airports[0].name.lstrip("_"),
+ destination_airports[0].name.lstrip("_"),
departure_date,
return_date,
currency=currency,
@@ -295,8 +295,14 @@ def _search_flights_core(
def flights(
- origin: Annotated[str, typer.Argument(help="Departure airport IATA code (e.g., JFK)")],
- destination: Annotated[str, typer.Argument(help="Arrival airport IATA code (e.g., LHR)")],
+ origin: Annotated[
+ str,
+ typer.Argument(help="Departure airport code, or a comma-separated list (e.g., JFK,LGA)"),
+ ],
+ destination: Annotated[
+ str,
+ typer.Argument(help="Arrival airport code, or a comma-separated list (e.g., LHR,LGW)"),
+ ],
departure_date: Annotated[str, typer.Argument(help="Travel date (YYYY-MM-DD)")],
return_date: Annotated[
str | None,
@@ -483,6 +489,7 @@ def flights(
Example:
fli flights JFK LHR 2026-10-25 --time 6-20 --airlines BA,KL --stops NON_STOP
fli flights JFK LHR 2026-10-25 --format json
+ fli flights JFK,LGA LHR,LGW 2026-10-25
fli flights JFK LHR 2026-10-25 --exclude-basic
fli flights JFK LAX 2026-10-25 --bags 1 --carry-on
fli flights JFK LAX 2026-10-25 --emissions LESS
diff --git a/fli/core/__init__.py b/fli/core/__init__.py
index 33045c8..bc37bef 100644
--- a/fli/core/__init__.py
+++ b/fli/core/__init__.py
@@ -24,6 +24,7 @@ from .parsers import (
parse_sort_by,
parse_time_range,
resolve_airport,
+ resolve_airports,
resolve_enum,
)
@@ -38,6 +39,7 @@ __all__ = [
"parse_sort_by",
"parse_time_range",
"resolve_airport",
+ "resolve_airports",
"resolve_enum",
# Builders
"build_date_search_segments",
diff --git a/fli/core/parsers.py b/fli/core/parsers.py
index 596b727..ab0659e 100644
--- a/fli/core/parsers.py
+++ b/fli/core/parsers.py
@@ -99,6 +99,27 @@ def resolve_airport(code: str) -> Airport:
raise ParseError(f"Invalid airport code: '{code}'") from e
+def resolve_airports(codes: str) -> list[Airport]:
+ """Resolve one or more comma-separated airport codes.
+
+ Args:
+ codes: A single code or a comma-separated list (e.g. ``"JFK,LGA"``).
+ Blank entries from stray or doubled commas are ignored.
+
+ Returns:
+ The resolved airports, in the order given.
+
+ Raises:
+ ParseError: If any code is unknown, or no codes remain after
+ discarding blanks (e.g. ``","``).
+
+ """
+ airports = [resolve_airport(code.strip()) for code in codes.split(",") if code.strip()]
+ if not airports:
+ raise ParseError(f"No valid airport codes found in: '{codes}'")
+ return airports
+
+
def parse_airlines(codes: list[str] | None) -> list[Airline] | None:
"""Parse a list of airline codes into Airline enums.
diff --git a/fli/mcp/server.py b/fli/mcp/server.py
index 2ad073c..f7adcd6 100755
--- a/fli/mcp/server.py
+++ b/fli/mcp/server.py
@@ -27,7 +27,7 @@ from fli.core import (
parse_emissions,
parse_max_stops,
parse_sort_by,
- resolve_airport,
+ resolve_airports,
search_airports,
)
from fli.core.parsers import ParseError
@@ -547,12 +547,8 @@ def _serialize_date_result(
# =============================================================================
-def _resolve_airports(codes: str) -> list[Airport]:
- """Resolve one or more comma-separated airport codes."""
- airports = [resolve_airport(code.strip()) for code in codes.split(",") if code.strip()]
- if not airports:
- raise ParseError(f"No valid airport codes found in: '{codes}'")
- return airports
+# Shared with the CLI; the private name is kept for backwards compatibility.
+_resolve_airports = resolve_airports
def _build_flight_filters(
diff --git a/tests/cli/test_flights.py b/tests/cli/test_flights.py
index affbea3..71ca8f5 100644
--- a/tests/cli/test_flights.py
+++ b/tests/cli/test_flights.py
@@ -389,3 +389,50 @@ def test_flights_json_no_results(runner, mock_search_flights, mock_console):
assert payload["success"] is True
assert payload["count"] == 0
assert payload["flights"] == []
+
+
+def test_given_comma_separated_origin_list_then_returns_flights_from_all(
+ runner, mock_search_flights, mock_console
+):
+ """Comma-separated origin passes multiple airports to the search segment."""
+ result = runner.invoke(
+ app,
+ ["flights", "JFK,LGA", "LAX", datetime.now().strftime("%Y-%m-%d")],
+ )
+ assert result.exit_code == 0
+ args, _ = mock_search_flights.search.call_args
+ departure_airports = [apt for apt, _ in args[0].flight_segments[0].departure_airport]
+ assert Airport.JFK in departure_airports
+ assert Airport.LGA in departure_airports
+
+
+def test_given_comma_separated_destination_list_then_returns_flights_to_all(
+ runner, mock_search_flights, mock_console
+):
+ """Comma-separated destination passes multiple airports to the search segment."""
+ result = runner.invoke(
+ app,
+ ["flights", "JFK", "LHR,CDG", datetime.now().strftime("%Y-%m-%d")],
+ )
+ assert result.exit_code == 0
+ args, _ = mock_search_flights.search.call_args
+ arrival_airports = [apt for apt, _ in args[0].flight_segments[0].arrival_airport]
+ assert Airport.LHR in arrival_airports
+ assert Airport.CDG in arrival_airports
+
+
[email protected]("bad_origin", [",", ",,", " , "])
+def test_flights_separator_only_origin_is_a_clean_error(
+ runner, mock_search_flights, mock_console, bad_origin
+):
+ """An origin made only of separators gets a clear parse error.
+
+ Previously the empty airport list reached the models and surfaced as a raw
+ pydantic validation dump.
+ """
+ tomorrow = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
+ result = runner.invoke(app, ["flights", bad_origin, "LAX", tomorrow])
+ assert result.exit_code != 0
+ assert "No valid airport codes" in result.output
+ assert "pydantic" not in result.output
+ mock_search_flights.search.assert_not_called()
diff --git a/tests/core/test_parsers.py b/tests/core/test_parsers.py
index fd72fbf..d74be70 100644
--- a/tests/core/test_parsers.py
+++ b/tests/core/test_parsers.py
@@ -8,6 +8,7 @@ from fli.core.parsers import (
parse_emissions,
parse_sort_by,
resolve_airport,
+ resolve_airports,
)
from fli.models import Airline, Airport, EmissionsFilter, SortBy
@@ -151,3 +152,23 @@ class TestResolveAirportICAO:
def test_three_letter_not_icao(self):
assert resolve_airport("AAA") == Airport.AAA
+
+
+class TestResolveAirports:
+ """Tests for the comma-separated ``resolve_airports`` helper."""
+
+ def test_single_and_multiple_codes(self):
+ """Codes resolve in order, tolerating whitespace and case."""
+ assert resolve_airports("JFK") == [Airport.JFK]
+ assert resolve_airports(" jfk , LGA ") == [Airport.JFK, Airport.LGA]
+
+ @pytest.mark.parametrize("blank", ["", ",", ",,,", " ", " , "])
+ def test_only_separators_raises_parse_error(self, blank):
+ """Input with no real codes raises ParseError rather than returning []."""
+ with pytest.raises(ParseError, match="No valid airport codes"):
+ resolve_airports(blank)
+
+ def test_unknown_code_in_list_raises(self):
+ """One bad code fails the whole list."""
+ with pytest.raises(ParseError, match="NOTREAL"):
+ resolve_airports("JFK,NOTREAL")