mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
feat(mcp): import flights from AirTrail
TREK's own bulk travel-history importer, and the closest thing in the product to what this whole branch is about. Both halves are server-side JSON, so neither was ever browser-bound; they simply had no tools. The list tool's output carries what the import tool needs, so a model can run the pair without a detour through the UI.
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
import {
|
||||
McpController, Tool, type McpContext,
|
||||
TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
|
||||
errorResult, ok,
|
||||
} from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import type { AirtrailFlight } from '@trek/shared';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { AirtrailService } from './airtrail.service';
|
||||
|
||||
/** Same gate as the controller's @RequireAddon(ADDON_IDS.AIRTRAIL): no addon, no tool. */
|
||||
const airtrailAddonOn = addonGate(ADDON_IDS.AIRTRAIL);
|
||||
|
||||
/**
|
||||
* An AirTrail history grows for years, and the whole of it in one tool result
|
||||
* is context a model pays for on every turn. The picker in the browser can
|
||||
* afford the full list because a human scrolls it; a tool caller gets a window
|
||||
* and is told when the window cut something off.
|
||||
*/
|
||||
const DEFAULT_FLIGHT_LIMIT = 100;
|
||||
const MAX_FLIGHT_LIMIT = 500;
|
||||
|
||||
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Use an ISO date, YYYY-MM-DD');
|
||||
|
||||
/** The calendar day a flight belongs to, preferring AirTrail's own `date` over the departure instant. */
|
||||
function flightDate(flight: AirtrailFlight): string | null {
|
||||
return flight.date ?? (flight.departure ? flight.departure.slice(0, 10) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Chronological, undated flights last. The window and the cap are only
|
||||
* meaningful over a stable order, and AirTrail returns its list in whatever
|
||||
* order its query produced.
|
||||
*/
|
||||
function byDeparture(a: AirtrailFlight, b: AirtrailFlight): number {
|
||||
const left = a.departure ?? a.date;
|
||||
const right = b.departure ?? b.date;
|
||||
if (!left && !right) return 0;
|
||||
if (!left) return 1;
|
||||
if (!right) return -1;
|
||||
return left < right ? -1 : left > right ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* AirTrail MCP surface: the read half of the flight import, mirroring
|
||||
* GET /api/integrations/airtrail/flights (airtrail.controller.ts). Same
|
||||
* per-user scoping the route has (the flights are fetched with the caller's
|
||||
* own stored key, so a tool can only ever see that caller's own history), and
|
||||
* the same addon gate, expressed as `when:` so a disabled addon hides the tool
|
||||
* instead of answering it.
|
||||
*
|
||||
* The write half is not here: the import is trip-scoped and lives on the
|
||||
* /api/trips/:tripId/reservations/import prefix, so its tool sits in
|
||||
* reservation-import/ with the controller that owns that route.
|
||||
*
|
||||
* The connection settings routes (GET/PUT settings, status, test, sync) stay
|
||||
* off MCP on purpose: they take an API key, and the key is exactly the thing
|
||||
* settings:write promises never to touch.
|
||||
*/
|
||||
@McpController()
|
||||
export class AirtrailMcp {
|
||||
constructor(
|
||||
private readonly airtrail: AirtrailService,
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'list_airtrail_flights',
|
||||
description: 'List the flights in the caller\'s connected AirTrail account, which are the ones available to import into a trip. Each entry carries the id that import_airtrail_flights takes, plus route, times, airline and flight number, so call this first and pass the ids you picked to that tool. Use it for flights that have already been flown or booked and recorded in AirTrail; a flight that exists nowhere yet is created with create_transport instead. Narrow it with from/to to the trip window rather than pulling a whole flight history.',
|
||||
inputSchema: {
|
||||
from: isoDate.optional().describe('Only flights departing on or after this date'),
|
||||
to: isoDate.optional().describe('Only flights departing on or before this date'),
|
||||
limit: z.number().int().min(1).max(MAX_FLIGHT_LIMIT).optional()
|
||||
.describe(`Maximum flights to return, oldest departure first (default ${DEFAULT_FLIGHT_LIMIT}, max ${MAX_FLIGHT_LIMIT})`),
|
||||
},
|
||||
// Reads a remote AirTrail instance, not TREK's own database.
|
||||
annotations: TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
|
||||
// The flights are candidate bookings and the import writes reservations, so
|
||||
// the pair rides one group. There is no airtrail scope, and settings:read
|
||||
// covers preferences rather than travel data.
|
||||
access: { group: 'reservations', mode: 'read' },
|
||||
when: airtrailAddonOn,
|
||||
})
|
||||
async listAirtrailFlights(
|
||||
{ from, to, limit }: { from?: string; to?: string; limit?: number },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
let flights: AirtrailFlight[];
|
||||
try {
|
||||
flights = await this.airtrail.getFlightsForPicker(ctx.userId);
|
||||
} catch (err) {
|
||||
// The route dresses this as a 400 or a 502; a tool caller can act on the
|
||||
// sentence, which already says whether AirTrail is unconnected or unreachable.
|
||||
return errorResult((err as Error)?.message || 'Could not load AirTrail flights');
|
||||
}
|
||||
|
||||
// A flight with no date at all cannot be proven outside the window, and
|
||||
// dropping it would lose it silently, so it stays in and sorts last.
|
||||
const matched = flights.filter(flight => {
|
||||
const date = flightDate(flight);
|
||||
if (!date) return true;
|
||||
if (from && date < from) return false;
|
||||
if (to && date > to) return false;
|
||||
return true;
|
||||
}).sort(byDeparture);
|
||||
|
||||
const cap = limit ?? DEFAULT_FLIGHT_LIMIT;
|
||||
const page = matched.slice(0, cap);
|
||||
return ok({
|
||||
flights: page,
|
||||
total: matched.length,
|
||||
truncated: matched.length > page.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { AirtrailCoreModule } from './airtrail-core.module';
|
||||
import { AirtrailSyncService } from './airtrail-sync.service';
|
||||
import { AirtrailSyncJob } from './airtrail-sync.job';
|
||||
import { AirtrailImportService } from './airtrail-import.service';
|
||||
import { AirtrailMcp } from './airtrail.mcp';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
@@ -26,7 +27,7 @@ import { ReservationsModule } from '../reservations/reservations.module';
|
||||
@Module({
|
||||
imports: [AirtrailCoreModule, PermissionsModule, AddonsModule, AuditModule, ReservationsModule, SchedulingModule],
|
||||
controllers: [AirtrailController],
|
||||
providers: [AirtrailSyncService, AirtrailSyncJob, AirtrailImportService],
|
||||
providers: [AirtrailSyncService, AirtrailSyncJob, AirtrailImportService, AirtrailMcp],
|
||||
exports: [AirtrailSyncService, AirtrailImportService],
|
||||
})
|
||||
export class AirtrailModule {}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import {
|
||||
McpController, Tool, type McpContext,
|
||||
TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { airtrailImportSchema } from '@trek/shared';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import { AirtrailImportService } from '../integrations/airtrail-import.service';
|
||||
|
||||
/** The handler's own @RequireAddon(ADDON_IDS.AIRTRAIL), as an availability gate. */
|
||||
const airtrailAddonOn = addonGate(ADDON_IDS.AIRTRAIL);
|
||||
|
||||
/**
|
||||
* The picker sends whatever a human ticked; a model can name a hundred ids off
|
||||
* one hallucinated list, and each one becomes a reservation and a broadcast.
|
||||
* The same reasoning as MAX_MCP_TRIP_DAYS: the tool surface caps a bulk write
|
||||
* the REST route leaves open, and says how to continue.
|
||||
*/
|
||||
const MAX_MCP_AIRTRAIL_FLIGHTS = 50;
|
||||
|
||||
/**
|
||||
* MCP surface for /api/trips/:tripId/reservations/import.
|
||||
*
|
||||
* Only the AirTrail half is here. The booking-file routes on the same prefix
|
||||
* take an uploaded EML/PDF/PKPass body, and MCP has no file to hand them; the
|
||||
* job-status route is the recovery path for a client that missed a WebSocket
|
||||
* push, which a tool caller never has.
|
||||
*
|
||||
* The guard chain on the controller is AddonGuard, JwtAuthGuard,
|
||||
* TripAccessGuard plus @RequirePermission('reservation_edit'), so the tool runs
|
||||
* the same three checks in the same order: demo, trip access (the 404
|
||||
* equivalent), then the identical permission action.
|
||||
*/
|
||||
@McpController()
|
||||
export class ReservationImportMcp {
|
||||
constructor(
|
||||
private readonly airtrailImport: AirtrailImportService,
|
||||
private readonly db: DatabaseService,
|
||||
private readonly auth: AuthService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'import_airtrail_flights',
|
||||
description: 'Import flights from the caller\'s connected AirTrail account into a trip as flight bookings, keeping them linked to AirTrail for two-way sync. Get the ids from list_airtrail_flights first; this tool only accepts ids that account already holds, so it cannot invent a flight. Prefer it over create_transport whenever the flight is already recorded in AirTrail: the route, times, airline and aircraft come across without retyping. Flights already on the trip are reported as skipped rather than duplicated.',
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
flightIds: airtrailImportSchema.shape.flightIds
|
||||
.describe(`AirTrail flight ids from list_airtrail_flights, at most ${MAX_MCP_AIRTRAIL_FLIGHTS} per call`),
|
||||
connections: airtrailImportSchema.shape.connections
|
||||
.describe('Chains of the ids above to import as ONE multi-leg booking each, with the connection airports as layover stops, e.g. [["12","13"]] for a flight with one change. Every id in a chain must also be in flightIds. A chain whose legs do not actually connect is imported as separate flights instead.'),
|
||||
},
|
||||
// Creating the same flights twice does not duplicate them (the dedupe
|
||||
// reports them skipped), but a call still creates rows, and it reaches out
|
||||
// to the AirTrail instance to re-read the flights it is given.
|
||||
annotations: TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
|
||||
access: { group: 'reservations', mode: 'write' },
|
||||
when: airtrailAddonOn,
|
||||
})
|
||||
async importAirtrailFlights(
|
||||
{ tripId, flightIds, connections }: { tripId: number; flightIds: string[]; connections?: string[][] },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
|
||||
if (flightIds.length > MAX_MCP_AIRTRAIL_FLIGHTS) {
|
||||
return errorResult(
|
||||
`Too many flights in one call (${flightIds.length}). Import at most ${MAX_MCP_AIRTRAIL_FLIGHTS} at a time.`,
|
||||
);
|
||||
}
|
||||
|
||||
// The service quietly degrades a chain it cannot resolve to individual
|
||||
// imports, which is right for a picker that only ever sends ids it just
|
||||
// rendered. A model assembling the chain itself gets told instead, because
|
||||
// the silent version looks like a successful multi-leg import.
|
||||
const selected = new Set(flightIds);
|
||||
for (const chain of connections ?? []) {
|
||||
const stray = chain.find(id => !selected.has(id));
|
||||
if (stray !== undefined) {
|
||||
return errorResult(`Connection references flight ${stray}, which is not in flightIds.`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// socketId is undefined: there is no originating browser socket to spare
|
||||
// from the echo, so every member including the caller's own session gets
|
||||
// the reservation:created events the service broadcasts.
|
||||
const result = await this.airtrailImport.importAirtrailFlights(
|
||||
tripId, ctx.userId, flightIds, undefined, connections ?? [],
|
||||
);
|
||||
return ok(result);
|
||||
} catch (err) {
|
||||
return errorResult((err as Error)?.message || 'AirTrail import failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ReservationImportController } from './reservation-import.controller';
|
||||
import { ReservationImportMcp } from './reservation-import.mcp';
|
||||
import { BookingImportModule } from '../booking-import/booking-import.module';
|
||||
import { AirtrailModule } from '../integrations/airtrail.module';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
|
||||
/**
|
||||
* The one route prefix that turns something external into reservations.
|
||||
@@ -11,10 +14,15 @@ import { PermissionsModule } from '../permissions/permissions.module';
|
||||
* It owns the controller and nothing else: the file-upload pipeline stays in
|
||||
* booking-import/ and the AirTrail pipeline in integrations/, because those are
|
||||
* where their own domains live. What moved here is the HTTP surface they were
|
||||
* both declaring separately.
|
||||
* both declaring separately. ReservationImportMcp is the second surface over
|
||||
* the same prefix, so it lives with the controller for the same reason.
|
||||
*
|
||||
* AuthModule and McpSharedModule are the tool's demo check and its
|
||||
* permission/broadcast guards; neither is @Global, so both are named here.
|
||||
*/
|
||||
@Module({
|
||||
imports: [BookingImportModule, AirtrailModule, AddonsModule, PermissionsModule],
|
||||
imports: [BookingImportModule, AirtrailModule, AddonsModule, PermissionsModule, AuthModule, McpSharedModule],
|
||||
controllers: [ReservationImportController],
|
||||
providers: [ReservationImportMcp],
|
||||
})
|
||||
export class ReservationImportModule {}
|
||||
|
||||
Reference in New Issue
Block a user