#11742·langchainjs

bug(mcp-adapters): cancelled discovery opens servers after close and poisons reuse

Author: To3akaRinCreated Sep 27, 2026Updated Sep 27, 2026

Description

This is reproducible on current main at 5d509ad4b8a5ed9dd4b83020b4c103ac8a69859c, in the unreleased MCP SDK 2 migration. It is not a report against the published 1.1.4 API: the package version still says 1.1.4 on this branch, but the example below uses the new MCPAdapter API from source.

When discovery spans multiple servers, a pending discovery response or an async onConnectionError handler can settle after await adapter.close() has completed. The old discovery then connects to the next server. Its request still uses the old aborted signal, so that server fails and is added to the new connection epoch's failed-server set. Reusing the adapter subsequently skips this otherwise healthy server.

Expected: the cancelled discovery rejects without connecting to remaining servers; a later discovery can load every configured healthy server.

Actual: another connection is created after close completes, and later discovery only returns the first server's tools.

Example Code

Add this test under libs/langchain-mcp-adapters/src/tests/ on the commit above and run it with the package's Vitest command. It loads the real adapter and connection manager and mocks only SDK connection/discovery methods. No MCP service or API key is required.

typescript
import { afterEach, expect, test, vi } from "vitest";
import { Client } from "@modelcontextprotocol/client";
import { MCPAdapter } from "../client.js";

afterEach(() => vi.restoreAllMocks());

test("cancelled discovery must not restart servers after close", async () => {
  const connect = vi.spyOn(Client.prototype, "connect").mockResolvedValue();
  vi.spyOn(Client.prototype, "close").mockResolvedValue();
  vi.spyOn(Client.prototype, "listTools")
    .mockRejectedValueOnce(new Error("discovery failed"))
    .mockImplementation(async (_params, options) => {
      options?.signal?.throwIfAborted();
      return { tools: [{ name: "echo", inputSchema: { type: "object" } }] };
    });

  let startHandler = () => {};
  const handling = new Promise<void>((resolve) => { startHandler = resolve; });
  let releaseHandler = () => {};
  const held = new Promise<void>((resolve) => { releaseHandler = resolve; });
  const server = { mode: "legacy" as const, url: "https://example.com/mcp" };
  const adapter = new MCPAdapter({
    servers: { first: server, second: server },
    prefixToolNameWithServerName: true,
    onConnectionError: async () => { startHandler(); await held; },
  });

  const discovery = adapter.listTools();
  const rejected = expect(discovery).rejects.toThrow(/closed during discovery/);
  try {
    await handling;
    await adapter.close();
    releaseHandler();
    await rejected;
    expect.soft(connect).toHaveBeenCalledTimes(1); // Actual: 2
    expect((await adapter.listTools()).map((tool) => tool.name)).toEqual([
      "first__echo", "second__echo", // Actual: only first__echo
    ]);
  } finally {
    releaseHandler();
    await adapter.close();
  }
});

Cause

#discoverToolsets() checks the epoch signal only after its server loop. Its error policy can swallow a request's cancellation or await a callback while close() clears the connection identities and resets #failedServers. Continuing the loop afterwards creates identities belonging to the reusable adapter, then stores failures caused by the previous epoch's cancelled signal.

The existing lifecycle tests cover cancellation and reuse with a single server, which does not exercise this continuation to a second server.

System Info

  • macOS, Node 24.18.0, pnpm 10.14.0
  • Repository main: 5d509ad4b8a5ed9dd4b83020b4c103ac8a69859c
  • @modelcontextprotocol/client / @modelcontextprotocol/core: 2.0.0
  • @langchain/core: repository workspace
  • @langchain/langgraph: 1.4.13

I checked open issues/PRs and the current MCP changes in #11720, #11721 and #11727; I did not find this cancellation fix.

Source: langchain-ai/langchainjs