Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

v0.7.0 (#27)

Punit Arani6c5330430fb8
diff --git a/CLAUDE.md b/CLAUDE.md
index f91e93e..3eac206 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6,8 +6,10 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
Fli is a Python library that provides programmatic access to Google Flights data through direct API interaction (reverse engineering). The project consists of:
-- **CLI interface** (`fli/cli/`) - Typer-based command line tool with `search` and `cheap` commands
-- **Core search engine** (`fli/search/`) - Flight and date search implementations using Google Flights API
+- **CLI interface** (`fli/cli/`) - Typer-based command line tool with `flights` and `dates` commands
+- **MCP server** (`fli/mcp/`) - Model Context Protocol server for AI assistant integration
+- **Core utilities** (`fli/core/`) - Shared parsing and building utilities
+- **Search engine** (`fli/search/`) - Flight and date search implementations using Google Flights API
- **Data models** (`fli/models/`) - Pydantic models for airports, airlines, and flight data structures
- **FastAPI server** (`fli/server/`) - REST API endpoints for flight search functionality
@@ -16,69 +18,71 @@ Fli is a Python library that provides programmatic access to Google Flights data
### Core Development Tasks
```bash
# Install dependencies
-poetry install
+uv sync --all-extras
# Run tests (use these specific commands)
make test # Standard test suite
make test-fuzz # Run fuzzing tests (pytest -vv --fuzz)
make test-all # Run all tests (pytest -vv --all)
-poetry run pytest -vv # Alternative direct command
+uv run pytest -vv # Alternative direct command
# Code quality
make lint # Check code with ruff
make lint-fix # Auto-fix linting issues
make format # Format code with ruff
-poetry run ruff check . # Direct ruff check
-poetry run ruff format . # Direct ruff format
+uv run ruff check . # Direct ruff check
+uv run ruff format . # Direct ruff format
-# Server development
-make server # Run production server
-make server-dev # Run development server with reload
-poetry run uvicorn fli.server.main:app --reload
+# MCP server
+fli-mcp # Run MCP server on STDIO
+fli-mcp-http # Run MCP server over HTTP
# Documentation
make docs # Build MkDocs documentation
-poetry run mkdocs serve # Serve docs locally
-poetry run mkdocs build # Build static docs
-
-# Dependencies
-make requirements # Generate requirements.txt from poetry.lock
+uv run mkdocs serve # Serve docs locally
+uv run mkdocs build # Build static docs
```
### Test Configuration
- Tests use pytest with custom markers: `fuzz` (requires `--fuzz` flag) and `parallel` (for pytest-xdist)
-- Test structure mirrors source code: `tests/cli/`, `tests/models/`, `tests/search/`, `tests/server/`
+- Test structure mirrors source code: `tests/cli/`, `tests/models/`, `tests/search/`, `tests/mcp/`
- Fuzzing tests are available but gated behind `--fuzz` flag
## Architecture Overview
### Core Components
-1. **Client Layer** (`fli/search/client.py`)
+1. **Core Layer** (`fli/core/`)
+ - `parsers.py`: Shared parsing utilities (airports, airlines, stops, cabin class, time ranges)
+ - `builders.py`: Filter building utilities (flight segments, time restrictions)
+ - Used by both CLI and MCP for consistent parameter handling
+
+2. **Client Layer** (`fli/search/client.py`)
- Rate-limited HTTP client (10 req/sec) using curl-cffi for browser impersonation
- Automatic retries with exponential backoff
- Session management for Google Flights API communication
-2. **Search Engine** (`fli/search/`)
+3. **Search Engine** (`fli/search/`)
- `SearchFlights`: Core flight search using Google Flights API
- `SearchDates`: Find cheapest dates within date ranges
- Direct API integration (no web scraping)
-3. **Data Models** (`fli/models/`)
+4. **Data Models** (`fli/models/`)
- **Base models**: `Airport`, `Airline` enums with IATA codes
- **Google Flights models**: `FlightSearchFilters`, `FlightResult`, `FlightLeg`, etc.
- **Filter models**: `TimeRestrictions`, `MaxStops`, `SeatType`, `SortBy`
- All models use Pydantic for validation
-4. **CLI Interface** (`fli/cli/`)
- - Typer-based with two main commands: `search` and `cheap`
- - Smart argument parsing (treats non-command args as search)
- - Rich console output for flight results
+5. **MCP Server** (`fli/mcp/`)
+ - FastMCP-based server with two tools: `search_flights` and `search_dates`
+ - Industry-standard parameter naming: `origin`, `destination`, `cabin_class`, `max_stops`
+ - Prompt templates for guided searches
+ - Configuration via environment variables
-5. **Server API** (`fli/server/`)
- - FastAPI application with CORS middleware
- - Routes: `/flights/` and `/dates/`
- - Request tracing middleware for monitoring
+6. **CLI Interface** (`fli/cli/`)
+ - Typer-based with two main commands: `flights` and `dates`
+ - Smart argument parsing (treats non-command args as flights)
+ - Rich console output for flight results
### Key Design Patterns
@@ -86,22 +90,50 @@ make requirements # Generate requirements.txt from poetry.lock
- **Rate Limiting**: Built-in 10 req/sec limit with automatic retry logic
- **Enum-Based Configuration**: Airports, airlines, seat types, etc. are strongly typed enums
- **Filter Pattern**: Search functionality uses comprehensive filter objects
+- **Shared Utilities**: Core parsing/building logic shared between CLI and MCP
- **Validation**: Pydantic models ensure data integrity throughout
## Key Files and Entry Points
- `fli/cli/main.py` - CLI entry point and command registration
-- `fli/server/main.py` - FastAPI application setup and router registration
+- `fli/mcp/server.py` - MCP server with `search_flights` and `search_dates` tools
+- `fli/core/parsers.py` - Shared parsing utilities
+- `fli/core/builders.py` - Shared filter building utilities
- `fli/search/flights.py` - Core flight search implementation
- `fli/search/client.py` - HTTP client with rate limiting and retries
- `fli/models/google_flights/` - All Google Flights data structures
-- `pyproject.toml` - Poetry configuration with script entry points
+- `pyproject.toml` - Package configuration with script entry points
+
+## MCP Tool Reference
+
+### `search_flights`
+Search for flights on a specific date.
+
+**Key Parameters:**
+- `origin` / `destination` - Airport IATA codes
+- `departure_date` / `return_date` - Dates in YYYY-MM-DD format
+- `cabin_class` - ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST
+- `max_stops` - ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS
+- `departure_window` - Time range in 'HH-HH' format
+- `airlines` - List of airline IATA codes
+- `sort_by` - CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME
+
+### `search_dates`
+Find cheapest travel dates within a range.
+
+**Key Parameters:**
+- `origin` / `destination` - Airport IATA codes
+- `start_date` / `end_date` - Date range in YYYY-MM-DD format
+- `trip_duration` - Number of days for round trips
+- `is_round_trip` - Boolean for round-trip search
+- `cabin_class`, `max_stops`, `departure_window`, `airlines` - Same as above
+- `sort_by_price` - Boolean to sort by price
## Code Style and Standards
- **Linting**: Uses Ruff with pycodestyle, pyflakes, isort, flake8-bugbear, and pydocstyle
- **Formatting**: Ruff formatter with 100 character line length, 4-space indentation
-- **Type Hints**: Python 3.12+ with full type annotations
+- **Type Hints**: Python 3.10+ with full type annotations
- **Docstrings**: Google-style docstrings (configured in mkdocs.yml)
- **Testing**: pytest with asyncio support and parallel execution capabilities
@@ -111,5 +143,5 @@ make requirements # Generate requirements.txt from poetry.lock
- Airport and airline codes use official IATA standards
- Flight search supports complex filters: time ranges, cabin classes, stop preferences, sorting
- Date search finds cheapest flights within flexible date ranges
-- Server includes request tracing for monitoring API usage
-- CLI supports both explicit commands and smart argument inference
\ No newline at end of file
+- MCP server uses industry-standard naming: `origin`/`destination`, `cabin_class`, `max_stops`
+- Core utilities ensure consistent parsing between CLI and MCP interfaces
diff --git a/README.md b/README.md
index 8fd1130..fe3f63b 100644
--- a/README.md
+++ b/README.md
@@ -42,6 +42,47 @@ fli-mcp-http # serves at http://127.0.0.1:8000/mcp/
> **Note**: Replace `<user>` with your actual username.
> You can also find the path to the MCP server by running `which fli-mcp` in your terminal.
+### MCP Tools Available
+
+The MCP server provides two main tools:
+
+| Tool | Description |
+|------|-------------|
+| **`search_flights`** | Search for flights on a specific date with detailed filters |
+| **`search_dates`** | Find the cheapest travel dates across a flexible date range |
+
+#### `search_flights` Parameters
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `origin` | string | Departure airport IATA code (e.g., 'JFK') |
+| `destination` | string | Arrival airport IATA code (e.g., 'LHR') |
+| `departure_date` | string | Travel date in YYYY-MM-DD format |
+| `return_date` | string | Return date for round trips (optional) |
+| `cabin_class` | string | ECONOMY, PREMIUM_ECONOMY, BUSINESS, or FIRST |
+| `max_stops` | string | ANY, NON_STOP, ONE_STOP, or TWO_PLUS_STOPS |
+| `departure_window` | string | Time window in 'HH-HH' format (e.g., '6-20') |
+| `airlines` | list | Filter by airline codes (e.g., ['BA', 'AA']) |
+| `sort_by` | string | CHEAPEST, DURATION, DEPARTURE_TIME, or ARRIVAL_TIME |
+| `passengers` | int | Number of adult passengers |
+
+#### `search_dates` Parameters
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `origin` | string | Departure airport IATA code (e.g., 'JFK') |
+| `destination` | string | Arrival airport IATA code (e.g., 'LHR') |
+| `start_date` | string | Start of date range in YYYY-MM-DD format |
+| `end_date` | string | End of date range in YYYY-MM-DD format |
+| `trip_duration` | int | Trip duration in days (for round-trips) |
+| `is_round_trip` | bool | Whether to search for round-trip flights |
+| `cabin_class` | string | ECONOMY, PREMIUM_ECONOMY, BUSINESS, or FIRST |
+| `max_stops` | string | ANY, NON_STOP, ONE_STOP, or TWO_PLUS_STOPS |
+| `departure_window` | string | Time window in 'HH-HH' format (e.g., '6-20') |
+| `airlines` | list | Filter by airline codes (e.g., ['BA', 'AA']) |
+| `sort_by_price` | bool | Sort results by price (lowest first) |
+| `passengers` | int | Number of adult passengers |
+
## Quick Start
```bash
@@ -88,29 +129,29 @@ fli --help
## CLI Usage
-### Search for Specific Flights
+### Search for Flights
```bash
-# Basic search
-fli search JFK LHR 2025-10-25
+# Basic flight search
+fli flights JFK LHR 2025-10-25
# Advanced search with filters
-fli search JFK LHR 2025-10-25 \
- -t 6-20 \ # Time range (6 AM - 8 PM)
- -a BA KL \ # Airlines (British Airways, KLM)
- -s BUSINESS \ # Seat type
- -x NON_STOP \ # Non-stop flights only
- -o DURATION # Sort by duration
+fli flights JFK LHR 2025-10-25 \
+ --time 6-20 \ # Departure time window (6 AM - 8 PM)
+ --airlines BA KL \ # Airlines (British Airways, KLM)
+ --class BUSINESS \ # Cabin class
+ --stops NON_STOP \ # Non-stop flights only
+ --sort DURATION # Sort by duration
```
### Find Cheapest Dates
```bash
-# Basic search for cheapest dates
-fli cheap JFK LHR
+# Basic date search
+fli dates JFK LHR
# Advanced search with date range
-fli cheap JFK LHR \
+fli dates JFK LHR \
--from 2025-01-01 \
--to 2025-02-01 \
--monday --friday # Only Mondays and Fridays
@@ -118,25 +159,25 @@ fli cheap JFK LHR \
### CLI Options
-#### Search Command (`fli search`)
+#### Flights Command (`fli flights`)
-| Option | Description | Example |
-|------------------|-------------------------|------------------------|
-| `-t, --time` | Time range (24h format) | `6-20` |
-| `-a, --airlines` | Airline codes | `BA KL` |
-| `-s, --seat` | Cabin class | `ECONOMY`, `BUSINESS` |
-| `-x, --stops` | Maximum stops | `NON_STOP`, `ONE_STOP` |
-| `-o, --sort` | Sort results by | `CHEAPEST`, `DURATION` |
+| Option | Description | Example |
+|------------------|--------------------------|------------------------|
+| `--time, -t` | Departure time window | `6-20` |
+| `--airlines, -a` | Airline IATA codes | `BA KL` |
+| `--class, -c` | Cabin class | `ECONOMY`, `BUSINESS` |
+| `--stops, -s` | Maximum stops | `NON_STOP`, `ONE_STOP` |
+| `--sort, -o` | Sort results by | `CHEAPEST`, `DURATION` |
-#### Cheap Command (`fli cheap`)
+#### Dates Command (`fli dates`)
-| Option | Description | Example |
-|---------------|---------------|------------------------|
-| `--from` | Start date | `2025-01-01` |
-| `--to` | End date | `2025-02-01` |
-| `-s, --seat` | Cabin class | `ECONOMY`, `BUSINESS` |
-| `-x, --stops` | Maximum stops | `NON_STOP`, `ONE_STOP` |
-| `--[day]` | Day filters | `--monday`, `--friday` |
+| Option | Description | Example |
+|---------------|----------------------|------------------------|
+| `--from` | Start date | `2025-01-01` |
+| `--to` | End date | `2025-02-01` |
+| `--class, -c` | Cabin class | `ECONOMY`, `BUSINESS` |
+| `--stops, -s` | Maximum stops | `NON_STOP`, `ONE_STOP` |
+| `--[day]` | Day filters | `--monday`, `--friday` |
## MCP Server Integration
@@ -183,13 +224,6 @@ After adding this configuration:
* "What are the cheapest dates to fly from NYC to London in January?"
* "Search for business class flights from SFO to NRT with no stops"
-### MCP Tools Available
-
-The MCP server provides two main tools:
-
-* **`search_flights`**: Search for specific flights with detailed filters
-* **`search_cheap_flights`**: Find the cheapest dates across a flexible date range
-
## Python API Usage
### Basic Search Example
diff --git a/docs/guides/mcp.md b/docs/guides/mcp.md
index 0dc1445..2da0c78 100644
--- a/docs/guides/mcp.md
+++ b/docs/guides/mcp.md
@@ -1,10 +1,22 @@
-## MCP Server (FastMCP)
+# MCP Server Guide
This project exposes flight search tools via a FastMCP server. You can run it over STDIO (default) or the streamable HTTP transport.
+## Installation
+
+```bash
+# Install with pipx (recommended)
+pipx install flights
+
+# Or with pip
+pip install flights
+```
+
+## Running the Server
+
### Run over STDIO
-Use the existing console script:
+Use the console script for Claude Desktop and other MCP clients:
```bash
fli-mcp
@@ -12,7 +24,7 @@ fli-mcp
### Run over HTTP (streamable)
-Use the new HTTP entrypoint. By default it binds to `127.0.0.1:8000`.
+Use the HTTP entrypoint for web-based integrations. By default it binds to `127.0.0.1:8000`.
```bash
fli-mcp-http
@@ -27,3 +39,169 @@ run_http(host="0.0.0.0", port=8000)
```
Once running, the MCP endpoint is served at `/mcp/`, for example: `http://127.0.0.1:8000/mcp/`.
+
+## Claude Desktop Configuration
+
+Add this configuration to your `claude_desktop_config.json`:
+
+**Location**: `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS)
+
+```json
+{
+ "mcpServers": {
+ "fli": {
+ "command": "fli-mcp"
+ }
+ }
+}
+```
+
+> **Tip**: Run `which fli-mcp` to find the full path if needed.
+
+## Available Tools
+
+### `search_flights`
+
+Search for flights between two airports on a specific date.
+
+**Parameters:**
+
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| `origin` | string | Yes | - | Departure airport IATA code (e.g., 'JFK') |
+| `destination` | string | Yes | - | Arrival airport IATA code (e.g., 'LHR') |
+| `departure_date` | string | Yes | - | Travel date in YYYY-MM-DD format |
+| `return_date` | string | No | null | Return date for round trips |
+| `cabin_class` | string | No | ECONOMY | ECONOMY, PREMIUM_ECONOMY, BUSINESS, or FIRST |
+| `max_stops` | string | No | ANY | ANY, NON_STOP, ONE_STOP, or TWO_PLUS_STOPS |
+| `departure_window` | string | No | null | Time window in 'HH-HH' format (e.g., '6-20') |
+| `airlines` | list | No | null | Filter by airline codes (e.g., ['BA', 'AA']) |
+| `sort_by` | string | No | CHEAPEST | CHEAPEST, DURATION, DEPARTURE_TIME, or ARRIVAL_TIME |
+| `passengers` | int | No | 1 | Number of adult passengers |
+
+**Example Response:**
+
+```json
+{
+ "success": true,
+ "flights": [
+ {
+ "price": 450.00,
+ "currency": "USD",
+ "legs": [
+ {
+ "departure_airport": "JFK",
+ "arrival_airport": "LHR",
+ "departure_time": "2025-03-15T18:00:00",
+ "arrival_time": "2025-03-16T06:30:00",
+ "duration": 450,
+ "airline": "BA",
+ "flight_number": "BA178"
+ }
+ ]
+ }
+ ],
+ "count": 5,
+ "trip_type": "ONE_WAY"
+}
+```
+
+### `search_dates`
+
+Find the cheapest travel dates between two airports within a date range.
+
+**Parameters:**
+
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| `origin` | string | Yes | - | Departure airport IATA code (e.g., 'JFK') |
+| `destination` | string | Yes | - | Arrival airport IATA code (e.g., 'LHR') |
+| `start_date` | string | Yes | - | Start of date range in YYYY-MM-DD format |
+| `end_date` | string | Yes | - | End of date range in YYYY-MM-DD format |
+| `trip_duration` | int | No | 3 | Trip duration in days (for round-trips) |
+| `is_round_trip` | bool | No | false | Search for round-trip flights |
+| `cabin_class` | string | No | ECONOMY | ECONOMY, PREMIUM_ECONOMY, BUSINESS, or FIRST |
+| `max_stops` | string | No | ANY | ANY, NON_STOP, ONE_STOP, or TWO_PLUS_STOPS |
+| `departure_window` | string | No | null | Time window in 'HH-HH' format (e.g., '6-20') |
+| `airlines` | list | No | null | Filter by airline codes (e.g., ['BA', 'AA']) |
+| `sort_by_price` | bool | No | false | Sort results by price (lowest first) |
+| `passengers` | int | No | 1 | Number of adult passengers |
+
+**Example Response:**
+
+```json
+{
+ "success": true,
+ "dates": [
+ {
+ "date": "2025-03-15",
+ "price": 350.00,
+ "currency": "USD",
+ "return_date": null
+ },
+ {
+ "date": "2025-03-18",
+ "price": 375.00,
+ "currency": "USD",
+ "return_date": null
+ }
+ ],
+ "count": 30,
+ "trip_type": "ONE_WAY",
+ "date_range": "2025-03-01 to 2025-03-31"
+}
+```
+
+## Available Prompts
+
+The MCP server also provides prompt templates to help guide searches:
+
+### `search-direct-flight`
+
+Generates a tool call to find direct flights between two airports.
+
+**Arguments:**
+- `origin` - Departure airport IATA code (required)
+- `destination` - Arrival airport IATA code (required)
+- `date` - Departure date in YYYY-MM-DD format (optional)
+- `prefer_non_stop` - Set to true to prefer nonstop flights (optional)
+
+### `find-budget-window`
+
+Suggests the cheapest travel dates for a route within a flexible window.
+
+**Arguments:**
+- `origin` - Departure airport IATA code (required)
+- `destination` - Arrival airport IATA code (required)
+- `start_date` - Start of the travel window (optional)
+- `end_date` - End of the travel window (optional)
+- `duration` - Desired trip length in days (optional)
+
+## Configuration
+
+The MCP server can be configured via environment variables:
+
+| Variable | Description | Default |
+|----------|-------------|---------|
+| `FLI_MCP_DEFAULT_PASSENGERS` | Default number of adult passengers | 1 |
+| `FLI_MCP_DEFAULT_CURRENCY` | Currency code for results | USD |
+| `FLI_MCP_DEFAULT_CABIN_CLASS` | Default cabin class | ECONOMY |
+| `FLI_MCP_DEFAULT_SORT_BY` | Default sorting strategy | CHEAPEST |
+| `FLI_MCP_DEFAULT_DEPARTURE_WINDOW` | Default departure window (HH-HH) | null |
+| `FLI_MCP_MAX_RESULTS` | Maximum results returned | null (no limit) |
+
+## Example Conversations
+
+Once configured with Claude Desktop, you can have natural conversations:
+
+> **User**: "Find me flights from New York to London next month"
+>
+> **Claude**: *Uses `search_flights` with origin=JFK, destination=LHR*
+
+> **User**: "What are the cheapest dates to fly to Tokyo from San Francisco in April?"
+>
+> **Claude**: *Uses `search_dates` with origin=SFO, destination=NRT, start_date and end_date in April*
+
+> **User**: "Search for business class, non-stop flights from LAX to Paris on March 15th"
+>
+> **Claude**: *Uses `search_flights` with cabin_class=BUSINESS, max_stops=NON_STOP*
diff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.md
index 637cc16..f8c61f0 100644
--- a/docs/guides/quickstart.md
+++ b/docs/guides/quickstart.md
@@ -23,31 +23,45 @@ pipx install flights
1. Search for one-way flights:
```bash
-fli search JFK LHR 2024-06-01
+fli flights JFK LHR 2025-06-01
```
2. Search for round trip flights:
```bash
-fli search JFK LHR 2024-06-01 --return 2024-06-15
+fli flights JFK LHR 2025-06-01 --return 2025-06-15
```
3. Search with filters:
```bash
-fli search JFK LHR 2024-06-01 \
- -t 6-20 \ # Time range (6 AM - 8 PM)
- -a BA KL \ # Airlines (British Airways, KLM)
- -c BUSINESS \ # Seat type
- -s 0 # Non-stop flights only
+fli flights JFK LHR 2025-06-01 \
+ --time 6-20 \ # Departure window (6 AM - 8 PM)
+ --airlines BA KL \ # Airlines (British Airways, KLM)
+ --class BUSINESS \ # Cabin class
+ --stops NON_STOP # Non-stop flights only
```
4. Find cheapest dates:
```bash
-fli cheap JFK LHR --from 2024-06-01 --to 2024-06-30
+fli dates JFK LHR --from 2025-06-01 --to 2025-06-30
```
+### MCP Server (for AI Assistants)
+
+Run the MCP server for use with Claude Desktop or other MCP clients:
+
+```bash
+# Run on STDIO (for Claude Desktop)
+fli-mcp
+
+# Run over HTTP (for web integrations)
+fli-mcp-http
+```
+
+See the [MCP Guide](mcp.md) for detailed configuration.
+
### Python API
1. Basic One-Way Flight Search:
@@ -64,7 +78,7 @@ flight_segments = [
FlightSegment(
departure_airport=[[Airport.JFK, 0]],
arrival_airport=[[Airport.LAX, 0]],
- travel_date="2024-06-01"
+ travel_date="2025-06-01"
)
]
@@ -102,12 +116,12 @@ flight_segments = [
FlightSegment(
departure_airport=[[Airport.JFK, 0]],
arrival_airport=[[Airport.LAX, 0]],
- travel_date="2024-06-01"
+ travel_date="2025-06-01"
),
FlightSegment(
departure_airport=[[Airport.LAX, 0]],
arrival_airport=[[Airport.JFK, 0]],
- travel_date="2024-06-15"
+ travel_date="2025-06-15"
)
]
@@ -122,21 +136,19 @@ filters = FlightSearchFilters(
search = SearchFlights()
results = search.search(filters)
-# Process results
-for flight in results:
+# Process results - round trips return tuples of (outbound, return)
+for outbound, return_flight in results:
print(f"\nOutbound Flight:")
- for leg in flight.outbound.legs:
- print(f"Flight: {leg.airline.value} {leg.flight_number}")
- print(f"Departure: {leg.departure_datetime}")
- print(f"Arrival: {leg.arrival_datetime}")
+ for leg in outbound.legs:
+ print(f" {leg.airline.value} {leg.flight_number}")
+ print(f" {leg.departure_datetime} -> {leg.arrival_datetime}")
print(f"\nReturn Flight:")
- for leg in flight.return_flight.legs:
- print(f"Flight: {leg.airline.value} {leg.flight_number}")
- print(f"Departure: {leg.departure_datetime}")
- print(f"Arrival: {leg.arrival_datetime}")
+ for leg in return_flight.legs:
+ print(f" {leg.airline.value} {leg.flight_number}")
+ print(f" {leg.departure_datetime} -> {leg.arrival_datetime}")
- print(f"\nTotal Price: ${flight.total_price}")
+ print(f"\nTotal Price: ${outbound.price + return_flight.price}")
```
3. Date Range Search:
@@ -152,11 +164,11 @@ filters = DateSearchFilters(
FlightSegment(
departure_airport=[[Airport.JFK, 0]],
arrival_airport=[[Airport.LAX, 0]],
- travel_date="2024-06-01",
+ travel_date="2025-06-01",
)
],
- from_date="2024-06-01",
- to_date="2024-06-30"
+ from_date="2025-06-01",
+ to_date="2025-06-30"
)
# Search dates
@@ -165,7 +177,7 @@ results = search.search(filters)
# Process results
for date_price in results:
- print(f"Date: {date_price.date}, Price: ${date_price.price}")
+ print(f"Date: {date_price.date[0]}, Price: ${date_price.price}")
```
### Running Complete Examples
@@ -197,4 +209,5 @@ python examples/basic_one_way_search.py
* Check out the [API Reference](../api/models.md) for detailed documentation
* See [Advanced Examples](../examples/advanced.md) for more complex use cases
+* Read the [MCP Guide](mcp.md) for AI assistant integration
* Read about [Rate Limiting and Error Handling](../api/search.md#http-client)
diff --git a/docs/index.md b/docs/index.md
index 2b5b55b..ba2b717 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -13,6 +13,13 @@ flights and analyze pricing data.
* Less prone to breaking from UI changes
* Clean, modular architecture
+### 🤖 MCP Server Integration
+
+* Model Context Protocol server for AI assistants
+* Natural language flight search with Claude
+* Two powerful tools: `search_flights` and `search_dates`
+* Easy configuration with environment variables
+
### 🔍 Search Capabilities
* One-way and round-trip flight searches
@@ -41,6 +48,18 @@ pip install flights
pipx install flights
```
+### MCP Server (for AI Assistants)
+
+```bash
+# Run the MCP server
+fli-mcp
+
+# Or run over HTTP
+fli-mcp-http
+```
+
+See the [MCP Guide](guides/mcp.md) for Claude Desktop configuration.
+
### Basic Usage
```python
@@ -104,6 +123,10 @@ python examples/basic_one_way_search.py
The library is organized into several key modules:
+* `core/`: Shared utilities
+ * `parsers.py`: Parameter parsing (airports, airlines, stops, etc.)
+ * `builders.py`: Filter building utilities
+
* `models/`: Data models and enums
* `google_flights`: Core data models specific to Google Flights
* `airline.py`: Airline enums and data
@@ -114,6 +137,13 @@ The library is organized into several key modules:
* `dates.py`: Date-based price search
* `client.py`: HTTP client with rate limiting
+* `mcp/`: MCP server
+ * `server.py`: FastMCP server with `search_flights` and `search_dates` tools
+
+* `cli/`: Command-line interface
+ * `commands/`: CLI commands (`flights`, `dates`)
+ * `utils.py`: Display and validation utilities
+
## Contributing
We welcome contributions! Here's how you can help:
@@ -121,7 +151,7 @@ We welcome contributions! Here's how you can help:
1. Fork the repository
2. Create a feature branch
3. Make your changes
-4. Run tests: `poetry run pytest`
+4. Run tests: `uv run pytest`
5. Submit a pull request
## License
diff --git a/fli/cli/commands/__init__.py b/fli/cli/commands/__init__.py
index ffb3b0c..0eeb2cc 100644
--- a/fli/cli/commands/__init__.py
+++ b/fli/cli/commands/__init__.py
@@ -1,6 +1,6 @@
"""Command functions for the CLI."""
-from fli.cli.commands.cheap import cheap
-from fli.cli.commands.search import search
+from fli.cli.commands.dates import dates
+from fli.cli.commands.flights import flights
-__all__ = ["search", "cheap"]
+__all__ = ["flights", "dates"]
diff --git a/fli/cli/commands/cheap.py b/fli/cli/commands/dates.py
similarity index 61%
rename from fli/cli/commands/cheap.py
rename to fli/cli/commands/dates.py
index fbd2b95..fbccc76 100644
--- a/fli/cli/commands/cheap.py
+++ b/fli/cli/commands/dates.py
@@ -1,3 +1,5 @@
+"""Date search CLI command for finding cheapest travel dates."""
+
from datetime import datetime, timedelta
from typing import Annotated
@@ -7,38 +9,42 @@ from fli.cli.enums import DayOfWeek
from fli.cli.utils import (
display_date_results,
filter_dates_by_days,
- parse_airlines,
- parse_stops,
validate_date,
validate_time_range,
)
+from fli.core import (
+ build_date_search_segments,
+ parse_airlines,
+ parse_cabin_class,
+ parse_max_stops,
+ resolve_airport,
+)
+from fli.core.parsers import ParseError
from fli.models import (
- Airport,
DateSearchFilters,
- FlightSegment,
PassengerInfo,
- SeatType,
TimeRestrictions,
TripType,
)
from fli.search import SearchDates
-def cheap(
- from_airport: Annotated[str, typer.Argument(help="Departure airport code (e.g., JFK)")],
- to_airport: Annotated[str, typer.Argument(help="Arrival airport code (e.g., LHR)")],
- from_date: Annotated[
- str, typer.Option("--from", help="Start date (YYYY-MM-DD)", callback=validate_date)
+def dates(
+ origin: Annotated[str, typer.Argument(help="Departure airport IATA code (e.g., JFK)")],
+ destination: Annotated[str, typer.Argument(help="Arrival airport IATA code (e.g., LHR)")],
+ start_date: Annotated[
+ str,
+ typer.Option("--from", help="Start date (YYYY-MM-DD)", callback=validate_date),
] = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d"),
- to_date: Annotated[
+ end_date: Annotated[
str, typer.Option("--to", help="End date (YYYY-MM-DD)", callback=validate_date)
] = (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d"),
- duration: Annotated[
+ trip_duration: Annotated[
int,
typer.Option(
"--duration",
"-d",
- help="Duration of trip in days",
+ help="Trip duration in days",
),
] = 3,
airlines: Annotated[
@@ -46,10 +52,10 @@ def cheap(
typer.Option(
"--airlines",
"-a",
- help="List of airline codes (e.g., BA KL)",
+ help="List of airline IATA codes (e.g., BA KL)",
),
] = None,
- round_trip: Annotated[
+ is_round_trip: Annotated[
bool,
typer.Option(
"--round",
@@ -57,23 +63,23 @@ def cheap(
help="Search for round-trip flights",
),
] = False,
- stops: Annotated[
+ max_stops: Annotated[
str,
typer.Option(
"--stops",
"-s",
- help="Maximum number of stops (ANY, 0 for non-stop, 1 for one stop, 2+ for two stops)",
+ help="Maximum stops (ANY, 0 for non-stop, 1 for one stop, 2+ for two stops)",
),
] = "ANY",
- seat: Annotated[
+ cabin_class: Annotated[
str,
typer.Option(
"--class",
"-c",
- help="Seat type (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
+ help="Cabin class (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
),
] = "ECONOMY",
- sort: Annotated[
+ sort_by_price: Annotated[
bool,
typer.Option(
"--sort",
@@ -136,12 +142,12 @@ def cheap(
help="Include Sundays in results",
),
] = False,
- time: Annotated[
+ departure_window: Annotated[
str | None,
typer.Option(
"--time",
"-time",
- help="Time range in 24h format (e.g., 6-20)",
+ help="Departure time window in 24h format (e.g., 6-20)",
callback=validate_time_range,
),
] = None,
@@ -149,25 +155,25 @@ def cheap(
"""Find the cheapest dates to fly between two airports.
Example:
- fli cheap LAX MIA --seat BUSINESS --stops NON_STOP --friday
+ fli dates LAX MIA --class BUSINESS --stops NON_STOP --friday
"""
try:
- # Parse parameters
- departure_airport = getattr(Airport, from_airport.upper())
- arrival_airport = getattr(Airport, to_airport.upper())
- trip_type = TripType.ROUND_TRIP if round_trip else TripType.ONE_WAY
- max_stops = parse_stops(stops)
- seat_type = getattr(SeatType, seat.upper())
- airlines = parse_airlines(airlines)
-
- # Parse time restrictions
+ # Parse parameters using shared utilities
+ origin_airport = resolve_airport(origin)
+ destination_airport = resolve_airport(destination)
+ trip_type = TripType.ROUND_TRIP if is_round_trip else TripType.ONE_WAY
+ stops = parse_max_stops(max_stops)
+ seat_type = parse_cabin_class(cabin_class)
+ parsed_airlines = parse_airlines(airlines)
+
+ # Build time restrictions from tuple
time_restrictions = None
- if time:
- if isinstance(time, tuple):
- start_hour, end_hour = time
+ if departure_window:
+ if isinstance(departure_window, tuple):
+ start_hour, end_hour = departure_window
else:
- start_hour, end_hour = map(int, time.split("-"))
+ start_hour, end_hour = map(int, departure_window.split("-"))
time_restrictions = TimeRestrictions(
earliest_departure=start_hour,
latest_departure=end_hour,
@@ -175,48 +181,34 @@ def cheap(
latest_arrival=None,
)
- # Create flight segment
- flight_segment = FlightSegment(
- departure_airport=[[departure_airport, 0]],
- arrival_airport=[[arrival_airport, 0]],
- travel_date=from_date,
+ # Build flight segments using shared builder
+ segments, trip_type = build_date_search_segments(
+ origin=origin_airport,
+ destination=destination_airport,
+ start_date=start_date,
+ trip_duration=trip_duration,
+ is_round_trip=is_round_trip,
time_restrictions=time_restrictions,
)
- # Handle round trip
- if trip_type == TripType.ROUND_TRIP:
- return_flight_segment = FlightSegment(
- departure_airport=[[arrival_airport, 0]],
- arrival_airport=[[departure_airport, 0]],
- travel_date=(
- datetime.strptime(flight_segment.travel_date, "%Y-%m-%d")
- + timedelta(days=duration)
- ).strftime("%Y-%m-%d"),
- time_restrictions=time_restrictions,
- )
-
- flight_segments = [flight_segment, return_flight_segment]
- else:
- flight_segments = [flight_segment]
-
# Create search filters
filters = DateSearchFilters(
trip_type=trip_type,
passenger_info=PassengerInfo(adults=1),
- flight_segments=flight_segments,
- stops=max_stops,
+ flight_segments=segments,
+ stops=stops,
seat_type=seat_type,
- airlines=airlines,
- from_date=from_date,
- to_date=to_date,
- duration=duration if trip_type == TripType.ROUND_TRIP else None,
+ airlines=parsed_airlines,
+ from_date=start_date,
+ to_date=end_date,
+ duration=trip_duration if trip_type == TripType.ROUND_TRIP else None,
)
# Perform search
search_client = SearchDates()
- dates = search_client.search(filters)
+ results = search_client.search(filters)
- if not dates:
+ if not results:
typer.echo("No flights found for these dates.")
raise typer.Exit(1)
@@ -238,19 +230,22 @@ def cheap(
selected_days.append(DayOfWeek.SUNDAY)
if selected_days:
- dates = filter_dates_by_days(dates, selected_days, trip_type)
+ results = filter_dates_by_days(results, selected_days, trip_type)
- if not dates:
+ if not results:
typer.echo("No flights found for the selected days.")
raise typer.Exit(1)
# Sort dates by price if sort flag is enabled
- if sort:
- dates.sort(key=lambda x: x.price)
+ if sort_by_price:
+ results.sort(key=lambda x: x.price)
# Display results
- display_date_results(dates, trip_type)
+ display_date_results(results, trip_type)
+ except ParseError as e:
+ typer.echo(f"Error: {str(e)}")
+ raise typer.Exit(1) from e
except (AttributeError, ValueError) as e:
if "module 'fli.search' has no attribute 'SearchDates'" in str(e):
raise
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
new file mode 100644
index 0000000..b8c99e3
--- /dev/null
+++ b/fli/cli/commands/flights.py
@@ -0,0 +1,167 @@
+"""Flight search CLI command."""
+
+from typing import Annotated
+
+import typer
+
+from fli.cli.utils import display_flight_results, validate_date, validate_time_range
+from fli.core import (
+ build_flight_segments,
+ parse_airlines,
+ parse_cabin_class,
+ parse_max_stops,
+ parse_sort_by,
+ resolve_airport,
+)
+from fli.core.parsers import ParseError
+from fli.models import (
+ FlightSearchFilters,
+ PassengerInfo,
+)
+from fli.search import SearchFlights
+
+
+def _search_flights_core(
+ origin: str,
+ destination: str,
+ departure_date: str,
+ return_date: str | None = None,
+ departure_window: tuple[int, int] | None = None,
+ airlines: list[str] | None = None,
+ cabin_class: str = "ECONOMY",
+ max_stops: str = "ANY",
+ sort_by: str = "CHEAPEST",
+):
+ """Core flight search functionality."""
+ try:
+ # Parse parameters using shared utilities
+ origin_airport = resolve_airport(origin)
+ destination_airport = resolve_airport(destination)
+ seat_type = parse_cabin_class(cabin_class)
+ stops = parse_max_stops(max_stops)
+ parsed_airlines = parse_airlines(airlines)
+ sort = parse_sort_by(sort_by)
+
+ # Build time restrictions from tuple
+ time_restrictions = None
+ if departure_window:
+ from fli.models import TimeRestrictions
+
+ time_restrictions = TimeRestrictions(
+ earliest_departure=departure_window[0],
+ latest_departure=departure_window[1],
+ )
+
+ # Create flight segments using shared builder
+ segments, trip_type = build_flight_segments(
+ origin=origin_airport,
+ destination=destination_airport,
+ departure_date=departure_date,
+ return_date=return_date,
+ time_restrictions=time_restrictions,
+ )
+
+ # Create search filters
+ filters = FlightSearchFilters(
+ trip_type=trip_type,
+ passenger_info=PassengerInfo(adults=1),
+ flight_segments=segments,
+ stops=stops,
+ seat_type=seat_type,
+ airlines=parsed_airlines,
+ sort_by=sort,
+ )
+
+ # Perform search
+ search_client = SearchFlights()
+ results = search_client.search(filters)
+
+ if not results:
+ typer.echo("No flights found.")
+ raise typer.Exit(1)
+
+ # Display results
+ display_flight_results(results)
+
+ except ParseError as e:
+ typer.echo(f"Error: {str(e)}")
+ raise typer.Exit(1) from e
+ except (AttributeError, ValueError) as e:
+ typer.echo(f"Error: {str(e)}")
+ raise typer.Exit(1) from e
+
+
+def flights(
+ origin: Annotated[str, typer.Argument(help="Departure airport IATA code (e.g., JFK)")],
+ destination: Annotated[str, typer.Argument(help="Arrival airport IATA code (e.g., LHR)")],
+ departure_date: Annotated[
+ str, typer.Argument(help="Travel date (YYYY-MM-DD)", callback=validate_date)
+ ],
+ return_date: Annotated[
+ str | None,
+ typer.Option(
+ "--return",
+ "-r",
+ help="Return date (YYYY-MM-DD)",
+ callback=validate_date,
+ ),
+ ] = None,
+ departure_window: Annotated[
+ str | None,
+ typer.Option(
+ "--time",
+ "-t",
+ help="Departure time window in 24h format (e.g., 6-20)",
+ callback=validate_time_range,
+ ),
+ ] = None,
+ airlines: Annotated[
+ list[str] | None,
+ typer.Option(
+ "--airlines",
+ "-a",
+ help="List of airline IATA codes (e.g., BA KL)",
+ ),
+ ] = None,
+ cabin_class: Annotated[
+ str,
+ typer.Option(
+ "--class",
+ "-c",
+ help="Cabin class (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
+ ),
+ ] = "ECONOMY",
+ max_stops: Annotated[
+ str,
+ typer.Option(
+ "--stops",
+ "-s",
+ help="Maximum stops (ANY, 0 for non-stop, 1 for one stop, 2+ for two stops)",
+ ),
+ ] = "ANY",
+ sort_by: Annotated[
+ str,
+ typer.Option(
+ "--sort",
+ "-o",
+ help="Sort results by (CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME)",
+ ),
+ ] = "CHEAPEST",
+):
+ """Search for flights on a specific date.
+
+ Example:
+ fli flights JFK LHR 2025-10-25 --time 6-20 --airlines BA KL --stops NON_STOP
+
+ """
+ _search_flights_core(
+ origin=origin,
+ destination=destination,
+ departure_date=departure_date,
+ return_date=return_date,
+ departure_window=departure_window,
+ airlines=airlines,
+ cabin_class=cabin_class,
+ max_stops=max_stops,
+ sort_by=sort_by,
+ )
diff --git a/fli/cli/commands/search.py b/fli/cli/commands/search.py
deleted file mode 100644
index 182a915..0000000
--- a/fli/cli/commands/search.py
+++ /dev/null
@@ -1,171 +0,0 @@
-from typing import Annotated
-
-import typer
-
-from fli.cli.utils import (
- display_flight_results,
- parse_airlines,
- parse_stops,
- validate_date,
- validate_time_range,
-)
-from fli.models import (
- Airport,
- FlightSearchFilters,
- FlightSegment,
- PassengerInfo,
- SeatType,
- SortBy,
-)
-from fli.models.google_flights.base import TimeRestrictions, TripType
-from fli.search import SearchFlights
-
-
-def search_flights(
- trip_type: TripType,
- from_airport: str,
- to_airport: str,
- date: str,
- return_date: str | None = None,
- time: tuple[int, int] | None = None,
- airlines: list[str] | None = None,
- seat: str = "ECONOMY",
- stops: str = "ANY",
- sort: str = "CHEAPEST",
-):
- """Core flight search functionality."""
- try:
- # Parse parameters
- departure_airport = getattr(Airport, from_airport.upper())
- arrival_airport = getattr(Airport, to_airport.upper())
- seat_type = getattr(SeatType, seat.upper())
- max_stops = parse_stops(stops)
- airlines = parse_airlines(airlines)
- sort_by = getattr(SortBy, sort.upper())
-
- time_restrictions = None
- if time:
- start_hour, end_hour = time
- time_restrictions = TimeRestrictions(
- earliest_departure=start_hour, latest_departure=end_hour
- )
-
- # Create flight segments
- flight_segments = [
- FlightSegment(
- departure_airport=[[departure_airport, 0]],
- arrival_airport=[[arrival_airport, 0]],
- travel_date=date,
- time_restrictions=time_restrictions,
- )
- ]
- if return_date:
- flight_segments.append(
- FlightSegment(
- departure_airport=[[arrival_airport, 0]],
- arrival_airport=[[departure_airport, 0]],
- travel_date=return_date,
- time_restrictions=time_restrictions,
- )
- )
-
- # Create search filters
- filters = FlightSearchFilters(
- trip_type=trip_type,
- passenger_info=PassengerInfo(adults=1),
- flight_segments=flight_segments,
- stops=max_stops,
- seat_type=seat_type,
- airlines=airlines,
- sort_by=sort_by,
- )
-
- # Perform search
- search_client = SearchFlights()
- flights = search_client.search(filters)
-
- if not flights:
- typer.echo("No flights found.")
- raise typer.Exit(1)
-
- # Display results
- display_flight_results(flights)
-
- except (AttributeError, ValueError) as e:
- typer.echo(f"Error: {str(e)}")
- raise typer.Exit(1) from e
-
-
-def search(
- from_airport: Annotated[str, typer.Argument(help="Departure airport code (e.g., JFK)")],
- to_airport: Annotated[str, typer.Argument(help="Arrival airport code (e.g., LHR)")],
- date: Annotated[str, typer.Argument(help="Travel date (YYYY-MM-DD)", callback=validate_date)],
- return_date: Annotated[
- str | None,
- typer.Option(
- "--return",
- "-r",
- help="Return date (YYYY-MM-DD)",
- callback=validate_date,
- ),
- ] = None,
- time: Annotated[
- str | None,
- typer.Option(
- "--time",
- "-t",
- help="Time range in 24h format (e.g., 6-20)",
- callback=validate_time_range,
- ),
- ] = None,
- airlines: Annotated[
- list[str] | None,
- typer.Option(
- "--airlines",
- "-a",
- help="List of airline codes (e.g., BA KL)",
- ),
- ] = None,
- seat: Annotated[
- str,
- typer.Option(
- "--class",
- "-c",
- help="Seat type (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
- ),
- ] = "ECONOMY",
- stops: Annotated[
- str,
- typer.Option(
- "--stops",
- "-s",
- help="Maximum number of stops (ANY, 0 for non-stop, 1 for one stop, 2+ for two stops)",
- ),
- ] = "ANY",
- sort: Annotated[
- str,
- typer.Option(
- "--sort",
- "-o",
- help="Sort results by (CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME)",
- ),
- ] = "CHEAPEST",
-):
- """Search for flights with flexible filtering options.
-
- Example:
- fli search JFK LHR 2025-10-25 --time 6-20 --airlines BA KL --stops NON_STOP
-
- """
- search_flights(
- trip_type=TripType.ROUND_TRIP if return_date else TripType.ONE_WAY,
- from_airport=from_airport,
- to_airport=to_airport,
- date=date,
- return_date=return_date,
- time=time,
- airlines=airlines,
- seat=seat,
- stops=stops,
- sort=sort,
- )
diff --git a/fli/cli/main.py b/fli/cli/main.py
index 369fc8d..9625b66 100644
--- a/fli/cli/main.py
+++ b/fli/cli/main.py
@@ -1,11 +1,12 @@
#!/usr/bin/env python3
+"""CLI entry point for the fli flight search tool."""
import sys
import typer
-from fli.cli.commands.cheap import cheap
-from fli.cli.commands.search import search
+from fli.cli.commands.dates import dates
+from fli.cli.commands.flights import flights
app = typer.Typer(
help="Search for flights using Google Flights data",
@@ -13,17 +14,16 @@ app = typer.Typer(
)
# Register commands
-app.command(name="cheap")(cheap)
-app.command(name="search")(search)
+app.command(name="flights")(flights)
+app.command(name="dates")(dates)
@app.callback(invoke_without_command=True)
def main(ctx: typer.Context):
"""Search for flights using Google Flights data.
- If no command is provided, the search command will be used.
+ If no command is provided, show help.
"""
- # If no command is provided, show help
if ctx.invoked_subcommand is None:
ctx.get_help()
raise typer.Exit()
@@ -36,9 +36,9 @@ def cli():
sys.argv.append("--help")
args.append("--help")
- # If the first argument isn't a command, treat as search
- if args[0] not in ["cheap", "search", "--help", "-h"]:
- sys.argv.insert(1, "search")
+ # If the first argument isn't a command, treat as flights search
+ if args[0] not in ["flights", "dates", "--help", "-h"]:
+ sys.argv.insert(1, "flights")
app()
diff --git a/fli/cli/utils.py b/fli/cli/utils.py
index c7ffdfa..6eb79ad 100644
--- a/fli/cli/utils.py
+++ b/fli/cli/utils.py
@@ -1,5 +1,8 @@
+"""CLI utility functions for display and validation."""
+
from datetime import datetime
+import plotext as plt
import typer
from click import Context, Parameter
from rich import box
@@ -10,11 +13,14 @@ from rich.text import Text
from fli.cli.console import console
from fli.cli.enums import DayOfWeek
+from fli.core.parsers import ParseError
+from fli.core.parsers import parse_airlines as core_parse_airlines
+from fli.core.parsers import parse_max_stops as core_parse_max_stops
from fli.models import Airline, Airport, MaxStops, TripType
def validate_date(ctx: Context, param: Parameter, value: str) -> str | None:
- """Validate date format."""
+ """Validate date format for typer callbacks."""
if value is None:
return None
@@ -28,7 +34,7 @@ def validate_date(ctx: Context, param: Parameter, value: str) -> str | None:
def validate_time_range(
ctx: Context, param: Parameter, value: str | None
) -> tuple[int, int] | None:
- """Validate and parse time range in format 'start-end' (24h format)."""
+ """Validate and parse time range in format 'start-end' (24h format) for typer callbacks."""
if not value:
return None
@@ -42,37 +48,28 @@ def validate_time_range(
def parse_airlines(airlines: list[str] | None) -> list[Airline] | None:
- """Parse airlines from list of airline codes."""
+ """Parse airlines from list of airline codes.
+
+ Delegates to core parser but wraps errors for CLI.
+ """
if not airlines:
return None
try:
- return [
- getattr(Airline, airline.strip().upper()) for airline in airlines if airline.strip()
- ]
- except AttributeError as e:
- raise typer.BadParameter(f"Invalid airline code: {str(e)}") from e
+ return core_parse_airlines(airlines)
+ except ParseError as e:
+ raise typer.BadParameter(str(e)) from e
def parse_stops(stops: str) -> MaxStops:
- """Convert stops parameter to MaxStops enum."""
- # Try parsing as integer first
+ """Convert stops parameter to MaxStops enum.
+
+ Delegates to core parser but wraps errors for CLI.
+ """
try:
- stops_int = int(stops)
- if stops_int == 0:
- return MaxStops.NON_STOP
- elif stops_int == 1:
- return MaxStops.ONE_STOP_OR_FEWER
- elif stops_int >= 2:
- return MaxStops.TWO_OR_FEWER_STOPS
- else:
- return MaxStops.ANY
- except ValueError:
- # If not an integer, try as enum string
- try:
- return getattr(MaxStops, stops.upper())
- except AttributeError as e:
- raise typer.BadParameter(f"Invalid stops value: {stops}") from e
+ return core_parse_max_stops(stops)
+ except ParseError as e:
+ raise typer.BadParameter(str(e)) from e
def parse_trip_type(trip_type: str) -> TripType:
@@ -173,7 +170,7 @@ def display_flight_results(flights: list):
for idx, flight in enumerate(flight_segments):
direction = "Outbound" if idx == 0 else "Return" if is_round_trip else ""
segments = Table(
- title=f"{direction} Flight Segments" if direction else "Flight Segments",
+ title=(f"{direction} Flight Segments" if direction else "Flight Segments"),
box=box.ROUNDED,
)
segments.add_column("Airline", style="cyan")
@@ -214,11 +211,41 @@ def display_flight_results(flights: list):
def display_date_results(dates: list, trip_type: TripType):
- """Display date search results in a beautiful format."""
+ """Display date search results with sparkline chart and table."""
if not dates:
console.print(Panel("No flights found for these dates", style="red"))
return
+ # Sort dates chronologically for proper trend visualization
+ sorted_dates = sorted(dates, key=lambda x: x.date[0])
+
+ # Extract data for chart
+ date_labels = [d.date[0].strftime("%m/%d") for d in sorted_dates]
+ prices = [d.price for d in sorted_dates]
+
+ # Render sparkline chart
+ plt.clear_figure()
+ plt.plot(prices, marker="braille")
+ plt.title("Price Trend")
+ plt.xlabel("Date")
+ plt.ylabel("Price ($)")
+
+ # Set x-axis labels (show subset if too many dates)
+ if len(date_labels) <= 10:
+ plt.xticks(range(len(date_labels)), date_labels)
+ else:
+ # Show every nth label to avoid crowding
+ step = len(date_labels) // 8
+ indices = list(range(0, len(date_labels), step))
+ plt.xticks(indices, [date_labels[i] for i in indices])
+
+ plt.theme("pro")
+ plt.plotsize(80, 12)
+ plt.show()
+
+ console.print() # Add spacing between chart and table
+
+ # Build the table (using original order, not sorted)
table = Table(title="Cheapest Dates to Fly", box=box.ROUNDED)
table.add_column("Departure", style="cyan")
table.add_column("Day", style="yellow")
diff --git a/fli/core/__init__.py b/fli/core/__init__.py
new file mode 100644
index 0000000..a55709f
--- /dev/null
+++ b/fli/core/__init__.py
@@ -0,0 +1,31 @@
+"""Core utilities for flight search operations.
+
+This module provides shared parsing and building utilities used by both
+the CLI and MCP interfaces.
+"""
+
+from .builders import build_date_search_segments, build_flight_segments, build_time_restrictions
+from .parsers import (
+ parse_airlines,
+ parse_cabin_class,
+ parse_max_stops,
+ parse_sort_by,
+ parse_time_range,
+ resolve_airport,
+ resolve_enum,
+)
+
+__all__ = [
+ # Parsers
+ "parse_airlines",
+ "parse_cabin_class",
+ "parse_max_stops",
+ "parse_sort_by",
+ "parse_time_range",
+ "resolve_airport",
+ "resolve_enum",
+ # Builders
+ "build_date_search_segments",
+ "build_flight_segments",
+ "build_time_restrictions",
+]
diff --git a/fli/core/builders.py b/fli/core/builders.py
new file mode 100644
index 0000000..53529b5
--- /dev/null
+++ b/fli/core/builders.py
@@ -0,0 +1,145 @@
+"""Shared building utilities for constructing search filters.
+
+This module provides builder functions used by both the CLI and MCP interfaces
+to construct flight search filter objects.
+"""
+
+from datetime import datetime, timedelta
+
+from fli.models import Airport, FlightSegment, TimeRestrictions, TripType
+
+
+def build_time_restrictions(
+ departure_window: str | None = None,
+ arrival_window: str | None = None,
+) -> TimeRestrictions | None:
+ """Build a TimeRestrictions object from time window strings.
+
+ Args:
+ departure_window: Departure time range in 'HH-HH' format (e.g., '6-20')
+ arrival_window: Arrival time range in 'HH-HH' format (e.g., '8-22')
+
+ Returns:
+ TimeRestrictions object, or None if no restrictions specified
+
+ """
+ if not departure_window and not arrival_window:
+ return None
+
+ earliest_departure = None
+ latest_departure = None
+ earliest_arrival = None
+ latest_arrival = None
+
+ if departure_window:
+ from fli.core.parsers import parse_time_range
+
+ earliest_departure, latest_departure = parse_time_range(departure_window)
+
+ if arrival_window:
+ from fli.core.parsers import parse_time_range
+
+ earliest_arrival, latest_arrival = parse_time_range(arrival_window)
+
+ return TimeRestrictions(
+ earliest_departure=earliest_departure,
+ latest_departure=latest_departure,
+ earliest_arrival=earliest_arrival,
+ latest_arrival=latest_arrival,
+ )
+
+
+def build_flight_segments(
+ origin: Airport,
+ destination: Airport,
+ departure_date: str,
+ return_date: str | None = None,
+ time_restrictions: TimeRestrictions | None = None,
+) -> tuple[list[FlightSegment], TripType]:
+ """Build flight segments for a search request.
+
+ Args:
+ origin: Departure airport
+ destination: Arrival airport
+ departure_date: Outbound travel date in YYYY-MM-DD format
+ return_date: Return travel date in YYYY-MM-DD format (optional)
+ time_restrictions: Time restrictions to apply to segments
+
+ Returns:
+ Tuple of (list of FlightSegment objects, TripType)
+
+ """
+ segments = [
+ FlightSegment(
+ departure_airport=[[origin, 0]],
+ arrival_airport=[[destination, 0]],
+ travel_date=departure_date,
+ time_restrictions=time_restrictions,
+ )
+ ]
+
+ trip_type = TripType.ONE_WAY
+
+ if return_date:
+ trip_type = TripType.ROUND_TRIP
+ segments.append(
+ FlightSegment(
+ departure_airport=[[destination, 0]],
+ arrival_airport=[[origin, 0]],
+ travel_date=return_date,
+ time_restrictions=time_restrictions,
+ )
+ )
+
+ return segments, trip_type
+
+
+def build_date_search_segments(
+ origin: Airport,
+ destination: Airport,
+ start_date: str,
+ trip_duration: int | None = None,
+ is_round_trip: bool = False,
+ time_restrictions: TimeRestrictions | None = None,
+) -> tuple[list[FlightSegment], TripType]:
+ """Build flight segments for a date range search.
+
+ Args:
+ origin: Departure airport
+ destination: Arrival airport
+ start_date: Start date of the search range in YYYY-MM-DD format
+ trip_duration: Duration of the trip in days (for round trips)
+ is_round_trip: Whether to search for round-trip flights
+ time_restrictions: Time restrictions to apply to segments
+
+ Returns:
+ Tuple of (list of FlightSegment objects, TripType)
+
+ """
+ segments = [
+ FlightSegment(
+ departure_airport=[[origin, 0]],
+ arrival_airport=[[destination, 0]],
+ travel_date=start_date,
+ time_restrictions=time_restrictions,
+ )
+ ]
+
+ trip_type = TripType.ONE_WAY
+
+ if is_round_trip:
+ trip_type = TripType.ROUND_TRIP
+ return_date = (
+ datetime.strptime(start_date, "%Y-%m-%d") + timedelta(days=trip_duration or 3)
+ ).strftime("%Y-%m-%d")
+
+ segments.append(
+ FlightSegment(
+ departure_airport=[[destination, 0]],
+ arrival_airport=[[origin, 0]],
+ travel_date=return_date,
+ time_restrictions=time_restrictions,
+ )
+ )
+
+ return segments, trip_type
diff --git a/fli/core/parsers.py b/fli/core/parsers.py
new file mode 100644
index 0000000..5a4efeb
--- /dev/null
+++ b/fli/core/parsers.py
@@ -0,0 +1,217 @@
+"""Shared parsing utilities for flight search parameters.
+
+This module provides parsing functions used by both the CLI and MCP interfaces
+to convert user input into domain model objects.
+"""
+
+from enum import Enum
+from typing import TypeVar
+
+from fli.models import Airline, Airport, MaxStops, SeatType, SortBy
+
+T = TypeVar("T", bound=Enum)
+
+
+class ParseError(ValueError):
+ """Error raised when parsing fails."""
+
+ pass
+
+
+def resolve_enum(enum_cls: type[T], name: str) -> T:
+ """Resolve an enum member by name with normalized errors.
+
+ Args:
+ enum_cls: The enum class to resolve from
+ name: The name of the enum member (case-insensitive)
+
+ Returns:
+ The resolved enum member
+
+ Raises:
+ ParseError: If the name is not a valid enum member
+
+ """
+ try:
+ return getattr(enum_cls, name.upper())
+ except AttributeError as e:
+ valid_values = [m.name for m in enum_cls]
+ raise ParseError(
+ f"Invalid {enum_cls.__name__} value: '{name}'. Valid values: {', '.join(valid_values)}"
+ ) from e
+
+
+def resolve_airport(code: str) -> Airport:
+ """Resolve an airport code to an Airport enum.
+
+ Args:
+ code: IATA airport code (e.g., 'JFK', 'LHR')
+
+ Returns:
+ The corresponding Airport enum member
+
+ Raises:
+ ParseError: If the code is not a valid airport
+
+ """
+ try:
+ return getattr(Airport, code.upper())
+ except AttributeError as e:
+ raise ParseError(f"Invalid airport code: '{code}'") from e
+
+
+def parse_airlines(codes: list[str] | None) -> list[Airline] | None:
+ """Parse a list of airline codes into Airline enums.
+
+ Args:
+ codes: List of IATA airline codes (e.g., ['BA', 'KL'])
+
+ Returns:
+ List of Airline enums, or None if input is empty
+
+ Raises:
+ ParseError: If any code is not a valid airline
+
+ """
+ if not codes:
+ return None
+
+ airlines = []
+ for code in codes:
+ code = code.strip().upper()
+ if not code:
+ continue
+ try:
+ airline = getattr(Airline, code)
+ airlines.append(airline)
+ except AttributeError as e:
+ raise ParseError(f"Invalid airline code: '{code}'") from e
+
+ return airlines if airlines else None
+
+
+def parse_max_stops(stops: str) -> MaxStops:
+ """Parse a stops parameter into a MaxStops enum.
+
+ Accepts both string names (ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS)
+ and integer values (0, 1, 2+).
+
+ Args:
+ stops: Stops value as string or integer representation
+
+ Returns:
+ The corresponding MaxStops enum member
+
+ Raises:
+ ParseError: If the value is not valid
+
+ """
+ # Mapping for user-friendly names
+ stops_map = {
+ "ANY": MaxStops.ANY,
+ "NON_STOP": MaxStops.NON_STOP,
+ "NONSTOP": MaxStops.NON_STOP,
+ "ONE_STOP": MaxStops.ONE_STOP_OR_FEWER,
+ "ONE_STOP_OR_FEWER": MaxStops.ONE_STOP_OR_FEWER,
+ "TWO_PLUS_STOPS": MaxStops.TWO_OR_FEWER_STOPS,
+ "TWO_OR_FEWER_STOPS": MaxStops.TWO_OR_FEWER_STOPS,
+ }
+
+ # Try as integer first
+ try:
+ stops_int = int(stops)
+ if stops_int == 0:
+ return MaxStops.NON_STOP
+ elif stops_int == 1:
+ return MaxStops.ONE_STOP_OR_FEWER
+ elif stops_int >= 2:
+ return MaxStops.TWO_OR_FEWER_STOPS
+ else:
+ return MaxStops.ANY
+ except ValueError:
+ pass
+
+ # Try as string name
+ upper_stops = stops.upper()
+ if upper_stops in stops_map:
+ return stops_map[upper_stops]
+
+ raise ParseError(
+ f"Invalid max_stops value: '{stops}'. "
+ f"Valid values: ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS, or 0/1/2"
+ )
+
+
+def parse_cabin_class(cabin_class: str) -> SeatType:
+ """Parse a cabin class string into a SeatType enum.
+
+ Args:
+ cabin_class: Cabin class name (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)
+
+ Returns:
+ The corresponding SeatType enum member
+
+ Raises:
+ ParseError: If the value is not valid
+
+ """
+ try:
+ return getattr(SeatType, cabin_class.upper())
+ except AttributeError as e:
+ valid_values = [m.name for m in SeatType]
+ raise ParseError(
+ f"Invalid cabin_class value: '{cabin_class}'. Valid values: {', '.join(valid_values)}"
+ ) from e
+
+
+def parse_sort_by(sort_by: str) -> SortBy:
+ """Parse a sort_by string into a SortBy enum.
+
+ Args:
+ sort_by: Sort option (CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME)
+
+ Returns:
+ The corresponding SortBy enum member
+
+ Raises:
+ ParseError: If the value is not valid
+
+ """
+ try:
+ return getattr(SortBy, sort_by.upper())
+ except AttributeError as e:
+ valid_values = [m.name for m in SortBy]
+ raise ParseError(
+ f"Invalid sort_by value: '{sort_by}'. Valid values: {', '.join(valid_values)}"
+ ) from e
+
+
+def parse_time_range(time_range: str) -> tuple[int, int]:
+ """Parse a time range string into start and end hours.
+
+ Args:
+ time_range: Time range in 'HH-HH' format (e.g., '6-20')
+
+ Returns:
+ Tuple of (start_hour, end_hour)
+
+ Raises:
+ ParseError: If the format is invalid
+
+ """
+ try:
+ parts = time_range.split("-")
+ if len(parts) != 2:
+ raise ValueError("Invalid format")
+
+ start_hour = int(parts[0].strip())
+ end_hour = int(parts[1].strip())
+
+ if not (0 <= start_hour <= 23 and 0 <= end_hour <= 23):
+ raise ValueError("Hours must be between 0 and 23")
+
+ return start_hour, end_hour
+ except (ValueError, AttributeError) as e:
+ raise ParseError(
+ f"Invalid time range format: '{time_range}'. Expected 'HH-HH' (e.g., '6-20')"
+ ) from e
diff --git a/fli/mcp/__init__.py b/fli/mcp/__init__.py
index 801dd4e..26b1cc1 100644
--- a/fli/mcp/__init__.py
+++ b/fli/mcp/__init__.py
@@ -1,19 +1,19 @@
"""MCP module for the fli package."""
from fli.mcp.server import (
- CheapFlightSearchRequest,
- FlightSearchRequest,
+ DateSearchParams,
+ FlightSearchParams,
mcp,
run,
run_http,
- search_cheap_flights,
+ search_dates,
search_flights,
)
__all__ = [
- "CheapFlightSearchRequest",
- "FlightSearchRequest",
- "search_cheap_flights",
+ "DateSearchParams",
+ "FlightSearchParams",
+ "search_dates",
"search_flights",
"mcp",
"run",
diff --git a/fli/mcp/server.py b/fli/mcp/server.py
index 9f9946f..6118d9e 100755
--- a/fli/mcp/server.py
+++ b/fli/mcp/server.py
@@ -1,3 +1,10 @@
+"""Flight Search MCP Server.
+
+This module provides an MCP (Model Context Protocol) server for flight search
+functionality, enabling AI assistants to search for flights and find cheapest
+travel dates.
+"""
+
import json
import os
from collections.abc import Callable
@@ -21,17 +28,21 @@ from mcp.types import (
from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
+from fli.core import (
+ build_date_search_segments,
+ build_flight_segments,
+ build_time_restrictions,
+ parse_airlines,
+ parse_cabin_class,
+ parse_max_stops,
+ parse_sort_by,
+ resolve_airport,
+)
+from fli.core.parsers import ParseError
from fli.models import (
- Airline,
- Airport,
DateSearchFilters,
FlightSearchFilters,
- FlightSegment,
- MaxStops,
PassengerInfo,
- SeatType,
- SortBy,
- TimeRestrictions,
TripType,
)
from fli.search import SearchDates, SearchFlights
@@ -53,7 +64,7 @@ class FlightSearchConfig(BaseSettings):
max_length=3,
description="Three-letter currency code returned with search results.",
)
- default_seat_class: str = Field(
+ default_cabin_class: str = Field(
"ECONOMY",
description="Default cabin class used when none is provided.",
)
@@ -61,7 +72,7 @@ class FlightSearchConfig(BaseSettings):
"CHEAPEST",
description="Default sorting strategy for flight results.",
)
- default_time_range: str | None = Field(
+ default_departure_window: str | None = Field(
None,
description="Optional default departure window in 'HH-HH' 24-hour format.",
)
@@ -96,8 +107,7 @@ class FliMCP(FastMCP):
def _setup_handlers(self) -> None:
"""Register MCP protocol handlers including prompts."""
- super()._setup_handlers() # Set up standard handlers from parent
- # Override only the handlers that FliMCP customizes
+ super()._setup_handlers()
self._mcp_server.list_tools()(self.list_tools)
self._mcp_server.list_prompts()(self.list_prompts)
self._mcp_server.get_prompt()(self.get_prompt)
@@ -195,175 +205,160 @@ class FliMCP(FastMCP):
mcp = FliMCP("Flight Search MCP Server")
-class FlightSearchRequest(BaseModel):
- """Search for flights between two airports on a specific date."""
+# =============================================================================
+# Request/Response Models
+# =============================================================================
+
- from_airport: str = Field(description="Departure airport code (e.g., 'JFK')")
- to_airport: str = Field(description="Arrival airport code (e.g., 'LHR')")
- date: str = Field(description="Travel date in YYYY-MM-DD format")
+class FlightSearchParams(BaseModel):
+ """Parameters for searching flights on a specific date."""
+
+ origin: str = Field(description="Departure airport IATA code (e.g., 'JFK', 'LAX')")
+ destination: str = Field(description="Arrival airport IATA code (e.g., 'LHR', 'NRT')")
+ departure_date: str = Field(description="Outbound travel date in YYYY-MM-DD format")
return_date: str | None = Field(
- None, description="Return date in YYYY-MM-DD format for round trips"
+ None, description="Return date in YYYY-MM-DD format (omit for one-way)"
+ )
+ departure_window: str | None = Field(
+ None, description="Preferred departure time window in 'HH-HH' 24h format (e.g., '6-20')"
)
- time_range: str | None = Field(None, description="Time range in 24h format (e.g., '6-20')")
airlines: list[str] | None = Field(
- None, description="List of airline codes (e.g., ['BA', 'KL'])"
+ None, description="Filter by airline IATA codes (e.g., ['BA', 'AA'])"
)
- seat_class: str = Field(
- CONFIG.default_seat_class,
- description="Seat type: ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST",
+ cabin_class: str = Field(
+ CONFIG.default_cabin_class,
+ description="Cabin class: ECONOMY, PREMIUM_ECONOMY, BUSINESS, or FIRST",
+ )
+ max_stops: str = Field(
+ "ANY", description="Maximum stops: ANY, NON_STOP, ONE_STOP, or TWO_PLUS_STOPS"
)
- stops: str = Field("ANY", description="Maximum stops: ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS")
sort_by: str = Field(
CONFIG.default_sort_by,
- description="Sort by: CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME",
+ description="Sort results by: CHEAPEST, DURATION, DEPARTURE_TIME, or ARRIVAL_TIME",
)
passengers: int = Field(
CONFIG.default_passengers,
ge=1,
- description="Number of adult passengers to include in the search.",
+ description="Number of adult passengers",
)
-class CheapFlightSearchRequest(BaseModel):
- """Search for the cheapest flights between two airports over a date range."""
+class DateSearchParams(BaseModel):
+ """Parameters for finding the cheapest travel dates within a range."""
- from_airport: str = Field(description="Departure airport code (e.g., 'JFK')")
- to_airport: str = Field(description="Arrival airport code (e.g., 'LHR')")
- from_date: str = Field(description="Start date for search range in YYYY-MM-DD format")
- to_date: str = Field(description="End date for search range in YYYY-MM-DD format")
- duration: int = Field(3, description="Duration of trip in days for round trips")
- round_trip: bool = Field(False, description="Whether to search for round-trip flights")
+ origin: str = Field(description="Departure airport IATA code (e.g., 'JFK', 'LAX')")
+ destination: str = Field(description="Arrival airport IATA code (e.g., 'LHR', 'NRT')")
+ start_date: str = Field(description="Start of date range in YYYY-MM-DD format")
+ end_date: str = Field(description="End of date range in YYYY-MM-DD format")
+ trip_duration: int = Field(
+ 3, ge=1, description="Trip duration in days (for round-trip searches)"
+ )
+ is_round_trip: bool = Field(False, description="Search for round-trip flights")
airlines: list[str] | None = Field(
- None, description="List of airline codes (e.g., ['BA', 'KL'])"
+ None, description="Filter by airline IATA codes (e.g., ['BA', 'AA'])"
)
- seat_class: str = Field(
- CONFIG.default_seat_class,
- description="Seat type: ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST",
+ cabin_class: str = Field(
+ CONFIG.default_cabin_class,
+ description="Cabin class: ECONOMY, PREMIUM_ECONOMY, BUSINESS, or FIRST",
)
- stops: str = Field("ANY", description="Maximum stops: ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS")
- time_range: str | None = Field(None, description="Time range in 24h format (e.g., '6-20')")
- sort_by_price: bool = Field(False, description="Sort results by price (lowest to highest)")
+ max_stops: str = Field(
+ "ANY", description="Maximum stops: ANY, NON_STOP, ONE_STOP, or TWO_PLUS_STOPS"
+ )
+ departure_window: str | None = Field(
+ None, description="Preferred departure time window in 'HH-HH' 24h format (e.g., '6-20')"
+ )
+ sort_by_price: bool = Field(False, description="Sort results by price (lowest first)")
passengers: int = Field(
CONFIG.default_passengers,
ge=1,
- description="Number of adult passengers to include when evaluating prices.",
+ description="Number of adult passengers",
)
-def parse_stops(stops: str) -> MaxStops:
- """Parse stops parameter to MaxStops enum."""
- stops_map = {
- "ANY": MaxStops.ANY,
- "NON_STOP": MaxStops.NON_STOP,
- "ONE_STOP": MaxStops.ONE_STOP_OR_FEWER,
- "TWO_PLUS_STOPS": MaxStops.TWO_OR_FEWER_STOPS,
- }
- if stops.upper() not in stops_map:
- raise ValueError(f"Invalid stops value: {stops}")
- return stops_map[stops.upper()]
+# =============================================================================
+# Result Serialization
+# =============================================================================
-def parse_time_range(time_range: str) -> tuple[int, int]:
- """Parse time range string to start and end hours."""
- start_str, end_str = time_range.split("-")
- return int(start_str), int(end_str)
+def _serialize_flight_leg(leg: Any) -> dict[str, Any]:
+ """Serialize a single flight leg to a dictionary."""
+ return {
+ "departure_airport": leg.departure_airport,
+ "arrival_airport": leg.arrival_airport,
+ "departure_time": leg.departure_datetime,
+ "arrival_time": leg.arrival_datetime,
+ "duration": leg.duration,
+ "airline": leg.airline,
+ "flight_number": leg.flight_number,
+ }
-def parse_airlines(airline_codes: list[str] | None) -> list[Airline] | None:
- """Convert airline code strings to Airline enum objects."""
- if not airline_codes:
- return None
+def _serialize_flight_result(flight: Any, is_round_trip: bool = False) -> dict[str, Any]:
+ """Serialize a flight result (or round-trip pair) to a dictionary."""
+ if is_round_trip and isinstance(flight, tuple):
+ outbound, return_flight = flight
+ return {
+ "price": outbound.price + return_flight.price,
+ "currency": CONFIG.default_currency,
+ "legs": [
+ *[_serialize_flight_leg(leg) for leg in outbound.legs],
+ *[_serialize_flight_leg(leg) for leg in return_flight.legs],
+ ],
+ }
+ else:
+ return {
+ "price": flight.price,
+ "currency": CONFIG.default_currency,
+ "legs": [_serialize_flight_leg(leg) for leg in flight.legs],
+ }
- airlines = []
- for code in airline_codes:
- try:
- airline = getattr(Airline, code.upper())
- airlines.append(airline)
- except AttributeError as e:
- raise ValueError(f"Invalid airline code: {code}") from e
- return airlines if airlines else None
+def _serialize_date_result(date_result: Any) -> dict[str, Any]:
+ """Serialize a date price result to a dictionary."""
+ return {
+ "date": date_result.date,
+ "price": date_result.price,
+ "currency": CONFIG.default_currency,
+ "return_date": getattr(date_result, "return_date", None),
+ }
-def resolve_enum(enum_cls, name: str):
- """Resolve enum member name to enum value with normalized errors."""
- try:
- return getattr(enum_cls, name.upper())
- except AttributeError as e:
- raise ValueError("Invalid parameter value") from e
-
-
-def _apply_flight_defaults(request: FlightSearchRequest) -> FlightSearchRequest:
- """Apply configuration defaults to a flight search request."""
- if request.passengers < 1:
- request.passengers = CONFIG.default_passengers
- if not request.seat_class:
- request.seat_class = CONFIG.default_seat_class
- if not request.sort_by:
- request.sort_by = CONFIG.default_sort_by
- if not request.time_range and CONFIG.default_time_range:
- request.time_range = CONFIG.default_time_range
- return request
-
-
-def _execute_flight_search(request: FlightSearchRequest) -> dict[str, Any]:
- """Perform the flight search and format the results."""
- request = _apply_flight_defaults(request)
- try:
- # Parse airports
- departure_airport = resolve_enum(Airport, request.from_airport)
- arrival_airport = resolve_enum(Airport, request.to_airport)
-
- # Parse seat type and sort options
- seat_type = resolve_enum(SeatType, request.seat_class)
- sort_by = resolve_enum(SortBy, request.sort_by)
-
- # Parse stops
- max_stops = parse_stops(request.stops)
-
- # Parse airlines
- airlines = parse_airlines(request.airlines)
-
- # Parse time restrictions
- time_restrictions = None
- time_range = request.time_range or CONFIG.default_time_range
- if time_range:
- start_hour, end_hour = parse_time_range(time_range)
- time_restrictions = TimeRestrictions(
- earliest_departure=start_hour,
- latest_departure=end_hour,
- )
+# =============================================================================
+# Search Execution
+# =============================================================================
- # Create flight segments
- flight_segments = [
- FlightSegment(
- departure_airport=[[departure_airport, 0]],
- arrival_airport=[[arrival_airport, 0]],
- travel_date=request.date,
- time_restrictions=time_restrictions,
- )
- ]
- # Add return segment if round trip
- trip_type = TripType.ONE_WAY
- if request.return_date:
- trip_type = TripType.ROUND_TRIP
- flight_segments.append(
- FlightSegment(
- departure_airport=[[arrival_airport, 0]],
- arrival_airport=[[departure_airport, 0]],
- travel_date=request.return_date,
- time_restrictions=time_restrictions,
- )
- )
+def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
+ """Execute a flight search and return formatted results."""
+ try:
+ # Parse inputs using shared utilities
+ origin = resolve_airport(params.origin)
+ destination = resolve_airport(params.destination)
+ cabin_class = parse_cabin_class(params.cabin_class)
+ max_stops = parse_max_stops(params.max_stops)
+ sort_by = parse_sort_by(params.sort_by)
+ airlines = parse_airlines(params.airlines)
+
+ # Build time restrictions
+ departure_window = params.departure_window or CONFIG.default_departure_window
+ time_restrictions = build_time_restrictions(departure_window) if departure_window else None
+
+ # Build flight segments
+ segments, trip_type = build_flight_segments(
+ origin=origin,
+ destination=destination,
+ departure_date=params.departure_date,
+ return_date=params.return_date,
+ time_restrictions=time_restrictions,
+ )
# Create search filters
filters = FlightSearchFilters(
trip_type=trip_type,
- passenger_info=PassengerInfo(adults=request.passengers),
- flight_segments=flight_segments,
+ passenger_info=PassengerInfo(adults=params.passengers),
+ flight_segments=segments,
stops=max_stops,
- seat_type=seat_type,
+ seat_type=cabin_class,
airlines=airlines,
sort_by=sort_by,
)
@@ -373,62 +368,11 @@ def _execute_flight_search(request: FlightSearchRequest) -> dict[str, Any]:
flights = search_client.search(filters)
if not flights:
- return {"error": "No flights found", "flights": []}
-
- # Convert flights to serializable format
- flight_results = []
- for flight in flights:
- if isinstance(flight, tuple):
- outbound, return_flight = flight
- flight_data = {
- "price": outbound.price + return_flight.price,
- "currency": CONFIG.default_currency,
- "legs": [],
- }
-
- for leg in outbound.legs:
- leg_data = {
- "departure_airport": leg.departure_airport,
- "arrival_airport": leg.arrival_airport,
- "departure_time": leg.departure_datetime,
- "arrival_time": leg.arrival_datetime,
- "duration": leg.duration,
- "airline": leg.airline,
- "flight_number": leg.flight_number,
- }
- flight_data["legs"].append(leg_data)
-
- for leg in return_flight.legs:
- leg_data = {
- "departure_airport": leg.departure_airport,
- "arrival_airport": leg.arrival_airport,
- "departure_time": leg.departure_datetime,
- "arrival_time": leg.arrival_datetime,
- "duration": leg.duration,
- "airline": leg.airline,
- "flight_number": leg.flight_number,
- }
- flight_data["legs"].append(leg_data)
- else:
- flight_data = {
- "price": flight.price,
- "currency": CONFIG.default_currency,
- "legs": [],
- }
-
- for leg in flight.legs:
- leg_data = {
- "departure_airport": leg.departure_airport,
- "arrival_airport": leg.arrival_airport,
- "departure_time": leg.departure_datetime,
- "arrival_time": leg.arrival_datetime,
- "duration": leg.duration,
- "airline": leg.airline,
- "flight_number": leg.flight_number,
- }
- flight_data["legs"].append(leg_data)
-
- flight_results.append(flight_data)
+ return {"success": True, "flights": [], "count": 0, "trip_type": trip_type.name}
+
+ # Serialize results
+ is_round_trip = trip_type == TripType.ROUND_TRIP
+ flight_results = [_serialize_flight_result(f, is_round_trip) for f in flights]
if CONFIG.max_results:
flight_results = flight_results[: CONFIG.max_results]
@@ -440,130 +384,70 @@ def _execute_flight_search(request: FlightSearchRequest) -> dict[str, Any]:
"trip_type": trip_type.name,
}
- except ValueError as e:
- error_msg = str(e)
- if (
- "Invalid time range" in error_msg
- or "split" in error_msg
- or "invalid literal for int()" in error_msg
- ):
- return {
- "success": False,
- "error": "Invalid time range format",
- "flights": [],
- }
- if "Invalid airline code" in error_msg:
- return {"success": False, "error": "Invalid airline code", "flights": []}
- if "Invalid stops value" in error_msg:
- return {"success": False, "error": "Invalid parameter value", "flights": []}
- return {"success": False, "error": "Invalid parameter value", "flights": []}
+ except ParseError as e:
+ return {"success": False, "error": str(e), "flights": []}
except Exception as e:
error_msg = str(e)
- if (
- "Invalid time range" in error_msg
- or "split" in error_msg
- or "invalid literal for int()" in error_msg
- ):
- return {
- "success": False,
- "error": "Invalid time range format",
- "flights": [],
- }
- if "validation error" in error_msg and (
- "Airport" in error_msg or "airline" in error_msg.lower()
- ):
+ if "validation error" in error_msg.lower():
return {"success": False, "error": "Invalid parameter value", "flights": []}
- return {
- "success": False,
- "error": f"Search failed: {error_msg}",
- "flights": [],
- }
-
+ return {"success": False, "error": f"Search failed: {error_msg}", "flights": []}
-def _apply_date_defaults(request: CheapFlightSearchRequest) -> CheapFlightSearchRequest:
- """Apply configuration defaults to a date search request."""
- if request.passengers < 1:
- request.passengers = CONFIG.default_passengers
- if not request.seat_class:
- request.seat_class = CONFIG.default_seat_class
- if not request.time_range and CONFIG.default_time_range:
- request.time_range = CONFIG.default_time_range
- return request
-
-def _execute_cheap_flight_search(request: CheapFlightSearchRequest) -> dict[str, Any]:
- """Perform the date search and format the results."""
- request = _apply_date_defaults(request)
+def _execute_date_search(params: DateSearchParams) -> dict[str, Any]:
+ """Execute a date search and return formatted results."""
try:
- departure_airport = resolve_enum(Airport, request.from_airport)
- arrival_airport = resolve_enum(Airport, request.to_airport)
-
- trip_type = TripType.ROUND_TRIP if request.round_trip else TripType.ONE_WAY
- seat_type = resolve_enum(SeatType, request.seat_class)
- max_stops = parse_stops(request.stops)
- airlines = parse_airlines(request.airlines)
-
- time_restrictions = None
- time_range = request.time_range or CONFIG.default_time_range
- if time_range:
- start_hour, end_hour = parse_time_range(time_range)
- time_restrictions = TimeRestrictions(
- earliest_departure=start_hour,
- latest_departure=end_hour,
- earliest_arrival=None,
- latest_arrival=None,
- )
-
- flight_segment = FlightSegment(
- departure_airport=[[departure_airport, 0]],
- arrival_airport=[[arrival_airport, 0]],
- travel_date=request.from_date,
+ # Parse inputs using shared utilities
+ origin = resolve_airport(params.origin)
+ destination = resolve_airport(params.destination)
+ cabin_class = parse_cabin_class(params.cabin_class)
+ max_stops = parse_max_stops(params.max_stops)
+ airlines = parse_airlines(params.airlines)
+
+ # Build time restrictions
+ departure_window = params.departure_window or CONFIG.default_departure_window
+ time_restrictions = build_time_restrictions(departure_window) if departure_window else None
+
+ # Build flight segments
+ segments, trip_type = build_date_search_segments(
+ origin=origin,
+ destination=destination,
+ start_date=params.start_date,
+ trip_duration=params.trip_duration,
+ is_round_trip=params.is_round_trip,
time_restrictions=time_restrictions,
)
- flight_segments = [flight_segment]
- if trip_type == TripType.ROUND_TRIP:
- return_flight_segment = FlightSegment(
- departure_airport=[[arrival_airport, 0]],
- arrival_airport=[[departure_airport, 0]],
- travel_date=(
- datetime.strptime(flight_segment.travel_date, "%Y-%m-%d")
- + timedelta(days=request.duration)
- ).strftime("%Y-%m-%d"),
- time_restrictions=time_restrictions,
- )
- flight_segments.append(return_flight_segment)
-
+ # Create search filters
filters = DateSearchFilters(
trip_type=trip_type,
- passenger_info=PassengerInfo(adults=request.passengers),
- flight_segments=flight_segments,
+ passenger_info=PassengerInfo(adults=params.passengers),
+ flight_segments=segments,
stops=max_stops,
- seat_type=seat_type,
+ seat_type=cabin_class,
airlines=airlines,
- from_date=request.from_date,
- to_date=request.to_date,
- duration=request.duration if trip_type == TripType.ROUND_TRIP else None,
+ from_date=params.start_date,
+ to_date=params.end_date,
+ duration=params.trip_duration if params.is_round_trip else None,
)
+ # Perform search
search_client = SearchDates()
dates = search_client.search(filters)
if not dates:
- return {"error": "No flights found for these dates", "dates": []}
+ return {
+ "success": True,
+ "dates": [],
+ "count": 0,
+ "trip_type": trip_type.name,
+ "date_range": f"{params.start_date} to {params.end_date}",
+ }
- if request.sort_by_price:
+ if params.sort_by_price:
dates.sort(key=lambda x: x.price)
- date_results = []
- for date_result in dates:
- date_data = {
- "date": date_result.date,
- "price": date_result.price,
- "currency": CONFIG.default_currency,
- "return_date": getattr(date_result, "return_date", None),
- }
- date_results.append(date_data)
+ # Serialize results
+ date_results = [_serialize_date_result(d) for d in dates]
if CONFIG.max_results:
date_results = date_results[: CONFIG.max_results]
@@ -573,12 +457,19 @@ def _execute_cheap_flight_search(request: CheapFlightSearchRequest) -> dict[str,
"dates": date_results,
"count": len(date_results),
"trip_type": trip_type.name,
- "date_range": f"{request.from_date} to {request.to_date}",
- "duration": request.duration if trip_type == TripType.ROUND_TRIP else None,
+ "date_range": f"{params.start_date} to {params.end_date}",
+ "duration": params.trip_duration if params.is_round_trip else None,
}
+ except ParseError as e:
+ return {"success": False, "error": str(e), "dates": []}
except Exception as e:
- return {"error": f"Date search failed: {str(e)}", "dates": []}
+ return {"success": False, "error": f"Search failed: {str(e)}", "dates": []}
+
+
+# =============================================================================
+# MCP Tools
+# =============================================================================
@mcp.tool(
@@ -589,26 +480,26 @@ def _execute_cheap_flight_search(request: CheapFlightSearchRequest) -> dict[str,
},
)
def search_flights(
- from_airport: Annotated[str, Field(description="Departure airport code (e.g., 'JFK')")],
- to_airport: Annotated[str, Field(description="Arrival airport code (e.g., 'LHR')")],
- date: Annotated[str, Field(description="Travel date in YYYY-MM-DD format")],
+ origin: Annotated[str, Field(description="Departure airport IATA code (e.g., 'JFK')")],
+ destination: Annotated[str, Field(description="Arrival airport IATA code (e.g., 'LHR')")],
+ departure_date: Annotated[str, Field(description="Travel date in YYYY-MM-DD format")],
return_date: Annotated[
str | None,
- Field(description="Return date in YYYY-MM-DD format for round trips"),
+ Field(description="Return date in YYYY-MM-DD format (omit for one-way)"),
] = None,
- time_range: Annotated[
+ departure_window: Annotated[
str | None,
- Field(description="Preferred departure window in 'HH-HH' 24-hour format"),
+ Field(description="Departure time window in 'HH-HH' 24h format (e.g., '6-20')"),
] = None,
airlines: Annotated[
list[str] | None,
- Field(description="List of airline codes (e.g., ['BA', 'KL'])"),
+ Field(description="Filter by airline IATA codes (e.g., ['BA', 'AA'])"),
] = None,
- seat_class: Annotated[
+ cabin_class: Annotated[
str,
- Field(description="Seat type: ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST"),
- ] = CONFIG.default_seat_class,
- stops: Annotated[
+ Field(description="Cabin class: ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST"),
+ ] = CONFIG.default_cabin_class,
+ max_stops: Annotated[
str,
Field(description="Maximum stops: ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS"),
] = "ANY",
@@ -618,121 +509,130 @@ def search_flights(
] = CONFIG.default_sort_by,
passengers: Annotated[
int | None,
- Field(description="Override the default number of adult passengers.", ge=1),
+ Field(description="Number of adult passengers", ge=1),
] = None,
) -> dict[str, Any]:
- """Search for flights with flexible filtering options."""
- effective_time_range = time_range or CONFIG.default_time_range
- request = FlightSearchRequest(
- from_airport=from_airport,
- to_airport=to_airport,
- date=date,
+ """Search for flights between two airports on a specific date.
+
+ Returns a list of available flights with prices, durations, and leg details.
+ Supports one-way and round-trip searches with various filtering options.
+ """
+ effective_departure_window = departure_window or CONFIG.default_departure_window
+ params = FlightSearchParams(
+ origin=origin,
+ destination=destination,
+ departure_date=departure_date,
return_date=return_date,
- time_range=effective_time_range,
+ departure_window=effective_departure_window,
airlines=airlines,
- seat_class=seat_class,
- stops=stops,
+ cabin_class=cabin_class,
+ max_stops=max_stops,
sort_by=sort_by,
passengers=passengers or CONFIG.default_passengers,
)
- return _execute_flight_search(request)
+ return _execute_flight_search(params)
-def _search_flights_from_request(request: FlightSearchRequest) -> dict[str, Any]:
- """Compatibility wrapper for tests expecting the original request-based signature."""
- return _execute_flight_search(request)
+def _search_flights_from_params(params: FlightSearchParams) -> dict[str, Any]:
+ """Compatibility wrapper for tests expecting the params-based signature."""
+ return _execute_flight_search(params)
-search_flights.fn = _search_flights_from_request # type: ignore[attr-defined]
+search_flights.fn = _search_flights_from_params # type: ignore[attr-defined]
@mcp.tool(
annotations={
- "title": "Find Cheapest Dates",
+ "title": "Search Dates",
"readOnlyHint": True,
"idempotentHint": True,
},
)
-def search_cheap_flights(
- from_airport: Annotated[str, Field(description="Departure airport code (e.g., 'JFK')")],
- to_airport: Annotated[str, Field(description="Arrival airport code (e.g., 'LHR')")],
- from_date: Annotated[
- str, Field(description="Start date for search range in YYYY-MM-DD format")
- ],
- to_date: Annotated[str, Field(description="End date for search range in YYYY-MM-DD format")],
- duration: Annotated[
+def search_dates(
+ origin: Annotated[str, Field(description="Departure airport IATA code (e.g., 'JFK')")],
+ destination: Annotated[str, Field(description="Arrival airport IATA code (e.g., 'LHR')")],
+ start_date: Annotated[str, Field(description="Start of date range in YYYY-MM-DD format")],
+ end_date: Annotated[str, Field(description="End of date range in YYYY-MM-DD format")],
+ trip_duration: Annotated[
int,
- Field(description="Duration of trip in days for round trips", ge=1),
+ Field(description="Trip duration in days for round-trips", ge=1),
] = 3,
- round_trip: Annotated[
+ is_round_trip: Annotated[
bool,
- Field(description="Whether to search for round-trip flights"),
+ Field(description="Search for round-trip flights"),
] = False,
airlines: Annotated[
list[str] | None,
- Field(description="List of airline codes (e.g., ['BA', 'KL'])"),
+ Field(description="Filter by airline IATA codes (e.g., ['BA', 'AA'])"),
] = None,
- seat_class: Annotated[
+ cabin_class: Annotated[
str,
- Field(description="Seat type: ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST"),
- ] = CONFIG.default_seat_class,
- stops: Annotated[
+ Field(description="Cabin class: ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST"),
+ ] = CONFIG.default_cabin_class,
+ max_stops: Annotated[
str,
Field(description="Maximum stops: ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS"),
] = "ANY",
- time_range: Annotated[
+ departure_window: Annotated[
str | None,
- Field(description="Preferred departure window in 'HH-HH' 24-hour format"),
+ Field(description="Departure time window in 'HH-HH' 24h format (e.g., '6-20')"),
] = None,
sort_by_price: Annotated[
bool,
- Field(description="Sort the resulting dates by price (lowest to highest)"),
+ Field(description="Sort results by price (lowest first)"),
] = False,
passengers: Annotated[
int | None,
- Field(description="Override the default number of adult passengers.", ge=1),
+ Field(description="Number of adult passengers", ge=1),
] = None,
) -> dict[str, Any]:
- """Find the cheapest travel dates between two airports."""
- effective_time_range = time_range or CONFIG.default_time_range
- request = CheapFlightSearchRequest(
- from_airport=from_airport,
- to_airport=to_airport,
- from_date=from_date,
- to_date=to_date,
- duration=duration,
- round_trip=round_trip,
+ """Find the cheapest travel dates between two airports within a date range.
+
+ Returns a list of dates with their prices, useful for flexible travel planning.
+ Supports both one-way and round-trip searches.
+ """
+ effective_departure_window = departure_window or CONFIG.default_departure_window
+ params = DateSearchParams(
+ origin=origin,
+ destination=destination,
+ start_date=start_date,
+ end_date=end_date,
+ trip_duration=trip_duration,
+ is_round_trip=is_round_trip,
airlines=airlines,
- seat_class=seat_class,
- stops=stops,
- time_range=effective_time_range,
+ cabin_class=cabin_class,
+ max_stops=max_stops,
+ departure_window=effective_departure_window,
sort_by_price=sort_by_price,
passengers=passengers or CONFIG.default_passengers,
)
- return _execute_cheap_flight_search(request)
+ return _execute_date_search(params)
-def _search_cheap_flights_from_request(
- request: CheapFlightSearchRequest,
-) -> dict[str, Any]:
- """Compatibility wrapper for tests expecting the original request-based signature."""
- return _execute_cheap_flight_search(request)
+def _search_dates_from_params(params: DateSearchParams) -> dict[str, Any]:
+ """Compatibility wrapper for tests expecting the params-based signature."""
+ return _execute_date_search(params)
-search_cheap_flights.fn = _search_cheap_flights_from_request # type: ignore[attr-defined]
+search_dates.fn = _search_dates_from_params # type: ignore[attr-defined]
+
+
+# =============================================================================
+# Prompts
+# =============================================================================
def _build_search_prompt(args: dict[str, str]) -> list[PromptMessage]:
"""Create a helper prompt to guide flight searches."""
- from_airport = args.get("from_airport", "JFK").upper()
- to_airport = args.get("to_airport", "LHR").upper()
+ origin = args.get("origin", "JFK").upper()
+ destination = args.get("destination", "LHR").upper()
date = args.get("date") or datetime.utcnow().date().isoformat()
prefer_non_stop = args.get("prefer_non_stop", "true").lower()
- stops_hint = "NON_STOP" if prefer_non_stop in {"true", "1", "yes"} else "ANY"
+ max_stops_hint = "NON_STOP" if prefer_non_stop in {"true", "1", "yes"} else "ANY"
text = (
"Use the `search_flights` tool to look for flights from "
- f"{from_airport} to {to_airport} departing on {date}. "
- f"Set `stops` to '{stops_hint}' and highlight the three most affordable options."
+ f"{origin} to {destination} departing on {date}. "
+ f"Set `max_stops` to '{max_stops_hint}' and highlight the three most affordable options."
)
return [
PromptMessage(role=Role.USER, content=TextContent(type="text", text=text)),
@@ -741,15 +641,17 @@ def _build_search_prompt(args: dict[str, str]) -> list[PromptMessage]:
def _build_budget_prompt(args: dict[str, str]) -> list[PromptMessage]:
"""Create a helper prompt to guide flexible date searches."""
- from_airport = args.get("from_airport", "SFO").upper()
- to_airport = args.get("to_airport", "NRT").upper()
- from_date = args.get("from_date") or (datetime.utcnow().date() + timedelta(days=30)).isoformat()
- to_date = args.get("to_date") or (datetime.utcnow().date() + timedelta(days=90)).isoformat()
+ origin = args.get("origin", "SFO").upper()
+ destination = args.get("destination", "NRT").upper()
+ start_date = (
+ args.get("start_date") or (datetime.utcnow().date() + timedelta(days=30)).isoformat()
+ )
+ end_date = args.get("end_date") or (datetime.utcnow().date() + timedelta(days=90)).isoformat()
duration = args.get("duration", "7")
text = (
- "Use the `search_cheap_flights` tool to find the lowest fares between "
- f"{from_airport} and {to_airport} for trips between {from_date} and {to_date}. "
- f"Limit the duration to {duration} days and sort the results by price."
+ "Use the `search_dates` tool to find the lowest fares between "
+ f"{origin} and {destination} for trips between {start_date} and {end_date}. "
+ f"Set trip_duration to {duration} days and sort the results by price."
)
return [
PromptMessage(role=Role.USER, content=TextContent(type="text", text=text)),
@@ -763,13 +665,13 @@ mcp.add_prompt(
),
arguments=[
PromptArgument(
- name="from_airport",
- description="Departure airport code",
+ name="origin",
+ description="Departure airport IATA code",
required=True,
),
PromptArgument(
- name="to_airport",
- description="Arrival airport code",
+ name="destination",
+ description="Arrival airport IATA code",
required=True,
),
PromptArgument(
@@ -791,22 +693,22 @@ mcp.add_prompt(
description=("Suggest the cheapest travel dates for a route within a flexible window."),
arguments=[
PromptArgument(
- name="from_airport",
- description="Departure airport code",
+ name="origin",
+ description="Departure airport IATA code",
required=True,
),
PromptArgument(
- name="to_airport",
- description="Arrival airport code",
+ name="destination",
+ description="Arrival airport IATA code",
required=True,
),
PromptArgument(
- name="from_date",
+ name="start_date",
description="Start of the travel window (YYYY-MM-DD)",
required=False,
),
PromptArgument(
- name="to_date",
+ name="end_date",
description="End of the travel window (YYYY-MM-DD)",
required=False,
),
@@ -820,6 +722,11 @@ mcp.add_prompt(
)
+# =============================================================================
+# Resources
+# =============================================================================
+
+
@mcp.resource(
"resource://fli-mcp/configuration",
name="Fli MCP Configuration",
@@ -839,9 +746,9 @@ def configuration_resource() -> str:
"variables": {
"FLI_MCP_DEFAULT_PASSENGERS": "Adjust the default passenger count.",
"FLI_MCP_DEFAULT_CURRENCY": "Override the currency code returned with results.",
- "FLI_MCP_DEFAULT_SEAT_CLASS": "Set a default seat class.",
+ "FLI_MCP_DEFAULT_CABIN_CLASS": "Set a default cabin class.",
"FLI_MCP_DEFAULT_SORT_BY": "Set the default result sorting strategy.",
- "FLI_MCP_DEFAULT_TIME_RANGE": "Provide a default departure window (HH-HH).",
+ "FLI_MCP_DEFAULT_DEPARTURE_WINDOW": "Provide a default departure window (HH-HH).",
"FLI_MCP_MAX_RESULTS": "Limit the maximum number of results returned by tools.",
},
},
@@ -849,6 +756,11 @@ def configuration_resource() -> str:
return json.dumps(payload, indent=2)
+# =============================================================================
+# Entry Points
+# =============================================================================
+
+
def run():
"""Run the MCP server on STDIO."""
mcp.run(transport="stdio")
diff --git a/pyproject.toml b/pyproject.toml
index f6d3d3a..8d2c120 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "flights"
-version = "0.6.1"
+version = "0.7.0"
description = "A Python wrapper for Google Flights API"
authors = [
{ name = "Punit Arani", email = "[email protected]" }
@@ -28,6 +28,7 @@ dependencies = [
"fastmcp>=0.1.0",
"httpx>=0.28.1",
"pandas>=2.2.3",
+ "plotext>=5.3.2",
"pydantic>=2.10.4",
"python-dotenv>=1.0.1",
"ratelimit>=2.2.1",
diff --git a/tests/cli/test_cheap.py b/tests/cli/test_dates.py
similarity index 65%
rename from tests/cli/test_cheap.py
rename to tests/cli/test_dates.py
index 960c7c5..162625c 100644
--- a/tests/cli/test_cheap.py
+++ b/tests/cli/test_dates.py
@@ -1,3 +1,5 @@
+"""Tests for the dates CLI command."""
+
from datetime import datetime, timedelta
import pytest
@@ -14,23 +16,23 @@ def runner():
return CliRunner()
-def test_basic_cheap_search(runner, mock_search_dates, mock_console):
- """Test basic cheap flight search (one-way by default)."""
+def test_basic_dates_search(runner, mock_search_dates, mock_console):
+ """Test basic dates search (one-way by default)."""
mock_search_dates.search.return_value = [
DatePrice(
date=(datetime.now() + timedelta(days=1),),
price=299.99,
),
]
- result = runner.invoke(app, ["cheap", "JFK", "LAX"])
+ result = runner.invoke(app, ["dates", "JFK", "LAX"])
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
args, _ = mock_search_dates.search.call_args
assert args[0].trip_type == TripType.ONE_WAY
-def test_cheap_with_date_range(runner, mock_search_dates, mock_console):
- """Test cheap search with custom date range."""
+def test_dates_with_date_range(runner, mock_search_dates, mock_console):
+ """Test dates search with custom date range."""
from_date = datetime.now().strftime("%Y-%m-%d")
to_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
@@ -42,15 +44,14 @@ def test_cheap_with_date_range(runner, mock_search_dates, mock_console):
]
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "--from", from_date, "--to", to_date],
+ ["dates", "JFK", "LAX", "--from", from_date, "--to", to_date],
)
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
-def test_cheap_with_days(runner, mock_search_dates, mock_console):
- """Test cheap search with specific days."""
- # Get next Monday
+def test_dates_with_days(runner, mock_search_dates, mock_console):
+ """Test dates search with specific days."""
today = datetime.now()
days_until_monday = (7 - today.weekday()) % 7
next_monday = today + timedelta(days=days_until_monday)
@@ -63,14 +64,14 @@ def test_cheap_with_days(runner, mock_search_dates, mock_console):
]
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "--monday", "--friday"],
+ ["dates", "JFK", "LAX", "--monday", "--friday"],
)
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
-def test_cheap_with_airlines(runner, mock_search_dates, mock_console):
- """Test cheap search with airline filter."""
+def test_dates_with_airlines(runner, mock_search_dates, mock_console):
+ """Test dates search with airline filter."""
mock_search_dates.search.return_value = [
DatePrice(
date=(datetime.now() + timedelta(days=1),),
@@ -79,14 +80,14 @@ def test_cheap_with_airlines(runner, mock_search_dates, mock_console):
]
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "-a", "DL", "-a", "UA"],
+ ["dates", "JFK", "LAX", "-a", "DL", "-a", "UA"],
)
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
-def test_cheap_with_seat_type(runner, mock_search_dates, mock_console):
- """Test cheap search with seat type."""
+def test_dates_with_cabin_class(runner, mock_search_dates, mock_console):
+ """Test dates search with cabin class."""
mock_search_dates.search.return_value = [
DatePrice(
date=(datetime.now() + timedelta(days=1),),
@@ -95,14 +96,14 @@ def test_cheap_with_seat_type(runner, mock_search_dates, mock_console):
]
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "--class", "BUSINESS"],
+ ["dates", "JFK", "LAX", "--class", "BUSINESS"],
)
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
-def test_cheap_with_stops(runner, mock_search_dates, mock_console):
- """Test cheap search with stops filter."""
+def test_dates_with_stops(runner, mock_search_dates, mock_console):
+ """Test dates search with stops filter."""
mock_search_dates.search.return_value = [
DatePrice(
date=(datetime.now() + timedelta(days=1),),
@@ -111,14 +112,14 @@ def test_cheap_with_stops(runner, mock_search_dates, mock_console):
]
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "--stops", "NON_STOP"],
+ ["dates", "JFK", "LAX", "--stops", "NON_STOP"],
)
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
-def test_cheap_with_time(runner, mock_search_dates, mock_console):
- """Test cheap search with time filter."""
+def test_dates_with_time(runner, mock_search_dates, mock_console):
+ """Test dates search with time filter."""
mock_search_dates.search.return_value = [
DatePrice(
date=(datetime.now() + timedelta(days=1),),
@@ -127,14 +128,14 @@ def test_cheap_with_time(runner, mock_search_dates, mock_console):
]
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "--time", "6-20"],
+ ["dates", "JFK", "LAX", "--time", "6-20"],
)
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
-def test_cheap_with_sort(runner, mock_search_dates, mock_console):
- """Test cheap search with sort option."""
+def test_dates_with_sort(runner, mock_search_dates, mock_console):
+ """Test dates search with sort option."""
mock_search_dates.search.return_value = [
DatePrice(
date=(datetime.now() + timedelta(days=1),),
@@ -143,41 +144,40 @@ def test_cheap_with_sort(runner, mock_search_dates, mock_console):
]
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "--sort"],
+ ["dates", "JFK", "LAX", "--sort"],
)
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
-def test_cheap_invalid_airport(runner, mock_search_dates, mock_console):
- """Test cheap search with invalid airport code."""
- result = runner.invoke(app, ["cheap", "XXX", "LAX"])
+def test_dates_invalid_airport(runner, mock_search_dates, mock_console):
+ """Test dates search with invalid airport code."""
+ result = runner.invoke(app, ["dates", "XXX", "LAX"])
assert result.exit_code == 1
assert "Error" in result.stdout
-def test_cheap_invalid_date_range(runner, mock_search_dates, mock_console):
- """Test cheap search with invalid date range."""
+def test_dates_invalid_date_range(runner, mock_search_dates, mock_console):
+ """Test dates search with invalid date range."""
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "--from", "2024-01-01", "--to", "2023-12-31"],
+ ["dates", "JFK", "LAX", "--from", "2024-01-01", "--to", "2023-12-31"],
)
assert result.exit_code == 1
assert "Error" in result.stdout
-def test_cheap_no_results(runner, mock_search_dates, mock_console):
- """Test cheap search with no results."""
- # Override the mock to return an empty list
+def test_dates_no_results(runner, mock_search_dates, mock_console):
+ """Test dates search with no results."""
mock_search_dates.search.return_value = []
- result = runner.invoke(app, ["cheap", "JFK", "LAX"])
+ result = runner.invoke(app, ["dates", "JFK", "LAX"])
assert result.exit_code == 1
assert "No flights found" in result.stdout
-def test_cheap_round_trip(runner, mock_search_dates, mock_console):
- """Test cheap search with round-trip flag."""
+def test_dates_round_trip(runner, mock_search_dates, mock_console):
+ """Test dates search with round-trip flag."""
mock_search_dates.search.return_value = [
DatePrice(
date=(
@@ -189,7 +189,7 @@ def test_cheap_round_trip(runner, mock_search_dates, mock_console):
]
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "--round"],
+ ["dates", "JFK", "LAX", "--round"],
)
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
@@ -197,8 +197,8 @@ def test_cheap_round_trip(runner, mock_search_dates, mock_console):
assert args[0].trip_type == TripType.ROUND_TRIP
-def test_cheap_round_trip_with_duration(runner, mock_search_dates, mock_console):
- """Test cheap round-trip search with custom duration."""
+def test_dates_round_trip_with_duration(runner, mock_search_dates, mock_console):
+ """Test dates round-trip search with custom duration."""
mock_search_dates.search.return_value = [
DatePrice(
date=(
@@ -210,7 +210,7 @@ def test_cheap_round_trip_with_duration(runner, mock_search_dates, mock_console)
]
result = runner.invoke(
app,
- ["cheap", "JFK", "LAX", "--round", "-d", "14"],
+ ["dates", "JFK", "LAX", "--round", "-d", "14"],
)
assert result.exit_code == 0
mock_search_dates.search.assert_called_once()
diff --git a/tests/cli/test_search.py b/tests/cli/test_flights.py
similarity index 69%
rename from tests/cli/test_search.py
rename to tests/cli/test_flights.py
index c8220ec..e9a8c65 100644
--- a/tests/cli/test_search.py
+++ b/tests/cli/test_flights.py
@@ -1,3 +1,5 @@
+"""Tests for the flights CLI command."""
+
from datetime import datetime, timedelta
import pytest
@@ -13,19 +15,19 @@ def runner():
return CliRunner()
-def test_basic_search(runner, mock_search_flights, mock_console):
+def test_basic_flights_search(runner, mock_search_flights, mock_console):
"""Test basic flight search with required parameters."""
- result = runner.invoke(app, ["search", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d")])
+ result = runner.invoke(app, ["flights", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d")])
assert result.exit_code == 0
mock_search_flights.search.assert_called_once()
-def test_search_with_time_filter(runner, mock_search_flights, mock_console):
- """Test search with time filter."""
+def test_flights_with_time_filter(runner, mock_search_flights, mock_console):
+ """Test flights search with time filter."""
result = runner.invoke(
app,
[
- "search",
+ "flights",
"JFK",
"LAX",
datetime.now().strftime("%Y-%m-%d"),
@@ -37,12 +39,12 @@ def test_search_with_time_filter(runner, mock_search_flights, mock_console):
mock_search_flights.search.assert_called_once()
-def test_search_with_airlines(runner, mock_search_flights, mock_console):
- """Test search with airline filter."""
+def test_flights_with_airlines(runner, mock_search_flights, mock_console):
+ """Test flights search with airline filter."""
result = runner.invoke(
app,
[
- "search",
+ "flights",
"JFK",
"LAX",
datetime.now().strftime("%Y-%m-%d"),
@@ -56,12 +58,12 @@ def test_search_with_airlines(runner, mock_search_flights, mock_console):
mock_search_flights.search.assert_called_once()
-def test_search_with_seat_type(runner, mock_search_flights, mock_console):
- """Test search with seat type."""
+def test_flights_with_cabin_class(runner, mock_search_flights, mock_console):
+ """Test flights search with cabin class."""
result = runner.invoke(
app,
[
- "search",
+ "flights",
"JFK",
"LAX",
datetime.now().strftime("%Y-%m-%d"),
@@ -73,12 +75,12 @@ def test_search_with_seat_type(runner, mock_search_flights, mock_console):
mock_search_flights.search.assert_called_once()
-def test_search_with_stops(runner, mock_search_flights, mock_console):
- """Test search with stops filter."""
+def test_flights_with_stops(runner, mock_search_flights, mock_console):
+ """Test flights search with stops filter."""
result = runner.invoke(
app,
[
- "search",
+ "flights",
"JFK",
"LAX",
datetime.now().strftime("%Y-%m-%d"),
@@ -90,37 +92,36 @@ def test_search_with_stops(runner, mock_search_flights, mock_console):
mock_search_flights.search.assert_called_once()
-def test_search_invalid_airport(runner, mock_search_flights, mock_console):
- """Test search with invalid airport code."""
+def test_flights_invalid_airport(runner, mock_search_flights, mock_console):
+ """Test flights search with invalid airport code."""
result = runner.invoke(
app,
- ["search", "XXX", "LAX", datetime.now().strftime("%Y-%m-%d")],
+ ["flights", "XXX", "LAX", datetime.now().strftime("%Y-%m-%d")],
)
assert result.exit_code == 1
assert "Error" in result.stdout
-def test_search_invalid_date(runner, mock_search_flights, mock_console):
- """Test search with invalid date format."""
- result = runner.invoke(app, ["search", "JFK", "LAX", "2024-13-45"])
+def test_flights_invalid_date(runner, mock_search_flights, mock_console):
+ """Test flights search with invalid date format."""
+ result = runner.invoke(app, ["flights", "JFK", "LAX", "2024-13-45"])
assert result.exit_code == 2
assert "Error" in result.output
-def test_search_no_results(runner, mock_search_flights, mock_console):
- """Test search with no results."""
- # Override the mock to return no results
+def test_flights_no_results(runner, mock_search_flights, mock_console):
+ """Test flights search with no results."""
mock_search_flights.search.return_value = []
result = runner.invoke(
app,
- ["search", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d")],
+ ["flights", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d")],
)
assert result.exit_code == 1
assert "No flights found" in result.stdout
-def test_basic_round_trip_search(runner, mock_search_flights, mock_console):
+def test_basic_round_trip_flights(runner, mock_search_flights, mock_console):
"""Test basic round-trip flight search."""
outbound_date = datetime.now().strftime("%Y-%m-%d")
return_date = (datetime.now() + timedelta(days=7)).strftime("%Y-%m-%d")
@@ -128,7 +129,7 @@ def test_basic_round_trip_search(runner, mock_search_flights, mock_console):
result = runner.invoke(
app,
[
- "search",
+ "flights",
"JFK",
"LAX",
outbound_date,
@@ -141,14 +142,14 @@ def test_basic_round_trip_search(runner, mock_search_flights, mock_console):
def test_round_trip_with_filters(runner, mock_search_flights, mock_console):
- """Test round-trip search with additional filters."""
+ """Test round-trip flights search with additional filters."""
outbound_date = datetime.now().strftime("%Y-%m-%d")
return_date = (datetime.now() + timedelta(days=7)).strftime("%Y-%m-%d")
result = runner.invoke(
app,
[
- "search",
+ "flights",
"JFK",
"LAX",
outbound_date,
@@ -164,20 +165,19 @@ def test_round_trip_with_filters(runner, mock_search_flights, mock_console):
)
assert result.exit_code == 0
mock_search_flights.search.assert_called_once()
- # Verify the trip type was set to ROUND_TRIP
args, kwargs = mock_search_flights.search.call_args
assert args[0].trip_type == TripType.ROUND_TRIP
def test_round_trip_invalid_dates(runner, mock_search_flights, mock_console):
- """Test round-trip search with return date before outbound date."""
+ """Test round-trip flights search with return date before outbound date."""
outbound_date = datetime.now().strftime("%Y-%m-%d")
return_date = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
result = runner.invoke(
app,
[
- "search",
+ "flights",
"JFK",
"LAX",
outbound_date,
diff --git a/tests/mcp/test_mcp_server.py b/tests/mcp/test_mcp_server.py
index fa56d0b..d0fe555 100644
--- a/tests/mcp/test_mcp_server.py
+++ b/tests/mcp/test_mcp_server.py
@@ -3,9 +3,9 @@
from datetime import datetime, timedelta
from fli.mcp.server import (
- CheapFlightSearchRequest,
- FlightSearchRequest,
- search_cheap_flights,
+ DateSearchParams,
+ FlightSearchParams,
+ search_dates,
search_flights,
)
@@ -20,12 +20,12 @@ class TestMCPServer:
def test_search_flights_one_way(self):
"""Test one-way flight search."""
- params = FlightSearchRequest(
- from_airport="JFK",
- to_airport="LHR",
- date=get_future_date(30),
- seat_class="ECONOMY",
- stops="ANY",
+ params = FlightSearchParams(
+ origin="JFK",
+ destination="LHR",
+ departure_date=get_future_date(30),
+ cabin_class="ECONOMY",
+ max_stops="ANY",
sort_by="CHEAPEST",
)
@@ -43,15 +43,15 @@ class TestMCPServer:
def test_search_flights_round_trip(self):
"""Test round-trip flight search."""
- params = FlightSearchRequest(
- from_airport="LAX",
- to_airport="JFK",
- date=get_future_date(30),
+ params = FlightSearchParams(
+ origin="LAX",
+ destination="JFK",
+ departure_date=get_future_date(30),
return_date=get_future_date(37),
- time_range="8-20",
+ departure_window="8-20",
airlines=["AA", "DL"],
- seat_class="BUSINESS",
- stops="NON_STOP",
+ cabin_class="BUSINESS",
+ max_stops="NON_STOP",
sort_by="DURATION",
)
@@ -67,23 +67,23 @@ class TestMCPServer:
assert "count" in result
assert isinstance(result["flights"], list)
- def test_search_cheap_flights_one_way(self):
- """Test one-way cheap flight search."""
+ def test_search_dates_one_way(self):
+ """Test one-way date search."""
start_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
end_date = (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d")
- params = CheapFlightSearchRequest(
- from_airport="JFK",
- to_airport="LHR",
- from_date=start_date,
- to_date=end_date,
- round_trip=False,
- seat_class="ECONOMY",
- stops="ANY",
+ params = DateSearchParams(
+ origin="JFK",
+ destination="LHR",
+ start_date=start_date,
+ end_date=end_date,
+ is_round_trip=False,
+ cabin_class="ECONOMY",
+ max_stops="ANY",
sort_by_price=True,
)
- result = search_cheap_flights.fn(params)
+ result = search_dates.fn(params)
assert isinstance(result, dict)
assert "success" in result
@@ -96,27 +96,26 @@ class TestMCPServer:
assert "date_range" in result
assert isinstance(result["dates"], list)
- def test_search_cheap_flights_round_trip(self):
- """Test round-trip cheap flight search."""
+ def test_search_dates_round_trip(self):
+ """Test round-trip date search."""
start_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
end_date = (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d")
- params = CheapFlightSearchRequest(
- from_airport="LAX",
- to_airport="MIA",
- from_date=start_date,
- to_date=end_date,
- duration=7,
- round_trip=True,
+ params = DateSearchParams(
+ origin="LAX",
+ destination="MIA",
+ start_date=start_date,
+ end_date=end_date,
+ trip_duration=7,
+ is_round_trip=True,
airlines=["AA", "B6"],
- seat_class="PREMIUM_ECONOMY",
- stops="ONE_STOP",
- time_range="6-22",
- days_of_week=["friday", "saturday"],
+ cabin_class="PREMIUM_ECONOMY",
+ max_stops="ONE_STOP",
+ departure_window="6-22",
sort_by_price=True,
)
- result = search_cheap_flights.fn(params)
+ result = search_dates.fn(params)
assert isinstance(result, dict)
assert "success" in result
@@ -132,8 +131,8 @@ class TestMCPServer:
def test_invalid_airport_code(self):
"""Test error handling for invalid airport code."""
- params = FlightSearchRequest(
- from_airport="INVALID", to_airport="LHR", date=get_future_date(30)
+ params = FlightSearchParams(
+ origin="INVALID", destination="LHR", departure_date=get_future_date(30)
)
result = search_flights.fn(params)
@@ -141,16 +140,16 @@ class TestMCPServer:
assert isinstance(result, dict)
assert result["success"] is False
assert "error" in result
- assert "Invalid parameter value" in result["error"]
+ assert "Invalid airport code" in result["error"]
assert result["flights"] == []
- def test_invalid_time_range(self):
- """Test error handling for invalid time range."""
- params = FlightSearchRequest(
- from_airport="JFK",
- to_airport="LHR",
- date=get_future_date(30),
- time_range="invalid-time",
+ def test_invalid_departure_window(self):
+ """Test error handling for invalid departure window."""
+ params = FlightSearchParams(
+ origin="JFK",
+ destination="LHR",
+ departure_date=get_future_date(30),
+ departure_window="invalid-time",
)
result = search_flights.fn(params)
@@ -158,16 +157,16 @@ class TestMCPServer:
assert isinstance(result, dict)
assert result["success"] is False
assert "error" in result
- assert "Invalid time range format" in result["error"]
+ assert "time range" in result["error"].lower()
assert result["flights"] == []
- def test_invalid_seat_class(self):
- """Test error handling for invalid seat class."""
- params = FlightSearchRequest(
- from_airport="JFK",
- to_airport="LHR",
- date=get_future_date(30),
- seat_class="INVALID_CLASS",
+ def test_invalid_cabin_class(self):
+ """Test error handling for invalid cabin class."""
+ params = FlightSearchParams(
+ origin="JFK",
+ destination="LHR",
+ departure_date=get_future_date(30),
+ cabin_class="INVALID_CLASS",
)
result = search_flights.fn(params)
@@ -175,16 +174,16 @@ class TestMCPServer:
assert isinstance(result, dict)
assert result["success"] is False
assert "error" in result
- assert "Invalid parameter value" in result["error"]
+ assert "cabin_class" in result["error"].lower()
assert result["flights"] == []
def test_invalid_max_stops(self):
"""Test error handling for invalid max stops."""
- params = FlightSearchRequest(
- from_airport="JFK",
- to_airport="LHR",
- date=get_future_date(30),
- stops="INVALID_STOPS",
+ params = FlightSearchParams(
+ origin="JFK",
+ destination="LHR",
+ departure_date=get_future_date(30),
+ max_stops="INVALID_STOPS",
)
result = search_flights.fn(params)
@@ -192,15 +191,15 @@ class TestMCPServer:
assert isinstance(result, dict)
assert result["success"] is False
assert "error" in result
- assert "Invalid parameter value" in result["error"]
+ assert "max_stops" in result["error"].lower()
assert result["flights"] == []
def test_invalid_airline_code(self):
"""Test error handling for invalid airline code."""
- params = FlightSearchRequest(
- from_airport="JFK",
- to_airport="LHR",
- date=get_future_date(30),
+ params = FlightSearchParams(
+ origin="JFK",
+ destination="LHR",
+ departure_date=get_future_date(30),
airlines=["INVALID_AIRLINE"],
)
@@ -209,38 +208,36 @@ class TestMCPServer:
assert isinstance(result, dict)
assert result["success"] is False
assert "error" in result
- assert "Invalid airline code" in result["error"]
+ assert "airline" in result["error"].lower()
assert result["flights"] == []
def test_flight_search_params_validation(self):
"""Test FlightSearchParams validation."""
- # Valid params
future_date = get_future_date(30)
- params = FlightSearchRequest(from_airport="JFK", to_airport="LHR", date=future_date)
- assert params.from_airport == "JFK"
- assert params.to_airport == "LHR"
- assert params.date == future_date
- assert params.seat_class == "ECONOMY" # default
- assert params.stops == "ANY" # default
+ params = FlightSearchParams(origin="JFK", destination="LHR", departure_date=future_date)
+ assert params.origin == "JFK"
+ assert params.destination == "LHR"
+ assert params.departure_date == future_date
+ assert params.cabin_class == "ECONOMY" # default
+ assert params.max_stops == "ANY" # default
assert params.sort_by == "CHEAPEST" # default
- def test_cheap_flight_search_params_validation(self):
- """Test CheapFlightSearchParams validation."""
- # Valid params
- from_date = get_future_date(30)
- to_date = get_future_date(60)
- params = CheapFlightSearchRequest(
- from_airport="JFK",
- to_airport="LHR",
- from_date=from_date,
- to_date=to_date,
+ def test_date_search_params_validation(self):
+ """Test DateSearchParams validation."""
+ start_date = get_future_date(30)
+ end_date = get_future_date(60)
+ params = DateSearchParams(
+ origin="JFK",
+ destination="LHR",
+ start_date=start_date,
+ end_date=end_date,
)
- assert params.from_airport == "JFK"
- assert params.to_airport == "LHR"
- assert params.from_date == from_date
- assert params.to_date == to_date
- assert params.duration == 3 # default
- assert params.round_trip is False # default
- assert params.seat_class == "ECONOMY" # default
- assert params.stops == "ANY" # default
+ assert params.origin == "JFK"
+ assert params.destination == "LHR"
+ assert params.start_date == start_date
+ assert params.end_date == end_date
+ assert params.trip_duration == 3 # default
+ assert params.is_round_trip is False # default
+ assert params.cabin_class == "ECONOMY" # default
+ assert params.max_stops == "ANY" # default
assert params.sort_by_price is False # default
diff --git a/tests/search/test_search_flights.py b/tests/search/test_search_flights.py
index 7a8cabd..0a05069 100644
--- a/tests/search/test_search_flights.py
+++ b/tests/search/test_search_flights.py
@@ -3,6 +3,7 @@
from datetime import datetime, timedelta
import pytest
+from tenacity import retry, stop_after_attempt, wait_exponential
from fli.models import (
Airport,
@@ -17,6 +18,15 @@ from fli.models.google_flights.base import TripType
from fli.search import SearchFlights
+@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10), reraise=True)
+def search_with_retry(search: SearchFlights, search_params):
+ """Search with retry logic for flaky API responses."""
+ results = search.search(search_params)
+ if not results:
+ raise ValueError("Empty results, retrying...")
+ return results
+
+
@pytest.fixture
def search():
"""Create a reusable Search instance."""
@@ -234,7 +244,7 @@ def test_round_trip_with_selected_outbound(search, round_trip_search_params):
def test_round_trip_result_structure(search, search_params_fixture, request):
"""Test the structure of round trip search results with different parameters."""
search_params = request.getfixturevalue(search_params_fixture)
- results = search.search(search_params)
+ results = search_with_retry(search, search_params)
assert isinstance(results, list)
assert len(results) > 0
diff --git a/uv.lock b/uv.lock
index 8582397..33e6fb8 100644
--- a/uv.lock
+++ b/uv.lock
@@ -567,7 +567,7 @@ wheels = [
[[package]]
name = "flights"
-version = "0.6.0"
+version = "0.7.0"
source = { editable = "." }
dependencies = [
{ name = "curl-cffi" },
@@ -575,6 +575,7 @@ dependencies = [
{ name = "fastmcp" },
{ name = "httpx" },
{ name = "pandas" },
+ { name = "plotext" },
{ name = "pydantic" },
{ name = "python-dotenv" },
{ name = "ratelimit" },
@@ -604,6 +605,7 @@ requires-dist = [
{ name = "mkdocs-material", extras = ["imaging"], marker = "extra == 'dev'", specifier = ">=9.5.49" },
{ name = "mkdocstrings", extras = ["python"], marker = "extra == 'dev'", specifier = ">=0.27.0" },
{ name = "pandas", specifier = ">=2.2.3" },
+ { name = "plotext", specifier = ">=5.3.2" },
{ name = "pydantic", specifier = ">=2.10.4" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.3.4" },
{ name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.25.2" },
@@ -1536,6 +1538,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/fe/39/979e8e21520d4e47a0bbe349e2713c0aac6f3d853d0e5b34d76206c439aa/platformdirs-4.3.8-py3-none-any.whl", hash = "sha256:ff7059bb7eb1179e2685604f4aaf157cfd9535242bd23742eadc3c13542139b4", size = 18567 },
]
+[[package]]
+name = "plotext"
+version = "5.3.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c9/d7/f75f397af966fe252d0d34ffd3cae765317fce2134f925f95e7d6725d1ce/plotext-5.3.2.tar.gz", hash = "sha256:52d1e932e67c177bf357a3f0fe6ce14d1a96f7f7d5679d7b455b929df517068e", size = 61967 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f6/1e/12fe7c40cd2099a1f454518754ed229b01beaf3bbb343127f0cc13ce6c22/plotext-5.3.2-py3-none-any.whl", hash = "sha256:394362349c1ddbf319548cfac17ca65e6d5dfc03200c40dfdc0503b3e95a2283", size = 64047 },
+]
+
[[package]]
name = "pluggy"
version = "1.6.0"