Skip to content

[v2] After client.close(), listTools() and the other list methods resolve empty instead of rejecting "Not connected" #3195

Open

Description

@prkomb

Since #2286, Client.close() ends with _resetConnectionState(), which sets _serverCapabilities to undefined. The four capability-lenient list methods in packages/client/src/client/client.ts (listTools, listPrompts, listResources, listResourceTemplates) short-circuit when _serverCapabilities lacks the capability, so on a closed client they now resolve with an empty list instead of rejecting with "Not connected". Other requests still reject: ping() after close() gives "Not connected". Before #2286 nothing cleared _serverCapabilities, so for a capability the server had advertised these calls went on to request() and rejected.

So code that lists tools after it closed the client gets { tools: [] } and no error; nothing is sent, and only a console.debug line says why.

The e2e suite checks this case but can't see it fail. typescript:protocol:error:not-connected asserts the after-close rejection (the afterClose check in test/e2e/scenarios/protocol.test.ts), but its knownFailures entry covers the whole requirement because of the before-connect case, and its note says "the after-close rejection still behaves as required". With the three before-connect lines skipped and the entry removed, all 12 cells fail at the after-close check with:

AssertionError: promise resolved "{ tools: [] }" instead of rejecting
Reproduction

Save as repro.mjs in the repository root after pnpm install && pnpm build:all, then run node repro.mjs.

// node repro.mjs: the client; it spawns itself as a stdio server.
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import { Server } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';

if (process.argv[2] === 'server') {
    const server = new Server({ name: 'server', version: '0' }, { capabilities: { tools: {}, prompts: {}, resources: {} } });
    server.setRequestHandler('tools/list', () => ({ tools: [{ name: 'echo', inputSchema: { type: 'object' } }] }));
    server.setRequestHandler('prompts/list', () => ({ prompts: [{ name: 'greet' }] }));
    server.setRequestHandler('resources/list', () => ({ resources: [{ uri: 'file:///a.txt', name: 'a' }] }));
    server.setRequestHandler('resources/templates/list', () => ({ resourceTemplates: [{ uriTemplate: 'file:///{name}', name: 't' }] }));
    await server.connect(new StdioServerTransport());
} else {
    const client = new Client({ name: 'repro', version: '0' });
    const lists = {
        listTools: r => r.tools,
        listPrompts: r => r.prompts,
        listResources: r => r.resources,
        listResourceTemplates: r => r.resourceTemplates
    };
    const show = async label => {
        for (const [method, items] of Object.entries(lists)) {
            try {
                console.log(`${label} ${method}: resolved with ${items(await client[method]()).length} item(s)`);
            } catch (error) {
                console.log(`${label} ${method}: rejected: ${error.message}`);
            }
        }
    };
    await client.connect(new StdioClientTransport({ command: process.execPath, args: [process.argv[1], 'server'] }));
    await show('connected');
    await client.close();
    console.log('closed; client.transport:', client.transport);
    await show('after close()');
    console.log('ping after close():', await client.ping().then(() => 'resolved', e => `rejected: ${e.message}`));
}

Output on main (919bb8e) and on @modelcontextprotocol/client 2.4.0 from npm, Node 26.13.0, with the console.debug lines left out:

connected listTools: resolved with 1 item(s)
connected listPrompts: resolved with 1 item(s)
connected listResources: resolved with 1 item(s)
connected listResourceTemplates: resolved with 1 item(s)
closed; client.transport: undefined
after close() listTools: resolved with 0 item(s)
after close() listPrompts: resolved with 0 item(s)
after close() listResources: resolved with 0 item(s)
after close() listResourceTemplates: resolved with 0 item(s)
ping after close(): rejected: Not connected

When the transport closes on its own (the server exits), close() doesn't run, so a list method for a capability the server advertised still rejects with "Not connected" there.

A small fix would check for a transport before the capability short-circuit in those four methods (if (this.transport && !this._serverCapabilities?.tools && ...)), so a call with no transport goes on to request() and rejects. I tried that locally: with the knownFailures entry removed, all 12 cells of the requirement pass, before-connect check included, and nothing else in the e2e suite changes (3,150 passed and 129 expected failures, against 3,138 and 141 on main), and the client unit tests pass. It also makes the before-connect case reject, which the note calls a change in v2. If the empty result before connect() is meant to stay, the check has to tell "never connected" from "closed" instead. Which would you prefer? Happy to send the PR.

Activity

  1. robertwmccarty commented on Nov 17, 2026

    @robertwmccarty

    One additional edge case for the proposed connection guard, from an independent pinned-source test on 919bb8ea88b6e10e72c2f8b6218fad4cfdc40b2c:

    Changing the lenient-capability branch to if (this.transport && !this._serverCapabilities?.tools ...) fixes the normal after-close repro, but a disconnected client can still reach _serveFromCache() before it reaches request(). The SDK deliberately retains caller-supplied ResponseCacheStore entries across resets. A synthetically seeded fresh tools/list entry under the pre-connect identity partition (JSON.stringify(['', ''])) can therefore make listTools() resolve a stale tool list while client.transport === undefined. This is a defensive negative test; it does not assert that an ordinary connected session writes that sentinel entry.

    The simpler fail-closed guard is to check connection at the start of each of the four list methods, before both the capability short-circuit and the cache lookup:

    if (!this.transport) throw new Error('Not connected');
    if (!this._serverCapabilities?.tools && !this._enforceStrictCapabilities) {
        return { tools: [] };
    }

    Our candidate tests cover before-connect, connected/no advertised capability, after-close, explicit-cursor calls and the seeded external-cache case. The refined candidate passed the full affected client Vitest suite, relevant typechecks/lint and the workspace build. This would intentionally make pre-connect calls reject, as the issue's conformance check expects; maintainer confirmation of that behavioral choice remains important. No unrelated feature or public API is needed.

  2. A7mdMe commented on Nov 18, 2026

    @A7mdMe

    Strongly agree with @robertwmccarty-caelum and @prkomb on enforcing fail-closed checks before both capability short-circuits and cache lookups.

    Why Silent Empty Resolution Breaks Agent Reasoning

    In production AI agent architectures (Claude Desktop, Cursor, orchestrators, and autonomous loops), this silent { tools: [] } resolution on disconnected/closed clients creates a subtle failure mode:

    1. When a server restarts, crashes, or is torn down, the client enters a disconnected state.
    2. The agent reasoning loop polls or invokes listTools().
    3. Instead of catching Not connected (which would trigger retry, health alert, or automated reconnection), the agent receives a successful { tools: [] }.
    4. The model concludes that the tool never existed or has been removed by the user, leading to hallucinated explanations ("I don't have access to this tool") rather than initiating a reconnection flow.

    Upstream Fix in packages/client/src/client/client.ts

    The fail-closed invariant should be evaluated at the top of each discovery method (listTools, listPrompts, listResources, listResourceTemplates), preceding both the capability short-circuit and any response cache read:

    if (!this.transport) {
      throw new Error('Not connected');
    }
    
    // Only evaluate capability short-circuits once an active transport is verified
    if (!this._serverCapabilities?.tools && !this._enforceStrictCapabilities) {
      return { tools: [] };
    }

    This cleanly resolves the external cache retention vector noted by @robertwmccarty-caelum as well: cached entries are never read while the transport is dead.

    Drop-in Client Wrapper (For Production Agent Runners Today)

    For applications running in production today before the upstream patch lands, you can wrap the client to enforce fail-closed discovery invariants across all four list methods:

    import { Client } from '@modelcontextprotocol/sdk/client/index.js';
    
    export function wrapClientWithSessionGuard<T extends Client>(client: T): T {
      const methods = ['listTools', 'listPrompts', 'listResources', 'listResourceTemplates'] as const;
    
      for (const method of methods) {
        const original = (client as any)[method]?.bind(client);
        if (!original) continue;
    
        (client as any)[method] = async (params?: unknown) => {
          // Fail-closed invariant: Disallow capability short-circuits & cache lookups on dead connections
          if (!client.transport) {
            throw new Error('Not connected');
          }
          return await original(params);
        };
      }
    
      return client;
    }
    
    // Usage:
    const client = wrapClientWithSessionGuard(new Client({ name: 'my-agent', version: '1.0.0' }));
    await client.connect(transport);
    
    // While connected: returns real tools
    console.log(await client.listTools());
    
    // After close: strictly throws "Not connected" instead of returning { tools: [] }
    await client.close();
    try {
      await client.listTools();
    } catch (err) {
      console.log('Caught disconnected state cleanly:', err.message); // Not connected
    }

    Looking forward to seeing @prkomb's PR land.


    Disclosure: I maintain MCP Production Kit, an open-source kit and commercial suite providing fail-closed session invariants, monotonic epoch fencing, and slowloris lifecycle guards for production MCP servers and clients.

  3. added
    v2
    on Nov 18, 2026
  4. robertwmccarty commented on Nov 19, 2026

    @robertwmccarty

    Independent reproduction request for #3195, with a bounded acceptance matrix rather than another implementation claim:

    • Never connected: listTools, listPrompts, listResources, and listResourceTemplates each reject with Not connected.
    • Disconnected after close(): same four methods reject, including when capability negotiation was lenient and the server never advertised the respective capability.
    • External cache negative: seed a fresh response in a caller-supplied ResponseCacheStore under the pre-connection partition; a disconnected listTools() must still reject, not serve a cached list.
    • Positive controls: a connected client can still list advertised capabilities; a connected client without an advertised capability retains its documented lenient behavior; explicit cursor calls stay per-page.

    A useful report is pinned SDK commit + transport/Node version + exact command + observed output for both a negative and a connected positive control. In particular, distinguish a test fixture's intentionally seeded cache from a cache entry written by a normal session.

    We published a voluntary, no-signup reproduction worksheet covering this and three adjacent agent-infrastructure issues: https://linkedais-lab-bertday.vercel.app/ . The worksheet is not an upstream standard, an SDK release, or evidence that anyone independently reproduced the issue. Results should be posted here or in an inspectable public regression; maintainers retain all acceptance decisions.

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

    v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions