Skip to content

Client.listTools() corrupts its cached tool metadata when an output schema fails to compile #2614

Open

Description

@sebthom

Description

Client.listTools() clears its existing output-validator and task-metadata caches before every schema in the replacement catalog has compiled successfully.

If compilation of a later output schema throws, listTools() rejects as expected, but the previously valid metadata has already been erased or partially replaced. Subsequent callTool() operations may
therefore skip output validation, and cached task-support information may also be lost.

A failed catalog refresh should leave the previous complete metadata generation unchanged.

This is separate from the concurrent callTool()/listTools() validator-generation race reported in: #2612

Reproduction

Tested with @modelcontextprotocol/[email protected].

import assert from "node:assert/strict";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";

const client = new Client({
  name: "metadata-cache-repro",
  version: "1.0.0",
});

const validCatalog = ListToolsResultSchema.parse({
  tools: [{
    name: "versioned",
    inputSchema: {
      type: "object",
      additionalProperties: false,
    },
    outputSchema: {
      type: "object",
      properties: {
        generation: { const: "old" },
      },
      required: ["generation"],
      additionalProperties: false,
    },
  }],
});

// The MCP result schema accepts this catalog because the output schema has a
// valid object root. AJV later rejects the invalid nested `type`.
const invalidCatalog = ListToolsResultSchema.parse({
  tools: [{
    name: "invalid",
    inputSchema: {
      type: "object",
      additionalProperties: false,
    },
    outputSchema: {
      type: "object",
      properties: {
        value: { type: "not-a-json-schema-type" },
      },
    },
  }],
});

const catalogs = [validCatalog, invalidCatalog];

client.request = async ({ method }) => {
  if (method === "tools/list") {
    return catalogs.shift();
  }

  if (method === "tools/call") {
    return {
      content: [{ type: "text", text: "new" }],
      structuredContent: { generation: "new" },
      isError: false,
    };
  }

  throw new Error(`Unexpected method: ${method}`);
};

// Installs the validator requiring generation === "old".
await client.listTools();

// Compilation throws, which is expected for the invalid schema.
await assert.rejects(() => client.listTools());

// This should still use the validator from the last successful catalog and
// reject generation === "new". Instead, it resolves because that validator
// was cleared before the failed replacement compiled.
await assert.rejects(
  () => client.callTool({
    name: "versioned",
    arguments: {},
  }),
  /does not match the tool's output schema/,
);

The final assertion fails with:

AssertionError: Missing expected rejection

Expected behavior

Metadata replacement should be failure-atomic:

  1. Compile all output validators and collect all task metadata into temporary collections.
  2. Publish the new collections only after the entire catalog succeeds.
  3. If any schema compilation throws, preserve the previous complete collections.

Actual behavior

cacheToolMetadata() clears the current collections before compilation begins:

this._cachedToolOutputValidators.clear();
this._cachedKnownTaskTools.clear();
this._cachedRequiredTaskTools.clear();

A later compilation error therefore leaves the client with empty or partially replaced metadata.

Suggested fix

One possible failure-atomic fix is to build replacement Map and Set instances locally, then publish them only after every tool has been processed and every output schema has compiled successfully.

diff --git a/src/client/index.ts b/src/client/index.ts
--- a/src/client/index.ts
+++ b/src/client/index.ts
@@
 private cacheToolMetadata(tools: Tool[]): void {
-    this._cachedToolOutputValidators.clear();
-    this._cachedKnownTaskTools.clear();
-    this._cachedRequiredTaskTools.clear();
+    // Compile the complete replacement before publishing it so a late schema
+    // failure leaves the previous successful metadata generation intact.
+    const toolOutputValidators = new Map<string, JsonSchemaValidator<unknown>>();
+    const knownTaskTools = new Set<string>();
+    const requiredTaskTools = new Set<string>();

     for (const tool of tools) {
         // If the tool has an outputSchema, create and cache the validator
         if (tool.outputSchema) {
             const toolValidator = this._jsonSchemaValidator.getValidator(
                 tool.outputSchema as JsonSchemaType
             );
-            this._cachedToolOutputValidators.set(tool.name, toolValidator);
+            toolOutputValidators.set(tool.name, toolValidator);
         }

         // If the tool supports task-based execution, cache that information
         const taskSupport = tool.execution?.taskSupport;
         if (taskSupport === 'required' || taskSupport === 'optional') {
-            this._cachedKnownTaskTools.add(tool.name);
+            knownTaskTools.add(tool.name);
         }

         if (taskSupport === 'required') {
-            this._cachedRequiredTaskTools.add(tool.name);
+            requiredTaskTools.add(tool.name);
         }
     }
+
+    this._cachedToolOutputValidators = toolOutputValidators;
+    this._cachedKnownTaskTools = knownTaskTools;
+    this._cachedRequiredTaskTools = requiredTaskTools;
 }

Activity

  1. kinKingen commented on Aug 4, 2026

    @kinKingen

    I'd like to take this if maintainers are happy to assign it.

    I verified that the current v1.x branch still clears all three metadata caches before output-schema validator compilation in cacheToolMetadata(). Since this report targets @modelcontextprotocol/[email protected] and the main v2 client now uses a different cache architecture, I would target v1.x.

    Proposed focused change:

    • add a regression test that installs valid output/task metadata, makes the next listTools() refresh fail during schema compilation, then verifies the previous output validator and task-support metadata are still active;
    • build replacement Map/Set collections locally and publish them only after every tool compiles successfully;
    • run the focused client tests plus the v1.x typecheck/lint gates.

    I will wait for assignment before starting implementation, per the contribution guide.

    AI disclosure: I used an AI coding assistant to help inspect the current branches and formulate this plan; I personally reviewed the repository rules, code path, and conclusions above.

  2. added
    bug
    P3
    ready for work
    on Aug 17, 2026
  3. added
    v1
    on Aug 18, 2026
  4. alexsalazar-asjr commented on Oct 29, 2026

    @alexsalazar-asjr

    Since three PRs now target this issue and none has a review yet, I ran a comparative verification of the two in-repo candidates against v1.x (base 3b73021, v1.32.2), hoping it saves a maintainer a pass. Method: for each PR, run its new test on unpatched v1.x (expect red), then with its source change (expect green), then the full test/client/index.test.ts.

    #2976 (@Misyuk-T) #3093 (@kanchingyg)
    Test red on unpatched v1.x ✅ fails as expected ✅ fails as expected
    Test green with fix ✅ ✅
    Full client test file ✅ 69/69 ✅ 69/69
    Deps/lockfile touched none none
    Fix shape exactly the atomic swap proposed in this issue: build replacement Map/Sets, publish after the loop same atomic swap plus a try/catch that attaches a non-enumerable toolName property to compile errors
    Changeset patch, accurate patch, accurate

    Both implement the same correct core fix: build toolOutputValidators / knownTaskTools / requiredTaskTools locally and assign the fields only after every schema compiles. The three fields are plain mutable privates read via accessors (getToolOutputValidator, isToolTaskRequired, etc.), so reference-swap is safe — no other code path holds the old collections.

    Differences that may matter for the merge decision:

    Both leave #2612 (validator read after await in callTool()) correctly out of scope.

    Suggested resolution: #2976 as the merge candidate (smallest diff, issue-endorsed shape, robust assertions); the toolName diagnostics idea from #3093 could be a separate follow-up if maintainers want it. There is also a third implementation on a fork (Jihaochang1#3) that was never opened against this repo.

    Disclosure: verification performed with AI assistance (Claude); each PR's diff was read in full and the test runs above were executed locally as described.

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

    P3bugready for workv1

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions