Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

fix: don't reject same-day flights on UTC servers, and surface real validation errors. (#215)

Scott J. Goldman061678319ec1
diff --git a/fli/mcp/server.py b/fli/mcp/server.py
index a4e286f..d1f097d 100755
--- a/fli/mcp/server.py
+++ b/fli/mcp/server.py
@@ -12,7 +12,7 @@ from typing import Annotated, Any
from fastmcp import FastMCP
from mcp.types import Icon
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, ValidationError
from pydantic_settings import BaseSettings, SettingsConfigDict
from fli.core import (
@@ -264,6 +264,20 @@ class DateSearchParams(BaseModel):
# =============================================================================
+def _format_validation_error(exc: ValidationError) -> str:
+ """Flatten a pydantic ValidationError into one actionable message.
+
+ The underlying validators already say exactly what is wrong ("Travel date
+ cannot be in the past"); callers only ever saw "Invalid parameter value",
+ which gives an agent nothing to correct.
+ """
+ problems = []
+ for error in exc.errors():
+ location = ".".join(str(part) for part in error["loc"]) or "input"
+ problems.append(f"{location}: {error['msg']}")
+ return f"Invalid parameter value - {'; '.join(problems)}"
+
+
def _airline_code(airline: Any) -> str:
return getattr(airline, "name", str(airline)).lstrip("_")
@@ -662,11 +676,10 @@ def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
except ParseError as e:
return {"success": False, "error": str(e), "flights": []}
+ except ValidationError as e:
+ return {"success": False, "error": _format_validation_error(e), "flights": []}
except Exception as e:
- error_msg = str(e)
- if "validation error" in error_msg.lower():
- return {"success": False, "error": "Invalid parameter value", "flights": []}
- return {"success": False, "error": f"Search failed: {error_msg}", "flights": []}
+ return {"success": False, "error": f"Search failed: {e}", "flights": []}
def _execute_booking_options(
@@ -757,11 +770,10 @@ def _execute_booking_options(
except ParseError as e:
return {"success": False, "error": str(e), "options": []}
+ except ValidationError as e:
+ return {"success": False, "error": _format_validation_error(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": []}
+ return {"success": False, "error": f"Booking lookup failed: {e}", "options": []}
def _execute_date_search(params: DateSearchParams) -> dict[str, Any]:
@@ -857,6 +869,8 @@ def _execute_date_search(params: DateSearchParams) -> dict[str, Any]:
except ParseError as e:
return {"success": False, "error": str(e), "dates": []}
+ except ValidationError as e:
+ return {"success": False, "error": _format_validation_error(e), "dates": []}
except Exception as e:
return {"success": False, "error": f"Search failed: {str(e)}", "dates": []}
diff --git a/fli/models/google_flights/base.py b/fli/models/google_flights/base.py
index 9777e88..10117c6 100644
--- a/fli/models/google_flights/base.py
+++ b/fli/models/google_flights/base.py
@@ -4,7 +4,7 @@ This module contains all the data models used for flight searches and results.
Models are designed to match Google Flights' APIs while providing a clean pythonic interface.
"""
-from datetime import datetime
+from datetime import date, datetime, timedelta, timezone
from enum import Enum
from pydantic import (
@@ -21,6 +21,25 @@ from fli.models.airline import Airline
from fli.models.airport import Airport
+def earliest_searchable_date() -> date:
+ """Return the earliest date that is still "today" somewhere on Earth.
+
+ Travel dates are supplied in the *origin airport's* local timezone, but this
+ library has no per-airport timezone data, so validation can only reference
+ the clock of the machine it happens to be running on. Comparing against a
+ naive local "today" makes results depend on the server's ``TZ`` — a UTC
+ container rejects a same-day San Francisco evening flight for the last seven
+ hours of every Pacific day, even though that flight has not departed.
+
+ Real UTC offsets span UTC-12 to UTC+14, so any traveler's local date is
+ within one day of the UTC date. Anchoring to ``utc_today - 1`` therefore
+ never rejects a date that is still today-or-future for the actual traveler.
+ The cost is that a genuinely past date may reach Google, which simply
+ returns no flights — a better failure than refusing a valid search.
+ """
+ return datetime.now(timezone.utc).date() - timedelta(days=1)
+
+
class SeatType(Enum):
"""Available cabin classes for flights."""
@@ -373,7 +392,7 @@ class FlightSegment(BaseModel):
def validate_travel_date(cls, v: str) -> str:
"""Validate that the travel date is not in the past."""
travel_date = datetime.strptime(v, "%Y-%m-%d").date()
- if travel_date < datetime.now().date():
+ if travel_date < earliest_searchable_date():
raise ValueError("Travel date cannot be in the past")
return v
diff --git a/fli/models/google_flights/dates.py b/fli/models/google_flights/dates.py
index 6b6781e..49b7e0b 100644
--- a/fli/models/google_flights/dates.py
+++ b/fli/models/google_flights/dates.py
@@ -1,6 +1,6 @@
import json
import urllib.parse
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
from enum import Enum
from pydantic import (
@@ -24,6 +24,7 @@ from fli.models.google_flights.base import (
PriceLimit,
SeatType,
TripType,
+ earliest_searchable_date,
)
MAX_PAST_FROM_DATE_DAYS = 6
@@ -123,22 +124,27 @@ class DateSearchFilters(BaseModel):
@field_validator("to_date")
@classmethod
def validate_to_date(cls, v: str) -> str:
- """Validate that to_date is in the future."""
+ """Validate that to_date is not in the past."""
to_date = datetime.strptime(v, "%Y-%m-%d").date()
- if to_date <= datetime.now().date():
- raise ValueError("To date must be in the future")
+ if to_date < earliest_searchable_date():
+ raise ValueError("To date cannot be in the past")
return v
@model_validator(mode="after")
def validate_and_adjust_from_date(self) -> "DateSearchFilters":
"""Adjust from_date to current date if it's in the past."""
from_date = self.parsed_from_date.date()
- current_date = datetime.now().date()
+ to_date = self.parsed_to_date.date()
+ # The clamp target is plain "today", not the rejection floor: anchoring it
+ # to earliest_searchable_date() would widen MAX_PAST_FROM_DATE_DAYS by a day.
+ current_date = datetime.now(timezone.utc).date()
if from_date < current_date:
delta = current_date - from_date
if delta > timedelta(days=MAX_PAST_FROM_DATE_DAYS):
- self.from_date = current_date.strftime("%Y-%m-%d")
+ # to_date may itself sit at the rejection floor (yesterday UTC),
+ # so cap the clamp at to_date to keep the range ordered.
+ self.from_date = min(current_date, to_date).strftime("%Y-%m-%d")
return self
diff --git a/fli/models/google_flights/flights.py b/fli/models/google_flights/flights.py
index 6b952c8..47e784b 100644
--- a/fli/models/google_flights/flights.py
+++ b/fli/models/google_flights/flights.py
@@ -1,10 +1,12 @@
import json
import urllib.parse
+from datetime import datetime
from enum import Enum
from pydantic import (
BaseModel,
PositiveInt,
+ model_validator,
)
from fli.models.airline import Airline
@@ -48,6 +50,33 @@ class FlightSearchFilters(BaseModel):
bags: BagsFilter | None = None
show_all_results: bool = True
+ @model_validator(mode="after")
+ def validate_segment_date_order(self) -> "FlightSearchFilters":
+ """Validate that each leg departs no earlier than the one before it.
+
+ Nothing else catches a return date that precedes the outbound date: it
+ used to be rejected only when it happened to land in the past, so a
+ backwards round trip in the future was passed straight to Google.
+ """
+ if self.trip_type not in (TripType.ROUND_TRIP, TripType.MULTI_CITY):
+ return self
+
+ dates = [
+ datetime.strptime(segment.travel_date, "%Y-%m-%d").date()
+ for segment in self.flight_segments
+ ]
+ for index, (previous, current) in enumerate(zip(dates, dates[1:], strict=False), start=2):
+ if current < previous:
+ if self.trip_type == TripType.ROUND_TRIP:
+ raise ValueError(
+ f"Return date ({current}) cannot be before departure date ({previous})"
+ )
+ raise ValueError(
+ f"Segment {index} travel date ({current}) cannot be before "
+ f"segment {index - 1} travel date ({previous})"
+ )
+ return self
+
def format(self) -> list:
"""Format filters into Google Flights API structure.
diff --git a/tests/models/test_date_search_filters_validation.py b/tests/models/test_date_search_filters_validation.py
index 853f742..8f46af7 100644
--- a/tests/models/test_date_search_filters_validation.py
+++ b/tests/models/test_date_search_filters_validation.py
@@ -1,6 +1,6 @@
"""Tests for DateSearchFilters validation and auto-correction."""
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
import pytest
@@ -12,6 +12,12 @@ from fli.models import (
PassengerInfo,
SeatType,
)
+from fli.models.google_flights.dates import MAX_PAST_FROM_DATE_DAYS
+
+
+def utc_today():
+ """Today's date in UTC — the anchor the validators reference."""
+ return datetime.now(timezone.utc).date()
@pytest.fixture
@@ -59,7 +65,7 @@ def test_date_search_normal_dates(basic_search_params, future_date):
def test_date_search_past_from_date(basic_search_params, future_date):
"""Test DateSearchFilters auto-corrects past from_date to today."""
- past_date = datetime.now() - timedelta(days=7)
+ past_date = utc_today() - timedelta(days=7)
to_date = future_date + timedelta(days=7)
filters = DateSearchFilters(
@@ -68,7 +74,7 @@ def test_date_search_past_from_date(basic_search_params, future_date):
to_date=to_date.strftime("%Y-%m-%d"),
)
- assert filters.from_date == datetime.now().date().strftime("%Y-%m-%d")
+ assert filters.from_date == utc_today().strftime("%Y-%m-%d")
assert filters.to_date == to_date.strftime("%Y-%m-%d")
@@ -91,18 +97,18 @@ def test_date_search_reversed_dates(basic_search_params, future_date):
def test_date_search_past_to_date(basic_search_params):
"""Test DateSearchFilters raises error for past to_date."""
- from_date = datetime.now() - timedelta(days=7)
- to_date = datetime.now() - timedelta(days=1)
+ from_date = utc_today() - timedelta(days=7)
+ to_date = utc_today() - timedelta(days=2)
- with pytest.raises(ValueError, match="To date must be in the future"):
+ with pytest.raises(ValueError, match="To date cannot be in the past"):
DateSearchFilters(
**basic_search_params,
from_date=from_date.strftime("%Y-%m-%d"),
to_date=to_date.strftime("%Y-%m-%d"),
)
- # Even if the from and to dates are reversed, the to date should still be in the future
- with pytest.raises(ValueError, match="To date must be in the future"):
+ # Even if the from and to dates are reversed, the to date must not be in the past
+ with pytest.raises(ValueError, match="To date cannot be in the past"):
DateSearchFilters(
**basic_search_params,
from_date=to_date.strftime("%Y-%m-%d"),
@@ -111,29 +117,45 @@ def test_date_search_past_to_date(basic_search_params):
def test_date_search_today_to_date(basic_search_params, future_date):
- """Test DateSearchFilters raises error for today's to_date."""
- today = datetime.now()
- from_date = today - timedelta(days=7)
+ """Test DateSearchFilters accepts a to_date of today.
- with pytest.raises(ValueError, match="To date must be in the future"):
- DateSearchFilters(
- **basic_search_params,
- from_date=from_date.strftime("%Y-%m-%d"),
- to_date=today.strftime("%Y-%m-%d"),
- )
+ A range ending "today" is still live for any traveler west of UTC, so the
+ validator anchors to utc_today - 1 rather than the server's naive today.
+ """
+ today = utc_today()
+ from_date = today - timedelta(days=1)
- # Even if the from and to dates are reversed, the to date should still be in the future
- with pytest.raises(ValueError, match="To date must be in the future"):
- DateSearchFilters(
- **basic_search_params,
- from_date=today.strftime("%Y-%m-%d"),
- to_date=from_date.strftime("%Y-%m-%d"),
- )
+ filters = DateSearchFilters(
+ **basic_search_params,
+ from_date=from_date.strftime("%Y-%m-%d"),
+ to_date=today.strftime("%Y-%m-%d"),
+ )
+
+ assert filters.to_date == today.strftime("%Y-%m-%d")
+
+
+def test_date_search_from_date_clamp_cannot_pass_to_date(basic_search_params):
+ """Test the from_date clamp cannot push from_date past a to_date at the rejection floor.
+
+ to_date may be as early as yesterday UTC, so clamping from_date to plain
+ "today" would invert the range; the clamp must cap at to_date instead.
+ """
+ from_date = utc_today() - timedelta(days=MAX_PAST_FROM_DATE_DAYS + 4)
+ to_date = utc_today() - timedelta(days=1)
+
+ filters = DateSearchFilters(
+ **basic_search_params,
+ from_date=from_date.strftime("%Y-%m-%d"),
+ to_date=to_date.strftime("%Y-%m-%d"),
+ )
+
+ assert filters.from_date == to_date.strftime("%Y-%m-%d")
+ assert filters.parsed_from_date <= filters.parsed_to_date
def test_date_search_past_from_date_after_swap(basic_search_params, future_date):
"""Test DateSearchFilters bumps up from_date to current date after date swap."""
- past_date = datetime.now() - timedelta(days=7)
+ past_date = utc_today() - timedelta(days=7)
later_date = future_date + timedelta(days=7)
# Create with reversed dates where from_date is in the future but will be swapped with past date
@@ -144,5 +166,5 @@ def test_date_search_past_from_date_after_swap(basic_search_params, future_date)
)
# After swap and adjustment, from_date should be today and to_date should be the later date
- assert filters.from_date == datetime.now().date().strftime("%Y-%m-%d")
+ assert filters.from_date == utc_today().strftime("%Y-%m-%d")
assert filters.to_date == later_date.strftime("%Y-%m-%d")
diff --git a/tests/models/test_flight_search_filters_validation.py b/tests/models/test_flight_search_filters_validation.py
new file mode 100644
index 0000000..3fdb19f
--- /dev/null
+++ b/tests/models/test_flight_search_filters_validation.py
@@ -0,0 +1,115 @@
+"""Tests for FlightSearchFilters validation."""
+
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+from fli.models import (
+ Airport,
+ FlightSearchFilters,
+ FlightSegment,
+ PassengerInfo,
+ TripType,
+)
+
+
+def utc_today():
+ """Today's date in UTC — the anchor the validators reference."""
+ return datetime.now(timezone.utc).date()
+
+
+def segment(origin, destination, travel_date):
+ """Build a FlightSegment for the given route and date."""
+ return FlightSegment(
+ departure_airport=[[origin, 0]],
+ arrival_airport=[[destination, 0]],
+ travel_date=travel_date.strftime("%Y-%m-%d"),
+ )
+
+
+def passengers():
+ """Get a single adult passenger."""
+ return PassengerInfo(adults=1, children=0, infants_in_seat=0, infants_on_lap=0)
+
+
+def test_round_trip_return_after_departure(passengers):
+ """Test FlightSearchFilters accepts a return date after the departure date."""
+ depart = utc_today() + timedelta(days=30)
+ back = utc_today() + timedelta(days=37)
+
+ filters = FlightSearchFilters(
+ trip_type=TripType.ROUND_TRIP,
+ passenger_info=passengers,
+ flight_segments=[
+ segment(Airport.SFO, Airport.LAX, depart),
+ segment(Airport.LAX, Airport.SFO, back),
+ ],
+ )
+
+ assert filters.flight_segments[1].travel_date == back.strftime("%Y-%m-%d")
+
+
+def test_round_trip_return_before_departure(passengers):
+ """Test FlightSearchFilters rejects a return date before the departure date.
+
+ Both dates are in the future, so the past-date validator cannot catch this.
+ It previously went unvalidated and was passed straight to Google.
+ """
+ depart = utc_today() + timedelta(days=30)
+ back = utc_today() + timedelta(days=20)
+
+ with pytest.raises(ValueError, match="cannot be before departure date"):
+ FlightSearchFilters(
+ trip_type=TripType.ROUND_TRIP,
+ passenger_info=passengers,
+ flight_segments=[
+ segment(Airport.SFO, Airport.LAX, depart),
+ segment(Airport.LAX, Airport.SFO, back),
+ ],
+ )
+
+
+def test_round_trip_same_day_return(passengers):
+ """Test FlightSearchFilters accepts a same-day return."""
+ depart = utc_today() + timedelta(days=30)
+
+ filters = FlightSearchFilters(
+ trip_type=TripType.ROUND_TRIP,
+ passenger_info=passengers,
+ flight_segments=[
+ segment(Airport.SFO, Airport.LAX, depart),
+ segment(Airport.LAX, Airport.SFO, depart),
+ ],
+ )
+
+ assert filters.flight_segments[0].travel_date == filters.flight_segments[1].travel_date
+
+
+def test_one_way_is_not_order_checked(passengers):
+ """Test the ordering check does not apply to one-way trips."""
+ filters = FlightSearchFilters(
+ trip_type=TripType.ONE_WAY,
+ passenger_info=passengers,
+ flight_segments=[segment(Airport.SFO, Airport.LAX, utc_today() + timedelta(days=30))],
+ )
+
+ assert filters.trip_type == TripType.ONE_WAY
+
+
+def test_multi_city_rejects_backwards_leg(passengers):
+ """Test FlightSearchFilters rejects a multi-city leg that departs before the previous one."""
+ first = utc_today() + timedelta(days=10)
+ second = utc_today() + timedelta(days=20)
+ third = utc_today() + timedelta(days=15) # earlier than the second leg
+
+ with pytest.raises(ValueError, match="Segment 3 .* cannot be before segment 2"):
+ FlightSearchFilters(
+ trip_type=TripType.MULTI_CITY,
+ passenger_info=passengers,
+ flight_segments=[
+ segment(Airport.SFO, Airport.LAX, first),
+ segment(Airport.LAX, Airport.JFK, second),
+ segment(Airport.JFK, Airport.SFO, third),
+ ],
+ )
diff --git a/tests/models/test_flight_segment_validation.py b/tests/models/test_flight_segment_validation.py
index c57d5df..38243b2 100644
--- a/tests/models/test_flight_segment_validation.py
+++ b/tests/models/test_flight_segment_validation.py
@@ -1,12 +1,17 @@
"""Tests for FlightSegment validation."""
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
import pytest
from fli.models import Airport, FlightSegment, TimeRestrictions
+def utc_today():
+ """Today's date in UTC — the anchor the validators reference."""
+ return datetime.now(timezone.utc).date()
+
+
@pytest.fixture
def future_date():
"""Get a date 30 days in the future."""
@@ -28,7 +33,7 @@ def test_flight_segment_normal():
def test_flight_segment_past_date():
"""Test FlightSegment rejects past travel dates."""
- past = datetime.now() - timedelta(days=1)
+ past = utc_today() - timedelta(days=2)
with pytest.raises(ValueError, match="Travel date cannot be in the past"):
FlightSegment(
departure_airport=[[Airport.PHX, 0]],
@@ -48,6 +53,24 @@ def test_flight_segment_today():
assert segment.travel_date == today.strftime("%Y-%m-%d")
+def test_flight_segment_accepts_yesterday_in_utc():
+ """Test FlightSegment accepts the day before the UTC date.
+
+ Travel dates are local to the origin airport, but the validator can only see
+ the server clock. At 17:00 in San Francisco the UTC date has already rolled
+ over, so a same-day evening SFO departure looks like "yesterday" to a UTC
+ container. Rejecting it blinds every westward user to same-day flights for
+ the last hours of their day, so utc_today - 1 must remain searchable.
+ """
+ yesterday_utc = utc_today() - timedelta(days=1)
+ segment = FlightSegment(
+ departure_airport=[[Airport.SFO, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ travel_date=yesterday_utc.strftime("%Y-%m-%d"),
+ )
+ assert segment.travel_date == yesterday_utc.strftime("%Y-%m-%d")
+
+
def test_flight_segment_same_airports():
"""Test FlightSegment rejects same departure and arrival airports."""
future = datetime.now() + timedelta(days=30)