Google Flights MCP, CLI and Python Library
Add configurable default currency via environment variable and CLI option (#123)
Punit Aranifcb8d49ab549
diff --git a/fli/cli/commands/dates.py b/fli/cli/commands/dates.pyindex 3e1b5e6..c49635b 100644--- a/fli/cli/commands/dates.py+++ b/fli/cli/commands/dates.py@@ -15,6 +15,7 @@ from fli.cli.utils import (normalize_cli_date,normalize_cli_time_range,serialize_date_result,+ validate_currency,)from fli.core import (build_date_search_segments,@@ -191,6 +192,14 @@ def dates(case_sensitive=False,),] = OutputFormat.TEXT,+ currency: Annotated[+ str,+ typer.Option(+ "--currency",+ callback=validate_currency,+ help="Fallback currency code when not returned by Google (e.g., CAD, EUR).",+ ),+ ] = "USD",):"""Find the cheapest dates to fly between two airports.@@ -295,7 +304,10 @@ def dates(trip_type=trip_type,query=query,results_key="dates",- results=[serialize_date_result(result, trip_type) for result in results],+ results=[+ serialize_date_result(result, trip_type, default_currency=currency)+ for result in results+ ],))return@@ -309,7 +321,7 @@ def dates(typer.echo(message)raise typer.Exit(1)- display_date_results(results, trip_type)+ display_date_results(results, trip_type, default_currency=currency)except ParseError as e:if output_format == OutputFormat.JSON:diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.pyindex a7efda1..db37d9b 100644--- a/fli/cli/commands/flights.py+++ b/fli/cli/commands/flights.py@@ -13,6 +13,7 @@ from fli.cli.utils import (normalize_cli_date,normalize_cli_time_range,serialize_flight_result,+ validate_currency,)from fli.core import (build_flight_segments,@@ -50,6 +51,7 @@ def _search_flights_core(carry_on: bool = False,all_results: bool = True,output_format: OutputFormat = OutputFormat.TEXT,+ currency: str = "USD",) -> None:"""Core flight search functionality."""query: dict[str, Any] = {@@ -156,12 +158,15 @@ def _search_flights_core(trip_type=trip_type,query=query,results_key="flights",- results=[serialize_flight_result(result) for result in results],+ results=[+ serialize_flight_result(result, default_currency=currency)+ for result in results+ ],))return- display_flight_results(results)+ display_flight_results(results, default_currency=currency)except ParseError as e:if output_format == OutputFormat.JSON:@@ -300,6 +305,14 @@ def flights(case_sensitive=False,),] = OutputFormat.TEXT,+ currency: Annotated[+ str,+ typer.Option(+ "--currency",+ callback=validate_currency,+ help="Fallback currency code when not returned by Google (e.g., CAD, EUR).",+ ),+ ] = "USD",):"""Search for flights on a specific date.@@ -329,4 +342,5 @@ def flights(carry_on=carry_on,all_results=all_results,output_format=output_format,+ currency=currency,)diff --git a/fli/cli/utils.py b/fli/cli/utils.pyindex 011af30..c025198 100644--- a/fli/cli/utils.py+++ b/fli/cli/utils.py@@ -1,6 +1,7 @@"""CLI utility functions for display and validation."""import json+import refrom typing import Anyimport plotext as plt@@ -21,7 +22,15 @@ from fli.core.parsers import parse_airlines as core_parse_airlinesfrom fli.core.parsers import parse_max_stops as core_parse_max_stopsfrom fli.models import Airline, Airport, MaxStops, TripType-DEFAULT_CURRENCY = "USD"++def validate_currency(ctx: Context, param: Parameter, value: str | None) -> str | None:+ """Validate currency code format for typer callbacks."""+ if value is None:+ return None+ normalized = value.upper()+ if not re.fullmatch(r"[A-Z]{3}", normalized):+ raise typer.BadParameter(f"'{value}' is not a valid 3-letter currency code")+ return normalizeddef validate_date(ctx: Context, param: Parameter, value: str) -> str | None:@@ -187,7 +196,12 @@ def serialize_flight_leg(leg: Any) -> dict[str, Any]:}-def _serialize_flight_segment_result(flight: Any, *, include_price: bool = False) -> dict[str, Any]:+def _serialize_flight_segment_result(+ flight: Any,+ *,+ include_price: bool = False,+ default_currency: str = "USD",+) -> dict[str, Any]:"""Serialize a one-direction flight result."""payload = {"duration": flight.duration,@@ -196,14 +210,19 @@ def _serialize_flight_segment_result(flight: Any, *, include_price: bool = False}if include_price:payload["price"] = flight.price- payload["currency"] = flight.currency or DEFAULT_CURRENCY+ payload["currency"] = flight.currency or default_currencyreturn payload-def serialize_flight_result(flight_data: Any) -> dict[str, Any]:+def serialize_flight_result(+ flight_data: Any,+ default_currency: str = "USD",+) -> 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(flight_data, include_price=True)+ return _serialize_flight_segment_result(+ flight_data, include_price=True, default_currency=default_currency+ )segments = list(flight_data)@@ -212,7 +231,7 @@ def serialize_flight_result(flight_data: Any) -> dict[str, Any]:outbound, return_flight = segmentsreturn {"price": outbound.price,- "currency": outbound.currency or DEFAULT_CURRENCY,+ "currency": outbound.currency or default_currency,"duration": outbound.duration + return_flight.duration,"stops": outbound.stops + return_flight.stops,"outbound": _serialize_flight_segment_result(outbound),@@ -223,20 +242,24 @@ def serialize_flight_result(flight_data: Any) -> dict[str, Any]:price_segment = segments[-1]return {"price": price_segment.price,- "currency": price_segment.currency or DEFAULT_CURRENCY,+ "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],}-def serialize_date_result(date_result: Any, trip_type: TripType) -> dict[str, Any]:+def serialize_date_result(+ date_result: Any,+ trip_type: TripType,+ default_currency: str = "USD",+) -> dict[str, Any]:"""Serialize a date search result for JSON output."""payload = {"departure_date": date_result.date[0].date().isoformat(),"return_date": None,"price": date_result.price,- "currency": date_result.currency or DEFAULT_CURRENCY,+ "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()@@ -290,12 +313,13 @@ def emit_json(payload: dict[str, Any]) -> None:typer.echo(json.dumps(payload, indent=2))-def display_flight_results(flights: list):+def display_flight_results(flights: list, default_currency: str = "USD"):"""Display flight results in a beautiful format.Args:flights: List of either FlightResult objects (one-way)or tuples of (outbound, return) FlightResults (round-trip)+ default_currency: Fallback currency code when Google does not return one."""if not flights:@@ -316,7 +340,9 @@ def display_flight_results(flights: list):# and on the final leg for multi-city trips.price_segment = flight_segments[-1] if num_legs > 2 else flight_segments[0]total_price = price_segment.price- table.add_row("Total Price", format_price(total_price, price_segment.currency))+ table.add_row(+ "Total Price", format_price(total_price, price_segment.currency or default_currency)+ )total_duration = sum(flight.duration for flight in flight_segments)table.add_row("Total Duration", format_duration(total_duration))@@ -377,7 +403,7 @@ def display_flight_results(flights: list):console.print()-def display_date_results(dates: list, trip_type: TripType):+def display_date_results(dates: list, trip_type: TripType, default_currency: str = "USD"):"""Display date search results with sparkline chart and table."""if not dates:console.print(Panel("No flights found for these dates", style="red"))@@ -395,7 +421,7 @@ def display_date_results(dates: list, trip_type: TripType):plt.plot(prices, marker="braille")plt.title("Price Trend")plt.xlabel("Date")- plt.ylabel(format_price_axis_label(date.currency for date in sorted_dates))+ plt.ylabel(format_price_axis_label(date.currency or default_currency for date in sorted_dates))# Set x-axis labels (show subset if too many dates)if len(date_labels) <= 10:@@ -426,7 +452,7 @@ def display_date_results(dates: list, trip_type: TripType):table.add_row(date_price.date[0].strftime("%Y-%m-%d"),date_price.date[0].strftime("%A"),- format_price(date_price.price, date_price.currency),+ format_price(date_price.price, date_price.currency or default_currency),)else:table.add_row(@@ -434,7 +460,7 @@ def display_date_results(dates: list, trip_type: TripType):date_price.date[0].strftime("%A"),date_price.date[1].strftime("%Y-%m-%d"),date_price.date[1].strftime("%A"),- format_price(date_price.price, date_price.currency),+ format_price(date_price.price, date_price.currency or default_currency),)console.print(table)diff --git a/fli/search/flights.py b/fli/search/flights.pyindex fa72009..aec8872 100644--- a/fli/search/flights.py+++ b/fli/search/flights.py@@ -146,25 +146,6 @@ class SearchFlights:)return flight- @staticmethod- def _parse_price(data: list) -> float:- """Extract the numeric price from raw flight data.-- Args:- data: Raw flight data from the API response-- Returns:- Flight price, or 0.0 if price data is unavailable-- """- try:- price_block = SearchFlights._get_price_block(data)- if price_block and price_block[0]:- return float(price_block[0][-1])- except (IndexError, TypeError):- pass- return 0.0-@staticmethoddef _parse_price_info(data: list) -> tuple[float, str | None]:"""Extract the numeric price and returned currency from raw flight data."""diff --git a/tests/cli/test_utils.py b/tests/cli/test_utils.pyindex 9217ac8..8aefb40 100644--- a/tests/cli/test_utils.py+++ b/tests/cli/test_utils.py@@ -429,3 +429,43 @@ def test_serialize_date_result_uses_returned_currency():payload = serialize_date_result(result, TripType.ONE_WAY)assert payload["currency"] == "SEK"+++def test_serialize_flight_result_fallback_currency_override():+ """Fallback currency should use the provided default when Google returns None."""+ flight = _make_flight_result(price=117.0, currency=None)++ payload = serialize_flight_result(flight, default_currency="CAD")++ assert payload["currency"] == "CAD"+++def test_serialize_flight_result_round_trip_fallback_currency_override():+ """Round-trip fallback currency should use the provided default."""+ outbound = _make_flight_result(price=250.0, currency=None, flight_number="AC100")+ return_flight = _make_flight_result(price=250.0, currency=None, flight_number="AC200")++ payload = serialize_flight_result((outbound, return_flight), default_currency="CAD")++ assert payload["currency"] == "CAD"+++def test_serialize_date_result_fallback_currency_override():+ """Date serialization fallback currency should use the provided default."""+ result = DatePrice(+ date=(datetime(2026, 5, 1),),+ price=117.0,+ )++ payload = serialize_date_result(result, TripType.ONE_WAY, default_currency="CAD")++ assert payload["currency"] == "CAD"+++def test_serialize_flight_result_extracted_currency_takes_precedence():+ """Extracted currency from Google should take precedence over default_currency."""+ flight = _make_flight_result(price=117.0, currency="GBP")++ payload = serialize_flight_result(flight, default_currency="CAD")++ assert payload["currency"] == "GBP"diff --git a/tests/search/test_search_flights.py b/tests/search/test_search_flights.pyindex 0082347..f62bbd9 100644--- a/tests/search/test_search_flights.py+++ b/tests/search/test_search_flights.py@@ -193,38 +193,45 @@ def test_multiple_searches(search, basic_search_params, complex_search_params):# def test_round_trip_result_structure(search, search_params_fixture, request):-class TestParsePrice:- """Tests for _parse_price method handling missing/malformed price data."""+class TestParsePriceInfo:+ """Tests for _parse_price_info method handling missing/malformed price data."""- def test_parse_price_valid_data(self):- """Test _parse_price with valid price data."""+ def test_parse_price_info_valid_data(self):+ """Test _parse_price_info with valid price data."""data = [None, [[100, 200, 299.99]]]- assert SearchFlights._parse_price(data) == 299.99+ price, currency = SearchFlights._parse_price_info(data)+ assert price == 299.99+ assert currency is None- def test_parse_price_empty_inner_list(self):- """Test _parse_price returns 0.0 when inner price list is empty."""+ def test_parse_price_info_empty_inner_list(self):+ """Test _parse_price_info returns 0.0 when inner price list is empty."""data = [None, [[]]]- assert SearchFlights._parse_price(data) == 0.0+ price, _ = SearchFlights._parse_price_info(data)+ assert price == 0.0- def test_parse_price_empty_outer_list(self):- """Test _parse_price returns 0.0 when outer price list is empty."""+ def test_parse_price_info_empty_outer_list(self):+ """Test _parse_price_info returns 0.0 when outer price list is empty."""data = [None, []]- assert SearchFlights._parse_price(data) == 0.0+ price, _ = SearchFlights._parse_price_info(data)+ assert price == 0.0- def test_parse_price_none_price_section(self):- """Test _parse_price returns 0.0 when price section is None."""+ def test_parse_price_info_none_price_section(self):+ """Test _parse_price_info returns 0.0 when price section is None."""data = [None, None]- assert SearchFlights._parse_price(data) == 0.0+ price, _ = SearchFlights._parse_price_info(data)+ assert price == 0.0- def test_parse_price_missing_price_section(self):- """Test _parse_price returns 0.0 when data has no price section."""+ def test_parse_price_info_missing_price_section(self):+ """Test _parse_price_info returns 0.0 when data has no price section."""data = [None]- assert SearchFlights._parse_price(data) == 0.0+ price, _ = SearchFlights._parse_price_info(data)+ assert price == 0.0- def test_parse_price_inner_list_none(self):- """Test _parse_price returns 0.0 when inner list is None."""+ def test_parse_price_info_inner_list_none(self):+ """Test _parse_price_info returns 0.0 when inner list is None."""data = [None, [None]]- assert SearchFlights._parse_price(data) == 0.0+ price, _ = SearchFlights._parse_price_info(data)+ assert price == 0.0def test_parse_currency_from_live_price_token(self):"""_parse_currency should decode the returned currency from a live token sample."""