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.

19.1 KB
Raw Blame
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import {
  McpController,
  Tool,
  type McpContext,
  TOOL_ANNOTATIONS_READONLY,
  TOOL_ANNOTATIONS_WRITE,
  TOOL_ANNOTATIONS_DELETE,
  TOOL_ANNOTATIONS_NON_IDEMPOTENT,
  errorResult,
  ok,
} from '../../nest-mcp';
import { DaysService } from '../days/days.service';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { AssignmentsService } from './assignments.service';
import {
  idSchema,
  assignmentCreateRequestSchema,
  assignmentEndDayRequestSchema,
  assignmentStayRequestSchema,
  type AssignmentEndDayRequest,
  type AssignmentStayRequest,
} from '@trek/shared';

import { z } from 'zod';

/**
 * Assignment MCP surface — ported 1:1 from the legacy registrar in
 * src/mcp/tools/assignments.ts (identical names, descriptions, schemas,
 * annotations, error/payload shapes and broadcasts). The legacy `if (R)` /
 * `if (W)` registration gates on the 'places' scope group map to the
 * declarative access markers (resolved by trekMcpAccessPolicy); there is no
 * addon gate, so no `when`. The target-day check on move uses the injected
 * DaysService.getDay.
 */
@McpController()
export class AssignmentsMcp {
  constructor(
    private readonly assignments: AssignmentsService,
    private readonly days: DaysService,
    private readonly guards: McpToolGuardsService,
  ) {}

  @Tool({
    name: 'assign_place_to_day',
    description:
      'Assign a place to a specific day in a trip. For a multi-day tour, pass tourStageKey to put one of its stages on the day instead of the whole tour: the key of the stop the stage starts at, from the stage_stops list_tours gives (every stop but the last starts a stage). A stage is on one day at most, and a day holds a tour, or one of its stages, once.',
    inputSchema: {
      tripId: idSchema,
      dayId: idSchema,
      placeId: idSchema,
      notes: z.string().max(500).optional(),
      tourStageKey: assignmentCreateRequestSchema.shape.tour_stage_key.describe(
        'The key of the stop a stage of a multi-day tour starts at, to put that stage on the day instead of the whole tour',
      ),
    },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    access: { group: 'places', mode: 'write' },
  })
  async assignPlaceToDay(
    {
      tripId,
      dayId,
      placeId,
      notes,
      tourStageKey,
    }: { tripId: number; dayId: number; placeId: number; notes?: string; tourStageKey?: string },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.dayExists(dayId, tripId))) return errorResult('Day not found.');
    if (!(await this.assignments.placeExists(placeId, tripId))) return errorResult('Place not found.');
    const assignment = await this.assignments.createAssignment(dayId, placeId, notes || null, {
      ...(tourStageKey !== undefined ? { tourStageKey } : {}),
    });
    this.guards.safeBroadcast(tripId, 'assignment:created', { assignment });
    await this.assignments.reconcile(tripId);
    return ok({ assignment });
  }

  @Tool({
    name: 'set_assignment_end_day',
    description:
      'End the travel day after this visit and its stay. Applies only with daily travel times enabled. Pass false to follow the default again.',
    inputSchema: {
      tripId: idSchema,
      assignmentId: idSchema,
      ...assignmentEndDayRequestSchema.shape,
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    access: { group: 'places', mode: 'write' },
  })
  async setAssignmentEndDay(
    { tripId, assignmentId, end_day }: AssignmentEndDayRequest & { tripId: number; assignmentId: number },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.getAssignmentForTrip(assignmentId, tripId)))
      return errorResult('Assignment not found.');
    const assignment = await this.assignments.setEndDay(assignmentId, end_day);
    this.guards.safeBroadcast(tripId, 'assignment:updated', { assignment });
    return ok({ assignment });
  }

  @Tool({
    name: 'set_assignment_stay',
    description:
      'Set how long the road trip stands at this one visit, in minutes. Two visits of the same place keep their own stays: 0 drives past without stopping. Pass null to use the stay of the place (its duration_minutes) again.',
    inputSchema: {
      tripId: idSchema,
      assignmentId: idSchema,
      ...assignmentStayRequestSchema.shape,
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    access: { group: 'places', mode: 'write' },
  })
  async setAssignmentStay(
    { tripId, assignmentId, stay_minutes }: AssignmentStayRequest & { tripId: number; assignmentId: number },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.getAssignmentForTrip(assignmentId, tripId)))
      return errorResult('Assignment not found.');
    const assignment = await this.assignments.setStay(assignmentId, stay_minutes);
    this.guards.safeBroadcast(tripId, 'assignment:updated', { assignment });
    return ok({ assignment });
  }

  @Tool({
    name: 'unassign_place',
    description: 'Remove a place assignment from a day.',
    inputSchema: {
      tripId: idSchema,
      dayId: idSchema,
      assignmentId: idSchema,
    },
    annotations: TOOL_ANNOTATIONS_DELETE,
    access: { group: 'places', mode: 'write' },
  })
  async unassignPlace(
    { tripId, dayId, assignmentId }: { tripId: number; dayId: number; assignmentId: number },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.assignmentExistsInDay(assignmentId, dayId, tripId)))
      return errorResult('Assignment not found.');
    await this.assignments.deleteAssignment(assignmentId);
    this.guards.safeBroadcast(tripId, 'assignment:deleted', { assignmentId, dayId });
    await this.assignments.reconcile(tripId);
    return ok({ success: true });
  }

  @Tool({
    name: 'clear_day_assignments',
    description:
      'Remove every place from one day in a single step. The day itself, its notes and its bookings stay; the places stay in the trip and can be planned again. Returns the removed assignment ids.',
    inputSchema: {
      tripId: idSchema,
      dayId: idSchema,
    },
    annotations: TOOL_ANNOTATIONS_DELETE,
    access: { group: 'places', mode: 'write' },
  })
  async clearDayAssignments({ tripId, dayId }: { tripId: number; dayId: number }, ctx: McpContext) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.dayExists(dayId, tripId))) return errorResult('Day not found.');
    const removedIds = await this.assignments.clearDay(dayId);
    for (const assignmentId of removedIds)
      this.guards.safeBroadcast(tripId, 'assignment:deleted', { assignmentId, dayId });
    if (removedIds.length > 0) await this.assignments.reconcile(tripId);
    return ok({ success: true, removedIds });
  }

  @Tool({
    name: 'update_assignment_time',
    description:
      'Set the start and/or end time for a place assignment on a day (e.g. "09:00", "11:30"). Pass null to clear a time.',
    inputSchema: {
      tripId: idSchema,
      assignmentId: idSchema,
      place_time: z.string().max(50).nullable().optional().describe('Start time (e.g. "09:00"), or null to clear'),
      end_time: z.string().max(50).nullable().optional().describe('End time (e.g. "11:00"), or null to clear'),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    access: { group: 'places', mode: 'write' },
  })
  async updateAssignmentTime(
    {
      tripId,
      assignmentId,
      place_time,
      end_time,
    }: {
      tripId: number;
      assignmentId: number;
      place_time?: string | null;
      end_time?: string | null;
    },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    const existing = await this.assignments.getAssignmentForTrip(assignmentId, tripId);
    if (!existing) return errorResult('Assignment not found.');
    const { assignment, reordered, vias } = await this.assignments.updateTime(
      assignmentId,
      place_time !== undefined ? place_time : existing.assignment_time,
      end_time !== undefined ? end_time : existing.assignment_end_time,
    );
    // Same three events as PUT /assignments/:id/time.
    this.guards.safeBroadcast(tripId, 'assignment:updated', { assignment });
    if (reordered) this.guards.safeBroadcast(tripId, 'assignment:reordered', reordered);
    if (vias) this.guards.safeBroadcast(tripId, 'roadtripVia:changed', vias);
    await this.assignments.reconcile(tripId);
    return ok({ assignment });
  }

  @Tool({
    name: 'update_assignment_notes',
    description:
      'Set or clear the day-specific note on a place assignment (the note assign_place_to_day and create_and_assign_place accept at creation). Pass null or an empty string to clear it.',
    inputSchema: {
      tripId: idSchema,
      assignmentId: idSchema,
      // Mirrors the REST contract (assignmentNotesRequestSchema): uncapped on
      // purpose, unlike the create tools' max(500) — a longer note written
      // through REST or the plugin RPC must stay editable here (#2163).
      notes: z.string().nullable().describe('The note text, or null to clear'),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    access: { group: 'places', mode: 'write' },
  })
  async updateAssignmentNotes(
    { tripId, assignmentId, notes }: { tripId: number; assignmentId: number; notes: string | null },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.getAssignmentForTrip(assignmentId, tripId)))
      return errorResult('Assignment not found.');
    const assignment = await this.assignments.updateNotes(assignmentId, notes);
    this.guards.safeBroadcast(tripId, 'assignment:updated', { assignment });
    return ok({ assignment });
  }

  @Tool({
    name: 'set_leg_transport_mode',
    description:
      'Set the travel mode of a route leg for a place assignment. Use direction "outgoing" (default) for the common case: the leg leaving this stop toward the next. Use direction "incoming" ONLY when this stop\'s arriving leg originates from something that is not itself a place assignment (e.g. a flight/train booking arrival, or a morning hotel departure) – setting "incoming" on an ordinary place-to-place leg is stored but has no effect on route rendering, because it targets a column that is only read for non-place origins. transport_mode is a route profile key: "driving", "walking", "cycling", or a plugin profile written as "plugin:<pluginId>/<profileId>". Any other value is stored but drawn as a driving route. null clears it so the leg inherits the day default.',
    inputSchema: {
      tripId: idSchema,
      assignmentId: idSchema,
      transport_mode: z
        .string()
        .nullable()
        .optional()
        .describe('Route profile key (e.g. "driving"), or null to inherit the day default'),
      direction: z
        .enum(['outgoing', 'incoming'])
        .default('outgoing')
        .describe('Which leg to set: "outgoing" (leaving this stop, default) or "incoming" (arriving at it)'),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    access: { group: 'places', mode: 'write' },
  })
  async setLegTransportMode(
    {
      tripId,
      assignmentId,
      transport_mode,
      direction,
    }: {
      tripId: number;
      assignmentId: number;
      transport_mode?: string | null;
      direction?: 'outgoing' | 'incoming';
    },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.getAssignmentForTrip(assignmentId, tripId)))
      return errorResult('Assignment not found.');
    const assignment =
      direction === 'incoming'
        ? await this.assignments.setIncomingLegTransportMode(assignmentId, transport_mode ?? null)
        : await this.assignments.setLegTransportMode(assignmentId, transport_mode ?? null);
    this.guards.safeBroadcast(tripId, 'assignment:updated', { assignment });
    return ok({ assignment });
  }

  @Tool({
    name: 'set_assignment_route_excluded',
    description:
      'Keep a place on its day but leave it out of that day route, or put it back. An excluded stop still shows in the day plan and on the map, and the route runs from the stop before it straight to the one after. Use it for a place only visited on foot from somewhere nearby, or one that is just a point of interest.',
    inputSchema: {
      tripId: idSchema,
      assignmentId: idSchema,
      excluded: z.boolean().describe('true leaves the stop out of the route, false routes it again'),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    access: { group: 'places', mode: 'write' },
  })
  async setAssignmentRouteExcluded(
    { tripId, assignmentId, excluded }: { tripId: number; assignmentId: number; excluded: boolean },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.getAssignmentForTrip(assignmentId, tripId)))
      return errorResult('Assignment not found.');
    const assignment = await this.assignments.setRouteExcluded(assignmentId, excluded);
    this.guards.safeBroadcast(tripId, 'assignment:updated', { assignment });
    return ok({ assignment });
  }

  @Tool({
    name: 'move_assignment',
    description: 'Move a place assignment to a different day.',
    inputSchema: {
      tripId: idSchema,
      assignmentId: idSchema,
      newDayId: idSchema,
      oldDayId: idSchema
        .optional()
        .describe('Deprecated and ignored — the server derives the source day from the assignment'),
      orderIndex: z.number().int().min(0).optional().default(0),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    access: { group: 'places', mode: 'write' },
  })
  async moveAssignment(
    {
      tripId,
      assignmentId,
      newDayId,
      orderIndex,
    }: {
      tripId: number;
      assignmentId: number;
      newDayId: number;
      oldDayId?: number;
      orderIndex?: number;
    },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.getAssignmentForTrip(assignmentId, tripId)))
      return errorResult('Assignment not found.');
    if (!(await this.days.getDay(newDayId, tripId))) return errorResult('Day not found.');
    const result = await this.assignments.moveAssignment(assignmentId, newDayId, orderIndex ?? 0);
    // REST parity shape ({ assignment, oldDayId, newDayId }) — the client keys its
    // per-day assignment map on newDayId, so omitting it filed the moved assignment
    // under "undefined" on collaborator screens.
    this.guards.safeBroadcast(tripId, 'assignment:moved', {
      assignment: result.assignment,
      oldDayId: result.oldDayId,
      newDayId,
    });
    await this.assignments.reconcile(tripId);
    return ok({ assignment: result.assignment });
  }

  @Tool({
    name: 'get_assignment_participants',
    description: 'Get the list of users participating in a specific place assignment.',
    inputSchema: {
      tripId: idSchema,
      assignmentId: idSchema,
    },
    annotations: TOOL_ANNOTATIONS_READONLY,
    access: { group: 'places', mode: 'read' },
  })
  async getAssignmentParticipants({ tripId, assignmentId }: { tripId: number; assignmentId: number }, ctx: McpContext) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.assignments.getAssignmentForTrip(assignmentId, tripId)))
      return errorResult('Assignment not found.');
    const participants = await this.assignments.getParticipants(assignmentId);
    return ok({ participants });
  }

  @Tool({
    name: 'set_assignment_participants',
    description: 'Set the participants for a place assignment (replaces current list).',
    inputSchema: {
      tripId: idSchema,
      assignmentId: idSchema,
      userIds: z.array(idSchema).describe('User IDs to set as participants; empty array clears all'),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    access: { group: 'places', mode: 'write' },
  })
  async setAssignmentParticipants(
    { tripId, assignmentId, userIds }: { tripId: number; assignmentId: number; userIds: number[] },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.assignments.getAssignmentForTrip(assignmentId, tripId)))
      return errorResult('Assignment not found.');
    const participants = await this.assignments.setParticipants(assignmentId, userIds, tripId);
    this.guards.safeBroadcast(tripId, 'assignment:participants', { assignmentId, participants });
    return ok({ participants });
  }

  @Tool({
    name: 'reorder_day_assignments',
    description: 'Reorder places within a day by providing the assignment IDs in the desired order.',
    inputSchema: {
      tripId: idSchema,
      dayId: idSchema,
      assignmentIds: z.array(idSchema).min(1).max(200).describe('Assignment IDs in desired display order'),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    access: { group: 'places', mode: 'write' },
  })
  async reorderDayAssignments(
    { tripId, dayId, assignmentIds }: { tripId: number; dayId: number; assignmentIds: number[] },
    ctx: McpContext,
  ) {
    if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
    if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
    if (!(await this.days.getDay(dayId, tripId))) return errorResult('Day not found.');
    await this.assignments.reorderAssignments(dayId, assignmentIds);
    // REST parity shape ({ dayId, orderedIds }) — the client only reads orderedIds,
    // so broadcasting the tool-input key name emptied the day for collaborators.
    this.guards.safeBroadcast(tripId, 'assignment:reordered', { dayId, orderedIds: assignmentIds });
    return ok({ success: true, dayId, order: assignmentIds });
  }
}