Google Flights MCP, CLI and Python Library
Add typed error handling and clean CLI error reporting (#159)
Punit Arani56ecc6bc5dd9
diff --git a/fli/cli/commands/dates.py b/fli/cli/commands/dates.pyindex 5f7cc5c..36e2548 100644--- a/fli/cli/commands/dates.py+++ b/fli/cli/commands/dates.py@@ -6,6 +6,7 @@ from typing import Annotatedimport typerfrom fli.cli.enums import DayOfWeek, OutputFormat+from fli.cli.errors import json_error_payload, report_cli_errorfrom fli.cli.utils import (build_json_error_response,build_json_success_response,@@ -32,7 +33,7 @@ from fli.models import (TimeRestrictions,TripType,)-from fli.search import SearchDates+from fli.search import SearchClientError, SearchDatesdef _build_selected_days(@@ -441,6 +442,18 @@ def dates(raise typer.Exit(1) from etyper.echo(f"Error: {str(e)}")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 = build_json_error_response(+ search_type="dates",+ message=message,+ error_type=error_type,+ )+ payload["error"]["log_path"] = str(log_path)+ emit_json(payload)+ raise typer.Exit(1) from e+ raise report_cli_error(e, command="dates") from eexcept (AttributeError, ValueError) as e:if "module 'fli.search' has no attribute 'SearchDates'" in str(e):raise@@ -484,3 +497,15 @@ def dates(raise typer.Exit(1) from etyper.echo(f"Error: {str(e)}")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 = build_json_error_response(+ search_type="dates",+ message=message,+ error_type=error_type,+ )+ payload["error"]["log_path"] = str(log_path)+ emit_json(payload)+ raise typer.Exit(1) from e+ raise report_cli_error(e, command="dates") from ediff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.pyindex 084a1a4..57d46c5 100644--- a/fli/cli/commands/flights.py+++ b/fli/cli/commands/flights.py@@ -5,6 +5,7 @@ from typing import Annotated, Anyimport typerfrom fli.cli.enums import OutputFormat+from fli.cli.errors import json_error_payload, report_cli_errorfrom fli.cli.utils import (build_json_error_response,build_json_success_response,@@ -32,7 +33,7 @@ from fli.models import (LayoverRestrictions,PassengerInfo,)-from fli.search import SearchFlights+from fli.search import SearchClientError, SearchFlightsdef _search_flights_core(@@ -231,6 +232,32 @@ def _search_flights_core(typer.echo(f"Error: {str(e)}")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 = build_json_error_response(+ search_type="flights",+ message=message,+ error_type=error_type,+ query=query,+ )+ payload["error"]["log_path"] = str(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 = build_json_error_response(+ search_type="flights",+ message=message,+ error_type=error_type,+ query=query,+ )+ payload["error"]["log_path"] = str(log_path)+ emit_json(payload)+ raise typer.Exit(1) from e+ raise report_cli_error(e, command="flights") from edef flights(diff --git a/fli/cli/commands/multi.py b/fli/cli/commands/multi.pyindex 88c7e2a..c76025f 100644--- a/fli/cli/commands/multi.py+++ b/fli/cli/commands/multi.py@@ -5,6 +5,7 @@ from typing import Annotatedimport typer+from fli.cli.errors import report_cli_errorfrom fli.cli.utils import display_flight_results, validate_time_rangefrom fli.core import (build_multi_city_segments,@@ -21,7 +22,7 @@ from fli.models import (PassengerInfo,TimeRestrictions,)-from fli.search import SearchFlights+from fli.search import SearchClientError, SearchFlightsLEG_PATTERN = re.compile(r"^([A-Za-z]{3}),([A-Za-z]{3}),(\d{4}-\d{1,2}-\d{1,2})$")@@ -165,3 +166,7 @@ def multi(except (AttributeError, ValueError) as e:typer.echo(f"Error: {str(e)}")raise typer.Exit(1) from e+ except SearchClientError as e:+ raise report_cli_error(e, command="multi") from e+ except Exception as e: # noqa: BLE001 — fall back to clean reporting+ raise report_cli_error(e, command="multi") from ediff --git a/fli/cli/errors.py b/fli/cli/errors.pynew file mode 100644index 0000000..e6f7f53--- /dev/null+++ b/fli/cli/errors.py@@ -0,0 +1,101 @@+"""CLI error reporting helpers.++Turns ugly tracebacks into a one-line message for the user plus a+self-contained log file under ~/.fli/logs/ that captures the full+traceback for debugging.+"""++from __future__ import annotations++import logging+import sys+import traceback+from datetime import datetime, timezone+from pathlib import Path++import typer++from fli.cli.console import console+from fli.search.exceptions import (+ SearchClientError,+ SearchConnectionError,+ SearchHTTPError,+ SearchTimeoutError,+)++_LOG_DIR = Path.home() / ".fli" / "logs"+_logger = logging.getLogger("fli")+++def _friendly_message(exc: BaseException) -> str:+ """Return the short, user-facing message for ``exc``."""+ if isinstance(exc, SearchTimeoutError):+ return f"Request timed out. {exc}"+ if isinstance(exc, SearchConnectionError):+ return f"Network error. {exc}"+ if isinstance(exc, SearchHTTPError):+ return f"Google Flights error. {exc}"+ if isinstance(exc, SearchClientError):+ return f"Search failed. {exc}"+ return f"Unexpected error: {exc.__class__.__name__}: {exc}"+++def _write_log(exc: BaseException, *, command: str | None = None) -> Path:+ """Write the full traceback for ``exc`` to a log file and return the path."""+ _LOG_DIR.mkdir(parents=True, exist_ok=True)+ # Microsecond precision so rapid-fire errors (e.g. tests, parallel+ # legs) don't collide on the same filename and silently overwrite.+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")+ log_path = _LOG_DIR / f"fli-error-{timestamp}.log"++ lines: list[str] = []+ lines.append(f"timestamp: {datetime.now(timezone.utc).isoformat()}")+ if command:+ lines.append(f"command: {command}")+ lines.append(f"argv: {sys.argv}")+ lines.append(f"error_type: {exc.__class__.__module__}.{exc.__class__.__name__}")+ lines.append(f"error_message: {exc}")+ lines.append("")+ lines.append("traceback:")+ lines.append("".join(traceback.format_exception(type(exc), exc, exc.__traceback__)))++ log_path.write_text("\n".join(lines), encoding="utf-8")+ return log_path+++def report_cli_error(+ exc: BaseException,+ *,+ command: str | None = None,+ exit_code: int = 1,+) -> typer.Exit:+ """Print a clean message for ``exc``, write a log file, and return a ``typer.Exit``.++ Callers should ``raise`` the returned :class:`typer.Exit` so typer+ handles the exit code (and the original exception is suppressed from+ the user's terminal).+ """+ log_path = _write_log(exc, command=command)+ message = _friendly_message(exc)++ console.print(f"[red]Error:[/red] {message}")+ console.print(f"[dim]Full traceback written to {log_path}[/dim]")++ # Still log at debug for anyone who wired up python logging.+ _logger.debug("CLI error", exc_info=exc)++ 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."""+ 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, SearchClientError):+ return str(exc), "search_error", log_path+ return f"{exc.__class__.__name__}: {exc}", "unexpected_error", log_pathdiff --git a/fli/search/__init__.py b/fli/search/__init__.pyindex 98a34cd..91dc068 100644--- a/fli/search/__init__.py+++ b/fli/search/__init__.py@@ -1,8 +1,18 @@from .dates import DatePrice, SearchDates+from .exceptions import (+ SearchClientError,+ SearchConnectionError,+ SearchHTTPError,+ SearchTimeoutError,+)from .flights import SearchFlights__all__ = ["SearchFlights","SearchDates","DatePrice",+ "SearchClientError",+ "SearchTimeoutError",+ "SearchConnectionError",+ "SearchHTTPError",]diff --git a/fli/search/client.py b/fli/search/client.pyindex 7273cc5..6126574 100644--- a/fli/search/client.py+++ b/fli/search/client.py@@ -26,6 +26,12 @@ from typing import TYPE_CHECKING, Anyfrom tenacity import retry, stop_after_attempt, wait_exponentialfrom fli.search._concurrency import TokenBucketRateLimiter+from fli.search.exceptions import (+ SearchClientError,+ SearchConnectionError,+ SearchHTTPError,+ SearchTimeoutError,+)# ``curl_cffi`` adds ~100ms to import time on first load — we only need# it once an HTTP request actually fires, so import lazily on first use.@@ -110,7 +116,7 @@ class Client:response.raise_for_status()return responseexcept Exception as e:- raise Exception(f"GET request failed: {str(e)}") from e+ raise _wrap_request_error("GET", url, e) from e@retry(stop=stop_after_attempt(3), wait=wait_exponential(), reraise=True)def post(self, url: str, **kwargs: Any) -> Response:@@ -121,7 +127,61 @@ class Client:response.raise_for_status()return responseexcept Exception as e:- raise Exception(f"POST request failed: {str(e)}") from e+ raise _wrap_request_error("POST", url, e) from e+++def _wrap_request_error(method: str, url: str, exc: BaseException) -> SearchClientError:+ """Map curl-cffi / network errors into our typed ``SearchClientError`` family.++ The CLI surfaces these as short user-facing messages and writes the+ underlying traceback to a log file, so the message here should read+ well on its own.+ """+ # If a typed error somehow escapes the request body (e.g. a future+ # change in ``_session()``), keep its original type instead of+ # downgrading it to the generic fallback below.+ if isinstance(exc, SearchClientError):+ return exc++ # Imported lazily — ``curl_cffi.requests.exceptions`` triggers the+ # full curl-cffi load, which we otherwise defer until first request.+ from curl_cffi.requests import exceptions as curl_exc++ host = _host_from_url(url)+ if isinstance(exc, curl_exc.Timeout):+ return SearchTimeoutError(+ f"Timed out talking to Google Flights ({host}). "+ "The service may be slow or unreachable from your network — "+ "check your connection and try again."+ )+ if isinstance(exc, curl_exc.ConnectionError):+ return SearchConnectionError(+ f"Could not reach Google Flights ({host}). "+ "Check your internet connection or DNS and try again."+ )+ if isinstance(exc, curl_exc.HTTPError):+ status = getattr(getattr(exc, "response", None), "status_code", None)+ suffix = f" (HTTP {status})" if status else ""+ return SearchHTTPError(+ f"Google Flights returned an error response{suffix}. "+ "The request may be malformed, rate-limited, or blocked.",+ status_code=status,+ )+ # Anything else (including bare CurlError) — keep a clean message but+ # preserve the original via ``__cause__`` so logs still show details.+ return SearchClientError(+ f"{method} request to Google Flights ({host}) failed: {exc.__class__.__name__}"+ )+++def _host_from_url(url: str) -> str:+ """Best-effort host extraction for error messages."""+ try:+ from urllib.parse import urlparse++ return urlparse(url).hostname or url+ except Exception: # noqa: BLE001 — never let logging fail the request path+ return urldef get_client() -> Client:diff --git a/fli/search/exceptions.py b/fli/search/exceptions.pynew file mode 100644index 0000000..ced740a--- /dev/null+++ b/fli/search/exceptions.py@@ -0,0 +1,30 @@+"""Typed errors raised by the search client.++These exist so the CLI (and library consumers) can react to network+failures with a clear, user-facing message instead of a raw curl-cffi+traceback. They are intentionally light wrappers — the original+exception is kept as ``__cause__`` for logging.+"""++from __future__ import annotations+++class SearchClientError(Exception):+ """Base class for errors talking to the Google Flights backend."""+++class SearchTimeoutError(SearchClientError):+ """The request to Google Flights timed out before any data arrived."""+++class SearchConnectionError(SearchClientError):+ """A network/DNS issue prevented us from reaching Google Flights."""+++class SearchHTTPError(SearchClientError):+ """Google Flights returned a non-2xx HTTP response."""++ def __init__(self, message: str, *, status_code: int | None = None):+ """Store the HTTP status alongside the message for richer logging."""+ super().__init__(message)+ self.status_code = status_codediff --git a/tests/cli/test_errors.py b/tests/cli/test_errors.pynew file mode 100644index 0000000..47072dc--- /dev/null+++ b/tests/cli/test_errors.py@@ -0,0 +1,132 @@+"""Tests for the CLI error reporting helpers."""++from __future__ import annotations++from pathlib import Path++import pytest+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.search.exceptions import (+ SearchClientError,+ SearchConnectionError,+ SearchHTTPError,+ SearchTimeoutError,+)+++def runner() -> CliRunner:+ """Return a CliRunner instance."""+ return CliRunner()++[email protected](autouse=True)+def _isolated_tmp_log_dir(monkeypatch, tmp_path):+ """Redirect _LOG_DIR so log files land under tmp_path instead of ~/.fli/logs/."""+ monkeypatch.setattr("fli.cli.errors._LOG_DIR", tmp_path / "fli-logs")+++def test_write_log_creates_file_with_traceback(tmp_path):+ """`_write_log` should write a file containing the traceback details."""+ try:+ raise SearchTimeoutError("backend slow")+ except SearchTimeoutError as exc:+ log_path = _write_log(exc, command="flights")++ assert log_path.exists()+ contents = log_path.read_text()+ assert "command: flights" in contents+ assert "SearchTimeoutError" in contents+ assert "backend slow" in contents+ assert "traceback:" in contents+++def test_json_error_payload_maps_error_types():+ """Each SearchClientError subclass should map to a distinct error_type string."""+ cases = [+ (SearchTimeoutError("timed out"), "timeout"),+ (SearchConnectionError("dns"), "connection_error"),+ (SearchHTTPError("403", status_code=403), "http_error"),+ (SearchClientError("generic"), "search_error"),+ (RuntimeError("boom"), "unexpected_error"),+ ]+ for exc, expected_type in cases:+ 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_report_cli_error_returns_typer_exit_and_writes_log(tmp_path, capsys):+ """`report_cli_error` should write a log and return a typer.Exit."""+ import typer++ exc = SearchTimeoutError("hung")+ result = report_cli_error(exc, command="multi")+ assert isinstance(result, typer.Exit)+ assert result.exit_code == 1++ # A log file should now exist under our redirected tmp dir.+ log_files = list((tmp_path / "fli-logs").glob("fli-error-*.log"))+ assert len(log_files) == 1+++def test_multi_command_handles_timeout_cleanly(runner, monkeypatch, tmp_path):+ """A curl timeout inside `multi` should produce a clean message + log file."""+ from curl_cffi.requests import exceptions as curl_exc++ def fake_post(self, url, **kwargs):+ raise curl_exc.Timeout("curl: (28) timed out", 28, None)++ monkeypatch.setattr("curl_cffi.requests.Session.post", fake_post)++ result = runner.invoke(+ app,+ [+ "multi",+ "-l",+ "SEA,NRT,2026-12-26",+ "-l",+ "NRT,HKG,2026-12-30",+ "-l",+ "HKG,SEA,2027-01-05",+ ],+ )++ assert result.exit_code == 1+ # Friendly message — no raw curl traceback in the output.+ assert "Error" in result.output+ assert "Timed out talking to Google Flights" in result.output+ assert "Full traceback written to" in result.output+ assert "Traceback (most recent call last)" not in result.output++ log_files = list((tmp_path / "fli-logs").glob("fli-error-*.log"))+ assert len(log_files) >= 1+++def test_flights_command_json_error_includes_log_path(runner, monkeypatch, tmp_path):+ """JSON-mode errors should include the log path and a typed error_type."""+ import json++ from curl_cffi.requests import exceptions as curl_exc++ def fake_post(self, url, **kwargs):+ raise curl_exc.ConnectionError("dns lookup failed", 6, None)++ monkeypatch.setattr("curl_cffi.requests.Session.post", fake_post)++ result = runner.invoke(+ app,+ ["flights", "JFK", "LHR", "2026-10-25", "--format", "json"],+ )++ assert result.exit_code == 1+ payload = json.loads(result.output)+ assert payload["success"] is False+ assert payload["error"]["type"] == "connection_error"+ assert "log_path" in payload["error"]+ assert Path(payload["error"]["log_path"]).exists()