Google Flights MCP, CLI and Python Library
feat: expose top_n for round-trip searches on the CLI and MCP tools (#250)
Punit Arani901d23d9b8cd
diff --git a/CLAUDE.md b/CLAUDE.mdindex bbde06c..1b13d7c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -197,6 +197,11 @@ Search for flights on a specific date.- `airlines` / `exclude_airlines` - Include / exclude airline IATA codes- `alliance` / `exclude_alliance` - Include / exclude ONEWORLD / SKYTEAM / STAR_ALLIANCE- `min_layover` / `max_layover` - Layover duration bounds in minutes+- `top_n` - Round-trip only: outbound options expanded into return-flight+ combinations (default 5, 1-10). Cost is `1 + top_n` page fetches. Round-trip+ results all from one airline? Raise `top_n` (or `sort_by` differently) — the+ default sort only ever expands the cheapest `top_n` outbounds, which are+ often the same carrier (issue #142). Ignored for one-way searches.- `currency` / `language` / `country` - Google `curr=` / `hl=` / `gl=` URL params- `sort_by` - CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME- `passengers` - Number of adult passengers (default 1)@@ -249,9 +254,9 @@ options — each with a clickable `booking_url` and `google_click_url`.- `cabin_class`, `max_stops`, `passengers`, `children`, `infants_in_seat`,`infants_on_lap`, `airlines`, `exclude_basic_economy` - Same as `search_flights`- `departure_window`, `sort_by`, `exclude_airlines`, `alliance`, `exclude_alliance`,- `min_layover`, `max_layover`, `emissions`, `checked_bags`, `carry_on` - Same as- `search_flights`. Pass the **same filters used for `search_flights`** so the- re-run search reproduces the same result set; otherwise (especially when+ `min_layover`, `max_layover`, `top_n`, `emissions`, `checked_bags`, `carry_on` - Same as+ `search_flights`. Pass the **same filters used for `search_flights`** (including+ `top_n`) so the re-run search reproduces the same result set; otherwise (especially when`flight_numbers` is omitted) the priced "top result" may differ from what theuser saw.- `currency`, `language`, `country` - Same locale knobs as `search_flights`diff --git a/README.md b/README.mdindex 9b671d5..c1b3b8f 100644--- a/README.md+++ b/README.md@@ -70,6 +70,7 @@ The MCP server provides two main tools:| `exclude_alliance` | list | Alliance names to **exclude** from results || `min_layover` | int | Minimum layover duration in minutes (multi-stop only) || `max_layover` | int | Maximum layover duration in minutes (multi-stop only) |+| `top_n` | int | Round-trip only: outbound options expanded into return flights (default 5, 1-10) || `currency` | string | ISO 4217 code (e.g. 'EUR', 'JPY') — flows to `curr=` param || `language` | string | BCP-47 language code (e.g. 'en-GB') — flows to `hl=` param || `country` | string | ISO 3166-1 alpha-2 country code (e.g. 'GB') for `gl=` param |@@ -81,6 +82,11 @@ The MCP server provides two main tools:> Total travelers (`passengers + children + infants_in_seat + infants_on_lap`) must be> between 1 and 9, and `infants_on_lap` cannot exceed `passengers`.+>+> A round trip costs `1 + top_n` page fetches (one outbound search, plus one per+> outbound candidate expanded into return flights), so `top_n` is capped at 10. Round-trip+> results all from one airline? Raise `top_n`, or sort differently — the default sort only+> ever expands the cheapest `top_n` outbounds, which are often the same carrier.#### `search_dates` Parameters@@ -237,6 +243,10 @@ fli flights JFK LHR 2026-10-25 \--max-layover 360 \--currency EUR --language en-GB --country GB+# Round trip: raise --top-n to see more airlines (default 5, max 10, costs 1 + top_n+# page fetches per search)+fli flights JFK LHR 2026-10-25 --return 2026-11-01 --top-n 8+# Family mix: 2 adults, 1 child, 1 lap infant (total must be 1-9)fli flights JFK LHR 2026-10-25 --passengers 2 --children 1 --infants-on-lap 1```@@ -299,6 +309,7 @@ fli multi \| `--exclude-alliance` | Alliance(s) to **exclude** | `STAR_ALLIANCE` || `--min-layover` | Minimum layover (minutes) | `90` || `--max-layover` | Maximum layover (minutes) | `360` |+| `--top-n` | Round-trip only: outbound options expanded into return flights (default 5, 1-10) | `8` || `--currency` | ISO 4217 currency code | `EUR`, `JPY` || `--language` | BCP-47 language code (Google `hl=`) | `en-GB` || `--country` | ISO 3166-1 alpha-2 country (`gl=`) | `GB` |@@ -312,6 +323,11 @@ fli multi \| `--format` | Output format | `text`, `json` |> Total passengers (adults + children + infants) must be between 1 and 9.+>+> `--top-n` only applies to round trips (it is rejected if set on a one-way search) and+> costs `1 + top_n` page fetches. Round-trip results all from one airline? Raise `--top-n`+> (up to 10), or `--sort` differently — the default sort only expands the cheapest+> `top_n` outbounds, which are often the same carrier.#### Dates Command (`fli dates`)diff --git a/docs/guides/mcp.md b/docs/guides/mcp.mdindex 3e52cba..ef8908b 100644--- a/docs/guides/mcp.md+++ b/docs/guides/mcp.md@@ -85,6 +85,7 @@ Search for flights between two airports on a specific date.| `exclude_alliance` | list | No | null | Alliance(s) to **exclude** from results || `min_layover` | int | No | null | Minimum layover duration (minutes) || `max_layover` | int | No | null | Maximum layover duration (minutes) |+| `top_n` | int | No | 5 | Round-trip only: outbound options expanded into return-flight combinations (1-10) || `currency` | string | No | null | ISO 4217 code (`curr=`) — e.g. 'EUR', 'JPY' || `language` | string | No | null | BCP-47 language code (`hl=`) — e.g. 'en-GB' || `country` | string | No | null | ISO 3166-1 alpha-2 code (`gl=`) — e.g. 'GB' |@@ -99,6 +100,12 @@ Search for flights between two airports on a specific date.> `passengers` — Google Flights' own booking limits. An invalid mix returns> `success: false` with the specific problem (e.g. `"Total passengers must be> between 1 and 9 (got 10: ...)"`), not a generic error.+>+> **`top_n` cost model:** a round trip costs `1 + top_n` page fetches (one outbound+> search, plus one per outbound candidate expanded into return flights) — `top_n` is+> capped at 10 for that reason. Round-trip results all from one airline? Raise `top_n`,+> or `sort_by` differently: the default sort only ever expands the cheapest `top_n`+> outbounds, which are often the same carrier. `top_n` is ignored for one-way searches.**Example Response:**@@ -233,6 +240,7 @@ find out where (and at what price) a specific flight can be booked.| `exclude_airlines` | list | No | null | Airline IATA codes to **exclude** || `alliance` / `exclude_alliance` | list | No | null | Restrict / exclude ONEWORLD, SKYTEAM, STAR_ALLIANCE || `min_layover` / `max_layover` | int | No | null | Layover duration bounds (minutes) |+| `top_n` | int | No | 5 | Round-trip only: outbound options the re-run search expands into return-flight combinations (1-10) || `emissions` | string | No | ALL | ALL or LESS. **Currently ignored by the search transport** (logged as a warning). || `checked_bags` | int | No | 0 | Checked bags included in price (0–2). **Currently ignored by the search transport** (logged as a warning). || `carry_on` | bool | No | false | Include carry-on bag fee in price. **Currently ignored by the search transport** (logged as a warning). |@@ -240,10 +248,10 @@ find out where (and at what price) a specific flight can be booked.| `language` | string | No | null | BCP-47 language code (`hl=`) || `country` | string | No | null | ISO 3166-1 alpha-2 country (`gl=`) |-> **Tip:** Pass the **same filters you used for `search_flights`** so the re-run-> search reproduces the same result set. Otherwise — especially when-> `flight_numbers` is omitted — the priced "top result" may differ from the one-> the user saw.+> **Tip:** Pass the **same filters you used for `search_flights`** — including+> `top_n` — so the re-run search reproduces the same result set. Otherwise — especially+> when `flight_numbers` is omitted — the priced "top result" may differ from the one the+> user saw, and a flight only visible at a higher `top_n` may not be found at all.**Example Response:**diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.pyindex 7535c94..54224be 100644--- a/fli/cli/commands/flights.py+++ b/fli/cli/commands/flights.py@@ -37,6 +37,7 @@ from fli.models import (FlightSearchFilters,LayoverRestrictions,PassengerInfo,+ TripType,)from fli.search import SearchClientError, SearchFlights@@ -70,6 +71,7 @@ def _search_flights_core(children: int = 0,infants_in_seat: int = 0,infants_on_lap: int = 0,+ top_n: int | None = None,) -> None:"""Core flight search functionality."""query: dict[str, Any] = {@@ -140,6 +142,26 @@ def _search_flights_core(time_restrictions=time_restrictions,)+ # `--top-n` only matters once there is a return leg to expand into —+ # it controls how many outbound candidates get chased into+ # GetShoppingResults calls for the return flight (see+ # SearchFlights.search / _expand_multi_leg). Left at its Typer+ # default of None, it silently resolves to the library default (5)+ # for both trip types. Set explicitly on a one-way search, it can+ # never take effect, so we reject it instead of silently ignoring a+ # flag the caller thought was doing something.+ if trip_type == TripType.ONE_WAY:+ if top_n is not None:+ raise ValueError(+ "--top-n only applies to round-trip searches (it controls how many "+ "outbound options are expanded into return flights); remove it for "+ "a one-way search."+ )+ effective_top_n = 5+ else:+ effective_top_n = top_n if top_n is not None else 5+ query["top_n"] = effective_top_n+# Shareable Google Flights deep link for this search.booking_url = google_flights_url(origin_airports[0].name.lstrip("_"),@@ -195,6 +217,7 @@ def _search_flights_core(search_client = SearchFlights()results = search_client.search(filters,+ top_n=effective_top_n,currency=currency,language=language,country=country,@@ -557,6 +580,19 @@ def flights(min=0,),] = 0,+ top_n: Annotated[+ int | None,+ typer.Option(+ "--top-n",+ help=(+ "Round-trip only: number of outbound options to expand into return-flight "+ "combinations (default 5, 1-10). Cost is 1 + top_n page fetches. Results "+ "all from one airline? Raise this to see more carriers, or change --sort. "+ "Rejected if set on a one-way search."+ ),+ show_default=False,+ ),+ ] = None,):"""Search for flights on a specific date.@@ -573,6 +609,7 @@ def flights(fli flights BUF ATH 2026-10-25 --min-layover 120fli flights JFK LHR 2026-10-25 --passengers 2fli flights JFK LHR 2026-10-25 --passengers 2 --children 1 --infants-on-lap 1+ fli flights JFK LHR 2026-10-25 --return 2026-11-01 --top-n 8"""_search_flights_core(@@ -604,4 +641,5 @@ def flights(children=children,infants_in_seat=infants_in_seat,infants_on_lap=infants_on_lap,+ top_n=top_n,)diff --git a/fli/mcp/server.py b/fli/mcp/server.pyindex b4018a6..8a93728 100755--- a/fli/mcp/server.py+++ b/fli/mcp/server.py@@ -220,6 +220,17 @@ class FlightSearchParams(BaseModel):ge=1,description="Maximum layover duration in minutes (multi-stop trips only).",)+ top_n: int = Field(+ 5,+ description=(+ "Round-trip only: number of outbound options to expand into return-flight "+ "combinations. Cost is `1 + top_n` page fetches (one outbound search plus one "+ "per expanded candidate). The default sort expands only the cheapest `top_n` "+ "outbounds, which are often all the same airline — raise top_n (max 10) to see "+ "more carriers on a round trip, at the cost of more requests. Ignored for "+ "one-way searches."+ ),+ )class DateSearchParams(BaseModel):@@ -697,6 +708,7 @@ def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:search_client = SearchFlights()flights = search_client.search(filters,+ top_n=params.top_n,currency=currency,language=params.language,country=params.country,@@ -781,7 +793,10 @@ def _execute_booking_options(selects the itinerary identified by ``flight_numbers`` (or the topresult when omitted), then calls:meth:`fli.search.SearchFlights.get_booking_options` and serializes the- vendor list — each carrying a direct ``booking_url``.+ vendor list — each carrying a direct ``booking_url``. ``params.top_n``+ is forwarded to the re-run search so a round-trip itinerary that was+ only discoverable with a raised ``top_n`` (see :func:`search_flights`)+ can still be matched here."""try:filters, trip_type, origins, destinations = _build_flight_filters(params)@@ -790,6 +805,7 @@ def _execute_booking_options(search_client = SearchFlights()flights = search_client.search(filters,+ top_n=params.top_n,currency=currency,language=params.language,country=params.country,@@ -1138,6 +1154,20 @@ def search_flights(int | None,Field(description="Maximum layover duration in minutes.", ge=1),] = None,+ top_n: Annotated[+ int,+ Field(+ description=(+ "Round-trip only: number of outbound options to expand into return-flight "+ "combinations. Cost is `1 + top_n` page fetches. Round-trip results all "+ "from one airline? Raise top_n to see more carriers (max 10) — the default "+ "sort otherwise only expands the cheapest 5 outbounds, which are often the "+ "same carrier. Ignored for one-way searches."+ ),+ ge=1,+ le=10,+ ),+ ] = 5,) -> dict[str, Any]:"""Search for flights between two airports on a specific date.@@ -1175,6 +1205,7 @@ def search_flights(language=language,country=country,exclude_airlines=exclude_airlines,+ top_n=top_n,alliance=alliance,exclude_alliance=exclude_alliance,min_layover=min_layover,@@ -1466,6 +1497,20 @@ def get_booking_options(bool,Field(description=f"Include carry-on bag fee in displayed price. {_IGNORED_BY_TRANSPORT}"),] = False,+ top_n: Annotated[+ int,+ Field(+ description=(+ "Round-trip only: number of outbound options the re-run search expands "+ "into return-flight combinations — pass the same value used for the "+ "search_flights call that found this itinerary, or a flight found with a "+ "higher top_n may not be reproduced here. Cost is `1 + top_n` page fetches. "+ "Ignored for one-way searches."+ ),+ ge=1,+ le=10,+ ),+ ] = 5,) -> dict[str, Any]:"""Get bookable fares (vendor names, prices, and direct booking URLs) for a flight.@@ -1476,11 +1521,13 @@ def get_booking_options(flight numbers, then call this tool to retrieve where and at what priceit can be booked.- Pass the same filters (``sort_by``, ``departure_window``,+ Pass the same filters (``sort_by``, ``departure_window``, ``top_n``,``exclude_airlines``, ``alliance``, layover/bags/emissions, …) that wereused for ``search_flights`` so the re-run search reproduces the same resultset — otherwise, when ``flight_numbers`` is omitted, the priced "top- result" may differ from the one the user saw.+ result" may differ from the one the user saw, and a flight found only+ because ``search_flights`` was called with a higher ``top_n`` may not be+ found at all.On failure (``success: false``, including "no flight matchedflight_numbers"), the response also carries ``error_type`` (e.g.@@ -1518,6 +1565,7 @@ def get_booking_options(exclude_alliance=exclude_alliance,min_layover=min_layover,max_layover=max_layover,+ top_n=top_n,)return _execute_booking_options(params, flight_numbers)diff --git a/fli/search/flights.py b/fli/search/flights.pyindex dbeed1b..b7d1c52 100644--- a/fli/search/flights.py+++ b/fli/search/flights.py@@ -133,7 +133,14 @@ class SearchFlights:Args:filters: Full search descriptor (airports, dates, preferences).top_n: Number of outbound options to expand when chasing a- round-trip or multi-city itinerary.+ round-trip or multi-city itinerary. Must be between 1 and+ 10 (inclusive). A round trip costs ``1 + top_n`` page+ fetches — one for the outbound search plus one per+ candidate expanded into return flights — so raising it+ surfaces more airlines (the default sort otherwise expands+ only the cheapest ``top_n`` outbounds, which are often all+ from the same carrier) at the cost of more requests.+ Ignored for one-way searches.currency: Optional ISO 4217 currency code (``curr`` URL param).language: Optional BCP-47 language code (``hl`` URL param).country: Optional ISO 3166-1 alpha-2 country code (``gl`` URL param).@@ -145,9 +152,20 @@ class SearchFlights:when no results.Raises:+ ValueError: ``top_n`` is not an ``int`` (``bool`` included — a+ Python ``int`` subclass, rejected explicitly rather than+ silently treated as ``0``/``1``) or is outside ``1..10``+ inclusive.Exception: HTTP failure or unparseable response."""+ if not isinstance(top_n, int) or isinstance(top_n, bool) or not 1 <= top_n <= 10:+ raise ValueError(+ f"top_n must be an integer between 1 and 10 (inclusive); got {top_n!r} "+ f"({type(top_n).__name__}). It controls how many outbound options a "+ "round-trip search expands into return-flight combinations — cost is "+ "1 + top_n page fetches, hence the cap."+ )flights = self._fetch_flights(filters,currency=currency,diff --git a/tests/cli/test_top_n.py b/tests/cli/test_top_n.pynew file mode 100644index 0000000..2e164ea--- /dev/null+++ b/tests/cli/test_top_n.py@@ -0,0 +1,167 @@+"""CLI parsing tests for ``fli flights --top-n`` (issue #142).++``--top-n`` controls how many outbound options a round-trip search expands+into return-flight combinations; the default sort otherwise only ever+expands the cheapest 5 outbounds, which are often all the same carrier.+It only matters for round trips: left at its Typer default it is silently+ignored on a one-way search, but explicitly set on a one-way search it is a+clear, single-line error.++These tests mock ``SearchFlights`` (via the shared ``mock_search_flights``+fixture) for the "value reaches search()" and "echoed in JSON query"+assertions, and fall back to the *real* ``SearchFlights.search`` (with only+``_fetch_flights`` stubbed, never actually reached) for the bounds-rejection+assertions — the point of those is that the shared+``fli.core.errors.classify_error`` bound-check ``ValueError`` from+``fli/search/flights.py`` is what the CLI's ``--format json`` path surfaces,+not a mocked stand-in that would never raise it.+"""++from __future__ import annotations++import json+from datetime import datetime, timedelta++import pytest+from typer.testing import CliRunner++from fli.cli.main import app+from fli.search.flights import SearchFlights+++def runner() -> CliRunner:+ return CliRunner()+++def _future(days: int) -> str:+ """Return a YYYY-MM-DD date ``days`` from now — never a literal calendar date."""+ return (datetime.now() + timedelta(days=days)).strftime("%Y-%m-%d")+++def _round_trip_args(*extra: str) -> list[str]:+ return [+ "flights",+ "JFK",+ "LHR",+ _future(35),+ "--return",+ _future(42),+ *extra,+ ]+++def _one_way_args(*extra: str) -> list[str]:+ return ["flights", "JFK", "LHR", _future(35), *extra]+++class TestTopNReachesSearch:+ def test_default_top_n_is_5_for_round_trip(self, runner, mock_search_flights, mock_console):+ result = runner.invoke(app, _round_trip_args())+ assert result.exit_code == 0+ _, kwargs = mock_search_flights.search.call_args+ assert kwargs["top_n"] == 5++ def test_explicit_top_n_reaches_search(self, runner, mock_search_flights, mock_console):+ result = runner.invoke(app, _round_trip_args("--top-n", "8"))+ assert result.exit_code == 0+ _, kwargs = mock_search_flights.search.call_args+ assert kwargs["top_n"] == 8++ def test_default_top_n_reaches_search_for_one_way_too(+ self, runner, mock_search_flights, mock_console+ ):+ """Left at its default, top_n is passed through (and ignored downstream)."""+ result = runner.invoke(app, _one_way_args())+ assert result.exit_code == 0+ _, kwargs = mock_search_flights.search.call_args+ assert kwargs["top_n"] == 5+++class TestTopNJsonQueryEcho:+ def test_round_trip_echoes_top_n_in_query(self, runner, mock_search_flights, mock_console):+ result = runner.invoke(app, _round_trip_args("--top-n", "7", "--format", "json"))+ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert payload["query"]["top_n"] == 7++ def test_round_trip_default_top_n_echoed_too(self, runner, mock_search_flights, mock_console):+ result = runner.invoke(app, _round_trip_args("--format", "json"))+ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert payload["query"]["top_n"] == 5++ def test_one_way_omits_top_n_from_query(self, runner, mock_search_flights, mock_console):+ result = runner.invoke(app, _one_way_args("--format", "json"))+ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert "top_n" not in payload["query"]+++class TestTopNOneWayRejection:+ def test_explicit_top_n_on_one_way_is_rejected(self, runner, mock_search_flights, mock_console):+ result = runner.invoke(app, _one_way_args("--top-n", "3"))+ assert result.exit_code == 1+ assert "--top-n" in result.output+ assert "one-way" in result.output+ mock_search_flights.search.assert_not_called()++ def test_explicit_top_n_on_one_way_json_error_is_validation_error(+ self, runner, mock_search_flights, mock_console+ ):+ result = runner.invoke(app, _one_way_args("--top-n", "3", "--format", "json"))+ assert result.exit_code == 1+ payload = json.loads(result.stdout)+ assert payload["success"] is False+ assert payload["error"]["type"] == "validation_error"+ assert payload["error"]["retryable"] is False+ mock_search_flights.search.assert_not_called()++ def test_default_top_n_on_one_way_is_not_rejected(+ self, runner, mock_search_flights, mock_console+ ):+ """Left at its default (not passed on the command line), no rejection."""+ result = runner.invoke(app, _one_way_args())+ assert result.exit_code == 0+ assert "--top-n" not in result.output+ mock_search_flights.search.assert_called_once()+++class TestTopNBoundsRejectedByCli:+ """Bounds are enforced by the real SearchFlights.search() bound-check.++ See fli/search/flights.py, which raises before any network call. Stub+ _fetch_flights to fail the test loudly if that assumption ever breaks,+ instead of the test silently attempting a real network request.+ """++ @pytest.fixture(autouse=True)+ def _guard_against_network(self, monkeypatch):+ def _unexpected_call(*_args, **_kwargs):+ raise AssertionError("_fetch_flights should not be reached for a bad top_n")++ monkeypatch.setattr(SearchFlights, "_fetch_flights", _unexpected_call)++ @pytest.mark.parametrize("bad_top_n", ["0", "11"])+ def test_out_of_range_top_n_is_a_clean_error(self, runner, mock_console, bad_top_n):+ result = runner.invoke(app, _round_trip_args("--top-n", bad_top_n))+ assert result.exit_code == 1+ # Fix round 1 (reviewer I1): assert the specific bound-check wording, not a+ # bare "top_n" substring — the _guard_against_network fixture's own+ # AssertionError message ("_fetch_flights should not be reached for a bad+ # top_n") also contains "top_n", so a loose check here stayed green even+ # with the production bound check fully reverted (see the round-1 report's+ # RED->GREEN evidence for this exact test).+ assert "between 1 and 10" in result.output++ @pytest.mark.parametrize("bad_top_n", ["0", "11"])+ def test_out_of_range_top_n_json_error_is_validation_error(+ self, runner, mock_console, bad_top_n+ ):+ result = runner.invoke(app, _round_trip_args("--top-n", bad_top_n, "--format", "json"))+ assert result.exit_code == 1+ payload = json.loads(result.stdout)+ assert payload["success"] is False+ assert payload["error"]["type"] == "validation_error"+ assert payload["error"]["retryable"] is False+ assert "between 1 and 10" in payload["error"]["message"]diff --git a/tests/core/test_error_type_parity.py b/tests/core/test_error_type_parity.pyindex 1900a56..a047ae8 100644--- a/tests/core/test_error_type_parity.py+++ b/tests/core/test_error_type_parity.py@@ -251,6 +251,52 @@ class TestCliCommandAndMcpToolAgreeOnErrorType:assert "in the past" not in cli_payload["error"]["message"]assert "in the past" not in mcp_result["error"]+ def test_top_n_out_of_range(self, runner):+ """T12 (issue #142): top_n outside 1-10 -> bare ValueError -> validation_error.++ ``SearchFlights.search``'s own bound check (``fli/search/flights.py``)+ raises before any network call, so both the real CLI command and the+ real MCP executor exercise the exact same ``ValueError`` — this is the+ library-level source of truth for the bound, not a CLI- or MCP-only+ check that could drift from it.+ """+ return_date = (datetime.now() + timedelta(days=37)).strftime("%Y-%m-%d")++ cli_result = runner.invoke(+ app,+ [+ "flights",+ "JFK",+ "LHR",+ _FUTURE_DATE,+ "--return",+ return_date,+ "--top-n",+ "11",+ "--format",+ "json",+ ],+ )+ cli_payload = json.loads(cli_result.stdout)++ mcp_result = _execute_flight_search(+ FlightSearchParams(+ origin="JFK",+ destination="LHR",+ departure_date=_FUTURE_DATE,+ return_date=return_date,+ top_n=11,+ )+ )++ assert cli_payload["success"] is False+ assert mcp_result["success"] is False+ assert cli_payload["error"]["type"] == mcp_result["error_type"] == "validation_error"+ assert cli_payload["error"]["retryable"] == mcp_result["retryable"] is False+ # Specific bound wording, not a bare "top_n" substring (fix round 1, I1 audit).+ assert "between 1 and 10" in cli_payload["error"]["message"]+ assert "between 1 and 10" in mcp_result["error"]+def test_invalid_passenger_mix(self, runner):"""1 adult + 2 lap infants (each needs its own adult): pydantic ValidationError."""cli_result = runner.invoke(diff --git a/tests/mcp/test_top_n.py b/tests/mcp/test_top_n.pynew file mode 100644index 0000000..f3341d0--- /dev/null+++ b/tests/mcp/test_top_n.py@@ -0,0 +1,167 @@+"""Tests for the ``top_n`` parameter on the MCP tools (issue #142).++``top_n`` controls how many outbound options a round-trip search expands+into return-flight combinations (``SearchFlights.search`` in+``fli/search/flights.py``); the default sort otherwise only ever expands+the cheapest 5 outbounds, which are often all the same carrier. Cost is+``1 + top_n`` page fetches, which is why it is capped at 10.++Unlike the CLI, the MCP tools do not reject an explicitly-set ``top_n`` on+a one-way search — see the CLI's ``--top-n`` docstring in+``fli/cli/commands/flights.py`` for that UX decision, which is deliberately+CLI-only. ``SearchFlights.search`` itself simply ignores ``top_n`` for+one-way trips (it never reaches the expansion step), so passing it through+unconditionally for MCP callers is enough.++``get_booking_options`` re-runs the search to locate the itinerary it is+about to price; ``top_n`` must reach that re-run search too, or a flight+only discoverable with a raised ``top_n`` could never be matched.+"""++from __future__ import annotations++from datetime import datetime, timedelta++import pytest++from fli.mcp.server import (+ FlightSearchParams,+ _execute_booking_options,+ _execute_flight_search,+)+++def _future(days: int) -> str:+ """Return a YYYY-MM-DD date ``days`` from now — never a literal calendar date."""+ return (datetime.now() + timedelta(days=days)).strftime("%Y-%m-%d")+++def _round_trip_params(**overrides) -> FlightSearchParams:+ fields = {+ "origin": "JFK",+ "destination": "LHR",+ "departure_date": _future(35),+ "return_date": _future(42),+ }+ fields.update(overrides)+ return FlightSearchParams(**fields)+++def _one_way_params(**overrides) -> FlightSearchParams:+ fields = {+ "origin": "JFK",+ "destination": "LHR",+ "departure_date": _future(35),+ }+ fields.update(overrides)+ return FlightSearchParams(**fields)+++def _capturing_stub(calls: list[dict]):+ """Return a ``SearchFlights.search`` stand-in that records its kwargs and no-ops."""++ def _stub(self, filters, **kwargs):+ calls.append(kwargs)+ return None++ return _stub+++class TestTopNDefaultsAndForwarding:+ def test_default_top_n_is_5(self):+ assert (+ FlightSearchParams(origin="JFK", destination="LHR", departure_date=_future(35)).top_n+ == 5+ )++ def test_round_trip_forwards_top_n_to_search(self, monkeypatch):+ calls: list[dict] = []+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", _capturing_stub(calls))++ _execute_flight_search(_round_trip_params(top_n=8))++ assert calls, "SearchFlights.search was not called"+ assert calls[-1]["top_n"] == 8++ def test_round_trip_default_top_n_forwarded_too(self, monkeypatch):+ calls: list[dict] = []+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", _capturing_stub(calls))++ _execute_flight_search(_round_trip_params())++ assert calls[-1]["top_n"] == 5++ def test_one_way_top_n_still_forwarded_and_causes_no_error(self, monkeypatch):+ """MCP does not reject an explicit top_n on a one-way search (unlike the CLI)."""+ calls: list[dict] = []+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", _capturing_stub(calls))++ result = _execute_flight_search(_one_way_params(top_n=9))++ assert result["success"] is True+ assert calls[-1]["top_n"] == 9+++class TestTopNForwardedToBookingOptionsRerunSearch:+ """get_booking_options re-runs the search; the same top_n must reach it."""++ def test_top_n_reaches_the_rerun_search(self, monkeypatch):+ calls: list[dict] = []+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", _capturing_stub(calls))++ _execute_booking_options(_round_trip_params(top_n=10), flight_numbers=None)++ assert calls, "SearchFlights.search was not called"+ assert calls[-1]["top_n"] == 10++ def test_default_top_n_reaches_the_rerun_search(self, monkeypatch):+ calls: list[dict] = []+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", _capturing_stub(calls))++ _execute_booking_options(_round_trip_params(), flight_numbers=None)++ assert calls[-1]["top_n"] == 5+++class TestTopNBoundsRejectedByMcpTools:+ """Out-of-range top_n surfaces as error_type: validation_error.++ Uses the real ``SearchFlights.search`` (not a mock) so the assertion+ actually exercises the library's own bound-check ``ValueError`` — see+ ``fli/search/flights.py`` — flowing through the shared+ ``fli.core.errors.classify_error``, the same path the CLI's+ ``--format json`` output goes through.++ Fix round 1 (reviewer audit of I1's loose-substring pattern): the bound+ check raising before ``_fetch_flights`` is reached is exactly the+ behavior under test, not a safe assumption to lean on for test hygiene —+ an autouse guard makes a reverted bound check fail loudly here instead+ of silently making a real network call. The message assertions check+ the specific bound wording ("between 1 and 10"), not a bare "top_n"+ substring the guard's own AssertionError could also satisfy.+ """++ @pytest.fixture(autouse=True)+ def _guard_against_network(self, monkeypatch):+ def _unexpected_call(*_args, **_kwargs):+ raise AssertionError("_fetch_flights should not be reached for a bad top_n")++ monkeypatch.setattr("fli.mcp.server.SearchFlights._fetch_flights", _unexpected_call)++ @pytest.mark.parametrize("bad_top_n", [0, 11])+ def test_search_flights_rejects_out_of_range_top_n(self, bad_top_n):+ result = _execute_flight_search(_round_trip_params(top_n=bad_top_n))++ assert result["success"] is False+ assert result["error_type"] == "validation_error"+ assert result["retryable"] is False+ assert "between 1 and 10" in result["error"]++ @pytest.mark.parametrize("bad_top_n", [0, 11])+ def test_get_booking_options_rejects_out_of_range_top_n(self, bad_top_n):+ result = _execute_booking_options(_round_trip_params(top_n=bad_top_n), flight_numbers=None)++ assert result["success"] is False+ assert result["error_type"] == "validation_error"+ assert result["retryable"] is False+ assert "between 1 and 10" in result["error"]diff --git a/tests/search/test_top_n.py b/tests/search/test_top_n.pynew file mode 100644index 0000000..65a47d8--- /dev/null+++ b/tests/search/test_top_n.py@@ -0,0 +1,245 @@+"""Tests for the ``top_n`` parameter on :meth:`SearchFlights.search` (issue #142).++Round-trip results "all come from a single airline" because the outbound+options are fetched once, sorted, and only the first ``top_n`` of them are+expanded into return-flight combinations (``_expand_multi_leg`` in+``fli/search/flights.py``). With the default sort that's usually five+outbounds from the same cheap carrier. ``top_n`` was already a library+parameter; these tests pin its contract now that it is also exposed on the+CLI and MCP tools:++* bounds (``1..10`` inclusive) are enforced with a clear ``ValueError``,+ raised before any network call;+* a round trip costs exactly ``1 + top_n`` page fetches — one outbound+ ``GetShoppingResults`` call plus one per expanded candidate;+* one-way searches never expand, regardless of ``top_n``.++Follows the existing mocking convention from ``tests/search/test_expand_multi_leg.py``:+``SearchFlights._fetch_flights`` is patched so no real HTTP call is made.+"""++from __future__ import annotations++import threading+from datetime import datetime, timedelta+from unittest.mock import patch++import pytest++from fli.models import (+ Airline,+ Airport,+ FlightLeg,+ FlightResult,+ FlightSearchFilters,+ FlightSegment,+ PassengerInfo,+ TripType,+)+from fli.search.flights import SearchFlights+++def _future(days: int) -> str:+ """Return a YYYY-MM-DD date ``days`` from now — never a literal calendar date."""+ return (datetime.now() + timedelta(days=days)).strftime("%Y-%m-%d")+++def _result(dep: Airport, arr: Airport, hour: int = 9) -> FlightResult:+ # hour stays well under 24 for every caller below (max 6 + 9 = 15), so a+ # plain ``hour + 3`` arrival never needs to roll over into the next day.+ # Relative to "now" (fix round 1, I3) — this is leg metadata for a+ # fabricated FlightResult, not a search filter's travel_date, but the+ # file's own rule (never a literal calendar date) still applies to it.+ departure = (datetime.now() + timedelta(days=35)).replace(+ hour=hour, minute=0, second=0, microsecond=0+ )+ return FlightResult(+ legs=[+ FlightLeg(+ airline=Airline.AA,+ flight_number="100",+ departure_airport=dep,+ arrival_airport=arr,+ departure_datetime=departure,+ arrival_datetime=departure + timedelta(hours=3),+ duration=180,+ )+ ],+ price=300,+ currency="USD",+ duration=180,+ stops=0,+ )+++def _round_trip_filters() -> FlightSearchFilters:+ return FlightSearchFilters(+ trip_type=TripType.ROUND_TRIP,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LHR, 0]],+ travel_date=_future(35),+ ),+ FlightSegment(+ departure_airport=[[Airport.LHR, 0]],+ arrival_airport=[[Airport.JFK, 0]],+ travel_date=_future(42),+ ),+ ],+ )+++def _one_way_filters() -> FlightSearchFilters:+ return FlightSearchFilters(+ trip_type=TripType.ONE_WAY,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.LHR, 0]],+ travel_date=_future(35),+ ),+ ],+ )+++class TestTopNBoundsValidation:+ """1 <= top_n <= 10 — a clear ValueError, raised before any network call."""++ @pytest.mark.parametrize("bad_top_n", [0, -1, 11, 100])+ def test_out_of_range_raises_value_error(self, bad_top_n):+ client = SearchFlights()+ with pytest.raises(ValueError, match="top_n"):+ client.search(_round_trip_filters(), top_n=bad_top_n)++ @pytest.mark.parametrize("good_top_n", [1, 5, 10])+ def test_boundary_values_do_not_raise_for_the_bound_check(self, good_top_n, monkeypatch):+ """1 and 10 are valid boundaries — the bound check itself must let them through."""+ client = SearchFlights()+ monkeypatch.setattr(SearchFlights, "_fetch_flights", lambda self, *a, **k: None)+ # None outbound flights short-circuits to None *after* the bound check —+ # reaching that path (instead of the ValueError) proves 1 and 10 passed.+ assert client.search(_round_trip_filters(), top_n=good_top_n) is None++ @pytest.mark.parametrize("bad_top_n", [0, 11])+ def test_out_of_range_never_reaches_the_network(self, bad_top_n, monkeypatch):+ """The bound check must short-circuit before _fetch_flights is ever called."""+ client = SearchFlights()++ def _unexpected_call(*_args, **_kwargs):+ raise AssertionError("_fetch_flights should not be called for an out-of-range top_n")++ monkeypatch.setattr(SearchFlights, "_fetch_flights", _unexpected_call)+ with pytest.raises(ValueError):+ client.search(_round_trip_filters(), top_n=bad_top_n)+++class TestTopNTypeValidation:+ """Fix round 1, C1/I2: non-int top_n (and bool) must raise ValueError, not TypeError.++ A bare ``if not 1 <= top_n <= 10:`` comparison against a non-comparable+ type (``"5"``, ``None``) raises ``TypeError`` from Python itself, which+ ``classify_error()`` does NOT map to ``validation_error`` (it only+ matches ``ValidationError | ValueError``) — so it would have surfaced as+ ``unexpected_error`` instead. ``bool`` is an ``int`` subclass in Python+ (``True == 1``), so it silently passed the old bound check too; the+ ruling for this fix is to reject it explicitly rather than accept it as+ 1.+ """++ @pytest.mark.parametrize("bad_top_n", ["5", 5.0, None, True, False])+ def test_non_int_or_bool_raises_value_error_not_type_error(self, bad_top_n):+ client = SearchFlights()+ with pytest.raises(ValueError, match="top_n"):+ client.search(_round_trip_filters(), top_n=bad_top_n)++ @pytest.mark.parametrize("bad_top_n", ["5", 5.0, None, True, False])+ def test_non_int_or_bool_never_reaches_the_network(self, bad_top_n, monkeypatch):+ client = SearchFlights()++ def _unexpected_call(*_args, **_kwargs):+ raise AssertionError("_fetch_flights should not be called for a non-int/bool top_n")++ monkeypatch.setattr(SearchFlights, "_fetch_flights", _unexpected_call)+ with pytest.raises(ValueError):+ client.search(_round_trip_filters(), top_n=bad_top_n)++ @pytest.mark.parametrize("good_top_n", [1, 10])+ def test_valid_edge_ints_still_pass(self, good_top_n, monkeypatch):+ """1 and 10 are valid int boundaries — must not be caught by the new type check."""+ client = SearchFlights()+ monkeypatch.setattr(SearchFlights, "_fetch_flights", lambda self, *a, **k: None)+ assert client.search(_round_trip_filters(), top_n=good_top_n) is None+++class TestTopNFetchCount:+ """A round trip costs exactly 1 + top_n page fetches."""++ @pytest.mark.parametrize("top_n", [1, 5, 10])+ def test_fetch_count_is_one_plus_top_n(self, top_n):+ client = SearchFlights()+ # Exactly top_n outbound candidates so every one of them gets expanded+ # (top_n candidates fed into a top_n cap == top_n expansions, never fewer).+ outbound_candidates = [_result(Airport.JFK, Airport.LHR, hour=6 + i) for i in range(top_n)]++ lock = threading.Lock()+ state = {"n": 0}++ def _fake_fetch(filters, **kwargs):+ with lock:+ state["n"] += 1+ call_index = state["n"]+ if call_index == 1:+ return outbound_candidates+ return [_result(Airport.LHR, Airport.JFK, hour=6)]++ with patch.object(SearchFlights, "_fetch_flights", side_effect=_fake_fetch):+ results = client.search(_round_trip_filters(), top_n=top_n)++ assert state["n"] == 1 + top_n+ assert results is not None+ assert len(results) == top_n++ def test_more_outbound_candidates_than_top_n_still_costs_one_plus_top_n(self):+ """Cost model holds even when Google returns more outbounds than top_n."""+ top_n = 3+ client = SearchFlights()+ outbound_candidates = [_result(Airport.JFK, Airport.LHR, hour=6 + i) for i in range(10)]++ lock = threading.Lock()+ state = {"n": 0}++ def _fake_fetch(filters, **kwargs):+ with lock:+ state["n"] += 1+ call_index = state["n"]+ if call_index == 1:+ return outbound_candidates+ return [_result(Airport.LHR, Airport.JFK, hour=6)]++ with patch.object(SearchFlights, "_fetch_flights", side_effect=_fake_fetch):+ client.search(_round_trip_filters(), top_n=top_n)++ assert state["n"] == 1 + top_n+++class TestTopNOneWayIgnored:+ """top_n only matters once there is a return leg to expand into."""++ def test_one_way_never_expands_regardless_of_top_n(self):+ client = SearchFlights()+ outbound = [_result(Airport.JFK, Airport.LHR)]++ with patch.object(SearchFlights, "_fetch_flights", return_value=outbound) as mocked_fetch:+ results = client.search(_one_way_filters(), top_n=9)++ # Only the single outbound fetch — no expansion calls at all.+ mocked_fetch.assert_called_once()+ assert results == outbound++ def test_one_way_default_top_n_produces_no_error(self):+ client = SearchFlights()+ with patch.object(SearchFlights, "_fetch_flights", return_value=None):+ assert client.search(_one_way_filters()) is None