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.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(mcp): validate a tool or prompt field again once NUL stripping changed it
Maurice8fb720ea4997
diff --git a/server/src/nest-mcp/registry.ts b/server/src/nest-mcp/registry.tsindex c7c4d6ca1..bbb74fe80 100644--- a/server/src/nest-mcp/registry.ts+++ b/server/src/nest-mcp/registry.ts@@ -19,6 +19,7 @@ import type {} from './types';import { ResourceTemplate as SdkResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types';import { z } from 'zod';@@ -38,6 +39,43 @@ function strictInputSchema(schema: ToolOptions['inputSchema']): unknown {return z.strictObject(schema);}+/** The fields of an object schema by name; undefined for any other schema. */+function shapeOf(schema: unknown): Record<string, z.ZodType> | undefined {+ const shape = (schema as { shape?: unknown } | undefined)?.shape;+ return shape && typeof shape === 'object' ? (shape as Record<string, z.ZodType>) : undefined;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++/**+ * Runs the host's input mapper over what the SDK parsed. The SDK validated the+ * fields before the mapper changed them, so each field it changed is validated+ * again against its own schema: a name of nothing but dropped characters must+ * fail its min(1) here as it does over REST, not reach the handler empty. A+ * field the mapper left as it was is not parsed twice. The issues are worded+ * as the SDK words its own.+ */+function mapValidated(+ mapper: McpInputMapper,+ input: unknown,+ shape: Record<string, z.ZodType> | undefined,+ refuse: (message: string) => McpError,+): unknown {+ const mapped = mapper(input);+ if (mapped === input || !shape || !isRecord(input) || !isRecord(mapped)) return mapped;+ const messages = Object.entries(mapped).flatMap(([key, value]) => {+ const field = shape[key];+ if (!field || value === input[key]) return [];+ const result = field.safeParse(value);+ if (result.success) return [];+ return result.error.issues.map((issue) => `${issue.message} at ${[key, ...issue.path].map(String).join('.')}`);+ });+ if (messages.length > 0) throw refuse(messages.join('\n'));+ return mapped;+}+export interface McpRegistryOptions {accessPolicy?: McpAccessPolicy;validateAccess?: McpAccessValidator;@@ -380,10 +418,11 @@ export class McpRegistry {ctx: McpContext,opts?: McpAttachOptions,): void {+ const inputSchema = strictInputSchema(options.inputSchema);const config: Record<string, unknown> = {title: options.title,description: options.description,- inputSchema: strictInputSchema(options.inputSchema),+ inputSchema,outputSchema: options.outputSchema,annotations: options.annotations,_meta: options._meta,@@ -395,10 +434,12 @@ export class McpRegistry {const cb =options.inputSchema !== undefined? (args: unknown, _extra: unknown) => {+ const input = mapValidated(this.inputMapper, args, shapeOf(inputSchema), (message) => {+ const text = `Input validation error: Invalid arguments for tool ${options.name}: ${message}`;+ return new McpError(ErrorCode.InvalidParams, text);+ });opts?.onInvoke?.({ kind: 'tool', name: options.name });- return invoke(opts, { kind: 'tool', name: options.name }, () =>- handler.call(instance, this.inputMapper(args), ctx),- );+ return invoke(opts, { kind: 'tool', name: options.name }, () => handler.call(instance, input, ctx));}: (_extra: unknown) => {opts?.onInvoke?.({ kind: 'tool', name: options.name });@@ -476,10 +517,12 @@ export class McpRegistry {const cb =argsSchema !== undefined? (args: unknown, _extra: unknown) => {+ const input = mapValidated(this.inputMapper, args, argsSchema, (message) => {+ const text = `Invalid arguments for prompt ${options.name}: ${message}`;+ return new McpError(ErrorCode.InvalidParams, text);+ });opts?.onInvoke?.({ kind: 'prompt', name: options.name });- return invoke(opts, { kind: 'prompt', name: options.name }, () =>- handler.call(instance, this.inputMapper(args), ctx),- );+ return invoke(opts, { kind: 'prompt', name: options.name }, () => handler.call(instance, input, ctx));}: (_extra: unknown) => {opts?.onInvoke?.({ kind: 'prompt', name: options.name });diff --git a/server/tests/unit/nest-mcp/attach.test.ts b/server/tests/unit/nest-mcp/attach.test.tsindex 76defa1a2..1340c48eb 100644--- a/server/tests/unit/nest-mcp/attach.test.ts+++ b/server/tests/unit/nest-mcp/attach.test.ts@@ -141,6 +141,21 @@ class WhenMcp {featureOn = false;}+@McpController()+class NamedMcp {+ @Tool({ name: 'named_tool', inputSchema: { name: z.string().min(1), note: z.string().optional() } })+ async namedTool(args: { name: string }, ctx: TestCtx) {+ return { content: [{ type: 'text', text: JSON.stringify({ args, userId: ctx.userId }) }] };+ }++ @Prompt({ name: 'named_prompt', argsSchema: { topic: z.string().min(1) } })+ async namedPrompt({ topic }: { topic: string }, ctx: TestCtx) {+ return {+ messages: [{ role: 'user' as const, content: { type: 'text' as const, text: `${topic} for ${ctx.userId}` } }],+ };+ }+}+const policy: McpAccessPolicy = ({ mode }, ctx) =>mode === 'write' ? (ctx as TestCtx).canWrite === true : (ctx as TestCtx).canRead === true;@@ -250,6 +265,20 @@ describe('McpRegistry.attach', () => {expect(mapped).toEqual([{ name: 'tr!ek' }, { topic: 'pack!ing' }, { id: '4!2' }]);});+ it('validates a field again once the input mapper changed it, as REST validates the stripped value', async () => {+ const inputMapper = (input: unknown) => JSON.parse(JSON.stringify(input).replaceAll('!', '')) as unknown;+ harness = await createAttachHarness(createTestRegistry([new NamedMcp()], { inputMapper }), { userId: 5 });++ const emptied = await harness.client.callTool({ name: 'named_tool', arguments: { name: '!!', note: 'ok' } });+ expect(emptied.isError).toBe(true);+ expect(textOf(emptied)).toMatch(/Invalid arguments for tool named_tool: .* at name/);+ const kept = await harness.client.callTool({ name: 'named_tool', arguments: { name: 'tr!ek', note: '!' } });+ expect(JSON.parse(textOf(kept))).toEqual({ args: { name: 'trek', note: '' }, userId: 5 });+ await expect(harness.client.getPrompt({ name: 'named_prompt', arguments: { topic: '!' } })).rejects.toThrow(+ /Invalid arguments for prompt named_prompt: .* at topic/,+ );+ });+it('serves fixed resources with (uri, ctx)', async () => {harness = await createAttachHarness(buildRegistry(), { userId: 9, canRead: true });const result = await harness.client.readResource({ uri: 'test://doc' });