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.

refactor(server): move the journey resources onto the registry and retire src/mcp/resources.ts

jubnl7880eba6fb45
diff --git a/server/CLAUDE.md b/server/CLAUDE.md
new file mode 100644
index 000000000..566ab36df
--- /dev/null
+++ b/server/CLAUDE.md
@@ -0,0 +1,104 @@
+# CLAUDE.md
+
+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+
+Scope: the **`@trek/server`** workspace. See the repo-root `CLAUDE.md` for the monorepo-wide picture (shared contracts, client, conventions). This file covers server internals only.
+
+## Commands (run from `server/`)
+
+```bash
+npm run dev # scripts/dev.mjs: tsc -w then node --watch dist/index.js (server on :3001)
+npm run build # scripts/build.mjs — see "emit-anyway" note below
+npm run typecheck # tsc --noEmit (the real type gate; build does NOT fail on type errors)
+npm run lint # eslint --fix on src/apps/libs/test
+npm run lint:check # eslint, no fix
+npm run test # vitest run (all of tests/**)
+npm run test:unit # tests/unit
+npm run test:integration # tests/integration
+npm run test:ws # tests/websocket
+npm run test:e2e # tests/e2e (boots Nest modules against a temp in-memory SQLite)
+npm run test:coverage # istanbul coverage; per-domain ratchet over src/nest/** (floor ≥80%)
+```
+
+Single test:
+
+```bash
+npx vitest run tests/unit/nest/weather.controller.test.ts
+npx vitest run -t "returns 401 without cookie"
+npx vitest watch tests/unit/nest/auth-guard.test.ts
+```
+
+**Build emits even with type errors** (`scripts/build.mjs` catches `tsc` failures and warns). So `npm run build` succeeding does **not** mean the code typechecks — always run `npm run typecheck` to gate types.
+
+## Architecture
+
+Nest owns everything: the strangler migration **completed 2026-08-10**. Legacy `src/services/` is **deleted** — `eslint.config.mjs` errors on any import of it — and every domain is a DI module under `src/nest/<domain>/`. `src/nest/README.md` is the per-module blueprint and records the migration's design decisions. What still runs outside the container (tracked in `roadmap.md`): `index.ts` boots the websocket server by hand, and the MCP/OAuth transport mounts before `app.init()` — that seam is why a handful of `*.bridge.ts` files survive (plus four permanent cycle-dodge bridges; each bridge's header states its deletion trigger). The scheduler seam is gone: every cron is a domain provider on `@nestjs/schedule` (see `src/nest/scheduling/` below).
+
+- **`src/index.ts`** — process entry: creates upload/data dirs, builds the app via `bootstrap.ts`, wires the WebSocket server onto the same HTTP server, prints the startup banner. Default port **3001**.
+- **`src/bootstrap.ts` — `buildApp()`** — the single shared app builder for both prod and the test harness. **Registration order is load-bearing**: `applyGlobalMiddleware` → `applyPlatformUploads` → `applyPlatformTransport` → `applyPlatformStatic` all run on the raw Express instance **before `app.init()`**, because Nest throws `NotFoundException` on unmatched routes and won't fall through to anything registered after init. `bodyParser: false` keeps the raw `/mcp` body unparsed for the MCP SDK.
+- **Domain modules** live in `src/nest/<domain>/` as `controller` + `service` + `module`, registered in `src/nest/app.module.ts`. **`weather/` is the reference implementation** — copy its shape. The Zod contract is in `shared/src/<domain>/`.
+- **`src/services/` no longer exists** — deleted 2026-08-10 after the last fold; ESLint walls off any new import. Business logic lives in each domain's injectable `.service.ts`, with pure halves split into `.helpers.ts` plain modules and, in newer folds, SQL into a repository (`trek_photos` pattern).
+- **`src/db/`** — `better-sqlite3` (WAL, FK on). `database.ts` boots and runs `schema.ts` → `migrations.ts` → `seeds.ts`. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).
+- **`src/websocket.ts`** — JWT-authed `ws` server on `/ws`, room-per-trip, heartbeat, per-connection rate limiting. Trip mutations forward `X-Socket-Id` so the originating client doesn't echo its own change.
+- **`src/mcp/`** — OAuth 2.1 MCP server transport (scopes, sessionManager, `nest-mcp-policy.ts` boot gate). The tools/resources/prompts themselves live in decorator-driven `<domain>.mcp.ts` files under `src/nest/` — `src/mcp/tools.ts` is registry-attach-only.
+- **`src/nest/scheduling/`** — `CronRegistrarService`, the one way TREK schedules a cron (`@nestjs/schedule` + the `cron` package). Every job is a `*.job.ts` provider in its owning domain, registered from `onApplicationBootstrap`; the registrar refuses to schedule under `NODE_ENV=test` (the shared `buildApp()` harness must never tick — `tests/integration/scheduler-gate.test.ts` pins it) and stops everything on `nestApp.close()`. Never use a `@Cron` decorator — decorator jobs bypass the gate.
+- **`src/nest/plugins/`** — sandboxed plugin runtime in three layers: `supervisor/` + `runtime/plugin-host-entry.ts` + `protocol/envelope.ts` (forked child per plugin, IPC envelopes, rate/RSS policing — **intentionally not Nest**, it's the security boundary); `host/rpc-host.ts` (enforcement: a method is registered at spawn only if the plugin holds the unlocking permission — registration = authorization); `host/plugin-host-deps.factory.ts` (dependency wiring — an `@Injectable()` factory injecting the domain services; the RPC surface is decorator-driven since 2026-08-09, with `PluginsModule` split into four and per-domain coverage gates) + `host/plugin-host-state.ts` (process-wide data-DB/budget maps, module-level on purpose). Install-time gates in `install/` (manifest, safe-extract, Ed25519 signature verify, egress). ⚠️ `runtime/egress-policy.ts` and `HOOK_PERMISSION` in `supervisor/plugin-supervisor.ts` are mirrored (egress-policy **byte-identical**) into `plugin-sdk/` and guarded by parity tests there — keep both sides in sync when touching either.
+
+## Direction (from the 2026 audit — `audit_report/TREK_audit_reports/`)
+
+**Nest is the destination — and as of 2026-08-10 the code is there.** These rules now guard against regression rather than describe a migration in flight:
+
+- **Follow the Nest philosophy, don't work against it.** New surfaces are real Nest modules: thin controller (HTTP shaping, guards, status codes) → injectable provider (business logic, DI-injected deps). The migration to this shape is complete — never resurrect a plain function-module service, and don't grow god services: when a domain outgrows one class, split it (the trips domain became `trips`/`trip-members`/`trip-membership`/`trip-invite`/`trip-read-model`/`calendar`; auth split into `auth` + profile + `tokens`).
+- **Inject, don't reach for module globals.** No new imports of the global `db` proxy from `nest/` layers; no new code depending on the `ws` singleton or event-sink globals. Write new code so it can move to DI (`DatabaseModule`, injectable realtime/config/scheduler) without rework. New modules must be importable without side effects (no disk/DB access at module evaluation).
+- **Don't add routes to the pre-`app.init()` Express shell** — it bypasses every global Nest guard/interceptor/filter. New routes go through Nest so cross-cutting controls actually apply.
+- **Transactions are not optional.** Any multi-statement write goes in `db.transaction()`; never hand-roll `BEGIN`/`COMMIT` via `db.exec`. Bind values with `?`; identifiers only via a literal allow-list.
+- **Migrations are append-only.** Identity is positional (array index == `schema_version`) — never reorder, insert mid-list, or delete; no env interpolation in SQL.
+- **Every write endpoint validates.** `@Body()` must go through the Zod pipe with a schema from `@trek/shared` — no `Record<string, unknown>` + ad-hoc checks. Validating the caller's permission isn't enough: verify every referenced id (place/day/user) exists and belongs to the same trip.
+- **Every outbound `fetch` gets a timeout (`AbortSignal`), a response-size cap, and boundary validation** — no `as`-casting provider responses, no silent `catch → null`. User-influenced URLs go through the SSRF guard. Never silently fall back to another user's API key.
+- **Fail closed.** Unrecognized flag values mean OFF; sandbox/permission opt-outs must refuse in production; never select a less-safe code path based on the *absence* of a file. GET handlers must not write to the DB.
+- **Don't fork the canonical paths.** Auth verification is `verifyJwtAndLoadUser` (with the `password_version` gate) — reuse it, never reimplement. MCP tools are adapters over the same services/`canAccessTrip`/`checkPermission`; a validation or permission change on a REST route must land in the parallel MCP tool in the same change.
+- **Money rules**: integer-cent arithmetic; largest-remainder splits (`budgetService.splitEqualShares` is the reference); FX frozen at entry; explicit flags, never sentinel values (`rate === 1`, `scopes: null`); custom splits must reconcile (`Σ balances = 0`) before persisting.
+- **Reference controllers**: `collections.controller.ts` (Zod pipe on every body + enumeration-safe owner checks) alongside `weather/` for module shape.
+
+## Configuration (app-config)
+
+**Never read `process.env` directly in `src/**`** — ESLint errors on it. All env
+access goes through `src/app-config/`:
+
+- **Nest DI classes**: inject a boot-stable namespace token
+ (`@Inject(mcpConfig.KEY) private mcp: ConfigType<typeof mcpConfig>` from
+ `src/nest/app-config/`) for values frozen per app build, or use
+ `RuntimeEnvService` / `readEnv()` for runtime-toggled values (DEMO_MODE,
+ NODE_ENV, OIDC_*, …) that ~60 tests mutate mid-lifetime.
+- **Everything else** (services, mcp, websocket, scheduler, db, middleware):
+ `readEnv()` from `src/app-config` — live, uncached, per call. Modules that
+ froze env in module-top consts keep that timing (read `readEnv()` at module
+ top, marked "frozen on purpose").
+- **Validation is fail-fast at boot only** (`boot-validate.ts`, imported by
+ `index.ts` right after dotenv): present-but-malformed values abort startup;
+ unset/blank always defaults. Never wire validation into `buildApp()` or
+ `ConfigModule.forRoot` — and never enable `cache: true` or `load`-snapshot a
+ runtime-toggled value (breaks the env-mutating tests).
+- **Booleans are unified**: every switch accepts true/1/on/yes vs false/0/off/no
+ (any casing) via `parseBool`. Everything else pins its exact legacy coercion —
+ parity quirks are documented in `src/app-config/README.md`, including the
+ exemption list for the ESLint ban (plugin child process, dynamic keys,
+ `config.ts` key material, scripts, tests).
+
+## Cross-cutting Nest pieces
+
+- **`src/nest/common/`**: `trek-exception.filter.ts` (global error envelope, `APP_FILTER`), `zod-validation.pipe.ts` (validates against `@trek/shared` schemas), `idempotency.interceptor.ts` (global `APP_INTERCEPTOR` replaying `X-Idempotency-Key` on mutations).
+- **Auth is default-deny**: `src/nest/auth/global-auth.guard.ts` + `mfa-policy.guard.ts` run as `APP_GUARD`s; routes opt out with `@Public()`/`@OptionalAuth()` (`public.decorator.ts`), and `src/nest/common/validate-route-guards.ts` refuses at boot any public route not on `PUBLIC_ROUTE_ALLOW_LIST`. The global guard stands down for routes that declare their own guard chain (still resolving `req.user` for MFA), so per-controller `@UseGuards(JwtAuthGuard, ...)` stacks keep working. Other guards: `admin.guard.ts`, `addons/addon.guard.ts` (`@RequireAddon`), `permissions/trip-access.guard.ts` (`@RequirePermission` + `@Trip()` — the standard trip-scoped shape), `permissions/trip-owner.guard.ts`. Auth is cookie-based (`trek_session`); `@CurrentUser()` decorator. **Never gate a multipart upload with a guard** — guards run before the parser, so the client sees ECONNRESET instead of your 403; check in the handler (PROFILE-015).
+- **`src/middleware/`** — only `globalMiddleware.ts` remains (helmet/CSP, CORS, HSTS, forced-HTTPS, logging, cookie-parser), applied in `bootstrap`. The old `mfaPolicy`/`tripAccess`/`idempotency`/`validate` middlewares are deleted — their jobs moved into the guards above and the Nest pipe/interceptor layer.
+
+## Tests
+
+`tests/` is split into `unit/` (mirrors `src/`, incl. `unit/nest/<domain>.controller.test.ts` and `auth-guard.test.ts`), `integration/`, `e2e/` (one `<domain>.e2e.test.ts` per module, booting the real `JwtAuthGuard` against a temp DB via `tests/e2e/harness.ts` — `createTempDb`/`seedUser`/`sessionCookie`), and `websocket/`. Shared helpers in `tests/helpers/`, fixtures in `tests/fixtures/`, global setup in `tests/setup.ts`.
+
+- **vitest uses the SWC plugin** (`vitest.config.ts`), not esbuild, because Nest's type-based DI needs emitted decorator metadata — esbuild drops it. Keep that config when touching test tooling. Pool is `forks` (isolated DBs per worker).
+- **Coverage gate is a per-domain ratchet over `src/nest/**`** (statements/branches/functions/lines; ≥80% floor, most domains pinned higher — see `vitest.config.ts`); legacy code is intentionally ungated.
+- The config also aliases `@modelcontextprotocol/sdk/*` to CJS dist files because the SDK's exports map uses unresolvable extension-less wildcards.
+
+## Parity discipline (when adding/changing routes)
+
+Routes must be **byte-identical** for the client: same URL, method, query/body, HTTP status, `Set-Cookie`, and JSON body — including bespoke error strings. Nest defaults POST to **201**; add `@HttpCode(200)` where the contract returns 200. Declare static sub-routes (e.g. `/reorder`, `/in-app/all`) **before** `:id` param routes. Trip-scoped handlers verify trip access (404) and permission (403) per handler.
diff --git a/server/src/mcp/index.ts b/server/src/mcp/index.ts
index 7d2b60bdf..ad34a2349 100644
--- a/server/src/mcp/index.ts
+++ b/server/src/mcp/index.ts
@@ -7,7 +7,6 @@ import { verifyMcpToken, verifyJwtToken } from '../nest/auth/auth.bridge';
import { getUserByAccessToken } from '../nest/oauth/oauth.bridge';
import { isAddonEnabled } from '../nest/addons/addons.bridge';
import { ADDON_IDS } from '../addons';
-import { registerResources } from './resources';
import { registerTools } from './tools';
import { McpSession, sessions, revokeUserSessions, revokeUserSessionsForClient, evictOldestSessionForUser } from './sessionManager';
import { readEnv } from '../app-config';
@@ -356,7 +355,6 @@ export async function mcpHandler(req: Request, res: Response): Promise<void> {
return STATIC_TOKEN_DEPRECATION_NOTICE;
};
- registerResources(server, user.id, scopes);
registerTools(server, user.id, scopes, isStaticToken, getDeprecationNotice);
const transport = new StreamableHTTPServerTransport({
diff --git a/server/src/mcp/resources.ts b/server/src/mcp/resources.ts
deleted file mode 100644
index 03c165a78..000000000
--- a/server/src/mcp/resources.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp';
-import { isAddonEnabled } from '../nest/addons/addons.bridge';
-import { ADDON_IDS } from '../addons';
-import { canAccessJourney, getJourneyFull, listEntries, listJourneys } from '../nest/journey/journey.bridge';
-import { canRead } from './scopes';
-
-function parseId(value: string | string[]): number | null {
- const n = Number(Array.isArray(value) ? value[0] : value);
- return Number.isInteger(n) && n > 0 ? n : null;
-}
-
-function accessDenied(uri: string) {
- return {
- contents: [{
- uri,
- mimeType: 'application/json',
- text: JSON.stringify({ error: 'Trip not found or access denied' }),
- }],
- };
-}
-
-function scopeDenied(uri: string) {
- return {
- contents: [{
- uri,
- mimeType: 'application/json',
- text: JSON.stringify({ error: 'Insufficient OAuth scope to access this resource' }),
- }],
- };
-}
-
-function jsonContent(uri: string, data: unknown) {
- return {
- contents: [{
- uri,
- mimeType: 'application/json',
- text: JSON.stringify(data, null, 2),
- }],
- };
-}
-
-export function registerResources(server: McpServer, userId: number, scopes: string[] | null): void {
- // The trips and trip (trek://trips, trek://trips/{tripId}) resources moved
- // to the DI-discovered src/nest/trips/trips.mcp.ts (@Resource /
- // @ResourceTemplate, attached via the nest-mcp registry in registerTools).
-
- // The trip-days resource moved to the DI-discovered
- // src/nest/days/days.mcp.ts (@ResourceTemplate).
-
- // The trip-places resource moved to the DI-discovered
- // src/nest/places/places.mcp.ts (@ResourceTemplate).
-
- // The trip-budget resource moved to the DI-discovered
- // src/nest/budget/budget.mcp.ts (@ResourceTemplate).
-
- // The trip-packing resource moved to the DI-discovered
- // src/nest/packing/packing.mcp.ts (@ResourceTemplate).
-
- // The trip-reservations resource moved to the DI-discovered
- // src/nest/reservations/reservations.mcp.ts (@ResourceTemplate).
-
- // The day-notes resource moved to the DI-discovered
- // src/nest/day-notes/day-notes.mcp.ts (@ResourceTemplate).
-
- // The trip-accommodations resource moved to the DI-discovered
- // src/nest/days/days.mcp.ts (@ResourceTemplate).
-
- // The trip-members resource moved to the DI-discovered
- // src/nest/trips/trips.mcp.ts (@ResourceTemplate).
-
- // The trek://trips/{tripId}/collab-notes, …/collab/polls and …/collab/messages
- // resources moved to the DI-discovered src/nest/collab/collab.mcp.ts
- // (@ResourceTemplate, attached via the nest-mcp registry in registerTools).
-
- // The trek://trips/{tripId}/todos resource moved to the DI-discovered
- // src/nest/todo/todo.mcp.ts (@ResourceTemplate, attached via the nest-mcp
- // registry in registerTools).
-
- // The trek://categories resource moved to the DI-discovered
- // src/nest/categories/categories.mcp.ts (@Resource, attached via the
- // nest-mcp registry in registerTools).
-
- // The bucket-list and visited-countries resources moved to the DI-discovered
- // src/nest/atlas/atlas.mcp.ts (@Resource, attached via the nest-mcp registry
- // in registerTools).
-
- // The trip-budget-per-person and trip-budget-settlement resources moved to
- // the DI-discovered src/nest/budget/budget.mcp.ts (@ResourceTemplate).
-
- // The trip-packing-bags resource moved to the DI-discovered
- // src/nest/packing/packing.mcp.ts (@ResourceTemplate).
-
- // The notifications-in-app resource moved to the DI-discovered
- // src/nest/notifications/notifications.mcp.ts (@Resource, attached via the
- // nest-mcp registry in registerTools).
-
- // The atlas-stats and atlas-regions resources moved to the DI-discovered
- // src/nest/atlas/atlas.mcp.ts (@Resource, attached via the nest-mcp registry
- // in registerTools).
-
- // The vacay resources moved to the DI-discovered src/nest/vacay/vacay.mcp.ts
- // (@McpController, attached via the nest-mcp registry in tools.ts).
-
- // Journey resources (Journey addon)
- if (isAddonEnabled(ADDON_IDS.JOURNEY) && canRead(scopes, 'journey')) {
- server.registerResource(
- 'journeys',
- 'trek://journeys',
- { description: 'All journeys owned or contributed to by the current user', mimeType: 'application/json' },
- async (uri) => {
- const journeys = listJourneys(userId);
- return jsonContent(uri.href, journeys);
- }
- );
-
- server.registerResource(
- 'journey-detail',
- new ResourceTemplate('trek://journeys/{journeyId}', { list: undefined }),
- { description: 'Single journey with entries, contributors, and trip links', mimeType: 'application/json' },
- async (uri, { journeyId }) => {
- const id = parseId(journeyId);
- if (id === null) return accessDenied(uri.href);
- const journey = getJourneyFull(id, userId);
- if (!journey) return accessDenied(uri.href);
- return jsonContent(uri.href, journey);
- }
- );
-
- server.registerResource(
- 'journey-entries',
- new ResourceTemplate('trek://journeys/{journeyId}/entries', { list: undefined }),
- { description: 'All entries in a journey (date, text, mood, linked trip)', mimeType: 'application/json' },
- async (uri, { journeyId }) => {
- const id = parseId(journeyId);
- if (id === null) return accessDenied(uri.href);
- const j = canAccessJourney(id, userId);
- if (!j) return accessDenied(uri.href);
- const entries = listEntries(id, userId);
- return jsonContent(uri.href, entries);
- }
- );
-
- server.registerResource(
- 'journey-contributors',
- new ResourceTemplate('trek://journeys/{journeyId}/contributors', { list: undefined }),
- { description: 'Contributors (owners and collaborators) of a journey', mimeType: 'application/json' },
- async (uri, { journeyId }) => {
- const id = parseId(journeyId);
- if (id === null) return accessDenied(uri.href);
- const j = getJourneyFull(id, userId);
- if (!j) return accessDenied(uri.href);
- return jsonContent(uri.href, (j as any).contributors ?? []);
- }
- );
- }
-}
diff --git a/server/src/nest/journey/journey.bridge.ts b/server/src/nest/journey/journey.bridge.ts
deleted file mode 100644
index 8e84396fb..000000000
--- a/server/src/nest/journey/journey.bridge.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { db } from '../../db/database';
-import { DatabaseService } from '../database/database.service';
-import { RealtimeService } from '../realtime/realtime.service';
-import { TrekPhotosRepository } from '../photos/trek-photos.repository';
-import { JourneyDomainService } from './journey-domain.service';
-
-/**
- * Non-Nest entry point for the journey domain — for the four journey MCP
- * resources in src/mcp/resources.ts, which are registered at import time and
- * so cannot be injected. The journey *tools* no longer need it: they became
- * src/nest/journey/journey.mcp.ts. Inside the container, inject
- * JourneyDomainService or JourneyShareService instead. Delete this file when
- * resources.ts moves to @ResourceTemplate.
- *
- * Module-level construction is safe: `db` is the reinitialize-proof Proxy onto
- * the shared better-sqlite3 singleton, and neither service holds state.
- */
-const dbs = new DatabaseService(db);
-const journey = new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs));
-
-export function canAccessJourney(...args: Parameters<JourneyDomainService['canAccessJourney']>) {
- return journey.canAccessJourney(...args);
-}
-export function getJourneyFull(...args: Parameters<JourneyDomainService['getJourneyFull']>) {
- return journey.getJourneyFull(...args);
-}
-export function listEntries(...args: Parameters<JourneyDomainService['listEntries']>) {
- return journey.listEntries(...args);
-}
-export function listJourneys(...args: Parameters<JourneyDomainService['listJourneys']>) {
- return journey.listJourneys(...args);
-}
diff --git a/server/src/nest/journey/journey.mcp.ts b/server/src/nest/journey/journey.mcp.ts
index efbd657ea..415e0dc5a 100644
--- a/server/src/nest/journey/journey.mcp.ts
+++ b/server/src/nest/journey/journey.mcp.ts
@@ -1,5 +1,5 @@
import {
- McpController, Tool,
+ McpController, Tool, Resource, ResourceTemplate,
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
demoDenied, ok, type McpContext,
@@ -20,6 +20,31 @@ function notFound(msg: string) {
return { content: [{ type: 'text' as const, text: msg }], isError: true };
}
+function parseId(value: string | string[]): number | null {
+ const n = Number(Array.isArray(value) ? value[0] : value);
+ return Number.isInteger(n) && n > 0 ? n : null;
+}
+
+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),
+ }],
+ };
+}
+
/**
* Journey MCP surface — ported 1:1 from the legacy registrar
* src/mcp/tools/journey.ts (23 tools): identical names, descriptions, zod input
@@ -422,4 +447,69 @@ export class JourneyMcp {
if (!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, 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 = parseId(journeyId);
+ if (id === null) return accessDenied(uri.href);
+ const journey = 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 = parseId(journeyId);
+ if (id === null) return accessDenied(uri.href);
+ if (!this.journey.canAccessJourney(id, ctx.userId)) return accessDenied(uri.href);
+ return jsonContent(uri.href, 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 = parseId(journeyId);
+ if (id === null) return accessDenied(uri.href);
+ const journey = this.journey.getJourneyFull(id, ctx.userId);
+ if (!journey) return accessDenied(uri.href);
+ return jsonContent(uri.href, (journey as { contributors?: JourneyContributor[] }).contributors ?? []);
+ }
}
diff --git a/server/tests/helpers/mcp-harness.ts b/server/tests/helpers/mcp-harness.ts
index 3f2c2853a..ae21188d5 100644
--- a/server/tests/helpers/mcp-harness.ts
+++ b/server/tests/helpers/mcp-harness.ts
@@ -13,7 +13,6 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { Client } from '@modelcontextprotocol/sdk/client/index';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
-import { registerResources } from '../../src/mcp/resources';
import { registerTools } from '../../src/mcp/tools';
import { setMcpRegistry } from '../../src/mcp/registry-handoff';
import { createMcpTestRegistry } from './mcp-test-controllers';
@@ -26,7 +25,12 @@ export interface McpHarness {
export interface McpHarnessOptions {
userId: number;
- /** Register read-only resources (default: true) */
+ /**
+ * Inert since the journey resources moved onto the nest-mcp registry
+ * (src/mcp/resources.ts is gone): every resource now rides `withTools`,
+ * like tools-vacay.test.ts has always documented. Accepted so the ~26
+ * suites passing it keep compiling; remove opportunistically.
+ */
withResources?: boolean;
/** Register read-write tools (default: true) */
withTools?: boolean;
@@ -39,13 +43,10 @@ export interface McpHarnessOptions {
}
export async function createMcpHarness(options: McpHarnessOptions): Promise<McpHarness> {
- const { userId, withResources = true, withTools = true, scopes = null, isStaticToken = false, getDeprecationNotice } = options;
+ const { userId, withTools = true, scopes = null, isStaticToken = false, getDeprecationNotice } = options;
const server = new McpServer({ name: 'trek-test', version: '1.0.0' });
- // registerResources gates the journey resources on the same scope list the
- // tools use, so the harness has to hand it over as well.
- if (withResources) registerResources(server, userId, scopes ?? null);
if (withTools) {
// In production bootstrap.ts hands the Nest-discovered registry to
// registerTools after app.init(); the harness has no Nest app, so it
diff --git a/server/tests/unit/mcp/tools-journey.test.ts b/server/tests/unit/mcp/tools-journey.test.ts
index aa5faf38e..06327ffff 100644
--- a/server/tests/unit/mcp/tools-journey.test.ts
+++ b/server/tests/unit/mcp/tools-journey.test.ts
@@ -40,7 +40,7 @@ import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { setAddonEnabled } from '../../helpers/test-db';
import { ADDON_IDS } from '../../../src/addons';
-import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
+import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
createTables(testDb);
@@ -491,3 +491,103 @@ describe('demo mode', () => {
});
});
});
+
+// ---------------------------------------------------------------------------
+// Resources (first-time coverage, added when the four journey resources moved
+// from src/mcp/resources.ts onto the nest-mcp registry — same URIs, names and
+// payload shapes as the legacy registrar)
+// ---------------------------------------------------------------------------
+
+async function createJourney(h: McpHarness, title = 'Eurotrip'): Promise<any> {
+ return (parseToolResult(await h.client.callTool({
+ name: 'create_journey', arguments: { title },
+ })) as any).journey;
+}
+
+describe('Resource: trek://journeys', () => {
+ it('returns the journeys of the current user', async () => {
+ const { user } = createUser(testDb);
+ await withHarness(user.id, async (h) => {
+ const journey = await createJourney(h);
+ const data = parseResourceResult(await h.client.readResource({ uri: 'trek://journeys' })) as any[];
+ expect(Array.isArray(data)).toBe(true);
+ expect(data.map((j) => j.id)).toContain(journey.id);
+ });
+ });
+});
+
+describe('Resource: trek://journeys/{journeyId}', () => {
+ it('returns the hydrated journey', async () => {
+ const { user } = createUser(testDb);
+ await withHarness(user.id, async (h) => {
+ const journey = await createJourney(h);
+ const data = parseResourceResult(await h.client.readResource({ uri: `trek://journeys/${journey.id}` })) as any;
+ expect(data.title).toBe('Eurotrip');
+ expect(Array.isArray(data.entries)).toBe(true);
+ expect(Array.isArray(data.contributors)).toBe(true);
+ });
+ });
+
+ it('answers the legacy denial payload for a bad id and an inaccessible journey', async () => {
+ const { user } = createUser(testDb);
+ const { user: other } = createUser(testDb);
+ await withHarness(other.id, async (hOther) => {
+ const foreign = await createJourney(hOther, 'Private');
+ await withHarness(user.id, async (h) => {
+ for (const uri of ['trek://journeys/abc', `trek://journeys/${foreign.id}`]) {
+ const data = parseResourceResult(await h.client.readResource({ uri })) as any;
+ expect(data).toEqual({ error: 'Trip not found or access denied' });
+ }
+ });
+ });
+ });
+});
+
+describe('Resource: trek://journeys/{journeyId}/entries', () => {
+ it('returns the enriched entries', async () => {
+ const { user } = createUser(testDb);
+ await withHarness(user.id, async (h) => {
+ const journey = await createJourney(h);
+ await h.client.callTool({
+ name: 'create_journey_entry',
+ arguments: { journeyId: journey.id, entry_date: '2026-07-01', title: 'Day 1', story: 'Arrived' },
+ });
+ const data = parseResourceResult(await h.client.readResource({ uri: `trek://journeys/${journey.id}/entries` })) as any[];
+ expect(data).toHaveLength(1);
+ expect(data[0].title).toBe('Day 1');
+ expect(Array.isArray(data[0].tags)).toBe(true);
+ });
+ });
+});
+
+describe('Resource: trek://journeys/{journeyId}/contributors', () => {
+ it('returns the contributors, with the legacy [] fallback shape', async () => {
+ const { user } = createUser(testDb);
+ await withHarness(user.id, async (h) => {
+ const journey = await createJourney(h);
+ const data = parseResourceResult(await h.client.readResource({ uri: `trek://journeys/${journey.id}/contributors` })) as any[];
+ expect(Array.isArray(data)).toBe(true);
+ expect(data.map((c) => c.user_id ?? c.id)).toContain(user.id);
+ });
+ });
+});
+
+describe('Journey resource gating', () => {
+ it('does not register the resources when the journey addon is off', async () => {
+ const { user } = createUser(testDb);
+ setAddonEnabled(testDb, ADDON_IDS.JOURNEY, false);
+ await withHarness(user.id, async (h) => {
+ await expect(h.client.readResource({ uri: 'trek://journeys' })).rejects.toThrow();
+ });
+ });
+
+ it('does not register the resources without the journey:read scope', async () => {
+ const { user } = createUser(testDb);
+ const h = await createMcpHarness({ userId: user.id, scopes: ['trips:read'] });
+ try {
+ await expect(h.client.readResource({ uri: 'trek://journeys' })).rejects.toThrow();
+ } finally {
+ await h.cleanup();
+ }
+ });
+});