Google Flights MCP, CLI and Python Library
fix: round-trip price doubling and MCP list_tools compatibility (#72)
Punit Arani38f18c16d1ac
diff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.mdindex f8c61f0..73d7dec 100644--- a/docs/guides/quickstart.md+++ b/docs/guides/quickstart.md@@ -148,7 +148,7 @@ for outbound, return_flight in results:print(f" {leg.airline.value} {leg.flight_number}")print(f" {leg.departure_datetime} -> {leg.arrival_datetime}")- print(f"\nTotal Price: ${outbound.price + return_flight.price}")+ print(f"\nTotal Price: ${outbound.price}")```3. Date Range Search:diff --git a/examples/complex_round_trip_validation.py b/examples/complex_round_trip_validation.pyindex d48e3e4..b7ae551 100644--- a/examples/complex_round_trip_validation.py+++ b/examples/complex_round_trip_validation.py@@ -105,7 +105,7 @@ def main():for i, (outbound, return_flight) in enumerate(results[:3], 1): # Show first 3 resultsprint(f"\n{'=' * 50}")- print(f"Option {i}: Total Price: ${outbound.price + return_flight.price}")+ print(f"Option {i}: Total Price: ${outbound.price}")print("\n🛫 Outbound Flight:")for leg in outbound.legs:diff --git a/examples/round_trip_search.py b/examples/round_trip_search.pyindex 36e87d3..a229260 100644--- a/examples/round_trip_search.py+++ b/examples/round_trip_search.py@@ -60,7 +60,7 @@ def main():print(f"Departure: {leg.departure_datetime}")print(f"Arrival: {leg.arrival_datetime}")- print(f"\nTotal Price: ${outbound.price + return_flight.price}")+ print(f"\nTotal Price: ${outbound.price}")if __name__ == "__main__":diff --git a/fli/cli/utils.py b/fli/cli/utils.pyindex d322583..ea1a0cc 100644--- a/fli/cli/utils.py+++ b/fli/cli/utils.py@@ -149,15 +149,10 @@ def display_flight_results(flights: list):table.add_column("Label", style="blue")table.add_column("Value", style="green")+ # Google Flights returns the full round-trip price on the outbound legtotal_price = flight_segments[0].price- if is_round_trip:- total_price += flight_segments[1].pricetable.add_row("Total Price", f"${total_price:,.2f}")- if is_round_trip:- table.add_row("Outbound Price", f"${flight_segments[0].price:,.2f}")- table.add_row("Return Price", f"${flight_segments[1].price:,.2f}")-total_duration = sum(flight.duration for flight in flight_segments)table.add_row("Total Duration", format_duration(total_duration))total_stops = sum(flight.stops for flight in flight_segments)diff --git a/fli/mcp/server.py b/fli/mcp/server.pyindex 65f78d0..64ec7fb 100755--- a/fli/mcp/server.py+++ b/fli/mcp/server.py@@ -298,7 +298,8 @@ def _serialize_flight_result(flight: Any, is_round_trip: bool = False) -> dict[sif is_round_trip and isinstance(flight, tuple):outbound, return_flight = flightreturn {- "price": outbound.price + return_flight.price,+ # Google Flights returns the full round-trip price on the outbound leg+ "price": outbound.price,"currency": CONFIG.default_currency,"legs": [*[_serialize_flight_leg(leg) for leg in outbound.legs],diff --git a/pyproject.toml b/pyproject.tomlindex 7519268..c76c27a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -25,7 +25,7 @@ classifiers = [dependencies = ["curl-cffi>=0.7.4","fastapi>=0.115.6",- "fastmcp>=0.1.0,<3",+ "fastmcp>=2.0.0,<3.0.0","httpx>=0.28.1","pandas>=2.2.3","plotext>=5.3.2",diff --git a/tests/cli/test_utils.py b/tests/cli/test_utils.pyindex a2d97e8..be6ec80 100644--- a/tests/cli/test_utils.py+++ b/tests/cli/test_utils.py@@ -1,11 +1,14 @@from datetime import datetime, timedelta-from unittest.mock import MagicMock+from io import StringIO+from unittest.mock import MagicMock, patchimport pytest+from rich.console import Consolefrom typer import BadParameterfrom fli.cli.enums import DayOfWeekfrom fli.cli.utils import (+ display_flight_results,filter_dates_by_days,filter_flights_by_airlines,filter_flights_by_time,@@ -193,3 +196,66 @@ def test_filter_dates_by_days():# No day filters should return all datesresult = filter_dates_by_days(dates, [], TripType.ONE_WAY)assert len(result) == 2+++# ---------------------------------------------------------------------------+# display_flight_results — round-trip price must not be doubled+# ---------------------------------------------------------------------------+++def _make_flight_result(price: float, airline=Airline.DL, flight_number="DL123") -> FlightResult:+ """Create a FlightResult for testing display."""+ now = datetime.now()+ return FlightResult(+ price=price,+ duration=300,+ stops=0,+ legs=[+ FlightLeg(+ airline=airline,+ flight_number=flight_number,+ departure_airport=Airport.JFK,+ arrival_airport=Airport.LAX,+ departure_datetime=now,+ arrival_datetime=now + timedelta(hours=5),+ duration=300,+ )+ ],+ )+++def _capture_display(flights: list) -> str:+ """Run display_flight_results and capture the rendered text."""+ buf = StringIO()+ test_console = Console(file=buf, width=120, force_terminal=True)+ with patch("fli.cli.utils.console", test_console):+ display_flight_results(flights)+ return buf.getvalue()+++def test_display_one_way_price():+ """One-way flight should display the flight price as-is."""+ output = _capture_display([_make_flight_result(price=159.0)])+ assert "$159.00" in output+++def test_display_round_trip_price_not_doubled():+ """Round-trip display must use outbound price only (Google returns full RT price per leg)."""+ outbound = _make_flight_result(price=317.0, flight_number="DL100")+ return_flight = _make_flight_result(price=317.0, airline=Airline.DL, flight_number="DL200")++ output = _capture_display([(outbound, return_flight)])++ assert "$317.00" in output+ assert "$634.00" not in output+++def test_display_round_trip_price_asymmetric():+ """When leg prices differ, total should be the outbound price, not the sum."""+ outbound = _make_flight_result(price=400.0)+ return_flight = _make_flight_result(price=350.0)++ output = _capture_display([(outbound, return_flight)])++ assert "$400.00" in output+ assert "$750.00" not in outputdiff --git a/tests/mcp/test_mcp_server_fixes.py b/tests/mcp/test_mcp_server_fixes.pynew file mode 100644index 0000000..f330a0a--- /dev/null+++ b/tests/mcp/test_mcp_server_fixes.py@@ -0,0 +1,129 @@+"""Tests for MCP server bug fixes.++Covers:+ 1. list_tools FastMCP 2.x compatibility (get_tools async dict API)+ 2. Round-trip price doubling (Google Flights returns combined RT price on outbound leg)+"""++from unittest.mock import AsyncMock, MagicMock++import pytest++from fli.mcp.server import FliMCP, _serialize_flight_result++# ---------------------------------------------------------------------------+# Bug 1: list_tools — FastMCP 2.x compatibility+# ---------------------------------------------------------------------------+++class TestListTools:+ """FliMCP.list_tools() must use the async get_tools() dict API."""++ @pytest.mark.asyncio+ async def test_list_tools_uses_get_tools(self):+ """list_tools() should call get_tools() (FastMCP 2.x) not list_tools()."""+ server = FliMCP("test")++ fake_tool = MagicMock()+ fake_tool.name = "search_flights"+ fake_tool.description = "Search flights"+ fake_tool.parameters = {}++ # get_tools() returns a dict in FastMCP 2.x+ server._tool_manager.get_tools = AsyncMock(return_value={"search_flights": fake_tool})++ tools = await server.list_tools()++ server._tool_manager.get_tools.assert_awaited_once()+ assert len(tools) == 1+ assert tools[0].name == "search_flights"++ @pytest.mark.asyncio+ async def test_list_tools_does_not_call_sync_list_tools(self):+ """list_tools() must not call the old synchronous list_tools() method."""+ server = FliMCP("test")++ server._tool_manager.get_tools = AsyncMock(return_value={})+ # If the old sync path is called it would raise AttributeError on FastMCP 2.x+ server._tool_manager.list_tools = MagicMock(+ side_effect=AttributeError("list_tools removed in FastMCP 2.x")+ )++ # Should not raise+ tools = await server.list_tools()+ server._tool_manager.list_tools.assert_not_called()+ assert tools == []+++# ---------------------------------------------------------------------------+# Bug 2: Round-trip price doubling+# ---------------------------------------------------------------------------+++def _make_leg(airport_from="TLV", airport_to="ATH"):+ leg = MagicMock()+ leg.departure_airport = airport_from+ leg.arrival_airport = airport_to+ leg.departure_datetime = None+ leg.arrival_datetime = None+ leg.duration = 145+ leg.airline = "Wizz Air"+ leg.flight_number = "W6100"+ return leg+++def _make_flight(price, legs=None):+ flight = MagicMock()+ flight.price = price+ flight.legs = legs or [_make_leg()]+ return flight+++class TestSerializeFlightResult:+ """_serialize_flight_result must not double round-trip prices."""++ def test_one_way_price_unchanged(self):+ """One-way flight price should pass through unchanged."""+ flight = _make_flight(price=250.0)+ result = _serialize_flight_result(flight, is_round_trip=False)+ assert result["price"] == 250.0++ def test_round_trip_uses_outbound_price_only(self):+ """Round-trip price must equal outbound.price (Google already includes full RT price)."""+ outbound = _make_flight(price=454.0, legs=[_make_leg("TLV", "ATH")])+ return_flight = _make_flight(price=454.0, legs=[_make_leg("ATH", "TLV")])++ result = _serialize_flight_result((outbound, return_flight), is_round_trip=True)++ # Must NOT be 454 + 454 = 908+ assert result["price"] == 454.0, (+ f"Expected 454.0 (outbound price only), got {result['price']}. "+ "Google Flights already includes the full RT price on the outbound leg."+ )++ def test_round_trip_price_not_doubled(self):+ """Explicit check that the price is not the sum of both legs."""+ outbound = _make_flight(price=300.0)+ return_flight = _make_flight(price=300.0)++ result = _serialize_flight_result((outbound, return_flight), is_round_trip=True)++ assert result["price"] != 600.0, "Price must not be doubled"+ assert result["price"] == 300.0++ def test_round_trip_includes_legs_from_both_directions(self):+ """Round-trip result must include legs from both outbound and return flights."""+ outbound_leg = _make_leg("TLV", "ATH")+ return_leg = _make_leg("ATH", "TLV")+ outbound = _make_flight(price=454.0, legs=[outbound_leg])+ return_flight = _make_flight(price=454.0, legs=[return_leg])++ result = _serialize_flight_result((outbound, return_flight), is_round_trip=True)++ assert len(result["legs"]) == 2++ def test_round_trip_non_tuple_falls_back_to_single_flight(self):+ """If flight is not a tuple, treat it as a one-way even if is_round_trip=True."""+ flight = _make_flight(price=500.0)+ result = _serialize_flight_result(flight, is_round_trip=True)+ assert result["price"] == 500.0diff --git a/uv.lock b/uv.lockindex 33e6fb8..2efcd40 100644--- a/uv.lock+++ b/uv.lock@@ -600,7 +600,7 @@ dev = [requires-dist = [{ name = "curl-cffi", specifier = ">=0.7.4" },{ name = "fastapi", specifier = ">=0.115.6" },- { name = "fastmcp", specifier = ">=0.1.0" },+ { name = "fastmcp", specifier = ">=2.0.0,<3.0.0" },{ name = "httpx", specifier = ">=0.28.1" },{ name = "mkdocs-material", extras = ["imaging"], marker = "extra == 'dev'", specifier = ">=9.5.49" },{ name = "mkdocstrings", extras = ["python"], marker = "extra == 'dev'", specifier = ">=0.27.0" },