Skip to content

ClientResponseCache compiles every cached output schema before the first ordinary callTool #2997

Closed
morluto/rea
#1583

Description

@N0zoM1z0

On @modelcontextprotocol/[email protected] (latest npm version checked on 2026-10-10), the first ordinary callTool after complete discovery prepares output validators for every cached tool, including tools that are never called. This leaves substantial cold latency even when schema identity reuse eliminates refresh recompilation.

The owning path is ClientResponseCache.outputValidator: its stamp change rebuilds the validator index for the whole list. This is distinct from #2605's repeated compilation of schemas without $id and #2614's compile-failure metadata corruption.

Observed with a compiled REA stdio server, the pinned SDK's default Ajv implementation, Node 24.18.0, Linux x64, two CPUs:

  • Discovery exposes all 139 tools with complete input/output schemas, 1,884,470 compact UTF-8 bytes. Output schemas carry content/dialect-bound IDs; there are 118 distinct output schemas.
  • Only binary_session is called after initial discovery. That one call invokes 118 actual engine.compile calls and 21 ID-cache hits, taking 2,743.6 ms including 2,434.7 ms inside compilation.
  • Refreshed catalogs and a reconnect of the same client invoke zero new compilations for unchanged schemas. Subsequent directory analysis, retained-Evidence summary/module paging, ping and close pass.
  • No per-call toolDefinition was supplied. Compiler/cache-hit counters observe the unchanged default implementation; they do not substitute validation.

The server-side identity mitigation and its schema-change/availability/reconnect tests are in morluto/rea#1433. It keeps complete discovery and output validation and deliberately does not claim reduced model context.

Could the stamp-bound validator index compile only the requested tool on demand? The metadata/name index can remain complete. Compilation errors should stay isolated to the requested tool, and the derived validator must inherit the same list-change, expiry, header-mismatch, availability and reconnect invalidation. A changed output schema must never reuse the old validator.

Suggested consumer checks: a valid called tool alongside an uncompilable uncalled output schema; the bad tool's own typed error; changed schemas after refresh; removed/re-enabled tools; reconnect/server changes; metadata/header invalidation. The existing explicit toolDefinition option is useful, but requiring callers to supply it for ordinary cache-backed calls leaves the default path's cold cost.

Activity

  1. added
    v1
    v2
    on Oct 10, 2026
  2. Ben-Home commented on Oct 10, 2026

    @Ben-Home
  3. morluto commented on Oct 26, 2026

    @morluto
    Contributor

    Confirmed this remains reproducible in published @modelcontextprotocol/[email protected] and @modelcontextprotocol/[email protected] (checked 2026-10-26), as well as REA's pinned 2.3.1. This issue is closed as completed, but #2998 is still open and unmerged. Could this issue be reopened or kept linked to that pending fix?

    Small standalone reproduction: three tools, one call, real in-memory MCP transport and genuine Ajv validation. Tested on Node 24.22.1, macOS arm64. In a fresh directory, install the pinned packages below, save the script as repro.mjs, and run node repro.mjs:

    npm install --ignore-scripts --no-audit --no-fund @modelcontextprotocol/[email protected] @modelcontextprotocol/[email protected] [email protected]
    import assert from 'node:assert/strict';
    import { Client, InMemoryTransport } from '@modelcontextprotocol/client';
    import { AjvJsonSchemaValidator } from '@modelcontextprotocol/client/validators/ajv';
    import { McpServer } from '@modelcontextprotocol/server';
    import { z } from 'zod';
    
    async function run(useToolDefinition) {
      const compiled = [];
      let validations = 0;
      const ajv = new AjvJsonSchemaValidator();
      const client = new Client(
        { name: 'schema-compilation-repro', version: '1' },
        {
          jsonSchemaValidator: {
            getValidator(schema) {
              compiled.push(schema.properties.tool.const);
              const validate = ajv.getValidator(schema);
              return value => {
                validations++;
                return validate(value);
              };
            },
          },
        },
      );
      const server = new McpServer({ name: 'three-tools', version: '1' });
      for (const name of ['alpha', 'beta', 'gamma']) {
        server.registerTool(
          name,
          {
            inputSchema: z.object({}),
            outputSchema: z.object({ tool: z.literal(name), value: z.number() }),
          },
          async () => ({
            content: [],
            structuredContent: { tool: name, value: 1 },
          }),
        );
      }
      const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
      try {
        await server.connect(serverTransport);
        await client.connect(clientTransport);
        const { tools } = await client.listTools();
        const alpha = tools.find(tool => tool.name === 'alpha');
        assert.ok(alpha);
        const response = await client.callTool(
          { name: 'alpha', arguments: {} },
          useToolDefinition ? { toolDefinition: alpha } : undefined,
        );
        assert.deepEqual(response.structuredContent, { tool: 'alpha', value: 1 });
        assert.equal(validations, 1);
        assert.equal(compiled.length, useToolDefinition ? 1 : 3);
        console.log(JSON.stringify({
          mode: useToolDefinition ? 'selected toolDefinition' : 'cached tools/list',
          compiled,
          validations,
          result: response.structuredContent,
        }));
      } finally {
        await client.close();
        await server.close();
      }
    }
    
    await run(false);
    await run(true);

    Observed with both versions:

    {"mode":"cached tools/list","compiled":["alpha","beta","gamma"],"validations":1,"result":{"tool":"alpha","value":1}}
    {"mode":"selected toolDefinition","compiled":["alpha"],"validations":1,"result":{"tool":"alpha","value":1}}

    The instrumentation delegates every validator request and actual validation to AjvJsonSchemaValidator; it does not bypass validation. Expected: an ordinary call to alpha should prepare only alpha's output validator, with the existing cache invalidation and error behavior preserved.

    For scale, a separate passing REA workflow on pinned SDK 2.3.1 prepared 229 validators through the ordinary cached path versus 2 with explicit tool definitions. In a single before/after sample, time inside validator preparation was 3.477 s versus 54.7 ms; sampled heap at preparation checkpoints peaked at 468.5 versus 307.5 MiB. Both complete workflows passed under the same 512 MiB worker heap. These are workload-specific measurements, not an OOM reproduction or a benchmark of 2.4.0. We are correcting the affected REA test callers to use the supported toolDefinition path while retaining full output validation.

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