Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

feat: machine-readable error_type and retryable on MCP and CLI JSON errors (#248)

Punit Arani546ab9eb4b6b
diff --git a/CLAUDE.md b/CLAUDE.md
index 76fdbfa..e378715 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -249,6 +249,42 @@ options — each with a clickable `booking_url` and `google_click_url`.
user saw.
- `currency`, `language`, `country` - Same locale knobs as `search_flights`
+### Error responses (`error_type` / `retryable`)
+Every tool's failure response (`success: false`) carries `error_type` (a
+stable string) and `retryable` (bool) alongside the existing free-text
+`error` message, so a caller can decide what to do without string-matching
+`error`. `http_error` responses also carry `http_status` when the upstream
+status code is known. Classification is by exception **type**, never by
+message text — see `fli.core.errors.classify_error` (`fli/core/errors.py`).
+
+**This vocabulary is shared** by the MCP tools *and* the CLI's
+`--format json` error output (`fli/cli/errors.py::json_error_payload`) —
+both call the same `classify_error`, so the same exception always produces
+the same `error_type` string on either surface. Some values are a released
+contract from the CLI (`"timeout"`, `"connection_error"`, `"http_error"`,
+`"search_error"`, `"unexpected_error"`, shipped in v0.9.0) and were kept
+as-is rather than renamed for the MCP tools.
+
+| `error_type` | `retryable` | Meaning / what to do |
+|---|---|---|
+| `validation_error` | `false` | Bad input — unknown airport code, an invalid passenger mix, a date range over the 93-date cap, etc. Fix the request; retrying unchanged will fail again. |
+| `unsupported_error` | `false` | The request is well-formed but this transport can't serve it (e.g. multi-city). Change the request. |
+| `parse_error` | `false` | Google served a page fli couldn't read. Usually (not always) a regional consent/blocked interstitial. Not retryable as-is; set `FLI_SOCS_COOKIE` (EU/EEA) and retry — don't just retry the same request unchanged. |
+| `rejected_error` | `false` | Google refused the RPC outright (e.g. `get_booking_options`'s `GetBookingResults` call today — see above). Deterministic; retrying the same request will not help. |
+| `timeout` | `true` | The request to Google Flights timed out. See retry guidance below. |
+| `connection_error` | `true` | A network/DNS issue prevented reaching Google Flights. See retry guidance below. |
+| `http_error` | `true` iff `http_status` is 429 or 5xx | Non-2xx HTTP response from Google; check `http_status`. See retry guidance below. |
+| `search_error` | `false` | Any other typed search-client failure not covered above. |
+| `unexpected_error` | `false` | An unclassified exception — most likely a bug, worth reporting. |
+
+**Retry guidance for `retryable: true`.** The HTTP client has *already*
+retried internally with backoff before raising (`fli/search/client.py`'s
+`tenacity` decorator) — a caller seeing `retryable: true` should retry **at
+most once or twice more**, with its own exponential backoff in *seconds*
+(not milliseconds) between attempts, not hammer the endpoint immediately.
+`http_status: 429` specifically means Google is telling you to slow down —
+back off more, not less.
+
### Note on passenger limits
`PassengerInfo` (`fli/models/google_flights/base.py`) validates every
passenger mix against Google Flights' own booking limits: total travelers
diff --git a/docs/guides/mcp.md b/docs/guides/mcp.md
index 009585c..3e52cba 100644
--- a/docs/guides/mcp.md
+++ b/docs/guides/mcp.md
@@ -287,6 +287,55 @@ you can retry with a valid identifier.
specific flight's booking page directly, or fall back to the top-level
`booking_url` for the search page.
+## Error Responses
+
+Every tool's failure response (`success: false`) also carries `error_type` (a
+stable string) and `retryable` (a bool), alongside the existing free-text
+`error` message — so a caller can decide what to do next without
+string-matching `error`. `http_error` responses additionally carry
+`http_status` when the upstream status code is known. Classification is by
+exception **type**, never by message text, so `error_type` will not change
+out from under you even if wording on `error` does.
+
+This vocabulary is **shared with the CLI**: `fli flights ... --format json`
+and `fli dates ... --format json` errors use the exact same `error_type`
+strings from the exact same classifier (`fli.core.errors.classify_error`),
+so an agent or script that handles both surfaces only needs to learn the
+vocabulary once.
+
+| `error_type` | `retryable` | Meaning / what to do |
+|---|---|---|
+| `validation_error` | `false` | Bad input — unknown airport code, an invalid passenger mix, a date range over the 93-date cap, etc. Fix the request; retrying unchanged will fail again. |
+| `unsupported_error` | `false` | The request is well-formed but this transport can't serve it (e.g. multi-city). Change the request. |
+| `parse_error` | `false` | Google served a page fli couldn't read. Usually (not always) a regional consent/blocked interstitial. Not retryable as-is; set `FLI_SOCS_COOKIE` (EU/EEA) and retry — don't just retry the same request unchanged. |
+| `rejected_error` | `false` | Google refused the RPC outright (e.g. `get_booking_options`'s `GetBookingResults` call today). Deterministic; retrying the same request will not help. |
+| `timeout` | `true` | The request to Google Flights timed out. See retry guidance below. |
+| `connection_error` | `true` | A network/DNS issue prevented reaching Google Flights. See retry guidance below. |
+| `http_error` | `true` iff `http_status` is 429 or 5xx | Non-2xx HTTP response from Google; check `http_status`. See retry guidance below. |
+| `search_error` | `false` | Any other typed search-client failure not covered above. |
+| `unexpected_error` | `false` | An unclassified exception — most likely a bug, worth reporting. |
+
+!!! warning "Retry guidance for `retryable: true`"
+ The client has **already retried internally** with backoff before
+ raising (see the `tenacity`-based retry in `fli/search/client.py`). A
+ caller that sees `retryable: true` should retry **at most once or
+ twice more**, with its own exponential backoff measured in **seconds**
+ (not milliseconds) between attempts — not hammer the endpoint
+ immediately. `http_status: 429` specifically is Google telling you to
+ slow down — back off more, not less.
+
+**Example error response:**
+
+```json
+{
+ "success": false,
+ "error": "Search failed: Timed out talking to Google Flights (www.google.com). ...",
+ "flights": [],
+ "error_type": "timeout",
+ "retryable": true
+}
+```
+
## 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 4c30241..1a996fa 100644
--- a/fli/cli/commands/dates.py
+++ b/fli/cli/commands/dates.py
@@ -21,6 +21,7 @@ from fli.cli.utils import (
)
from fli.core import (
build_date_search_segments,
+ classify_error,
format_validation_error,
parse_airlines,
parse_alliances,
@@ -508,6 +509,7 @@ def dates(
)
],
},
+ **classify_error(e).as_fields(),
)
)
raise typer.Exit(1) from e
@@ -515,13 +517,15 @@ def dates(
raise typer.Exit(1) from e
except SearchClientError as e:
if output_format == OutputFormat.JSON:
- message, error_type, log_path = json_error_payload(e, command="dates")
+ payload_info = json_error_payload(e, command="dates")
payload = build_json_error_response(
search_type="dates",
- message=message,
- error_type=error_type,
+ message=payload_info.message,
+ error_type=payload_info.error_type,
+ retryable=payload_info.retryable,
+ http_status=payload_info.http_status,
)
- payload["error"]["log_path"] = str(log_path)
+ payload["error"]["log_path"] = str(payload_info.log_path)
emit_json(payload)
raise typer.Exit(1) from e
raise report_cli_error(e, command="dates") from e
@@ -533,6 +537,7 @@ def dates(
search_type="dates",
message=message,
query=query,
+ **classify_error(e).as_fields(),
)
)
raise typer.Exit(1) from e
@@ -542,12 +547,22 @@ def dates(
except (AttributeError, ValueError) as e:
if "module 'fli.search' has no attribute 'SearchDates'" in str(e):
raise
+ # Historically this caught a bare AttributeError from an unknown
+ # airport/airline code; fli.core.parsers now converts those to
+ # ParseError before they ever reach here (see the except above), so
+ # in practice this block only sees: a bare ValueError (e.g. the
+ # 93-date search-range cap raised by SearchDates.search()) ->
+ # classify_error's validation_error bucket; or a genuine
+ # AttributeError from an unrelated bug elsewhere in the call stack
+ # -> classify_error's unexpected_error bucket, since it isn't a
+ # recognized search-client or input-validation failure. T10 fix
+ # round 2, maintainer ruling U1: previously hardcoded
+ # "search_error" for both — see the report's "Behaviour changes".
if output_format == OutputFormat.JSON:
emit_json(
build_json_error_response(
search_type="dates",
message=str(e),
- error_type="search_error",
query={
"origin": origin,
"destination": destination,
@@ -577,6 +592,7 @@ def dates(
)
],
},
+ **classify_error(e).as_fields(),
)
)
raise typer.Exit(1) from e
@@ -584,13 +600,15 @@ def dates(
raise typer.Exit(1) from e
except Exception as e: # noqa: BLE001 — fall back to clean reporting
if output_format == OutputFormat.JSON:
- message, error_type, log_path = json_error_payload(e, command="dates")
+ payload_info = json_error_payload(e, command="dates")
payload = build_json_error_response(
search_type="dates",
- message=message,
- error_type=error_type,
+ message=payload_info.message,
+ error_type=payload_info.error_type,
+ retryable=payload_info.retryable,
+ http_status=payload_info.http_status,
)
- payload["error"]["log_path"] = str(log_path)
+ payload["error"]["log_path"] = str(payload_info.log_path)
emit_json(payload)
raise typer.Exit(1) from e
raise report_cli_error(e, command="dates") from e
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
index 7bf2cf4..7535c94 100644
--- a/fli/cli/commands/flights.py
+++ b/fli/cli/commands/flights.py
@@ -19,6 +19,7 @@ from fli.cli.utils import (
)
from fli.core import (
build_flight_segments,
+ classify_error,
format_validation_error,
google_flights_url,
parse_airlines,
@@ -259,6 +260,7 @@ def _search_flights_core(
search_type="flights",
message=str(e),
query=query,
+ **classify_error(e).as_fields(),
)
)
raise typer.Exit(1) from e
@@ -273,6 +275,7 @@ def _search_flights_core(
search_type="flights",
message=message,
query=query,
+ **classify_error(e).as_fields(),
)
)
raise typer.Exit(1) from e
@@ -280,13 +283,24 @@ def _search_flights_core(
typer.echo(f"Error: {message}")
raise typer.Exit(1) from e
except (AttributeError, ValueError) as e:
+ # Historically this caught a bare AttributeError from an unknown
+ # airport/airline code; fli.core.parsers now converts those to
+ # ParseError before they ever reach here (see the except above), so
+ # in practice this block only sees: a bare ValueError (e.g. the
+ # 93-date search-range cap, or any other library call that raises
+ # ValueError directly) -> classify_error's validation_error bucket;
+ # or a genuine AttributeError from an unrelated bug elsewhere in the
+ # call stack -> classify_error's unexpected_error bucket, since it
+ # isn't a recognized search-client or input-validation failure.
+ # T10 fix round 2, maintainer ruling U1: previously hardcoded
+ # "search_error" for both — see the report's "Behaviour changes".
if output_format == OutputFormat.JSON:
emit_json(
build_json_error_response(
search_type="flights",
message=str(e),
- error_type="search_error",
query=query,
+ **classify_error(e).as_fields(),
)
)
raise typer.Exit(1) from e
@@ -295,27 +309,31 @@ def _search_flights_core(
raise typer.Exit(1) from e
except SearchClientError as e:
if output_format == OutputFormat.JSON:
- message, error_type, log_path = json_error_payload(e, command="flights")
+ payload_info = json_error_payload(e, command="flights")
payload = build_json_error_response(
search_type="flights",
- message=message,
- error_type=error_type,
+ message=payload_info.message,
+ error_type=payload_info.error_type,
+ retryable=payload_info.retryable,
+ http_status=payload_info.http_status,
query=query,
)
- payload["error"]["log_path"] = str(log_path)
+ payload["error"]["log_path"] = str(payload_info.log_path)
emit_json(payload)
raise typer.Exit(1) from e
raise report_cli_error(e, command="flights") from e
except Exception as e: # noqa: BLE001 — fall back to clean reporting
if output_format == OutputFormat.JSON:
- message, error_type, log_path = json_error_payload(e, command="flights")
+ payload_info = json_error_payload(e, command="flights")
payload = build_json_error_response(
search_type="flights",
- message=message,
- error_type=error_type,
+ message=payload_info.message,
+ error_type=payload_info.error_type,
+ retryable=payload_info.retryable,
+ http_status=payload_info.http_status,
query=query,
)
- payload["error"]["log_path"] = str(log_path)
+ payload["error"]["log_path"] = str(payload_info.log_path)
emit_json(payload)
raise typer.Exit(1) from e
raise report_cli_error(e, command="flights") from e
diff --git a/fli/cli/errors.py b/fli/cli/errors.py
index f96dcdd..2045f42 100644
--- a/fli/cli/errors.py
+++ b/fli/cli/errors.py
@@ -10,12 +10,14 @@ from __future__ import annotations
import logging
import sys
import traceback
+from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
import typer
from fli.cli.console import console
+from fli.core.errors import classify_error
from fli.search.exceptions import (
SearchClientError,
SearchConnectionError,
@@ -97,19 +99,46 @@ def report_cli_error(
return typer.Exit(exit_code)
-def json_error_payload(exc: BaseException, *, command: str | None = None) -> tuple[str, str, Path]:
- """Return ``(message, error_type, log_path)`` for JSON-mode error output."""
+@dataclass(frozen=True)
+class JsonErrorPayload:
+ """Everything a CLI ``--format json`` error path needs, from one classification.
+
+ A named structure (rather than a positional tuple) on purpose: T10 fix
+ round 2 added ``retryable``/``http_status`` alongside the original
+ ``message``/``error_type``/``log_path`` triple, and a wider tuple would
+ have made every call site's unpacking order a silent trap. Use
+ attribute access (``payload.error_type``, ...) at call sites.
+ """
+
+ message: str
+ error_type: str
+ retryable: bool
+ http_status: int | None
+ log_path: Path
+
+
+def json_error_payload(exc: BaseException, *, command: str | None = None) -> JsonErrorPayload:
+ """Return the classified JSON-mode error payload for ``exc``.
+
+ ``error_type`` (and, since T10 fix round 2, ``retryable``/``http_status``)
+ come from the shared :func:`fli.core.errors.classify_error` classifier —
+ the same one ``fli.mcp.server`` uses for MCP tool error responses — so a
+ CLI ``--format json`` error and an MCP error for the same exception
+ always agree. See that module's docstring for the full vocabulary table
+ and retry guidance.
+
+ The message formatting is unchanged from before this classifier existed:
+ ``str(exc)`` for any :class:`SearchClientError`, and
+ ``f"{type}: {exc}"`` for anything else — only ``error_type`` itself was
+ ever hand-rolled here, and it has moved to the shared classifier.
+ """
log_path = _write_log(exc, command=command)
- if isinstance(exc, SearchTimeoutError):
- return str(exc), "timeout", log_path
- if isinstance(exc, SearchConnectionError):
- return str(exc), "connection_error", log_path
- if isinstance(exc, SearchHTTPError):
- return str(exc), "http_error", log_path
- if isinstance(exc, SearchRejectedError):
- return str(exc), "rejected", log_path
- if isinstance(exc, SearchParseError):
- return str(exc), "parse_error", log_path
- if isinstance(exc, SearchClientError):
- return str(exc), "search_error", log_path
- return f"{exc.__class__.__name__}: {exc}", "unexpected_error", log_path
+ classification = classify_error(exc)
+ message = str(exc) if isinstance(exc, SearchClientError) else f"{exc.__class__.__name__}: {exc}"
+ return JsonErrorPayload(
+ message=message,
+ error_type=classification.error_type,
+ retryable=classification.retryable,
+ http_status=classification.http_status,
+ log_path=log_path,
+ )
diff --git a/fli/cli/utils.py b/fli/cli/utils.py
index fa079a4..abbb8c8 100644
--- a/fli/cli/utils.py
+++ b/fli/cli/utils.py
@@ -367,9 +367,17 @@ def build_json_error_response(
search_type: str,
message: str,
error_type: str = "validation_error",
+ retryable: bool = False,
+ http_status: int | None = None,
query: dict[str, Any] | None = None,
) -> dict[str, Any]:
- """Build a JSON error payload for CLI commands."""
+ """Build a JSON error payload for CLI commands.
+
+ ``retryable`` and (when known) ``http_status`` mirror the MCP tools'
+ error responses — both come from the same
+ :func:`fli.core.errors.classify_error`, typically passed straight
+ through via ``**classify_error(exc).as_fields()`` at the call site.
+ """
payload = {
"success": False,
"data_source": "google_flights",
@@ -377,8 +385,11 @@ def build_json_error_response(
"error": {
"type": error_type,
"message": message,
+ "retryable": retryable,
},
}
+ if http_status is not None:
+ payload["error"]["http_status"] = http_status
if query is not None:
payload["query"] = query
return payload
diff --git a/fli/core/__init__.py b/fli/core/__init__.py
index 1847dbc..dfe182e 100644
--- a/fli/core/__init__.py
+++ b/fli/core/__init__.py
@@ -13,7 +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_error
+from .errors import ErrorClassification, classify_error, format_validation_error
from .links import google_flights_url, with_locale_params
from .parsers import (
parse_airlines,
@@ -54,6 +54,8 @@ __all__ = [
"format_price",
"format_price_axis_label",
# Errors
+ "ErrorClassification",
+ "classify_error",
"format_validation_error",
# Links
"google_flights_url",
diff --git a/fli/core/errors.py b/fli/core/errors.py
index 9337023..9d76697 100644
--- a/fli/core/errors.py
+++ b/fli/core/errors.py
@@ -1,13 +1,90 @@
-"""Shared error-formatting utilities for the CLI and MCP interfaces.
+"""Shared error-formatting and error-classification utilities.
-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.
+Two related jobs live here, both shared verbatim between the CLI and the
+MCP interfaces so the two surfaces can never drift apart:
+
+1. ``format_validation_error`` flattens pydantic's multi-line
+ ``ValidationError`` dump into one actionable line.
+2. ``classify_error`` maps any exception a search can raise into a stable,
+ machine-readable ``(error_type, retryable[, http_status])`` triple.
+
+Design note on (2) — why this lives in ``fli.core`` and not ``fli.mcp`` or
+``fli.cli``: a review of the first cut of this classifier found that
+``fli.cli.errors.json_error_payload`` already emitted a field literally
+named ``error_type`` for the same exceptions, with a *different* string
+for some of them (``"timeout"`` shipped in the CLI since v0.9.0 vs.
+``"timeout_error"`` in the first MCP-only cut). Two vocabularies under one
+field name is a trap for anyone building against both surfaces. The fix is
+one classifier, used by both ``fli.mcp.server`` and
+``fli.cli.errors.json_error_payload`` — which means it cannot live in
+either interface package. This is a deliberate, narrow exception to the
+general rule (see ``fli/core/links.py``) that ``fli.core`` stays free of a
+dependency on ``fli.search``: unlike ``with_locale_params``,
+``classify_error`` has no way to exist without knowing the
+``fli.search.exceptions`` type hierarchy, and duplicating it per interface
+is exactly what caused the drift this module now prevents.
+
+**Vocabulary.** Released values (shipped in the CLI's ``--format json``
+error output before this module existed) are a contract and were kept
+as-is: ``"timeout"``, ``"connection_error"``, ``"http_error"``,
+``"search_error"``, ``"unexpected_error"``. Everything else was free to
+pick: ``"parse_error"`` (not ``"blocked_error"``) matches what the CLI and
+PR #164 already independently converged on, and names *what happened*
+(a page arrived but couldn't be read) rather than asserting *why*
+(usually, but not always, a consent/blocked interstitial — see
+``FLI_SOCS_COOKIE`` below). ``"rejected_error"``, ``"unsupported_error"``
+and ``"validation_error"`` are new additions both surfaces now share.
+
+- ``validation_error`` (not retryable): bad parameters — pydantic
+ ``ValidationError``, ``fli.core.parsers.ParseError``, or a bare
+ ``ValueError`` (e.g. the 93-date search-range cap).
+- ``unsupported_error`` (not retryable): ``SearchUnsupportedError``, e.g.
+ multi-city.
+- ``parse_error`` (not retryable as-is): ``SearchParseError`` — a page
+ arrived but couldn't be read, usually a regional consent/blocked
+ interstitial. Set ``FLI_SOCS_COOKIE`` (EU/EEA) and retry; don't just
+ retry the same request unchanged.
+- ``rejected_error`` (not retryable): ``SearchRejectedError`` — Google
+ refused the RPC outright (e.g. booking options); deterministic,
+ retrying will not help.
+- ``timeout`` (retryable): ``SearchTimeoutError``.
+- ``connection_error`` (retryable): ``SearchConnectionError``.
+- ``http_error`` (retryable iff ``http_status`` is 429 or 5xx):
+ ``SearchHTTPError``, with the status in ``http_status`` when known.
+- ``search_error`` (not retryable): any other ``SearchClientError``.
+- ``unexpected_error`` (not retryable): anything else — a bug, not a
+ known failure mode.
+
+**Retry guidance for ``retryable: true``.** Both the CLI's HTTP client and
+the search layer it wraps have *already* retried internally with backoff
+before ever raising — see ``fli/search/client.py``'s ``tenacity`` retry
+decorator. A caller (human or agent) that sees ``retryable: true`` should
+retry **at most once or twice more**, with its own exponential backoff
+measured in seconds (not milliseconds) between attempts — not hammer the
+endpoint immediately. For ``http_error`` with ``http_status: 429``
+specifically, that status *is* Google explicitly saying "slow down":
+back off more, not less.
"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
from pydantic import ValidationError
+from fli.search.exceptions import (
+ SearchClientError,
+ SearchConnectionError,
+ SearchHTTPError,
+ SearchParseError,
+ SearchRejectedError,
+ SearchTimeoutError,
+ SearchUnsupportedError,
+)
+
+_RETRYABLE_HTTP_STATUSES = {429}
+
def format_validation_error(exc: ValidationError) -> str:
"""Flatten a pydantic ``ValidationError`` into one actionable message.
@@ -21,3 +98,73 @@ def format_validation_error(exc: ValidationError) -> str:
location = ".".join(str(part) for part in error["loc"]) or "input"
problems.append(f"{location}: {error['msg']}")
return f"Invalid parameter value - {'; '.join(problems)}"
+
+
+@dataclass(frozen=True)
+class ErrorClassification:
+ """Stable, machine-readable shape describing why a search call failed."""
+
+ error_type: str
+ retryable: bool
+ http_status: int | None = None
+
+ def as_fields(self) -> dict[str, Any]:
+ """Return the dict fields to splice into an MCP error response.
+
+ `http_status` is only included when known (i.e. for `http_error`
+ responses where the upstream status code was captured), so every
+ other response shape stays exactly as additive as `error_type` /
+ `retryable` themselves — no caller sees a new key it can't explain.
+ """
+ fields: dict[str, Any] = {"error_type": self.error_type, "retryable": self.retryable}
+ if self.http_status is not None:
+ fields["http_status"] = self.http_status
+ return fields
+
+
+def classify_error(exc: BaseException) -> ErrorClassification:
+ """Classify ``exc`` into a stable ``error_type`` + ``retryable`` pair.
+
+ Checks run most-specific-subclass first, purely by exception **type**
+ (never by message text — wording is free to change without breaking
+ callers that key off `error_type`). See the module docstring for the
+ full vocabulary table, the CLI/MCP-parity rationale, and retry guidance.
+ """
+ if isinstance(exc, SearchTimeoutError):
+ return ErrorClassification("timeout", retryable=True)
+ if isinstance(exc, SearchConnectionError):
+ return ErrorClassification("connection_error", retryable=True)
+ if isinstance(exc, SearchHTTPError):
+ status = exc.status_code
+ retryable = status is not None and (status in _RETRYABLE_HTTP_STATUSES or status >= 500)
+ return ErrorClassification("http_error", retryable=retryable, http_status=status)
+ if isinstance(exc, SearchRejectedError):
+ # Google answered but declined the RPC outright (e.g. booking
+ # options without a browser-signed header). Deterministic for a
+ # plain HTTP client — retrying the same request will not help.
+ return ErrorClassification("rejected_error", retryable=False)
+ if isinstance(exc, SearchUnsupportedError):
+ # The query is well formed but this transport has no path to
+ # answer it (e.g. multi-city). Retrying will not help; the
+ # request itself needs to change.
+ return ErrorClassification("unsupported_error", retryable=False)
+ if isinstance(exc, SearchParseError):
+ # A page arrived but couldn't be read — most often a regional
+ # consent/blocked interstitial. Not retryable *as-is*: the caller
+ # needs to set FLI_SOCS_COOKIE (EU/EEA consent) or otherwise
+ # change the request, not just retry the same one.
+ return ErrorClassification("parse_error", retryable=False)
+ if isinstance(exc, SearchClientError):
+ # Catch-all for any other/future SearchClientError subclass that
+ # doesn't have a more specific bucket above yet. Deterministic
+ # until proven otherwise.
+ return ErrorClassification("search_error", retryable=False)
+ if isinstance(exc, ValidationError | ValueError):
+ # Covers pydantic ValidationError, fli.core.parsers.ParseError
+ # (a ValueError subclass used for bad airport/airline/etc. input),
+ # and bare ValueError — notably the 93-date-per-search cap raised
+ # by SearchDates.search(). All three mean "the request itself is
+ # invalid", which the caller must fix before retrying, so they
+ # share validation_error/not-retryable.
+ return ErrorClassification("validation_error", retryable=False)
+ return ErrorClassification("unexpected_error", retryable=False)
diff --git a/fli/mcp/server.py b/fli/mcp/server.py
index 94a0bd0..b4018a6 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,
+ classify_error,
format_validation_error,
google_flights_url,
parse_airlines,
@@ -749,11 +750,26 @@ def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
}
except ParseError as e:
- return {"success": False, "error": str(e), "flights": []}
+ return {
+ "success": False,
+ "error": str(e),
+ "flights": [],
+ **classify_error(e).as_fields(),
+ }
except ValidationError as e:
- return {"success": False, "error": format_validation_error(e), "flights": []}
+ return {
+ "success": False,
+ "error": format_validation_error(e),
+ "flights": [],
+ **classify_error(e).as_fields(),
+ }
except Exception as e:
- return {"success": False, "error": _search_error_message(e), "flights": []}
+ return {
+ "success": False,
+ "error": _search_error_message(e),
+ "flights": [],
+ **classify_error(e).as_fields(),
+ }
def _execute_booking_options(
@@ -803,6 +819,11 @@ def _execute_booking_options(
"available_flights": [_flight_idents(f) for f in flights[:20]],
"options": [],
"booking_url": booking_url,
+ # Not an exception — the caller passed flight_numbers that don't
+ # match any result from this search. Deterministic and
+ # caller-fixable, same bucket as a bad parameter.
+ "error_type": "validation_error",
+ "retryable": False,
}
options = search_client.get_booking_options(
@@ -844,14 +865,25 @@ def _execute_booking_options(
return result
except ParseError as e:
- return {"success": False, "error": str(e), "options": []}
+ return {
+ "success": False,
+ "error": str(e),
+ "options": [],
+ **classify_error(e).as_fields(),
+ }
except ValidationError as e:
- return {"success": False, "error": format_validation_error(e), "options": []}
+ return {
+ "success": False,
+ "error": format_validation_error(e),
+ "options": [],
+ **classify_error(e).as_fields(),
+ }
except Exception as e:
return {
"success": False,
"error": _search_error_message(e, "Booking lookup failed"),
"options": [],
+ **classify_error(e).as_fields(),
}
@@ -952,11 +984,26 @@ def _execute_date_search(params: DateSearchParams) -> dict[str, Any]:
}
except ParseError as e:
- return {"success": False, "error": str(e), "dates": []}
+ return {
+ "success": False,
+ "error": str(e),
+ "dates": [],
+ **classify_error(e).as_fields(),
+ }
except ValidationError as e:
- return {"success": False, "error": format_validation_error(e), "dates": []}
+ return {
+ "success": False,
+ "error": format_validation_error(e),
+ "dates": [],
+ **classify_error(e).as_fields(),
+ }
except Exception as e:
- return {"success": False, "error": _search_error_message(e), "dates": []}
+ return {
+ "success": False,
+ "error": _search_error_message(e),
+ "dates": [],
+ **classify_error(e).as_fields(),
+ }
# =============================================================================
@@ -1096,6 +1143,13 @@ def search_flights(
Returns a list of available flights with prices, durations, and leg details.
Supports one-way and round-trip searches with various filtering options.
+
+ On failure (`success: false`), the response also carries `error_type`
+ (e.g. `validation_error`, `timeout`, `parse_error`) and a `retryable`
+ bool — classify the failure from `error_type` instead of parsing the
+ `error` message text. The client has already retried internally with
+ backoff; if `retryable` is true, retry at most once or twice more with
+ your own exponential backoff in seconds (429 means slow down further).
"""
effective_departure_window = departure_window or CONFIG.default_departure_window
params = FlightSearchParams(
@@ -1247,6 +1301,13 @@ def search_dates(
Returns a list of dates with their prices, useful for flexible travel planning.
Supports both one-way and round-trip searches.
+
+ On failure (`success: false`), the response also carries `error_type`
+ (e.g. `validation_error`, `timeout`, `parse_error`) and a `retryable`
+ bool — classify the failure from `error_type` instead of parsing the
+ `error` message text. The client has already retried internally with
+ backoff; if `retryable` is true, retry at most once or twice more with
+ your own exponential backoff in seconds (429 means slow down further).
"""
effective_departure_window = departure_window or CONFIG.default_departure_window
params = DateSearchParams(
@@ -1420,6 +1481,15 @@ def get_booking_options(
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.
+
+ On failure (``success: false``, including "no flight matched
+ flight_numbers"), the response also carries ``error_type`` (e.g.
+ ``validation_error``, ``rejected_error``) and a ``retryable`` bool —
+ classify the failure from ``error_type`` instead of parsing the
+ ``error`` message text. The client has already retried internally with
+ backoff; if ``retryable`` is true, retry at most once or twice more
+ with your own exponential backoff in seconds (429 means slow down
+ further).
"""
effective_departure_window = departure_window or CONFIG.default_departure_window
params = FlightSearchParams(
@@ -1468,6 +1538,7 @@ def _find_airports_impl(query: str, limit: int = 10) -> dict[str, Any]:
"success": False,
"error": str(exc),
"query": query,
+ **classify_error(exc).as_fields(),
}
return {
@@ -1505,6 +1576,11 @@ def find_airports(
Supports city names (e.g., "new york" returns JFK, LGA, EWR),
airport names (e.g., "heathrow" returns LHR), IATA codes, and 4-letter
ICAO codes (e.g., "KJFK" returns JFK).
+
+ On failure (``success: false``), the response also carries ``error_type``
+ (currently always ``unexpected_error`` for this tool, since airport
+ lookup is local and has no known-transient failure modes) and a
+ ``retryable`` bool.
"""
return _find_airports_impl(query, limit=limit)
diff --git a/tests/cli/test_dates.py b/tests/cli/test_dates.py
index 79a2c5e..408bce7 100644
--- a/tests/cli/test_dates.py
+++ b/tests/cli/test_dates.py
@@ -10,6 +10,12 @@ from fli.cli.main import app
from fli.models import Airline
from fli.models.google_flights.base import TripType
from fli.search import DatePrice
+from fli.search.exceptions import (
+ SearchClientError,
+ SearchConnectionError,
+ SearchHTTPError,
+ SearchTimeoutError,
+)
@pytest.fixture
@@ -398,7 +404,16 @@ def test_dates_over_the_cap_reports_cleanly(runner, mock_console):
def test_dates_over_the_cap_json(runner, mock_console):
- """The same cap error is a structured JSON error, not a crash."""
+ """The same cap error is a structured JSON error, not a crash.
+
+ T10 fix round 2, maintainer ruling U1: this is a bare ``ValueError``
+ raised by ``SearchDates.search()`` with no mocking involved — it used
+ to hit the CLI's ``except (AttributeError, ValueError)`` block and get
+ hardcoded ``error_type="search_error"``. It's now routed through the
+ shared classifier and reports ``validation_error`` (deliberate
+ behaviour change, see the report's "Behaviour changes" section) plus
+ the new ``retryable`` field.
+ """
from_date = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
to_date = (datetime.now() + timedelta(days=200)).strftime("%Y-%m-%d")
@@ -411,3 +426,58 @@ def test_dates_over_the_cap_json(runner, mock_console):
payload = json.loads(result.stdout)
assert payload["success"] is False
assert "93-date limit" in payload["error"]["message"]
+ assert payload["error"]["type"] == "validation_error"
+ assert payload["error"]["retryable"] is False
+
+
+def test_dates_json_invalid_airport_code(runner, mock_search_dates, mock_console):
+ """An unresolvable airport code reports validation_error, not a crash."""
+ result = runner.invoke(
+ app,
+ ["dates", "ZZZZ", "LAX", "--format", "json"],
+ )
+
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout)
+ assert payload["success"] is False
+ assert payload["error"]["type"] == "validation_error"
+ assert payload["error"]["retryable"] is False
+ mock_search_dates.search.assert_not_called()
+
+
+ "exc, expected_type, expected_retryable",
+ [
+ # Released v0.9.0 CLI --format json values — must not move.
+ pytest.param(SearchTimeoutError("slow"), "timeout", True, id="timeout"),
+ pytest.param(SearchConnectionError("no route"), "connection_error", True, id="connection"),
+ pytest.param(SearchHTTPError("bad gw", status_code=502), "http_error", True, id="http-5xx"),
+ pytest.param(
+ SearchClientError("generic"), "search_error", False, id="generic-search-error"
+ ),
+ pytest.param(RuntimeError("bug"), "unexpected_error", False, id="unexpected"),
+ # Gained in T10 fix round 2 (U1): a bare AttributeError used to be
+ # hardcoded to "search_error" by the (AttributeError, ValueError)
+ # block; it isn't a SearchClientError or input-validation failure,
+ # so the shared classifier now calls it unexpected_error.
+ pytest.param(
+ AttributeError("'NoneType' object has no attribute 'name'"),
+ "unexpected_error",
+ False,
+ id="bare-attribute-error",
+ ),
+ ],
+)
+def test_dates_json_error_type_matches_shared_classifier(
+ runner, mock_search_dates, mock_console, exc, expected_type, expected_retryable
+):
+ """Dates --format json's error_type/retryable match fli.core.errors.classify_error."""
+ mock_search_dates.search.side_effect = exc
+
+ result = runner.invoke(app, ["dates", "JFK", "LAX", "--format", "json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout)
+ assert payload["success"] is False
+ assert payload["error"]["type"] == expected_type
+ assert payload["error"]["retryable"] is expected_retryable
diff --git a/tests/cli/test_errors.py b/tests/cli/test_errors.py
index 6c970fa..aa7f474 100644
--- a/tests/cli/test_errors.py
+++ b/tests/cli/test_errors.py
@@ -9,11 +9,15 @@ from typer.testing import CliRunner
from fli.cli.errors import _write_log, json_error_payload, report_cli_error
from fli.cli.main import app
+from fli.core.parsers import ParseError
from fli.search.exceptions import (
SearchClientError,
SearchConnectionError,
SearchHTTPError,
+ SearchParseError,
+ SearchRejectedError,
SearchTimeoutError,
+ SearchUnsupportedError,
)
@@ -56,22 +60,56 @@ def test_write_log_creates_file_with_traceback(tmp_path):
@pytest.mark.parametrize(
- "exc, expected_type",
+ "exc, expected_type, expected_retryable",
[
- (SearchTimeoutError("timed out"), "timeout"),
- (SearchConnectionError("dns"), "connection_error"),
- (SearchHTTPError("403", status_code=403), "http_error"),
- (SearchClientError("generic"), "search_error"),
- (RuntimeError("boom"), "unexpected_error"),
+ # Released values (shipped before the shared classifier existed) —
+ # must stay exactly as they are; see fli/core/errors.py and the
+ # T10 fix round 2 report's "Behaviour changes" section.
+ (SearchTimeoutError("timed out"), "timeout", True),
+ (SearchConnectionError("dns"), "connection_error", True),
+ (SearchHTTPError("403", status_code=403), "http_error", False),
+ (SearchClientError("generic"), "search_error", False),
+ (RuntimeError("boom"), "unexpected_error", False),
+ # Gained from the shared fli.core.errors.classify_error classifier
+ # (T10 fix round 1, maintainer ruling V1) — the CLI didn't
+ # distinguish these from "search_error"/"unexpected_error" before.
+ (SearchRejectedError(13), "rejected_error", False),
+ (SearchUnsupportedError("multi-city"), "unsupported_error", False),
+ (SearchParseError("no ds:1 payload"), "parse_error", False),
+ (ParseError("unknown airport code 'ZZZ'"), "validation_error", False),
+ # T10 fix round 2, maintainer ruling U1: these two used to hit the
+ # CLI commands' hand-rolled `except (AttributeError, ValueError)`
+ # block and get hardcoded "search_error". Routed through the shared
+ # classifier here now covers json_error_payload itself; the command
+ # files' own except blocks are covered in tests/cli/test_flights.py
+ # and tests/cli/test_dates.py.
+ (ValueError("bad date range"), "validation_error", False),
+ (AttributeError("'NoneType' object has no attribute 'name'"), "unexpected_error", False),
],
)
-def test_json_error_payload_maps_error_types(exc, expected_type):
- """Each SearchClientError subclass should map to a distinct error_type string."""
- message, error_type, log_path = json_error_payload(exc)
- assert error_type == expected_type
- assert isinstance(log_path, Path)
- assert log_path.exists()
- assert message # non-empty
+def test_json_error_payload_maps_error_types(exc, expected_type, expected_retryable):
+ """Each exception class should map to the shared classifier's error_type string."""
+ payload = json_error_payload(exc)
+ assert payload.error_type == expected_type
+ assert payload.retryable is expected_retryable
+ assert isinstance(payload.log_path, Path)
+ assert payload.log_path.exists()
+ assert payload.message # non-empty
+
+
+def test_json_error_payload_pydantic_validation_error_maps_to_validation_error():
+ """Pydantic's own ValidationError should classify as validation_error too."""
+ from pydantic import BaseModel, ValidationError
+
+ class _Model(BaseModel):
+ passengers: int
+
+ try:
+ _Model(passengers="not-a-number")
+ except ValidationError as exc:
+ payload = json_error_payload(exc)
+ assert payload.error_type == "validation_error"
+ assert payload.retryable is False
def test_report_cli_error_returns_typer_exit_and_writes_log(tmp_path, capsys):
@@ -189,20 +227,32 @@ class TestWriteLogDetails:
class TestJsonErrorPayloadMessages:
def test_message_is_str_of_exception(self):
exc = SearchTimeoutError("timed out waiting for response")
- message, _, _ = json_error_payload(exc)
- assert message == str(exc) == "timed out waiting for response"
+ payload = json_error_payload(exc)
+ assert payload.message == str(exc) == "timed out waiting for response"
def test_unexpected_error_message_format(self):
exc = RuntimeError("bad input")
- message, error_type, _ = json_error_payload(exc)
- assert message == "RuntimeError: bad input"
- assert error_type == "unexpected_error"
+ payload = json_error_payload(exc)
+ assert payload.message == "RuntimeError: bad input"
+ assert payload.error_type == "unexpected_error"
def test_log_path_is_a_real_file(self):
exc = SearchConnectionError("dns failure")
- _, _, log_path = json_error_payload(exc)
- assert log_path.exists()
- assert log_path.is_file()
+ payload = json_error_payload(exc)
+ assert payload.log_path.exists()
+ assert payload.log_path.is_file()
+
+ def test_http_status_present_when_known(self):
+ exc = SearchHTTPError("rate limited", status_code=429)
+ payload = json_error_payload(exc)
+ assert payload.error_type == "http_error"
+ assert payload.retryable is True
+ assert payload.http_status == 429
+
+ def test_http_status_none_when_unknown(self):
+ exc = SearchHTTPError("mystery failure", status_code=None)
+ payload = json_error_payload(exc)
+ assert payload.http_status is None
class TestReportCliErrorOptions:
@@ -236,6 +286,7 @@ def test_flights_command_json_error_includes_log_path(runner, monkeypatch, tmp_p
payload = json.loads(result.output)
assert payload["success"] is False
assert payload["error"]["type"] == "connection_error"
+ assert payload["error"]["retryable"] is True
assert "log_path" in payload["error"]
assert Path(payload["error"]["log_path"]).exists()
@@ -277,11 +328,14 @@ class TestTransportErrorClassification:
("exc_factory", "expected_type"),
[
(lambda: __import__("fli.search", fromlist=["x"]).SearchParseError("x"), "parse_error"),
- (lambda: __import__("fli.search", fromlist=["x"]).SearchRejectedError(13), "rejected"),
+ (
+ lambda: __import__("fli.search", fromlist=["x"]).SearchRejectedError(13),
+ "rejected_error",
+ ),
],
)
def test_json_error_types(self, exc_factory, expected_type):
from fli.cli.errors import json_error_payload
- _, error_type, _ = json_error_payload(exc_factory(), command="flights")
- assert error_type == expected_type
+ payload = json_error_payload(exc_factory(), command="flights")
+ assert payload.error_type == expected_type
diff --git a/tests/cli/test_flights.py b/tests/cli/test_flights.py
index ede7a38..b3d20a1 100644
--- a/tests/cli/test_flights.py
+++ b/tests/cli/test_flights.py
@@ -9,6 +9,13 @@ from typer.testing import CliRunner
from fli.cli.main import app
from fli.models import Airline, Airport, FlightLeg, FlightResult, SeatType
from fli.models.google_flights.base import TripType
+from fli.search.exceptions import (
+ SearchClientError,
+ SearchConnectionError,
+ SearchHTTPError,
+ SearchParseError,
+ SearchTimeoutError,
+)
@pytest.fixture
@@ -180,6 +187,111 @@ def test_flights_invalid_passenger_mix_json_error(runner, mock_search_flights, m
payload = json.loads(result.stdout)
assert payload["success"] is False
assert "Total passengers must be between 1 and 9" in payload["error"]["message"]
+ assert payload["error"]["type"] == "validation_error"
+ assert payload["error"]["retryable"] is False
+
+
+def test_flights_invalid_lap_infant_mix_json_error(runner, mock_search_flights, mock_console):
+ """1 adult + 2 lap infants (each needs its own adult) is also validation_error."""
+ result = runner.invoke(
+ app,
+ [
+ "flights",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "--passengers",
+ "1",
+ "--infants-on-lap",
+ "2",
+ "--format",
+ "json",
+ ],
+ )
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout)
+ assert payload["success"] is False
+ assert payload["error"]["type"] == "validation_error"
+ assert payload["error"]["retryable"] is False
+ mock_search_flights.search.assert_not_called()
+
+
+def test_flights_json_invalid_airport_code(runner, mock_search_flights, mock_console):
+ """An unresolvable airport code reports validation_error, not a crash."""
+ result = runner.invoke(
+ app,
+ ["flights", "ZZZZ", "LAX", datetime.now().strftime("%Y-%m-%d"), "--format", "json"],
+ )
+
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout)
+ assert payload["success"] is False
+ assert payload["error"]["type"] == "validation_error"
+ assert payload["error"]["retryable"] is False
+ mock_search_flights.search.assert_not_called()
+
+
+def test_flights_json_stubbed_blocked_page(runner, mock_search_flights, mock_console):
+ """A SearchParseError (consent/blocked page) reports parse_error, not retryable as-is."""
+ mock_search_flights.search.side_effect = SearchParseError(
+ "the search page carried no ds:1 payload — Google may have changed the "
+ "page shape, or served a consent/blocked page instead"
+ )
+
+ result = runner.invoke(
+ app,
+ ["flights", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d"), "--format", "json"],
+ )
+
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout)
+ assert payload["success"] is False
+ assert payload["error"]["type"] == "parse_error"
+ assert payload["error"]["retryable"] is False
+
+
+ "exc, expected_type, expected_retryable",
+ [
+ # Released v0.9.0 CLI --format json values — must not move.
+ pytest.param(SearchTimeoutError("slow"), "timeout", True, id="timeout"),
+ pytest.param(SearchConnectionError("no route"), "connection_error", True, id="connection"),
+ pytest.param(SearchHTTPError("bad gw", status_code=502), "http_error", True, id="http-5xx"),
+ pytest.param(
+ SearchClientError("generic"), "search_error", False, id="generic-search-error"
+ ),
+ pytest.param(RuntimeError("bug"), "unexpected_error", False, id="unexpected"),
+ # Gained in T10 fix round 2 (U1): a bare ValueError used to be
+ # hardcoded to "search_error" by the CLI's
+ # except (AttributeError, ValueError) block — now validation_error.
+ pytest.param(ValueError("simulated bug"), "validation_error", False, id="bare-value-error"),
+ # A bare AttributeError isn't a SearchClientError or an
+ # input-validation failure, so the shared classifier calls it
+ # unexpected_error (also previously hardcoded to "search_error").
+ pytest.param(
+ AttributeError("'NoneType' object has no attribute 'name'"),
+ "unexpected_error",
+ False,
+ id="bare-attribute-error",
+ ),
+ ],
+)
+def test_flights_json_error_type_matches_shared_classifier(
+ runner, mock_search_flights, mock_console, exc, expected_type, expected_retryable
+):
+ """Flights --format json's error_type/retryable match fli.core.errors.classify_error."""
+ mock_search_flights.search.side_effect = exc
+
+ result = runner.invoke(
+ app,
+ ["flights", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d"), "--format", "json"],
+ )
+
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout)
+ assert payload["success"] is False
+ assert payload["error"]["type"] == expected_type
+ assert payload["error"]["retryable"] is expected_retryable
def test_flights_with_airlines(runner, mock_search_flights, mock_console):
@@ -475,6 +587,7 @@ def test_flights_json_invalid_date(runner, mock_search_flights, mock_console):
assert payload["success"] is False
assert payload["search_type"] == "flights"
assert payload["error"]["type"] == "validation_error"
+ assert payload["error"]["retryable"] is False
assert "YYYY-MM-DD" in payload["error"]["message"]
diff --git a/tests/core/test_error_type_parity.py b/tests/core/test_error_type_parity.py
new file mode 100644
index 0000000..1900a56
--- /dev/null
+++ b/tests/core/test_error_type_parity.py
@@ -0,0 +1,328 @@
+"""CLI `--format json` and MCP tools must agree on `error_type` for every exception.
+
+T10 fix round 1, maintainer ruling V1: a review found
+``fli.cli.errors.json_error_payload`` already emitted an ``error_type``
+field for the same exceptions with a *different* vocabulary than the
+MCP tools' first cut. Both now build on the single shared
+:func:`fli.core.errors.classify_error` (see that module's docstring for
+the full history and vocabulary table), which makes drift structurally
+impossible — but only as long as neither interface stops using it. This
+suite proves that by going through each interface's real production
+entry point (:func:`fli.cli.errors.json_error_payload` and
+:func:`fli.mcp.server._execute_flight_search`) rather than calling
+``classify_error`` a second time, so it would catch either surface
+silently reverting to its own hardcoded strings.
+
+The ``SearchClientError`` subclass coverage reuses the same
+"every subclass must be listed" guard as
+``tests/core/test_errors.py::TestEverySearchClientErrorSubclassIsClassified``
+— a new subclass shows up in the parametrize list automatically and fails
+here until ``_INSTANCES`` is updated for it, same as it does there.
+
+T10 fix round 2, maintainer ruling U3: ``TestCliCommandAndMcpToolAgreeOnErrorType``
+below extends this to the COMMAND level — a real ``CliRunner`` invocation
+of ``fli flights`` / ``fli dates --format json`` compared against the
+matching MCP tool executor for the same input. This is the layer where
+round 1's parity test could not have caught U1 (the CLI commands'
+``except (AttributeError, ValueError)`` blocks hardcoding
+``error_type="search_error"`` independently of ``json_error_payload``,
+which they never called for that branch).
+
+T10 fix round 3: every date below is computed relative to
+``datetime.now()`` at test-run time — no fixed pinned clock, no hardcoded
+absolute dates. The original version of this file paired a hardcoded
+``PINNED_TODAY = "2026-01-01"`` clock with a hardcoded
+``"2026-02-01"``/``"2026-12-01"`` date-range in
+``test_date_range_over_93_day_cap``; the two were meant to keep the range
+comfortably in the future forever, but that pairing is exactly the kind
+of fixture that can silently stop exercising its intended code path
+(there is no pytest failure that fires when a "far future" date stops
+being far enough in the future relative to whatever governs "today" — it
+just quietly starts hitting a different, unintended branch that happens
+to produce the same top-level assertion). Relative dates have no such
+window to fall out of.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+
+import pytest
+from pydantic import BaseModel, ValidationError
+from typer.testing import CliRunner
+
+from fli.cli.errors import json_error_payload
+from fli.cli.main import app
+from fli.core.parsers import ParseError
+from fli.mcp.server import (
+ DateSearchParams,
+ FlightSearchParams,
+ _execute_date_search,
+ _execute_flight_search,
+)
+from fli.search.exceptions import (
+ SearchClientError,
+ SearchConnectionError,
+ SearchHTTPError,
+ SearchParseError,
+ SearchRejectedError,
+ SearchTimeoutError,
+ SearchUnsupportedError,
+)
+
+# A single "comfortably in the future, whatever day this runs" date for
+# tests that only need *a* valid date (not a specific range) — every test
+# below builds its own dates from datetime.now(), so none of them rot.
+_FUTURE_DATE = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
+
+
+def _all_subclasses(cls: type) -> set[type]:
+ """Recursively collect every currently-defined subclass of ``cls``."""
+ seen: set[type] = set()
+ stack = [cls]
+ while stack:
+ current = stack.pop()
+ for sub in current.__subclasses__():
+ if sub not in seen:
+ seen.add(sub)
+ stack.append(sub)
+ return seen
+
+
+def _pydantic_validation_error() -> ValidationError:
+ class _Model(BaseModel):
+ passengers: int
+
+ try:
+ _Model(passengers="not-a-number")
+ except ValidationError as exc:
+ return exc
+ raise AssertionError("expected pydantic to raise ValidationError") # pragma: no cover
+
+
+# One representative instance per exception class that classify_error()
+# handles — every SearchClientError subclass (+ its base) plus the other
+# classes the shared classifier is documented to cover.
+_INSTANCES: dict[type, BaseException] = {
+ SearchClientError: SearchClientError("boom"),
+ SearchTimeoutError: SearchTimeoutError("timed out"),
+ SearchConnectionError: SearchConnectionError("no route"),
+ SearchHTTPError: SearchHTTPError("bad response", status_code=500),
+ SearchRejectedError: SearchRejectedError(13),
+ SearchUnsupportedError: SearchUnsupportedError("multi-city"),
+ SearchParseError: SearchParseError("no ds:1 payload"),
+ ParseError: ParseError("unknown airport code 'ZZZ'"),
+ ValueError: ValueError("bad date range"),
+ ValidationError: _pydantic_validation_error(),
+ Exception: Exception("totally unclassified"),
+}
+
+
+class TestEverySearchClientErrorSubclassHasAnInstance:
+ """Guards against a new fli.search.exceptions class going untested here."""
+
+ @pytest.mark.parametrize(
+ "exc_class",
+ sorted(_all_subclasses(SearchClientError) | {SearchClientError}, key=lambda c: c.__name__),
+ )
+ def test_class_has_instance(self, exc_class):
+ assert exc_class in _INSTANCES, (
+ f"{exc_class.__name__} is a SearchClientError subclass with no instance in "
+ "tests/core/test_error_type_parity.py::_INSTANCES — add one so CLI/MCP "
+ "error_type parity is verified for it too."
+ )
+
+
[email protected]("exc", list(_INSTANCES.values()), ids=[c.__name__ for c in _INSTANCES])
+def test_cli_and_mcp_agree_on_error_type(exc, monkeypatch):
+ """The CLI's json_error_payload and the MCP's error response must match."""
+ # CLI side: the real json_error_payload entry point.
+ cli_payload = json_error_payload(exc)
+
+ # MCP side: the real _execute_flight_search entry point, with the
+ # search client stubbed to raise the same exception instance.
+ def _raise(self, *args, **kwargs):
+ raise exc
+
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", _raise)
+ params = FlightSearchParams(origin="JFK", destination="LHR", departure_date=_FUTURE_DATE)
+ mcp_result = _execute_flight_search(params)
+
+ assert mcp_result["success"] is False
+ assert mcp_result["error_type"] == cli_payload.error_type
+ assert mcp_result["retryable"] == cli_payload.retryable
+
+
+class TestCliCommandAndMcpToolAgreeOnErrorType:
+ """Command-level parity (U3): a real CliRunner invocation vs. the MCP executor.
+
+ ``fli.mcp.server.SearchFlights`` / ``SearchDates`` and
+ ``fli.cli.commands.flights`` / ``dates``' ``SearchFlights`` / ``SearchDates``
+ are literally the same class objects (both re-exported from
+ ``fli.search``), so patching ``fli.search.flights.SearchFlights.search``
+ (or ``fli.search.dates.SearchDates.search``) affects both surfaces at
+ once — no separate CLI-specific mock needed.
+ """
+
+ @pytest.fixture
+ def runner(self) -> CliRunner:
+ return CliRunner()
+
+ def test_invalid_airport_code(self, runner):
+ """Bad origin code: ParseError -> validation_error on both surfaces."""
+ cli_result = runner.invoke(
+ app, ["flights", "ZZZZ", "LHR", _FUTURE_DATE, "--format", "json"]
+ )
+ cli_payload = json.loads(cli_result.stdout)
+
+ mcp_result = _execute_flight_search(
+ FlightSearchParams(origin="ZZZZ", destination="LHR", departure_date=_FUTURE_DATE)
+ )
+
+ assert cli_payload["success"] is False
+ assert mcp_result["success"] is False
+ assert cli_payload["error"]["type"] == mcp_result["error_type"] == "validation_error"
+ assert cli_payload["error"]["retryable"] == mcp_result["retryable"] is False
+
+ def test_date_range_over_93_day_cap(self, runner):
+ """A >93-date range: bare ValueError -> validation_error on both surfaces.
+
+ This is exactly the U1 regression: the CLI's dates command used to
+ hardcode "search_error" for this bare ValueError while the MCP tool
+ already said "validation_error" — the drift this whole task exists
+ to prevent, and the one round 1's parity test (which only compared
+ json_error_payload against the MCP executor, not the full CLI
+ command) could not catch.
+
+ Dates are relative to today (not a pinned clock) and the range is
+ 150 days wide — comfortably over the 93-date cap regardless of what
+ day this runs. The message assertions are the important part: they
+ prove this hit SearchDates.search()'s cap ValueError specifically
+ (the except (AttributeError, ValueError) block — the actual U1 fix
+ site), not some other validation_error path (e.g. a pydantic "date
+ in the past" check, which is a *different* except block that was
+ never broken and would give the same top-level error_type while
+ testing nothing about U1). A round 3 fix: the original version of
+ this test used hardcoded "2026-02-01"/"2026-12-01" dates that only
+ stayed in that intended future window because of a matching
+ hardcoded pinned clock — a pairing that, if either side ever drifts
+ independently, silently starts hitting the "in the past" branch
+ instead while still asserting True, defeating the point of the test
+ without failing it. Confirmed (manually, not committed) that
+ reverting the classify_error call in dates.py's
+ except (AttributeError, ValueError) block makes this test fail.
+ """
+ today = datetime.now()
+ start_date = (today + timedelta(days=10)).strftime("%Y-%m-%d")
+ end_date = (today + timedelta(days=10 + 150)).strftime("%Y-%m-%d")
+
+ cli_result = runner.invoke(
+ app,
+ [
+ "dates",
+ "JFK",
+ "LAX",
+ "--from",
+ start_date,
+ "--to",
+ end_date,
+ "--format",
+ "json",
+ ],
+ )
+ cli_payload = json.loads(cli_result.stdout)
+
+ mcp_result = _execute_date_search(
+ DateSearchParams(
+ origin="JFK", destination="LAX", start_date=start_date, end_date=end_date
+ )
+ )
+
+ assert cli_payload["success"] is False
+ assert mcp_result["success"] is False
+ assert cli_payload["error"]["type"] == mcp_result["error_type"] == "validation_error"
+ assert cli_payload["error"]["retryable"] == mcp_result["retryable"] is False
+ # Prove this hit the 93-date cap, not a "date in the past" pydantic
+ # validator that would also report validation_error but exercises
+ # a completely different except block.
+ assert "93-date limit" in cli_payload["error"]["message"]
+ assert "93-date limit" in mcp_result["error"]
+ assert "in the past" not in cli_payload["error"]["message"]
+ assert "in the past" not in mcp_result["error"]
+
+ def test_invalid_passenger_mix(self, runner):
+ """1 adult + 2 lap infants (each needs its own adult): pydantic ValidationError."""
+ cli_result = runner.invoke(
+ app,
+ [
+ "flights",
+ "JFK",
+ "LHR",
+ _FUTURE_DATE,
+ "--passengers",
+ "1",
+ "--infants-on-lap",
+ "2",
+ "--format",
+ "json",
+ ],
+ )
+ cli_payload = json.loads(cli_result.stdout)
+
+ mcp_result = _execute_flight_search(
+ FlightSearchParams(
+ origin="JFK",
+ destination="LHR",
+ departure_date=_FUTURE_DATE,
+ passengers=1,
+ infants_on_lap=2,
+ )
+ )
+
+ assert cli_payload["success"] is False
+ assert mcp_result["success"] is False
+ assert cli_payload["error"]["type"] == mcp_result["error_type"] == "validation_error"
+ assert cli_payload["error"]["retryable"] == mcp_result["retryable"] is False
+
+ def test_stubbed_blocked_page(self, runner, monkeypatch):
+ """SearchParseError (consent/blocked page): parse_error, not retryable as-is."""
+ monkeypatch.setattr(
+ "fli.search.flights.SearchFlights.search",
+ lambda self, *a, **k: (_ for _ in ()).throw(
+ SearchParseError("no ds:1 payload — consent/blocked page")
+ ),
+ )
+
+ cli_result = runner.invoke(app, ["flights", "JFK", "LHR", _FUTURE_DATE, "--format", "json"])
+ cli_payload = json.loads(cli_result.stdout)
+
+ mcp_result = _execute_flight_search(
+ FlightSearchParams(origin="JFK", destination="LHR", departure_date=_FUTURE_DATE)
+ )
+
+ assert cli_payload["success"] is False
+ assert mcp_result["success"] is False
+ assert cli_payload["error"]["type"] == mcp_result["error_type"] == "parse_error"
+ assert cli_payload["error"]["retryable"] == mcp_result["retryable"] is False
+
+ def test_stubbed_connection_error(self, runner, monkeypatch):
+ """SearchConnectionError: connection_error, retryable — a released CLI value."""
+ monkeypatch.setattr(
+ "fli.search.flights.SearchFlights.search",
+ lambda self, *a, **k: (_ for _ in ()).throw(
+ SearchConnectionError("Could not reach Google Flights")
+ ),
+ )
+
+ cli_result = runner.invoke(app, ["flights", "JFK", "LHR", _FUTURE_DATE, "--format", "json"])
+ cli_payload = json.loads(cli_result.stdout)
+
+ mcp_result = _execute_flight_search(
+ FlightSearchParams(origin="JFK", destination="LHR", departure_date=_FUTURE_DATE)
+ )
+
+ assert cli_payload["success"] is False
+ assert mcp_result["success"] is False
+ assert cli_payload["error"]["type"] == mcp_result["error_type"] == "connection_error"
+ assert cli_payload["error"]["retryable"] == mcp_result["retryable"] is True
diff --git a/tests/core/test_errors.py b/tests/core/test_errors.py
new file mode 100644
index 0000000..9931ad3
--- /dev/null
+++ b/tests/core/test_errors.py
@@ -0,0 +1,164 @@
+"""Table-driven tests for fli.core.errors.classify_error.
+
+Requirement: this suite must fail if a new exception class is added to
+fli.search.exceptions without giving it a classification here. That is
+enforced by iterating SearchClientError.__subclasses__() at collection
+time (see TestEverySearchClientErrorSubclassIsClassified) instead of
+hand-listing the classes — a new subclass shows up in the parametrize
+list automatically and fails until _EXPECTED is updated for it.
+
+classify_error moved here (from fli/mcp/errors.py) in T10 fix round 1: a
+review found fli.cli.errors.json_error_payload already emitted an
+error_type field with a different vocabulary for the same exceptions, so
+the classifier now lives in fli.core and is shared by both fli.mcp.server
+and fli.cli.errors — see fli/core/errors.py's module docstring for the
+full history and vocabulary table. tests/core/test_error_type_parity.py
+covers the "CLI and MCP agree" half of that; this file covers the
+classifier itself.
+"""
+
+from __future__ import annotations
+
+import pytest
+from pydantic import BaseModel, ValidationError
+
+from fli.core.errors import ErrorClassification, classify_error
+from fli.core.parsers import ParseError
+from fli.search.exceptions import (
+ SearchClientError,
+ SearchConnectionError,
+ SearchHTTPError,
+ SearchParseError,
+ SearchRejectedError,
+ SearchTimeoutError,
+ SearchUnsupportedError,
+)
+
+
+def _all_subclasses(cls: type) -> set[type]:
+ """Recursively collect every currently-defined subclass of ``cls``."""
+ seen: set[type] = set()
+ stack = [cls]
+ while stack:
+ current = stack.pop()
+ for sub in current.__subclasses__():
+ if sub not in seen:
+ seen.add(sub)
+ stack.append(sub)
+ return seen
+
+
+# One representative-instance factory + expected (error_type, retryable) per
+# exception class defined in fli.search.exceptions. SearchHTTPError is
+# exercised separately below across several status codes since its
+# `retryable` depends on the status code, not just the type.
+_EXPECTED: dict[type, tuple[type[BaseException], tuple[str, bool]]] = {
+ SearchClientError: (SearchClientError("boom"), ("search_error", False)),
+ SearchTimeoutError: (SearchTimeoutError("timed out"), ("timeout", True)),
+ SearchConnectionError: (SearchConnectionError("no route"), ("connection_error", True)),
+ SearchHTTPError: (SearchHTTPError("bad response", status_code=500), ("http_error", True)),
+ SearchRejectedError: (SearchRejectedError(13), ("rejected_error", False)),
+ SearchUnsupportedError: (SearchUnsupportedError("multi-city"), ("unsupported_error", False)),
+ SearchParseError: (SearchParseError("no ds:1 payload"), ("parse_error", False)),
+}
+
+
+class TestEverySearchClientErrorSubclassIsClassified:
+ """Guards against a new fli.search.exceptions class going unclassified."""
+
+ @pytest.mark.parametrize(
+ "exc_class",
+ sorted(_all_subclasses(SearchClientError) | {SearchClientError}, key=lambda c: c.__name__),
+ )
+ def test_class_has_expected_mapping(self, exc_class):
+ assert exc_class in _EXPECTED, (
+ f"{exc_class.__name__} is a SearchClientError subclass with no entry in "
+ "tests/core/test_errors.py::_EXPECTED — classify_error() in "
+ "fli/core/errors.py needs an isinstance branch for it, and this table needs "
+ "the expected (error_type, retryable) pair."
+ )
+
+ @pytest.mark.parametrize(
+ "exc_class",
+ sorted(_all_subclasses(SearchClientError) | {SearchClientError}, key=lambda c: c.__name__),
+ )
+ def test_class_classifies_as_expected(self, exc_class):
+ instance, (expected_type, expected_retryable) = _EXPECTED[exc_class]
+ result = classify_error(instance)
+ assert result.error_type == expected_type
+ assert result.retryable == expected_retryable
+
+
+class TestSearchHTTPErrorRetryability:
+ """retryable depends on the status code: 429 and 5xx are, everything else isn't."""
+
+ @pytest.mark.parametrize(
+ "status_code,expected_retryable",
+ [
+ (429, True),
+ (500, True),
+ (502, True),
+ (503, True),
+ (599, True),
+ (400, False),
+ (403, False),
+ (404, False),
+ (None, False),
+ ],
+ )
+ def test_retryable_by_status(self, status_code, expected_retryable):
+ exc = SearchHTTPError("Google Flights returned an error response", status_code=status_code)
+ result = classify_error(exc)
+ assert result.error_type == "http_error"
+ assert result.retryable is expected_retryable
+
+ def test_http_status_field_present_when_known(self):
+ result = classify_error(SearchHTTPError("boom", status_code=503))
+ assert result.http_status == 503
+ assert result.as_fields()["http_status"] == 503
+
+ def test_http_status_field_absent_when_unknown(self):
+ result = classify_error(SearchHTTPError("boom", status_code=None))
+ assert result.http_status is None
+ assert "http_status" not in result.as_fields()
+
+
+class TestNonSearchExceptions:
+ """Pydantic ValidationError, ParseError, bare ValueError, and bare Exception."""
+
+ def test_pydantic_validation_error(self):
+ class _Model(BaseModel):
+ passengers: int
+
+ try:
+ _Model(passengers="not-a-number")
+ except ValidationError as exc:
+ result = classify_error(exc)
+ assert result == ErrorClassification("validation_error", retryable=False)
+
+ def test_core_parse_error(self):
+ result = classify_error(ParseError("unknown airport code 'ZZZ'"))
+ assert result == ErrorClassification("validation_error", retryable=False)
+
+ def test_bare_value_error_93_date_cap(self):
+ # Mirrors the message SearchDates.search() raises when a date range
+ # covers more than MAX_DATES_PER_SEARCH (93) dates — a plain
+ # ValueError, not a ParseError or SearchClientError subclass.
+ result = classify_error(
+ ValueError("This date search covers 120 dates, above the 93-date limit.")
+ )
+ assert result == ErrorClassification("validation_error", retryable=False)
+
+ def test_bare_exception_is_unexpected(self):
+ result = classify_error(Exception("something nobody classified"))
+ assert result == ErrorClassification("unexpected_error", retryable=False)
+
+ def test_unrelated_builtin_exception_is_unexpected(self):
+ result = classify_error(KeyError("missing"))
+ assert result == ErrorClassification("unexpected_error", retryable=False)
+
+
+class TestErrorClassificationAsFields:
+ def test_no_http_status_key_when_not_http_error(self):
+ fields = classify_error(SearchTimeoutError("slow")).as_fields()
+ assert fields == {"error_type": "timeout", "retryable": True}
diff --git a/tests/mcp/test_error_type_responses.py b/tests/mcp/test_error_type_responses.py
new file mode 100644
index 0000000..5f2aeaa
--- /dev/null
+++ b/tests/mcp/test_error_type_responses.py
@@ -0,0 +1,267 @@
+"""Every MCP error response carries error_type + retryable (issue #234 follow-up).
+
+Additive contract: `success`, `error`, and the tool's existing empty-result
+key (`flights` / `dates` / `options`) must be byte-identical to what they
+were before this change — these tests assert the new keys are *added*, not
+that the old ones changed.
+
+T10 fix round 3: dates are computed relative to `datetime.now()` at
+test-run time rather than pinned to a fixed clock, per the same fix
+applied to `tests/core/test_error_type_parity.py` — see that file's
+docstring for why a fixed pinned clock paired with fixed future dates is
+fragile (it can silently stop exercising the intended code path without
+any test failure to flag it).
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+
+import pytest
+
+from fli.mcp.server import (
+ DateSearchParams,
+ FlightSearchParams,
+ _execute_booking_options,
+ _execute_date_search,
+ _execute_flight_search,
+ _find_airports_impl,
+)
+from fli.search.exceptions import (
+ SearchClientError,
+ SearchConnectionError,
+ SearchHTTPError,
+ SearchParseError,
+ SearchRejectedError,
+ SearchTimeoutError,
+ SearchUnsupportedError,
+)
+
+# A single "comfortably in the future, whatever day this runs" date for
+# tests that only need *a* valid date (not a specific range).
+_FUTURE_DATE = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
+_SHORT_RANGE_START = (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d")
+_SHORT_RANGE_END = (datetime.now() + timedelta(days=69)).strftime("%Y-%m-%d")
+
+
+def _raiser(exc: BaseException):
+ def _fn(*args, **kwargs):
+ raise exc
+
+ return _fn
+
+
+# (exception instance, expected error_type, expected retryable)
+_SEARCH_CLIENT_ERROR_CASES = [
+ pytest.param(SearchTimeoutError("slow"), "timeout", True, id="timeout"),
+ pytest.param(SearchConnectionError("no route"), "connection_error", True, id="connection"),
+ pytest.param(
+ SearchHTTPError("bad gateway", status_code=502), "http_error", True, id="http-5xx"
+ ),
+ pytest.param(SearchHTTPError("forbidden", status_code=403), "http_error", False, id="http-4xx"),
+ pytest.param(SearchRejectedError(13), "rejected_error", False, id="rejected"),
+ pytest.param(
+ SearchUnsupportedError("multi-city unsupported"),
+ "unsupported_error",
+ False,
+ id="unsupported",
+ ),
+ pytest.param(SearchParseError("no ds:1 payload"), "parse_error", False, id="blocked"),
+ pytest.param(SearchClientError("generic failure"), "search_error", False, id="generic"),
+ pytest.param(RuntimeError("bug"), "unexpected_error", False, id="unexpected"),
+]
+
+
+class TestSearchFlightsErrorType:
+ @pytest.fixture
+ def params(self):
+ return FlightSearchParams(origin="JFK", destination="LHR", departure_date=_FUTURE_DATE)
+
+ @pytest.mark.parametrize("exc,expected_type,expected_retryable", _SEARCH_CLIENT_ERROR_CASES)
+ def test_search_error_types(self, monkeypatch, params, exc, expected_type, expected_retryable):
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", _raiser(exc))
+ result = _execute_flight_search(params)
+ assert result["success"] is False
+ assert result["error_type"] == expected_type
+ assert result["retryable"] is expected_retryable
+ assert result["flights"] == [] # existing field untouched
+
+ def test_http_error_carries_http_status(self, monkeypatch, params):
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ _raiser(SearchHTTPError("rate limited", status_code=429)),
+ )
+ result = _execute_flight_search(params)
+ assert result["error_type"] == "http_error"
+ assert result["retryable"] is True
+ assert result["http_status"] == 429
+
+ def test_http_error_omits_http_status_when_unknown(self, monkeypatch, params):
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ _raiser(SearchHTTPError("mystery failure", status_code=None)),
+ )
+ result = _execute_flight_search(params)
+ assert result["error_type"] == "http_error"
+ assert "http_status" not in result
+
+ def test_bad_airport_code_is_validation_error(self):
+ """An unresolvable origin raises fli.core.parsers.ParseError -> validation_error."""
+ params = FlightSearchParams(origin="ZZZZ", destination="LHR", departure_date=_FUTURE_DATE)
+ result = _execute_flight_search(params)
+ assert result["success"] is False
+ assert result["error_type"] == "validation_error"
+ assert result["retryable"] is False
+
+ def test_too_many_travelers_is_validation_error(self):
+ """9 adults + 5 children exceeds the 1-9 total-traveler cap -> pydantic ValidationError."""
+ params = FlightSearchParams(
+ origin="JFK",
+ destination="LHR",
+ departure_date=_FUTURE_DATE,
+ passengers=9,
+ children=5,
+ )
+ result = _execute_flight_search(params)
+ assert result["success"] is False
+ assert result["error_type"] == "validation_error"
+ assert result["retryable"] is False
+
+ def test_successful_response_has_no_error_type(self, monkeypatch, params):
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", lambda self, *a, **k: None)
+ result = _execute_flight_search(params)
+ assert result["success"] is True
+ assert "error_type" not in result
+ assert "retryable" not in result
+
+
+class TestSearchDatesErrorType:
+ @pytest.fixture
+ def params(self):
+ return DateSearchParams(
+ origin="JFK",
+ destination="LHR",
+ start_date=_SHORT_RANGE_START,
+ end_date=_SHORT_RANGE_END,
+ )
+
+ @pytest.mark.parametrize("exc,expected_type,expected_retryable", _SEARCH_CLIENT_ERROR_CASES)
+ def test_date_search_error_types(
+ self, monkeypatch, params, exc, expected_type, expected_retryable
+ ):
+ monkeypatch.setattr("fli.mcp.server.SearchDates.search", _raiser(exc))
+ result = _execute_date_search(params)
+ assert result["success"] is False
+ assert result["error_type"] == expected_type
+ assert result["retryable"] is expected_retryable
+ assert result["dates"] == []
+
+ def test_over_93_date_cap_is_validation_error(self):
+ """SearchDates.search() raises a bare ValueError for >93-date ranges — no mocking needed.
+
+ Dates are relative to today (150-day range, well over the 93-date
+ cap) so this keeps exercising SearchDates.search()'s cap check
+ rather than drifting onto a "date in the past" pydantic validator
+ that would also report validation_error but prove nothing about
+ the cap path — see tests/core/test_error_type_parity.py's
+ docstring for the fragile-fixed-date failure mode this avoids.
+ """
+ today = datetime.now()
+ start_date = (today + timedelta(days=10)).strftime("%Y-%m-%d")
+ end_date = (today + timedelta(days=10 + 150)).strftime("%Y-%m-%d")
+ params = DateSearchParams(
+ origin="JFK", destination="LHR", start_date=start_date, end_date=end_date
+ )
+ result = _execute_date_search(params)
+ assert result["success"] is False
+ assert "93-date limit" in result["error"] # existing message untouched
+ assert "in the past" not in result["error"]
+ assert result["error_type"] == "validation_error"
+ assert result["retryable"] is False
+
+ def test_bad_airport_code_is_validation_error(self):
+ params = DateSearchParams(
+ origin="ZZZZ",
+ destination="LHR",
+ start_date=_SHORT_RANGE_START,
+ end_date=_SHORT_RANGE_END,
+ )
+ result = _execute_date_search(params)
+ assert result["error_type"] == "validation_error"
+ assert result["retryable"] is False
+
+ def test_successful_response_has_no_error_type(self, monkeypatch, params):
+ monkeypatch.setattr("fli.mcp.server.SearchDates.search", lambda self, *a, **k: None)
+ result = _execute_date_search(params)
+ assert result["success"] is True
+ assert "error_type" not in result
+
+
+class TestBookingOptionsErrorType:
+ @pytest.fixture
+ def params(self):
+ return FlightSearchParams(origin="JFK", destination="LHR", departure_date=_FUTURE_DATE)
+
+ def _flight(self):
+ from unittest.mock import MagicMock
+
+ leg = MagicMock()
+ airline = MagicMock()
+ airline.name = "BA"
+ leg.airline = airline
+ leg.flight_number = "178"
+ flight = MagicMock()
+ flight.legs = [leg]
+ flight.price = 400.0
+ flight.currency = "USD"
+ flight.booking_token = "tok"
+ return flight
+
+ def test_no_match_is_validation_error(self, monkeypatch, params):
+ """No exception at all — a deterministic "you passed bad flight_numbers" case."""
+ flight = self._flight()
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", lambda me, *a, **k: [flight])
+ result = _execute_booking_options(params, ["ZZ999"])
+ assert result["success"] is False
+ assert result["available_flights"] == [["BA178"]] # existing field untouched
+ assert result["error_type"] == "validation_error"
+ assert result["retryable"] is False
+
+ @pytest.mark.parametrize("exc,expected_type,expected_retryable", _SEARCH_CLIENT_ERROR_CASES)
+ def test_get_booking_options_error_types(
+ self, monkeypatch, params, exc, expected_type, expected_retryable
+ ):
+ flight = self._flight()
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", lambda me, *a, **k: [flight])
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.get_booking_options", _raiser(exc))
+ result = _execute_booking_options(params, None)
+ assert result["success"] is False
+ assert result["error_type"] == expected_type
+ assert result["retryable"] is expected_retryable
+ assert result["options"] == []
+
+ def test_successful_response_has_no_error_type(self, monkeypatch, params):
+ flight = self._flight()
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", lambda me, *a, **k: [flight])
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.get_booking_options", lambda me, *a, **k: []
+ )
+ result = _execute_booking_options(params, None)
+ assert result["success"] is True
+ assert "error_type" not in result
+
+
+class TestFindAirportsErrorType:
+ def test_unexpected_failure_is_unexpected_error(self, monkeypatch):
+ monkeypatch.setattr(
+ "fli.mcp.server.search_airports", _raiser(RuntimeError("index corrupted"))
+ )
+ result = _find_airports_impl("new york")
+ assert result["success"] is False
+ assert result["error_type"] == "unexpected_error"
+ assert result["retryable"] is False
+
+ def test_successful_response_has_no_error_type(self):
+ result = _find_airports_impl("new york")
+ assert result["success"] is True
+ assert "error_type" not in result
diff --git a/tests/search/fixtures/flight_search_error13_rejected.txt b/tests/search/fixtures/flight_search_error13_rejected.txt
new file mode 100644
index 0000000..6f7e3d4
--- /dev/null
+++ b/tests/search/fixtures/flight_search_error13_rejected.txt
@@ -0,0 +1,3 @@
+)]}'
+
+[["wrb.fr",null,null,null,null,[13,null,[["type.googleapis.com/travel.frontend.flights.ErrorResponse",[[null,[[1782183274701731,54776872,2101123823],null,null,null,null,[[0]]],0,"avU5aqPqKqioj8oP77Xy6Qc","HNWGCqEBKFkQAY0-mABG----------okrt5AAAAAGo59WoKnS6iA"],0]]]]],["di",49],["af.httprm",49,"2038896757614171247",16]]
diff --git a/tests/search/test_error_envelope_fixture.py b/tests/search/test_error_envelope_fixture.py
new file mode 100644
index 0000000..8b9f76d
--- /dev/null
+++ b/tests/search/test_error_envelope_fixture.py
@@ -0,0 +1,173 @@
+"""A real captured Google Flights error-13 envelope, end to end.
+
+``tests/search/fixtures/flight_search_error13_rejected.txt`` is ported
+verbatim (byte-identical, credit to @bjgross10767 / PR #208 for the
+capture) from a genuine ``GetBookingResults`` response. It is a
+``wrb.fr`` row with a ``null`` payload and a ``type.googleapis.com/
+travel.frontend.flights.ErrorResponse`` blob carrying numeric error code
+``13`` (INTERNAL) in slot 5 — exactly the shape ``SearchRejectedError``
+exists to catch (see ``fli/search/exceptions.py`` and
+``fli/search/_wire.py::_chunks_from_outer``).
+
+PR #208 read this capture as a *rate limit* and proposed a 30s-retry
+hint. That diagnosis doesn't hold: the gate is Google's now-mandatory
+``x-goog-batchexecute-bgr`` header (see issue #223) which a plain HTTP
+client can never produce, so the failure is deterministic, not transient
+— retrying the exact same request will not succeed. This file locks in
+the correct classification instead: parse -> ``SearchRejectedError`` ->
+MCP ``error_type == "rejected_error"``, ``retryable == False``.
+
+Fixture contents, checked for anything sensitive: the XSSI prefix
+``)]}'``, the ``wrb.fr``/error-code framing described above, three plain
+integers that read as Google-internal trace/counters, one short opaque
+token (``avU5aqPqKqioj8oP77Xy6Qc``) and one longer opaque token
+(``HNWGCqEBKFkQAY0-...``) that are ephemeral per-RPC correlation ids
+minted by Google's batchexecute framework for this single anonymous,
+unauthenticated request, and trailing ``di``/``af.httprm`` protocol
+framing. There is no email, cookie, auth token, IP address, or other
+personal data — fli never authenticates to Google Flights, so there is
+no account for these ids to identify.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, time, timedelta
+from pathlib import Path
+
+import pytest
+
+from fli.core.errors import classify_error
+from fli.mcp.server import FlightSearchParams, _execute_booking_options
+from fli.models import (
+ Airline,
+ Airport,
+ FlightLeg,
+ FlightResult,
+ FlightSearchFilters,
+ FlightSegment,
+ PassengerInfo,
+)
+from fli.search import SearchFlights
+from fli.search._wire import iter_wrb_chunks
+from fli.search.exceptions import SearchRejectedError
+
+FIXTURE_PATH = Path(__file__).parent / "fixtures" / "flight_search_error13_rejected.txt"
+
+# Segment/leg travel dates are validated against today; keep them relative
+# so this test doesn't rot as the capture ages (same convention as
+# tests/search/test_booking_options.py).
+OUT_DATE = (datetime.now() + timedelta(days=30)).date()
+
+
+def fixture_body() -> str:
+ return FIXTURE_PATH.read_text(encoding="utf-8")
+
+
+def _one_way_filters() -> FlightSearchFilters:
+ return FlightSearchFilters(
+ passenger_info=PassengerInfo(adults=1),
+ flight_segments=[
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.LHR, 0]],
+ travel_date=OUT_DATE.isoformat(),
+ )
+ ],
+ )
+
+
+def _one_way_flight() -> FlightResult:
+ leg = FlightLeg(
+ airline=Airline.BA,
+ flight_number="178",
+ departure_airport=Airport.JFK,
+ arrival_airport=Airport.LHR,
+ departure_datetime=datetime.combine(OUT_DATE, time(18, 0)),
+ arrival_datetime=datetime.combine(OUT_DATE, time(6, 30)),
+ duration=450,
+ )
+ return FlightResult(
+ legs=[leg],
+ price=450.0,
+ currency="USD",
+ duration=450,
+ stops=0,
+ # Per-row token captured at parse time — lets get_booking_options
+ # resolve a token without a prior search() call / session id.
+ booking_token="CAPTURED_ROW_TOKEN",
+ )
+
+
+class _StaticResponse:
+ """Stand-in for curl-cffi's response object; always returns the same body."""
+
+ __slots__ = ("text",)
+
+ def __init__(self, text: str):
+ self.text = text
+
+ def raise_for_status(self) -> None:
+ return None
+
+
+class _StaticClient:
+ """Returns the captured envelope for any POST, regardless of payload."""
+
+ def __init__(self, body: str):
+ self._body = body
+
+ def post(self, url: str, **kwargs) -> _StaticResponse:
+ return _StaticResponse(self._body)
+
+
+class TestWireLevelParsing:
+ """The lowest layer: iter_wrb_chunks must raise, not swallow, this envelope."""
+
+ def test_iter_wrb_chunks_raises_search_rejected_error(self, fixture_body):
+ with pytest.raises(SearchRejectedError) as exc_info:
+ list(iter_wrb_chunks(fixture_body))
+ assert exc_info.value.code == 13
+
+ def test_classify_error_calls_it_rejected_and_not_retryable(self, fixture_body):
+ with pytest.raises(SearchRejectedError) as exc_info:
+ list(iter_wrb_chunks(fixture_body))
+ result = classify_error(exc_info.value)
+ assert result.error_type == "rejected_error"
+ assert result.retryable is False
+
+
+class TestSearchFlightsGetBookingOptions:
+ """One layer up: the real get_booking_options() call, network mocked only at POST."""
+
+ def test_get_booking_options_raises_search_rejected_error(self, fixture_body):
+ search = SearchFlights()
+ search.client = _StaticClient(fixture_body)
+ filters = _one_way_filters()
+ flight = _one_way_flight()
+
+ with pytest.raises(SearchRejectedError) as exc_info:
+ search.get_booking_options(flight, filters, currency="USD")
+ assert exc_info.value.code == 13
+
+
+class TestMcpGetBookingOptionsReportsRejectedError:
+ """End to end: the MCP tool's response carries the new classification fields."""
+
+ def test_error_type_and_retryable(self, monkeypatch, fixture_body):
+ flight = _one_way_flight()
+ # Short-circuit the initial shopping search (no network needed for it) —
+ # only the booking-options POST should hit the captured envelope.
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.search", lambda self, *a, **k: [flight])
+ monkeypatch.setattr("fli.search.flights.get_client", lambda: _StaticClient(fixture_body))
+
+ params = FlightSearchParams(
+ origin="JFK", destination="LHR", departure_date=OUT_DATE.isoformat()
+ )
+ result = _execute_booking_options(params, None)
+
+ assert result["success"] is False
+ assert result["options"] == [] # existing field untouched
+ assert "13" in result["error"] # existing message untouched
+ assert result["error_type"] == "rejected_error"
+ assert result["retryable"] is False