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.

feat(server): services refuse with a DomainError that REST and MCP answer in their existing shapes

Maurice66042ae1c7ba
diff --git a/server/src/mcp/nest-mcp-policy.ts b/server/src/mcp/nest-mcp-policy.ts
index fb1fd09da..424154bad 100644
--- a/server/src/mcp/nest-mcp-policy.ts
+++ b/server/src/mcp/nest-mcp-policy.ts
@@ -1,12 +1,15 @@
import {
demoDenied,
+ errorResult,
type McpAccessGroup,
type McpAccessMode,
type McpAccessPolicy,
type McpAccessValidator,
+ type McpErrorMapper,
type McpToolGate,
type ToolOptions,
} from '../nest-mcp';
+import { DomainError } from '../nest/common/domain-error';
import { ALL_SCOPES, canRead, canWrite, type Scope, type ScopeGroup } from './scopes';
/** The mode half of every scope: 'read' | 'write' | 'delete' | 'share'. */
@@ -76,3 +79,13 @@ export function isDemoGatedTool(tool: ToolOptions): boolean {
export function trekDemoToolGate(isDemoUser: (userId: number) => Promise<boolean>): McpToolGate {
return async (tool, ctx) => (isDemoGatedTool(tool) && (await isDemoUser(ctx.userId)) ? demoDenied() : undefined);
}
+
+/**
+ * A service refusal (`DomainError`) thrown out of a tool answers the call with
+ * `errorResult(publicMessage)`: the same text REST sends as `{ error }`, and the
+ * same result the tools built by hand from a `{ error, status }` return. Any
+ * other error propagates as before. Given to McpModule.forRoot (AppModule) and
+ * to the MCP test registry.
+ */
+export const trekMcpErrorMapper: McpErrorMapper = (err) =>
+ err instanceof DomainError ? errorResult(err.publicMessage) : undefined;
diff --git a/server/src/nest-mcp/index.ts b/server/src/nest-mcp/index.ts
index d9eb8bb83..284d7dce3 100644
--- a/server/src/nest-mcp/index.ts
+++ b/server/src/nest-mcp/index.ts
@@ -33,6 +33,7 @@ export {
type McpDynamicToolSource,
type McpEntry,
type McpEntryKind,
+ type McpErrorMapper,
type McpModuleOptions,
type McpRegistryListing,
type McpToolGate,
diff --git a/server/src/nest-mcp/mcp-registry.service.ts b/server/src/nest-mcp/mcp-registry.service.ts
index d16aec898..774ae3a05 100644
--- a/server/src/nest-mcp/mcp-registry.service.ts
+++ b/server/src/nest-mcp/mcp-registry.service.ts
@@ -21,6 +21,7 @@ export class McpRegistryService extends McpRegistry implements OnModuleInit {
accessPolicy: options.accessPolicy,
validateAccess: options.validateAccess,
toolGate: toolGate ?? undefined,
+ errorMapper: options.errorMapper,
});
}
diff --git a/server/src/nest-mcp/registry.ts b/server/src/nest-mcp/registry.ts
index dda9aad19..a9b1fd609 100644
--- a/server/src/nest-mcp/registry.ts
+++ b/server/src/nest-mcp/registry.ts
@@ -8,6 +8,7 @@ import type {
McpDynamicToolSource,
McpEntry,
McpEntryKind,
+ McpErrorMapper,
McpRegistryListing,
McpToolGate,
PromptOptions,
@@ -40,6 +41,8 @@ export interface McpRegistryOptions {
validateAccess?: McpAccessValidator;
/** Runs before every registered tool handler; see `McpToolGate`. */
toolGate?: McpToolGate;
+ /** Turns an error a registered tool handler threw into its result; see `McpErrorMapper`. */
+ errorMapper?: McpErrorMapper;
}
type AnyHandler = (this: unknown, ...handlerArgs: unknown[]) => unknown;
@@ -106,6 +109,7 @@ export class McpRegistry {
private readonly accessPolicy?: McpAccessPolicy;
private readonly validateAccess?: McpAccessValidator;
private readonly toolGate?: McpToolGate;
+ private readonly errorMapper?: McpErrorMapper;
/** Memoised `reservedNames()`; dropped by register() so it can never go stale. */
private reserved?: ReadonlySet<string>;
@@ -113,6 +117,7 @@ export class McpRegistry {
this.accessPolicy = options.accessPolicy;
this.validateAccess = options.validateAccess;
this.toolGate = options.toolGate;
+ this.errorMapper = options.errorMapper;
}
/**
@@ -145,7 +150,7 @@ export class McpRegistry {
const handler = (instance as unknown as Record<string, AnyHandler>)[entry.methodName];
switch (entry.kind) {
case 'tool':
- this.attachTool(registrar, entry.options, instance, this.gated(entry.options, handler, ctx), ctx, opts);
+ this.attachTool(registrar, entry.options, instance, this.mapped(this.gated(entry.options, handler, ctx)), ctx, opts);
break;
case 'resource':
this.attachResource(registrar, entry.options, instance, handler, ctx, opts);
@@ -320,6 +325,25 @@ export class McpRegistry {
};
}
+ /**
+ * The handler with the host's error mapper around it, when one is configured:
+ * an error the mapper recognises becomes the call's result, anything else
+ * propagates as before. Registered tools only, like the gate.
+ */
+ private mapped(handler: AnyHandler): AnyHandler {
+ const mapError = this.errorMapper;
+ if (!mapError) return handler;
+ return async function (this: unknown, ...handlerArgs: unknown[]) {
+ try {
+ return await handler.apply(this, handlerArgs);
+ } catch (err) {
+ const result = mapError(err);
+ if (result !== undefined) return result;
+ throw err;
+ }
+ };
+ }
+
// D6: this callback is invoked from inside McpTransportController's @Post/@Get/
// @Delete handlers (mcp-transport.controller.ts), which are ordinary Nest routes —
// `@Public()` only exempts the auth guard, and the raw-body parser exemption in
diff --git a/server/src/nest-mcp/types.ts b/server/src/nest-mcp/types.ts
index a0630e887..1e6334952 100644
--- a/server/src/nest-mcp/types.ts
+++ b/server/src/nest-mcp/types.ts
@@ -267,6 +267,18 @@ export type McpAccessValidator = (access: McpDeclarativeAccess, entry: McpRegist
*/
export type McpToolGate = (tool: ToolOptions, ctx: McpContext) => unknown;
+/**
+ * Host-supplied translation of an error a registered tool handler threw into
+ * the tool's result. Return a result to answer the call with it, or undefined
+ * to let the error propagate unchanged. The package attaches no meaning to it;
+ * TREK maps its `DomainError` to an `errorResult` in `src/mcp/nest-mcp-policy.ts`,
+ * so a service refusal reaches MCP with the same text REST answers with.
+ *
+ * Registered entries only, like the tool gate: a dynamic tool's source owns
+ * its own failure handling.
+ */
+export type McpErrorMapper = (err: unknown) => unknown;
+
/**
* How the module builds its `McpToolGate`: a factory with the providers it
* needs, resolved from the container like any other provider. A gate that
@@ -283,6 +295,8 @@ export interface McpModuleOptions {
accessPolicy?: McpAccessPolicy;
validateAccess?: McpAccessValidator;
toolGate?: McpToolGateProvider;
+ /** See `McpErrorMapper`. Static: it needs nothing from the container. */
+ errorMapper?: McpErrorMapper;
}
/** Injection token for the resolved `McpToolGate` (null when none was configured). */
diff --git a/server/src/nest/README.md b/server/src/nest/README.md
index 728f5d42a..d3fc59644 100644
--- a/server/src/nest/README.md
+++ b/server/src/nest/README.md
@@ -167,6 +167,18 @@ it instead of leaning on the generic pipe envelope.
- A guard with a constructor dependency has to be a registered provider
wherever it is used, which is why the three auth guards stay dependency-free.
+## Refusals: one error, both channels
+
+A service refuses by throwing a `DomainError` (`common/domain-error.ts`) with
+the status and the exact text the client sees, `throw forbidden('Admin access
+required')`, never by returning `{ error, status }` for each caller to
+translate. The global filter writes it as `{ error, ...details }` at its status,
+and the MCP registry's error mapper (`trekMcpErrorMapper` in
+`src/mcp/nest-mcp-policy.ts`) answers the tool call with `errorResult` of the
+same text, so the controller and the tool need no branch of their own. A caller
+that has to act on a refusal before passing it on (an audit row, a timing pad)
+uses `catchDomainError`.
+
## Tests
Every module ships two kinds of tests.
diff --git a/server/src/nest/app.module.ts b/server/src/nest/app.module.ts
index f558a5283..9bd81aacc 100644
--- a/server/src/nest/app.module.ts
+++ b/server/src/nest/app.module.ts
@@ -1,4 +1,4 @@
-import { trekDemoToolGate, trekMcpAccessPolicy, trekMcpValidateAccess } from '../mcp/nest-mcp-policy';
+import { trekDemoToolGate, trekMcpAccessPolicy, trekMcpErrorMapper, trekMcpValidateAccess } from '../mcp/nest-mcp-policy';
import mikroOrmConfig from '../mikro-orm.config';
import { AppSettings } from '../db/entities/AppSettings.entity';
import { Users } from '../db/entities/Users.entity';
@@ -108,6 +108,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
accessPolicy: trekMcpAccessPolicy,
validateAccess: trekMcpValidateAccess,
toolGate: { inject: [DemoService], useFactory: (demo: DemoService) => trekDemoToolGate((id) => demo.isDemoUserId(id)) },
+ errorMapper: trekMcpErrorMapper,
}),
HealthModule,
PlatformModule,
diff --git a/server/src/nest/common/domain-error.ts b/server/src/nest/common/domain-error.ts
new file mode 100644
index 000000000..096a4a8f7
--- /dev/null
+++ b/server/src/nest/common/domain-error.ts
@@ -0,0 +1,92 @@
+import { HttpException } from '@nestjs/common';
+
+/**
+ * A refusal a service raises for its caller to pass on as it stands: the HTTP
+ * status, the exact `error` text the client sees, and any further fields the
+ * body carries next to it.
+ *
+ * It replaces the `return { error, status }` result a controller had to turn
+ * into `throw new HttpException({ error: r.error }, r.status)` and an MCP tool
+ * into `errorResult(r.error)`. Raised once in the service, it reaches both
+ * channels in their existing shapes:
+ *
+ * - REST: it IS an HttpException whose response is `{ error, ...details }`, so
+ * TrekExceptionFilter writes that body verbatim at `status` (5xx included,
+ * exactly as the hand-thrown HttpException did), and every
+ * `if (err instanceof HttpException) throw err` along the way lets it pass.
+ * - MCP: the registry's error mapper (`trekMcpErrorMapper`) answers the tool
+ * call with `errorResult(publicMessage)`.
+ *
+ * `code` names the refusal for logs and tests; it never reaches the body, so
+ * adding one changes no response.
+ */
+export class DomainError extends HttpException {
+ readonly code: string;
+ readonly publicMessage: string;
+ readonly details?: Readonly<Record<string, unknown>>;
+
+ constructor(
+ status: number,
+ publicMessage: string,
+ options: { code?: string; details?: Record<string, unknown> } = {},
+ ) {
+ super({ ...options.details, error: publicMessage }, status);
+ this.name = 'DomainError';
+ this.message = publicMessage;
+ this.publicMessage = publicMessage;
+ this.code = options.code ?? defaultCode(status);
+ if (options.details) this.details = { ...options.details };
+ }
+
+ /** The JSON body REST answers with: `{ error, ...details }`. */
+ toBody(): Record<string, unknown> {
+ return { ...this.details, error: this.publicMessage };
+ }
+}
+
+const CODES: Record<number, string> = {
+ 400: 'bad_request',
+ 401: 'unauthorized',
+ 403: 'forbidden',
+ 404: 'not_found',
+ 409: 'conflict',
+ 410: 'gone',
+ 413: 'payload_too_large',
+ 422: 'unprocessable',
+ 429: 'too_many_requests',
+ 500: 'internal',
+ 502: 'bad_gateway',
+ 503: 'unavailable',
+};
+
+function defaultCode(status: number): string {
+ return CODES[status] ?? `http_${status}`;
+}
+
+/** Shorthands for the statuses services raise most. */
+export const badRequest = (message: string, details?: Record<string, unknown>) =>
+ new DomainError(400, message, { details });
+export const unauthorized = (message: string, details?: Record<string, unknown>) =>
+ new DomainError(401, message, { details });
+export const forbidden = (message: string, details?: Record<string, unknown>) =>
+ new DomainError(403, message, { details });
+export const notFound = (message: string, details?: Record<string, unknown>) =>
+ new DomainError(404, message, { details });
+export const conflict = (message: string, details?: Record<string, unknown>) =>
+ new DomainError(409, message, { details });
+
+/**
+ * Runs `fn` and returns the DomainError it raised instead of throwing it; any
+ * other error propagates. For the few callers that must act on a refusal before
+ * passing it on (an audit row, a constant-time pad) and for service tests.
+ */
+export async function catchDomainError<T>(
+ fn: () => Promise<T> | T,
+): Promise<{ ok: true; value: T } | { ok: false; error: DomainError }> {
+ try {
+ return { ok: true, value: await fn() };
+ } catch (err) {
+ if (err instanceof DomainError) return { ok: false, error: err };
+ throw err;
+ }
+}
diff --git a/server/src/nest/common/trek-exception.filter.ts b/server/src/nest/common/trek-exception.filter.ts
index 1c6a5a63b..7c55fe901 100644
--- a/server/src/nest/common/trek-exception.filter.ts
+++ b/server/src/nest/common/trek-exception.filter.ts
@@ -1,6 +1,7 @@
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
import type { Response } from 'express';
import { MulterError } from 'multer';
+import { DomainError } from './domain-error';
import { ACCESS_LOG_ATTACHED, UNHANDLED_ERROR } from './request-correlation';
/**
@@ -61,6 +62,16 @@ export class TrekExceptionFilter implements ExceptionFilter {
return;
}
+ // A service refusal: its status and its body, verbatim, whatever the
+ // status (the `{ error }` HttpException it replaces was passed through the
+ // same way). Checked before the generic HttpException branch so the body
+ // never depends on that branch's shape sniffing.
+ if (exception instanceof DomainError) {
+ if (exception.getStatus() >= 500) handOverToAccessLog(res, exception);
+ res.status(exception.getStatus()).json(exception.toBody());
+ return;
+ }
+
if (exception instanceof HttpException) {
const status = exception.getStatus();
const body = exception.getResponse();
diff --git a/server/tests/helpers/mcp-test-controllers.ts b/server/tests/helpers/mcp-test-controllers.ts
index 3edc77fa3..4dc5540a4 100644
--- a/server/tests/helpers/mcp-test-controllers.ts
+++ b/server/tests/helpers/mcp-test-controllers.ts
@@ -2,7 +2,7 @@ import { createTestRegistry, type McpRegistry } from '../../src/nest-mcp';
import { SchoolHolidaysMcp } from '../../src/nest/school-holidays/school-holidays.mcp';
import { SchoolHolidaysService } from '../../src/nest/school-holidays/school-holidays.service';
import { db } from '../../src/db/database';
-import { trekDemoToolGate, trekMcpAccessPolicy, trekMcpValidateAccess } from '../../src/mcp/nest-mcp-policy';
+import { trekDemoToolGate, trekMcpAccessPolicy, trekMcpErrorMapper, trekMcpValidateAccess } from '../../src/mcp/nest-mcp-policy';
import { AssignmentsMcp } from '../../src/nest/assignments/assignments.mcp';
import { AssignmentsService } from '../../src/nest/assignments/assignments.service';
import { AtlasMcp } from '../../src/nest/atlas/atlas.mcp';
@@ -504,6 +504,7 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
validateAccess: trekMcpValidateAccess,
// The same demo gate AppModule hands McpModule.forRoot.
toolGate: trekDemoToolGate((id) => demoService.isDemoUserId(id)),
+ errorMapper: trekMcpErrorMapper,
},
);
}
diff --git a/server/tests/unit/nest-mcp/error-mapper.test.ts b/server/tests/unit/nest-mcp/error-mapper.test.ts
new file mode 100644
index 000000000..bfaf5da79
--- /dev/null
+++ b/server/tests/unit/nest-mcp/error-mapper.test.ts
@@ -0,0 +1,109 @@
+import {
+ createTestRegistry,
+ McpController,
+ McpModule,
+ McpRegistryService,
+ Tool,
+ type McpDynamicTool,
+} from '../../../src/nest-mcp';
+import { createAttachHarness, type AttachHarness } from './harness';
+import { Module } from '@nestjs/common';
+import { Test } from '@nestjs/testing';
+
+import 'reflect-metadata';
+import { afterEach, describe, expect, it } from 'vitest';
+import { z } from 'zod';
+
+class Refusal extends Error {}
+
+const mapRefusal = (err: unknown) =>
+ err instanceof Refusal ? { content: [{ type: 'text', text: `mapped: ${err.message}` }], isError: true } : undefined;
+
+@McpController()
+class ThrowingMcp {
+ @Tool({ name: 'refuse', inputSchema: { why: z.string() } })
+ async refuse({ why }: { why: string }) {
+ throw new Refusal(why);
+ }
+
+ @Tool({ name: 'refuse_sync', inputSchema: {} })
+ refuseSync() {
+ throw new Refusal('sync');
+ }
+
+ @Tool({ name: 'crash', inputSchema: {} })
+ async crash() {
+ throw new Error('boom');
+ }
+
+ @Tool({ name: 'fine', inputSchema: {} })
+ async fine() {
+ return { content: [{ type: 'text', text: 'ok' }] };
+ }
+}
+
+@Module({ providers: [ThrowingMcp] })
+class ThrowingModule {}
+
+const textOf = (result: unknown): string => (result as { content: { text: string }[] }).content[0].text;
+
+describe('tool error mapper', () => {
+ let harness: AttachHarness | undefined;
+ afterEach(async () => {
+ await harness?.cleanup();
+ harness = undefined;
+ });
+
+ it('answers with the mapped result for an error the mapper recognises', async () => {
+ harness = await createAttachHarness(createTestRegistry([new ThrowingMcp()], { errorMapper: mapRefusal }), {});
+ expect(await harness.client.callTool({ name: 'refuse', arguments: { why: 'nope' } })).toEqual({
+ content: [{ type: 'text', text: 'mapped: nope' }],
+ isError: true,
+ });
+ expect(textOf(await harness.client.callTool({ name: 'refuse_sync', arguments: {} }))).toBe('mapped: sync');
+ });
+
+ it('lets an error the mapper does not recognise propagate as before', async () => {
+ harness = await createAttachHarness(createTestRegistry([new ThrowingMcp()], { errorMapper: mapRefusal }), {});
+ const result = await harness.client.callTool({ name: 'crash', arguments: {} });
+ expect(result.isError).toBe(true);
+ expect(textOf(result)).toContain('boom');
+ });
+
+ it('passes a successful result through untouched', async () => {
+ harness = await createAttachHarness(createTestRegistry([new ThrowingMcp()], { errorMapper: mapRefusal }), {});
+ expect(textOf(await harness.client.callTool({ name: 'fine', arguments: {} }))).toBe('ok');
+ });
+
+ it('maps nothing without a configured mapper', async () => {
+ harness = await createAttachHarness(createTestRegistry([new ThrowingMcp()]), {});
+ const result = await harness.client.callTool({ name: 'refuse', arguments: { why: 'raw' } });
+ expect(result.isError).toBe(true);
+ expect(textOf(result)).not.toContain('mapped');
+ });
+
+ it('leaves dynamic tools to their own source', async () => {
+ const dynamic: McpDynamicTool = {
+ options: { name: 'dyn', inputSchema: {}, access: () => true },
+ handler: () => {
+ throw new Refusal('dynamic');
+ },
+ };
+ harness = await createAttachHarness(
+ createTestRegistry([], { errorMapper: mapRefusal }),
+ {},
+ { dynamicTools: () => [dynamic] },
+ );
+ expect(textOf(await harness.client.callTool({ name: 'dyn', arguments: {} }))).not.toContain('mapped');
+ });
+
+ it('is handed through McpModule.forRoot', async () => {
+ const moduleRef = await Test.createTestingModule({
+ imports: [ThrowingModule, McpModule.forRoot({ errorMapper: mapRefusal })],
+ }).compile();
+ await moduleRef.init();
+ harness = await createAttachHarness(moduleRef.get(McpRegistryService), {});
+ expect(textOf(await harness.client.callTool({ name: 'refuse', arguments: { why: 'di' } }))).toBe('mapped: di');
+ await moduleRef.close();
+ });
+});
diff --git a/server/tests/unit/nest/domain-error.test.ts b/server/tests/unit/nest/domain-error.test.ts
new file mode 100644
index 000000000..b2b926a9f
--- /dev/null
+++ b/server/tests/unit/nest/domain-error.test.ts
@@ -0,0 +1,133 @@
+import { trekMcpErrorMapper } from '../../../src/mcp/nest-mcp-policy';
+import {
+ badRequest,
+ catchDomainError,
+ conflict,
+ DomainError,
+ forbidden,
+ notFound,
+ unauthorized,
+} from '../../../src/nest/common/domain-error';
+import { TrekExceptionFilter } from '../../../src/nest/common/trek-exception.filter';
+import { HttpException } from '@nestjs/common';
+
+import { describe, expect, it, vi } from 'vitest';
+
+function mockHost() {
+ const res = {
+ status: vi.fn().mockReturnThis(),
+ json: vi.fn().mockReturnThis(),
+ destroy: vi.fn(),
+ headersSent: false,
+ };
+ const host = { switchToHttp: () => ({ getResponse: () => res }) } as never;
+ return { res, host };
+}
+
+describe('DomainError', () => {
+ it('carries status, public message, a default code and no details', () => {
+ const err = new DomainError(404, 'Trip not found');
+ expect(err.getStatus()).toBe(404);
+ expect(err.publicMessage).toBe('Trip not found');
+ expect(err.message).toBe('Trip not found');
+ expect(err.code).toBe('not_found');
+ expect(err.details).toBeUndefined();
+ expect(err.toBody()).toEqual({ error: 'Trip not found' });
+ expect(err).toBeInstanceOf(HttpException);
+ expect(err.name).toBe('DomainError');
+ });
+
+ it('takes an explicit code and folds details into the body next to error', () => {
+ const err = new DomainError(409, 'Taken', { code: 'email_taken', details: { field: 'email' } });
+ expect(err.code).toBe('email_taken');
+ expect(err.toBody()).toEqual({ field: 'email', error: 'Taken' });
+ expect(err.getResponse()).toEqual({ field: 'email', error: 'Taken' });
+ });
+
+ it('never lets a detail override the public message', () => {
+ expect(new DomainError(400, 'real', { details: { error: 'fake' } }).toBody()).toEqual({ error: 'real' });
+ });
+
+ it('names statuses without a table entry by number', () => {
+ expect(new DomainError(418, 'teapot').code).toBe('http_418');
+ expect(new DomainError(410, 'gone').code).toBe('gone');
+ });
+
+ it('has shorthands for the common statuses', () => {
+ expect(badRequest('a').getStatus()).toBe(400);
+ expect(unauthorized('a').getStatus()).toBe(401);
+ expect(forbidden('a').getStatus()).toBe(403);
+ expect(notFound('a', { id: 1 }).toBody()).toEqual({ id: 1, error: 'a' });
+ expect(conflict('a').getStatus()).toBe(409);
+ });
+});
+
+describe('catchDomainError', () => {
+ it('returns the value of a call that succeeds', async () => {
+ expect(await catchDomainError(() => 5)).toEqual({ ok: true, value: 5 });
+ });
+
+ it('returns the DomainError a call raised', async () => {
+ const err = forbidden('no');
+ expect(
+ await catchDomainError(async () => {
+ throw err;
+ }),
+ ).toEqual({ ok: false, error: err });
+ });
+
+ it('rethrows any other error', async () => {
+ await expect(
+ catchDomainError(() => {
+ throw new Error('boom');
+ }),
+ ).rejects.toThrow('boom');
+ });
+});
+
+describe('TrekExceptionFilter on a DomainError', () => {
+ const filter = new TrekExceptionFilter();
+
+ it('writes the status and { error } body verbatim', () => {
+ const { res, host } = mockHost();
+ filter.catch(new DomainError(410, 'Invite link has expired'), host);
+ expect(res.status).toHaveBeenCalledWith(410);
+ expect(res.json).toHaveBeenCalledWith({ error: 'Invite link has expired' });
+ });
+
+ it('keeps the public message of a 5xx, as the hand-thrown HttpException did', () => {
+ const { res, host } = mockHost();
+ filter.catch(new DomainError(500, 'Demo user not found'), host);
+ expect(res.status).toHaveBeenCalledWith(500);
+ expect(res.json).toHaveBeenCalledWith({ error: 'Demo user not found' });
+ });
+
+ it('answers byte-identically to the HttpException({ error }) it replaces', () => {
+ const before = mockHost();
+ const after = mockHost();
+ filter.catch(new HttpException({ error: 'Admin access required' }, 403), before.host);
+ filter.catch(forbidden('Admin access required'), after.host);
+ expect(after.res.status.mock.calls).toEqual(before.res.status.mock.calls);
+ expect(after.res.json.mock.calls).toEqual(before.res.json.mock.calls);
+ });
+
+ it('writes details next to error', () => {
+ const { res, host } = mockHost();
+ filter.catch(new DomainError(400, 'Bad', { details: { message: 'kept' } }), host);
+ expect(res.json).toHaveBeenCalledWith({ message: 'kept', error: 'Bad' });
+ });
+});
+
+describe('trekMcpErrorMapper', () => {
+ it('turns a DomainError into errorResult(publicMessage)', () => {
+ expect(trekMcpErrorMapper(notFound('Trip not found or access denied.'))).toEqual({
+ content: [{ type: 'text', text: 'Trip not found or access denied.' }],
+ isError: true,
+ });
+ });
+
+ it('leaves any other error alone', () => {
+ expect(trekMcpErrorMapper(new Error('boom'))).toBeUndefined();
+ expect(trekMcpErrorMapper(new HttpException('x', 400))).toBeUndefined();
+ });
+});