Google Flights MCP, CLI and Python Library
feat: CLI child/infant passenger flags and PassengerInfo validation (#243)
Punit Aranib25c61e15c1c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 11eea74..4385ada 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -120,6 +120,9 @@ Search for flights on a specific date.- `min_layover` / `max_layover` - Layover duration bounds in minutes- `currency` / `language` / `country` - Google `curr=` / `hl=` / `gl=` URL params- `sort_by` - CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME+- `passengers` - Number of adult passengers (default 1)+- `children` / `infants_in_seat` / `infants_on_lap` - Passenger mix additions;+ see "Note on passenger limits" below**Response:** Each flight in `flights[]` carries its own `booking_url` — a`tfs` protobuf deep link that opens the specific itinerary's booking page@@ -141,6 +144,7 @@ Find cheapest travel dates within a range.- `exclude_airlines`, `alliance`, `exclude_alliance`, `min_layover`, `max_layover` - Same as `search_flights`- `currency`, `language`, `country` - Same locale knobs as `search_flights`- `sort_by_price` - Boolean to sort by price+- `passengers`, `children`, `infants_in_seat`, `infants_on_lap` - Same as `search_flights`**Response:** Each date result carries a `booking_url` deep-linking to GoogleFlights for that specific date (and return date for round trips).@@ -158,7 +162,8 @@ options — each with a clickable `booking_url` and `google_click_url`.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`+- `cabin_class`, `max_stops`, `passengers`, `children`, `infants_in_seat`,+ `infants_on_lap`, `airlines`, `exclude_basic_economy` - Same as `search_flights`- `departure_window`, `sort_by`, `exclude_airlines`, `alliance`, `exclude_alliance`,`min_layover`, `max_layover`, `emissions`, `checked_bags`, `carry_on` - Same as`search_flights`. Pass the **same filters used for `search_flights`** so the@@ -167,6 +172,18 @@ options — each with a clickable `booking_url` and `google_click_url`.user saw.- `currency`, `language`, `country` - Same locale knobs as `search_flights`+### Note on passenger limits+`PassengerInfo` (`fli/models/google_flights/base.py`) validates every+passenger mix against Google Flights' own booking limits: total travelers+(`adults + children + infants_in_seat + infants_on_lap`) must be between 1+and 9, and `infants_on_lap` cannot exceed `adults` (each lap infant needs an+adult to sit with). A violation raises a pydantic `ValidationError` with the+specific offending values named in the message. Both interfaces flatten it+with the shared `fli.core.format_validation_error` helper: the CLI surfaces a+one-line `Error: ...` and a non-zero exit code; the MCP tools surface+`{"success": false, "error": "..."}` (same pattern PR #215 introduced for+other validators).+### Note on emissionsBoth tools accept the `emissions` filter (forwarded to Google's"less emissions" toggle as `LESS`), but raw CO₂ figures are intentionallydiff --git a/README.md b/README.mdindex afbf1a5..0bafe4b 100644--- a/README.md+++ b/README.md@@ -75,6 +75,12 @@ The MCP server provides two main tools:| `country` | string | ISO 3166-1 alpha-2 country code (e.g. 'GB') for `gl=` param || `sort_by` | string | CHEAPEST, DURATION, DEPARTURE_TIME, or ARRIVAL_TIME || `passengers` | int | Number of adult passengers |+| `children` | int | Number of children (ages 2-11) |+| `infants_in_seat` | int | Number of infants (under 2) occupying their own seat |+| `infants_on_lap` | int | Number of lap infants (under 2, no seat) |++> Total travelers (`passengers + children + infants_in_seat + infants_on_lap`) must be+> between 1 and 9, and `infants_on_lap` cannot exceed `passengers`.#### `search_dates` Parameters@@ -100,6 +106,11 @@ The MCP server provides two main tools:| `country` | string | ISO 3166-1 alpha-2 country code (e.g. 'GB') || `sort_by_price` | bool | Sort results by price (lowest first) || `passengers` | int | Number of adult passengers |+| `children` | int | Number of children (ages 2-11) |+| `infants_in_seat` | int | Number of infants (under 2) occupying their own seat |+| `infants_on_lap` | int | Number of lap infants (under 2, no seat) |++> Same passenger limits as `search_flights`: total 1-9, `infants_on_lap` ≤ `passengers`.## Quick Start@@ -169,6 +180,9 @@ fli flights JFK LHR 2026-10-25 \--min-layover 90 \--max-layover 360 \--currency EUR --language en-GB --country GB++# Family mix: 2 adults, 1 child, 1 lap infant (total must be 1-9)+fli flights JFK LHR 2026-10-25 --passengers 2 --children 1 --infants-on-lap 1```> ⚠️ **Experimental**@@ -235,8 +249,14 @@ fli multi \| `--class, -c` | Cabin class | `ECONOMY`, `BUSINESS` || `--stops, -s` | Maximum stops | `NON_STOP`, `ONE_STOP` || `--sort, -o` | Sort results by | `CHEAPEST`, `DURATION` |+| `--passengers, -p` | Number of adult passengers | `2` |+| `--children` | Number of children (ages 2-11) | `1` |+| `--infants-in-seat` | Number of infants occupying their own seat | `1` |+| `--infants-on-lap` | Number of lap infants (must be ≤ adults) | `1` || `--format` | Output format | `text`, `json` |+> Total passengers (adults + children + infants) must be between 1 and 9.+#### Dates Command (`fli dates`)| Option | Description | Example |@@ -259,6 +279,10 @@ fli multi \| `--time` | Departure time window | `6-20` || `--sort` | Sort by price | (flag) || `--[day]` | Day filters | `--monday`, `--friday` |+| `--passengers, -p` | Number of adult passengers | `2` |+| `--children` | Number of children (ages 2-11) | `1` |+| `--infants-in-seat` | Number of infants occupying their own seat | `1` |+| `--infants-on-lap` | Number of lap infants (must be ≤ adults) | `1` || `--format` | Output format | `text`, `json` |#### Multi Command (`fli multi`)@@ -271,6 +295,10 @@ fli multi \| `--class, -c` | Cabin class | `ECONOMY`, `BUSINESS` || `--stops, -s` | Maximum stops | `NON_STOP`, `ONE_STOP` || `--sort, -o` | Sort results by | `CHEAPEST`, `DURATION` |+| `--passengers, -p` | Number of adult passengers | `2` |+| `--children` | Number of children (ages 2-11) | `1` |+| `--infants-in-seat` | Number of infants occupying their own seat | `1` |+| `--infants-on-lap` | Number of lap infants (must be ≤ adults) | `1` |## MCP Server Integrationdiff --git a/docs/guides/mcp.md b/docs/guides/mcp.mdindex 89b49f8..6ff72ca 100644--- a/docs/guides/mcp.md+++ b/docs/guides/mcp.md@@ -90,6 +90,15 @@ Search for flights between two airports on a specific date.| `country` | string | No | null | ISO 3166-1 alpha-2 code (`gl=`) — e.g. 'GB' || `sort_by` | string | No | CHEAPEST | CHEAPEST, DURATION, DEPARTURE_TIME, or ARRIVAL_TIME || `passengers` | int | No | 1 | Number of adult passengers |+| `children` | int | No | 0 | Number of children (ages 2-11) |+| `infants_in_seat` | int | No | 0 | Number of infants (under 2) occupying their own seat |+| `infants_on_lap` | int | No | 0 | Number of lap infants (under 2, no seat) |++> **Passenger limits:** total travelers (`passengers + children + infants_in_seat ++> infants_on_lap`) must be between 1 and 9, and `infants_on_lap` cannot exceed+> `passengers` — Google Flights' own booking limits. An invalid mix returns+> `success: false` with the specific problem (e.g. `"Total passengers must be+> between 1 and 9 (got 10: ...)"`), not a generic error.**Example Response:**@@ -155,6 +164,12 @@ Find the cheapest travel dates between two airports within a date range.| `country` | string | No | null | ISO 3166-1 alpha-2 country (`gl=`) || `sort_by_price` | bool | No | false | Sort results by price (lowest first) || `passengers` | int | No | 1 | Number of adult passengers |+| `children` | int | No | 0 | Number of children (ages 2-11) |+| `infants_in_seat` | int | No | 0 | Number of infants (under 2) occupying their own seat |+| `infants_on_lap` | int | No | 0 | Number of lap infants (under 2, no seat) |++> **Passenger limits:** same as `search_flights` — total travelers 1-9, and+> `infants_on_lap` cannot exceed `passengers`.**Example Response:**@@ -208,6 +223,9 @@ find out where (and at what price) a specific flight can be booked.| `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 |+| `children` | int | No | 0 | Number of children (ages 2-11) |+| `infants_in_seat` | int | No | 0 | Number of infants (under 2) occupying their own seat |+| `infants_on_lap` | int | No | 0 | Number of lap infants (under 2, no seat) — cannot exceed `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') |diff --git a/docs/python/api/models.md b/docs/python/api/models.mdindex d026b3b..0dca991 100644--- a/docs/python/api/models.md+++ b/docs/python/api/models.md@@ -40,7 +40,7 @@ filters = FlightSearchFilters(- Flight segments must have different departure and arrival airports- Travel dates cannot be in the past- For round trips, exactly two flight segments are required-- Passenger counts must be valid (at least one adult)+- Passenger counts must be valid — see [`PassengerInfo`](#passengerinfo) below::: fli.models.google_flights.FlightSearchFilters@@ -88,6 +88,18 @@ Type of trip for flight search.Configuration for passenger counts.+Fields:++- `adults` (default `1`)+- `children` (default `0`)+- `infants_in_seat` (default `0`)+- `infants_on_lap` (default `0`)++**Validation Rules:**+- Total passengers (`adults + children + infants_in_seat + infants_on_lap`) must be+ between 1 and 9 — Google Flights refuses to price a booking outside that range+- `infants_on_lap` cannot exceed `adults` — each lap infant needs an adult to sit with+::: fli.models.google_flights.PassengerInfo### TimeRestrictionsdiff --git a/fli/cli/commands/dates.py b/fli/cli/commands/dates.pyindex 2a71d91..f28cd23 100644--- a/fli/cli/commands/dates.py+++ b/fli/cli/commands/dates.py@@ -4,6 +4,7 @@ from datetime import datetime, timedeltafrom typing import Annotatedimport typer+from pydantic import ValidationErrorfrom fli.cli.enums import DayOfWeek, OutputFormatfrom fli.cli.errors import json_error_payload, report_cli_error@@ -20,6 +21,7 @@ from fli.cli.utils import ()from fli.core import (build_date_search_segments,+ format_validation_error,parse_airlines,parse_alliances,parse_cabin_class,@@ -263,6 +265,30 @@ def dates(min=1,),] = 1,+ children: Annotated[+ int,+ typer.Option(+ "--children",+ help="Number of children",+ min=0,+ ),+ ] = 0,+ infants_in_seat: Annotated[+ int,+ typer.Option(+ "--infants-in-seat",+ help="Number of infants in seat",+ min=0,+ ),+ ] = 0,+ infants_on_lap: Annotated[+ int,+ typer.Option(+ "--infants-on-lap",+ help="Number of infants on lap",+ min=0,+ ),+ ] = 0,):"""Find the cheapest dates to fly between two airports.@@ -270,6 +296,7 @@ def dates(fli dates LAX MIA --class BUSINESS --stops NON_STOP --fridayfli dates LAX MIA --alliance ONEWORLD --currency EURfli dates LAX MIA --exclude-airlines DL --max-layover 240+ fli dates LAX MIA --passengers 2 --children 1 --infants-on-lap 1"""try:@@ -316,6 +343,9 @@ def dates("sort_by_price": sort_by_price,"days": [day.value for day in selected_days],"passengers": passengers,+ "children": children,+ "infants_in_seat": infants_in_seat,+ "infants_on_lap": infants_on_lap,}# Build time restrictions from tuple@@ -353,7 +383,12 @@ def dates(# Create search filtersfilters = DateSearchFilters(trip_type=trip_type,- passenger_info=PassengerInfo(adults=passengers),+ passenger_info=PassengerInfo(+ adults=passengers,+ children=children,+ infants_in_seat=infants_in_seat,+ infants_on_lap=infants_on_lap,+ ),flight_segments=segments,stops=stops,seat_type=seat_type,@@ -485,6 +520,20 @@ def dates(emit_json(payload)raise typer.Exit(1) from eraise report_cli_error(e, command="dates") from e+ except ValidationError as e:+ message = format_validation_error(e)+ if output_format == OutputFormat.JSON:+ emit_json(+ build_json_error_response(+ search_type="dates",+ message=message,+ query=query,+ )+ )+ raise typer.Exit(1) from e++ typer.echo(f"Error: {message}")+ raise typer.Exit(1) from eexcept (AttributeError, ValueError) as e:if "module 'fli.search' has no attribute 'SearchDates'" in str(e):raisediff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.pyindex f4bffa6..bd84bb6 100644--- a/fli/cli/commands/flights.py+++ b/fli/cli/commands/flights.py@@ -3,6 +3,7 @@from typing import Annotated, Anyimport typer+from pydantic import ValidationErrorfrom fli.cli.enums import OutputFormatfrom fli.cli.errors import json_error_payload, report_cli_error@@ -18,6 +19,7 @@ from fli.cli.utils import ()from fli.core import (build_flight_segments,+ format_validation_error,google_flights_url,parse_airlines,parse_alliances,@@ -64,6 +66,9 @@ def _search_flights_core(min_layover: int | None = None,max_layover: int | None = None,passengers: int = 1,+ children: int = 0,+ infants_in_seat: int = 0,+ infants_on_lap: int = 0,) -> None:"""Core flight search functionality."""query: dict[str, Any] = {@@ -77,6 +82,9 @@ def _search_flights_core("max_stops": max_stops.upper(),"sort_by": sort_by.upper(),"passengers": passengers,+ "children": children,+ "infants_in_seat": infants_in_seat,+ "infants_on_lap": infants_on_lap,}try:@@ -160,7 +168,12 @@ def _search_flights_core(# Create search filtersfilters = FlightSearchFilters(trip_type=trip_type,- passenger_info=PassengerInfo(adults=passengers),+ passenger_info=PassengerInfo(+ adults=passengers,+ children=children,+ infants_in_seat=infants_in_seat,+ infants_on_lap=infants_on_lap,+ ),flight_segments=segments,stops=stops,seat_type=seat_type,@@ -252,6 +265,20 @@ def _search_flights_core(typer.echo(f"Error: {str(e)}")raise typer.Exit(1) from e+ except ValidationError as e:+ message = format_validation_error(e)+ if output_format == OutputFormat.JSON:+ emit_json(+ build_json_error_response(+ search_type="flights",+ message=message,+ query=query,+ )+ )+ raise typer.Exit(1) from e++ typer.echo(f"Error: {message}")+ raise typer.Exit(1) from eexcept (AttributeError, ValueError) as e:if output_format == OutputFormat.JSON:emit_json(@@ -483,6 +510,30 @@ def flights(min=1,),] = 1,+ children: Annotated[+ int,+ typer.Option(+ "--children",+ help="Number of children",+ min=0,+ ),+ ] = 0,+ infants_in_seat: Annotated[+ int,+ typer.Option(+ "--infants-in-seat",+ help="Number of infants in seat",+ min=0,+ ),+ ] = 0,+ infants_on_lap: Annotated[+ int,+ typer.Option(+ "--infants-on-lap",+ help="Number of infants on lap",+ min=0,+ ),+ ] = 0,):"""Search for flights on a specific date.@@ -498,6 +549,7 @@ def flights(fli flights JFK LAX 2026-10-25 --exclude-airlines DLfli flights BUF ATH 2026-10-25 --min-layover 120fli flights JFK LHR 2026-10-25 --passengers 2+ fli flights JFK LHR 2026-10-25 --passengers 2 --children 1 --infants-on-lap 1"""_search_flights_core(@@ -526,4 +578,7 @@ def flights(min_layover=min_layover,max_layover=max_layover,passengers=passengers,+ children=children,+ infants_in_seat=infants_in_seat,+ infants_on_lap=infants_on_lap,)diff --git a/fli/cli/commands/multi.py b/fli/cli/commands/multi.pyindex 2ae2d80..2a231c1 100644--- a/fli/cli/commands/multi.py+++ b/fli/cli/commands/multi.py@@ -4,11 +4,13 @@ import refrom typing import Annotatedimport typer+from pydantic import ValidationErrorfrom fli.cli.errors import report_cli_errorfrom fli.cli.utils import display_flight_results, validate_time_rangefrom fli.core import (build_multi_city_segments,+ format_validation_error,normalize_date,parse_airlines,parse_cabin_class,@@ -104,6 +106,30 @@ def multi(min=1,),] = 1,+ children: Annotated[+ int,+ typer.Option(+ "--children",+ help="Number of children",+ min=0,+ ),+ ] = 0,+ infants_in_seat: Annotated[+ int,+ typer.Option(+ "--infants-in-seat",+ help="Number of infants in seat",+ min=0,+ ),+ ] = 0,+ infants_on_lap: Annotated[+ int,+ typer.Option(+ "--infants-on-lap",+ help="Number of infants on lap",+ min=0,+ ),+ ] = 0,):"""Search for multi-city flights with multiple legs.@@ -113,6 +139,7 @@ def multi(fli multi --leg SEA,HKG,2026-12-26 --leg PEK,SEA,2027-01-02fli multi -l SEA,NRT,2026-12-26 -l NRT,HKG,2026-12-30 -l HKG,SEA,2027-01-05 -c BUSINESSfli multi -l SEA,NRT,2026-12-26 -l HKG,SEA,2027-01-05 --passengers 2+ fli multi -l SEA,NRT,2026-12-26 -l HKG,SEA,2027-01-05 --passengers 2 --children 1"""try:@@ -152,7 +179,12 @@ def multi(# Create search filtersfilters = FlightSearchFilters(trip_type=trip_type,- passenger_info=PassengerInfo(adults=passengers),+ passenger_info=PassengerInfo(+ adults=passengers,+ children=children,+ infants_in_seat=infants_in_seat,+ infants_on_lap=infants_on_lap,+ ),flight_segments=segments,stops=stops,seat_type=seat_type,@@ -173,6 +205,9 @@ def multi(except ParseError as e:typer.echo(f"Error: {str(e)}")raise typer.Exit(1) from e+ except ValidationError as e:+ typer.echo(f"Error: {format_validation_error(e)}")+ raise typer.Exit(1) from eexcept (AttributeError, ValueError) as e:typer.echo(f"Error: {str(e)}")raise typer.Exit(1) from ediff --git a/fli/core/__init__.py b/fli/core/__init__.pyindex bc37bef..1847dbc 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 .errors import format_validation_errorfrom .links import google_flights_url, with_locale_paramsfrom .parsers import (parse_airlines,@@ -52,6 +53,8 @@ __all__ = ["extract_currency_from_price_token","format_price","format_price_axis_label",+ # Errors+ "format_validation_error",# Links"google_flights_url","with_locale_params",diff --git a/fli/core/errors.py b/fli/core/errors.pynew file mode 100644index 0000000..9337023--- /dev/null+++ b/fli/core/errors.py@@ -0,0 +1,23 @@+"""Shared error-formatting utilities for the CLI and MCP interfaces.++Pydantic's default ``str(ValidationError)`` is a multi-line dump meant for+developers, not end users or AI assistants driving the MCP tools. Both+interfaces need the same one-line, actionable rendering of "what exactly is+wrong" — this module keeps that logic in one place.+"""++from pydantic import ValidationError+++def format_validation_error(exc: ValidationError) -> str:+ """Flatten a pydantic ``ValidationError`` into one actionable message.++ The underlying validators already say exactly what is wrong (e.g. "Total+ passengers must be between 1 and 9"); without this, callers only ever saw+ a multi-line pydantic dump, which gives nothing to act on.+ """+ 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)}"diff --git a/fli/mcp/server.py b/fli/mcp/server.pyindex 4792ccf..289e8df 100755--- a/fli/mcp/server.py+++ b/fli/mcp/server.py@@ -21,6 +21,7 @@ from fli.core import (build_date_search_segments,build_flight_segments,build_time_restrictions,+ format_validation_error,google_flights_url,parse_airlines,parse_alliances,@@ -286,20 +287,6 @@ 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("_")@@ -701,7 +688,7 @@ 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": []}+ return {"success": False, "error": format_validation_error(e), "flights": []}except Exception as e:return {"success": False, "error": f"Search failed: {e}", "flights": []}@@ -796,7 +783,7 @@ 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": []}+ return {"success": False, "error": format_validation_error(e), "options": []}except Exception as e:return {"success": False, "error": f"Booking lookup failed: {e}", "options": []}@@ -900,7 +887,7 @@ 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": []}+ 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.pyindex 32122eb..918449f 100644--- a/fli/models/google_flights/base.py+++ b/fli/models/google_flights/base.py@@ -189,13 +189,39 @@ class TimeRestrictions(BaseModel):class PassengerInfo(BaseModel):- """Passenger configuration for flight search."""+ """Passenger configuration for flight search.++ Validation Rules:+ - Total passengers (adults + children + infants) must be between 1 and 9 —+ Google Flights refuses to price a booking outside that range.+ - ``infants_on_lap`` cannot exceed ``adults`` — every lap infant needs an+ adult to sit with.+ """adults: NonNegativeInt = 1children: NonNegativeInt = 0infants_in_seat: NonNegativeInt = 0infants_on_lap: NonNegativeInt = 0+ @model_validator(mode="after")+ def validate_passenger_counts(self) -> "PassengerInfo":+ """Enforce Google Flights' booking-wide passenger limits."""+ total = self.adults + self.children + self.infants_in_seat + self.infants_on_lap+ if not 1 <= total <= 9:+ raise ValueError(+ "Total passengers must be between 1 and 9 "+ f"(got {total}: {self.adults} adults, {self.children} children, "+ f"{self.infants_in_seat} infants in seat, {self.infants_on_lap} infants on lap)"+ )++ if self.infants_on_lap > self.adults:+ raise ValueError(+ f"infants_on_lap ({self.infants_on_lap}) cannot exceed adults ({self.adults}); "+ "each lap infant must be paired with an adult"+ )++ return self+class PriceLimit(BaseModel):"""Maximum price constraint for flight search."""diff --git a/tests/cli/test_dates.py b/tests/cli/test_dates.pyindex fce404a..d127d8c 100644--- a/tests/cli/test_dates.py+++ b/tests/cli/test_dates.py@@ -44,6 +44,76 @@ def test_dates_with_passengers(runner, mock_search_dates, mock_console):assert payload["query"]["passengers"] == 2+def test_dates_with_family_passenger_mix(runner, mock_search_dates, mock_console):+ """Test dates search passes the full passenger mix into filters and JSON query echo."""+ mock_search_dates.search.return_value = []+ result = runner.invoke(+ app,+ [+ "dates",+ "JFK",+ "LAX",+ "--passengers",+ "2",+ "--children",+ "1",+ "--infants-in-seat",+ "1",+ "--infants-on-lap",+ "1",+ "--format",+ "json",+ ],+ )+ assert result.exit_code == 0+ args, _ = mock_search_dates.search.call_args+ assert args[0].passenger_info.adults == 2+ assert args[0].passenger_info.children == 1+ assert args[0].passenger_info.infants_in_seat == 1+ assert args[0].passenger_info.infants_on_lap == 1+ payload = json.loads(result.stdout)+ assert payload["query"]["passengers"] == 2+ assert payload["query"]["children"] == 1+ assert payload["query"]["infants_in_seat"] == 1+ assert payload["query"]["infants_on_lap"] == 1+++def test_dates_invalid_passenger_mix_exits_nonzero_with_clean_message(+ runner, mock_search_dates, mock_console+):+ """A passenger mix Google Flights would reject fails cleanly, not with a pydantic dump."""+ result = runner.invoke(+ app,+ ["dates", "JFK", "LAX", "--passengers", "1", "--infants-on-lap", "3"],+ )+ assert result.exit_code == 1+ assert "validation error for" not in result.stdout.lower()+ assert "infants_on_lap" in result.stdout+ mock_search_dates.search.assert_not_called()+++def test_dates_invalid_passenger_mix_json_error(runner, mock_search_dates, mock_console):+ """JSON mode surfaces the same passenger-mix error as a clean payload."""+ result = runner.invoke(+ app,+ [+ "dates",+ "JFK",+ "LAX",+ "--passengers",+ "9",+ "--children",+ "1",+ "--format",+ "json",+ ],+ )+ assert result.exit_code == 1+ payload = json.loads(result.stdout)+ assert payload["success"] is False+ assert "Total passengers must be between 1 and 9" in payload["error"]["message"]++def test_dates_with_date_range(runner, mock_search_dates, mock_console):"""Test dates search with custom date range."""from_date = datetime.now().strftime("%Y-%m-%d")diff --git a/tests/cli/test_flights.py b/tests/cli/test_flights.pyindex 71ca8f5..ede7a38 100644--- a/tests/cli/test_flights.py+++ b/tests/cli/test_flights.py@@ -79,6 +79,109 @@ def test_flights_json_query_echoes_passengers(runner, mock_search_flights, mock_assert payload["query"]["passengers"] == 3+def test_flights_with_family_passenger_mix(runner, mock_search_flights, mock_console):+ """Test flights search passes the full passenger mix into filters."""+ result = runner.invoke(+ app,+ [+ "flights",+ "JFK",+ "LAX",+ datetime.now().strftime("%Y-%m-%d"),+ "--passengers",+ "2",+ "--children",+ "1",+ "--infants-in-seat",+ "1",+ "--infants-on-lap",+ "1",+ ],+ )+ assert result.exit_code == 0+ args, _ = mock_search_flights.search.call_args+ assert args[0].passenger_info.adults == 2+ assert args[0].passenger_info.children == 1+ assert args[0].passenger_info.infants_in_seat == 1+ assert args[0].passenger_info.infants_on_lap == 1+++def test_flights_json_query_echoes_full_passenger_mix(runner, mock_search_flights, mock_console):+ """JSON query echo includes children/infants alongside adult passengers."""+ result = runner.invoke(+ app,+ [+ "flights",+ "JFK",+ "LAX",+ datetime.now().strftime("%Y-%m-%d"),+ "--passengers",+ "2",+ "--children",+ "1",+ "--infants-in-seat",+ "1",+ "--infants-on-lap",+ "1",+ "--format",+ "json",+ ],+ )+ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert payload["query"]["passengers"] == 2+ assert payload["query"]["children"] == 1+ assert payload["query"]["infants_in_seat"] == 1+ assert payload["query"]["infants_on_lap"] == 1+++def test_flights_invalid_passenger_mix_exits_nonzero_with_clean_message(+ runner, mock_search_flights, mock_console+):+ """A passenger mix Google Flights would reject fails cleanly, not with a pydantic dump."""+ result = runner.invoke(+ app,+ [+ "flights",+ "JFK",+ "LAX",+ datetime.now().strftime("%Y-%m-%d"),+ "--passengers",+ "1",+ "--infants-on-lap",+ "3",+ ],+ )+ assert result.exit_code == 1+ # One readable line, not pydantic's multi-line "1 validation error for..." dump.+ assert "validation error for" not in result.stdout.lower()+ assert "infants_on_lap" in result.stdout+ mock_search_flights.search.assert_not_called()+++def test_flights_invalid_passenger_mix_json_error(runner, mock_search_flights, mock_console):+ """JSON mode surfaces the same passenger-mix error as a clean payload."""+ result = runner.invoke(+ app,+ [+ "flights",+ "JFK",+ "LAX",+ datetime.now().strftime("%Y-%m-%d"),+ "--passengers",+ "9",+ "--children",+ "1",+ "--format",+ "json",+ ],+ )+ assert result.exit_code == 1+ payload = json.loads(result.stdout)+ assert payload["success"] is False+ assert "Total passengers must be between 1 and 9" in payload["error"]["message"]++def test_flights_with_airlines(runner, mock_search_flights, mock_console):"""Repeated -a flags resolve to the matching Airline enums on the filter."""result = runner.invoke(diff --git a/tests/cli/test_multi.py b/tests/cli/test_multi.pyindex 3eaf2cf..44dcaa9 100644--- a/tests/cli/test_multi.py+++ b/tests/cli/test_multi.py@@ -149,6 +149,36 @@ class TestMultiCityCommand:args, _ = mock_search_flights.search.call_argsassert args[0].passenger_info.adults == 2+ def test_with_family_passenger_mix(self, runner, mock_search_flights, mock_console):+ """Test multi-city search passes the full passenger mix into filters."""+ date1 = _future_date(30)+ date2 = _future_date(37)++ result = runner.invoke(+ app,+ [+ "multi",+ "--leg",+ f"SEA,HKG,{date1}",+ "--leg",+ f"HKG,SEA,{date2}",+ "--passengers",+ "2",+ "--children",+ "1",+ "--infants-in-seat",+ "1",+ "--infants-on-lap",+ "1",+ ],+ )+ assert result.exit_code == 0+ args, _ = mock_search_flights.search.call_args+ assert args[0].passenger_info.adults == 2+ assert args[0].passenger_info.children == 1+ assert args[0].passenger_info.infants_in_seat == 1+ assert args[0].passenger_info.infants_on_lap == 1+def test_with_cabin_class(self, runner, mock_search_flights, mock_console):"""Test multi-city search with cabin class filter."""date1 = _future_date(30)@@ -294,3 +324,29 @@ class TestMultiCityValidation:)assert result.exit_code == 1assert "No flights found" in result.stdout++ def test_invalid_passenger_mix_exits_nonzero_with_clean_message(+ self, runner, mock_search_flights, mock_console+ ):+ """A passenger mix Google Flights would reject fails cleanly, not with a pydantic dump."""+ date1 = _future_date(30)+ date2 = _future_date(37)++ result = runner.invoke(+ app,+ [+ "multi",+ "--leg",+ f"SEA,HKG,{date1}",+ "--leg",+ f"HKG,SEA,{date2}",+ "--passengers",+ "1",+ "--infants-on-lap",+ "3",+ ],+ )+ assert result.exit_code == 1+ assert "validation error for" not in result.stdout.lower()+ assert "infants_on_lap" in result.stdout+ mock_search_flights.search.assert_not_called()diff --git a/tests/mcp/test_new_filters.py b/tests/mcp/test_new_filters.pyindex 8478d2f..1b8f93b 100644--- a/tests/mcp/test_new_filters.py+++ b/tests/mcp/test_new_filters.py@@ -308,3 +308,72 @@ class TestPassengerMix:assert info.children == 1assert info.infants_in_seat == 1assert info.infants_on_lap == 1+++# ---------------------------------------------------------------------------+# passenger mix — invalid combinations surface as clean success:false errors+# ---------------------------------------------------------------------------+++class TestPassengerMixValidation:+ """A passenger mix Google Flights would reject returns ``success: false``.++ ``PassengerInfo`` raises a pydantic ``ValidationError`` for these; the+ tool layer already turns any ``ValidationError`` into a+ ``success: False`` payload with the specific pydantic message (see+ ``_format_validation_error`` usage introduced by #215) — these tests+ confirm that also covers the new passenger-count validator.+ """++ def test_search_flights_rejects_too_many_total_passengers(self):+ params = FlightSearchParams(+ origin="JFK",+ destination="LAX",+ departure_date=_future(30),+ passengers=9,+ children=1,+ )+ result = _search_flights_from_params(params)+ assert result["success"] is False+ assert "Total passengers must be between 1 and 9" in result["error"]+ assert result["flights"] == []++ def test_search_flights_rejects_lap_infants_over_adults(self):+ params = FlightSearchParams(+ origin="JFK",+ destination="LAX",+ departure_date=_future(30),+ passengers=1,+ infants_on_lap=3,+ )+ result = _search_flights_from_params(params)+ assert result["success"] is False+ assert "infants_on_lap" in result["error"]+ assert result["flights"] == []++ def test_search_dates_rejects_too_many_total_passengers(self):+ params = DateSearchParams(+ origin="JFK",+ destination="LAX",+ start_date=_future(30),+ end_date=_future(60),+ passengers=9,+ children=1,+ )+ result = _search_dates_from_params(params)+ assert result["success"] is False+ assert "Total passengers must be between 1 and 9" in result["error"]+ assert result["dates"] == []++ def test_get_booking_options_rejects_lap_infants_over_adults(self):+ params = FlightSearchParams(+ origin="JFK",+ destination="LAX",+ departure_date=_future(30),+ passengers=1,+ infants_on_lap=3,+ )+ result = _get_booking_options_from_params(params)+ assert result["success"] is False+ assert "infants_on_lap" in result["error"]+ assert result["options"] == []diff --git a/tests/models/test_passenger_info_validation.py b/tests/models/test_passenger_info_validation.pynew file mode 100644index 0000000..e135424--- /dev/null+++ b/tests/models/test_passenger_info_validation.py@@ -0,0 +1,62 @@+"""Tests for PassengerInfo validation.++Google Flights caps a single booking at 9 total passengers and requires+every lap infant to be paired with an adult. Without validation,+``PassengerInfo(adults=1, infants_on_lap=3)`` or 20 adults built fine and+silently produced a wrong quote.+"""++import pytest++from fli.models import PassengerInfo+++def test_single_adult_is_valid():+ """Test the default single-adult mix is accepted."""+ info = PassengerInfo(adults=1)+ assert info.adults == 1+ assert info.children == 0+ assert info.infants_in_seat == 0+ assert info.infants_on_lap == 0+++def test_total_of_nine_is_accepted():+ """Test the maximum allowed total of 9 passengers is accepted."""+ info = PassengerInfo(adults=4, children=2, infants_in_seat=2, infants_on_lap=1)+ assert info.adults + info.children + info.infants_in_seat + info.infants_on_lap == 9+++def test_total_of_ten_is_rejected():+ """Test a total of 10 passengers is rejected."""+ with pytest.raises(ValueError, match="Total passengers must be between 1 and 9"):+ PassengerInfo(adults=4, children=2, infants_in_seat=2, infants_on_lap=2)+++def test_total_of_zero_is_rejected():+ """Test zero total passengers is rejected."""+ with pytest.raises(ValueError, match="Total passengers must be between 1 and 9"):+ PassengerInfo(adults=0, children=0, infants_in_seat=0, infants_on_lap=0)+++def test_lap_infants_equal_to_adults_is_accepted():+ """Test infants_on_lap == adults is accepted (one lap infant per adult)."""+ info = PassengerInfo(adults=2, infants_on_lap=2)+ assert info.infants_on_lap == info.adults+++def test_lap_infants_exceeding_adults_is_rejected():+ """Test infants_on_lap > adults is rejected (each lap infant needs an adult)."""+ with pytest.raises(ValueError, match="infants_on_lap"):+ PassengerInfo(adults=1, infants_on_lap=3)+++def test_error_message_names_offending_values():+ """Test the total-passengers error names the actual counts, not just the rule."""+ with pytest.raises(ValueError, match=r"got 10"):+ PassengerInfo(adults=9, children=1)+++def test_lap_infants_error_names_offending_values():+ """Test the lap-infants error names the actual adults/infants_on_lap values."""+ with pytest.raises(ValueError, match=r"infants_on_lap \(3\).*adults \(1\)"):+ PassengerInfo(adults=1, infants_on_lap=3)diff --git a/tests/search/test_search_flights_fuzz.py b/tests/search/test_search_flights_fuzz.pyindex ac14919..b37debb 100644--- a/tests/search/test_search_flights_fuzz.py+++ b/tests/search/test_search_flights_fuzz.py@@ -55,8 +55,16 @@ def generate_random_test_cases(num_tests: int) -> list[tuple]:dep_date = today + timedelta(days=random.randint(1, 365))adults = random.randint(1, 4)children = random.randint(0, 2)- infants_on_lap = random.randint(0, adults)- infants_in_seat = random.randint(0, max(0, adults - infants_on_lap))+ # PassengerInfo caps the booking-wide total at 9 (Google Flights' own+ # limit) and requires infants_on_lap <= adults; bound each draw by the+ # remaining headroom so the generator never produces a mix the model+ # would reject outright.+ remaining_after_children = max(0, 9 - adults - children)+ infants_on_lap = random.randint(0, min(adults, remaining_after_children))+ remaining_after_lap = max(0, remaining_after_children - infants_on_lap)+ infants_in_seat = random.randint(+ 0, min(max(0, adults - infants_on_lap), remaining_after_lap)+ )seat_type = random.choice(seat_types)stops = random.choice(max_stops)sort_by = random.choice(sort_bys)