mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
Fold nest mcp (#2017)
* refactor(server): fold @trek/nest-mcp into server/src/nest-mcp * docs(server): point nest-mcp references at server/src/nest-mcp * remove tracked md file
This commit is contained in:
@@ -1,45 +1,15 @@
|
||||
import type { McpAccessGroup, McpAccessMode, McpAccessPolicy, McpAccessValidator } from '@trek/nest-mcp';
|
||||
import type { McpAccessGroup, McpAccessMode, McpAccessPolicy, McpAccessValidator } from '../nest-mcp';
|
||||
import { ALL_SCOPES, canRead, canWrite, type Scope, type ScopeGroup } from './scopes';
|
||||
|
||||
/** The mode half of every scope: 'read' | 'write' | 'delete' | 'share'. */
|
||||
export type ScopeMode = Scope extends `${string}:${infer M}` ? M : never;
|
||||
|
||||
/**
|
||||
* TREK's context shape for @trek/nest-mcp handlers, predicates and the
|
||||
* access policy — mirrors what registerTools() receives per session.
|
||||
* The group registry types every decorator's `access.group` against the
|
||||
* scope-derived union, so a typo'd group is a compile error in `.mcp.ts`.
|
||||
*/
|
||||
declare module '@trek/nest-mcp' {
|
||||
interface McpContext {
|
||||
userId: number;
|
||||
scopes: string[] | null;
|
||||
isStaticToken: boolean;
|
||||
/**
|
||||
* Fire-once static-token deprecation notice closure (built per session in
|
||||
* src/mcp/index.ts and threaded through registerTools → registry.attach).
|
||||
* Optional so direct createTestRegistry ctxs without it keep working —
|
||||
* consumers (list_trips / get_trip_summary) treat absence as "no notice".
|
||||
*/
|
||||
getDeprecationNotice?: () => string | null;
|
||||
}
|
||||
// The augmentation pattern requires an empty single-extends interface —
|
||||
// same false positive (and same disable) as McpContext in @trek/nest-mcp.
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
interface McpAccessGroupRegistry extends Record<ScopeGroup, true> {}
|
||||
// Same augmentation, for the mode half. Without it `mode` is 'read' |
|
||||
// 'write' and journey's share tools could only be expressed as opaque
|
||||
// predicates, which the boot gate below cannot check.
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
interface McpAccessModeRegistry extends Record<ScopeMode, true> {}
|
||||
}
|
||||
|
||||
type AssertExact<A, B> = [A] extends [B] ? ([B] extends [A] ? true : never) : never;
|
||||
|
||||
/**
|
||||
* Compile-time lockstep: the augmented `access.group` union must be exactly
|
||||
* `ScopeGroup` — fails `npm run typecheck` if the augmentation above drifts
|
||||
* (which is also the proof that unknown groups like 'budgets' are rejected).
|
||||
* Compile-time lockstep: `access.group` (from the registry interfaces in
|
||||
* src/nest-mcp/types.ts) must be exactly `ScopeGroup` — fails
|
||||
* `npm run typecheck` if the registries drift from scopes.ts.
|
||||
* Exported so the policy unit test has a runtime touchpoint.
|
||||
*/
|
||||
export const MCP_ACCESS_GROUPS_MATCH_SCOPE_GROUPS: AssertExact<McpAccessGroup, ScopeGroup> = true;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import type { McpAttachOptions, McpRegistry } from '@trek/nest-mcp';
|
||||
import type { McpAttachOptions, McpRegistry } from '../nest-mcp';
|
||||
|
||||
export function registerTools(registry: McpRegistry | null, server: McpServer, userId: number, scopes: string[] | null, isStaticToken = false, getDeprecationNotice: () => string | null = () => null, onInvoke?: McpAttachOptions['onInvoke']): void {
|
||||
// The trip tools moved to the DI-discovered src/nest/trips/trips.mcp.ts and
|
||||
@@ -61,7 +61,7 @@ export function registerTools(registry: McpRegistry | null, server: McpServer, u
|
||||
// static-token notice to auth.mcp.ts (its `if (isStaticToken)` became a
|
||||
// `when` gate — the registry hands `when` the session context).
|
||||
|
||||
// Decorator-registered domains (@trek/nest-mcp). Production passes the
|
||||
// Decorator-registered domains (src/nest-mcp). Production passes the
|
||||
// container-discovered McpRegistryService (injected into the transport
|
||||
// service); the no-Nest harness hands in createTestRegistry()'s build.
|
||||
// A null registry (direct callers without either) ⇒ skip.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { errorResult } from '@trek/nest-mcp';
|
||||
import { errorResult } from '../../nest-mcp';
|
||||
|
||||
// Generic MCP result helpers and annotation presets live in @trek/nest-mcp
|
||||
// Generic MCP result helpers and annotation presets live in src/nest-mcp
|
||||
// (single source for the decorator-based domains). Re-exported so the
|
||||
// @McpController files keep importing from here. Everything below is PURE —
|
||||
// the impure guards (hasTripPermission/isAdminUser/safeBroadcast) moved onto
|
||||
@@ -15,7 +15,7 @@ export {
|
||||
TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
|
||||
export const MAX_MCP_TRIP_DAYS = 90;
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# nest-mcp
|
||||
|
||||
Decorator-driven MCP registration for NestJS. Domains declare MCP tools, resources and prompts as decorated methods on ordinary Nest providers; a discovery-backed registry collects them at boot and attaches them — filtered by the access policy — onto each per-session `McpServer`.
|
||||
|
||||
Formerly the standalone `@trek/nest-mcp` workspace package; folded into the server 2026-08-22. Two invariants survive the fold:
|
||||
|
||||
- **Self-contained**: this directory imports nothing from the rest of `server/` except the type-only `../mcp/scopes` import in `types.ts` (which types `access.group`/`mode` against the real scope unions). Keep it that way — new TREK semantics belong in the host layer, not here.
|
||||
- **No scope semantics of its own**: access *meaning* comes entirely from the `accessPolicy`/`validateAccess` given at `McpModule.forRoot(...)` — TREK's live in `src/mcp/nest-mcp-policy.ts`.
|
||||
|
||||
Tests live in `server/tests/unit/nest-mcp/` and run with the normal server suite; coverage is gated at ≥80% in `server/vitest.config.ts`.
|
||||
|
||||
## API
|
||||
|
||||
### Decorators
|
||||
|
||||
```ts
|
||||
import { McpController, Tool, Resource, ResourceTemplate, Prompt } from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
|
||||
@McpController() // implies @Injectable(); register the class in a module's providers: []
|
||||
export class ThingsMcp {
|
||||
constructor(private readonly things: ThingsService) {}
|
||||
|
||||
@Tool({
|
||||
name: 'list_things',
|
||||
description: 'List all things.',
|
||||
inputSchema: {}, // ZodRawShape, passed straight to the SDK
|
||||
annotations: { readOnlyHint: true },
|
||||
access: { group: 'things', mode: 'read' }, // resolved by the accessPolicy
|
||||
})
|
||||
async listThings(_args: Record<string, never>, ctx: McpContext) {
|
||||
return { content: [{ type: 'text', text: JSON.stringify(this.things.list(ctx.userId)) }] };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `@Tool(options)` — mirrors `server.registerTool` (`name`, `title`, `description`, `inputSchema`, `outputSchema`, `annotations`, `_meta`). Handler: `(args, ctx)`; `args` is `{}` when no `inputSchema` was declared.
|
||||
- `@Resource(options)` — fixed URI (`uri`, `mimeType`, …). Handler: `(uri: URL, ctx)`.
|
||||
- `@ResourceTemplate(options)` — `uriTemplate` (RFC 6570). Handler: `(uri: URL, variables, ctx)`. (No `list`/`complete` template callbacks yet — extend when a domain needs them.)
|
||||
- `@Prompt(options)` — mirrors `registerPrompt` (`argsSchema` entries must be string-valued Zod schemas). Handler: `(args, ctx)`.
|
||||
|
||||
`ctx` always takes the SDK `extra` slot — the last handler argument.
|
||||
|
||||
### Access control
|
||||
|
||||
Every decorator accepts `access` and `when`:
|
||||
|
||||
- **Declarative** — `access: { group: 'things', mode: 'read' | 'write' }`, resolved by the `accessPolicy` given once at `McpModule.forRoot(...)`. `group` and `mode` are typed against the scope-derived unions in `types.ts`, so a typo'd group is a compile error in `.mcp.ts` files.
|
||||
- **Predicate** — `access: (ctx) => boolean`, bypasses the policy.
|
||||
- **Availability gate** — `when: (ctx, self) => boolean`, evaluated *before* `access` (both must pass). Use it for feature/addon toggles so scope markers stay declarative: `when: (_ctx, self: PackingMcp) => self.addons.isAddonEnabled(...)`, `access: { group: 'packing', mode: 'read' }`. `self` is the `@McpController()` instance, handed in at attach time — the options object is built when the class is defined, so without it a gate can only reach a module-level singleton, and hosts end up constructing a second copy of a service outside their own container to answer a toggle.
|
||||
- **Omitted `access`** — the entry is always registered (subject to `when`).
|
||||
|
||||
### Result helpers & annotation presets
|
||||
|
||||
Handler-side conveniences, exported from the barrel so decorated domains need nothing from the legacy MCP layer:
|
||||
|
||||
```ts
|
||||
import { ok, errorResult, demoDenied, TOOL_ANNOTATIONS_READONLY } from '../../nest-mcp';
|
||||
|
||||
ok({ tags }) // { content: [{ type: 'text', text: <pretty JSON> }] }
|
||||
errorResult('Tag not found.') // { content: [...], isError: true } — message verbatim
|
||||
demoDenied() // canned demo-mode write refusal
|
||||
```
|
||||
|
||||
Six `TOOL_ANNOTATIONS_*` presets cover the read/write/delete/idempotency matrix (plus `OPEN_WORLD` variants). TREK-specific canned errors (permission wording, RBAC lookups) belong in the host layer, built on `errorResult` — see `server/src/mcp/tools/_shared.ts`, which re-exports the generic helpers from here.
|
||||
|
||||
### Fail-fast validation
|
||||
|
||||
`McpRegistryService` runs `registry.validate()` at boot (`onModuleInit`), and `createTestRegistry` runs it on construction, so misconfiguration breaks startup instead of MCP session creation:
|
||||
|
||||
- duplicate names per kind (fixed resources: duplicate URIs);
|
||||
- declarative `access` without a configured `accessPolicy`;
|
||||
- declarative `access` rejected by the optional `validateAccess` hook.
|
||||
|
||||
All problems are aggregated into one `Invalid MCP registry: ...` error, so a single boot failure reports every misconfiguration.
|
||||
|
||||
`validateAccess?: (access, entry) => string | null | undefined` (on both `McpModule.forRoot(...)` and `createTestRegistry(...)` options) is called once per entry with declarative access — predicates are opaque and skipped. Return a problem description to fail boot, null/undefined to accept:
|
||||
|
||||
```ts
|
||||
McpModule.forRoot({
|
||||
accessPolicy,
|
||||
validateAccess: ({ group, mode }) =>
|
||||
hostKnowsGroupMode(group, mode) ? null : `no '${group}:${mode}' scope`,
|
||||
})
|
||||
```
|
||||
|
||||
### Context and access typing
|
||||
|
||||
`McpContext` (the per-session context handed to every handler, predicate and the policy) and the `McpAccessGroupRegistry`/`McpAccessModeRegistry` interfaces that type `access.group`/`mode` are defined directly in `types.ts`. Before the fold they were empty interfaces the host augmented via `declare module '@trek/nest-mcp'`; the TREK shapes are now baked in, with the lockstep asserts in `src/mcp/nest-mcp-policy.ts` pinning the registries to `scopes.ts` at compile time.
|
||||
|
||||
### Wiring
|
||||
|
||||
```ts
|
||||
// AppModule
|
||||
McpModule.forRoot({ accessPolicy: (access, ctx) => /* scope semantics */ })
|
||||
|
||||
// wherever per-session servers are built (may be outside Nest — hand the
|
||||
// registry over after app.init()):
|
||||
const registry = app.get(McpRegistryService);
|
||||
registry.attach(server, { userId, scopes, isStaticToken });
|
||||
registry.list(); // introspection
|
||||
```
|
||||
|
||||
### Testing without Nest
|
||||
|
||||
```ts
|
||||
import { createTestRegistry } from '../../../src/nest-mcp';
|
||||
|
||||
const registry = createTestRegistry([new ThingsMcp(new ThingsService(db))], { accessPolicy });
|
||||
registry.attach(server, ctx);
|
||||
```
|
||||
|
||||
## Migrating a TREK MCP domain (recipe)
|
||||
|
||||
1. Create `server/src/nest/<domain>/<domain>.mcp.ts`: an `@McpController()` class injecting the domain's Nest service. Port each `server.registerTool(...)` from `server/src/mcp/tools/<domain>.ts` to a `@Tool()` method **byte-identically** (names, descriptions, schemas, annotations, error strings, `ok()` payloads).
|
||||
2. Replace the registrar's `canRead/canWrite` registration-time gates with `access: { group, mode }` (TREK's policy in `server/src/mcp/nest-mcp-policy.ts` implements the `scopes.ts` semantics). Addon gates become `when: (_ctx, self: XMcp) => self.addons.isAddonEnabled(ADDON_IDS.X)` alongside the declarative `access`.
|
||||
3. Add the class to the domain module's `providers: []`.
|
||||
4. Delete the legacy registrar file and its call in `server/src/mcp/tools.ts`.
|
||||
5. Add one line constructing the instance in `server/tests/helpers/mcp-test-controllers.ts` and keep the domain's existing unit tests green — behavior must be indistinguishable to a client.
|
||||
|
||||
## Notes
|
||||
|
||||
The MCP SDK's exports map uses extension-less wildcards that TypeScript cannot resolve; `server/tsconfig.json` `paths` and `server/vitest.config.ts` aliases point at the CJS dist files. `registry.ts` is the only file here importing the SDK.
|
||||
@@ -0,0 +1,42 @@
|
||||
import { addEntry, markController, type ClassRef } from './metadata';
|
||||
import type { PromptOptions, ResourceOptions, ResourceTemplateOptions, ToolOptions } from './types';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Marks a class as an MCP controller. Implies `@Injectable()` — register the
|
||||
* class in a module's `providers: []` and inject domain services through the
|
||||
* constructor as usual. Discovery scans ONLY marked classes (explicit opt-in,
|
||||
* deterministic registry).
|
||||
*/
|
||||
export function McpController(): ClassDecorator {
|
||||
return (target) => {
|
||||
Injectable()(target);
|
||||
markController(target as unknown as ClassRef);
|
||||
};
|
||||
}
|
||||
|
||||
function mcpMethodDecorator(entry: (methodName: string) => Parameters<typeof addEntry>[1]): MethodDecorator {
|
||||
return (target, propertyKey) => {
|
||||
addEntry((target as { constructor: unknown }).constructor as ClassRef, entry(String(propertyKey)));
|
||||
};
|
||||
}
|
||||
|
||||
/** Registers the method as an MCP tool. Handler signature: `(args, ctx)`. */
|
||||
export function Tool(options: ToolOptions): MethodDecorator {
|
||||
return mcpMethodDecorator((methodName) => ({ kind: 'tool', methodName, options }));
|
||||
}
|
||||
|
||||
/** Registers the method as a fixed-URI MCP resource. Handler signature: `(uri: URL, ctx)`. */
|
||||
export function Resource(options: ResourceOptions): MethodDecorator {
|
||||
return mcpMethodDecorator((methodName) => ({ kind: 'resource', methodName, options }));
|
||||
}
|
||||
|
||||
/** Registers the method as an MCP resource template. Handler signature: `(uri: URL, variables, ctx)`. */
|
||||
export function ResourceTemplate(options: ResourceTemplateOptions): MethodDecorator {
|
||||
return mcpMethodDecorator((methodName) => ({ kind: 'resourceTemplate', methodName, options }));
|
||||
}
|
||||
|
||||
/** Registers the method as an MCP prompt. Handler signature: `(args, ctx)`. */
|
||||
export function Prompt(options: PromptOptions): MethodDecorator {
|
||||
return mcpMethodDecorator((methodName) => ({ kind: 'prompt', methodName, options }));
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Result-shape helpers and tool-annotation presets shared by MCP handlers.
|
||||
* App-agnostic on purpose — host-specific canned errors (permission wording,
|
||||
* RBAC lookups, broadcasts) belong in the host, built on `errorResult`.
|
||||
*/
|
||||
|
||||
/** The text-content result shape MCP tool handlers return. */
|
||||
export interface McpTextResult {
|
||||
content: { type: 'text'; text: string }[];
|
||||
isError?: boolean;
|
||||
}
|
||||
|
||||
/** Success result: `data` pretty-printed as a single JSON text block. */
|
||||
export function ok(data: unknown): McpTextResult {
|
||||
return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] };
|
||||
}
|
||||
|
||||
/** Error result with a verbatim message (no formatting, no prefix). */
|
||||
export function errorResult(text: string): McpTextResult {
|
||||
return { content: [{ type: 'text' as const, text }], isError: true };
|
||||
}
|
||||
|
||||
/** Canned refusal for write tools when the acting user is a demo account. */
|
||||
export function demoDenied(): McpTextResult {
|
||||
return errorResult('Write operations are disabled in demo mode.');
|
||||
}
|
||||
|
||||
export const TOOL_ANNOTATIONS_READONLY = {
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
} as const;
|
||||
|
||||
export const TOOL_ANNOTATIONS_OPEN_WORLD_READONLY = {
|
||||
...TOOL_ANNOTATIONS_READONLY,
|
||||
openWorldHint: true,
|
||||
} as const;
|
||||
|
||||
export const TOOL_ANNOTATIONS_WRITE = {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
} as const;
|
||||
|
||||
export const TOOL_ANNOTATIONS_DELETE = {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: true,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
} as const;
|
||||
|
||||
export const TOOL_ANNOTATIONS_NON_IDEMPOTENT = {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: false,
|
||||
openWorldHint: false,
|
||||
} as const;
|
||||
|
||||
export const TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT = {
|
||||
...TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
openWorldHint: true,
|
||||
} as const;
|
||||
@@ -0,0 +1,39 @@
|
||||
export { McpController, Prompt, Resource, ResourceTemplate, Tool } from './decorators';
|
||||
export {
|
||||
demoDenied,
|
||||
errorResult,
|
||||
ok,
|
||||
TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
|
||||
TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
type McpTextResult,
|
||||
} from './helpers';
|
||||
export { McpRegistryService } from './mcp-registry.service';
|
||||
export { McpModule } from './mcp.module';
|
||||
export { McpRegistry, type McpRegistryOptions } from './registry';
|
||||
export { createTestRegistry } from './testing';
|
||||
export {
|
||||
MCP_MODULE_OPTIONS,
|
||||
type McpAccess,
|
||||
type McpAccessGroup,
|
||||
type McpAccessGroupRegistry,
|
||||
type McpAccessMode,
|
||||
type McpAccessModeRegistry,
|
||||
type McpAccessPolicy,
|
||||
type McpAccessPredicate,
|
||||
type McpAccessValidator,
|
||||
type McpAttachOptions,
|
||||
type McpContext,
|
||||
type McpDeclarativeAccess,
|
||||
type McpEntry,
|
||||
type McpEntryKind,
|
||||
type McpModuleOptions,
|
||||
type McpRegistryListing,
|
||||
type PromptOptions,
|
||||
type ResourceOptions,
|
||||
type ResourceTemplateOptions,
|
||||
type ToolOptions,
|
||||
} from './types';
|
||||
@@ -0,0 +1,37 @@
|
||||
import { isMcpController } from './metadata';
|
||||
import { McpRegistry } from './registry';
|
||||
import { MCP_MODULE_OPTIONS, type McpModuleOptions } from './types';
|
||||
import { Inject, Injectable, type OnModuleInit } from '@nestjs/common';
|
||||
import { DiscoveryService, MetadataScanner } from '@nestjs/core';
|
||||
|
||||
/**
|
||||
* DI-discovered registry: at boot, scans every provider marked with
|
||||
* `@McpController()` and records its decorated methods. Attach it to a
|
||||
* per-session `McpServer` with `attach(server, ctx)`.
|
||||
*/
|
||||
@Injectable()
|
||||
export class McpRegistryService extends McpRegistry implements OnModuleInit {
|
||||
constructor(
|
||||
private readonly discovery: DiscoveryService,
|
||||
private readonly scanner: MetadataScanner,
|
||||
@Inject(MCP_MODULE_OPTIONS) options: McpModuleOptions,
|
||||
) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
onModuleInit(): void {
|
||||
// A provider can be wrapped once per module that lists it — dedupe by
|
||||
// instance so an entry is never recorded (and later registered) twice.
|
||||
const seen = new Set<object>();
|
||||
for (const wrapper of this.discovery.getProviders()) {
|
||||
const { instance, metatype } = wrapper;
|
||||
if (!instance || typeof instance !== 'object' || seen.has(instance)) continue;
|
||||
if (!isMcpController(metatype)) continue;
|
||||
seen.add(instance);
|
||||
this.register(instance, this.scanner.getAllMethodNames(Object.getPrototypeOf(instance)));
|
||||
}
|
||||
// Fail app boot on duplicate names / policy-less declarative access
|
||||
// instead of failing per-session at attach().
|
||||
this.validate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { McpRegistryService } from './mcp-registry.service';
|
||||
import { MCP_MODULE_OPTIONS, type McpModuleOptions } from './types';
|
||||
import { Module, type DynamicModule } from '@nestjs/common';
|
||||
import { DiscoveryModule } from '@nestjs/core';
|
||||
|
||||
@Module({})
|
||||
export class McpModule {
|
||||
/**
|
||||
* Registers the discovery-backed `McpRegistryService` globally. The
|
||||
* `accessPolicy` resolves every declarative `access: { group, mode }`
|
||||
* marker — the package itself defines no scope semantics.
|
||||
*/
|
||||
static forRoot(options: McpModuleOptions = {}): DynamicModule {
|
||||
return {
|
||||
module: McpModule,
|
||||
global: true,
|
||||
imports: [DiscoveryModule],
|
||||
providers: [{ provide: MCP_MODULE_OPTIONS, useValue: options }, McpRegistryService],
|
||||
exports: [McpRegistryService],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { McpEntry } from './types';
|
||||
|
||||
/**
|
||||
* Metadata store. A package-private WeakMap/WeakSet keyed by class
|
||||
* constructor instead of reflect-metadata: it has zero runtime
|
||||
* prerequisites (no polyfill import order to get right), works in bare
|
||||
* vitest workers and in `createTestRegistry` without a Nest app, and is
|
||||
* trivially extraction-clean.
|
||||
*/
|
||||
|
||||
/** A class constructor, without using the banned bare `Function` type. */
|
||||
export type ClassRef = abstract new (...args: never[]) => unknown;
|
||||
|
||||
const controllers = new WeakSet<ClassRef>();
|
||||
const entries = new WeakMap<ClassRef, Map<string, McpEntry>>();
|
||||
|
||||
export function markController(ctor: ClassRef): void {
|
||||
controllers.add(ctor);
|
||||
}
|
||||
|
||||
export function isMcpController(ctor: unknown): ctor is ClassRef {
|
||||
return typeof ctor === 'function' && controllers.has(ctor as ClassRef);
|
||||
}
|
||||
|
||||
export function addEntry(ctor: ClassRef, entry: McpEntry): void {
|
||||
let map = entries.get(ctor);
|
||||
if (!map) {
|
||||
map = new Map();
|
||||
entries.set(ctor, map);
|
||||
}
|
||||
map.set(entry.methodName, entry);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the entry recorded for `methodName`, walking the constructor
|
||||
* prototype chain so inherited decorated methods are found on subclasses.
|
||||
*/
|
||||
export function getEntry(ctor: ClassRef, methodName: string): McpEntry | undefined {
|
||||
let current: ClassRef | null = ctor;
|
||||
while (current) {
|
||||
const found = entries.get(current)?.get(methodName);
|
||||
if (found) return found;
|
||||
const parent: unknown = Object.getPrototypeOf(current);
|
||||
current = typeof parent === 'function' ? (parent as ClassRef) : null;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
import { getEntry, isMcpController, type ClassRef } from './metadata';
|
||||
import type {
|
||||
McpAccessPolicy,
|
||||
McpAccessValidator,
|
||||
McpAttachOptions,
|
||||
McpContext,
|
||||
McpEntry,
|
||||
McpRegistryListing,
|
||||
PromptOptions,
|
||||
ResourceOptions,
|
||||
ResourceTemplateOptions,
|
||||
ToolOptions,
|
||||
} from './types';
|
||||
import { ResourceTemplate as SdkResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
|
||||
import type { ZodRawShape } from 'zod';
|
||||
|
||||
interface BoundEntry {
|
||||
entry: McpEntry;
|
||||
instance: object;
|
||||
}
|
||||
|
||||
export interface McpRegistryOptions {
|
||||
accessPolicy?: McpAccessPolicy;
|
||||
validateAccess?: McpAccessValidator;
|
||||
}
|
||||
|
||||
type AnyHandler = (this: unknown, ...handlerArgs: unknown[]) => unknown;
|
||||
|
||||
/**
|
||||
* Structural view of the SDK registration surface. The SDK's real signatures
|
||||
* are generic over the Zod shapes; the registry passes schemas straight
|
||||
* through and binds `ctx` where the SDK would pass `extra`, so it needs (and
|
||||
* exposes) none of that type-level machinery.
|
||||
*/
|
||||
interface LooseRegistrar {
|
||||
registerTool(name: string, config: Record<string, unknown>, cb: (...cbArgs: unknown[]) => unknown): unknown;
|
||||
registerResource(
|
||||
name: string,
|
||||
uriOrTemplate: string | SdkResourceTemplate,
|
||||
config: Record<string, unknown>,
|
||||
cb: (...cbArgs: unknown[]) => unknown,
|
||||
): unknown;
|
||||
registerPrompt(name: string, config: Record<string, unknown>, cb: (...cbArgs: unknown[]) => unknown): unknown;
|
||||
}
|
||||
|
||||
function describeBound({ entry, instance }: BoundEntry): string {
|
||||
return `${(instance as { constructor: { name: string } }).constructor.name}.${entry.methodName}`;
|
||||
}
|
||||
|
||||
/** Own + inherited method names, excluding constructor and Object.prototype. */
|
||||
function enumerateMethodNames(instance: object): string[] {
|
||||
const names = new Set<string>();
|
||||
let proto: object | null = Object.getPrototypeOf(instance);
|
||||
while (proto && proto !== Object.prototype) {
|
||||
for (const name of Object.getOwnPropertyNames(proto)) {
|
||||
if (name === 'constructor') continue;
|
||||
const descriptor = Object.getOwnPropertyDescriptor(proto, name);
|
||||
if (typeof descriptor?.value === 'function') names.add(name);
|
||||
}
|
||||
proto = Object.getPrototypeOf(proto);
|
||||
}
|
||||
return [...names];
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds every decorated MCP entry bound to its provider instance and attaches
|
||||
* them, filtered by access, onto a per-session `McpServer`. Plain class with
|
||||
* no DI so `createTestRegistry` can build one without a Nest app;
|
||||
* `McpRegistryService` is the DI-discovered subclass.
|
||||
*/
|
||||
export class McpRegistry {
|
||||
private readonly bound: BoundEntry[] = [];
|
||||
private readonly accessPolicy?: McpAccessPolicy;
|
||||
private readonly validateAccess?: McpAccessValidator;
|
||||
|
||||
constructor(options: McpRegistryOptions = {}) {
|
||||
this.accessPolicy = options.accessPolicy;
|
||||
this.validateAccess = options.validateAccess;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records every decorated method of `instance`. `methodNames` (e.g. from
|
||||
* Nest's MetadataScanner) narrows the scan; omitted, the instance's
|
||||
* prototype chain is enumerated directly.
|
||||
*/
|
||||
register(instance: object, methodNames?: readonly string[]): void {
|
||||
const ctor = (instance as { constructor: unknown }).constructor;
|
||||
if (!isMcpController(ctor)) {
|
||||
throw new Error(`${(ctor as ClassRef).name} is not decorated with @McpController()`);
|
||||
}
|
||||
const names = methodNames ?? enumerateMethodNames(instance);
|
||||
for (const name of new Set(names)) {
|
||||
const entry = getEntry(ctor, name);
|
||||
if (entry) this.bound.push({ entry, instance });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers every entry passing its access check onto `server`, binding
|
||||
* `ctx` as the handler's last argument (in the SDK `extra` slot). `opts`
|
||||
* carries per-session hooks — see `McpAttachOptions`.
|
||||
*/
|
||||
attach(server: McpServer, ctx: McpContext, opts?: McpAttachOptions): void {
|
||||
const registrar = server as unknown as LooseRegistrar;
|
||||
for (const { entry, instance } of this.bound) {
|
||||
if (!this.allowed(entry, ctx, instance)) continue;
|
||||
const handler = (instance as unknown as Record<string, AnyHandler>)[entry.methodName];
|
||||
switch (entry.kind) {
|
||||
case 'tool':
|
||||
this.attachTool(registrar, entry.options, instance, handler, ctx, opts);
|
||||
break;
|
||||
case 'resource':
|
||||
this.attachResource(registrar, entry.options, instance, handler, ctx, opts);
|
||||
break;
|
||||
case 'resourceTemplate':
|
||||
this.attachResourceTemplate(registrar, entry.options, instance, handler, ctx, opts);
|
||||
break;
|
||||
case 'prompt':
|
||||
this.attachPrompt(registrar, entry.options, instance, handler, ctx, opts);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail-fast configuration check — call once after all instances are
|
||||
* registered (McpRegistryService runs it at boot, createTestRegistry on
|
||||
* construction) so misconfiguration breaks app startup instead of MCP
|
||||
* session creation:
|
||||
* - duplicate names per kind (fixed resources: duplicate URIs), which the
|
||||
* SDK would otherwise reject per-session at attach();
|
||||
* - declarative access without a configured accessPolicy;
|
||||
* - declarative access the host-supplied `validateAccess` hook rejects
|
||||
* (predicates are opaque to the host and never passed to it).
|
||||
* All problems are aggregated into one error so a single boot failure
|
||||
* reports every misconfiguration.
|
||||
*/
|
||||
validate(): void {
|
||||
const seen = new Map<string, BoundEntry>();
|
||||
const duplicates: string[] = [];
|
||||
const unresolvable: string[] = [];
|
||||
const invalidAccess: string[] = [];
|
||||
for (const bound of this.bound) {
|
||||
const { entry } = bound;
|
||||
const key =
|
||||
entry.kind === 'resource' ? `resource uri "${entry.options.uri}"` : `${entry.kind} "${entry.options.name}"`;
|
||||
const prior = seen.get(key);
|
||||
if (prior) duplicates.push(`${key} (${describeBound(prior)} and ${describeBound(bound)})`);
|
||||
else seen.set(key, bound);
|
||||
const access = entry.options.access;
|
||||
if (access === undefined || typeof access === 'function') continue;
|
||||
if (!this.accessPolicy) unresolvable.push(`${key} (${describeBound(bound)})`);
|
||||
const problem = this.validateAccess?.(access, this.toListing(bound));
|
||||
if (problem) invalidAccess.push(`${key} (${describeBound(bound)}): ${problem}`);
|
||||
}
|
||||
const problems: string[] = [];
|
||||
if (duplicates.length) problems.push(`duplicate MCP registrations: ${duplicates.join(', ')}`);
|
||||
if (unresolvable.length) {
|
||||
problems.push(
|
||||
`entries declare declarative access but no accessPolicy was configured ` +
|
||||
`(McpModule.forRoot({ accessPolicy })): ${unresolvable.join(', ')}`,
|
||||
);
|
||||
}
|
||||
if (invalidAccess.length) problems.push(`invalid access declarations: ${invalidAccess.join(', ')}`);
|
||||
if (problems.length) throw new Error(`Invalid MCP registry: ${problems.join('; ')}`);
|
||||
}
|
||||
|
||||
/** Introspection: every recorded entry, regardless of access. */
|
||||
list(): McpRegistryListing[] {
|
||||
return this.bound.map((bound) => this.toListing(bound));
|
||||
}
|
||||
|
||||
private toListing({ entry, instance }: BoundEntry): McpRegistryListing {
|
||||
return {
|
||||
kind: entry.kind,
|
||||
name: entry.options.name,
|
||||
className: (instance as { constructor: { name: string } }).constructor.name,
|
||||
methodName: entry.methodName,
|
||||
access: entry.options.access,
|
||||
};
|
||||
}
|
||||
|
||||
private allowed(entry: McpEntry, ctx: McpContext, instance: object): boolean {
|
||||
// The declaring instance goes in so the gate can read an injected
|
||||
// collaborator. It is resolved here, at attach, rather than captured when
|
||||
// the options object was built — the class body runs long before the
|
||||
// container exists.
|
||||
if (entry.options.when && !entry.options.when(ctx, instance)) return false;
|
||||
const access = entry.options.access;
|
||||
if (access === undefined) return true;
|
||||
if (typeof access === 'function') return access(ctx);
|
||||
if (!this.accessPolicy) {
|
||||
// Fail loud: silently registering would leak a gated entry, silently
|
||||
// skipping would be undebuggable.
|
||||
throw new Error(
|
||||
`MCP ${entry.kind} "${entry.options.name}" declares declarative access ` +
|
||||
`but no accessPolicy was configured (McpModule.forRoot({ accessPolicy }))`,
|
||||
);
|
||||
}
|
||||
return this.accessPolicy(access, ctx);
|
||||
}
|
||||
|
||||
private attachTool(
|
||||
registrar: LooseRegistrar,
|
||||
options: ToolOptions,
|
||||
instance: object,
|
||||
handler: AnyHandler,
|
||||
ctx: McpContext,
|
||||
opts?: McpAttachOptions,
|
||||
): void {
|
||||
const config: Record<string, unknown> = {
|
||||
title: options.title,
|
||||
description: options.description,
|
||||
inputSchema: options.inputSchema as ZodRawShape | undefined,
|
||||
outputSchema: options.outputSchema,
|
||||
annotations: options.annotations,
|
||||
_meta: options._meta,
|
||||
};
|
||||
// The SDK invokes the callback as (args, extra) when inputSchema is
|
||||
// present (even an empty shape) and as (extra) otherwise — normalize so
|
||||
// the decorated method always receives (args, ctx).
|
||||
const cb =
|
||||
options.inputSchema !== undefined
|
||||
? (args: unknown, _extra: unknown) => {
|
||||
opts?.onInvoke?.({ kind: 'tool', name: options.name });
|
||||
return handler.call(instance, args, ctx);
|
||||
}
|
||||
: (_extra: unknown) => {
|
||||
opts?.onInvoke?.({ kind: 'tool', name: options.name });
|
||||
return handler.call(instance, {}, ctx);
|
||||
};
|
||||
registrar.registerTool(options.name, config, cb);
|
||||
}
|
||||
|
||||
private attachResource(
|
||||
registrar: LooseRegistrar,
|
||||
options: ResourceOptions,
|
||||
instance: object,
|
||||
handler: AnyHandler,
|
||||
ctx: McpContext,
|
||||
opts?: McpAttachOptions,
|
||||
): void {
|
||||
const metadata: Record<string, unknown> = {
|
||||
title: options.title,
|
||||
description: options.description,
|
||||
mimeType: options.mimeType,
|
||||
_meta: options._meta,
|
||||
};
|
||||
registrar.registerResource(options.name, options.uri, metadata, (uri: unknown, _extra: unknown) => {
|
||||
opts?.onInvoke?.({ kind: 'resource', name: options.name });
|
||||
return handler.call(instance, uri, ctx);
|
||||
});
|
||||
}
|
||||
|
||||
private attachResourceTemplate(
|
||||
registrar: LooseRegistrar,
|
||||
options: ResourceTemplateOptions,
|
||||
instance: object,
|
||||
handler: AnyHandler,
|
||||
ctx: McpContext,
|
||||
opts?: McpAttachOptions,
|
||||
): void {
|
||||
const metadata: Record<string, unknown> = {
|
||||
title: options.title,
|
||||
description: options.description,
|
||||
mimeType: options.mimeType,
|
||||
_meta: options._meta,
|
||||
};
|
||||
registrar.registerResource(
|
||||
options.name,
|
||||
new SdkResourceTemplate(options.uriTemplate, { list: undefined }),
|
||||
metadata,
|
||||
(uri: unknown, variables: unknown, _extra: unknown) => {
|
||||
opts?.onInvoke?.({ kind: 'resourceTemplate', name: options.name });
|
||||
return handler.call(instance, uri, variables, ctx);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private attachPrompt(
|
||||
registrar: LooseRegistrar,
|
||||
options: PromptOptions,
|
||||
instance: object,
|
||||
handler: AnyHandler,
|
||||
ctx: McpContext,
|
||||
opts?: McpAttachOptions,
|
||||
): void {
|
||||
const config: Record<string, unknown> = {
|
||||
title: options.title,
|
||||
description: options.description,
|
||||
argsSchema: options.argsSchema,
|
||||
};
|
||||
const cb =
|
||||
options.argsSchema !== undefined
|
||||
? (args: unknown, _extra: unknown) => {
|
||||
opts?.onInvoke?.({ kind: 'prompt', name: options.name });
|
||||
return handler.call(instance, args, ctx);
|
||||
}
|
||||
: (_extra: unknown) => {
|
||||
opts?.onInvoke?.({ kind: 'prompt', name: options.name });
|
||||
return handler.call(instance, {}, ctx);
|
||||
};
|
||||
registrar.registerPrompt(options.name, config, cb);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { McpRegistry, type McpRegistryOptions } from './registry';
|
||||
|
||||
/**
|
||||
* Builds a registry from hand-constructed `@McpController()` instances —
|
||||
* no Nest app required. For test harnesses that assemble a bare `McpServer`
|
||||
* (e.g. over an in-memory transport).
|
||||
*/
|
||||
export function createTestRegistry(instances: readonly object[], options: McpRegistryOptions = {}): McpRegistry {
|
||||
const registry = new McpRegistry(options);
|
||||
for (const instance of instances) registry.register(instance);
|
||||
// Same fail-fast contract as McpRegistryService.onModuleInit.
|
||||
registry.validate();
|
||||
return registry;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import type { Scope, ScopeGroup } from '../mcp/scopes';
|
||||
|
||||
import type { ZodRawShape } from 'zod';
|
||||
|
||||
/**
|
||||
* The mode half of every scope: 'read' | 'write' | 'delete' | 'share'.
|
||||
* Mirrors `ScopeMode` in `src/mcp/nest-mcp-policy.ts`, which stays the
|
||||
* exported one (its only consumer is that file's own lockstep assert).
|
||||
*/
|
||||
type ScopeMode = Scope extends `${string}:${infer M}` ? M : never;
|
||||
|
||||
/**
|
||||
* The per-session context handed to `McpRegistry.attach(server, ctx)` and
|
||||
* forwarded to every handler (last argument) and access predicate/policy —
|
||||
* mirrors what registerTools() receives per session.
|
||||
*
|
||||
* Historically this was an empty interface augmented by the host (nest-mcp
|
||||
* was a separate extraction-clean workspace); since the fold into the server
|
||||
* the TREK shape lives here directly. The type-only `../mcp/scopes` import
|
||||
* above is the one deliberate coupling to the rest of the server.
|
||||
*/
|
||||
export interface McpContext {
|
||||
userId: number;
|
||||
scopes: string[] | null;
|
||||
isStaticToken: boolean;
|
||||
/**
|
||||
* Fire-once static-token deprecation notice closure (built per session in
|
||||
* src/mcp/index.ts and threaded through registerTools → registry.attach).
|
||||
* Optional so direct createTestRegistry ctxs without it keep working —
|
||||
* consumers (list_trips / get_trip_summary) treat absence as "no notice".
|
||||
*/
|
||||
getDeprecationNotice?: () => string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registry of valid `access.group` values, keyed by the scope-derived union
|
||||
* so a typo'd group is a compile error in `.mcp.ts` files. The semantics of
|
||||
* a group come from the access policy in `src/mcp/nest-mcp-policy.ts`, not
|
||||
* from here.
|
||||
*/
|
||||
// The registry pattern requires an empty single-extends interface — the
|
||||
// keys ARE the contract, so the lint's "no members" finding is a false
|
||||
// positive.
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
export interface McpAccessGroupRegistry extends Record<ScopeGroup, true> {}
|
||||
|
||||
export type McpAccessGroup = keyof McpAccessGroupRegistry extends never
|
||||
? string
|
||||
: keyof McpAccessGroupRegistry & string;
|
||||
|
||||
/**
|
||||
* Same registry pattern for the access *mode* half. Without the full mode
|
||||
* union `mode` would be 'read' | 'write' only, and journey's share tools
|
||||
* could only be expressed as opaque predicates, which the boot gate in
|
||||
* `src/mcp/nest-mcp-policy.ts` cannot check.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
export interface McpAccessModeRegistry extends Record<ScopeMode, true> {}
|
||||
|
||||
export type McpAccessMode = keyof McpAccessModeRegistry extends never
|
||||
? 'read' | 'write'
|
||||
: keyof McpAccessModeRegistry & string;
|
||||
|
||||
/**
|
||||
* Declarative access marker resolved by the host-supplied `accessPolicy`.
|
||||
* The package attaches no semantics to `group`/`mode` — the policy does.
|
||||
*/
|
||||
export interface McpDeclarativeAccess {
|
||||
group: McpAccessGroup;
|
||||
mode: McpAccessMode;
|
||||
}
|
||||
|
||||
/** Predicate escape hatch — bypasses the policy entirely. */
|
||||
export type McpAccessPredicate = (ctx: McpContext) => boolean;
|
||||
|
||||
export type McpAccess = McpDeclarativeAccess | McpAccessPredicate;
|
||||
|
||||
/**
|
||||
* Host-supplied resolver for declarative access, given once at
|
||||
* `McpModule.forRoot({ accessPolicy })`. Return true to register the entry
|
||||
* on the session's server.
|
||||
*/
|
||||
export type McpAccessPolicy = (access: McpDeclarativeAccess, ctx: McpContext) => boolean;
|
||||
|
||||
interface McpEntryOptionsBase {
|
||||
name: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
/**
|
||||
* Availability gate evaluated BEFORE `access` (short-circuits it) — for
|
||||
* "is this feature on at all" checks like addon toggles. Keeps `access`
|
||||
* purely about permissions, so declarative scope markers still compose
|
||||
* with runtime feature gates instead of being replaced by predicates.
|
||||
*
|
||||
* `self` is the `@McpController()` instance the entry was declared on,
|
||||
* handed in at attach time. Without it the gate could only reach a
|
||||
* module-level singleton, because the options object is built when the class
|
||||
* is defined and there is no `this` yet — which is how a host ends up
|
||||
* constructing a second copy of a service outside its own container just to
|
||||
* answer "is this addon on". With it, the predicate reads an injected
|
||||
* collaborator and the dependency is visible in the module graph.
|
||||
*
|
||||
* Declared with method syntax on purpose: that makes the parameter bivariant,
|
||||
* so a predicate written against its own controller class stays assignable
|
||||
* here. The registry always passes the instance that declared the entry.
|
||||
*/
|
||||
when?(ctx: McpContext, self: object): boolean;
|
||||
/** Omitted ⇒ the entry is always registered (subject to `when`). */
|
||||
access?: McpAccess;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors the SDK's `registerTool` config. `inputSchema` is a ZodRawShape
|
||||
* passed straight through — the SDK does the parsing/validation.
|
||||
* `annotations`/`_meta` are kept structural so the package's public d.ts
|
||||
* never imports deep SDK subpaths.
|
||||
*/
|
||||
export interface ToolOptions extends McpEntryOptionsBase {
|
||||
inputSchema?: ZodRawShape;
|
||||
outputSchema?: ZodRawShape;
|
||||
annotations?: Record<string, unknown>;
|
||||
_meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Mirrors `registerResource(name, uri, metadata, cb)` for a fixed URI. */
|
||||
export interface ResourceOptions extends McpEntryOptionsBase {
|
||||
uri: string;
|
||||
mimeType?: string;
|
||||
_meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Mirrors `registerResource(name, new ResourceTemplate(uriTemplate), metadata, cb)`. */
|
||||
export interface ResourceTemplateOptions extends McpEntryOptionsBase {
|
||||
uriTemplate: string;
|
||||
mimeType?: string;
|
||||
_meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Mirrors the SDK's `registerPrompt` config (argsSchema entries must be string-valued Zod schemas). */
|
||||
export interface PromptOptions extends McpEntryOptionsBase {
|
||||
argsSchema?: ZodRawShape;
|
||||
}
|
||||
|
||||
export type McpEntryKind = 'tool' | 'resource' | 'resourceTemplate' | 'prompt';
|
||||
|
||||
/** Per-session options for `McpRegistry.attach()`. */
|
||||
export interface McpAttachOptions {
|
||||
/**
|
||||
* Called immediately before every attached handler runs, with the entry's
|
||||
* kind and registered name. This is the host's observability seam (e.g. a
|
||||
* tool-call audit trail) — nest-mcp itself attaches no semantics to it.
|
||||
* Contract: the hook MUST NOT throw; nest-mcp does not catch, so a throwing
|
||||
* hook fails the very invocation it is observing. Hosts wrap their own
|
||||
* failure handling.
|
||||
*/
|
||||
onInvoke?: (info: { kind: McpEntryKind; name: string }) => void;
|
||||
}
|
||||
|
||||
export type McpEntry =
|
||||
| { kind: 'tool'; methodName: string; options: ToolOptions }
|
||||
| { kind: 'resource'; methodName: string; options: ResourceOptions }
|
||||
| { kind: 'resourceTemplate'; methodName: string; options: ResourceTemplateOptions }
|
||||
| { kind: 'prompt'; methodName: string; options: PromptOptions };
|
||||
|
||||
/** Introspection view of one recorded entry (see `McpRegistry.list()`). */
|
||||
export interface McpRegistryListing {
|
||||
kind: McpEntryKind;
|
||||
name: string;
|
||||
className: string;
|
||||
methodName: string;
|
||||
access?: McpAccess;
|
||||
}
|
||||
|
||||
/**
|
||||
* Host-supplied per-entry check run by `validate()`. Return a problem
|
||||
* description to fail boot, null/undefined to accept. Only called for
|
||||
* entries with DECLARATIVE access (predicates are opaque to the host).
|
||||
*/
|
||||
export type McpAccessValidator = (access: McpDeclarativeAccess, entry: McpRegistryListing) => string | null | undefined;
|
||||
|
||||
export interface McpModuleOptions {
|
||||
accessPolicy?: McpAccessPolicy;
|
||||
validateAccess?: McpAccessValidator;
|
||||
}
|
||||
|
||||
/** Injection token for the options object given to `McpModule.forRoot()`. */
|
||||
export const MCP_MODULE_OPTIONS = Symbol('MCP_MODULE_OPTIONS');
|
||||
@@ -275,7 +275,7 @@ graph**, which is a different problem from serving a genuine outside consumer.
|
||||
Nine `*.mcp.ts` files did that with `addons.bridge` for one boolean each, and
|
||||
not by preference: a decorator's options object is built while the class is
|
||||
being defined, so the `when:` closure had no `this` to reach an injected service
|
||||
through. `@trek/nest-mcp` hands the gate its declaring instance now, and
|
||||
through. `src/nest-mcp/` hands the gate its declaring instance now, and
|
||||
`addons/addon-gate.ts` turns that into `addonGate(ADDON_IDS.X)` over an injected
|
||||
`AddonsService`. `reservations.mcp.ts` (assignments) and `atlas.mcp.ts` /
|
||||
`journey.mcp.ts` (auth) went the same way.
|
||||
@@ -932,9 +932,9 @@ crons all inject now (`*.job.ts` providers on `scheduling/CronRegistrarService`)
|
||||
boot-validated by `trekMcpValidateAccess` (`src/mcp/nest-mcp-policy.ts`) —
|
||||
an unknown group, or `mode: 'write'` on a read-only group (`geo`,
|
||||
`weather`), fails app boot. **`mode` is typed the same way**: it is the mode
|
||||
half of `Scope` (`read | write | delete | share`), augmented into
|
||||
`@trek/nest-mcp` through `McpAccessModeRegistry` exactly like the group
|
||||
registry. A scope that is neither read nor write — `journey:share` is the
|
||||
half of `Scope` (`read | write | delete | share`), fed into
|
||||
`src/nest-mcp/types.ts` through `McpAccessModeRegistry` exactly like the
|
||||
group registry. A scope that is neither read nor write — `journey:share` is the
|
||||
one today — gets a real marker, *not* a `(ctx) => canX(ctx.scopes)`
|
||||
predicate: predicates bypass the policy entirely and are invisible to the
|
||||
boot gate, so a scope typo in one would ship as a silent full-access tool.
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
McpController, Tool, ResourceTemplate, type McpContext,
|
||||
TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { McpContext } from '@trek/nest-mcp';
|
||||
import type { McpContext } from '../../nest-mcp';
|
||||
import type { AddonsService } from './addons.service';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
|
||||
@@ -11,7 +11,7 @@ import { ADDON_IDS } from '../../addons';
|
||||
* `this` to reach an injected service through, and nine domains hid an edge to
|
||||
* the addons domain from the module graph to answer one boolean.
|
||||
*
|
||||
* `@trek/nest-mcp` now hands the gate the declaring controller instance, so the
|
||||
* `src/nest-mcp` now hands the gate the declaring controller instance, so the
|
||||
* only thing a domain has to do is expose the service it already injects:
|
||||
*
|
||||
* constructor(private readonly vacay: VacayService, readonly addons: AddonsService) {}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '@trek/nest-mcp';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { findByIata, searchAirports } from './airports.data';
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ import { AuditModule } from './audit/audit.module';
|
||||
import { PermissionsModule } from './permissions/permissions.module';
|
||||
import { PluginsModule } from './plugins/plugins.module';
|
||||
import { SchedulingModule } from './scheduling/scheduling.module';
|
||||
import { McpModule } from '@trek/nest-mcp';
|
||||
import { McpModule } from '../nest-mcp';
|
||||
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../mcp/nest-mcp-policy';
|
||||
import { TrekExceptionFilter } from './common/trek-exception.filter';
|
||||
import { SpaFallbackFilter } from './platform/spa-fallback.filter';
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AtlasService, BucketItemExistsError } from './atlas.service';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { McpController, Prompt, type McpContext } from '@trek/nest-mcp';
|
||||
import { McpController, Prompt, type McpContext } from '../../nest-mcp';
|
||||
|
||||
/**
|
||||
* Auth-related MCP surface. One prompt today, moved 1:1 from the legacy
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
McpController, Tool, Resource, type McpContext,
|
||||
TOOL_ANNOTATIONS_READONLY, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { CategoriesService } from './categories.service';
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
McpController, Tool, ResourceTemplate, type McpContext,
|
||||
TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
McpController, Tool, ResourceTemplate, type McpContext,
|
||||
TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
demoDenied, ok, type McpContext,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '@trek/nest-mcp';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { MapsService } from './maps.service';
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { RealtimeService } from '../realtime/realtime.service';
|
||||
* src/websocket stub as module globals. The @McpController domain classes are
|
||||
* ordinary Nest providers, so they inject this instead. The pure result
|
||||
* helpers (noAccess/permissionDenied/adminRequired/MAX_MCP_TRIP_DAYS and the
|
||||
* @trek/nest-mcp re-exports) stay in _shared.ts — they carry no dependencies.
|
||||
* src/nest-mcp re-exports) stay in _shared.ts — they carry no dependencies.
|
||||
*/
|
||||
@Injectable()
|
||||
export class McpToolGuardsService {
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Request, Response } from 'express';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';
|
||||
import { McpRegistryService } from '@trek/nest-mcp';
|
||||
import { McpRegistryService } from '../../nest-mcp';
|
||||
import type { User } from '../../types';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { getMcpSafeUrl } from '../../app-config';
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
McpController, Tool, Resource, type McpContext,
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { placeWebsiteSchema } from '@trek/shared';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -1,317 +0,0 @@
|
||||
# Plugin RPC boundary — migration to Nest DI
|
||||
|
||||
Status: **Option A implemented (2026-07)** — the wiring layer is now
|
||||
`host/plugin-host-deps.factory.ts` (`@Injectable() PluginHostDepsFactory`),
|
||||
with process-wide host state split into `host/plugin-host-state.ts`. Option B
|
||||
below remains the roadmap.
|
||||
Goal: make the host side of the plugin boundary fully Nest-native, in step with
|
||||
the ongoing legacy-service migration (`src/nest/README.md`, "Migrating a legacy
|
||||
`src/services/*` service" recipe). The **process boundary itself does not
|
||||
change** — only how the host sources and organizes its dependencies.
|
||||
|
||||
---
|
||||
|
||||
## 1. Where we are today
|
||||
|
||||
The plugin runtime has three layers. Only the third is "un-Nest".
|
||||
|
||||
| Layer | File(s) | Role | Nest-native? |
|
||||
|---|---|---|---|
|
||||
| Sandbox / transport | `supervisor/plugin-supervisor.ts`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts` | Forked child per plugin, IPC envelopes, permission tables, actor resolution, rate limiting, RSS policing | Intentionally not — this is the security boundary |
|
||||
| Enforcement | `host/rpc-host.ts` (~1330 lines) | `PluginRpcHost`: builds a per-plugin method map at spawn — a handler is registered **only if the plugin holds the unlocking permission** (registration = authorization). Depends only on the `HostDeps` interface | Neutral — decoupled by design |
|
||||
| **Wiring** | `host/plugin-host-deps.factory.ts` (was `create-rpc-host.ts`) | Fills the ~130-member `HostDeps` object. Since Option A: an `@Injectable() PluginHostDepsFactory` with the DI-native domain services (`BudgetService`, `ReservationsService`, `TagsService`, `CategoriesService`, `TodoService`, `PluginOAuthService`) constructor-injected, sixteen domains as of 2026-07 (exchange-rates joined with the budget-domain fold, after the Wave-2 permissions pair); legacy `services/*` domains stay plain function imports until their own migration. Raw `db`/`broadcast` also stay until injectable equivalents exist | **Yes (Option A)** — drains further per §3 |
|
||||
| Host state | `host/plugin-host-state.ts` | Deliberately module-level (NOT a provider): the per-plugin data-DB map (`getPluginDataDb`/`closePluginDataDb`) and daily broker budgets (`budgetFor`/`pluginBudgetUsage`). Must be one shared instance across host recreations, and is read by `PluginsService`, which the factory imports from — folding it into the injectable would create a provider cycle | Intentionally not |
|
||||
|
||||
Key fact that made Option A cheap: the wiring is **called from inside a Nest
|
||||
provider** — `PluginRuntimeService` binds `hostDeps.create(id, granted, this)`
|
||||
in its supervisor field initializer (the arrow resolves `this.hostDeps` lazily
|
||||
at spawn time, so field-initializer ordering is safe). Unlike the MCP handler
|
||||
(mounted pre-`app.init()`, needs `registry-handoff.ts`), **no handoff seam is
|
||||
needed here** — plain constructor injection is used.
|
||||
|
||||
### The bridge pattern (mostly retired)
|
||||
|
||||
`<domain>.bridge.ts` shims existed for one reason: a domain's SQL moved into a
|
||||
DI-only service and the legacy function module was deleted, but the wiring
|
||||
layer didn't inject — so a module-level shim re-exported the legacy names over
|
||||
a hand-built instance. Option A deleted `tags.bridge.ts` and
|
||||
`categories.bridge.ts` (the plugin host was their only consumer).
|
||||
`todo.bridge.ts`, `share.bridge.ts`, `collab.bridge.ts` and `vacay.bridge.ts`
|
||||
followed with the 2026-07 trip fold — their last consumers (the legacy
|
||||
`src/mcp/tools/trips.ts` registrar and the legacy tripService itself) migrated
|
||||
into the DI-discovered `trips.mcp.ts`/`share.mcp.ts` and the DI-native
|
||||
`TripsService`. New bridges should only be added for genuinely
|
||||
non-Nest consumers (legacy MCP registrars, scheduler, websocket) — the plugin
|
||||
host no longer needs them, ever.
|
||||
|
||||
### What never changes (the invariants)
|
||||
|
||||
These are the sandbox. Every option below leaves them untouched:
|
||||
|
||||
- One forked child process per plugin; IPC envelope protocol (`req`/`res`/`evt`).
|
||||
- `protocol/envelope.ts` stays a **zero-runtime-import module** and stays the
|
||||
**single source of truth** for `KNOWN_METHODS`, `METHOD_PERMISSION`,
|
||||
`KNOWN_PERMISSIONS` (it is loaded by both host and child).
|
||||
- Registration-is-authorization: an ungranted method is *absent*, not guarded.
|
||||
- Host-side acting-user resolution (`_inv` map in the supervisor) — a plugin
|
||||
can never name an arbitrary user.
|
||||
- Scrubbed child env, Node `--permission` flags, RSS ceiling, heartbeat
|
||||
reaping, crash backoff.
|
||||
- The error taxonomy (`PERMISSION_DENIED`, `UNKNOWN_METHOD`, `BAD_PARAMS`,
|
||||
`RESOURCE_FORBIDDEN`, …) and audit trail.
|
||||
|
||||
We also explicitly **rejected** modelling the IPC boundary as a
|
||||
`@nestjs/microservices` custom transporter ("Option C"): the supervisor's
|
||||
security model is bespoke and load-bearing, and hiding it behind Nest's
|
||||
microservice abstractions would obscure the boundary for near-zero payoff.
|
||||
|
||||
---
|
||||
|
||||
## 2. Option A — inject the wiring layer (DONE, 2026-07)
|
||||
|
||||
**What shipped:** `create-rpc-host.ts` became two files:
|
||||
|
||||
- `host/plugin-host-deps.factory.ts` — `@Injectable() PluginHostDepsFactory`
|
||||
with constructor deps `BudgetService`, `ReservationsService`, `TagsService`,
|
||||
`CategoriesService`, `TodoService`, `PluginOAuthService` (the last was
|
||||
previously `new`-ed **per call** inside the `getOAuthToken` closure).
|
||||
`create(id, granted, router)` returns the `PluginRpcHost` with the same
|
||||
~130-member `HostDeps` object — closures over `this.*` for DI domains, still
|
||||
plain imports for legacy `services/*`. `DatabaseService` is injected too
|
||||
(since 2026-07): the factory's inline SQL, the `canEditTripAs` gate and the
|
||||
`HostDeps.db`/audit connection all go through it instead of the raw `db`
|
||||
proxy (behavior-identical — the injected connection IS the proxy).
|
||||
- `host/plugin-host-state.ts` — the process-wide maps (`dataDbs`, `budgets`)
|
||||
and their accessors, kept module-level on purpose (see §1 table).
|
||||
|
||||
`PluginRuntimeService` takes the factory as a third, type-optional constructor
|
||||
param (same convention as `registry?` — tests construct without it, Nest always
|
||||
injects it) and binds `this.hostDeps.create(id, granted, this)` in the
|
||||
supervisor field initializer.
|
||||
|
||||
**Module wiring:** `TagsModule`/`CategoriesModule`/`BudgetModule`/
|
||||
`ReservationsModule`/`PackingModule` gained `exports: [XService]` (`TodoModule`
|
||||
already exported), and `PluginsModule` imports all six. The dependency graph
|
||||
moved from hidden (bridge files) to explicit (the container). `DatabaseModule`
|
||||
is `@Global`, so no import needed for it.
|
||||
|
||||
**Interaction with the service-migration track:** legacy `services/*` functions
|
||||
(place, day, trip, …) stay as plain imports inside the
|
||||
factory *until their own domain migrates*. Each future migration then swaps one
|
||||
import for one injected service (+ module export/import) — **no more bridge
|
||||
files for the plugin host, ever**. The factory's import list shrinks
|
||||
monotonically as the recipe in `src/nest/README.md` proceeds (packing and
|
||||
day-notes swapped in 2026-07; trip-invite migrated without touching the
|
||||
factory — it was never imported here; assignments swapped in 2026-07; share
|
||||
migrated 2026-07 without touching the factory — it was never imported here
|
||||
either; settings swapped in 2026-07 indirectly — the factory never imported it,
|
||||
but its `resolveLlmConfig` import became the injected `LlmConfigResolver`;
|
||||
fileService swapped in 2026-07 — its ten imported symbols became the injected
|
||||
`FilesService` plus the load-time constants from `files.constants.ts`;
|
||||
collabService swapped in 2026-07 — its seven imported symbols became the
|
||||
injected `CollabService`, completing Wave 3; vacayService swapped in 2026-07 —
|
||||
its four imported symbols became the injected `VacayService`; dayService
|
||||
swapped in 2026-07 — its eleven imported symbols (the heaviest single import)
|
||||
became the injected `DaysService`; permissions swapped in 2026-07 with the
|
||||
Wave-2 pair — its `checkPermission` import became the injected
|
||||
`PermissionsService` (the auditLog half never touched the factory: the plugin
|
||||
host's audit trail is the separate `plugin-audit.ts`); exchangeRateService
|
||||
swapped in 2026-07 with the budget-domain fold — its `getRates` import became
|
||||
the injected `ExchangeRatesService`; budgetService swapped in 2026-07 with the
|
||||
budget migration — its `listBudgetItems` import became the already-injected
|
||||
`BudgetService`, so no constructor change at all; tripService swapped in
|
||||
2026-07 with the trip fold — its six imported symbols (`listTrips`,
|
||||
`updateTrip`, `createTrip`, `removeMember`, `NotFoundError`, `ValidationError`)
|
||||
became the injected `TripsService`, with the error classes now imported from
|
||||
`nest/trips/trips.service`; placeService swapped in 2026-07 with the place
|
||||
fold — its four imported symbols (`createPlace`, `updatePlace`, `deletePlace`,
|
||||
`getPlace`) became the injected `PlacesService`, the factory's 21st constructor
|
||||
dep; collectionsService swapped in 2026-08 with the collections fold — its
|
||||
seven imported symbols (`listCollections`, `getCollection`, `createCollection`,
|
||||
`updateCollection`, `savePlace`, `copyToTrip`, `deletePlace`) became the
|
||||
injected `CollectionsService`, the factory's 22nd constructor dep, with
|
||||
`mapCollectionError` unchanged on top; atlasService swapped in 2026-08 with
|
||||
the atlas fold — its nine imported symbols (`listVisitedCountries`,
|
||||
`listManuallyVisitedRegions`, `listBucketList`, `markCountryVisited`,
|
||||
`unmarkCountryVisited`, `markRegionVisited`, `unmarkRegionVisited`,
|
||||
`createBucketItem`, `deleteBucketItem`) became the injected `AtlasService`,
|
||||
the factory's 23rd constructor dep; notificationService swapped in 2026-08
|
||||
with the notifications fold — its single imported symbol (`send as
|
||||
sendNotification`, the `sendPluginNotification` closure) became the injected
|
||||
`NotificationsService`, the factory's 24th constructor dep; the remaining
|
||||
factory domain imports are `weatherService` (`getWeather`) and the Wave-5
|
||||
journeys domain).
|
||||
|
||||
### Test impact (as landed)
|
||||
|
||||
- `tests/unit/plugins/rpc-host.test.ts` — **unchanged** (constructs
|
||||
`PluginRpcHost` directly with hand-built `HostDeps`).
|
||||
- `tests/unit/plugins/plugin-host-deps.factory.test.ts` (was
|
||||
`create-rpc-host.test.ts`) — the six DI-domain path mocks became constructor
|
||||
stubs (sixteen stubs as of the 2026-07 exchange-rates fold, plus `tripsStub`
|
||||
with the 2026-07 trip fold — the tripService path mock's sentinel behaviors
|
||||
moved onto the stub, its throws now built from the real
|
||||
`nest/trips/trips.service` error classes); the ~22
|
||||
legacy-service path mocks shrank by one with the 2026-07 budget migration
|
||||
(the budgetService satisfy-the-import mock died with the legacy file — the
|
||||
`budgetStub` gained `listBudgetItems` for the two swapped closures); the
|
||||
collectionsService path mock became `collectionsStub` with the 2026-08
|
||||
collections fold (same sentinel behaviors — the status-tagged throws the
|
||||
factory's `mapCollectionError` maps); the atlasService path mock became
|
||||
`atlasStub` with the 2026-08 atlas fold (same sentinel behaviors, keyed by
|
||||
the service method names — `bucketList`, `markCountry`, …); the
|
||||
notificationService path mock became `notificationsStub` with the 2026-08
|
||||
notifications fold (the hoisted `notifySend` handle survived as the stub's
|
||||
`send`); a
|
||||
file-local shim keeps the
|
||||
historical `createRealRpcHost(id, granted)` call sites and supplies a default
|
||||
no-op router.
|
||||
- Bridge delegation tests (TAG-SVC-016..020, CAT-SVC-016) — deleted with the
|
||||
bridges (owner-scoping etc. already covered by the service-level cases).
|
||||
- `tests/helpers/plugin-host.ts` — `createPluginRuntime()` builds the runtime
|
||||
the way Nest would (real services over the test DB) for the suites that fork
|
||||
real plugin children.
|
||||
|
||||
---
|
||||
|
||||
## 3. Option B — decorator-driven RPC registry (the end state)
|
||||
|
||||
**What:** mirror the `@trek/nest-mcp` pilot for the plugin RPC surface.
|
||||
Per-domain `<domain>.rpc.ts` classes with declarative metadata, discovered at
|
||||
boot, from which the supervisor builds each plugin's granted method map.
|
||||
|
||||
```ts
|
||||
// nest/tags/tags.rpc.ts (sketch)
|
||||
@RpcController()
|
||||
export class TagsRpc {
|
||||
constructor(private readonly tags: TagsService) {}
|
||||
|
||||
@RpcMethod({ method: 'tags.list', permission: 'db:read:tags' })
|
||||
list(_params: unknown, ctx: RpcCtx) {
|
||||
return this.tags.list(requireActor(ctx));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A registry service (same shape as `McpRegistryService`: `DiscoveryService` +
|
||||
`MetadataScanner`, `OnModuleInit` scan, fail-fast `validate()`) replaces the
|
||||
hand-built method map. `PluginRpcHost` shrinks to dispatch + shared resource
|
||||
gates (`tripRead`, `requireTripEdit`, addon gates) offered as helpers the
|
||||
domain classes call.
|
||||
|
||||
**The one hard constraint:** `envelope.ts` remains the single source of truth.
|
||||
Decorator metadata inevitably duplicates the method→permission mapping, so the
|
||||
registry's boot-time `validate()` must assert, fail-fast at app start:
|
||||
|
||||
1. every `@RpcMethod` names a method present in `KNOWN_METHODS`;
|
||||
2. its declared permission **equals** `METHOD_PERMISSION[method]`;
|
||||
3. every `KNOWN_METHOD` has exactly one handler (no orphans, no duplicates).
|
||||
|
||||
That turns today's implicit convention into a checked invariant — a strict
|
||||
improvement over the status quo, where a table/registration mismatch is only
|
||||
found by tests (or not at all).
|
||||
|
||||
**What does *not* map onto Nest:** the resource gates are not HTTP guards.
|
||||
There is no request context; the acting user comes from the supervisor's
|
||||
`_inv` map. Don't force `CanActivate` — keep the gates as plain helpers (or a
|
||||
thin wrap around dispatch). Option B buys *structure and colocation*, not
|
||||
Nest's HTTP middleware machinery.
|
||||
|
||||
### Pros
|
||||
|
||||
- **Kills the compounding cost.** One new plugin capability = one decorated
|
||||
method on the domain class + one `envelope.ts` table entry. Today it is six
|
||||
edits across two monoliths. Over months-to-years of API growth this is the
|
||||
dominant term.
|
||||
- **One mental model for the whole codebase.** A complete domain becomes
|
||||
`x.controller.ts` + `x.service.ts` + `x.mcp.ts` + `x.rpc.ts` + `x.module.ts`
|
||||
— same folder, same discovery pattern, same test style as the proven
|
||||
nest-mcp pilot. New contributors learn one shape.
|
||||
- **Dissolves the monoliths.** `plugin-host-deps.factory.ts` disappears; `rpc-host.ts`
|
||||
shrinks to a small dispatch core. Per-domain diffs, per-domain tests, less
|
||||
merge contention.
|
||||
- **Boot-time validation** of the method/permission tables (see above).
|
||||
- **Strangler-compatible.** The registry can coexist with the legacy method
|
||||
map exactly like the nest-mcp registry coexists with the legacy tool
|
||||
registrars: migrated domains register via decorators, the rest stay in the
|
||||
old map until their turn. No big-bang cutover.
|
||||
|
||||
### Cons
|
||||
|
||||
- **Prerequisites.** Only worth starting once a domain's logic is a DI service;
|
||||
doing it before the service migration just wraps legacy function imports in
|
||||
decorator dressing. Today only tags and categories qualify.
|
||||
- **Real up-front build:** the decorator/registry package (or a generalized
|
||||
discovery core shared with `nest-mcp`), the validate() logic, a
|
||||
`createTestRegistry`-style harness, and migration of the two big test suites
|
||||
(`rpc-host.test.ts`'s `HostDeps`-shaped tests do **not** survive this one).
|
||||
- **Duplication risk** between decorators and `envelope.ts` if validate() is
|
||||
skipped or weakened — the mitigation is mandatory, not optional.
|
||||
- The supervisor/registry seam needs care: method maps are per-plugin
|
||||
(filtered by grants at spawn), so the registry must expose
|
||||
"build map for grant-set", not a global attach.
|
||||
|
||||
### Test impact
|
||||
|
||||
- New per-domain RPC test files (mirroring `tools-<domain>.test.ts` on the MCP
|
||||
side) + a registry unit suite.
|
||||
- `rpc-host.test.ts` progressively shrinks to the dispatch core;
|
||||
`plugin-host-deps.factory.test.ts` is deleted at the end of the drain.
|
||||
- Integration suites (`tests/integration/plugins/*`, real fork/IPC) are the
|
||||
parity net — they must pass unchanged throughout, same role
|
||||
`tests/integration/categories.test.ts` played for the categories migration.
|
||||
|
||||
---
|
||||
|
||||
## 4. Sequencing (the actual plan)
|
||||
|
||||
A is not an alternative to B — **A is the first commit of B's journey**, and
|
||||
none of it is throwaway.
|
||||
|
||||
1. ~~**Now / opportunistically — Option A.**~~ **Done (2026-07).** Injectable
|
||||
factory, tags/categories bridges deleted, wiring test rewritten against
|
||||
stubs (see §2).
|
||||
2. **Per domain, as the service migrations proceed** (`packingService`,
|
||||
`dayNoteService` and `assignmentService` done 2026-07; `tripInviteService`
|
||||
done 2026-07 with no factory impact — it was never imported here;
|
||||
`reservationService` done 2026-07, draining the factory's last
|
||||
plain-function reservation import — `notifyBookingChange` became a private
|
||||
method over the already-injected `ReservationsService`; `dayService` done
|
||||
2026-07, the heaviest factory import — eleven symbols became the injected
|
||||
`DaysService`; next per `src/nest/README.md`): migrate the
|
||||
service to DI as usual; the factory swaps one legacy import for one
|
||||
injected service. Optionally pilot `tags.rpc.ts` here — tags is small and
|
||||
already fully DI on HTTP + MCP.
|
||||
3. **Once ~half the domains are DI-native — commit to Option B.** Build the
|
||||
registry package, validate() against `envelope.ts`, then drain the method
|
||||
map domain by domain — the same strangler pattern that retired the Express
|
||||
API and is retiring the legacy MCP registrars.
|
||||
4. **Never — Option C** (Nest microservices transporter over the IPC channel).
|
||||
|
||||
### Decision triggers
|
||||
|
||||
- ~~**Start A** whenever there's a free session; it has no prerequisites.~~ Done.
|
||||
- **Start B** when (a) the majority of plugin-facing domains have DI services,
|
||||
or (b) the plugin API surface is about to grow significantly (new SDK
|
||||
capability wave) — whichever comes first.
|
||||
- **Stop at A** only if the plugin API is declared frozen: with no method
|
||||
growth, B's compounding payoff never materializes.
|
||||
|
||||
---
|
||||
|
||||
## 5. Key files (for whoever picks this up)
|
||||
|
||||
| File | Why it matters |
|
||||
|---|---|
|
||||
| `src/nest/plugins/host/plugin-host-deps.factory.ts` | The wiring layer (Option A's product); Option B eventually deletes it |
|
||||
| `src/nest/plugins/host/plugin-host-state.ts` | Process-wide host state (data-DB map, broker budgets) — module-level on purpose, see §1 |
|
||||
| `src/nest/plugins/host/rpc-host.ts` | Enforcement core; `HostDeps` interface is the seam A preserved and B drains |
|
||||
| `src/nest/plugins/protocol/envelope.ts` | Single source of truth for methods/permissions — must stay zero-import; B validates against it |
|
||||
| `src/nest/plugins/plugin-runtime.service.ts` | The provider that owns the factory call site (supervisor field initializer) |
|
||||
| `src/nest/plugins/supervisor/plugin-supervisor.ts` | Sandbox lifecycle — untouched by both options |
|
||||
| `src/nest/todo/todo.bridge.ts` | Surviving bridge — kept only for the legacy `get_trip_summary` MCP registrar (`src/nest/files/files.bridge.ts` also survives, but for module-scope multer configs, not the plugin host) |
|
||||
| `src/mcp/registry-handoff.ts` | The MCP precedent for non-container code — **not needed here**; documented to explain why |
|
||||
| `nest-mcp/` (`@trek/nest-mcp`) | The proven decorator/registry/discovery blueprint Option B mirrors |
|
||||
| `src/nest/README.md` | The per-service DI migration recipe this roadmap rides on |
|
||||
| `tests/unit/plugins/plugin-host-deps.factory.test.ts` | The wiring suite (bore most of A's one-time test cost) |
|
||||
| `tests/unit/plugins/rpc-host.test.ts` | Survived A untouched; shrinks under B |
|
||||
@@ -38,8 +38,9 @@ package as its data source, so it can read it directly.
|
||||
|
||||
## If this ever becomes its own package
|
||||
|
||||
`nest-mcp` is the worked example of the same layer as a separate workspace, and the
|
||||
delta is instructive. Because `nest-mcp` must not import the host, it needs a
|
||||
`nest-mcp` was the worked example of the same layer as a separate workspace (it has
|
||||
since been folded into `server/src/nest-mcp/`, which retired the machinery below), and
|
||||
the delta is instructive. Because `nest-mcp` could not import the host, it needed a
|
||||
`declare module` augmentation for its registries plus two `AssertExact` drift guards in
|
||||
`src/mcp/nest-mcp-policy.ts`, and a permissive `keyof X extends never ? string`
|
||||
fallback that silently disables all checking if someone forgets to augment.
|
||||
@@ -54,7 +55,7 @@ fallback that silently disables all checking if someone forgets to augment.
|
||||
3. Root `package.json` `workspaces`, `server/package.json` deps, the root lockfile, the
|
||||
Dockerfile COPY stages and a source alias in `server/vitest.config.ts` all change.
|
||||
|
||||
Note that a workspace would *not* let `trek-plugin-sdk` consume it: `nest-mcp` is
|
||||
Note that a workspace would *not* let `trek-plugin-sdk` consume it: `nest-mcp` was
|
||||
`"private": true`, and so would this be. The SDK gets its copy of the permission facts
|
||||
from the generated `plugin-sdk/src/generated/host-facts.ts` instead.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
McpController, Tool, ResourceTemplate, type McpContext,
|
||||
TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
McpController, Tool, type McpContext,
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { TagsService } from './tags.service';
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
McpController, Tool, type McpContext,
|
||||
TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT, TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
@@ -29,7 +29,7 @@ const transitRateLimiter = new RateLimitService();
|
||||
|
||||
const transitModes = z.enum(['TRANSIT', ...SCHEDULED_TRANSIT_MODES]);
|
||||
|
||||
// Local 2-arg variant (the @trek/nest-mcp errorResult takes a string only):
|
||||
// Local 2-arg variant (the src/nest-mcp errorResult takes a string only):
|
||||
// surface the provider/validation message when there is one, else the fallback.
|
||||
function errorResult(err: unknown, fallback: string) {
|
||||
return {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { McpController, Prompt, type McpContext } from '@trek/nest-mcp';
|
||||
import { McpController, Prompt, type McpContext } from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
} from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '@trek/nest-mcp';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { WeatherService } from './weather.service';
|
||||
|
||||
|
||||
Reference in New Issue
Block a user