Skip to content

[v2][Enhancement][Fix Proposed] McpServer input validation error hook #2879

Open

Description

@CyberStrike

Summary

When a tools/call's arguments fail the tool's inputSchema, McpServer returns a fixed plain-text tool error. A server can't change what that result contains, so it can't give a schema failure the same structured error its tool callbacks return for every other failure. I'd like a supported way to shape that result.

Current behaviour

In @modelcontextprotocol/server 2.0.0 and 2.1.0, McpServer.validateToolInput is private. On failure it throws:

throw new ProtocolError(
  ProtocolErrorCode.InvalidParams,
  `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`
);

The tools/call handler's catch turns this into createToolError(message), which is also private: { isError: true, content: [{ type: 'text', text }] }. There is no structuredContent, and the issues aren't structured (the path and message of each failing argument).

Returning a tool execution error rather than a protocol error matches SEP-1303. The problem is only that the result's shape is fixed. On 1.x a server could override validateToolInput; in v2 it can't.

Why it matters

Many servers wrap an API that already has a structured error format (RFC 9457 problem details, for example). Their tool callbacks return that format as structuredContent, with an outputSchema covering both success and failure. That way an agent can branch on an error type instead of parsing prose.

A schema failure is the one failure that can't follow the format:

  • An agent sees two error shapes from one tool, depending on whether the SDK or the callback refused the call.
  • The failing argument's path is only available by parsing the message string.

Workaround

Build each tool's inputSchema with fromJsonSchema(jsonSchema, validator), where the validator is a jsonSchemaValidator that accepts every input. Then validate inside the callback and return the structured error there.

This keeps tools/list correct, and it uses the documented validator extension point. But it defers validation in a way that surprises readers. It also depends on the SDK continuing to validate through the schema's ~standard.validate, rather than against the JSON Schema directly.

Proposal

An option on McpServer (or per tool in registerTool) that receives the failure and returns the CallToolResult:

new McpServer(info, {
  onToolInputValidationError: ({ toolName, issues, arguments: args }) => ({
    isError: true,
    content: [{ type: 'text', text: summarize(issues) }],
    structuredContent: { problem: toProblem(toolName, issues) },
  }),
});
  • issues would be the Standard Schema issues, each with a path and a message.
  • The default stays today's text result, so existing servers see no change.
  • A smaller alternative: include the structured issues in the default result's structuredContent, or in _meta. That would leave the text unchanged but make the path readable without parsing.

Related

Versions checked: @modelcontextprotocol/server 2.0.0 and 2.1.0 (packages/server/src/server/mcp.ts), and @modelcontextprotocol/sdk 1.30.1 for comparison.

