Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

11.7 KB
Raw Blame
import { ADDON_IDS } from '../../addons';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import {
  McpController,
  Tool,
  TOOL_ANNOTATIONS_READONLY,
  TOOL_ANNOTATIONS_NON_IDEMPOTENT,
  ok,
  type McpContext,
} from '../../nest-mcp';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
import { RoadtripService } from './roadtrip.service';
import { idSchema, roadtripViaUpdateRequestSchema, type RoadtripViaUpdateRequest } from '@trek/shared';

import { z } from 'zod';

/**
 * The whole surface rides the road trip addon, the same way the controller does
 * (`@RequireAddon`). Without the gate the REST route answers 404 on an instance that
 * left the addon off while these four tools kept reading and writing vias, which is
 * exactly the parity the repo forbids breaking.
 */
const roadtripAddonOn = addonGate(ADDON_IDS.ROADTRIP);

/**
 * What a via on the drive into a booked night's hotel does, said on both tools that place
 * one. The planner refuses the click there with a sentence (`roadtrip.bookend.noVia`); a
 * tool stores what it is given, so the assistant has to hear before it reports a detour
 * that the calculation will not take.
 */
const BOOKEND_VIA_NOTE =
  'With roadtrip_hotel_bookends on, a via after the last stop of a day that ends at a booked night is kept but not used: the drive to the hotel keeps its own road, so calculate_roadtrip returns the same route. Add a stop there instead.';

/**
 * Road-trip via points over MCP, the same surface the REST routes expose (#1797).
 *
 * Parity is the point: the permission checked here is `day_edit`, the same action string
 * the controller demands, so an assistant can never do through a tool what a person
 * cannot do through the UI. Reads go through the same day-belongs-to-trip check, so a
 * valid day id from another trip is not reachable by way of one the caller can see.
 * The writes and their events are the service's use cases the routes call too; a tool
 * call has no socket of its own, so the tab that asked hears the change like everyone else.
 */
@McpController()
export class RoadtripMcp {
  constructor(
    private readonly roadtrip: RoadtripService,
    private readonly tripsRepo: TripAccessService,
    private readonly guards: McpToolGuardsService,
    readonly addons: AddonsService,
  ) {}

  @Tool({
    name: 'list_route_vias',
    description:
      "List the points a day's drive is routed through without stopping at them. These bend the route (a scenic road, a pass, avoiding a motorway) and are not stops on the itinerary.",
    inputSchema: {
      tripId: idSchema,
      dayId: idSchema.optional().describe('Omit to list the vias of every day of the trip'),
    },
    annotations: TOOL_ANNOTATIONS_READONLY,
    access: { group: 'trips', mode: 'read' },
    when: roadtripAddonOn,
  })
  async listVias({ tripId, dayId }: { tripId: number; dayId?: number }, ctx: McpContext) {
    if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
    if (dayId != null) {
      if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
      return ok({ vias: await this.roadtrip.listForDay(dayId) });
    }
    return ok({ vias: await this.roadtrip.listForTrip(tripId), tracks: await this.roadtrip.tracksForTrip(tripId) });
  }

  @Tool({
    name: 'add_route_via',
    description: `Make a day's drive pass through a point without stopping there: use it to send the route over a particular road or away from one. For somewhere the traveller actually stops, add a place and assign it to the day instead. ${BOOKEND_VIA_NOTE}`,
    inputSchema: {
      tripId: idSchema,
      dayId: idSchema,
      after_order_index: z.number().int().min(0).describe('Which stop of the day the via follows, counting from 0'),
      lat: z.number().min(-90).max(90),
      lng: z.number().min(-180).max(180),
    },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    access: { group: 'trips', mode: 'write' },
    when: roadtripAddonOn,
  })
  async addVia(
    {
      tripId,
      dayId,
      after_order_index,
      lat,
      lng,
    }: { tripId: number; dayId: number; after_order_index: number; lat: number; lng: number },
    ctx: McpContext,
  ) {
    if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
    const writer = await this.guards.tripWriter(tripId, ctx.userId);
    const via = await this.roadtrip.addVia(dayId, { after_order_index, lat, lng }, writer);
    return ok({ via });
  }

  @Tool({
    name: 'add_route_vias',
    description: `Lay a whole chain of via points on one day at once, so the drive follows a particular road for a stretch rather than being nudged at a single point. Use this when the shape comes from a line (a recorded track, a signed scenic route) and add_route_via when it is one detour. Pass replace_legs to clear the vias on those legs first; leave it out to add to what is already there, which is what leaves hand-placed detours on other legs alone. ${BOOKEND_VIA_NOTE}`,
    inputSchema: {
      tripId: idSchema,
      dayId: idSchema,
      vias: z
        .array(
          z.strictObject({
            after_order_index: z
              .number()
              .int()
              .min(0)
              .describe('Which stop of the day this via follows, counting from 0'),
            lat: z.number().min(-90).max(90),
            lng: z.number().min(-180).max(180),
          }),
        )
        .max(100)
        .describe('In the order the drive passes through them'),
      replace_legs: z
        .array(z.number().int().min(0))
        .max(100)
        .optional()
        .describe('Legs to clear before inserting, by the index of the stop they follow'),
      track: z
        .strictObject({
          place_id: idSchema.describe('The imported track this chain was fitted to, as its place id'),
          stray_km: z
            .number()
            .min(0)
            .max(40_000)
            .nullable()
            .optional()
            .describe('How far the fitted route still runs from the track at its worst point'),
        })
        .nullable()
        .optional()
        .describe(
          'Records which imported track the day now follows. Leave it out to keep whatever it followed before; pass null to say it follows nothing.',
        ),
    },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    access: { group: 'trips', mode: 'write' },
    when: roadtripAddonOn,
  })
  async addVias(
    {
      tripId,
      dayId,
      vias,
      replace_legs,
      track,
    }: {
      tripId: number;
      dayId: number;
      vias: { after_order_index: number; lat: number; lng: number }[];
      replace_legs?: number[];
      track?: { place_id: number; stray_km?: number | null } | null;
    },
    ctx: McpContext,
  ) {
    if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
    // The same check the REST route makes, in the same change: permission alone would let
    // a place id from another trip, or a place that is not a track at all, become this
    // day's label.
    if (track && !(await this.roadtrip.trackExists(track.place_id, tripId))) return noAccess();
    const writer = await this.guards.tripWriter(tripId, ctx.userId);
    const made = await this.roadtrip.addVias(tripId, dayId, { vias, replace_legs, track }, writer);
    return ok({ vias: made });
  }

  @Tool({
    name: 'reanchor_route_vias',
    description:
      "Re-pin a day's via points after its stops changed. A via records which stop it follows by position, so adding, removing or reordering a stop leaves every later via pointing at the wrong leg and the drive silently reverts to the road it was steered away from. Send the corrected positions for the whole day at once; ids left out keep the position they have.",
    inputSchema: {
      tripId: idSchema,
      dayId: idSchema,
      vias: z
        .array(
          z.strictObject({
            id: idSchema,
            after_order_index: z
              .number()
              .int()
              .min(0)
              .describe('Which stop of the day the via now follows, counting from 0'),
          }),
        )
        .max(500),
      remove: z
        .array(idSchema)
        .max(500)
        .optional()
        .describe(
          'Vias whose leg no longer exists at all — deleting the last stop of a day leaves the leg into it with nothing to sit on',
        ),
    },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    access: { group: 'trips', mode: 'write' },
    when: roadtripAddonOn,
  })
  async reanchorVias(
    {
      tripId,
      dayId,
      vias,
      remove,
    }: { tripId: number; dayId: number; vias: { id: number; after_order_index: number }[]; remove?: number[] },
    ctx: McpContext,
  ) {
    if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
    const writer = await this.guards.tripWriter(tripId, ctx.userId);
    const next = await this.roadtrip.reanchorVias(dayId, { vias, remove }, writer);
    return ok({ vias: next });
  }

  @Tool({
    name: 'remove_route_via',
    description: 'Remove a via point, letting the drive take the direct route again.',
    inputSchema: {
      tripId: idSchema,
      dayId: idSchema,
      viaId: idSchema,
    },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    access: { group: 'trips', mode: 'write' },
    when: roadtripAddonOn,
  })
  async removeVia({ tripId, dayId, viaId }: { tripId: number; dayId: number; viaId: number }, ctx: McpContext) {
    if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
    const writer = await this.guards.tripWriter(tripId, ctx.userId);
    if (!(await this.roadtrip.removeVia(dayId, viaId, writer))) return noAccess();
    return ok({ success: true });
  }

  @Tool({
    name: 'update_route_via',
    description:
      'Move an existing via point and optionally attach it to another outgoing leg of the same day. This is the same change as dragging a route handle. A via bends the route and does not add a stop or stay.',
    inputSchema: { tripId: idSchema, dayId: idSchema, viaId: idSchema, ...roadtripViaUpdateRequestSchema.shape },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    access: { group: 'trips', mode: 'write' },
    when: roadtripAddonOn,
  })
  async updateVia(input: RoadtripViaUpdateRequest & { tripId: number; dayId: number; viaId: number }, ctx: McpContext) {
    if (!(await this.tripsRepo.findAccessible(input.tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', input.tripId, ctx.userId))) return permissionDenied();
    if (!(await this.roadtrip.dayExists(input.dayId, input.tripId))) return noAccess();
    const writer = await this.guards.tripWriter(input.tripId, ctx.userId);
    const { lat, lng, after_order_index } = input;
    const via = await this.roadtrip.moveVia(input.dayId, input.viaId, { lat, lng, after_order_index }, writer);
    if (!via) return noAccess();
    return ok({ via });
  }
}