-
Notifications
You must be signed in to change notification settings - Fork 2
[UPDATE PRIMITIVE] Report all validation errors at once instead of one-at-a-time #227
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0438afb
Initial plan
Copilot ee7f0c0
Add tool-validation module to report all validation errors at once
Copilot 87dcf14
Add E2E integration tests for tool validation via InMemoryTransport
Copilot 23b7d51
Fixes for PR review feedback
data-douser 0e71d73
Merge branch 'main' into copilot/report-all-validation-errors
data-douser File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| /** | ||
| * Tool input validation enhancement for the MCP server. | ||
| * | ||
| * The upstream MCP SDK (`getParseErrorMessage` in `zod-compat.js`) extracts | ||
| * only the *first* Zod issue when a tool call fails validation. This module | ||
| * overrides `McpServer.validateToolInput` so that **all** issues are surfaced | ||
| * in a single, human-readable error message. | ||
| */ | ||
|
|
||
| import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; | ||
| import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'; | ||
| import { z } from 'zod'; | ||
|
|
||
| // βββ Error formatting ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | ||
|
|
||
| /** | ||
| * Format all Zod validation issues into a single, human-readable message. | ||
| * | ||
| * - Groups missing-required-field errors into one line | ||
| * (`must have required properties: 'a', 'b'`). | ||
| * - Appends any other validation errors individually. | ||
| */ | ||
| export function formatAllValidationErrors(error: z.ZodError): string { | ||
| const { issues } = error; | ||
|
|
||
| if (issues.length === 0) return 'Unknown validation error'; | ||
|
|
||
| // Partition into "required-field missing" vs "everything else" | ||
| const missingRequired: string[] = []; | ||
| const otherErrors: string[] = []; | ||
|
|
||
| for (const issue of issues) { | ||
| const path = issue.path.join('.'); | ||
|
|
||
| if (issue.code === 'invalid_type' && issue.received === 'undefined' && path) { | ||
| missingRequired.push(`'${path}'`); | ||
| } else { | ||
| otherErrors.push(path ? `${path}: ${issue.message}` : issue.message); | ||
| } | ||
| } | ||
|
|
||
| const parts: string[] = []; | ||
|
|
||
| if (missingRequired.length === 1) { | ||
| parts.push(`must have required property ${missingRequired[0]}`); | ||
| } else if (missingRequired.length > 1) { | ||
| parts.push(`must have required properties: ${missingRequired.join(', ')}`); | ||
| } | ||
|
|
||
| parts.push(...otherErrors); | ||
|
|
||
| return parts.join('; '); | ||
| } | ||
|
|
||
| // βββ Schema resolution βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | ||
|
|
||
| /** | ||
| * Resolve the tool's `inputSchema` into a parsable Zod schema. | ||
| * | ||
| * Handles both: | ||
| * - Raw Zod shapes (`{ owner: z.string(), ... }`) β wraps with `z.object()` | ||
| * - Pre-built Zod schemas (ZodObject, ZodEffects, etc.) β returns as-is | ||
| */ | ||
| function resolveZodSchema(inputSchema: unknown): z.ZodTypeAny | undefined { | ||
| if (!inputSchema || typeof inputSchema !== 'object') return undefined; | ||
|
|
||
| const schema = inputSchema as Record<string, unknown>; | ||
|
|
||
| // Already a Zod schema instance (has _def for Zod v3 or _zod for v4) | ||
| if ('_def' in schema || '_zod' in schema) { | ||
| return inputSchema as z.ZodTypeAny; | ||
| } | ||
data-douser marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // Check for raw Zod shape (all values are Zod schemas) | ||
| const values = Object.values(schema); | ||
| if ( | ||
| values.length > 0 && | ||
| values.every( | ||
| (v) => | ||
| typeof v === 'object' && | ||
| v !== null && | ||
| ('_def' in (v as Record<string, unknown>) || | ||
| '_zod' in (v as Record<string, unknown>) || | ||
| typeof (v as Record<string, unknown>).parse === 'function'), | ||
| ) | ||
| ) { | ||
| return z.object(schema as z.ZodRawShape); | ||
| } | ||
|
|
||
| return undefined; | ||
| } | ||
|
|
||
| // βββ Instance patch ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | ||
|
|
||
| /** | ||
| * Patch `validateToolInput` on the given McpServer **instance** so that | ||
| * **all** validation errors are reported in a single response instead of | ||
| * only the first one. | ||
| * | ||
| * Call this once after constructing the McpServer and before connecting | ||
| * any transport. | ||
| */ | ||
| export function patchValidateToolInput(server: McpServer): void { | ||
data-douser marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| const instance = server as any; | ||
|
|
||
| // Capture the original so we can delegate for unrecognized schema types | ||
| const originalValidateToolInput = instance.validateToolInput.bind(instance); | ||
|
|
||
| instance.validateToolInput = async function ( | ||
| tool: { inputSchema?: unknown }, | ||
| args: unknown, | ||
| toolName: string, | ||
| ): Promise<unknown> { | ||
| if (!tool.inputSchema) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const schema = resolveZodSchema(tool.inputSchema); | ||
| if (!schema) { | ||
| // Unrecognized schema type β delegate to the original SDK validation | ||
| // so mis-registered tools don't accidentally bypass input validation. | ||
| return originalValidateToolInput(tool, args, toolName); | ||
| } | ||
data-douser marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const parseResult = await schema.safeParseAsync(args); | ||
|
|
||
| if (!parseResult.success) { | ||
| const errorMessage = formatAllValidationErrors(parseResult.error); | ||
| throw new McpError( | ||
| ErrorCode.InvalidParams, | ||
| `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`, | ||
| ); | ||
| } | ||
|
|
||
| return parseResult.data; | ||
| }; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.