|
| 1 | +/** |
| 2 | + * Tool input validation enhancement for the MCP server. |
| 3 | + * |
| 4 | + * The upstream MCP SDK (`getParseErrorMessage` in `zod-compat.js`) extracts |
| 5 | + * only the *first* Zod issue when a tool call fails validation. This module |
| 6 | + * overrides `McpServer.validateToolInput` so that **all** issues are surfaced |
| 7 | + * in a single, human-readable error message. |
| 8 | + */ |
| 9 | + |
| 10 | +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; |
| 11 | +import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'; |
| 12 | +import { z } from 'zod'; |
| 13 | + |
| 14 | +// ─── Error formatting ──────────────────────────────────────────────────────── |
| 15 | + |
| 16 | +/** |
| 17 | + * Format all Zod validation issues into a single, human-readable message. |
| 18 | + * |
| 19 | + * - Groups missing-required-field errors into one line |
| 20 | + * (`must have required properties: 'a', 'b'`). |
| 21 | + * - Appends any other validation errors individually. |
| 22 | + */ |
| 23 | +export function formatAllValidationErrors(error: z.ZodError): string { |
| 24 | + const { issues } = error; |
| 25 | + |
| 26 | + if (issues.length === 0) return 'Unknown validation error'; |
| 27 | + |
| 28 | + // Partition into "required-field missing" vs "everything else" |
| 29 | + const missingRequired: string[] = []; |
| 30 | + const otherErrors: string[] = []; |
| 31 | + |
| 32 | + for (const issue of issues) { |
| 33 | + const path = issue.path.join('.'); |
| 34 | + |
| 35 | + if (issue.code === 'invalid_type' && issue.received === 'undefined' && path) { |
| 36 | + missingRequired.push(`'${path}'`); |
| 37 | + } else { |
| 38 | + otherErrors.push(path ? `${path}: ${issue.message}` : issue.message); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + const parts: string[] = []; |
| 43 | + |
| 44 | + if (missingRequired.length === 1) { |
| 45 | + parts.push(`must have required property ${missingRequired[0]}`); |
| 46 | + } else if (missingRequired.length > 1) { |
| 47 | + parts.push(`must have required properties: ${missingRequired.join(', ')}`); |
| 48 | + } |
| 49 | + |
| 50 | + parts.push(...otherErrors); |
| 51 | + |
| 52 | + return parts.join('; '); |
| 53 | +} |
| 54 | + |
| 55 | +// ─── Schema resolution ─────────────────────────────────────────────────────── |
| 56 | + |
| 57 | +/** |
| 58 | + * Resolve the tool's `inputSchema` into a parsable Zod schema. |
| 59 | + * |
| 60 | + * Handles both: |
| 61 | + * - Raw Zod shapes (`{ owner: z.string(), ... }`) — wraps with `z.object()` |
| 62 | + * - Pre-built Zod schemas (ZodObject, ZodEffects, etc.) — returns as-is |
| 63 | + */ |
| 64 | +function resolveZodSchema(inputSchema: unknown): z.ZodTypeAny | undefined { |
| 65 | + if (!inputSchema || typeof inputSchema !== 'object') return undefined; |
| 66 | + |
| 67 | + const schema = inputSchema as Record<string, unknown>; |
| 68 | + |
| 69 | + // Already a Zod schema instance (has _def for Zod v3 or _zod for v4) |
| 70 | + if ('_def' in schema || '_zod' in schema) { |
| 71 | + return inputSchema as z.ZodTypeAny; |
| 72 | + } |
| 73 | + |
| 74 | + // Check for raw Zod shape (all values are Zod schemas) |
| 75 | + const values = Object.values(schema); |
| 76 | + if ( |
| 77 | + values.length > 0 && |
| 78 | + values.every( |
| 79 | + (v) => |
| 80 | + typeof v === 'object' && |
| 81 | + v !== null && |
| 82 | + ('_def' in (v as Record<string, unknown>) || |
| 83 | + '_zod' in (v as Record<string, unknown>) || |
| 84 | + typeof (v as Record<string, unknown>).parse === 'function'), |
| 85 | + ) |
| 86 | + ) { |
| 87 | + return z.object(schema as z.ZodRawShape); |
| 88 | + } |
| 89 | + |
| 90 | + return undefined; |
| 91 | +} |
| 92 | + |
| 93 | +// ─── Instance patch ────────────────────────────────────────────────────────── |
| 94 | + |
| 95 | +/** |
| 96 | + * Patch `validateToolInput` on the given McpServer **instance** so that |
| 97 | + * **all** validation errors are reported in a single response instead of |
| 98 | + * only the first one. |
| 99 | + * |
| 100 | + * Call this once after constructing the McpServer and before connecting |
| 101 | + * any transport. |
| 102 | + */ |
| 103 | +export function patchValidateToolInput(server: McpServer): void { |
| 104 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 105 | + const instance = server as any; |
| 106 | + |
| 107 | + // Capture the original so we can delegate for unrecognized schema types |
| 108 | + const originalValidateToolInput = instance.validateToolInput.bind(instance); |
| 109 | + |
| 110 | + instance.validateToolInput = async function ( |
| 111 | + tool: { inputSchema?: unknown }, |
| 112 | + args: unknown, |
| 113 | + toolName: string, |
| 114 | + ): Promise<unknown> { |
| 115 | + if (!tool.inputSchema) { |
| 116 | + return undefined; |
| 117 | + } |
| 118 | + |
| 119 | + const schema = resolveZodSchema(tool.inputSchema); |
| 120 | + if (!schema) { |
| 121 | + // Unrecognized schema type — delegate to the original SDK validation |
| 122 | + // so mis-registered tools don't accidentally bypass input validation. |
| 123 | + return originalValidateToolInput(tool, args, toolName); |
| 124 | + } |
| 125 | + |
| 126 | + const parseResult = await schema.safeParseAsync(args); |
| 127 | + |
| 128 | + if (!parseResult.success) { |
| 129 | + const errorMessage = formatAllValidationErrors(parseResult.error); |
| 130 | + throw new McpError( |
| 131 | + ErrorCode.InvalidParams, |
| 132 | + `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`, |
| 133 | + ); |
| 134 | + } |
| 135 | + |
| 136 | + return parseResult.data; |
| 137 | + }; |
| 138 | +} |
0 commit comments