Google Flights MCP, CLI and Python Library
refactor: harden airport search (Pydantic AirportMatch + import-time validation) (#152)
Punit Arani1cb0231edd9e
diff --git a/fli/cli/commands/airports.py b/fli/cli/commands/airports.pyindex 6e67c85..a1b7dec 100644--- a/fli/cli/commands/airports.py+++ b/fli/cli/commands/airports.py@@ -37,8 +37,13 @@ def airports(if json_output:import json- output = [{"code": r.code, "name": r.name, "match_type": r.match_type} for r in results]- console.print(json.dumps(output, indent=2))+ output = [+ {"code": r.code.name, "name": r.name, "match_type": r.match_type} for r in results+ ]+ # Plain print() bypasses Rich's markup parsing — JSON's `[` would+ # otherwise be interpreted as a style tag in non-TTY environments+ # (e.g. CI, pipes), suppressing output.+ print(json.dumps(output, indent=2))else:table = Table(title=f"Airports matching '{query}'")table.add_column("Code", style="bold cyan", width=6)@@ -46,6 +51,6 @@ def airports(table.add_column("Match", style="dim")for result in results:- table.add_row(result.code, result.name, result.match_type)+ table.add_row(result.code.name, result.name, result.match_type)console.print(table)diff --git a/fli/core/airports.py b/fli/core/airports.pyindex ed746e8..1c70e05 100644--- a/fli/core/airports.py+++ b/fli/core/airports.py@@ -1,9 +1,15 @@"""Airport search utilities for looking up airports by city or name."""+from typing import Literal++from pydantic import BaseModel, ConfigDict, Field+from fli.models import Airport-# Mapping of city names to IATA codes for airports where the city name-# is NOT in the airport name (e.g., JFK doesn't contain "New York")+# Curated mapping of city names and common abbreviations to IATA codes.+# Provides multi-airport groupings (e.g., "new york" -> JFK, LGA, EWR) and+# short aliases (e.g., "sf", "la", "nyc") that pure airport-name substring+# search would miss. Validated against the Airport enum at import time.CITY_AIRPORTS: dict[str, list[str]] = {"new york": ["JFK", "LGA", "EWR"],"nyc": ["JFK", "LGA", "EWR"],@@ -58,30 +64,43 @@ CITY_AIRPORTS: dict[str, list[str]] = {"honolulu": ["HNL"],}+for _city, _codes in CITY_AIRPORTS.items():+ for _code in _codes:+ if _code not in Airport.__members__:+ raise RuntimeError(f"CITY_AIRPORTS[{_city!r}] references unknown IATA code {_code!r}")++MatchType = Literal["iata_exact", "iata_prefix", "city", "name"]-class AirportMatch:++class AirportMatch(BaseModel):"""A matched airport from a search query."""- def __init__(self, code: str, name: str, match_type: str, score: float):- """Initialize a matched airport result."""- self.code = code- self.name = name- self.match_type = match_type # "code", "city", "name"- self.score = score-- def __repr__(self) -> str:- """Return a debug representation for the match."""- return (- f"AirportMatch(code={self.code!r}, name={self.name!r}, match_type={self.match_type!r})"- )+ model_config = ConfigDict(frozen=True)++ code: Airport+ name: str+ match_type: MatchType+ score: float = Field(ge=0.0, le=100.0)def search_airports(query: str, limit: int = 10) -> list[AirportMatch]:"""Search airports by city name, airport name, or IATA code.+ Results are ranked by a 5-priority cascade, scored 0-100 (higher = better):++ 1. iata_exact (score 100) - query is an exact IATA code (e.g. "JFK")+ 2. city (score 90) - query is an exact city/alias in CITY_AIRPORTS+ 3. city (score 80) - query is a prefix of a city in CITY_AIRPORTS+ 4. name (score <=70) - query is a substring of an airport's name;+ earlier match position scores higher+ 5. iata_prefix (score 60) - query (<=3 chars) is a prefix of an IATA code++ Within a single result list, each IATA code appears at most once: the+ highest-priority match wins.+Args:- query: Search string (e.g., "new york", "san fran", "JFK", "heathrow")- limit: Maximum results to return (must be >= 1).+ query: Search string (e.g., "new york", "san fran", "JFK", "heathrow").+ limit: Maximum results to return. Values < 1 yield an empty list.Returns:List of matching airports sorted by relevance (best match first).@@ -96,23 +115,22 @@ def search_airports(query: str, limit: int = 10) -> list[AirportMatch]:# Priority 1: Exact IATA code matchquery_upper = query.strip().upper()- try:+ if query_upper in Airport.__members__:airport = Airport[query_upper]- results.append(AirportMatch(query_upper, airport.value, "code", 100.0))+ results.append(+ AirportMatch(code=airport, name=airport.value, match_type="iata_exact", score=100.0)+ )seen_codes.add(query_upper)- except KeyError:- pass- # Priority 2: City name lookup (handles "new york" -> JFK, LGA, EWR)+ # Priority 2: Exact city name lookup (handles "new york" -> JFK, LGA, EWR)if query_lower in CITY_AIRPORTS:for code in CITY_AIRPORTS[query_lower]:if code not in seen_codes:- try:- airport = Airport[code]- results.append(AirportMatch(code, airport.value, "city", 90.0))- seen_codes.add(code)- except KeyError:- pass+ airport = Airport[code]+ results.append(+ AirportMatch(code=airport, name=airport.value, match_type="city", score=90.0)+ )+ seen_codes.add(code)# Priority 3: Partial city name match (handles "new yo" matching "new york")if query_lower not in CITY_AIRPORTS:@@ -120,12 +138,13 @@ def search_airports(query: str, limit: int = 10) -> list[AirportMatch]:if city.startswith(query_lower):for code in codes:if code not in seen_codes:- try:- airport = Airport[code]- results.append(AirportMatch(code, airport.value, "city", 80.0))- seen_codes.add(code)- except KeyError:- pass+ airport = Airport[code]+ results.append(+ AirportMatch(+ code=airport, name=airport.value, match_type="city", score=80.0+ )+ )+ seen_codes.add(code)# Priority 4: Airport name substring matchfor airport in Airport:@@ -133,10 +152,13 @@ def search_airports(query: str, limit: int = 10) -> list[AirportMatch]:continueairport_name_lower = airport.value.lower()if query_lower in airport_name_lower:- # Score based on how early the match occurs.+ # 0.1-per-position weight keeps name matches (max ~70) below+ # city matches (80) regardless of where the substring lands.pos = airport_name_lower.find(query_lower)- score = 70.0 - (pos * 0.1) # Earlier matches score higher.- results.append(AirportMatch(airport.name, airport.value, "name", score))+ score = 70.0 - (pos * 0.1)+ results.append(+ AirportMatch(code=airport, name=airport.value, match_type="name", score=score)+ )seen_codes.add(airport.name)# Priority 5: IATA code prefix match (handles "SF" matching "SFO")@@ -145,9 +167,13 @@ def search_airports(query: str, limit: int = 10) -> list[AirportMatch]:if airport.name in seen_codes:continueif airport.name.startswith(query_upper):- results.append(AirportMatch(airport.name, airport.value, "code", 60.0))+ results.append(+ AirportMatch(+ code=airport, name=airport.value, match_type="iata_prefix", score=60.0+ )+ )seen_codes.add(airport.name)- # Sort by score descending, then by code alphabetically- results.sort(key=lambda m: (-m.score, m.code))+ # Sort by score descending, then by IATA code alphabetically.+ results.sort(key=lambda m: (-m.score, m.code.name))return results[:limit]diff --git a/fli/mcp/server.py b/fli/mcp/server.pyindex 13522cf..ac473e3 100755--- a/fli/mcp/server.py+++ b/fli/mcp/server.py@@ -589,6 +589,27 @@ def _search_dates_from_params(params: DateSearchParams) -> dict[str, Any]:return _execute_date_search(params)+def _find_airports_impl(query: str, limit: int = 10) -> dict[str, Any]:+ """Run search_airports and shape the result into the MCP response dict."""+ try:+ results = search_airports(query, limit=limit)+ except Exception as exc:+ return {+ "success": False,+ "error": str(exc),+ "query": query,+ }++ return {+ "success": True,+ "query": query,+ "count": len(results),+ "airports": [+ {"code": r.code.name, "name": r.name, "match_type": r.match_type} for r in results+ ],+ }++@mcp.tool(annotations={"title": "Search Airports",@@ -613,13 +634,7 @@ def find_airports(Supports city names (e.g., "new york" returns JFK, LGA, EWR),airport names (e.g., "heathrow" returns LHR), and IATA codes."""- results = search_airports(query, limit=limit)-- return {- "query": query,- "count": len(results),- "airports": [{"code": r.code, "name": r.name, "match_type": r.match_type} for r in results],- }+ return _find_airports_impl(query, limit=limit)# =============================================================================diff --git a/tests/cli/test_airports.py b/tests/cli/test_airports.pynew file mode 100644index 0000000..4247bf5--- /dev/null+++ b/tests/cli/test_airports.py@@ -0,0 +1,44 @@+"""Tests for the `fli airports` CLI command."""++import json++import pytest+from typer.testing import CliRunner++from fli.cli.main import app+++def runner():+ return CliRunner()+++class TestAirportsCommand:+ def test_exact_code_table_output(self, runner):+ result = runner.invoke(app, ["airports", "JFK"])+ assert result.exit_code == 0+ assert "JFK" in result.stdout++ def test_json_output(self, runner):+ result = runner.invoke(app, ["airports", "JFK", "--json"])+ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert isinstance(payload, list)+ assert payload[0]["code"] == "JFK"+ assert payload[0]["match_type"] == "iata_exact"++ def test_city_query_returns_all_airports(self, runner):+ result = runner.invoke(app, ["airports", "new york", "--json"])+ assert result.exit_code == 0+ codes = {row["code"] for row in json.loads(result.stdout)}+ assert {"JFK", "LGA", "EWR"} <= codes++ def test_no_results_exits_with_error(self, runner):+ result = runner.invoke(app, ["airports", "xyznonexistent"])+ assert result.exit_code == 1+ assert "No airports found" in result.stdout++ def test_limit_caps_results(self, runner):+ result = runner.invoke(app, ["airports", "international", "--limit", "2", "--json"])+ assert result.exit_code == 0+ assert len(json.loads(result.stdout)) <= 2diff --git a/tests/core/test_airports.py b/tests/core/test_airports.pyindex ffb6853..0e7a5e2 100644--- a/tests/core/test_airports.py+++ b/tests/core/test_airports.py@@ -1,99 +1,141 @@"""Tests for airport search functionality."""-from fli.core.airports import search_airports+from fli.core.airports import AirportMatch, search_airports+from fli.models import Airportclass TestSearchAirports:- """Tests for the search_airports function."""-def test_exact_iata_code(self):- """Exact IATA code returns the airport."""results = search_airports("JFK")assert len(results) >= 1- assert results[0].code == "JFK"- assert results[0].match_type == "code"+ assert results[0].code is Airport.JFK+ assert results[0].match_type == "iata_exact"+ assert results[0].score == 100.0def test_iata_code_case_insensitive(self):- """IATA code search is case-insensitive."""results = search_airports("jfk")- assert len(results) >= 1- assert results[0].code == "JFK"+ assert results[0].code is Airport.JFK++ def test_iata_code_with_surrounding_whitespace(self):+ results = search_airports(" JFK ")+ assert results[0].code is Airport.JFK+ assert results[0].match_type == "iata_exact"def test_city_name_new_york(self):- """City name 'new york' returns NYC airports."""- results = search_airports("new york")- codes = [r.code for r in results]- assert "JFK" in codes- assert "LGA" in codes- assert "EWR" in codes+ codes = {r.code for r in search_airports("new york")}+ assert {Airport.JFK, Airport.LGA, Airport.EWR} <= codesdef test_city_name_tokyo(self):- """City name 'tokyo' returns Tokyo airports."""- results = search_airports("tokyo")- codes = [r.code for r in results]- assert "NRT" in codes- assert "HND" in codes+ codes = {r.code for r in search_airports("tokyo")}+ assert {Airport.NRT, Airport.HND} <= codes- def test_city_name_london(self):- """City name 'london' returns London airports."""- results = search_airports("london")- codes = [r.code for r in results]- assert "LHR" in codes- assert "LGW" in codes+ def test_city_name_london_returns_all_five(self):+ codes = {r.code for r in search_airports("london")}+ assert {Airport.LHR, Airport.LGW, Airport.STN, Airport.LTN, Airport.LCY} <= codesdef test_airport_name_substring(self):- """Searching by airport name substring works."""results = search_airports("heathrow")- assert len(results) >= 1- assert results[0].code == "LHR"+ assert results[0].code is Airport.LHR+ assert results[0].match_type == "name"- def test_airport_name_san_francisco(self):- """Searching 'san francisco' matches via both city map and name."""+ def test_san_francisco_dedupes_across_priorities(self):+ # "san francisco" matches both Priority 2 (city map) and Priority 4+ # (airport name substring). seen_codes must prevent duplicates.results = search_airports("san francisco")codes = [r.code for r in results]- assert "SFO" in codes+ assert codes.count(Airport.SFO) == 1def test_partial_city_name(self):- """Partial city name matches."""- results = search_airports("new yo")- codes = [r.code for r in results]- assert "JFK" in codes-- def test_iata_prefix(self):- """Partial IATA code prefix matches."""- results = search_airports("SF")- codes = [r.code for r in results]- assert "SFO" in codes+ codes = {r.code for r in search_airports("new yo")}+ assert Airport.JFK in codes++ def test_iata_prefix_distinct_from_exact(self):+ # "JF" is not an exact IATA code, not a city alias, and not a substring+ # of any airport name -- so only Priority 5 (iata_prefix) fires.+ results = search_airports("JF")+ jfk_match = next(r for r in results if r.code is Airport.JFK)+ assert jfk_match.match_type == "iata_prefix"+ assert jfk_match.score == 60.0+ # All results for this query should be prefix matches.+ assert all(r.match_type == "iata_prefix" for r in results)def test_empty_query(self):- """Empty query returns empty list."""assert search_airports("") == []assert search_airports(" ") == []def test_no_results(self):- """Query with no matches returns empty list."""- results = search_airports("xyznonexistent")- assert results == []+ assert search_airports("xyznonexistent") == []++ def test_invalid_limit_returns_empty(self):+ assert search_airports("JFK", limit=0) == []+ assert search_airports("JFK", limit=-1) == []- def test_limit(self):- """Limit parameter caps results."""- results = search_airports("international", limit=3)- assert len(results) <= 3+ def test_limit_caps_results(self):+ assert len(search_airports("international", limit=3)) <= 3- def test_code_match_highest_priority(self):- """Exact code match scores higher than name match."""+ def test_default_limit_is_ten(self):+ # "international" appears in many airport names; default limit is 10.+ assert len(search_airports("international")) <= 10++ def test_priority_ordering(self):+ # Exact code (100) must rank above any city/name/prefix match for the same query family.results = search_airports("LAX")- assert results[0].code == "LAX"- assert results[0].match_type == "code"+ assert results[0].code is Airport.LAX+ assert results[0].match_type == "iata_exact"+ # Scores in the returned list must be monotonically non-increasing.+ scores = [r.score for r in results]+ assert scores == sorted(scores, reverse=True)++ def test_priority_3_skipped_when_exact_city_match(self):+ # When query is an exact city, only Priority 2 (score 90) should fire,+ # not Priority 3 (score 80). All city-matched results should be 90.+ results = search_airports("london")+ city_results = [r for r in results if r.match_type == "city"]+ assert city_results, "expected at least one city-typed match for 'london'"+ assert all(r.score == 90.0 for r in city_results)++ def test_name_score_decreases_with_position(self):+ # The 0.1-per-position weight means a match at position 0 outscores one later.+ results = search_airports("international")+ name_matches = [r for r in results if r.match_type == "name"]+ if len(name_matches) >= 2:+ scores = [r.score for r in name_matches]+ assert scores == sorted(scores, reverse=True)+ assert all(s <= 70.0 for s in scores)def test_city_abbreviation(self):- """City abbreviations work."""- results = search_airports("sf")- codes = [r.code for r in results]- assert "SFO" in codes+ codes = {r.code for r in search_airports("sf")}+ assert Airport.SFO in codesdef test_nyc_abbreviation(self):- """NYC abbreviation works."""- results = search_airports("nyc")- codes = [r.code for r in results]- assert "JFK" in codes+ codes = {r.code for r in search_airports("nyc")}+ assert Airport.JFK in codes+++class TestAirportMatch:+ def test_frozen(self):+ m = AirportMatch(code=Airport.JFK, name="JFK Airport", match_type="iata_exact", score=100.0)+ try:+ m.score = 0.0+ except Exception:+ return+ raise AssertionError("AirportMatch should be frozen")++ def test_equality(self):+ a = AirportMatch(code=Airport.JFK, name="JFK", match_type="city", score=90.0)+ b = AirportMatch(code=Airport.JFK, name="JFK", match_type="city", score=90.0)+ assert a == b++ def test_rejects_invalid_match_type(self):+ try:+ AirportMatch(code=Airport.JFK, name="JFK", match_type="bogus", score=50.0) # type: ignore[arg-type]+ except Exception:+ return+ raise AssertionError("AirportMatch should reject unknown match_type")++ def test_rejects_score_out_of_range(self):+ try:+ AirportMatch(code=Airport.JFK, name="JFK", match_type="iata_exact", score=101.0)+ except Exception:+ return+ raise AssertionError("AirportMatch should reject score > 100")diff --git a/tests/mcp/test_find_airports.py b/tests/mcp/test_find_airports.pynew file mode 100644index 0000000..fc23e70--- /dev/null+++ b/tests/mcp/test_find_airports.py@@ -0,0 +1,42 @@+"""Tests for the MCP find_airports tool."""++from fli.mcp.server import _find_airports_impl+++class TestFindAirports:+ def test_exact_code_returns_structured_result(self):+ result = _find_airports_impl("JFK")+ assert result["success"] is True+ assert result["query"] == "JFK"+ assert result["count"] >= 1+ top = result["airports"][0]+ assert top["code"] == "JFK"+ assert top["match_type"] == "iata_exact"+ assert "name" in top and isinstance(top["name"], str)++ def test_city_query_returns_multiple_airports(self):+ result = _find_airports_impl("new york")+ codes = {a["code"] for a in result["airports"]}+ assert {"JFK", "LGA", "EWR"} <= codes+ assert all(+ a["match_type"] == "city"+ for a in result["airports"]+ if a["code"] in {"JFK", "LGA", "EWR"}+ )++ def test_no_results_returns_empty_list_success(self):+ result = _find_airports_impl("xyznonexistent")+ assert result["success"] is True+ assert result["count"] == 0+ assert result["airports"] == []++ def test_limit_caps_results(self):+ result = _find_airports_impl("international", limit=3)+ assert len(result["airports"]) <= 3+ assert result["count"] == len(result["airports"])++ def test_invalid_limit_returns_empty_success(self):+ # _find_airports_impl forwards limit; search_airports handles <1 by returning [].+ result = _find_airports_impl("JFK", limit=0)+ assert result["success"] is True+ assert result["count"] == 0