Activity

  1. added
    v1
    v2
    on Sep 28, 2026
  2. Ben-Home commented on Sep 28, 2026

    @Ben-Home
  3. Pial-Al-Mamun commented on Oct 1, 2026

    @Pial-Al-Mamun

    @CyberStrike would it be cool if I build this feature (take this pr) and also if a maintainer assign me it would be nice to know how would you guys prefer it to be like designed compare to his proposal?

  4. CyberStrike commented on Oct 1, 2026

    @CyberStrike
    Author

    @CyberStrike would it be cool if I build this feature (take this pr) and also if a maintainer assign me it would be nice to know how would you guys prefer it to be like designed compare to his proposal?

    See their contributing docs, the route for this to get somewhere other than this issue would be the Specification Enhancement Path proposal process and to champion it through before implementation time should be handled.

  5. Pial-Al-Mamun commented on Oct 2, 2026

    @Pial-Al-Mamun

    @CyberStrike if that is the case I would prefer just waiting for a maintainer to see this issue and then assign the task so I know perhaps how they would like me to implement it or even if this issue is currently being tasked to someone else.

  6. chenxin-yan commented on Oct 30, 2026

    @chenxin-yan

    +1 from a production server. We hit exactly this on @modelcontextprotocol/server 2.0.0, and 2.4.0 still has validateToolInput and createToolError private.

    Our API returns one error shape on every surface: HTTP answers 400 {"error": "...", "code": "invalid_request"}, and every MCP tool failure is {"error": {"status", "code", "message"}}. The SDK's schema failure is the only MCP error that's prose without a code. It is also the most common error an agent hits:

    Input validation error: Invalid arguments for tool list_projects: limit: Too small: expected number to be >=1
    

    We tried the workaround described above: register a schema whose ~standard.validate passes values through, then validate in the callback. It worked, and tools/list stayed byte-identical. We backed it out anyway, because the registered schema says one thing and does another, and it relies on the SDK only ever validating through ~standard.validate.

    A server option that receives the Standard Schema issues and returns the error content (the narrower hook suggested above, so the SDK keeps the isError envelope) would cover our case completely, with today's text as the default.

  7. lecstor commented on Nov 15, 2026

    @lecstor

    +1, with a use case for the narrow hook, and an argument for passing the raw arguments as well as the issues.

    We run a remote MCP server for long-running coding agents (SDK 1.29, stateless Streamable HTTP). Most of our schema failures aren't agents misreading the schema. They come from two cases where an accurate schema can't help:

    1. The model's tool-call emission drops or merges a parameter. The agent read the schema correctly, but the call that arrives is missing a field. The useful reply names what is missing and what did arrive, so the agent can tell a lost parameter from a rejected one. With the default text, we watched an agent spend four calls working out what one line would have told it.
    2. The client's cached tools/list predates a newly required argument. Clients fetch the list once at connect, and a stateless server has no session to send notifications/tools/list_changed to. The useful reply is "your schema may be stale; reconnect and retry". The default names a field the agent's schema doesn't have, and gives no way out.

    Because the default can't say either thing, we declare every always-required field .optional() in zod and enforce it in the handler. That keeps our error, but tools/list then tells clients the field is optional, which is false, and quality scanners flag it as a description/schema mismatch. Our fix is to write required back into the served inputSchema at the tools/list seam, which is the same "registered schema says one thing, does another" problem as the pass-through workaround above. Bounds have the same problem: with a maximum in the schema, an over-cap limit gets "Too big" prose and no hint to page.

    The narrow hook (the SDK keeps the isError envelope and the server returns the content), called with the tool name, the Standard Schema issues and the raw arguments, would let us register an honest schema and delete both workarounds. Case 1 is why the raw arguments matter: the reply has to say what arrived, and the issues list only says what failed.

  8. A7mdMe commented on Nov 15, 2026

    @A7mdMe

    Strongly agree with @bdefore and @CyberStrike. The lack of structured error content on schema validation failures creates a major friction point for autonomous agents, because a model can branch cleanly on an error code or RFC 9457 type, but struggles when forced to parse unstructured prose like Input validation error: Invalid arguments for tool....

    In our production MCP server deployments, we found that solving this requires tackling two distinct layers:

    1. Pre-Validation Self-Healing Coercion

    Many schema rejections aren't logic errors—they are superficial distortions from LLM generation (e.g. emitting "50" instead of 50, "true" instead of true, or stringifying an object parameter). Normalizing primitives before schema validation eliminates the majority of validation errors before they ever hit the validator:

    export function normalizeToolArguments(rawArgs: unknown): Record<string, unknown> {
      if (!rawArgs || typeof rawArgs !== 'object') return {};
      const result: Record<string, unknown> = {};
    
      for (const [key, val] of Object.entries(rawArgs as Record<string, unknown>)) {
        if (typeof val === 'string') {
          const trimmed = val.trim();
          // Coerce boolean strings
          if (trimmed.toLowerCase() === 'true' || trimmed.toLowerCase() === 'false') {
            result[key] = trimmed.toLowerCase() === 'true';
            continue;
          }
          // Coerce strict numeric strings
          if (/^-?\d+(\.\d+)?$/.test(trimmed) && !isNaN(Number(trimmed))) {
            result[key] = Number(trimmed);
            continue;
          }
          // Parse escaped JSON objects / arrays
          if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
            try {
              result[key] = JSON.parse(trimmed);
              continue;
            } catch {}
          }
        }
        result[key] = val;
      }
      return result;
    }

    2. RFC 9457 Problem Details with Parameter Diffing

    When a call genuinely fails validation, returning an RFC 9457 envelope under structuredContent alongside concise prompt text provides agents with the exact machine-readable delta (missing keys vs received keys), stopping models from looping:

    // CallToolResult with RFC 9457 structuredContent
    {
      isError: true,
      content: [
        {
          type: "text",
          text: "Input validation error for tool 'query_database':\n  - Parameter 'limit': Too small: expected number to be >=1 (received: 0)\n  Missing required: [startDate]\n  Received keys: [limit, query]\n  Hint: Check parameter types, constraints, and required fields."
        }
      ],
      structuredContent: {
        type: "https://modelcontextprotocol.io/errors/invalid-tool-arguments",
        title: "Invalid Tool Arguments",
        status: 400,
        tool: "query_database",
        invalidParams: [
          {
            name: "limit",
            path: ["limit"],
            reason: "Too small: expected number to be >=1",
            received: 0,
            expected: ">=1"
          }
        ],
        receivedKeys: ["limit", "query"],
        expectedKeys: ["startDate", "limit", "query"],
        missingKeys: ["startDate"],
        hint: "Missing required parameters: startDate. Parameter(s) received: [limit, query]."
      }
    }

    By pairing self-healing coercion with RFC 9457 parameter diffing, autonomous agents immediately correct dropped or distorted arguments on the very next turn without burning tokens on exploratory guesses.


    Disclosure: Maintainer of mcp-production-kit (open-source TypeScript starter kit for MCP servers featuring self-healing argument normalization, RFC 9457 validation formatting, mid-execution auth challenges, and stdio stream isolation).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    v1v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions