Google Flights MCP, CLI and Python Library
feat(airports): resolve ICAO codes in airport search (#242)
Punit Arani1a67e26cab57
diff --git a/fli/cli/commands/airports.py b/fli/cli/commands/airports.pyindex a1b7dec..34d7d2d 100644--- a/fli/cli/commands/airports.py+++ b/fli/cli/commands/airports.py@@ -14,12 +14,12 @@ console = Console()def airports(query: Annotated[str,- typer.Argument(help="City name, airport name, or IATA code to search for"),+ typer.Argument(help="City name, airport name, IATA code, or ICAO code to search for"),],limit: Annotated[int, typer.Option("--limit", "-n", help="Maximum results")] = 10,json_output: Annotated[bool, typer.Option("--json", help="Output as JSON")] = False,):- """Search for airports by city name, airport name, or IATA code.+ """Search for airports by city name, airport name, IATA code, or ICAO code.Example:fli airports "new york"diff --git a/fli/core/airports.py b/fli/core/airports.pyindex e2db32f..39b56a1 100644--- a/fli/core/airports.py+++ b/fli/core/airports.py@@ -4,6 +4,7 @@ from typing import Literalfrom pydantic import BaseModel, ConfigDict, Field+from fli.core.parsers import icao_to_iatafrom fli.models import Airport, display_namefrom fli.models.airport import AIRPORT_NAMES@@ -70,7 +71,7 @@ for _city, _codes in CITY_AIRPORTS.items():if _code not in AIRPORT_NAMES:raise RuntimeError(f"CITY_AIRPORTS[{_city!r}] references unknown IATA code {_code!r}")-MatchType = Literal["iata_exact", "iata_prefix", "city", "name"]+MatchType = Literal["iata_exact", "icao_exact", "iata_prefix", "city", "name"]class AirportMatch(BaseModel):@@ -94,7 +95,13 @@ def search_airports(query: str, limit: int = 10) -> list[AirportMatch]:3. city (score 80) - query is a prefix of a city in CITY_AIRPORTS4. 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+ 5. icao_exact (score 65) - query is a known 4-letter ICAO code (e.g. "KJFK")+ 6. iata_prefix (score 60) - query (<=3 chars) is a prefix of an IATA code++ An ICAO hit deliberately ranks below city and name matches: many ICAO codes+ are also ordinary word fragments ("sant" is Tucuman's SANT, "kind" is+ Indianapolis' KIND), and a partial "Santa..." search must not be hijacked.+ For genuine ICAO input nothing else matches, so it is still the top result.Within a single result list, each IATA code appears at most once: thehighest-priority match wins.@@ -178,7 +185,19 @@ def search_airports(query: str, limit: int = 10) -> list[AirportMatch]:)seen_codes.add(code)- # Priority 5: IATA code prefix match (handles "SF" matching "SFO").+ # Priority 5: Exact ICAO code match (e.g. "KJFK" -> JFK), mirroring resolve_airport().+ # Scored below city/name matches on purpose - see the docstring.+ iata_from_icao = icao_to_iata(query_upper)+ if iata_from_icao in Airport.__members__ and iata_from_icao not in seen_codes:+ airport = Airport[iata_from_icao]+ results.append(+ AirportMatch(+ code=airport, name=display_name(airport), match_type="icao_exact", score=65.0+ )+ )+ seen_codes.add(iata_from_icao)++ # Priority 6: IATA code prefix match (handles "SF" matching "SFO").if len(query_upper) <= 3:for code in AIRPORT_NAMES:if code in seen_codes:diff --git a/fli/core/parsers.py b/fli/core/parsers.pyindex ab0659e..541013b 100644--- a/fli/core/parsers.py+++ b/fli/core/parsers.py@@ -47,6 +47,23 @@ def _load_icao_mapping() -> dict[str, str]:return _icao_to_iata+def icao_to_iata(code: str) -> str | None:+ """Translate a 4-letter ICAO airport code to its IATA code.++ Args:+ code: Candidate ICAO code (case-insensitive), e.g. ``"KJFK"``.++ Returns:+ The IATA code (e.g. ``"JFK"``), or ``None`` if ``code`` is not a known+ ICAO code.++ """+ normalized = code.strip().upper()+ if len(normalized) != 4 or not normalized.isalpha():+ return None+ return _load_icao_mapping().get(normalized)++def resolve_enum(enum_cls: type[T], name: str) -> T:"""Resolve an enum member by name with normalized errors.@@ -86,7 +103,7 @@ def resolve_airport(code: str) -> Airport:airport_code = code.upper()if len(airport_code) == 4 and airport_code.isalpha():- mapped = _load_icao_mapping().get(airport_code)+ mapped = icao_to_iata(airport_code)if mapped is None:raise ParseError(f"Unknown ICAO code: '{code}'. Not found in the ICAO-to-IATA mapping table."diff --git a/fli/mcp/server.py b/fli/mcp/server.pyindex 2b9f439..4792ccf 100755--- a/fli/mcp/server.py+++ b/fli/mcp/server.py@@ -1422,17 +1422,19 @@ def find_airports(str,Field(description=(- "City name, airport name, or IATA code (e.g., 'new york', 'heathrow', 'JFK')"+ "City name, airport name, IATA code, or ICAO code "+ "(e.g., 'new york', 'heathrow', 'JFK', 'KJFK')")),],limit: Annotated[int, Field(description="Maximum results to return", ge=1, le=50)] = 10,) -> dict[str, Any]:- """Search for airports by city name, airport name, or IATA code.+ """Search for airports by city name, airport name, IATA code, or ICAO code.Use this tool to find airport IATA codes before searching for flights.Supports city names (e.g., "new york" returns JFK, LGA, EWR),- airport names (e.g., "heathrow" returns LHR), and IATA codes.+ airport names (e.g., "heathrow" returns LHR), IATA codes, and 4-letter+ ICAO codes (e.g., "KJFK" returns JFK)."""return _find_airports_impl(query, limit=limit)diff --git a/tests/cli/test_airports.py b/tests/cli/test_airports.pyindex 4247bf5..ce01c7e 100644--- a/tests/cli/test_airports.py+++ b/tests/cli/test_airports.py@@ -27,6 +27,13 @@ class TestAirportsCommand:assert payload[0]["code"] == "JFK"assert payload[0]["match_type"] == "iata_exact"+ def test_icao_code_resolves(self, runner):+ result = runner.invoke(app, ["airports", "KJFK", "--json"])+ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert payload[0]["code"] == "JFK"+ assert payload[0]["match_type"] == "icao_exact"+def test_city_query_returns_all_airports(self, runner):result = runner.invoke(app, ["airports", "new york", "--json"])assert result.exit_code == 0diff --git a/tests/core/test_airports.py b/tests/core/test_airports.pyindex 8d3719c..e71aa32 100644--- a/tests/core/test_airports.py+++ b/tests/core/test_airports.py@@ -169,3 +169,36 @@ class TestDisambiguatedNamesStayInternal:" (1S)") # digit-leading code: suffix shows "1S", not "_1S"assert display_name(Airline._1S) == Airline._1S.value.removesuffix(" (1S)")+++class TestIcaoLookup:+ """`search_airports` resolves 4-letter ICAO codes, like `resolve_airport` does."""++ def test_icao_code_is_an_exact_match(self):+ """KJFK finds JFK as the top, exact result."""+ from fli.core.airports import search_airports++ results = search_airports("KJFK")+ assert results[0].code.name == "JFK"+ assert results[0].match_type == "icao_exact"++ def test_icao_lookup_is_case_insensitive(self):+ """Lower-case ICAO input resolves too."""+ from fli.core.airports import search_airports++ assert search_airports("egll")[0].code.name == "LHR"++ def test_unknown_four_letter_query_still_falls_through(self):+ """A 4-letter word that is not an ICAO code keeps using name/city search."""+ from fli.core.airports import search_airports++ results = search_airports("naha")+ assert results and all(r.match_type != "icao_exact" for r in results)++ def test_icao_hit_does_not_hijack_a_partial_word(self):+ """A "Santa..." search leads with names even though "sant" is Tucuman's ICAO code."""+ from fli.core.airports import search_airports++ results = search_airports("sant", limit=1000)+ assert results[0].match_type == "name"+ assert "TUC" in {r.code.name for r in results} # still offered, just not firstdiff --git a/tests/mcp/test_find_airports.py b/tests/mcp/test_find_airports.pyindex fc23e70..4dd8321 100644--- a/tests/mcp/test_find_airports.py+++ b/tests/mcp/test_find_airports.py@@ -14,6 +14,13 @@ class TestFindAirports:assert top["match_type"] == "iata_exact"assert "name" in top and isinstance(top["name"], str)+ def test_icao_code_returns_the_iata_airport(self):+ result = _find_airports_impl("KJFK")+ assert result["success"] is True+ top = result["airports"][0]+ assert top["code"] == "JFK"+ assert top["match_type"] == "icao_exact"+def test_city_query_returns_multiple_airports(self):result = _find_airports_impl("new york")codes = {a["code"] for a in result["airports"]}