Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

feat: add airport search by city name, airport name, or IATA code (#115)

Trevin Chowbeab57a2940a
diff --git a/fli/cli/commands/airports.py b/fli/cli/commands/airports.py
new file mode 100644
index 0000000..6e67c85
--- /dev/null
+++ b/fli/cli/commands/airports.py
@@ -0,0 +1,51 @@
+"""Airport search command for looking up IATA codes."""
+
+from typing import Annotated
+
+import typer
+from rich.console import Console
+from rich.table import Table
+
+from fli.core.airports import search_airports
+
+console = Console()
+
+
+def airports(
+ query: Annotated[
+ str,
+ typer.Argument(help="City name, airport name, or IATA 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.
+
+ Example:
+ fli airports "new york"
+ fli airports tokyo
+ fli airports JFK
+ fli airports heathrow
+
+ """
+ results = search_airports(query, limit=limit)
+
+ if not results:
+ console.print(f"[yellow]No airports found matching '{query}'[/yellow]")
+ raise typer.Exit(1)
+
+ 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))
+ else:
+ table = Table(title=f"Airports matching '{query}'")
+ table.add_column("Code", style="bold cyan", width=6)
+ table.add_column("Airport Name", style="white")
+ table.add_column("Match", style="dim")
+
+ for result in results:
+ table.add_row(result.code, result.name, result.match_type)
+
+ console.print(table)
diff --git a/fli/cli/main.py b/fli/cli/main.py
index 9625b66..68025a7 100644
--- a/fli/cli/main.py
+++ b/fli/cli/main.py
@@ -5,6 +5,7 @@ import sys
import typer
+from fli.cli.commands.airports import airports
from fli.cli.commands.dates import dates
from fli.cli.commands.flights import flights
@@ -16,6 +17,7 @@ app = typer.Typer(
# Register commands
app.command(name="flights")(flights)
app.command(name="dates")(dates)
+app.command(name="airports")(airports)
@app.callback(invoke_without_command=True)
@@ -37,7 +39,7 @@ def cli():
args.append("--help")
# If the first argument isn't a command, treat as flights search
- if args[0] not in ["flights", "dates", "--help", "-h"]:
+ if args[0] not in ["flights", "dates", "airports", "--help", "-h"]:
sys.argv.insert(1, "flights")
app()
diff --git a/fli/core/__init__.py b/fli/core/__init__.py
index 0f2a3f2..d1d9cc5 100644
--- a/fli/core/__init__.py
+++ b/fli/core/__init__.py
@@ -4,6 +4,7 @@ This module provides shared parsing and building utilities used by both
the CLI and MCP interfaces.
"""
+from .airports import search_airports
from .builders import (
build_date_search_segments,
build_flight_segments,
@@ -37,6 +38,7 @@ __all__ = [
"build_flight_segments",
"build_multi_city_segments",
"build_time_restrictions",
+ "search_airports",
# Currency
"extract_currency_from_price_token",
"format_price",
diff --git a/fli/core/airports.py b/fli/core/airports.py
new file mode 100644
index 0000000..ed746e8
--- /dev/null
+++ b/fli/core/airports.py
@@ -0,0 +1,153 @@
+"""Airport search utilities for looking up airports by city or name."""
+
+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")
+CITY_AIRPORTS: dict[str, list[str]] = {
+ "new york": ["JFK", "LGA", "EWR"],
+ "nyc": ["JFK", "LGA", "EWR"],
+ "chicago": ["ORD", "MDW"],
+ "washington": ["IAD", "DCA", "BWI"],
+ "washington dc": ["IAD", "DCA", "BWI"],
+ "london": ["LHR", "LGW", "STN", "LTN", "LCY"],
+ "paris": ["CDG", "ORY"],
+ "tokyo": ["NRT", "HND"],
+ "osaka": ["KIX", "ITM"],
+ "seoul": ["ICN", "GMP"],
+ "beijing": ["PEK", "PKX"],
+ "shanghai": ["PVG", "SHA"],
+ "bangkok": ["BKK", "DMK"],
+ "istanbul": ["IST", "SAW"],
+ "moscow": ["SVO", "DME", "VKO"],
+ "milan": ["MXP", "LIN"],
+ "rome": ["FCO", "CIA"],
+ "berlin": ["BER"],
+ "mumbai": ["BOM"],
+ "delhi": ["DEL"],
+ "sao paulo": ["GRU", "CGH"],
+ "rio": ["GIG", "SDU"],
+ "rio de janeiro": ["GIG", "SDU"],
+ "toronto": ["YYZ", "YTZ"],
+ "montreal": ["YUL"],
+ "mexico city": ["MEX"],
+ "buenos aires": ["EZE", "AEP"],
+ "dubai": ["DXB", "DWC"],
+ "singapore": ["SIN"],
+ "hong kong": ["HKG"],
+ "taipei": ["TPE", "TSA"],
+ "sydney": ["SYD"],
+ "melbourne": ["MEL"],
+ "san francisco": ["SFO", "OAK", "SJC"],
+ "sf": ["SFO", "OAK", "SJC"],
+ "bay area": ["SFO", "OAK", "SJC"],
+ "los angeles": ["LAX", "BUR", "SNA", "ONT", "LGB"],
+ "la": ["LAX", "BUR", "SNA", "ONT", "LGB"],
+ "dallas": ["DFW", "DAL"],
+ "houston": ["IAH", "HOU"],
+ "atlanta": ["ATL"],
+ "denver": ["DEN"],
+ "seattle": ["SEA"],
+ "boston": ["BOS"],
+ "miami": ["MIA", "FLL"],
+ "detroit": ["DTW"],
+ "minneapolis": ["MSP"],
+ "phoenix": ["PHX"],
+ "orlando": ["MCO"],
+ "las vegas": ["LAS"],
+ "honolulu": ["HNL"],
+}
+
+
+class AirportMatch:
+ """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})"
+ )
+
+
+def search_airports(query: str, limit: int = 10) -> list[AirportMatch]:
+ """Search airports by city name, airport name, or IATA code.
+
+ Args:
+ query: Search string (e.g., "new york", "san fran", "JFK", "heathrow")
+ limit: Maximum results to return (must be >= 1).
+
+ Returns:
+ List of matching airports sorted by relevance (best match first).
+
+ """
+ query_lower = query.strip().lower()
+ if not query_lower or limit < 1:
+ return []
+
+ results: list[AirportMatch] = []
+ seen_codes: set[str] = set()
+
+ # Priority 1: Exact IATA code match
+ query_upper = query.strip().upper()
+ try:
+ airport = Airport[query_upper]
+ results.append(AirportMatch(query_upper, airport.value, "code", 100.0))
+ seen_codes.add(query_upper)
+ except KeyError:
+ pass
+
+ # Priority 2: 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
+
+ # Priority 3: Partial city name match (handles "new yo" matching "new york")
+ if query_lower not in CITY_AIRPORTS:
+ for city, codes in CITY_AIRPORTS.items():
+ 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
+
+ # Priority 4: Airport name substring match
+ for airport in Airport:
+ if airport.name in seen_codes:
+ continue
+ airport_name_lower = airport.value.lower()
+ if query_lower in airport_name_lower:
+ # Score based on how early the match occurs.
+ 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))
+ seen_codes.add(airport.name)
+
+ # Priority 5: IATA code prefix match (handles "SF" matching "SFO")
+ if len(query_upper) <= 3:
+ for airport in Airport:
+ if airport.name in seen_codes:
+ continue
+ if airport.name.startswith(query_upper):
+ results.append(AirportMatch(airport.name, airport.value, "code", 60.0))
+ seen_codes.add(airport.name)
+
+ # Sort by score descending, then by code alphabetically
+ results.sort(key=lambda m: (-m.score, m.code))
+ return results[:limit]
diff --git a/fli/mcp/server.py b/fli/mcp/server.py
index 35a2471..fe7d987 100755
--- a/fli/mcp/server.py
+++ b/fli/mcp/server.py
@@ -24,6 +24,7 @@ from fli.core import (
parse_max_stops,
parse_sort_by,
resolve_airport,
+ search_airports,
)
from fli.core.parsers import ParseError
from fli.models import (
@@ -588,6 +589,40 @@ def _search_dates_from_params(params: DateSearchParams) -> dict[str, Any]:
return _execute_date_search(params)
+ annotations={
+ "title": "Search Airports",
+ "readOnlyHint": True,
+ "idempotentHint": True,
+ },
+)
+def find_airports(
+ query: Annotated[
+ str,
+ Field(
+ description=(
+ "City name, airport name, or IATA code (e.g., 'new york', 'heathrow', 'JFK')"
+ )
+ ),
+ ],
+ 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.
+
+ 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.
+ """
+ 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],
+ }
+
+
+
# =============================================================================
# Prompts
# =============================================================================
diff --git a/tests/core/test_airports.py b/tests/core/test_airports.py
new file mode 100644
index 0000000..ffb6853
--- /dev/null
+++ b/tests/core/test_airports.py
@@ -0,0 +1,99 @@
+"""Tests for airport search functionality."""
+
+from fli.core.airports import search_airports
+
+
+class 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"
+
+ def 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"
+
+ 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
+
+ def 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
+
+ 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_airport_name_substring(self):
+ """Searching by airport name substring works."""
+ results = search_airports("heathrow")
+ assert len(results) >= 1
+ assert results[0].code == "LHR"
+
+ def test_airport_name_san_francisco(self):
+ """Searching 'san francisco' matches via both city map and name."""
+ results = search_airports("san francisco")
+ codes = [r.code for r in results]
+ assert "SFO" in codes
+
+ def 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
+
+ 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 == []
+
+ def test_limit(self):
+ """Limit parameter caps results."""
+ results = search_airports("international", limit=3)
+ assert len(results) <= 3
+
+ def test_code_match_highest_priority(self):
+ """Exact code match scores higher than name match."""
+ results = search_airports("LAX")
+ assert results[0].code == "LAX"
+ assert results[0].match_type == "code"
+
+ def test_city_abbreviation(self):
+ """City abbreviations work."""
+ results = search_airports("sf")
+ codes = [r.code for r in results]
+ assert "SFO" in codes
+
+ def test_nyc_abbreviation(self):
+ """NYC abbreviation works."""
+ results = search_airports("nyc")
+ codes = [r.code for r in results]
+ assert "JFK" in codes