Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

feat: add per-flight booking deep-link URLs via tfs+tfu protobuf encoding (#190)

Punit Aranidaf9e9a76454
diff --git a/CLAUDE.md b/CLAUDE.md
index 07db516..11eea74 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -73,8 +73,9 @@ uv run mkdocs build # Build static docs
- All models use Pydantic for validation
5. **MCP Server** (`fli/mcp/`)
- - FastMCP-based server with two tools: `search_flights` and `search_dates`
+ - FastMCP-based server with four tools: `search_flights`, `search_dates`, `get_booking_options`, `find_airports`
- Industry-standard parameter naming: `origin`, `destination`, `cabin_class`, `max_stops`
+ - Per-flight booking deep-link URLs (`tfs` protobuf) in every search result
- Prompt templates for guided searches
- Configuration via environment variables
@@ -120,6 +121,14 @@ Search for flights on a specific date.
- `currency` / `language` / `country` - Google `curr=` / `hl=` / `gl=` URL params
- `sort_by` - CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME
+**Response:** Each flight in `flights[]` carries its own `booking_url` — a
+`tfs` protobuf deep link that opens the specific itinerary's booking page
+(vendor fares + "Continue" CTA) on Google Flights. The token is deterministic
+(no session id), so the same itinerary always yields the same URL. The
+top-level `booking_url` is a broader search-page link (route + dates
+pre-filled) kept as a reliable fallback. Each flight's `flight_number` can be
+passed to `get_booking_options` for per-vendor pricing.
+
### `search_dates`
Find cheapest travel dates within a range.
@@ -133,6 +142,31 @@ Find cheapest travel dates within a range.
- `currency`, `language`, `country` - Same locale knobs as `search_flights`
- `sort_by_price` - Boolean to sort by price
+**Response:** Each date result carries a `booking_url` deep-linking to Google
+Flights for that specific date (and return date for round trips).
+
+### `get_booking_options`
+Get bookable fares (vendor names, prices, and direct booking URLs) for a
+single itinerary. Runs a fresh search, selects the flight identified by
+`flight_numbers` (or the top result when omitted), then calls
+`SearchFlights.get_booking_options` and returns the airline-direct and OTA
+options — each with a clickable `booking_url` and `google_click_url`.
+
+**Key Parameters:**
+- `origin` / `destination` / `departure_date` / `return_date` - Same as `search_flights`
+- `flight_numbers` - Ordered flight numbers identifying the itinerary, taken
+ from a prior `search_flights` result (e.g. `['BA178']` one-way,
+ `['AA100', 'AA200']` round-trip). Accepts bare (`'178'`) or airline-prefixed
+ (`'BA178'`) forms. Omit to price the top result.
+- `cabin_class`, `max_stops`, `passengers`, `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
+ `flight_numbers` is omitted) the priced "top result" may differ from what the
+ user saw.
+- `currency`, `language`, `country` - Same locale knobs as `search_flights`
+
### Note on emissions
Both tools accept the `emissions` filter (forwarded to Google's
"less emissions" toggle as `LESS`), but raw CO₂ figures are intentionally
diff --git a/docs/guides/mcp.md b/docs/guides/mcp.md
index 5f75742..a6c85d9 100644
--- a/docs/guides/mcp.md
+++ b/docs/guides/mcp.md
@@ -104,16 +104,25 @@ Search for flights between two airports on a specific date.
"arrival_time": "2026-03-16T06:30:00",
"duration": 450,
"airline": "BA",
- "flight_number": "BA178"
+ "flight_number": "178"
}
- ]
+ ],
+ "booking_url": "https://www.google.com/travel/flights/booking?tfs=CBwQAh..."
}
],
"count": 5,
- "trip_type": "ONE_WAY"
+ "trip_type": "ONE_WAY",
+ "booking_url": "https://www.google.com/travel/flights?q=Flights%20from%20JFK%20to%20LHR%20on%202026-03-15"
}
```
+Each flight in `flights[]` carries a `booking_url` that deep-links directly to
+that specific flight's booking page on Google Flights (pre-loaded itinerary, no
+search step required). The top-level `booking_url` is a broader search-page
+link (route + date pre-filled) and is a reliable fallback. To retrieve
+per-vendor prices and airline-direct booking links, pass the flight's
+`flight_number` (e.g. `BA178`) to [`get_booking_options`](#get_booking_options).
+
### `search_dates`
Find the cheapest travel dates between two airports within a date range.
@@ -153,13 +162,15 @@ Find the cheapest travel dates between two airports within a date range.
"date": "2026-03-15",
"price": 350.00,
"currency": "USD",
- "return_date": null
+ "return_date": null,
+ "booking_url": "https://www.google.com/travel/flights?q=Flights%20from%20JFK%20to%20LHR%20on%202026-03-15"
},
{
"date": "2026-03-18",
"price": 375.00,
"currency": "USD",
- "return_date": null
+ "return_date": null,
+ "booking_url": "https://www.google.com/travel/flights?q=Flights%20from%20JFK%20to%20LHR%20on%202026-03-18"
}
],
"count": 30,
@@ -168,6 +179,92 @@ Find the cheapest travel dates between two airports within a date range.
}
```
+Each date result carries a `booking_url` deep-linking to Google Flights for
+that specific date (and return date for round trips).
+
+### `get_booking_options`
+
+Get bookable fares — vendor names, prices, and **direct booking URLs** — for a
+single itinerary. The tool runs a fresh search, selects the flight identified
+by `flight_numbers` (or the top result when omitted), and returns the
+airline-direct and online-travel-agency options Google surfaces for it.
+
+Use `search_flights` first to discover flight numbers, then call this tool to
+find out where (and at what price) a specific flight can be booked.
+
+**Parameters:**
+
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| `origin` | string | Yes | - | Departure airport IATA code (e.g., 'JFK') |
+| `destination` | string | Yes | - | Arrival airport IATA code (e.g., 'LHR') |
+| `departure_date` | string | Yes | - | Travel date in YYYY-MM-DD format |
+| `flight_numbers` | list | No | null | Ordered flight numbers identifying the itinerary (e.g. `['BA178']`, or `['AA100', 'AA200']` round-trip). Bare (`'178'`) or airline-prefixed (`'BA178'`). Omit to price the top result. |
+| `return_date` | string | No | null | Return date for round trips |
+| `cabin_class` | string | No | ECONOMY | ECONOMY, PREMIUM_ECONOMY, BUSINESS, or FIRST |
+| `max_stops` | string | No | ANY | ANY, NON_STOP, ONE_STOP, or TWO_PLUS_STOPS |
+| `passengers` | int | No | 1 | Number of adult passengers |
+| `airlines` | list | No | null | Filter by airline codes (e.g., ['BA', 'AA']) |
+| `exclude_basic_economy` | bool | No | false | Exclude basic economy fares |
+| `departure_window` | string | No | null | Time window in 'HH-HH' format (e.g., '6-20') |
+| `sort_by` | string | No | CHEAPEST | Sort order — matters when `flight_numbers` is omitted |
+| `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) |
+| `emissions` | string | No | ALL | ALL or LESS |
+| `checked_bags` | int | No | 0 | Checked bags included in price (0–2) |
+| `carry_on` | bool | No | false | Include carry-on bag fee in price |
+| `currency` | string | No | null | ISO 4217 currency code (`curr=`) |
+| `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.
+
+**Example Response:**
+
+```json
+{
+ "success": true,
+ "selected_flight": {
+ "price": 450.00,
+ "currency": "USD",
+ "legs": [{ "airline": "BA", "flight_number": "178", "...": "..." }],
+ "booking_url": "https://www.google.com/travel/flights/booking?tfs=CBwQAh..."
+ },
+ "options": [
+ {
+ "vendor_name": "British Airways",
+ "vendor_code": "BA",
+ "is_airline_direct": true,
+ "price": 450.00,
+ "currency": "USD",
+ "booking_url": "https://www.britishairways.com/...",
+ "google_click_url": "https://www.google.com/..."
+ }
+ ],
+ "count": 1,
+ "booking_url": "https://www.google.com/travel/flights?q=Flights%20from%20JFK%20to%20LHR%20on%202026-03-15"
+}
+```
+
+`selected_flight.booking_url` is a deep link that opens the specific itinerary's
+booking page directly on Google Flights (the `tfs` protobuf URL, no search step
+required). The top-level `booking_url` is a broader search-page link.
+
+When no flight matches `flight_numbers`, the response has `success: false` and
+an `available_flights` list of the flight-number sequences that were found, so
+you can retry with a valid identifier.
+
+!!! note "Vendor fares may be empty"
+ Google's booking endpoint often returns no per-vendor fares without a
+ browser-minted session token. When that happens `options` is `[]` and the
+ response carries a `note` — use `selected_flight.booking_url` to open the
+ specific flight's booking page directly, or fall back to the top-level
+ `booking_url` for the search page.
+
## Available Prompts
The MCP server also provides prompt templates to help guide searches:
diff --git a/fli/cli/commands/dates.py b/fli/cli/commands/dates.py
index 36e2548..a66a6fa 100644
--- a/fli/cli/commands/dates.py
+++ b/fli/cli/commands/dates.py
@@ -376,6 +376,9 @@ def dates(
if sort_by_price:
results.sort(key=lambda x: x.price)
+ origin_code = origin_airport.name.lstrip("_")
+ destination_code = destination_airport.name.lstrip("_")
+
if output_format == OutputFormat.JSON:
emit_json(
build_json_success_response(
@@ -384,7 +387,16 @@ def dates(
query=query,
results_key="dates",
results=[
- serialize_date_result(result, trip_type, default_currency=currency)
+ serialize_date_result(
+ result,
+ trip_type,
+ default_currency=currency,
+ origin=origin_code,
+ destination=destination_code,
+ currency=currency,
+ language=language,
+ country=country,
+ )
for result in results
],
)
@@ -400,7 +412,16 @@ def dates(
typer.echo(message)
raise typer.Exit(1)
- display_date_results(results, trip_type, default_currency=currency)
+ display_date_results(
+ results,
+ trip_type,
+ default_currency=currency,
+ origin=origin_code,
+ destination=destination_code,
+ currency=currency,
+ language=language,
+ country=country,
+ )
except ParseError as e:
if output_format == OutputFormat.JSON:
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
index 57d46c5..a1f995e 100644
--- a/fli/cli/commands/flights.py
+++ b/fli/cli/commands/flights.py
@@ -18,6 +18,7 @@ from fli.cli.utils import (
)
from fli.core import (
build_flight_segments,
+ google_flights_url,
parse_airlines,
parse_alliances,
parse_cabin_class,
@@ -128,6 +129,17 @@ def _search_flights_core(
time_restrictions=time_restrictions,
)
+ # Shareable Google Flights deep link for this search.
+ booking_url = google_flights_url(
+ origin_airport.name.lstrip("_"),
+ destination_airport.name.lstrip("_"),
+ departure_date,
+ return_date,
+ currency=currency,
+ language=language,
+ country=country,
+ )
+
# Parse layover constraints (airports, min duration, max duration).
layover_restrictions = None
layover_airports = [resolve_airport(code) for code in layover] if layover else None
@@ -181,6 +193,7 @@ def _search_flights_core(
query=query,
results_key="flights",
results=[],
+ booking_url=booking_url,
)
)
return
@@ -188,6 +201,14 @@ def _search_flights_core(
typer.echo("No flights found.")
raise typer.Exit(1)
+ # Build per-flight booking deep-links (tfs; never raises).
+ booking_urls = [
+ search_client.build_flight_booking_url(
+ result, currency=currency, language=language, country=country
+ )
+ for result in results
+ ]
+
if output_format == OutputFormat.JSON:
emit_json(
build_json_success_response(
@@ -196,14 +217,21 @@ def _search_flights_core(
query=query,
results_key="flights",
results=[
- serialize_flight_result(result, default_currency=currency)
- for result in results
+ serialize_flight_result(result, default_currency=currency, booking_url=burl)
+ for result, burl in zip(results, booking_urls, strict=False)
],
+ booking_url=booking_url,
)
)
return
- display_flight_results(results, trip_type=trip_type, default_currency=currency)
+ display_flight_results(
+ results,
+ trip_type=trip_type,
+ default_currency=currency,
+ booking_url=booking_url,
+ booking_urls=booking_urls,
+ )
except ParseError as e:
if output_format == OutputFormat.JSON:
diff --git a/fli/cli/utils.py b/fli/cli/utils.py
index 0c1207a..0b0918d 100644
--- a/fli/cli/utils.py
+++ b/fli/cli/utils.py
@@ -15,7 +15,7 @@ from rich.text import Text
from fli.cli.console import console
from fli.cli.enums import DayOfWeek
-from fli.core import format_price, format_price_axis_label
+from fli.core import format_price, format_price_axis_label, google_flights_url
from fli.core.builders import normalize_date
from fli.core.parsers import ParseError
from fli.core.parsers import parse_airlines as core_parse_airlines
@@ -232,7 +232,6 @@ def _serialize_flight_segment_result(
for src in (
"self_transfer",
"mixed_cabin",
- "booking_token",
):
v = getattr(flight, src, None)
if v is not None and v != "":
@@ -253,19 +252,24 @@ def _serialize_flight_segment_result(
def serialize_flight_result(
flight_data: Any,
default_currency: str = "USD",
+ *,
+ booking_url: str | None = None,
) -> dict[str, Any]:
"""Serialize a flight result or round-trip/multi-city tuple for JSON output."""
if not isinstance(flight_data, tuple):
- return _serialize_flight_segment_result(
+ out = _serialize_flight_segment_result(
flight_data, include_price=True, default_currency=default_currency
)
+ if booking_url:
+ out["booking_url"] = booking_url
+ return out
segments = list(flight_data)
if len(segments) == 2:
# Round-trip: Google Flights returns the full RT price on the outbound leg.
outbound, return_flight = segments
- return {
+ out = {
"price": outbound.price,
"currency": outbound.currency or default_currency,
"duration": outbound.duration + return_flight.duration,
@@ -273,32 +277,60 @@ def serialize_flight_result(
"outbound": _serialize_flight_segment_result(outbound),
"return": _serialize_flight_segment_result(return_flight),
}
+ if booking_url:
+ out["booking_url"] = booking_url
+ return out
# Multi-city (3+ legs): combined price is on the final leg.
price_segment = segments[-1]
- return {
+ out = {
"price": price_segment.price,
"currency": price_segment.currency or default_currency,
"duration": sum(s.duration for s in segments),
"stops": sum(s.stops for s in segments),
"segments": [_serialize_flight_segment_result(s) for s in segments],
}
+ if booking_url:
+ out["booking_url"] = booking_url
+ return out
def serialize_date_result(
date_result: Any,
trip_type: TripType,
default_currency: str = "USD",
+ *,
+ origin: str | None = None,
+ destination: str | None = None,
+ currency: str | None = None,
+ language: str | None = None,
+ country: str | None = None,
) -> dict[str, Any]:
- """Serialize a date search result for JSON output."""
+ """Serialize a date search result for JSON output.
+
+ When ``origin`` and ``destination`` are provided, a ``booking_url``
+ deep-linking to Google Flights for that specific date is included.
+ """
+ departure_date = date_result.date[0].date().isoformat()
+ return_date = None
+ if trip_type == TripType.ROUND_TRIP and len(date_result.date) > 1:
+ return_date = date_result.date[1].date().isoformat()
payload = {
- "departure_date": date_result.date[0].date().isoformat(),
- "return_date": None,
+ "departure_date": departure_date,
+ "return_date": return_date,
"price": date_result.price,
"currency": date_result.currency or default_currency,
}
- if trip_type == TripType.ROUND_TRIP and len(date_result.date) > 1:
- payload["return_date"] = date_result.date[1].date().isoformat()
+ if origin and destination:
+ payload["booking_url"] = google_flights_url(
+ origin,
+ destination,
+ departure_date,
+ return_date,
+ currency=currency,
+ language=language,
+ country=country,
+ )
return payload
@@ -309,9 +341,10 @@ def build_json_success_response(
query: dict[str, Any],
results_key: str,
results: list[dict[str, Any]],
+ booking_url: str | None = None,
) -> dict[str, Any]:
"""Build a JSON success payload for CLI commands."""
- return {
+ payload: dict[str, Any] = {
"success": True,
"data_source": "google_flights",
"search_type": search_type,
@@ -320,6 +353,9 @@ def build_json_success_response(
"count": len(results),
results_key: results,
}
+ if booking_url:
+ payload["booking_url"] = booking_url
+ return payload
def build_json_error_response(
@@ -350,7 +386,11 @@ def emit_json(payload: dict[str, Any]) -> None:
def display_flight_results(
- flights: list, trip_type: TripType = TripType.ONE_WAY, default_currency: str = "USD"
+ flights: list,
+ trip_type: TripType = TripType.ONE_WAY,
+ default_currency: str = "USD",
+ booking_url: str | None = None,
+ booking_urls: list[str | None] | None = None,
):
"""Display flight results in a beautiful format.
@@ -359,6 +399,11 @@ def display_flight_results(
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.
+ booking_url: Optional search-level Google Flights deep link shown as a
+ footer so the user can open and browse the full search results.
+ booking_urls: Optional per-flight booking deep-link URLs aligned with
+ ``flights``. When provided, a clickable "Book" row is added to
+ each flight's info table.
"""
if not flights:
@@ -396,6 +441,12 @@ def display_flight_results(
if price_segment.mixed_cabin:
table.add_row("Mixed cabin", "yes")
+ # Per-flight booking deep-link (when available)
+ if booking_urls is not None and i - 1 < len(booking_urls):
+ burl = booking_urls[i - 1]
+ if burl:
+ table.add_row("Book", f"[link={burl}]{burl}[/link]")
+
# Create segments tables for each direction
all_segments = []
for idx, flight in enumerate(flight_segments):
@@ -464,8 +515,29 @@ def display_flight_results(
)
console.print()
+ if booking_url:
+ console.print(
+ Panel(
+ Text(booking_url, style="cyan"),
+ title="[bold]Open on Google Flights[/bold]",
+ border_style="cyan",
+ box=box.ROUNDED,
+ )
+ )
+ console.print()
+
-def display_date_results(dates: list, trip_type: TripType, default_currency: str = "USD"):
+def display_date_results(
+ dates: list,
+ trip_type: TripType,
+ default_currency: str = "USD",
+ *,
+ origin: str | None = None,
+ destination: str | None = None,
+ currency: str | None = None,
+ language: str | None = None,
+ country: str | None = None,
+):
"""Display date search results with sparkline chart and table."""
if not dates:
console.print(Panel("No flights found for these dates", style="red"))
@@ -500,8 +572,37 @@ def display_date_results(dates: list, trip_type: TripType, default_currency: str
console.print() # Add spacing between chart and table
+ # When the route is known, render each departure date as a clickable
+ # Google Flights deep link (rich hyperlink — keeps the table narrow while
+ # still letting the user jump straight to that date's flights).
+ links_enabled = bool(origin and destination)
+
+ def _departure_cell(date_price: Any) -> str:
+ label = date_price.date[0].strftime("%Y-%m-%d")
+ if not links_enabled:
+ return label
+ return_date = (
+ date_price.date[1].date().isoformat()
+ if trip_type == TripType.ROUND_TRIP and len(date_price.date) > 1
+ else None
+ )
+ url = google_flights_url(
+ origin,
+ destination,
+ date_price.date[0].date().isoformat(),
+ return_date,
+ currency=currency,
+ language=language,
+ country=country,
+ )
+ return f"[link={url}]{label}[/link]"
+
# Build the table (using original order, not sorted)
- table = Table(title="Cheapest Dates to Fly", box=box.ROUNDED)
+ table = Table(
+ title="Cheapest Dates to Fly",
+ caption="Departure dates link to Google Flights" if links_enabled else None,
+ box=box.ROUNDED,
+ )
table.add_column("Departure", style="cyan")
table.add_column("Day", style="yellow")
if trip_type == TripType.ROUND_TRIP:
@@ -512,13 +613,13 @@ def display_date_results(dates: list, trip_type: TripType, default_currency: str
for date_price in dates:
if trip_type == TripType.ONE_WAY:
table.add_row(
- date_price.date[0].strftime("%Y-%m-%d"),
+ _departure_cell(date_price),
date_price.date[0].strftime("%A"),
format_price(date_price.price, date_price.currency or default_currency),
)
else:
table.add_row(
- date_price.date[0].strftime("%Y-%m-%d"),
+ _departure_cell(date_price),
date_price.date[0].strftime("%A"),
date_price.date[1].strftime("%Y-%m-%d"),
date_price.date[1].strftime("%A"),
diff --git a/fli/core/__init__.py b/fli/core/__init__.py
index 5309f44..33045c8 100644
--- a/fli/core/__init__.py
+++ b/fli/core/__init__.py
@@ -13,6 +13,7 @@ from .builders import (
normalize_date,
)
from .currency import extract_currency_from_price_token, format_price, format_price_axis_label
+from .links import google_flights_url, with_locale_params
from .parsers import (
parse_airlines,
parse_alliances,
@@ -49,4 +50,7 @@ __all__ = [
"extract_currency_from_price_token",
"format_price",
"format_price_axis_label",
+ # Links
+ "google_flights_url",
+ "with_locale_params",
]
diff --git a/fli/core/links.py b/fli/core/links.py
new file mode 100644
index 0000000..b5bfd2a
--- /dev/null
+++ b/fli/core/links.py
@@ -0,0 +1,75 @@
+"""Shared URL helpers for Google Flights deep links.
+
+Both the CLI and MCP surface a clickable Google Flights link alongside
+search results so a consumer can open the route (and complete a booking)
+in a browser. The natural-language ``q`` form used here is the same one
+Google's own frontend accepts.
+
+``with_locale_params`` lives here (rather than in :mod:`fli.search`) so the
+core layer stays free of any dependency on the search package; the search
+modules re-export it from :mod:`fli.search._urls` for backwards
+compatibility.
+"""
+
+from __future__ import annotations
+
+import urllib.parse
+
+GOOGLE_FLIGHTS_URL = "https://www.google.com/travel/flights"
+
+
+def with_locale_params(
+ url: str,
+ currency: str | None,
+ language: str | None,
+ country: str | None,
+) -> str:
+ """Append optional ``curr``/``hl``/``gl`` parameters to ``url``.
+
+ - ``currency`` is uppercased ("usd" → "USD") because Google rejects
+ lowercase codes silently (still 200, but ignores the override).
+ - ``language`` is passed through verbatim (BCP-47, may contain a hyphen).
+ - ``country`` is uppercased (ISO 3166-1 alpha-2).
+
+ All values are percent-encoded so a caller typo (a stray ``&``, ``+``,
+ or whitespace) can't break the URL — typical inputs like ``en-GB`` are
+ already URL-safe so the encoding is a no-op for them.
+
+ No-op when all three are None — returns the input URL unchanged so
+ callers can pass through without checking.
+ """
+ params: list[str] = []
+ if currency:
+ params.append(f"curr={urllib.parse.quote(currency.upper(), safe='')}")
+ if language:
+ params.append(f"hl={urllib.parse.quote(language, safe='')}")
+ if country:
+ params.append(f"gl={urllib.parse.quote(country.upper(), safe='')}")
+ if not params:
+ return url
+ sep = "&" if "?" in url else "?"
+ return f"{url}{sep}{'&'.join(params)}"
+
+
+def google_flights_url(
+ origin: str,
+ destination: str,
+ departure_date: str,
+ return_date: str | None = None,
+ *,
+ currency: str | None = None,
+ language: str | None = None,
+ country: str | None = None,
+) -> str:
+ """Build a shareable Google Flights deep link for a route and dates.
+
+ ``origin`` and ``destination`` are bare IATA codes (e.g. ``"JFK"``).
+ The returned URL pre-fills the route and outbound date (plus the return
+ date for round trips); locale knobs (``curr``/``hl``/``gl``) are appended
+ when supplied.
+ """
+ query = f"Flights from {origin} to {destination} on {departure_date}"
+ if return_date:
+ query += f" through {return_date}"
+ url = f"{GOOGLE_FLIGHTS_URL}?q={urllib.parse.quote(query)}"
+ return with_locale_params(url, currency, language, country)
diff --git a/fli/mcp/server.py b/fli/mcp/server.py
index ca890e0..a4e286f 100755
--- a/fli/mcp/server.py
+++ b/fli/mcp/server.py
@@ -19,6 +19,7 @@ from fli.core import (
build_date_search_segments,
build_flight_segments,
build_time_restrictions,
+ google_flights_url,
parse_airlines,
parse_alliances,
parse_cabin_class,
@@ -267,6 +268,102 @@ def _airline_code(airline: Any) -> str:
return getattr(airline, "name", str(airline)).lstrip("_")
+def _iata(airport: Any) -> str:
+ """Return the bare IATA code from an ``Airport`` enum or plain string."""
+ return getattr(airport, "name", str(airport)).lstrip("_")
+
+
+def _google_flights_url(
+ origins: list[Airport],
+ destinations: list[Airport],
+ departure_date: str,
+ return_date: str | None,
+ currency: str | None,
+ language: str | None,
+ country: str | None,
+) -> str:
+ """Build a shareable Google Flights deep link for the search.
+
+ Thin wrapper over :func:`fli.core.google_flights_url` that takes the
+ resolved airport lists used internally; the first airport of each side is
+ used when multiple are given, keeping the query unambiguous for Google's
+ parser.
+ """
+ return google_flights_url(
+ _iata(origins[0]),
+ _iata(destinations[0]),
+ departure_date,
+ return_date,
+ currency=currency,
+ language=language,
+ country=country,
+ )
+
+
+def _serialize_booking_option(option: Any) -> dict[str, Any]:
+ """Serialize a single bookable fare to a clean dictionary."""
+ out: dict[str, Any] = {}
+ for key in (
+ "vendor_name",
+ "vendor_code",
+ "fare_name",
+ "currency",
+ "booking_url",
+ "google_click_url",
+ ):
+ value = getattr(option, key, None)
+ if value not in (None, ""):
+ out[key] = value
+ if getattr(option, "price", None) is not None:
+ out["price"] = option.price
+ if getattr(option, "is_airline_direct", False):
+ out["is_airline_direct"] = True
+ return out
+
+
+def _flight_legs(flight: Any) -> list[Any]:
+ """Flatten a result (or round-trip/multi-city tuple) into its legs."""
+ if isinstance(flight, tuple):
+ return [leg for segment in flight for leg in segment.legs]
+ return list(flight.legs)
+
+
+def _leg_identifiers(leg: Any) -> set[str]:
+ """Return the accepted identifier spellings for a leg ('178' and 'BA178')."""
+ number = str(leg.flight_number).upper().replace(" ", "")
+ code = _airline_code(leg.airline).upper()
+ # Strip a leading airline-code prefix if the flight_number already carries
+ # it (e.g. "BA178" -> "178") so the bare and prefixed forms are always both
+ # valid and we never produce a double-prefixed token ("BABA178").
+ bare = number[len(code) :] if code and number.startswith(code) else number
+ return {bare, f"{code}{bare}"}
+
+
+def _match_flight(flights: list[Any], flight_numbers: list[str] | None) -> Any | None:
+ """Pick the result matching ``flight_numbers`` (order-sensitive).
+
+ Each entry is matched against either the bare flight number ('178') or
+ the airline-prefixed form ('BA178'), case-insensitively. When no flight
+ numbers are supplied the first result is returned (the top/cheapest row
+ under the default sort).
+ """
+ if not flight_numbers:
+ return flights[0] if flights else None
+ want = [fn.upper().replace(" ", "") for fn in flight_numbers]
+ for flight in flights:
+ legs = _flight_legs(flight)
+ if len(legs) != len(want):
+ continue
+ if all(token in _leg_identifiers(leg) for token, leg in zip(want, legs, strict=True)):
+ return flight
+ return None
+
+
+def _flight_idents(flight: Any) -> list[str]:
+ """Human-readable airline+number labels for each leg of a result."""
+ return [f"{_airline_code(leg.airline)}{leg.flight_number}" for leg in _flight_legs(flight)]
+
+
def _serialize_flight_leg(leg: Any) -> dict[str, Any]:
"""Serialize a single flight leg to a dictionary."""
out: dict[str, Any] = {
@@ -323,7 +420,6 @@ def _flight_extras(flight: Any) -> dict[str, Any]:
("primary_airline_name", "primary_airline_name"),
("self_transfer", "self_transfer"),
("mixed_cabin", "mixed_cabin"),
- ("booking_token", "booking_token"),
):
v = getattr(flight, src, None)
if v is not None and v != "":
@@ -337,7 +433,12 @@ def _flight_extras(flight: Any) -> dict[str, Any]:
return out
-def _serialize_flight_result(flight: Any, is_round_trip: bool = False) -> dict[str, Any]:
+def _serialize_flight_result(
+ flight: Any,
+ is_round_trip: bool = False,
+ *,
+ booking_url: str | None = None,
+) -> dict[str, Any]:
"""Serialize a flight result (or round-trip/multi-city tuple) to a dictionary."""
if not isinstance(flight, tuple):
out = {
@@ -346,6 +447,8 @@ def _serialize_flight_result(flight: Any, is_round_trip: bool = False) -> dict[s
"legs": [_serialize_flight_leg(leg) for leg in flight.legs],
}
out.update(_flight_extras(flight))
+ if booking_url:
+ out["booking_url"] = booking_url
return out
segments = list(flight)
@@ -365,6 +468,8 @@ def _serialize_flight_result(flight: Any, is_round_trip: bool = False) -> dict[s
return_extras = _flight_extras(return_flight)
if return_extras:
out["return_flight"] = return_extras
+ if booking_url:
+ out["booking_url"] = booking_url
return out
# Multi-city (3+ legs) or 2-leg non-round-trip: combined price on the
@@ -376,17 +481,41 @@ def _serialize_flight_result(flight: Any, is_round_trip: bool = False) -> dict[s
"legs": [_serialize_flight_leg(leg) for segment in segments for leg in segment.legs],
}
out.update(_flight_extras(price_segment))
+ if booking_url:
+ out["booking_url"] = booking_url
return out
-def _serialize_date_result(date_result: Any) -> dict[str, Any]:
- """Serialize a date price result to a dictionary."""
- return {
- "date": date_result.date,
+def _date_str(value: Any) -> str | None:
+ """Coerce a ``DatePrice`` date element (datetime) to ``YYYY-MM-DD``."""
+ if value is None:
+ return None
+ if hasattr(value, "date"):
+ return value.date().isoformat()
+ return str(value)
+
+
+def _serialize_date_result(
+ date_result: Any,
+ origins: list[Airport],
+ destinations: list[Airport],
+ locale: tuple[str | None, str | None, str | None],
+) -> dict[str, Any]:
+ """Serialize a date price result, including a deep link for that date."""
+ dates = date_result.date
+ departure = _date_str(dates[0]) if dates else None
+ return_date = _date_str(dates[1]) if dates and len(dates) > 1 else None
+ out: dict[str, Any] = {
+ "date": departure,
"price": date_result.price,
"currency": date_result.currency or CONFIG.default_currency,
- "return_date": getattr(date_result, "return_date", None),
+ "return_date": return_date,
}
+ if departure:
+ out["booking_url"] = _google_flights_url(
+ origins, destinations, departure, return_date, *locale
+ )
+ return out
# =============================================================================
@@ -402,66 +531,78 @@ def _resolve_airports(codes: str) -> list[Airport]:
return airports
-def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
- """Execute a flight search and return formatted results."""
- try:
- # Parse inputs using shared utilities (supports comma-separated multi-airport)
- origins = _resolve_airports(params.origin)
- destinations = _resolve_airports(params.destination)
- cabin_class = parse_cabin_class(params.cabin_class)
- max_stops = parse_max_stops(params.max_stops)
- sort_by = parse_sort_by(params.sort_by)
- airlines = parse_airlines(params.airlines)
- airlines_exclude = parse_airlines(params.exclude_airlines)
- alliances = parse_alliances(params.alliance)
- alliances_exclude = parse_alliances(params.exclude_alliance)
+def _build_flight_filters(
+ params: FlightSearchParams,
+) -> tuple[FlightSearchFilters, TripType, list[Airport], list[Airport]]:
+ """Translate request params into search filters and resolved airports.
- # Build time restrictions
- departure_window = params.departure_window or CONFIG.default_departure_window
- time_restrictions = build_time_restrictions(departure_window) if departure_window else None
+ Shared by :func:`_execute_flight_search` and
+ :func:`_execute_booking_options` so both build identical filters from
+ the same inputs.
+ """
+ # Parse inputs using shared utilities (supports comma-separated multi-airport)
+ origins = _resolve_airports(params.origin)
+ destinations = _resolve_airports(params.destination)
+ cabin_class = parse_cabin_class(params.cabin_class)
+ max_stops = parse_max_stops(params.max_stops)
+ sort_by = parse_sort_by(params.sort_by)
+ airlines = parse_airlines(params.airlines)
+ airlines_exclude = parse_airlines(params.exclude_airlines)
+ alliances = parse_alliances(params.alliance)
+ alliances_exclude = parse_alliances(params.exclude_alliance)
+
+ # Build time restrictions
+ departure_window = params.departure_window or CONFIG.default_departure_window
+ time_restrictions = build_time_restrictions(departure_window) if departure_window else None
+
+ # Build flight segments (pass full lists for multi-airport support)
+ segments, trip_type = build_flight_segments(
+ origin=origins,
+ destination=destinations,
+ departure_date=params.departure_date,
+ return_date=params.return_date,
+ time_restrictions=time_restrictions,
+ )
- # Build flight segments (pass full lists for multi-airport support)
- segments, trip_type = build_flight_segments(
- origin=origins,
- destination=destinations,
- departure_date=params.departure_date,
- return_date=params.return_date,
- time_restrictions=time_restrictions,
- )
+ # Parse new filters
+ emissions_filter = parse_emissions(params.emissions)
+ bags_filter = None
+ if params.checked_bags > 0 or params.carry_on:
+ bags_filter = BagsFilter(checked_bags=params.checked_bags, carry_on=params.carry_on)
- # Parse new filters
- emissions_filter = parse_emissions(params.emissions)
- bags_filter = None
- if params.checked_bags > 0 or params.carry_on:
- bags_filter = BagsFilter(checked_bags=params.checked_bags, carry_on=params.carry_on)
+ layover_restrictions = None
+ if params.min_layover is not None or params.max_layover is not None:
+ from fli.models import LayoverRestrictions
- layover_restrictions = None
- if params.min_layover is not None or params.max_layover is not None:
- from fli.models import LayoverRestrictions
+ layover_restrictions = LayoverRestrictions(
+ min_duration=params.min_layover,
+ max_duration=params.max_layover,
+ )
- layover_restrictions = LayoverRestrictions(
- min_duration=params.min_layover,
- max_duration=params.max_layover,
- )
+ filters = FlightSearchFilters(
+ trip_type=trip_type,
+ passenger_info=PassengerInfo(adults=params.passengers),
+ flight_segments=segments,
+ stops=max_stops,
+ seat_type=cabin_class,
+ airlines=airlines,
+ airlines_exclude=airlines_exclude,
+ alliances=alliances,
+ alliances_exclude=alliances_exclude,
+ layover_restrictions=layover_restrictions,
+ sort_by=sort_by,
+ exclude_basic_economy=params.exclude_basic_economy,
+ emissions=emissions_filter,
+ bags=bags_filter,
+ show_all_results=params.show_all_results,
+ )
+ return filters, trip_type, origins, destinations
- # Create search filters
- filters = FlightSearchFilters(
- trip_type=trip_type,
- passenger_info=PassengerInfo(adults=params.passengers),
- flight_segments=segments,
- stops=max_stops,
- seat_type=cabin_class,
- airlines=airlines,
- airlines_exclude=airlines_exclude,
- alliances=alliances,
- alliances_exclude=alliances_exclude,
- layover_restrictions=layover_restrictions,
- sort_by=sort_by,
- exclude_basic_economy=params.exclude_basic_economy,
- emissions=emissions_filter,
- bags=bags_filter,
- show_all_results=params.show_all_results,
- )
+
+def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
+ """Execute a flight search and return formatted results."""
+ try:
+ filters, trip_type, origins, destinations = _build_flight_filters(params)
# Perform search
currency = parse_currency(params.currency)
@@ -473,12 +614,40 @@ def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
country=params.country,
)
+ booking_url = _google_flights_url(
+ origins,
+ destinations,
+ params.departure_date,
+ params.return_date,
+ params.currency,
+ params.language,
+ params.country,
+ )
+
if not flights:
- return {"success": True, "flights": [], "count": 0, "trip_type": trip_type.name}
+ return {
+ "success": True,
+ "flights": [],
+ "count": 0,
+ "trip_type": trip_type.name,
+ "booking_url": booking_url,
+ }
- # Serialize results
+ # Serialize results; attach per-flight deep-link booking URL.
is_round_trip = trip_type == TripType.ROUND_TRIP
- flight_results = [_serialize_flight_result(f, is_round_trip) for f in flights]
+ flight_results = [
+ _serialize_flight_result(
+ f,
+ is_round_trip,
+ booking_url=search_client.build_flight_booking_url(
+ f,
+ currency=params.currency,
+ language=params.language,
+ country=params.country,
+ ),
+ )
+ for f in flights
+ ]
if CONFIG.max_results:
flight_results = flight_results[: CONFIG.max_results]
@@ -488,6 +657,7 @@ def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
"flights": flight_results,
"count": len(flight_results),
"trip_type": trip_type.name,
+ "booking_url": booking_url,
}
except ParseError as e:
@@ -499,6 +669,101 @@ def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
return {"success": False, "error": f"Search failed: {error_msg}", "flights": []}
+def _execute_booking_options(
+ params: FlightSearchParams, flight_numbers: list[str] | None
+) -> dict[str, Any]:
+ """Fetch real bookable fares (vendor URLs + prices) for one itinerary.
+
+ Re-runs the search so the client captures a fresh shopping session,
+ selects the itinerary identified by ``flight_numbers`` (or the top
+ result when omitted), then calls
+ :meth:`fli.search.SearchFlights.get_booking_options` and serializes the
+ vendor list — each carrying a direct ``booking_url``.
+ """
+ try:
+ filters, trip_type, origins, destinations = _build_flight_filters(params)
+
+ currency = parse_currency(params.currency)
+ search_client = SearchFlights()
+ flights = search_client.search(
+ filters,
+ currency=currency,
+ language=params.language,
+ country=params.country,
+ )
+
+ booking_url = _google_flights_url(
+ origins,
+ destinations,
+ params.departure_date,
+ params.return_date,
+ params.currency,
+ params.language,
+ params.country,
+ )
+
+ if not flights:
+ return {"success": True, "options": [], "count": 0, "booking_url": booking_url}
+
+ flight = _match_flight(flights, flight_numbers)
+ if flight is None:
+ return {
+ "success": False,
+ "error": (
+ "No flight matched the requested flight_numbers. Pass values "
+ "from a prior search_flights result (e.g. ['BA178'] or ['178'])."
+ ),
+ "available_flights": [_flight_idents(f) for f in flights[:20]],
+ "options": [],
+ "booking_url": booking_url,
+ }
+
+ options = search_client.get_booking_options(
+ flight,
+ filters,
+ currency=currency,
+ language=params.language,
+ country=params.country,
+ )
+
+ is_round_trip = trip_type == TripType.ROUND_TRIP
+ flight_booking_url = search_client.build_flight_booking_url(
+ flight,
+ currency=params.currency,
+ language=params.language,
+ country=params.country,
+ )
+ serialized = [_serialize_booking_option(o) for o in options]
+ result = {
+ "success": True,
+ "selected_flight": _serialize_flight_result(
+ flight, is_round_trip, booking_url=flight_booking_url
+ ),
+ "options": serialized,
+ "count": len(serialized),
+ "booking_url": booking_url,
+ }
+ if not serialized:
+ # Google's GetBookingResults frequently returns no vendors without a
+ # browser-minted session token that fli does not reproduce server-side.
+ # The per-flight deep link in selected_flight.booking_url opens the
+ # specific itinerary's booking page directly.
+ result["note"] = (
+ "Google returned no per-vendor booking fares for this itinerary. "
+ "Use selected_flight.booking_url to open the specific flight's "
+ "booking page on Google Flights."
+ )
+ return result
+
+ except ParseError as e:
+ return {"success": False, "error": str(e), "options": []}
+ except Exception as e:
+ error_msg = str(e)
+ if "validation error" in error_msg.lower():
+ return {"success": False, "error": "Invalid parameter value", "options": []}
+ return {"success": False, "error": f"Booking lookup failed: {error_msg}", "options": []}
+
+
def _execute_date_search(params: DateSearchParams) -> dict[str, Any]:
"""Execute a date search and return formatted results."""
try:
@@ -575,7 +840,8 @@ def _execute_date_search(params: DateSearchParams) -> dict[str, Any]:
dates.sort(key=lambda x: x.price)
# Serialize results
- date_results = [_serialize_date_result(d) for d in dates]
+ locale = (params.currency, params.language, params.country)
+ date_results = [_serialize_date_result(d, origins, destinations, locale) for d in dates]
if CONFIG.max_results:
date_results = date_results[: CONFIG.max_results]
@@ -876,6 +1142,164 @@ def _search_dates_from_params(params: DateSearchParams) -> dict[str, Any]:
return _execute_date_search(params)
+ annotations={
+ "title": "Get Booking Options",
+ "readOnlyHint": True,
+ "idempotentHint": True,
+ },
+)
+def get_booking_options(
+ origin: Annotated[
+ str,
+ Field(description="Departure airport IATA code(s), comma-separated for multiple"),
+ ],
+ destination: Annotated[
+ str,
+ Field(description="Arrival airport IATA code(s), comma-separated for multiple"),
+ ],
+ departure_date: Annotated[str, Field(description="Travel date in YYYY-MM-DD format")],
+ flight_numbers: Annotated[
+ list[str] | None,
+ Field(
+ description=(
+ "Flight numbers identifying the itinerary to price, in order, taken from a "
+ "prior search_flights result (e.g. ['BA178'] one-way, ['AA100', 'AA200'] "
+ "round-trip). Accepts bare numbers ('178') or airline-prefixed ('BA178'). "
+ "Omit to price the top result."
+ )
+ ),
+ ] = None,
+ return_date: Annotated[
+ str | None,
+ Field(description="Return date in YYYY-MM-DD format (omit for one-way)"),
+ ] = None,
+ cabin_class: Annotated[
+ str,
+ Field(description="Cabin class: ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST"),
+ ] = CONFIG.default_cabin_class,
+ max_stops: Annotated[
+ str,
+ Field(description="Maximum stops: ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS"),
+ ] = "ANY",
+ passengers: Annotated[
+ int | None,
+ Field(description="Number of adult passengers", ge=1),
+ ] = None,
+ airlines: Annotated[
+ list[str] | None,
+ Field(description="Filter by airline IATA codes (e.g., ['BA', 'AA'])"),
+ ] = None,
+ exclude_basic_economy: Annotated[
+ bool,
+ Field(description="Exclude basic economy fares from results"),
+ ] = False,
+ currency: Annotated[
+ str | None,
+ Field(description="ISO 4217 currency code (USD, EUR, GBP, JPY...) for prices."),
+ ] = None,
+ language: Annotated[
+ str | None,
+ Field(description="Optional BCP-47 language code (e.g., 'en-GB') for the `hl` URL param."),
+ ] = None,
+ country: Annotated[
+ str | None,
+ Field(description="Optional ISO 3166-1 alpha-2 country code (e.g., 'GB')."),
+ ] = None,
+ departure_window: Annotated[
+ str | None,
+ Field(description="Departure time window in 'HH-HH' 24h format (e.g., '6-20')"),
+ ] = None,
+ sort_by: Annotated[
+ str,
+ Field(
+ description="Sort by: TOP_FLIGHTS, BEST, CHEAPEST,"
+ " DEPARTURE_TIME, ARRIVAL_TIME, DURATION, EMISSIONS"
+ ),
+ ] = CONFIG.default_sort_by,
+ exclude_airlines: Annotated[
+ list[str] | None,
+ Field(description="Airline IATA codes to EXCLUDE from results."),
+ ] = None,
+ alliance: Annotated[
+ list[str] | None,
+ Field(description="Restrict to alliances: ONEWORLD, SKYTEAM, STAR_ALLIANCE."),
+ ] = None,
+ exclude_alliance: Annotated[
+ list[str] | None,
+ Field(description="Alliance names to EXCLUDE from results."),
+ ] = None,
+ min_layover: Annotated[
+ int | None,
+ Field(description="Minimum layover duration in minutes.", ge=1),
+ ] = None,
+ max_layover: Annotated[
+ int | None,
+ Field(description="Maximum layover duration in minutes.", ge=1),
+ ] = None,
+ emissions: Annotated[
+ str,
+ Field(description="Filter by emissions level: ALL or LESS"),
+ ] = "ALL",
+ checked_bags: Annotated[
+ int,
+ Field(description="Number of checked bags to include in price (0, 1, or 2)", ge=0, le=2),
+ ] = 0,
+ carry_on: Annotated[
+ bool,
+ Field(description="Include carry-on bag fee in displayed price"),
+ ] = False,
+) -> dict[str, Any]:
+ """Get bookable fares (vendor names, prices, and direct booking URLs) for a flight.
+
+ Runs a fresh search, selects the itinerary identified by ``flight_numbers``
+ (or the top result when omitted), and returns the airline-direct and
+ online-travel-agency options Google surfaces for it — each with a
+ clickable ``booking_url``. Use ``search_flights`` first to discover the
+ flight numbers, then call this tool to retrieve where and at what price
+ it can be booked.
+
+ Pass the same filters (``sort_by``, ``departure_window``,
+ ``exclude_airlines``, ``alliance``, layover/bags/emissions, …) that were
+ used for ``search_flights`` so the re-run search reproduces the same result
+ set — otherwise, when ``flight_numbers`` is omitted, the priced "top
+ result" may differ from the one the user saw.
+ """
+ effective_departure_window = departure_window or CONFIG.default_departure_window
+ params = FlightSearchParams(
+ origin=origin,
+ destination=destination,
+ departure_date=departure_date,
+ return_date=return_date,
+ departure_window=effective_departure_window,
+ cabin_class=cabin_class,
+ max_stops=max_stops,
+ sort_by=sort_by,
+ passengers=passengers or CONFIG.default_passengers,
+ airlines=airlines,
+ exclude_basic_economy=exclude_basic_economy,
+ emissions=emissions,
+ checked_bags=checked_bags,
+ carry_on=carry_on,
+ currency=currency,
+ language=language,
+ country=country,
+ exclude_airlines=exclude_airlines,
+ alliance=alliance,
+ exclude_alliance=exclude_alliance,
+ min_layover=min_layover,
+ max_layover=max_layover,
+ )
+ return _execute_booking_options(params, flight_numbers)
+
+
+def _get_booking_options_from_params(
+ params: FlightSearchParams, flight_numbers: list[str] | None = None
+) -> dict[str, Any]:
+ """Entry point for tests that call the tool via a params object."""
+ return _execute_booking_options(params, flight_numbers)
+
+
def _find_airports_impl(query: str, limit: int = 10) -> dict[str, Any]:
"""Run search_airports and shape the result into the MCP response dict."""
try:
diff --git a/fli/search/_booking_capture.py b/fli/search/_booking_capture.py
deleted file mode 100644
index 8c6e7c2..0000000
--- a/fli/search/_booking_capture.py
+++ /dev/null
@@ -1,143 +0,0 @@
-"""Browser-driven booking-token capture (optional Playwright helper).
-
-The ``GetBookingResults`` endpoint requires a server-minted session id
-that does not appear anywhere in the search response JSON or the rendered
-HTML — empirically confirmed by walking every nested string in multiple
-captured responses. Google's frontend JS bundle generates the booking
-URL's ``tfu`` parameter as part of the click-handler when the user
-selects a flight; reproducing that pipeline server-side would require
-deep reverse engineering of the JS bundle.
-
-This module provides an opt-in fallback: if the caller has Playwright
-installed, ``capture_booking_token`` drives a real browser through the
-search → select-outbound → select-return → booking-page flow, then
-reads the resulting URL's ``tfu`` parameter and returns the inner
-booking token. The caller can then pass that token straight to
-:meth:`fli.search.SearchFlights.get_booking_options`.
-
-Why opt-in: Playwright adds ~300 MB of browser binaries and is wrong
-for most fli use cases (CLI flight search, MCP queries). Users who
-need live booking options can install it on demand::
-
- uv add --optional booking playwright
- uv run playwright install chromium
-"""
-
-from __future__ import annotations
-
-from datetime import datetime
-
-from fli.models import FlightResult
-
-
-def _format_iata(airport) -> str: # noqa: ANN001
- """Return the bare IATA code from an Airport enum or string."""
- if hasattr(airport, "name"):
- return airport.name.removeprefix("_")
- return str(airport)
-
-
-async def capture_booking_token(
- outbound: FlightResult,
- return_flight: FlightResult | None,
- travel_date: str,
- return_date: str | None = None,
- *,
- currency: str = "USD",
- headless: bool = True,
- timeout_ms: int = 60_000,
-) -> str:
- """Drive a real browser through the booking flow and return the token.
-
- The token is the base64-encoded booking payload extracted from the
- booking page's ``tfu`` URL parameter — the same shape that
- :meth:`fli.search.SearchFlights.get_booking_options` accepts via its
- ``booking_token`` kwarg.
-
- Requires Playwright to be installed (``pip install playwright`` plus
- ``playwright install chromium``). The function imports Playwright
- lazily so that fli's main dependency footprint is unaffected.
-
- Args:
- outbound: Outbound :class:`FlightResult` (from a prior
- :meth:`fli.search.SearchFlights.search` call).
- return_flight: Return :class:`FlightResult` for round-trip
- itineraries, or ``None`` for one-way.
- travel_date: Outbound date in ``YYYY-MM-DD`` format.
- return_date: Return date in ``YYYY-MM-DD`` format (RT only).
- currency: ISO 4217 currency code for the booking page URL.
- headless: When True (default) runs the browser in headless mode.
- timeout_ms: Per-step navigation timeout in milliseconds.
-
- Returns:
- The base64-encoded booking token suitable for
- :meth:`fli.search.SearchFlights.get_booking_options`.
-
- Raises:
- ImportError: When Playwright isn't installed.
- RuntimeError: When the booking page URL doesn't carry the ``tfu``
- parameter (e.g. the flight is unavailable, or Google has
- changed the navigation flow).
-
- """
- try:
- from playwright.async_api import async_playwright
- except ImportError as e: # pragma: no cover - optional dependency
- raise ImportError(
- "capture_booking_token requires Playwright. Install with:\n"
- " pip install playwright\n"
- " playwright install chromium"
- ) from e
-
- from fli.search._proto import extract_booking_token_from_tfu
-
- out_iata = _format_iata(outbound.legs[0].departure_airport)
- in_iata = _format_iata(outbound.legs[-1].arrival_airport)
- parsed_date = datetime.strptime(travel_date, "%Y-%m-%d").strftime("%Y-%m-%d")
- search_url = (
- f"https://www.google.com/travel/flights"
- f"?hl=en&curr={currency}&gl=US"
- f"&q=Flights to {in_iata} from {out_iata} on {parsed_date}"
- )
-
- async with async_playwright() as pw:
- browser = await pw.chromium.launch(headless=headless)
- try:
- page = await browser.new_page()
- await page.goto(search_url, timeout=timeout_ms, wait_until="load")
- await page.wait_for_selector('a[aria-label*="Select flight"]', timeout=timeout_ms)
-
- # Click the matching outbound flight: filter by departure time + airline.
- outbound_label = _flight_aria_pattern(outbound)
- await page.locator(f'a[aria-label*="{outbound_label}"]').first.click()
-
- if return_flight is not None:
- # Round-trip: wait for the return-flight grid, then click.
- await page.wait_for_selector('a[aria-label*="Select flight"]', timeout=timeout_ms)
- return_label = _flight_aria_pattern(return_flight)
- await page.locator(f'a[aria-label*="{return_label}"]').first.click()
-
- await page.wait_for_url("**/travel/flights/booking?**", timeout=timeout_ms)
- booking_url = page.url
- finally:
- await browser.close()
-
- if "tfu=" not in booking_url:
- raise RuntimeError(
- f"Booking page URL has no `tfu` parameter: {booking_url}\n"
- "Google may have changed the navigation flow."
- )
- return extract_booking_token_from_tfu(booking_url)
-
-
-def _flight_aria_pattern(flight: FlightResult) -> str:
- """Build a short string that uniquely matches the flight's aria-label.
-
- Google's UI links each "Select flight" anchor have an aria-label like
- ``"From 342 US dollars round trip total. Nonstop flight with American."``
- We match on the *airline name* + *departure time* which together
- uniquely identify a row in the list.
- """
- dep = flight.legs[0].departure_datetime.strftime("%-I:%M %p")
- # The aria-label always includes the departure time + " on <weekday>".
- return f"{dep} on"
diff --git a/fli/search/_proto.py b/fli/search/_proto.py
index efe1833..bea7e99 100644
--- a/fli/search/_proto.py
+++ b/fli/search/_proto.py
@@ -1,19 +1,28 @@
-"""Minimal protobuf wire-format encoder used to build the GetBookingResults token.
+"""Minimal protobuf wire-format encoder used to build booking tokens and URLs.
-Google's booking-options endpoint accepts a base64-encoded protobuf as
-``outer[0][1]``. The structure was reverse-engineered from a live capture
-on 2026-05-14 (see ``.reverse-eng/notes/booking_results.md``):
+Two token types are implemented:
-::
+1. **GetBookingResults token** (``outer[0][1]``) — used for the vendor-list
+ API call. Structure reverse-engineered 2026-05-14 (see
+ ``.reverse-eng/notes/booking_results.md``):
- field 1 (length-delim): shopping session id (response `inner[0][4]`)
- field 2 (length-delim): "{airline}{flight_no}#{idx}" (selected itinerary)
- field 3 (length-delim, nested):
- field 1 (varint): price in smallest currency unit (e.g. cents)
- field 2 (varint): 2 (constant in our samples)
- field 3 (length-delim): ISO currency code (e.g. "USD")
- field 7 (varint): 28 (stops bucket marker)
- field 14 (varint): same as inner field 1 (price duplicated)
+ ::
+
+ field 1 (length-delim): shopping session id (response ``inner[0][4]``)
+ field 2 (length-delim): "{airline}{flight_no}#{idx}" (selected itinerary)
+ field 3 (length-delim, nested):
+ field 1 (varint): price in smallest currency unit (e.g. cents)
+ field 2 (varint): 2 (constant)
+ field 3 (length-delim): ISO currency code (e.g. "USD")
+ field 7 (varint): 28 (stops bucket marker)
+ field 14 (varint): same as inner field 1 (price duplicated)
+
+2. **Deep-link itinerary token** (``tfs``) — embedded in
+ ``https://www.google.com/travel/flights/booking?tfs=…`` to open a specific
+ itinerary's booking page (vendor fares + "Continue" CTA included). The
+ ``tfs`` token alone is sufficient; the companion ``tfu`` token Google's UI
+ also emits is not needed and is intentionally not built. Structure
+ reverse-engineered 2026-05-28 (see ``.reverse-eng/notes/booking_results.md``).
We implement only the protobuf primitives we need here — varint, length-
delimited string/bytes, nested-message — to avoid the protobuf-runtime
@@ -24,10 +33,36 @@ from __future__ import annotations
import base64
import logging
+from dataclasses import dataclass
logger = logging.getLogger(__name__)
+# ---------------------------------------------------------------------------
+# tfs deep-link helpers
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class LegSpec:
+ """One physical leg within a booking-URL segment.
+
+ Attributes:
+ origin: IATA code of the departure airport (e.g. ``"SFO"``).
+ dep_date: Departure date in ``YYYY-MM-DD`` format.
+ dest: IATA code of the arrival airport (e.g. ``"PHX"``).
+ airline: Airline IATA code (e.g. ``"AA"``).
+ flight_number: Flight number string (e.g. ``"2413"``).
+
+ """ # noqa: D413 — blank-line-after-last-section false-positive on frozen dataclass
+
+ origin: str
+ dep_date: str
+ dest: str
+ airline: str
+ flight_number: str
+
+
def _varint(value: int) -> bytes:
"""Encode an unsigned integer as a protobuf varint."""
if value < 0:
@@ -193,95 +228,97 @@ def _read_varint(buf: bytes, off: int) -> tuple[int, int]:
shift += 7
-def extract_booking_token_from_tfu(tfu: str) -> str:
- """Extract the booking token from a booking-page ``tfu`` URL parameter.
+# ---------------------------------------------------------------------------
+# Deep-link URL parameter builder (tfs)
+# ---------------------------------------------------------------------------
+
- Google Flights' booking page URL has the shape::
+def _to_urlsafe_b64(data: bytes) -> str:
+ """Encode *data* as URL-safe base64 without ``=`` padding.
+
+ The ``tfs`` query parameter uses the urlsafe alphabet (``-`` / ``_``) with
+ padding stripped.
+ """
+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
- /booking?tfs=<tfs>&tfu=<tfu>...
- where ``tfu`` is a base64-encoded protobuf wrapping the booking token::
+def build_tfs_token(
+ segments: list[list[LegSpec]],
+ *,
+ is_one_way: bool = True,
+) -> str:
+ """Build the ``tfs`` query parameter for a Google Flights deep-link URL.
- tfu = base64( protobuf {
- field 1 (str): base64( <booking token bytes> )
- field 2 (nested): { ... }
- field 4 (str): "" or other padding
- } )
+ The ``tfs`` token encodes the complete itinerary — one segment per travel
+ direction, each segment containing one leg per physical flight. It is
+ deterministic (no session id required) and can be constructed purely from
+ search-result data.
- This helper accepts either a bare ``tfu`` value or a full URL and
- returns the inner booking token in the same base64 form
- :class:`SearchFlights.get_booking_options` accepts via its
- ``booking_token`` kwarg.
+ Reverse-engineered 2026-05-28 from live browser captures of one-way
+ nonstop, one-way connection (2-stop), and round-trip booking pages (see
+ ``.reverse-eng/notes/booking_results.md``).
Args:
- tfu: A ``tfu`` URL parameter value, or a full URL containing one.
+ segments: Ordered list of travel directions. Each element is a list
+ of :class:`LegSpec` describing every physical leg in that
+ direction (one leg for nonstop, two or more for connections).
+ is_one_way: ``True`` for one-way (including multi-city); ``False``
+ for round-trip. Controls the ``f19`` constant.
Returns:
- The base64-encoded booking token suitable for
- :meth:`SearchFlights.get_booking_options`.
+ URL-safe base64 string (no ``=`` padding) suitable for use as the
+ ``tfs=`` query parameter.
Raises:
- ValueError: If the input does not contain a parseable tfu blob.
+ ValueError: *segments* is empty or any segment has no legs.
"""
- # Accept full URL
- if "tfu=" in tfu:
- from urllib.parse import parse_qs, urlparse
-
- parts = urlparse(tfu)
- qs = parse_qs(parts.query)
- if "tfu" not in qs:
- raise ValueError("URL has no `tfu` query parameter")
- tfu = qs["tfu"][0]
-
- # Decode the outer protobuf
- padding = "=" * ((4 - len(tfu) % 4) % 4)
- try:
- raw = base64.urlsafe_b64decode(tfu + padding)
- except (ValueError, base64.binascii.Error) as e:
- raise ValueError(f"tfu is not valid base64: {e}") from e
-
- # Walk protobuf fields looking for field 1 (length-delim string)
- off = 0
- while off < len(raw):
- tag, off = _read_varint(raw, off)
- field = tag >> 3
- wire = tag & 0x7
- if wire == 0:
- _, off = _read_varint(raw, off)
- elif wire == 2:
- length, off = _read_varint(raw, off)
- data = raw[off : off + length]
- off += length
- if field == 1:
- try:
- token_b64 = data.decode("ascii")
- except UnicodeDecodeError as e:
- raise ValueError("tfu field 1 is not ASCII") from e
- # Strip trailing whitespace/padding-like chars and
- # re-normalise to the standard base64 alphabet so the
- # downstream parser accepts it.
- token_b64 = token_b64.strip().rstrip("=")
- return token_b64
- elif wire == 5:
- off += 4
- elif wire == 1:
- off += 8
- else:
- raise ValueError(f"unsupported wire type {wire} at offset {off}")
-
- raise ValueError("tfu protobuf has no field 1 (booking token)")
+ if not segments:
+ raise ValueError("segments must be non-empty")
+ for i, seg in enumerate(segments):
+ if not seg:
+ raise ValueError(f"segment {i} has no legs")
+
+ segment_protos = b""
+ for seg in segments:
+ # Each leg becomes a repeated f4 within this segment.
+ legs_proto = b""
+ for leg in seg:
+ leg_proto = (
+ _length_delim(1, leg.origin.encode())
+ + _length_delim(2, leg.dep_date.encode())
+ + _length_delim(3, leg.dest.encode())
+ + _length_delim(5, leg.airline.encode())
+ + _length_delim(6, leg.flight_number.encode())
+ )
+ legs_proto += _length_delim(4, leg_proto)
+
+ origin_iata = seg[0].origin
+ dest_iata = seg[-1].dest
+ seg_date = seg[0].dep_date
+
+ seg_proto = (
+ _length_delim(2, seg_date.encode())
+ + legs_proto
+ + _length_delim(13, _varint_field(1, 1) + _length_delim(2, origin_iata.encode()))
+ + _length_delim(14, _varint_field(1, 1) + _length_delim(2, dest_iata.encode()))
+ )
+ segment_protos += _length_delim(3, seg_proto)
+
+ # f16 constant: max uint64 (0xFFFFFFFFFFFFFFFF)
+ _MAX_U64 = (1 << 64) - 1
+
+ # f19: 2 = one-way / multi-city, 1 = round-trip
+ f19 = 2 if is_one_way else 1
-
-def extract_session_id_from_tfu(tfu: str) -> str:
- """Extract the booking session id from a ``tfu`` URL parameter.
-
- Convenience wrapper that calls :func:`extract_booking_token_from_tfu`
- then decodes the inner token's ``field 1`` (the session id).
- """
- inner_token = extract_booking_token_from_tfu(tfu)
- decoded = decode_booking_token(inner_token)
- session = decoded.get("field_1")
- if not isinstance(session, str):
- raise ValueError("inner booking token has no field 1 (session id)")
- return session
+ payload = (
+ _varint_field(1, 28)
+ + _varint_field(2, 2)
+ + segment_protos
+ + _varint_field(8, 1)
+ + _varint_field(9, 1)
+ + _varint_field(14, 1)
+ + _length_delim(16, _varint_field(1, _MAX_U64))
+ + _varint_field(19, f19)
+ )
+ return _to_urlsafe_b64(payload)
diff --git a/fli/search/_urls.py b/fli/search/_urls.py
index 12d4557..f62d2b9 100644
--- a/fli/search/_urls.py
+++ b/fli/search/_urls.py
@@ -1,45 +1,19 @@
"""URL-construction helpers for the FlightsFrontendService RPC endpoints.
-Currently the only knob we expose at the URL layer is the locale tuple
-(``curr=``, ``hl=``, ``gl=``). Google honours these on every endpoint we
-talk to and they materially change the prices / language of the response,
-so we surface them as explicit kwargs on the search methods rather than
-hiding them as undocumented HTTP details.
+The locale tuple (``curr=``, ``hl=``, ``gl=``) is the only knob we expose at
+the URL layer. Google honours these on every endpoint we talk to and they
+materially change the prices / language of the response, so we surface them
+as explicit kwargs on the search methods rather than hiding them as
+undocumented HTTP details.
+
+The implementation now lives in :mod:`fli.core.links` so the same helper can
+build the public-facing Google Flights deep links shown by the CLI and MCP.
+It is re-exported here to keep ``fli.search._urls.with_locale_params`` stable
+for existing callers.
"""
from __future__ import annotations
-import urllib.parse
+from fli.core.links import with_locale_params
-
-def with_locale_params(
- url: str,
- currency: str | None,
- language: str | None,
- country: str | None,
-) -> str:
- """Append optional ``curr``/``hl``/``gl`` parameters to ``url``.
-
- - ``currency`` is uppercased ("usd" → "USD") because Google rejects
- lowercase codes silently (still 200, but ignores the override).
- - ``language`` is passed through verbatim (BCP-47, may contain a hyphen).
- - ``country`` is uppercased (ISO 3166-1 alpha-2).
-
- All values are percent-encoded so a caller typo (a stray ``&``, ``+``,
- or whitespace) can't break the URL — typical inputs like ``en-GB`` are
- already URL-safe so the encoding is a no-op for them.
-
- No-op when all three are None — returns the input URL unchanged so
- callers can pass through without checking.
- """
- params: list[str] = []
- if currency:
- params.append(f"curr={urllib.parse.quote(currency.upper(), safe='')}")
- if language:
- params.append(f"hl={urllib.parse.quote(language, safe='')}")
- if country:
- params.append(f"gl={urllib.parse.quote(country.upper(), safe='')}")
- if not params:
- return url
- sep = "&" if "?" in url else "?"
- return f"{url}{sep}{'&'.join(params)}"
+__all__ = ["with_locale_params"]
diff --git a/fli/search/flights.py b/fli/search/flights.py
index 16ec170..62c159a 100644
--- a/fli/search/flights.py
+++ b/fli/search/flights.py
@@ -350,6 +350,69 @@ class SearchFlights:
options.extend(chunk_options)
return options
+ def build_flight_booking_url(
+ self,
+ flight: FlightResult | tuple[FlightResult, ...],
+ *,
+ currency: str | None = None,
+ language: str | None = None,
+ country: str | None = None,
+ ) -> str:
+ """Build a Google Flights deep-link URL for a specific itinerary.
+
+ Constructs ``https://www.google.com/travel/flights/booking?tfs=…`` that
+ opens the booking page pre-loaded with the given itinerary — the
+ airline/OTA fare options and the "Continue" booking CTA included.
+
+ The ``tfs`` itinerary token is fully deterministic (built from the
+ flight's airports, dates and flight numbers); no session id or network
+ round-trip is required, so the same itinerary always yields the same
+ URL. This method never raises — on malformed input it falls back to the
+ generic Google Flights URL.
+
+ Args:
+ flight: A :class:`~fli.models.FlightResult` (one-way / single
+ segment) or a tuple of them (round-trip / multi-city, one
+ element per travel direction).
+ currency: ISO 4217 currency code appended as ``curr=``.
+ language: BCP-47 language code appended as ``hl=``.
+ country: ISO 3166-1 alpha-2 country code appended as ``gl=``.
+
+ Returns:
+ A ``https://www.google.com/travel/flights/booking?tfs=…`` URL.
+
+ """
+ from fli.search._proto import LegSpec, build_tfs_token
+
+ def _iata(airport: object) -> str:
+ # Handle both Airport enum (has .name) and plain strings.
+ return getattr(airport, "name", str(airport)).lstrip("_")
+
+ results: list[FlightResult] = list(flight) if isinstance(flight, tuple) else [flight]
+ is_one_way = len(results) == 1
+
+ try:
+ segments: list[list[LegSpec]] = []
+ for result in results:
+ seg_legs = [
+ LegSpec(
+ origin=_iata(leg.departure_airport),
+ dep_date=leg.departure_datetime.date().isoformat(),
+ dest=_iata(leg.arrival_airport),
+ airline=_iata(leg.airline),
+ flight_number=leg.flight_number,
+ )
+ for leg in result.legs
+ ]
+ segments.append(seg_legs)
+ tfs = build_tfs_token(segments, is_one_way=is_one_way)
+ url = f"https://www.google.com/travel/flights/booking?tfs={tfs}"
+ except Exception:
+ logger.debug("build_flight_booking_url: tfs construction failed", exc_info=True)
+ url = "https://www.google.com/travel/flights"
+
+ return with_locale_params(url, currency, language, country)
+
def _capture_session_id(self, inner: list) -> None:
"""Cache the shopping session id from ``inner[0][4]`` of a search response.
diff --git a/tests/cli/conftest.py b/tests/cli/conftest.py
index 3049109..7ed6869 100644
--- a/tests/cli/conftest.py
+++ b/tests/cli/conftest.py
@@ -97,6 +97,9 @@ def mock_search_flights(monkeypatch):
"total_price": 599.98,
}
]
+ mock.build_flight_booking_url.return_value = (
+ "https://www.google.com/travel/flights/booking?tfs=test"
+ )
monkeypatch.setattr("fli.search.flights.SearchFlights.__new__", lambda cls: mock)
monkeypatch.setattr("fli.search.SearchFlights.__new__", lambda cls: mock)
return mock
diff --git a/tests/cli/test_utils.py b/tests/cli/test_utils.py
index 0d4d6ea..fe359e9 100644
--- a/tests/cli/test_utils.py
+++ b/tests/cli/test_utils.py
@@ -8,6 +8,7 @@ from typer import BadParameter
from fli.cli.enums import DayOfWeek
from fli.cli.utils import (
+ build_json_success_response,
display_date_results,
display_flight_results,
filter_dates_by_days,
@@ -296,6 +297,46 @@ def test_display_round_trip_price_asymmetric():
assert "$750.00" not in output
+def test_display_flight_results_shows_booking_url_footer():
+ """A booking_url is rendered as a clickable footer below the options."""
+ buf = StringIO()
+ test_console = Console(file=buf, width=120, force_terminal=True)
+ url = "https://www.google.com/travel/flights?q=Flights%20from%20JFK%20to%20LHR"
+ with patch("fli.cli.utils.console", test_console):
+ display_flight_results(
+ [_make_flight_result(price=159.0)],
+ trip_type=TripType.ONE_WAY,
+ booking_url=url,
+ )
+ output = buf.getvalue()
+ assert "Open on Google Flights" in output
+ assert "travel/flights" in output
+
+
+def test_display_flight_results_no_footer_without_booking_url():
+ """No booking footer is shown when booking_url is omitted."""
+ output = _capture_display([_make_flight_result(price=159.0)])
+ assert "Open on Google Flights" not in output
+
+
+def test_display_date_results_links_dates_when_route_given():
+ """Departure dates become Google Flights hyperlinks when a route is supplied."""
+ buf = StringIO()
+ test_console = Console(file=buf, width=120, force_terminal=True)
+ dates = [DatePrice(date=(datetime(2026, 7, 15),), price=299.0, currency="USD")]
+ with patch("fli.cli.utils.console", test_console):
+ display_date_results(
+ dates,
+ TripType.ONE_WAY,
+ origin="JFK",
+ destination="LHR",
+ currency="USD",
+ )
+ output = buf.getvalue()
+ # Rich emits OSC-8 hyperlink escape sequences carrying the URL on a terminal.
+ assert "travel/flights" in output
+
+
def test_display_one_way_price_uses_returned_currency():
"""One-way flight should use the returned currency code for formatting."""
output = _capture_display([_make_flight_result(price=159.0, currency="HKD")])
@@ -398,6 +439,76 @@ def test_serialize_date_result_round_trip():
}
+def test_serialize_date_result_no_booking_url_without_route():
+ """Without origin/destination, no booking_url is added (back-compat shape)."""
+ result = DatePrice(date=(datetime(2026, 5, 1),), price=199.0)
+
+ payload = serialize_date_result(result, TripType.ONE_WAY)
+
+ assert "booking_url" not in payload
+
+
+def test_serialize_date_result_includes_booking_url_one_way():
+ """A route yields a per-date Google Flights deep link for one-way searches."""
+ result = DatePrice(date=(datetime(2026, 5, 1),), price=199.0)
+
+ payload = serialize_date_result(
+ result,
+ TripType.ONE_WAY,
+ origin="JFK",
+ destination="LHR",
+ currency="USD",
+ )
+
+ url = payload["booking_url"]
+ assert url.startswith("https://www.google.com/travel/flights?q=")
+ assert "JFK" in url
+ assert "LHR" in url
+ assert "2026-05-01" in url
+
+
+def test_serialize_date_result_booking_url_round_trip_has_return():
+ """Round-trip date links embed the return date too."""
+ result = DatePrice(date=(datetime(2026, 5, 1), datetime(2026, 5, 8)), price=599.0)
+
+ payload = serialize_date_result(
+ result,
+ TripType.ROUND_TRIP,
+ origin="JFK",
+ destination="LHR",
+ )
+
+ assert "2026-05-01" in payload["booking_url"]
+ assert "2026-05-08" in payload["booking_url"]
+
+
+def test_build_json_success_response_includes_booking_url():
+ """booking_url is added to the success payload when provided."""
+ payload = build_json_success_response(
+ search_type="flights",
+ trip_type=TripType.ONE_WAY,
+ query={},
+ results_key="flights",
+ results=[],
+ booking_url="https://www.google.com/travel/flights?q=x",
+ )
+
+ assert payload["booking_url"] == "https://www.google.com/travel/flights?q=x"
+
+
+def test_build_json_success_response_omits_booking_url_when_none():
+ """No booking_url key when not provided."""
+ payload = build_json_success_response(
+ search_type="flights",
+ trip_type=TripType.ONE_WAY,
+ query={},
+ results_key="flights",
+ results=[],
+ )
+
+ assert "booking_url" not in payload
+
+
def test_serialize_flight_result_uses_returned_currency():
"""JSON flight serialization should preserve the parsed result currency."""
flight = _make_flight_result(price=159.0, currency="SEK")
diff --git a/tests/mcp/test_mcp_http.py b/tests/mcp/test_mcp_http.py
index 7d79e1f..4173b86 100644
--- a/tests/mcp/test_mcp_http.py
+++ b/tests/mcp/test_mcp_http.py
@@ -14,7 +14,7 @@ from fastmcp import Client
from fli.mcp.server import mcp
-EXPECTED_TOOLS = {"search_flights", "search_dates", "find_airports"}
+EXPECTED_TOOLS = {"search_flights", "search_dates", "find_airports", "get_booking_options"}
# ---------------------------------------------------------------------------
diff --git a/tests/mcp/test_mcp_server_unit.py b/tests/mcp/test_mcp_server_unit.py
index 29ab9fc..d64fdab 100644
--- a/tests/mcp/test_mcp_server_unit.py
+++ b/tests/mcp/test_mcp_server_unit.py
@@ -14,8 +14,13 @@ import pytest
from fli.mcp.server import (
FlightSearchParams,
_airline_code,
+ _execute_booking_options,
_execute_flight_search,
_flight_extras,
+ _google_flights_url,
+ _match_flight,
+ _serialize_booking_option,
+ _serialize_date_result,
_serialize_flight_leg,
_serialize_layover,
)
@@ -174,26 +179,17 @@ class TestFlightExtras:
f.primary_airline_name = None
f.self_transfer = None
f.mixed_cabin = None
- f.booking_token = None
f.primary_airline = None
f.layovers = None
for k, v in overrides.items():
setattr(f, k, v)
return f
- def test_booking_token_included_when_set(self):
+ def test_booking_token_not_surfaced(self):
+ # booking_token is an internal artifact no MCP tool consumes; it must
+ # never appear in the response shape even when the parser populates it.
f = self._make_flight(booking_token="tok123")
result = _flight_extras(f)
- assert result["booking_token"] == "tok123"
-
- def test_booking_token_excluded_when_empty_string(self):
- f = self._make_flight(booking_token="")
- result = _flight_extras(f)
- assert "booking_token" not in result
-
- def test_booking_token_excluded_when_none(self):
- f = self._make_flight(booking_token=None)
- result = _flight_extras(f)
assert "booking_token" not in result
def test_self_transfer_true_included(self):
@@ -249,3 +245,353 @@ class TestExecuteFlightSearchNetworkError:
)
result = _execute_flight_search(valid_params)
assert result["flights"] == []
+
+
+def _make_bookable_leg(code="BA", number="178"):
+ """Build a flight leg mock with optional fields set to None for clean serialization."""
+ leg = MagicMock()
+ airline = MagicMock()
+ airline.name = code
+ leg.airline = airline
+ leg.flight_number = number
+ leg.departure_airport = "JFK"
+ leg.arrival_airport = "LHR"
+ leg.departure_datetime = None
+ leg.arrival_datetime = None
+ leg.duration = 420
+ leg.departure_airport_name = None
+ leg.arrival_airport_name = None
+ leg.operating_airline = None
+ leg.aircraft = None
+ leg.legroom = None
+ leg.overnight = False
+ leg.amenities = None
+ return leg
+
+
+def _make_bookable_flight(legs=None, price=342.0):
+ flight = MagicMock()
+ flight.legs = legs or [_make_bookable_leg()]
+ flight.price = price
+ flight.currency = "USD"
+ flight.layovers = None
+ flight.primary_airline = None
+ flight.primary_airline_name = None
+ flight.self_transfer = None
+ flight.mixed_cabin = None
+ flight.booking_token = "tok"
+ return flight
+
+
+def _make_option_helper():
+ opt = MagicMock()
+ opt.vendor_name = "American Airlines"
+ opt.vendor_code = "AA"
+ opt.fare_name = "Main Cabin"
+ opt.currency = "USD"
+ opt.booking_url = "https://book.aa.com/x"
+ opt.google_click_url = "https://www.google.com/x"
+ opt.price = 342.0
+ opt.is_airline_direct = True
+ return opt
+
+
+class TestGoogleFlightsUrl:
+ def _url(self, **kwargs):
+ from fli.models import Airport
+
+ defaults = {
+ "origins": [Airport.JFK],
+ "destinations": [Airport.LHR],
+ "departure_date": "2026-12-01",
+ "return_date": None,
+ "currency": None,
+ "language": None,
+ "country": None,
+ }
+ defaults.update(kwargs)
+ return _google_flights_url(
+ defaults["origins"],
+ defaults["destinations"],
+ defaults["departure_date"],
+ defaults["return_date"],
+ defaults["currency"],
+ defaults["language"],
+ defaults["country"],
+ )
+
+ def test_one_way_contains_route_and_date(self):
+ url = self._url()
+ assert url.startswith("https://www.google.com/travel/flights?q=")
+ assert "JFK" in url
+ assert "LHR" in url
+ assert "2026-12-01" in url
+
+ def test_round_trip_includes_return_date(self):
+ url = self._url(return_date="2026-12-10")
+ assert "2026-12-10" in url
+
+ def test_locale_params_appended(self):
+ url = self._url(currency="EUR", language="en-GB", country="GB")
+ assert "curr=EUR" in url
+ assert "hl=en-GB" in url
+ assert "gl=GB" in url
+
+ def test_uses_first_airport_when_multiple(self):
+ from fli.models import Airport
+
+ url = self._url(origins=[Airport.JFK, Airport.LGA], destinations=[Airport.LHR])
+ assert "JFK" in url
+ assert "LGA" not in url
+
+
+class TestMatchFlight:
+ def test_match_by_bare_number(self):
+ flight = _make_bookable_flight(legs=[_make_bookable_leg("BA", "178")])
+ assert _match_flight([flight], ["178"]) is flight
+
+ def test_match_by_airline_prefixed(self):
+ flight = _make_bookable_flight(legs=[_make_bookable_leg("BA", "178")])
+ assert _match_flight([flight], ["BA178"]) is flight
+
+ def test_match_is_case_insensitive(self):
+ flight = _make_bookable_flight(legs=[_make_bookable_leg("BA", "178")])
+ assert _match_flight([flight], ["ba178"]) is flight
+
+ def test_no_match_returns_none(self):
+ flight = _make_bookable_flight(legs=[_make_bookable_leg("BA", "178")])
+ assert _match_flight([flight], ["ZZ999"]) is None
+
+ def test_none_defaults_to_first(self):
+ first = _make_bookable_flight(legs=[_make_bookable_leg("BA", "1")])
+ second = _make_bookable_flight(legs=[_make_bookable_leg("AA", "2")])
+ assert _match_flight([first, second], None) is first
+
+ def test_round_trip_tuple_matched_in_order(self):
+ outbound = _make_bookable_flight(legs=[_make_bookable_leg("AA", "100")])
+ inbound = _make_bookable_flight(legs=[_make_bookable_leg("AA", "200")])
+ combo = (outbound, inbound)
+ assert _match_flight([combo], ["AA100", "AA200"]) is combo
+
+ def test_wrong_leg_count_does_not_match(self):
+ flight = _make_bookable_flight(legs=[_make_bookable_leg("BA", "178")])
+ assert _match_flight([flight], ["BA178", "BA179"]) is None
+
+ def test_match_when_flight_number_pre_prefixed(self):
+ """Pre-prefixed flight_number ('BA178') still matches both forms.
+
+ Guards against a double-prefix ('BABA178') if the decoder ever yields
+ an already-prefixed flight number; both bare and prefixed caller forms
+ must resolve.
+ """
+ flight = _make_bookable_flight(legs=[_make_bookable_leg("BA", "BA178")])
+ assert _match_flight([flight], ["178"]) is flight
+ assert _match_flight([flight], ["BA178"]) is flight
+
+
+class TestSerializeDateResult:
+ def _make_date_result(self, dates, price=350.0, currency="USD"):
+ dr = MagicMock()
+ dr.date = dates
+ dr.price = price
+ dr.currency = currency
+ return dr
+
+ def test_date_is_yyyy_mm_dd_string_one_way(self):
+ from datetime import datetime
+
+ from fli.models import Airport
+
+ dr = self._make_date_result((datetime(2026, 3, 15),))
+ out = _serialize_date_result(dr, [Airport.JFK], [Airport.LHR], (None, None, None))
+ assert out["date"] == "2026-03-15"
+ assert isinstance(out["date"], str)
+ assert out["return_date"] is None
+
+ def test_date_and_return_date_strings_round_trip(self):
+ from datetime import datetime
+
+ from fli.models import Airport
+
+ dr = self._make_date_result((datetime(2026, 3, 15), datetime(2026, 3, 22)))
+ out = _serialize_date_result(dr, [Airport.JFK], [Airport.LHR], (None, None, None))
+ assert out["date"] == "2026-03-15"
+ assert out["return_date"] == "2026-03-22"
+ assert "booking_url" in out
+
+
+class TestSerializeBookingOption:
+ def _make_option(self, **overrides):
+ opt = MagicMock()
+ opt.vendor_name = None
+ opt.vendor_code = None
+ opt.fare_name = None
+ opt.currency = None
+ opt.booking_url = None
+ opt.google_click_url = None
+ opt.price = None
+ opt.is_airline_direct = False
+ for k, v in overrides.items():
+ setattr(opt, k, v)
+ return opt
+
+ def test_populated_fields_included(self):
+ opt = self._make_option(
+ vendor_name="American Airlines",
+ booking_url="https://aa.com/book",
+ price=342.0,
+ currency="USD",
+ is_airline_direct=True,
+ )
+ result = _serialize_booking_option(opt)
+ assert result["vendor_name"] == "American Airlines"
+ assert result["booking_url"] == "https://aa.com/book"
+ assert result["price"] == 342.0
+ assert result["is_airline_direct"] is True
+
+ def test_empty_option_serializes_to_empty_dict(self):
+ result = _serialize_booking_option(self._make_option())
+ assert result == {}
+
+ def test_airline_direct_false_excluded(self):
+ opt = self._make_option(vendor_name="Expedia", is_airline_direct=False)
+ result = _serialize_booking_option(opt)
+ assert "is_airline_direct" not in result
+
+
+class TestSearchReturnsBookingUrl:
+ @pytest.fixture
+ def params(self):
+ return FlightSearchParams(origin="JFK", destination="LHR", departure_date="2026-12-01")
+
+ def test_booking_url_present_on_success(self, monkeypatch, params):
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ result = _execute_flight_search(params)
+ assert result["success"] is True
+ assert "booking_url" in result
+ assert "JFK" in result["booking_url"]
+
+ def test_per_flight_booking_url_in_flights_array(self, monkeypatch, params):
+ """Each flight in the flights[] array carries its own booking_url."""
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ # Monkeypatch build_flight_booking_url to return a recognisable value
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.build_flight_booking_url",
+ lambda self, f, **kw: "https://www.google.com/travel/flights/booking?tfs=TEST",
+ )
+ result = _execute_flight_search(params)
+ assert result["success"] is True
+ assert result["flights"][0]["booking_url"] == (
+ "https://www.google.com/travel/flights/booking?tfs=TEST"
+ )
+
+ def test_top_level_search_booking_url_still_present(self, monkeypatch, params):
+ """The top-level search booking_url (q= link) is kept alongside per-flight links."""
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ result = _execute_flight_search(params)
+ assert result["success"] is True
+ # Top-level booking_url points to the search page, not a specific flight
+ assert "q=" in result["booking_url"]
+ # Per-flight booking_url is in each flight dict
+ assert "booking_url" in result["flights"][0]
+
+ def test_booking_url_present_when_no_flights(self, monkeypatch, params):
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: None,
+ )
+ result = _execute_flight_search(params)
+ assert result["count"] == 0
+ assert "booking_url" in result
+
+
+class TestExecuteBookingOptions:
+ @pytest.fixture
+ def params(self):
+ return FlightSearchParams(origin="JFK", destination="LHR", departure_date="2026-12-01")
+
+ def test_returns_options_with_booking_url(self, monkeypatch, params):
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.get_booking_options",
+ lambda self, *a, **k: [_make_option_helper()],
+ )
+ result = _execute_booking_options(params, ["BA178"])
+ assert result["success"] is True
+ assert result["count"] == 1
+ assert result["options"][0]["booking_url"] == "https://book.aa.com/x"
+ assert "selected_flight" in result
+ assert "booking_url" in result
+
+ def test_selected_flight_has_per_flight_booking_url(self, monkeypatch, params):
+ """selected_flight in booking-options response carries its own booking_url."""
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.get_booking_options",
+ lambda self, *a, **k: [_make_option_helper()],
+ )
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.build_flight_booking_url",
+ lambda self, f, **kw: "https://www.google.com/travel/flights/booking?tfs=SEL",
+ )
+ result = _execute_booking_options(params, ["BA178"])
+ assert result["success"] is True
+ assert result["selected_flight"]["booking_url"] == (
+ "https://www.google.com/travel/flights/booking?tfs=SEL"
+ )
+
+ def test_no_match_lists_available_flights(self, monkeypatch, params):
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ result = _execute_booking_options(params, ["ZZ999"])
+ assert result["success"] is False
+ assert result["available_flights"] == [["BA178"]]
+
+ def test_no_flights_returns_empty_options(self, monkeypatch, params):
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: None,
+ )
+ result = _execute_booking_options(params, None)
+ assert result["success"] is True
+ assert result["options"] == []
+
+ def test_empty_vendor_list_adds_fallback_note(self, monkeypatch, params):
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.get_booking_options",
+ lambda self, *a, **k: [],
+ )
+ result = _execute_booking_options(params, ["BA178"])
+ assert result["success"] is True
+ assert result["options"] == []
+ assert "booking_url" in result
+ assert "note" in result
+ assert "booking_url" in result["note"]
diff --git a/tests/search/test_booking_capture.py b/tests/search/test_booking_capture.py
deleted file mode 100644
index e76d88f..0000000
--- a/tests/search/test_booking_capture.py
+++ /dev/null
@@ -1,97 +0,0 @@
-"""Smoke tests for the optional Playwright-based booking-token capturer.
-
-The actual browser run is opt-in (requires the ``playwright`` package
-plus ``playwright install chromium``); these tests only verify the
-public API surface, the import-error path, and the helper logic that
-doesn't need Playwright at all.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import sys
-from unittest.mock import patch
-
-import pytest
-
-from fli.models import Airline, Airport, FlightLeg, FlightResult
-from fli.search._booking_capture import _flight_aria_pattern, _format_iata
-
-
-def _result(airline: Airline, flight_no: str, dep_hour: int, dep_min: int) -> FlightResult:
- from datetime import datetime
-
- return FlightResult(
- legs=[
- FlightLeg(
- airline=airline,
- flight_number=flight_no,
- departure_airport=Airport.JFK,
- arrival_airport=Airport.LAX,
- departure_datetime=datetime(2026, 7, 15, dep_hour, dep_min),
- arrival_datetime=datetime(2026, 7, 15, dep_hour + 6, dep_min),
- duration=360,
- )
- ],
- price=347,
- currency="USD",
- duration=360,
- stops=0,
- )
-
-
-class TestFormatIata:
- def test_from_airport_enum(self):
- assert _format_iata(Airport.JFK) == "JFK"
-
- def test_from_airport_with_leading_underscore(self):
- # Some airline codes start with a digit and the enum prefixes "_";
- # _format_iata is also used for airports, exercise the same path.
- assert _format_iata(Airport.LAX) == "LAX"
-
- def test_from_plain_string(self):
- assert _format_iata("ATH") == "ATH"
-
-
-class TestFlightAriaPattern:
- def test_pattern_includes_departure_time(self):
- flight = _result(Airline.AA, "171", 6, 0)
- pattern = _flight_aria_pattern(flight)
- assert "6:00 AM" in pattern
- assert pattern.endswith("on")
-
- def test_pattern_uses_12_hour_format(self):
- flight_pm = _result(Airline.DL, "100", 17, 30)
- pattern = _flight_aria_pattern(flight_pm)
- assert "5:30 PM" in pattern
-
- def test_pattern_handles_midnight(self):
- flight = _result(Airline.AA, "1", 0, 15)
- pattern = _flight_aria_pattern(flight)
- # ``%-I`` gives 12 for midnight on POSIX.
- assert "12:15 AM" in pattern
-
-
-class TestImportErrorPath:
- def test_raises_clear_import_error_when_playwright_missing(self):
- """When Playwright isn't installed, the helper raises a clear ImportError."""
- from fli.search import _booking_capture
-
- # Patch the import to simulate Playwright being unavailable.
- original_modules = dict(sys.modules)
- # Drop any cached playwright.async_api so the import is re-attempted.
- sys.modules.pop("playwright", None)
- sys.modules.pop("playwright.async_api", None)
- try:
- with patch.dict(sys.modules, {"playwright": None, "playwright.async_api": None}):
- with pytest.raises(ImportError, match="Playwright"):
- asyncio.run(
- _booking_capture.capture_booking_token(
- outbound=_result(Airline.AA, "171", 6, 0),
- return_flight=None,
- travel_date="2026-07-15",
- )
- )
- finally:
- sys.modules.clear()
- sys.modules.update(original_modules)
diff --git a/tests/search/test_booking_url.py b/tests/search/test_booking_url.py
new file mode 100644
index 0000000..2a0b6ab
--- /dev/null
+++ b/tests/search/test_booking_url.py
@@ -0,0 +1,233 @@
+"""Tests for SearchFlights.build_flight_booking_url.
+
+All tests are purely in-process: no network calls, no live API.
+"""
+
+from __future__ import annotations
+
+import urllib.parse
+from datetime import datetime, timezone
+from unittest.mock import MagicMock
+
+from fli.models import Airline, Airport, FlightLeg, FlightResult
+from fli.search.flights import SearchFlights
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_leg(
+ airline: Airline,
+ flight_number: str,
+ departure_airport: Airport,
+ arrival_airport: Airport,
+ dep_date: str,
+) -> FlightLeg:
+ """Build a minimal FlightLeg with a real departure_datetime."""
+ dt = datetime.fromisoformat(f"{dep_date}T08:00:00").replace(tzinfo=timezone.utc)
+ return FlightLeg(
+ airline=airline,
+ flight_number=flight_number,
+ departure_airport=departure_airport,
+ arrival_airport=arrival_airport,
+ departure_datetime=dt,
+ arrival_datetime=dt.replace(hour=10),
+ duration=120,
+ )
+
+
+def _one_way(airline=Airline.AA, flight_number="1", price=100.0) -> FlightResult:
+ return FlightResult(
+ price=price,
+ duration=120,
+ stops=0,
+ legs=[_make_leg(airline, flight_number, Airport.SFO, Airport.PHX, "2026-09-01")],
+ )
+
+
+def _round_trip(price=200.0) -> tuple[FlightResult, FlightResult]:
+ outbound = FlightResult(
+ price=price,
+ duration=180,
+ stops=0,
+ legs=[_make_leg(Airline.AA, "100", Airport.JFK, Airport.LAX, "2026-09-01")],
+ )
+ inbound = FlightResult(
+ price=None,
+ duration=180,
+ stops=0,
+ legs=[_make_leg(Airline.AA, "200", Airport.LAX, Airport.JFK, "2026-09-08")],
+ )
+ return (outbound, inbound)
+
+
+def _connection(price=150.0) -> FlightResult:
+ dt1 = datetime.fromisoformat("2026-09-01T08:00:00").replace(tzinfo=timezone.utc)
+ dt2 = datetime.fromisoformat("2026-09-01T12:00:00").replace(tzinfo=timezone.utc)
+ return FlightResult(
+ price=price,
+ duration=360,
+ stops=1,
+ legs=[
+ FlightLeg(
+ airline=Airline.UA,
+ flight_number="101",
+ departure_airport=Airport.SFO,
+ arrival_airport=Airport.ORD,
+ departure_datetime=dt1,
+ arrival_datetime=dt1.replace(hour=12),
+ duration=240,
+ ),
+ FlightLeg(
+ airline=Airline.UA,
+ flight_number="202",
+ departure_airport=Airport.ORD,
+ arrival_airport=Airport.JFK,
+ departure_datetime=dt2,
+ arrival_datetime=dt2.replace(hour=15),
+ duration=120,
+ ),
+ ],
+ )
+
+
+def _make_client() -> SearchFlights:
+ # build_flight_booking_url needs no session id or HTTP client — the tfs
+ # token is fully deterministic from the itinerary.
+ client = SearchFlights.__new__(SearchFlights)
+ client._last_session_id = None
+ client.client = MagicMock()
+ return client
+
+
+# ---------------------------------------------------------------------------
+# URL structure tests
+# ---------------------------------------------------------------------------
+
+
+class TestBuildFlightBookingUrl:
+ def test_one_way_has_tfs(self):
+ client = _make_client()
+ url = client.build_flight_booking_url(_one_way())
+ assert url.startswith("https://www.google.com/travel/flights/booking?tfs=")
+
+ def test_round_trip_has_tfs(self):
+ client = _make_client()
+ url = client.build_flight_booking_url(_round_trip())
+ assert "tfs=" in url
+
+ def test_tfs_no_padding_or_standard_b64(self):
+ client = _make_client()
+ url = client.build_flight_booking_url(_one_way())
+ tfs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["tfs"][0]
+ assert "=" not in tfs
+ assert "+" not in tfs
+ assert "/" not in tfs
+
+ def test_no_tfu_param_emitted(self):
+ # tfu adds no value over tfs (tfs-only lands on the specific-flight
+ # booking page with vendor fares), so it is never emitted — even when
+ # a session id is cached.
+ client = _make_client()
+ client._last_session_id = "sess123"
+ url = client.build_flight_booking_url(_one_way(price=100.0))
+ assert "tfu" not in url
+
+ def test_deterministic_same_itinerary_same_url(self):
+ # No session id / network state means the same itinerary always yields
+ # an identical URL (cacheable, reproducible).
+ client = _make_client()
+ a = client.build_flight_booking_url(_one_way())
+ client._last_session_id = "some-session"
+ b = client.build_flight_booking_url(_one_way())
+ assert a == b
+
+ def test_locale_params_appended(self):
+ client = _make_client()
+ url = client.build_flight_booking_url(
+ _one_way(), currency="EUR", language="en-GB", country="GB"
+ )
+ assert "curr=EUR" in url
+ assert "hl=en-GB" in url
+ assert "gl=GB" in url
+
+ def test_no_locale_params_when_not_provided(self):
+ client = _make_client()
+ url = client.build_flight_booking_url(_one_way())
+ assert "curr=" not in url
+ assert "hl=" not in url
+ assert "gl=" not in url
+
+ def test_connection_flight_uses_each_leg_in_tfs(self):
+ client = _make_client()
+ flight = _connection()
+ url = client.build_flight_booking_url(flight)
+ # Decode tfs and verify both legs are encoded
+ import base64
+
+ tfs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["tfs"][0]
+ pad = "=" * ((4 - len(tfs) % 4) % 4)
+ raw = base64.urlsafe_b64decode(tfs + pad)
+ # Both flight numbers and airports should appear in proto bytes
+ assert b"101" in raw
+ assert b"202" in raw
+ assert b"ORD" in raw
+
+ def test_round_trip_two_segments_in_tfs(self):
+ client = _make_client()
+ import base64
+
+ url = client.build_flight_booking_url(_round_trip())
+ tfs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["tfs"][0]
+ pad = "=" * ((4 - len(tfs) % 4) % 4)
+ raw = base64.urlsafe_b64decode(tfs + pad)
+ # f3 field (tag 0x1a = 26) should appear at least twice (two segments)
+ assert raw.count(b"\x1a") >= 2
+
+ def test_digit_prefixed_airline_code(self):
+ """Frontier (F9 — enum _F9 with underscore prefix) encodes as 'F9'."""
+ import base64
+
+ client = _make_client()
+ # Use a mock airline with underscore prefix in name to simulate _F9
+ mock_leg = MagicMock()
+ mock_airline = MagicMock()
+ mock_airline.name = "_F9"
+ mock_leg.airline = mock_airline
+ mock_leg.flight_number = "2638"
+ mock_dep = MagicMock()
+ mock_dep.name = "SFO"
+ mock_arr = MagicMock()
+ mock_arr.name = "PHX"
+ mock_leg.departure_airport = mock_dep
+ mock_leg.arrival_airport = mock_arr
+ dep_dt = datetime.fromisoformat("2026-09-01T08:00:00").replace(tzinfo=timezone.utc)
+ mock_leg.departure_datetime = dep_dt
+
+ flight = MagicMock()
+ flight.legs = [mock_leg]
+ flight.price = 89.0
+ flight.currency = "USD"
+
+ url = client.build_flight_booking_url(flight)
+ tfs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["tfs"][0]
+ pad = "=" * ((4 - len(tfs) % 4) % 4)
+ raw = base64.urlsafe_b64decode(tfs + pad)
+ # Should encode 'F9', not '_F9'
+ assert b"F9" in raw
+ assert b"_F9" not in raw
+
+ def test_never_raises_on_bad_data(self):
+ """Method must not raise even when flight data is malformed."""
+ client = _make_client()
+ bad_flight = MagicMock()
+ bad_flight.legs = [MagicMock(departure_datetime=None)]
+ # Should not raise; falls back to a Google Flights URL
+ url = client.build_flight_booking_url(bad_flight)
+ assert "google.com" in url
+
+ def test_returns_string(self):
+ client = _make_client()
+ result = client.build_flight_booking_url(_one_way())
+ assert isinstance(result, str)
diff --git a/tests/search/test_proto.py b/tests/search/test_proto.py
index 553936f..0edb79b 100644
--- a/tests/search/test_proto.py
+++ b/tests/search/test_proto.py
@@ -1,12 +1,8 @@
-"""Tests for the GetBookingResults protobuf token builder + tfu URL parser.
+"""Tests for the GetBookingResults protobuf token builder and tfs deep-link token.
The builder reproduces a byte-perfect copy of the captured token from a
live booking-page URL. The captured fixture is the authoritative
reference — any change to the builder must keep this byte-equal.
-
-The tfu parser extracts the same booking token from a ``tfu=`` URL
-parameter — the value Google's UI puts in the booking-page URL after a
-user clicks "Select flight".
"""
from __future__ import annotations
@@ -16,10 +12,10 @@ import base64
import pytest
from fli.search._proto import (
+ LegSpec,
build_booking_token,
+ build_tfs_token,
decode_booking_token,
- extract_booking_token_from_tfu,
- extract_session_id_from_tfu,
)
# Captured live from a real booking page (2026-05-14):
@@ -153,54 +149,6 @@ class TestDecodeBookingTokenEdgeCases:
decode_booking_token(bad_token)
-# Live `tfu` URL parameter captured 2026-05-14 from a JFK→LAX RT booking page.
-LIVE_TFU = (
- "CmxDalJJVVZwUk1FOUJjRVZyZEVWQlEzaFRkVkZDUnkwdExTMHRMUzB0TFhCcVltWjZOMEZCUVVGQlIyOUd"
- "PVlpGU0U5SVVXRkJFZ1pCUVRJNEl6RWFDd2o0amdJUUFob0RWVk5FT0J4dytJNEMSAggAIgA"
-)
-LIVE_BOOKING_URL = (
- "https://www.google.com/travel/flights/booking"
- "?tfs=CBwQAho_EgoyMDI2LTA3LTE1Ih8KA0pGSxIKMjAyNi0wNy0xNRoDTEFYKgJBQTIDMTcxagcIAR"
- "IDSkZLcgcIARIDTEFYGj4SCjIwMjYtMDctMTkiHgoDTEFYEgoyMDI2LTA3LTE5GgNKRksqAkFBMgIy"
- "OGoHCAESA0xBWHIHCAESA0pGS0ABSAFwAYIBCwj___________8BmAEB"
- f"&tfu={LIVE_TFU}&hl=en&gl=US&curr=USD"
-)
-
-
-class TestExtractBookingTokenFromTfu:
- def test_extract_from_bare_tfu_value(self):
- token = extract_booking_token_from_tfu(LIVE_TFU)
- # The extracted bytes must decode back to a recognisable booking token.
- decoded = decode_booking_token(token)
- assert decoded["field_2"] == "AA28#1"
- assert decoded["field_3"]["field_3"] == "USD"
-
- def test_extract_from_full_booking_url(self):
- token_url = extract_booking_token_from_tfu(LIVE_BOOKING_URL)
- token_bare = extract_booking_token_from_tfu(LIVE_TFU)
- assert token_url == token_bare
-
- def test_extract_session_id_round_trip(self):
- session = extract_session_id_from_tfu(LIVE_TFU)
- # 50-ish base64-alphabet bytes, starts with H, has "--" separator
- assert isinstance(session, str)
- assert len(session) > 30
- assert session.startswith("H")
- assert "-" in session
-
- def test_url_without_tfu_param_rejected(self):
- with pytest.raises(ValueError):
- extract_booking_token_from_tfu(
- "https://www.google.com/travel/flights/booking?tfs=ABC&hl=en"
- )
-
- def test_invalid_base64_rejected(self):
- # Garbage input should raise ValueError (specific message varies
- # by which validation step rejects first).
- with pytest.raises(ValueError):
- extract_booking_token_from_tfu("!!!!not-valid-base64!!!!")
-
-
@pytest.mark.parametrize(
"data, expected",
[
@@ -222,42 +170,158 @@ def test_read_varint_truncated_raises():
_read_varint(b"\x80", 0) # MSB set but no continuation byte
-class TestExtractBookingTokenFromTfuEdgeCases:
- """edge-case wire types that appear before field 1 in the outer tfu protobuf."""
-
- def _encode_tfu(self, raw: bytes) -> str:
- return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
-
- @pytest.mark.parametrize(
- "prefix_bytes, token_bytes",
- [
- # field 2, wire 5 (fixed32): tag 0x15, 4 bytes
- (bytes([0x15]) + bytes([0x00, 0x00, 0x00, 0x01]), b"testtoken"),
- # field 3, wire 1 (fixed64): (3 << 3) | 1 = 0x19, 8 bytes
- (bytes([0x19]) + bytes(8), b"mytoken"),
- ],
- )
- def test_non_field1_wire_types_skipped(self, prefix_bytes, token_bytes):
- field1 = bytes([0x0A]) + bytes([len(token_bytes)]) + token_bytes
- tfu = self._encode_tfu(prefix_bytes + field1)
- assert extract_booking_token_from_tfu(tfu) == token_bytes.decode("ascii")
-
- def test_no_field1_raises_value_error(self):
- from fli.search._proto import _varint_field
-
- # Only field 2 as a varint — no field 1 present.
- raw = _varint_field(2, 42)
- tfu = self._encode_tfu(raw)
- with pytest.raises(ValueError, match="no field 1"):
- extract_booking_token_from_tfu(tfu)
-
- def test_unsupported_wire_type_raises_value_error(self):
- # Wire type 3 (start group) is not handled.
- # Tag for field 1, wire 3 = (1 << 3) | 3 = 11
- raw = bytes([11])
- tfu = self._encode_tfu(raw)
- with pytest.raises(ValueError, match="unsupported wire type"):
- extract_booking_token_from_tfu(tfu)
+# ---------------------------------------------------------------------------
+# Captured tfs booking-URL fixtures (2026-05-28)
+# ---------------------------------------------------------------------------
+
+# Round-trip JFK→LAX (AA171 outbound, AA28 return) — the authoritative
+# round-trip fixture, captured byte-for-byte from a live booking-page tfs.
+_LIVE_TFS_RT = (
+ "CBwQAho_EgoyMDI2LTA3LTE1Ih8KA0pGSxIKMjAyNi0wNy0xNRoDTEFYKgJBQTIDMTcxagcIAR"
+ "IDSkZLcgcIARIDTEFYGj4SCjIwMjYtMDctMTkiHgoDTEFYEgoyMDI2LTA3LTE5GgNKRksqAkFBMgIy"
+ "OGoHCAESA0xBWHIHCAESA0pGS0ABSAFwAYIBCwj___________8BmAEB"
+)
+
+# One-way nonstop LAX→ORD (UA729), captured 2026-05-28. No segment-level f5
+# field — matches encoder output byte-for-byte.
+_LIVE_TFS_OW = (
+ "CBwQAho_EgoyMDI2LTA4LTE1Ih8KA0xBWBIKMjAyNi0wOC0xNRoDT1JEKgJVQTIDNzI5"
+ "agcIARIDTEFYcgcIARIDT1JEQAFIAXABggELCP___________wGYAQI"
+)
+
+# One-way 2-stop BOS→DEN(WN739)→SJC(WN389)→SEA(WN389), captured 2026-05-28.
+# Three repeated f4 legs within one f3 segment.
+_LIVE_TFS_3LEG = (
+ "CBwQAhqBARIKMjAyNi0wOC0xNSIfCgNCT1MSCjIwMjYtMDgtMTUaA0RFTioCV04yAzczOSIfCgNERU4S"
+ "CjIwMjYtMDgtMTUaA1NKQyoCV04yAzM4OSIfCgNTSkMSCjIwMjYtMDgtMTUaA1NFQSoCV04yAzM4OWoH"
+ "CAESA0JPU3IHCAESA1NFQUABSAFwAYIBCwj___________8BmAEC"
+)
+
+
+def _b64url_to_bytes(s: str) -> bytes:
+ """Decode a urlsafe-base64 string (padding optional) to raw bytes."""
+ pad = "=" * ((4 - len(s) % 4) % 4)
+ return base64.urlsafe_b64decode(s + pad)
+
+
+class TestBuildTfsToken:
+ """Byte-perfect golden tests for build_tfs_token."""
+
+ def _tfs_bytes(self, tfs: str) -> bytes:
+ return _b64url_to_bytes(tfs)
+
+ def test_round_trip_byte_perfect(self):
+ """Two-segment round-trip reproduces the captured booking-page tfs byte-for-byte."""
+ segments = [
+ # Outbound: JFK→LAX on 2026-07-15, AA171
+ [LegSpec("JFK", "2026-07-15", "LAX", "AA", "171")],
+ # Return: LAX→JFK on 2026-07-19, AA28
+ [LegSpec("LAX", "2026-07-19", "JFK", "AA", "28")],
+ ]
+ built = build_tfs_token(segments, is_one_way=False)
+ capt_hex = self._tfs_bytes(_LIVE_TFS_RT).hex()
+ built_hex = _b64url_to_bytes(built).hex()
+ assert self._tfs_bytes(built) == self._tfs_bytes(_LIVE_TFS_RT), (
+ f"\nbuilt: {built_hex}\ncapt: {capt_hex}"
+ )
+
+ def test_one_way_nonstop_byte_perfect(self):
+ """One-way nonstop (LAX→ORD UA729) reproduces captured tfs byte-for-byte."""
+ segments = [[LegSpec("LAX", "2026-08-15", "ORD", "UA", "729")]]
+ built = build_tfs_token(segments, is_one_way=True)
+ capt_hex = self._tfs_bytes(_LIVE_TFS_OW).hex()
+ built_hex = _b64url_to_bytes(built).hex()
+ assert self._tfs_bytes(built) == self._tfs_bytes(_LIVE_TFS_OW), (
+ f"\nbuilt: {built_hex}\ncapt: {capt_hex}"
+ )
+
+ def test_multi_leg_connection_byte_perfect(self):
+ """Three-leg connection BOS→DEN→SJC→SEA reproduces captured tfs byte-for-byte."""
+ segments = [
+ [
+ LegSpec("BOS", "2026-08-15", "DEN", "WN", "739"),
+ LegSpec("DEN", "2026-08-15", "SJC", "WN", "389"),
+ LegSpec("SJC", "2026-08-15", "SEA", "WN", "389"),
+ ]
+ ]
+ built = build_tfs_token(segments, is_one_way=True)
+ capt_hex = self._tfs_bytes(_LIVE_TFS_3LEG).hex()
+ built_hex = _b64url_to_bytes(built).hex()
+ assert self._tfs_bytes(built) == self._tfs_bytes(_LIVE_TFS_3LEG), (
+ f"\nbuilt: {built_hex}\ncapt: {capt_hex}"
+ )
+
+ def test_f19_one_way_is_2(self):
+ built = build_tfs_token(
+ [[LegSpec("SFO", "2026-09-01", "PHX", "AA", "100")]], is_one_way=True
+ )
+ raw = _b64url_to_bytes(built)
+ # f19 tag: (19 << 3) | 0 = 152 = 0x98 (needs second varint byte 0x01); value = 2
+ assert raw[-3:] == bytes([0x98, 0x01, 0x02])
+
+ def test_f19_round_trip_is_1(self):
+ segs = [
+ [LegSpec("JFK", "2026-09-01", "LAX", "AA", "1")],
+ [LegSpec("LAX", "2026-09-08", "JFK", "AA", "2")],
+ ]
+ built = build_tfs_token(segs, is_one_way=False)
+ raw = _b64url_to_bytes(built)
+ # f19 tag 0x98 0x01; value = 1
+ assert raw[-3:] == bytes([0x98, 0x01, 0x01])
+
+ def test_urlsafe_no_padding(self):
+ built = build_tfs_token([[LegSpec("SFO", "2026-09-01", "PHX", "AA", "100")]])
+ assert "=" not in built
+ assert "+" not in built
+ assert "/" not in built
+
+ def test_empty_segments_raises(self):
+ with pytest.raises(ValueError, match="non-empty"):
+ build_tfs_token([])
+
+ def test_empty_leg_list_raises(self):
+ with pytest.raises(ValueError, match="no legs"):
+ build_tfs_token([[]])
+
+ def test_multi_leg_connection_repeated_f4(self):
+ """Three legs in one segment → three repeated f4 fields (verified by byte count)."""
+ segments = [
+ [
+ LegSpec("BOS", "2026-08-15", "DEN", "WN", "739"),
+ LegSpec("DEN", "2026-08-15", "SJC", "WN", "389"),
+ LegSpec("SJC", "2026-08-15", "SEA", "WN", "389"),
+ ]
+ ]
+ built = build_tfs_token(segments, is_one_way=True)
+ raw = _b64url_to_bytes(built)
+ assert len(raw) == 159, f"expected 159 bytes, got {len(raw)}"
+
+ def test_f9_airline_code_in_proto(self):
+ """Frontier (F9) airline code is correctly encoded in the proto bytes."""
+ segments = [[LegSpec("SFO", "2026-09-01", "PHX", "F9", "2638")]]
+ built = build_tfs_token(segments)
+ raw = _b64url_to_bytes(built)
+ assert b"F9" in raw
+
+
+class TestToUrlsafeB64:
+ def test_converts_standard_to_urlsafe(self):
+ from fli.search._proto import _to_urlsafe_b64
+
+ # Bytes that produce + and / in standard base64
+ data = bytes([0xFB, 0xFF]) # standard b64: +/8=
+ result = _to_urlsafe_b64(data)
+ assert "+" not in result
+ assert "/" not in result
+ assert "=" not in result
+
+ def test_round_trips_to_original_bytes(self):
+ from fli.search._proto import _to_urlsafe_b64
+
+ data = b"\xde\xad\xbe\xef"
+ encoded = _to_urlsafe_b64(data)
+ pad = "=" * ((4 - len(encoded) % 4) % 4)
+ assert base64.urlsafe_b64decode(encoded + pad) == data
class TestDecodeBookingTokenHexFallback: