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.

33.6 KB
Raw Blame
import { ADDON_IDS } from '../../addons';
import {
  McpController,
  Tool,
  Resource,
  ResourceTemplate,
  TOOL_ANNOTATIONS_DELETE,
  TOOL_ANNOTATIONS_NON_IDEMPOTENT,
  TOOL_ANNOTATIONS_READONLY,
  TOOL_ANNOTATIONS_WRITE,
  ok,
  type McpContext,
} from '../../nest-mcp';
import type { JourneyContributor } from '../../types';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { uriRowId } from '../common/row-id';
import { JourneyDomainService } from './journey-domain.service';
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
import { JourneySettingsService } from './journey-settings.service';
import { JourneyShareService } from './journey-share.service';
import {
  idSchema,
  journeyCreateToolSchema,
  journeyEntriesRangeSchema,
  journeyEntryUpdateToolSchema,
  journeyReorderEntriesToolSchema,
  journeyEntryProsConsSchema,
  journeyEntryTypeSchema,
  journeyEntryVisibilitySchema,
  journeyShareLinkRequestSchema,
  journeyUpdateToolSchema,
  type JourneyCreateTool,
  type JourneyEntryType,
  type JourneyEntryUpdateTool,
  type JourneyEntryVisibility,
  type JourneyReorderEntriesTool,
  type JourneyUpdateTool,
  JOURNEY_ENTRY_VISIBILITY_DEPRECATED,
} from '@trek/shared';

import { z } from 'zod';

/** Legacy registrar gate: the whole journey surface rode the journey addon. */
const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY);

function notFound(msg: string) {
  return { content: [{ type: 'text' as const, text: msg }], isError: true };
}

function accessDenied(uri: string) {
  return {
    contents: [
      {
        uri,
        mimeType: 'application/json',
        text: JSON.stringify({ error: 'Trip not found or access denied' }),
      },
    ],
  };
}

function jsonContent(uri: string, data: unknown) {
  return {
    contents: [
      {
        uri,
        mimeType: 'application/json',
        text: JSON.stringify(data, null, 2),
      },
    ],
  };
}

/*
 * The entry types and the verdict come from @trek/shared (journey.schema.ts),
 * where the assistant's cards read them too: a model that invents "note" would
 * write a value nothing reads. The entry's stored visibility is deprecated:
 * still accepted so older callers are not refused, but read by nothing, and
 * is_draft is what keeps an entry off the share link.
 */
const ENTRY_TYPE = journeyEntryTypeSchema;
const PROS_CONS = journeyEntryProsConsSchema;

/**
 * The photo backends a journey can reference. The REST route forwards whatever
 * `provider` string the body carried straight into `trek_photos.provider`, which
 * would let a model persist a row no resolver can ever match to a backend.
 */
const PHOTO_PROVIDER = z.enum(['immich', 'synologyphotos']);

/**
 * How many provider assets one call may attach. The REST route takes an
 * unbounded array, but it is driven by a picker where every id was clicked;
 * a tool call is not, and each id is a row plus a detached provider lookup.
 */
const MAX_PROVIDER_PHOTOS_PER_CALL = 100;

/**
 * Journey MCP surface — ported 1:1 from the legacy registrar
 * src/mcp/tools/journey.ts (23 tools): identical names, descriptions, zod input
 * schemas, annotations, and error/payload shapes. The legacy `if (R)` / `if (W)`
 * checks become declarative read/write markers; the three `if (S)` share tools
 * become `{ group: 'journey', mode: 'share' }`, which is why McpAccessMode is
 * host-augmentable now — canShareJourneys was the one scope the old two-mode
 * marker could not express, and folding it into a predicate would have put it
 * out of reach of the boot-time scope gate. The registration-time addon
 * early-return becomes the `when:` gate.
 *
 * Since the port the surface has grown past the legacy 23: the two entry tools
 * take the rest of the columns their REST routes always accepted (a place, its
 * coordinates, weather, tags, the verdict), and get_journey_stats answers what
 * GET /api/journeys/:id/stats answers.
 *
 * So does add_journey_provider_photos, which brings across
 * POST /api/journeys/entries/:entryId/provider-photos and its gallery twin
 * POST /api/journeys/:id/gallery/provider-photos. Finding the asset ids it takes
 * is the memories domain's half of the same job, in memories/memories.mcp.ts.
 */
@McpController()
export class JourneyMcp {
  constructor(
    private readonly journey: JourneyDomainService,
    private readonly share: JourneyShareService,
    readonly addons: AddonsService,
    private readonly photoCapture: JourneyPhotoCaptureService,
    private readonly settings: JourneySettingsService,
  ) {}

  // ── Read ────────────────────────────────────────────────────────────────

  @Tool({
    name: 'list_journeys',
    description: 'List all journeys owned or contributed to by the current user.',
    inputSchema: {},
    annotations: TOOL_ANNOTATIONS_READONLY,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async listJourneys(_args: unknown, ctx: McpContext) {
    return ok({ journeys: await this.journey.listJourneys(ctx.userId) });
  }

  @Tool({
    name: 'get_journey',
    description: 'Get a full journey including entries, contributors, and linked trips.',
    inputSchema: { journeyId: idSchema },
    annotations: TOOL_ANNOTATIONS_READONLY,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async getJourney({ journeyId }: { journeyId: number }, ctx: McpContext) {
    const journey = await this.journey.getJourneyFull(journeyId, ctx.userId);
    if (!journey) return notFound('Journey not found or access denied.');
    return ok({ journey });
  }

  @Tool({
    name: 'get_journey_stats',
    description:
      'What a journey adds up to: distance travelled in metres, calendar days spanned, countries in visit order, the furthest point reached, and entry, photo and place counts. Stops the traveller switched off with update_journey_entry count towards none of those and are listed under excluded instead. Prefer this over get_journey whenever the question is about totals, since the stats get_journey carries are three counts and nothing else.',
    inputSchema: {
      journeyId: idSchema,
      include_route: z
        .boolean()
        .optional()
        .describe(
          'Also return the route itself, up to 400 stops with coordinates. Off by default: the totals and the country list do not need it.',
        ),
    },
    annotations: TOOL_ANNOTATIONS_READONLY,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async getJourneyStats({ journeyId, include_route }: { journeyId: number; include_route?: boolean }, ctx: McpContext) {
    const stats = await this.journey.journeyStats(journeyId, ctx.userId);
    if (!stats) return notFound('Journey not found or access denied.');
    // Same payload as GET /api/journeys/:id/stats. The route is left out unless
    // it was asked for: 400 coordinate pairs answer a different question than
    // the totals do, and Studio is the caller that actually draws them.
    if (include_route) return ok({ stats });
    const { points: _route, ...totals } = stats;
    return ok({ stats: totals });
  }

  @Tool({
    name: 'list_journey_entries',
    description:
      'List the entries of a journey in reading order, with the id and title of the journey. from/to keep only the entries of those days (YYYY-MM-DD, both included), so asking for one day reads that day and no more.',
    inputSchema: { journeyId: idSchema, ...journeyEntriesRangeSchema.shape },
    annotations: TOOL_ANNOTATIONS_READONLY,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async listJourneyEntries(
    { journeyId, from, to }: { journeyId: number; from?: string; to?: string },
    ctx: McpContext,
  ) {
    const journey = await this.journey.canAccessJourney(journeyId, ctx.userId);
    const entries = journey ? await this.journey.listEntries(journeyId, ctx.userId) : null;
    if (!journey || !entries) return notFound('Journey not found or access denied.');
    const inRange = entries.filter((e) => (!from || e.entry_date >= from) && (!to || e.entry_date <= to));
    return ok({ entries: inRange, journey: { id: journey.id, title: journey.title } });
  }

  @Tool({
    name: 'get_journey_entry',
    description:
      'One journal entry by its id, as list_journey_entries answers it (photos included), with the id and title of its journey.',
    inputSchema: { entryId: idSchema },
    annotations: TOOL_ANNOTATIONS_READONLY,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async getJourneyEntry({ entryId }: { entryId: number }, ctx: McpContext) {
    const journeyId = await this.journey.journeyIdOfEntry(entryId);
    const journey = journeyId === null ? null : await this.journey.canAccessJourney(journeyId, ctx.userId);
    const entries = journey ? await this.journey.listEntries(journey.id, ctx.userId) : null;
    const entry = entries?.find((e) => e.id === entryId);
    if (!journey || !entry) return notFound('Entry not found or access denied.');
    return ok({ entry, journey: { id: journey.id, title: journey.title } });
  }

  @Tool({
    name: 'list_journey_contributors',
    description: 'List all contributors (owner and collaborators) of a journey.',
    inputSchema: { journeyId: idSchema },
    annotations: TOOL_ANNOTATIONS_READONLY,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async listJourneyContributors({ journeyId }: { journeyId: number }, ctx: McpContext) {
    const journey = await this.journey.getJourneyFull(journeyId, ctx.userId);
    if (!journey) return notFound('Journey not found or access denied.');
    return ok({ contributors: (journey as { contributors?: JourneyContributor[] }).contributors ?? [] });
  }

  @Tool({
    name: 'get_journey_suggestions',
    description: 'Get trip suggestions for creating a new journey (recently completed trips not yet in any journey).',
    inputSchema: {},
    annotations: TOOL_ANNOTATIONS_READONLY,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async getJourneySuggestions(_args: unknown, ctx: McpContext) {
    return ok({ trips: await this.journey.getSuggestions(ctx.userId) });
  }

  @Tool({
    name: 'list_journey_available_trips',
    description: 'List all trips available to link to a journey.',
    inputSchema: {},
    annotations: TOOL_ANNOTATIONS_READONLY,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async listJourneyAvailableTrips(_args: unknown, ctx: McpContext) {
    return ok({ trips: await this.journey.listUserTrips(ctx.userId) });
  }

  // ── Write ───────────────────────────────────────────────────────────────

  @Tool({
    name: 'create_journey',
    description: 'Create a new journey, optionally linking existing trips.',
    inputSchema: journeyCreateToolSchema.shape,
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async createJourney({ title, subtitle, trip_ids }: JourneyCreateTool, ctx: McpContext) {
    const journey = await this.journey.createJourney(ctx.userId, { title, subtitle, trip_ids });
    // Return the fully-hydrated journey (entries/contributors/trips/stats/my_role),
    // matching get_journey, rather than the bare row.
    return ok({ journey: (await this.journey.getJourneyFull(journey.id, ctx.userId)) ?? journey });
  }

  @Tool({
    name: 'update_journey',
    description:
      "Update an existing journey's title, subtitle, cover, or status. Owner only. status_override sets the state shown for the journey (draft, live, completed) instead of deriving it from the linked trips' dates; null goes back to the dates. auto_prepare_recordings switches the background preparation of its recorded days from Dawarich on or off (see get_journey_recording_prep). Answers with the journey and, under previous, what the changed settings held before.",
    inputSchema: { journeyId: idSchema, ...journeyUpdateToolSchema.shape },
    annotations: TOOL_ANNOTATIONS_WRITE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async updateJourney({ journeyId, ...data }: JourneyUpdateTool & { journeyId: number }, ctx: McpContext) {
    // The same owner check and reading of the settings as PATCH /api/journeys/:id, with what they held before.
    const updated = await this.settings.updateWithPrevious(journeyId, ctx.userId, data);
    if (!updated) return notFound('Journey not found or access denied.');
    return ok(updated);
  }

  @Tool({
    name: 'restore_journey_suggestions',
    description:
      'Bring back every trip-derived suggestion that was dismissed from this journey. Answers with how many came back.',
    inputSchema: {
      journeyId: idSchema,
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async restoreJourneySuggestions({ journeyId }: { journeyId: number }, ctx: McpContext) {
    const result = await this.journey.restoreDismissedSuggestions(journeyId, ctx.userId);
    if (!result) return notFound('Journey not found or access denied.');
    return ok(result);
  }

  @Tool({
    name: 'delete_journey',
    description: 'Delete a journey. Owner only — this cannot be undone.',
    inputSchema: { journeyId: idSchema },
    annotations: TOOL_ANNOTATIONS_DELETE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async deleteJourney({ journeyId }: { journeyId: number }, ctx: McpContext) {
    if (!(await this.journey.deleteJourney(journeyId, ctx.userId)))
      return notFound('Journey not found or access denied.');
    return ok({ success: true });
  }

  @Tool({
    name: 'add_journey_trip',
    description: 'Link a trip to a journey. Syncs skeleton entries for all places in the trip.',
    inputSchema: { journeyId: idSchema, tripId: idSchema },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async addJourneyTrip({ journeyId, tripId }: { journeyId: number; tripId: number }, ctx: McpContext) {
    if (!(await this.journey.canAccessJourney(journeyId, ctx.userId)))
      return notFound('Journey not found or access denied.');
    return ok({ success: await this.journey.addTripToJourney(journeyId, tripId, ctx.userId) });
  }

  @Tool({
    name: 'remove_journey_trip',
    description: 'Unlink a trip from a journey. Owner only.',
    inputSchema: { journeyId: idSchema, tripId: idSchema },
    annotations: TOOL_ANNOTATIONS_DELETE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async removeJourneyTrip({ journeyId, tripId }: { journeyId: number; tripId: number }, ctx: McpContext) {
    const success = await this.journey.removeTripFromJourney(journeyId, tripId, ctx.userId);
    if (!success) return notFound('Journey not found or access denied.');
    return ok({ success });
  }

  @Tool({
    name: 'create_journey_entry',
    description:
      'Create a new entry in a journey. Give location_lat/location_lng whenever the place is known, otherwise the entry is text-only and never appears on the journey map or in its distance.',
    inputSchema: {
      journeyId: idSchema,
      entry_date: z
        .string()
        .regex(/^\d{4}-\d{2}-\d{2}$/)
        .describe('Entry date (YYYY-MM-DD)'),
      title: z.string().max(300).optional(),
      story: z.string().optional(),
      entry_time: z.string().optional().describe('Time of day (e.g. "14:30")'),
      location_name: z.string().optional(),
      location_lat: z
        .number()
        .min(-90)
        .max(90)
        .optional()
        .describe('Latitude; needed, with location_lng, to place the entry on the journey map'),
      location_lng: z.number().min(-180).max(180).optional(),
      mood: z.string().optional(),
      weather: z
        .string()
        .max(100)
        .optional()
        .describe('Weather as the traveller recorded it (e.g. "sunny", "24C and windy")'),
      tags: z.array(z.string()).optional(),
      pros_cons: PROS_CONS.optional().describe('The verdict on the place: what was worth it and what was not'),
      visibility: journeyEntryVisibilitySchema.optional().describe(JOURNEY_ENTRY_VISIBILITY_DEPRECATED),
      type: ENTRY_TYPE.optional().describe(
        'Defaults to "entry"; "skeleton" is the stub TREK derives from a trip place and hides behind the hide-skeletons preference',
      ),
      sort_order: z.number().int().min(0).optional(),
      is_draft: z
        .boolean()
        .optional()
        .describe(
          'True keeps the entry a draft: contributors see it, the journey share link does not. Every entry that is not a draft shows on the share link',
        ),
    },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async createJourneyEntry(
    {
      journeyId,
      ...data
    }: {
      journeyId: number;
      entry_date: string;
      title?: string;
      story?: string;
      entry_time?: string;
      location_name?: string;
      location_lat?: number;
      location_lng?: number;
      mood?: string;
      weather?: string;
      tags?: string[];
      pros_cons?: { pros: string[]; cons: string[] };
      visibility?: JourneyEntryVisibility;
      type?: JourneyEntryType;
      sort_order?: number;
      is_draft?: boolean;
    },
    ctx: McpContext,
  ) {
    const entry = await this.journey.createEntry(journeyId, ctx.userId, data);
    if (!entry) return notFound('Journey not found or access denied.');
    // Return through the listEntries enrichment (parsed tags/pros_cons, photos, source_trip_name).
    const enriched = (await this.journey.listEntries(journeyId, ctx.userId))?.find((e) => e.id === entry.id) ?? entry;
    return ok({ entry: enriched });
  }

  @Tool({
    name: 'update_journey_entry',
    description:
      'Update an existing journey entry: its text, date, place, coordinates, weather, tags, verdict, whether it is a draft (is_draft, the one switch that keeps it off the share link), or whether it counts as a stop. Fields left out keep their value; pass null to clear one. To move an entry within its day use reorder_journey_entries rather than setting sort_order here. Answers with the entry and, under previous, what the changed fields held before.',
    inputSchema: { entryId: idSchema, ...journeyEntryUpdateToolSchema.shape },
    annotations: TOOL_ANNOTATIONS_WRITE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async updateJourneyEntry({ entryId, ...data }: JourneyEntryUpdateTool & { entryId: number }, ctx: McpContext) {
    // The update PATCH /api/journeys/entries/:entryId makes, with what it replaced.
    const updated = await this.journey.updateEntryWithPrevious(entryId, ctx.userId, data, undefined);
    if (!updated) return notFound('Entry not found or access denied.');
    const { entry, previous } = updated;
    // Return through the listEntries enrichment (parsed tags/pros_cons, photos), matching create_journey_entry.
    const enriched =
      (await this.journey.listEntries(entry.journey_id, ctx.userId))?.find((e) => e.id === entry.id) ?? entry;
    return ok({ entry: enriched, previous });
  }

  @Tool({
    name: 'delete_journey_entry',
    description: 'Delete a journey entry.',
    inputSchema: { entryId: idSchema },
    annotations: TOOL_ANNOTATIONS_DELETE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async deleteJourneyEntry({ entryId }: { entryId: number }, ctx: McpContext) {
    if (!(await this.journey.deleteEntry(entryId, ctx.userId, undefined)))
      return notFound('Entry not found or access denied.');
    return ok({ success: true });
  }

  @Tool({
    name: 'reorder_journey_entries',
    description:
      'Reorder entries within a journey by providing the desired order of entry IDs. Answers with previous_order, the same ids in the order they stood in before.',
    inputSchema: { journeyId: idSchema, ...journeyReorderEntriesToolSchema.shape },
    annotations: TOOL_ANNOTATIONS_WRITE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async reorderJourneyEntries(
    { journeyId, orderedIds }: JourneyReorderEntriesTool & { journeyId: number },
    ctx: McpContext,
  ) {
    const reordered = await this.journey.reorderEntriesWithPrevious(journeyId, ctx.userId, orderedIds, undefined);
    if (!reordered) return notFound('Journey not found, access denied, or entry IDs do not belong to this journey.');
    return ok({ success: true, previous_order: reordered.previousOrder });
  }

  @Tool({
    name: 'reorder_journey_entry_photos',
    description:
      'Put the photos of one journey entry in a new order. Pass every photo id the entry holds (the journey photo ids list_journey_entries returns), each once, first photo first. The first one is the entry cover.',
    inputSchema: {
      entryId: idSchema,
      orderedIds: z.array(idSchema).min(1).max(500),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async reorderJourneyEntryPhotos({ entryId, orderedIds }: { entryId: number; orderedIds: number[] }, ctx: McpContext) {
    if (!(await this.journey.reorderEntryPhotos(entryId, ctx.userId, orderedIds, undefined))) {
      return notFound('Entry not found, access denied, or the ids are not exactly the photos of this entry.');
    }
    return ok({ success: true });
  }

  @Tool({
    name: 'add_journey_contributor',
    description: 'Add a contributor to a journey. Owner only.',
    inputSchema: {
      journeyId: idSchema,
      targetUserId: idSchema,
      role: z.enum(['editor', 'viewer']),
    },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async addJourneyContributor(
    { journeyId, targetUserId, role }: { journeyId: number; targetUserId: number; role: 'editor' | 'viewer' },
    ctx: McpContext,
  ) {
    if (!(await this.journey.addContributor(journeyId, ctx.userId, targetUserId, role)))
      return notFound('Journey not found or access denied.');
    return ok({ success: true });
  }

  @Tool({
    name: 'update_journey_contributor_role',
    description: 'Update the role of a journey contributor. Owner only.',
    inputSchema: {
      journeyId: idSchema,
      targetUserId: idSchema,
      role: z.enum(['editor', 'viewer']),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async updateJourneyContributorRole(
    { journeyId, targetUserId, role }: { journeyId: number; targetUserId: number; role: 'editor' | 'viewer' },
    ctx: McpContext,
  ) {
    if (!(await this.journey.updateContributorRole(journeyId, ctx.userId, targetUserId, role)))
      return notFound('Journey not found or access denied.');
    return ok({ success: true });
  }

  @Tool({
    name: 'remove_journey_contributor',
    description: 'Remove a contributor from a journey. Owner only.',
    inputSchema: {
      journeyId: idSchema,
      targetUserId: idSchema,
    },
    annotations: TOOL_ANNOTATIONS_DELETE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async removeJourneyContributor(
    { journeyId, targetUserId }: { journeyId: number; targetUserId: number },
    ctx: McpContext,
  ) {
    if (!(await this.journey.removeContributor(journeyId, ctx.userId, targetUserId)))
      return notFound('Journey not found or access denied.');
    return ok({ success: true });
  }

  @Tool({
    name: 'update_journey_preferences',
    description: 'Update per-user preferences for a journey (e.g. hide skeleton entries).',
    inputSchema: {
      journeyId: idSchema,
      hide_skeletons: z.boolean().optional(),
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async updateJourneyPreferences(
    { journeyId, hide_skeletons }: { journeyId: number; hide_skeletons?: boolean },
    ctx: McpContext,
  ) {
    const result = await this.journey.updateJourneyPreferences(journeyId, ctx.userId, { hide_skeletons });
    if (!result) return notFound('Journey not found or access denied.');
    // Return the service result ({ hide_skeletons }), matching the REST route.
    return ok(result);
  }

  @Tool({
    name: 'add_journey_provider_photos',
    description:
      'Attach photos from a connected library (Immich or Synology Photos) to a journey: to one entry when entryId is given, otherwise to the journey gallery only. Find the asset ids first with search_provider_photos or list_provider_album_photos. No image data passes through here, the journey stores a reference and the app fetches the picture, so this also works for photos far too large to hand to a model. An asset already attached is skipped rather than duplicated, which makes re-running the same call safe.',
    inputSchema: {
      journeyId: idSchema,
      entryId: idSchema
        .optional()
        .describe(
          'Attach to this entry, which must belong to journeyId. The photo lands in the journey gallery either way; omitting this adds it to the gallery alone',
        ),
      provider: PHOTO_PROVIDER.describe('The library the asset ids came from'),
      asset_ids: z
        .array(z.string().min(1))
        .min(1)
        .max(MAX_PROVIDER_PHOTOS_PER_CALL)
        .describe('Provider asset ids, as returned by the search and album tools'),
      media_types: z
        .array(z.enum(['image', 'video']))
        .optional()
        .describe('Parallel to asset_ids; anything not named here counts as an image'),
      caption: z
        .string()
        .max(500)
        .optional()
        .describe('Stored only when entryId is given, matching the REST routes: the gallery add records no caption'),
      passphrase: z
        .string()
        .min(1)
        .optional()
        .describe(
          'Only for a Synology Photos album shared with the user: the passphrase list_provider_albums returned for that album',
        ),
    },
    annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'write' },
  })
  async addJourneyProviderPhotos(
    {
      journeyId,
      entryId,
      provider,
      asset_ids,
      media_types,
      caption,
      passphrase,
    }: {
      journeyId: number;
      entryId?: number;
      provider: z.infer<typeof PHOTO_PROVIDER>;
      asset_ids: string[];
      media_types?: Array<'image' | 'video'>;
      caption?: string;
      passphrase?: string;
    },
    ctx: McpContext,
  ) {
    // The REST routes derive the journey from the entry and let each per-asset
    // add answer for itself, which in the array branch means a caller with no
    // access gets an empty 200. Checking up front instead turns that silence
    // into a sentence, and is what makes journeyId worth asking for: the entry
    // has to be shown to belong to it before anything is written.
    if (!(await this.journey.canEdit(journeyId, ctx.userId))) return notFound('Journey not found or access denied.');
    if (
      entryId !== undefined &&
      !(await this.journey.listEntries(journeyId, ctx.userId))?.some((e) => e.id === entryId)
    ) {
      return notFound('Entry not found in this journey.');
    }

    // The same use case as the REST routes: the adds, the journey:updated every
    // open tab hears, then, detached, the provider is asked when and where each
    // photo was taken, without which it never appears on the journey map (#1614).
    const photos = await this.photoCapture.addProviderPhotos(
      entryId === undefined ? { journeyId } : { entryId },
      ctx.userId,
      {
        provider,
        assetIds: asset_ids,
        mediaTypes: media_types,
        caption: entryId === undefined ? undefined : caption,
        passphrase,
      },
    );
    // `skipped` is what tells a caller that a shortfall was duplicates rather
    // than a failure; the REST body carries only photos and added.
    return ok({ photos, added: photos.length, skipped: asset_ids.length - photos.length });
  }

  // ── Share links (journey:share, not implied by journey:write) ────────────

  @Tool({
    name: 'get_journey_share_link',
    description: 'Get the current public share link for a journey. Owner only. Returns null if none exists.',
    inputSchema: { journeyId: idSchema },
    annotations: TOOL_ANNOTATIONS_READONLY,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'share' },
  })
  async getJourneyShareLink({ journeyId }: { journeyId: number }, ctx: McpContext) {
    // Same read the REST route uses, so the owner check cannot drift apart
    // between the two surfaces: handing out the token is handing out the journey.
    const result = await this.share.readJourneyShareLink(journeyId, ctx.userId);
    if (!result.allowed) return notFound('Journey not found or access denied.');
    return ok({ shareLink: result.link });
  }

  @Tool({
    name: 'create_journey_share_link',
    description:
      'Create or update the public share link for a journey. Owner only. Flags left out keep their current value on an existing link; a new link defaults to timeline/gallery/map on and plan/recordings off. share_plan puts the planned places and GPX tracks on the shared map, share_recordings the recorded days that have a published entry and the stays of published entries; neither shows anything while share_map is off.',
    inputSchema: {
      journeyId: idSchema,
      share_timeline: z.boolean().optional(),
      share_gallery: z.boolean().optional(),
      share_map: z.boolean().optional(),
      newest_first: z.boolean().optional(),
      share_plan: journeyShareLinkRequestSchema.shape.share_plan,
      share_recordings: journeyShareLinkRequestSchema.shape.share_recordings,
    },
    annotations: TOOL_ANNOTATIONS_WRITE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'share' },
  })
  async createJourneyShareLink(
    {
      journeyId,
      ...permissions
    }: {
      journeyId: number;
      share_timeline?: boolean;
      share_gallery?: boolean;
      share_map?: boolean;
      newest_first?: boolean;
      share_plan?: boolean;
      share_recordings?: boolean;
    },
    ctx: McpContext,
  ) {
    const shareLink = await this.share.createOrUpdateJourneyShareLink(journeyId, ctx.userId, permissions);
    if (!shareLink) return notFound('Journey not found or access denied.');
    return ok({ shareLink });
  }

  @Tool({
    name: 'delete_journey_share_link',
    description: 'Revoke the public share link for a journey. Owner only.',
    inputSchema: { journeyId: idSchema },
    annotations: TOOL_ANNOTATIONS_DELETE,
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'share' },
  })
  async deleteJourneyShareLink({ journeyId }: { journeyId: number }, ctx: McpContext) {
    if (!(await this.share.deleteJourneyShareLink(journeyId, ctx.userId)))
      return notFound('Journey not found or access denied.');
    return ok({ success: true });
  }

  // --- RESOURCES ---
  // Ported 1:1 from src/mcp/resources.ts (the last legacy registrar): identical
  // names, URIs, descriptions and payload shapes. The legacy registration-time
  // gate `isAddonEnabled(JOURNEY) && canRead(scopes, 'journey')` becomes
  // `when: journeyAddonOn` + the declarative read marker.

  @Resource({
    name: 'journeys',
    uri: 'trek://journeys',
    description: 'All journeys owned or contributed to by the current user',
    mimeType: 'application/json',
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async journeysResource(uri: URL, ctx: McpContext) {
    return jsonContent(uri.href, await this.journey.listJourneys(ctx.userId));
  }

  @ResourceTemplate({
    name: 'journey-detail',
    uriTemplate: 'trek://journeys/{journeyId}',
    description: 'Single journey with entries, contributors, and trip links',
    mimeType: 'application/json',
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async journeyDetailResource(uri: URL, { journeyId }: { journeyId: string | string[] }, ctx: McpContext) {
    const id = uriRowId(journeyId);
    if (id === null) return accessDenied(uri.href);
    const journey = await this.journey.getJourneyFull(id, ctx.userId);
    if (!journey) return accessDenied(uri.href);
    return jsonContent(uri.href, journey);
  }

  @ResourceTemplate({
    name: 'journey-entries',
    uriTemplate: 'trek://journeys/{journeyId}/entries',
    description: 'All entries in a journey (date, text, mood, linked trip)',
    mimeType: 'application/json',
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async journeyEntriesResource(uri: URL, { journeyId }: { journeyId: string | string[] }, ctx: McpContext) {
    const id = uriRowId(journeyId);
    if (id === null) return accessDenied(uri.href);
    if (!(await this.journey.canAccessJourney(id, ctx.userId))) return accessDenied(uri.href);
    return jsonContent(uri.href, await this.journey.listEntries(id, ctx.userId));
  }

  @ResourceTemplate({
    name: 'journey-contributors',
    uriTemplate: 'trek://journeys/{journeyId}/contributors',
    description: 'Contributors (owners and collaborators) of a journey',
    mimeType: 'application/json',
    when: journeyAddonOn,
    access: { group: 'journey', mode: 'read' },
  })
  async journeyContributorsResource(uri: URL, { journeyId }: { journeyId: string | string[] }, ctx: McpContext) {
    const id = uriRowId(journeyId);
    if (id === null) return accessDenied(uri.href);
    const journey = await this.journey.getJourneyFull(id, ctx.userId);
    if (!journey) return accessDenied(uri.href);
    return jsonContent(uri.href, (journey as { contributors?: JourneyContributor[] }).contributors ?? []);
  }
}