diff --git a/server/src/nest/integrations/airtrail.mcp.ts b/server/src/nest/integrations/airtrail.mcp.ts new file mode 100644 index 000000000..43c272abb --- /dev/null +++ b/server/src/nest/integrations/airtrail.mcp.ts @@ -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, + }); + } +} diff --git a/server/src/nest/integrations/airtrail.module.ts b/server/src/nest/integrations/airtrail.module.ts index 19ed7bd90..a9fbc8a4e 100644 --- a/server/src/nest/integrations/airtrail.module.ts +++ b/server/src/nest/integrations/airtrail.module.ts @@ -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 {} diff --git a/server/src/nest/reservation-import/reservation-import.mcp.ts b/server/src/nest/reservation-import/reservation-import.mcp.ts new file mode 100644 index 000000000..3b67928e8 --- /dev/null +++ b/server/src/nest/reservation-import/reservation-import.mcp.ts @@ -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'); + } + } +} diff --git a/server/src/nest/reservation-import/reservation-import.module.ts b/server/src/nest/reservation-import/reservation-import.module.ts index 7502a6b2c..2fc52d1d3 100644 --- a/server/src/nest/reservation-import/reservation-import.module.ts +++ b/server/src/nest/reservation-import/reservation-import.module.ts @@ -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 {} diff --git a/server/tests/unit/mcp/tools-airtrail.test.ts b/server/tests/unit/mcp/tools-airtrail.test.ts new file mode 100644 index 000000000..1d2e975af --- /dev/null +++ b/server/tests/unit/mcp/tools-airtrail.test.ts @@ -0,0 +1,481 @@ +/** + * Unit tests for the AirTrail import pair: AirtrailMcp.list_airtrail_flights + * (mirrors GET /api/integrations/airtrail/flights) and + * ReservationImportMcp.import_airtrail_flights (mirrors + * POST /api/trips/:tripId/reservations/import/airtrail). + * + * The AirTrail instance is the only thing stubbed: the credentials are read out + * of the real users row, the mapper and the dedupe run for real, and the + * reservations land in the test DB. + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; + +const { testDb, dbMock } = vi.hoisted(() => { + const Database = require('better-sqlite3'); + const db = new Database(':memory:'); + db.exec('PRAGMA journal_mode = WAL'); + db.exec('PRAGMA foreign_keys = ON'); + db.exec('PRAGMA busy_timeout = 5000'); + const mock = { + db, + closeDb: () => {}, + reinitialize: () => {}, + getPlaceWithTags: () => null, + canAccessTrip: (tripId: any, userId: number) => + db.prepare(`SELECT t.id, t.user_id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)`).get(userId, tripId, userId), + isOwner: (tripId: any, userId: number) => + !!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId), + }; + return { testDb: db, dbMock: mock }; +}); + +vi.mock('../../../src/db/database', () => dbMock); +vi.mock('../../../src/config', () => ({ + JWT_SECRET: 'test-jwt-secret-for-trek-testing-only', + ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2', + updateJwtSecret: () => {}, +})); + +const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() })); +vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock })); + +import { createTables } from '../../../src/db/schema'; +import { runMigrations } from '../../../src/db/migrations'; +import { resetTestDb, setAddonEnabled } from '../../helpers/test-db'; +import { createUser, createTrip, addTripMember } from '../../helpers/factories'; +import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness'; +import { ADDON_IDS } from '../../../src/addons'; +import { AirtrailClient, AirtrailRequestError, type AirtrailFlightRaw } from '../../../src/nest/integrations/airtrail.client'; +import { AirtrailImportService } from '../../../src/nest/integrations/airtrail-import.service'; +import { PermissionsService } from '../../../src/nest/permissions/permissions.service'; +import { DatabaseService } from '../../../src/nest/database/database.service'; + +// The permissions cache is module-scoped, so a write through any instance is +// what the tool's own checkPermission call reads back. +const permissionsService = new PermissionsService(new DatabaseService(testDb)); +const savePermissions = permissionsService.savePermissions.bind(permissionsService); + +// The registry builds its own AirtrailClient per harness, so the stub goes on +// the prototype. Everything below listFlights (creds, mapper, dedupe) is real. +const listFlightsMock = vi.spyOn(AirtrailClient.prototype, 'listFlights'); + +beforeAll(() => { + createTables(testDb); + runMigrations(testDb); +}); + +beforeEach(() => { + resetTestDb(testDb); + broadcastMock.mockClear(); + listFlightsMock.mockReset(); + listFlightsMock.mockResolvedValue([]); + delete process.env.DEMO_MODE; + // resetTestDb leaves the addons table alone, and both tools are gated on the + // airtrail addon, so every case restates the toggle it needs. + setAddonEnabled(testDb, ADDON_IDS.AIRTRAIL, true); + savePermissions({ reservation_edit: 'trip_member' }); +}); + +afterAll(() => { + testDb.close(); +}); + +async function withHarness(userId: number, fn: (h: McpHarness) => Promise, scopes: string[] | null = null) { + const h = await createMcpHarness({ userId, withResources: false, scopes }); + try { await fn(h); } finally { await h.cleanup(); } +} + +/** The stored connection, plaintext key: decrypt_api_key passes legacy plaintext straight through. */ +function connectAirtrail(userId: number, url = 'https://airtrail.example.com') { + testDb.prepare('UPDATE users SET airtrail_url = ?, airtrail_api_key = ? WHERE id = ?').run(url, 'plain-test-key', userId); +} + +const ZRH = { id: 1, icao: 'LSZH', iata: 'ZRH', name: 'Zurich', lat: 47.458, lon: 8.548, tz: 'Europe/Zurich', country: 'CH' }; +const FRA = { id: 2, icao: 'EDDF', iata: 'FRA', name: 'Frankfurt', lat: 50.033, lon: 8.571, tz: 'Europe/Berlin', country: 'DE' }; +const JFK = { id: 3, icao: 'KJFK', iata: 'JFK', name: 'New York JFK', lat: 40.641, lon: -73.778, tz: 'America/New_York', country: 'US' }; + +function flight(overrides: Partial & { id: number }): AirtrailFlightRaw { + return { + from: ZRH, + to: FRA, + date: '2026-09-10', + datePrecision: 'day', + departure: '2026-09-10T06:00:00Z', + arrival: '2026-09-10T07:10:00Z', + departureScheduled: null, + arrivalScheduled: null, + airline: { icao: 'DLH', iata: 'LH', name: 'Lufthansa' }, + flightNumber: 'LH1201', + aircraft: { icao: 'A320' }, + aircraftReg: 'D-AIZA', + note: null, + seats: [{ userId: 'u1', guestName: null, seat: null, seatNumber: '14A', seatClass: 'economy' }], + ...overrides, + }; +} + +function reservationRows(tripId: number) { + return testDb.prepare( + 'SELECT id, title, type, external_source, external_id, external_owner_user_id, sync_enabled, metadata FROM reservations WHERE trip_id = ? ORDER BY id', + ).all(tripId) as { + id: number; title: string; type: string; external_source: string | null; external_id: string | null; + external_owner_user_id: number | null; sync_enabled: number | null; metadata: string | null; + }[]; +} + +// --------------------------------------------------------------------------- +// list_airtrail_flights +// --------------------------------------------------------------------------- + +describe('Tool: list_airtrail_flights', () => { + it('returns the caller flights, normalized and oldest departure first', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + listFlightsMock.mockResolvedValue([ + flight({ id: 22, date: '2026-09-20', departure: '2026-09-20T06:00:00Z', flightNumber: 'LH400', from: FRA, to: JFK }), + flight({ id: 11 }), + ]); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ name: 'list_airtrail_flights', arguments: {} }); + expect(result.isError).toBeFalsy(); + const data = parseToolResult(result) as any; + expect(data.flights.map((f: any) => f.id)).toEqual(['11', '22']); + expect(data.total).toBe(2); + expect(data.truncated).toBe(false); + expect(data.flights[0]).toMatchObject({ + id: '11', fromCode: 'ZRH', toCode: 'FRA', airline: 'Lufthansa', flightNumber: 'LH1201', seatClass: 'economy', + }); + }); + + // The stored connection is what reaches the client, so a tool can only ever + // read the caller's own AirTrail account. + expect(listFlightsMock).toHaveBeenCalledWith({ + baseUrl: 'https://airtrail.example.com', apiKey: 'plain-test-key', allowInsecureTls: false, + }); + }); + + it('narrows to a date window and keeps undated flights', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + listFlightsMock.mockResolvedValue([ + flight({ id: 1, date: '2026-08-01', departure: '2026-08-01T06:00:00Z' }), + flight({ id: 2, date: '2026-09-10', departure: null }), + flight({ id: 3, date: '2026-10-01', departure: '2026-10-01T06:00:00Z' }), + flight({ id: 4, date: null, departure: null, arrival: null }), + flight({ id: 5, date: null, departure: null, arrival: null }), + flight({ id: 6 }), + flight({ id: 7 }), + ]); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'list_airtrail_flights', + arguments: { from: '2026-09-01', to: '2026-09-30' }, + }); + const data = parseToolResult(result) as any; + // Dated first in departure order (6 and 7 share an instant and keep their + // input order), then the two that carry no date at all. + expect(data.flights.map((f: any) => f.id)).toEqual(['2', '6', '7', '4', '5']); + expect(data.total).toBe(5); + }); + }); + + it('falls back to its own wording when AirTrail fails without a message', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + listFlightsMock.mockRejectedValue(new Error('')); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ name: 'list_airtrail_flights', arguments: {} }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toBe('Could not load AirTrail flights'); + }); + }); + + it('caps the result and says it was truncated', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + listFlightsMock.mockResolvedValue( + Array.from({ length: 5 }, (_, i) => flight({ id: i + 1, departure: `2026-09-1${i}T06:00:00Z` })), + ); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ name: 'list_airtrail_flights', arguments: { limit: 2 } }); + const data = parseToolResult(result) as any; + expect(data.flights.map((f: any) => f.id)).toEqual(['1', '2']); + expect(data.total).toBe(5); + expect(data.truncated).toBe(true); + }); + }); + + it('reports an unconnected account instead of an empty list', async () => { + const { user } = createUser(testDb); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ name: 'list_airtrail_flights', arguments: {} }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('AirTrail is not connected'); + }); + expect(listFlightsMock).not.toHaveBeenCalled(); + }); + + it('passes an upstream failure through as the tool error', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + listFlightsMock.mockRejectedValue(new AirtrailRequestError('AirTrail list failed (HTTP 500)', 500)); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ name: 'list_airtrail_flights', arguments: {} }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('AirTrail list failed (HTTP 500)'); + }); + }); + + it('is hidden while the airtrail addon is off', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + setAddonEnabled(testDb, ADDON_IDS.AIRTRAIL, false); + + await withHarness(user.id, async (h) => { + const names = (await h.client.listTools()).tools.map(t => t.name); + expect(names).not.toContain('list_airtrail_flights'); + const result = await h.client.callTool({ name: 'list_airtrail_flights', arguments: {} }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('not found'); + }); + }); + + it('rides reservations:read and is hidden from a token without it', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + + await withHarness(user.id, async (h) => { + expect((await h.client.listTools()).tools.map(t => t.name)).toContain('list_airtrail_flights'); + }, ['reservations:read']); + + await withHarness(user.id, async (h) => { + expect((await h.client.listTools()).tools.map(t => t.name)).not.toContain('list_airtrail_flights'); + }, ['places:read']); + }); +}); + +// --------------------------------------------------------------------------- +// import_airtrail_flights +// --------------------------------------------------------------------------- + +describe('Tool: import_airtrail_flights', () => { + it('imports the listed flights as linked flight bookings', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + const trip = createTrip(testDb, user.id, { start_date: '2026-09-10', end_date: '2026-09-12' }); + listFlightsMock.mockResolvedValue([flight({ id: 11 }), flight({ id: 12, flightNumber: 'LH1202' })]); + + await withHarness(user.id, async (h) => { + // The ids the list tool hands back are exactly what the import tool takes. + const listed = parseToolResult(await h.client.callTool({ name: 'list_airtrail_flights', arguments: {} })) as any; + const result = await h.client.callTool({ + name: 'import_airtrail_flights', + arguments: { tripId: trip.id, flightIds: listed.flights.map((f: any) => f.id) }, + }); + expect(result.isError).toBeFalsy(); + const data = parseToolResult(result) as any; + expect([...data.imported].sort()).toEqual(['11', '12']); + expect(data.skipped).toEqual([]); + }); + + const rows = reservationRows(trip.id); + expect(rows).toHaveLength(2); + expect(rows[0]).toMatchObject({ + title: 'LH1201', type: 'flight', external_source: 'airtrail', external_id: '11', + external_owner_user_id: user.id, sync_enabled: 1, + }); + expect(broadcastMock).toHaveBeenCalledTimes(2); + expect(broadcastMock.mock.calls[0][1]).toBe('reservation:created'); + }); + + it('skips a flight that is already linked to the trip', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + const trip = createTrip(testDb, user.id, { start_date: '2026-09-10', end_date: '2026-09-12' }); + listFlightsMock.mockResolvedValue([flight({ id: 11 })]); + + await withHarness(user.id, async (h) => { + await h.client.callTool({ name: 'import_airtrail_flights', arguments: { tripId: trip.id, flightIds: ['11'] } }); + const again = await h.client.callTool({ name: 'import_airtrail_flights', arguments: { tripId: trip.id, flightIds: ['11'] } }); + const data = parseToolResult(again) as any; + expect(data.imported).toEqual([]); + expect(data.skipped).toEqual([{ flightId: '11', reason: 'already-imported' }]); + }); + expect(reservationRows(trip.id)).toHaveLength(1); + }); + + it('joins a connection into one multi-leg booking detached from sync', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + const trip = createTrip(testDb, user.id, { start_date: '2026-09-10', end_date: '2026-09-12' }); + listFlightsMock.mockResolvedValue([ + flight({ id: 11 }), + flight({ + id: 12, from: FRA, to: JFK, flightNumber: 'LH400', + departure: '2026-09-10T09:00:00Z', arrival: '2026-09-10T18:00:00Z', + }), + ]); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'import_airtrail_flights', + arguments: { tripId: trip.id, flightIds: ['11', '12'], connections: [['11', '12']] }, + }); + const data = parseToolResult(result) as any; + expect(data.imported).toEqual(['11', '12']); + }); + + const rows = reservationRows(trip.id); + expect(rows).toHaveLength(1); + expect(rows[0].sync_enabled).toBe(0); + expect(JSON.parse(rows[0].metadata ?? '{}').airtrail_ids).toEqual(['11', '12']); + }); + + it('refuses a connection naming a flight that is not being imported', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + const trip = createTrip(testDb, user.id, { start_date: '2026-09-10', end_date: '2026-09-12' }); + listFlightsMock.mockResolvedValue([flight({ id: 11 })]); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'import_airtrail_flights', + arguments: { tripId: trip.id, flightIds: ['11'], connections: [['11', '99']] }, + }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('flight 99'); + }); + expect(reservationRows(trip.id)).toHaveLength(0); + expect(listFlightsMock).not.toHaveBeenCalled(); + }); + + it('refuses more than fifty flights in one call', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + const trip = createTrip(testDb, user.id, { start_date: '2026-09-10', end_date: '2026-09-12' }); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'import_airtrail_flights', + arguments: { tripId: trip.id, flightIds: Array.from({ length: 51 }, (_, i) => String(i + 1)) }, + }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('at most 50'); + }); + expect(reservationRows(trip.id)).toHaveLength(0); + expect(listFlightsMock).not.toHaveBeenCalled(); + }); + + it('reports an unconnected account', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2026-09-10', end_date: '2026-09-12' }); + + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'import_airtrail_flights', + arguments: { tripId: trip.id, flightIds: ['11'] }, + }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('AirTrail is not connected'); + }); + expect(reservationRows(trip.id)).toHaveLength(0); + }); + + it('falls back to its own wording when the import fails without a message', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + const trip = createTrip(testDb, user.id, { start_date: '2026-09-10', end_date: '2026-09-12' }); + const importMock = vi.spyOn(AirtrailImportService.prototype, 'importAirtrailFlights') + .mockRejectedValue(new Error('')); + + try { + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'import_airtrail_flights', + arguments: { tripId: trip.id, flightIds: ['11'] }, + }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toBe('AirTrail import failed'); + }); + } finally { + // Nothing auto-restores spies in this config, so an escaped stub would + // silently answer for every later case in the file. + importMock.mockRestore(); + } + }); + + it('enforces demo, trip access and the reservation permission', async () => { + const { user: owner } = createUser(testDb); + const { user: demo } = createUser(testDb, { email: 'demo@trek.app' }); + const { user: stranger } = createUser(testDb); + const { user: member } = createUser(testDb); + const trip = createTrip(testDb, owner.id, { start_date: '2026-09-10', end_date: '2026-09-12' }); + addTripMember(testDb, trip.id, demo.id); + addTripMember(testDb, trip.id, member.id); + for (const u of [owner, demo, stranger, member]) connectAirtrail(u.id); + listFlightsMock.mockResolvedValue([flight({ id: 11 })]); + + process.env.DEMO_MODE = 'true'; + await withHarness(demo.id, async (h) => { + const result = await h.client.callTool({ name: 'import_airtrail_flights', arguments: { tripId: trip.id, flightIds: ['11'] } }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('demo mode'); + }); + delete process.env.DEMO_MODE; + + await withHarness(stranger.id, async (h) => { + const result = await h.client.callTool({ name: 'import_airtrail_flights', arguments: { tripId: trip.id, flightIds: ['11'] } }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('access denied'); + }); + + savePermissions({ reservation_edit: 'trip_owner' }); + await withHarness(member.id, async (h) => { + const result = await h.client.callTool({ name: 'import_airtrail_flights', arguments: { tripId: trip.id, flightIds: ['11'] } }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('permission'); + }); + + expect(reservationRows(trip.id)).toHaveLength(0); + expect(broadcastMock).not.toHaveBeenCalled(); + expect(listFlightsMock).not.toHaveBeenCalled(); + }); + + it('is hidden while the airtrail addon is off', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + const trip = createTrip(testDb, user.id, { start_date: '2026-09-10', end_date: '2026-09-12' }); + setAddonEnabled(testDb, ADDON_IDS.AIRTRAIL, false); + + await withHarness(user.id, async (h) => { + const names = (await h.client.listTools()).tools.map(t => t.name); + expect(names).not.toContain('import_airtrail_flights'); + const result = await h.client.callTool({ + name: 'import_airtrail_flights', + arguments: { tripId: trip.id, flightIds: ['11'] }, + }); + expect(result.isError).toBe(true); + expect((result.content as any)[0].text).toContain('not found'); + }); + expect(reservationRows(trip.id)).toHaveLength(0); + }); + + it('rides reservations:write and is hidden from a read-only token', async () => { + const { user } = createUser(testDb); + connectAirtrail(user.id); + + await withHarness(user.id, async (h) => { + expect((await h.client.listTools()).tools.map(t => t.name)).toContain('import_airtrail_flights'); + }, ['reservations:write']); + + await withHarness(user.id, async (h) => { + expect((await h.client.listTools()).tools.map(t => t.name)).not.toContain('import_airtrail_flights'); + }, ['reservations:read']); + }); +});