From c1e00529bb39b0fcc246d1ad55ea14bb3feee721 Mon Sep 17 00:00:00 2001 From: Muzaqil Hesenli Date: Wed, 18 Nov 2026 08:08:50 +0400 Subject: [PATCH 1/3] fix(client): forward listTools/listPrompts/listResources when not connected --- packages/client/src/client/client.ts | 12 +++ .../test/client/listNotConnected.test.ts | 74 +++++++++++++++++++ test/e2e/requirements.ts | 7 +- 3 files changed, 87 insertions(+), 6 deletions(-) create mode 100644 packages/client/test/client/listNotConnected.test.ts diff --git a/packages/client/src/client/client.ts b/packages/client/src/client/client.ts index f071b13e50..f06ad0a832 100644 --- a/packages/client/src/client/client.ts +++ b/packages/client/src/client/client.ts @@ -1629,6 +1629,9 @@ export class Client extends Protocol { * ``` */ async listPrompts(params?: ListPromptsRequest['params'], options?: CacheableRequestOptions): Promise { + if (!this.transport) { + return this.request({ method: 'prompts/list', params }, options); + } if (!this._serverCapabilities?.prompts && !this._enforceStrictCapabilities) { // Respect capability negotiation: server does not support prompts console.debug('Client.listPrompts() called but server does not advertise prompts capability - returning empty list'); @@ -1669,6 +1672,9 @@ export class Client extends Protocol { * ``` */ async listResources(params?: ListResourcesRequest['params'], options?: CacheableRequestOptions): Promise { + if (!this.transport) { + return this.request({ method: 'resources/list', params }, options); + } if (!this._serverCapabilities?.resources && !this._enforceStrictCapabilities) { // Respect capability negotiation: server does not support resources console.debug('Client.listResources() called but server does not advertise resources capability - returning empty list'); @@ -1698,6 +1704,9 @@ export class Client extends Protocol { params?: ListResourceTemplatesRequest['params'], options?: CacheableRequestOptions ): Promise { + if (!this.transport) { + return this.request({ method: 'resources/templates/list', params }, options); + } if (!this._serverCapabilities?.resources && !this._enforceStrictCapabilities) { // Respect capability negotiation: server does not support resources console.debug( @@ -2557,6 +2566,9 @@ export class Client extends Protocol { * ``` */ async listTools(params?: ListToolsRequest['params'], options?: CacheableRequestOptions): Promise { + if (!this.transport) { + return this.request({ method: 'tools/list', params }, options); + } if (!this._serverCapabilities?.tools && !this._enforceStrictCapabilities) { // Respect capability negotiation: server does not support tools console.debug('Client.listTools() called but server does not advertise tools capability - returning empty list'); diff --git a/packages/client/test/client/listNotConnected.test.ts b/packages/client/test/client/listNotConnected.test.ts new file mode 100644 index 0000000000..8e674511c0 --- /dev/null +++ b/packages/client/test/client/listNotConnected.test.ts @@ -0,0 +1,74 @@ +import { InMemoryTransport } from '@modelcontextprotocol/core-internal'; +import { McpServer } from '@modelcontextprotocol/server'; +import { describe, expect, it } from 'vitest'; + +import { Client } from '../../src/client/client.js'; +import { InMemoryResponseCacheStore } from '../../src/client/responseCache.js'; + +function createConnectedPair(capabilities?: { + tools?: Record; + prompts?: Record; + resources?: Record; +}) { + const server = new McpServer({ name: 'test-server', version: '1.0.0' }, capabilities ? { capabilities } : undefined); + const client = new Client({ name: 'test-client', version: '1.0.0' }); + return { server, client }; +} + +describe('Client list methods when disconnected (#3195)', () => { + it('rejects all four capability-lenient list methods before connect', async () => { + const client = new Client({ name: 'test-client', version: '1.0.0' }); + + await expect(client.listTools()).rejects.toThrow('Not connected'); + await expect(client.listPrompts()).rejects.toThrow('Not connected'); + await expect(client.listResources()).rejects.toThrow('Not connected'); + await expect(client.listResourceTemplates()).rejects.toThrow('Not connected'); + }); + + it('rejects all four list methods with Not connected after close()', async () => { + const { server, client } = createConnectedPair({ + tools: {}, + prompts: {}, + resources: {} + }); + const [clientTx, serverTx] = InMemoryTransport.createLinkedPair(); + await Promise.all([server.connect(serverTx), client.connect(clientTx)]); + + await expect(client.listTools()).resolves.toEqual({ tools: [] }); + await client.close(); + + await expect(client.listTools()).rejects.toMatchObject({ message: 'Not connected' }); + await expect(client.listPrompts()).rejects.toMatchObject({ message: 'Not connected' }); + await expect(client.listResources()).rejects.toMatchObject({ message: 'Not connected' }); + await expect(client.listResourceTemplates()).rejects.toMatchObject({ message: 'Not connected' }); + await server.close(); + }); + + it('still returns empty lists when connected to a server without the capability', async () => { + const { server, client } = createConnectedPair(); + const [clientTx, serverTx] = InMemoryTransport.createLinkedPair(); + await Promise.all([server.connect(serverTx), client.connect(clientTx)]); + + await expect(client.listTools()).resolves.toEqual({ tools: [] }); + await expect(client.listPrompts()).resolves.toEqual({ prompts: [] }); + await expect(client.listResources()).resolves.toEqual({ resources: [] }); + await expect(client.listResourceTemplates()).resolves.toEqual({ resourceTemplates: [] }); + + await client.close(); + await server.close(); + }); + + it('does not serve from a persistent cache store after close()', async () => { + const store = new InMemoryResponseCacheStore(); + const server = new McpServer({ name: 'cached-server', version: '1.0.0' }, { capabilities: { tools: {} } }); + const client = new Client({ name: 'cached-client', version: '1.0.0' }, { responseCacheStore: store }); + const [clientTx, serverTx] = InMemoryTransport.createLinkedPair(); + await Promise.all([server.connect(serverTx), client.connect(clientTx)]); + + await expect(client.listTools()).resolves.toEqual({ tools: [] }); + await client.close(); + + await expect(client.listTools()).rejects.toMatchObject({ message: 'Not connected' }); + await server.close(); + }); +}); diff --git a/test/e2e/requirements.ts b/test/e2e/requirements.ts index d26f6524d2..5f28eced70 100644 --- a/test/e2e/requirements.ts +++ b/test/e2e/requirements.ts @@ -3019,12 +3019,7 @@ export const REQUIREMENTS: Record = { 'typescript:protocol:error:not-connected': { source: 'sdk', behavior: - "Calling a request method on a Client whose transport is closed or never connected rejects with an Error containing 'Not connected', and client.transport is undefined before connect and after close.", - knownFailures: [ - { - note: "changed in v2: capability-lenient list methods resolve with an empty result before connect instead of rejecting 'Not connected'; the after-close rejection still behaves as required." - } - ] + "Calling a request method on a Client whose transport is closed or never connected rejects with an Error containing 'Not connected', and client.transport is undefined before connect and after close." }, 'typescript:client-transport:http:session-id-property': { source: 'sdk', From 367b706272ad02844d47536b2e11deb47ab7b0ce Mon Sep 17 00:00:00 2001 From: Muzaqil Hesenli Date: Thu, 19 Nov 2026 08:46:52 +0400 Subject: [PATCH 2/3] test(client): remove server import, pin cache ordering, add changeset --- .changeset/list-not-connected-rejects.md | 7 + .../test/client/listNotConnected.test.ts | 225 +++++++++++++++--- 2 files changed, 198 insertions(+), 34 deletions(-) create mode 100644 .changeset/list-not-connected-rejects.md diff --git a/.changeset/list-not-connected-rejects.md b/.changeset/list-not-connected-rejects.md new file mode 100644 index 0000000000..aa63b1f43b --- /dev/null +++ b/.changeset/list-not-connected-rejects.md @@ -0,0 +1,7 @@ +--- +'@modelcontextprotocol/client': patch +--- + +`Client.listTools()`, `Client.listPrompts()`, `Client.listResources()`, and `Client.listResourceTemplates()` now reject with `Error('Not connected')` when `client.transport` is `undefined` (before `connect()`, after `close()`, or after the transport closes), matching all other `Client` request methods and without consulting `ResponseCacheStore`. + +**Breaking change:** Previously, calling these four methods while disconnected fell into the missing-capability leniency path and resolved with an empty list (`{ tools: [] }`, `{ prompts: [] }`, `{ resources: [] }`, `{ resourceTemplates: [] }`) instead of rejecting. Callers that await `listTools()`, `listPrompts()`, `listResources()`, or `listResourceTemplates()` before `connect()` or after `close()` without handling errors will now reject with `Not connected`. Calling them on an active connection against a server that does not advertise the corresponding capability still returns an empty list unless `enforceStrictCapabilities` is enabled. diff --git a/packages/client/test/client/listNotConnected.test.ts b/packages/client/test/client/listNotConnected.test.ts index 8e674511c0..bb5f895c1a 100644 --- a/packages/client/test/client/listNotConnected.test.ts +++ b/packages/client/test/client/listNotConnected.test.ts @@ -1,18 +1,113 @@ +import type { JSONRPCRequest, ServerCapabilities } from '@modelcontextprotocol/core-internal'; import { InMemoryTransport } from '@modelcontextprotocol/core-internal'; -import { McpServer } from '@modelcontextprotocol/server'; import { describe, expect, it } from 'vitest'; -import { Client } from '../../src/client/client.js'; -import { InMemoryResponseCacheStore } from '../../src/client/responseCache.js'; - -function createConnectedPair(capabilities?: { - tools?: Record; - prompts?: Record; - resources?: Record; -}) { - const server = new McpServer({ name: 'test-server', version: '1.0.0' }, capabilities ? { capabilities } : undefined); - const client = new Client({ name: 'test-client', version: '1.0.0' }); - return { server, client }; +import { Client } from '../../src/client/client'; +import type { CacheKey, ResponseCacheStore } from '../../src/client/responseCache'; +import { InMemoryResponseCacheStore } from '../../src/client/responseCache'; + +const MODERN = '2026-07-28'; +const LEGACY = '2025-11-25'; +const PRE_CONNECT_PARTITION = JSON.stringify(['', '']); + +const LIST_RESULTS: Record> = { + 'tools/list': { tools: [{ name: 'echo', inputSchema: { type: 'object' } }] }, + 'prompts/list': { prompts: [{ name: 'greet' }] }, + 'resources/list': { resources: [{ uri: 'file:///a', name: 'a' }] }, + 'resources/templates/list': { resourceTemplates: [{ uriTemplate: 'file:///{name}', name: 'tmpl' }] } +}; + +interface PairOptions { + capabilities?: ServerCapabilities; + listTtlMs?: number; + modern?: boolean; + responseCacheStore?: ResponseCacheStore; +} + +async function connectedPair(opts: PairOptions = {}) { + const [clientTx, serverTx] = InMemoryTransport.createLinkedPair(); + const wireCounts = new Map(); + const capabilities = opts.capabilities ?? {}; + const modern = opts.modern ?? false; + + serverTx.onmessage = m => { + const r = m as JSONRPCRequest; + if (r.id === undefined) return; + wireCounts.set(r.method, (wireCounts.get(r.method) ?? 0) + 1); + + if (r.method === 'server/discover') { + void serverTx.send({ + jsonrpc: '2.0', + id: r.id, + result: { + resultType: 'complete', + supportedVersions: [MODERN], + capabilities, + _meta: { 'io.modelcontextprotocol/serverInfo': { name: 'scripted', version: '1.0.0' } } + } + }); + } else if (r.method === 'initialize') { + void serverTx.send({ + jsonrpc: '2.0', + id: r.id, + result: { + protocolVersion: LEGACY, + capabilities, + serverInfo: { name: 'scripted', version: '1.0.0' } + } + }); + } else if (Object.hasOwn(LIST_RESULTS, r.method)) { + const modernMeta = modern ? { resultType: 'complete', ttlMs: opts.listTtlMs ?? 0, cacheScope: 'public' } : {}; + void serverTx.send({ + jsonrpc: '2.0', + id: r.id, + result: { ...modernMeta, ...LIST_RESULTS[r.method] } + }); + } + }; + + await serverTx.start(); + const client = new Client( + { name: 'test-client', version: '1.0.0' }, + { + ...(modern && { versionNegotiation: { mode: { pin: MODERN } } }), + ...(opts.responseCacheStore && { responseCacheStore: opts.responseCacheStore }) + } + ); + await client.connect(clientTx); + const server = { close: () => serverTx.close() }; + return { client, server, wireCount: (method: string) => wireCounts.get(method) ?? 0 }; +} + +function createSpyCacheStore() { + const store = new InMemoryResponseCacheStore(); + const getCalls: CacheKey[] = []; + const realGet = store.get.bind(store); + (store as ResponseCacheStore).get = key => { + getCalls.push(key); + return realGet(key); + }; + return { store, getCalls }; +} + +function seedFreshListEntries(store: InMemoryResponseCacheStore, partition: string): void { + const expiresAt = Date.now() + 60_000; + const entries: Array<[string, Record]> = [ + ['tools/list', { tools: [{ name: 'cached-tool', inputSchema: { type: 'object' } }] }], + ['prompts/list', { prompts: [{ name: 'cached-prompt' }] }], + ['resources/list', { resources: [{ uri: 'file:///cached', name: 'cached' }] }], + ['resources/templates/list', { resourceTemplates: [{ uriTemplate: 'file:///{cached}', name: 'cached' }] }] + ]; + for (const [method, payload] of entries) { + store.set({ method, params: '', partition }, { value: JSON.stringify(payload), expiresAt, scope: 'public' }); + } +} + +async function expectAllListMethodsNotConnected(client: Client): Promise { + await expect(client.listTools()).rejects.toMatchObject({ message: 'Not connected' }); + await expect(client.listPrompts()).rejects.toMatchObject({ message: 'Not connected' }); + await expect(client.listResources()).rejects.toMatchObject({ message: 'Not connected' }); + await expect(client.listResourceTemplates()).rejects.toMatchObject({ message: 'Not connected' }); } describe('Client list methods when disconnected (#3195)', () => { @@ -26,28 +121,26 @@ describe('Client list methods when disconnected (#3195)', () => { }); it('rejects all four list methods with Not connected after close()', async () => { - const { server, client } = createConnectedPair({ - tools: {}, - prompts: {}, - resources: {} + const { client, server } = await connectedPair({ + capabilities: { + tools: {}, + prompts: {}, + resources: {} + } }); - const [clientTx, serverTx] = InMemoryTransport.createLinkedPair(); - await Promise.all([server.connect(serverTx), client.connect(clientTx)]); - await expect(client.listTools()).resolves.toEqual({ tools: [] }); - await client.close(); + await expect(client.listTools()).resolves.toMatchObject({ tools: [{ name: 'echo' }] }); + await expect(client.listPrompts()).resolves.toMatchObject({ prompts: [{ name: 'greet' }] }); + await expect(client.listResources()).resolves.toMatchObject({ resources: [{ name: 'a' }] }); + await expect(client.listResourceTemplates()).resolves.toMatchObject({ resourceTemplates: [{ name: 'tmpl' }] }); - await expect(client.listTools()).rejects.toMatchObject({ message: 'Not connected' }); - await expect(client.listPrompts()).rejects.toMatchObject({ message: 'Not connected' }); - await expect(client.listResources()).rejects.toMatchObject({ message: 'Not connected' }); - await expect(client.listResourceTemplates()).rejects.toMatchObject({ message: 'Not connected' }); + await client.close(); + await expectAllListMethodsNotConnected(client); await server.close(); }); it('still returns empty lists when connected to a server without the capability', async () => { - const { server, client } = createConnectedPair(); - const [clientTx, serverTx] = InMemoryTransport.createLinkedPair(); - await Promise.all([server.connect(serverTx), client.connect(clientTx)]); + const { client, server } = await connectedPair(); await expect(client.listTools()).resolves.toEqual({ tools: [] }); await expect(client.listPrompts()).resolves.toEqual({ prompts: [] }); @@ -58,17 +151,81 @@ describe('Client list methods when disconnected (#3195)', () => { await server.close(); }); - it('does not serve from a persistent cache store after close()', async () => { - const store = new InMemoryResponseCacheStore(); - const server = new McpServer({ name: 'cached-server', version: '1.0.0' }, { capabilities: { tools: {} } }); + it('fails with Not connected before consulting responseCacheStore before connect()', async () => { + const { store, getCalls } = createSpyCacheStore(); + seedFreshListEntries(store, PRE_CONNECT_PARTITION); const client = new Client({ name: 'cached-client', version: '1.0.0' }, { responseCacheStore: store }); - const [clientTx, serverTx] = InMemoryTransport.createLinkedPair(); - await Promise.all([server.connect(serverTx), client.connect(clientTx)]); - await expect(client.listTools()).resolves.toEqual({ tools: [] }); + await expectAllListMethodsNotConnected(client); + expect(getCalls).toEqual([]); + }); + + it('fails with Not connected before consulting responseCacheStore after close()', async () => { + const { store, getCalls } = createSpyCacheStore(); + const { client, server, wireCount } = await connectedPair({ + modern: true, + listTtlMs: 60_000, + capabilities: { + tools: {}, + prompts: {}, + resources: {} + }, + responseCacheStore: store + }); + + await client.listTools(); + await client.listPrompts(); + await client.listResources(); + await client.listResourceTemplates(); + + // Confirm all four list verbs are actively served from cache while connected. + await client.listTools(); + await client.listPrompts(); + await client.listResources(); + await client.listResourceTemplates(); + expect(wireCount('tools/list')).toBe(1); + expect(wireCount('prompts/list')).toBe(1); + expect(wireCount('resources/list')).toBe(1); + expect(wireCount('resources/templates/list')).toBe(1); + await client.close(); - await expect(client.listTools()).rejects.toMatchObject({ message: 'Not connected' }); + // Seed the pre-connect/post-reset sentinel partition as well: close() calls + // resetForReconnect() (clearing server identity to ''), so without this and + // the store.get spy a cache lookup before the transport check would miss on + // the server partition and mask an ordering regression. + seedFreshListEntries(store, PRE_CONNECT_PARTITION); + getCalls.length = 0; + + await expectAllListMethodsNotConnected(client); + expect(getCalls).toEqual([]); + await server.close(); + }); + + it('fails with Not connected before consulting responseCacheStore after remote transport close', async () => { + const { store, getCalls } = createSpyCacheStore(); + const { client, server } = await connectedPair({ + modern: true, + listTtlMs: 60_000, + capabilities: { + tools: {}, + prompts: {}, + resources: {} + }, + responseCacheStore: store + }); + + await client.listTools(); + await client.listPrompts(); + await client.listResources(); + await client.listResourceTemplates(); + + // Remote close clears client.transport via _onclose() without running + // resetForReconnect(), leaving the server's cached entries addressable. await server.close(); + getCalls.length = 0; + + await expectAllListMethodsNotConnected(client); + expect(getCalls).toEqual([]); }); }); From 740550061d6c2527763b6b161cabd624a2fc0a27 Mon Sep 17 00:00:00 2001 From: Muzaqil Hesenli Date: Fri, 20 Nov 2026 08:14:33 +0400 Subject: [PATCH 3/3] docs(changeset): narrow disconnected listTools description --- .changeset/list-not-connected-rejects.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/list-not-connected-rejects.md b/.changeset/list-not-connected-rejects.md index aa63b1f43b..bc4d5e7939 100644 --- a/.changeset/list-not-connected-rejects.md +++ b/.changeset/list-not-connected-rejects.md @@ -2,6 +2,6 @@ '@modelcontextprotocol/client': patch --- -`Client.listTools()`, `Client.listPrompts()`, `Client.listResources()`, and `Client.listResourceTemplates()` now reject with `Error('Not connected')` when `client.transport` is `undefined` (before `connect()`, after `close()`, or after the transport closes), matching all other `Client` request methods and without consulting `ResponseCacheStore`. +`Client.listTools()`, `Client.listPrompts()`, `Client.listResources()`, and `Client.listResourceTemplates()` now reject with `Error('Not connected')` when `client.transport` is `undefined` (before `connect()`, after `close()`, or after the transport closes), without consulting `ResponseCacheStore`. -**Breaking change:** Previously, calling these four methods while disconnected fell into the missing-capability leniency path and resolved with an empty list (`{ tools: [] }`, `{ prompts: [] }`, `{ resources: [] }`, `{ resourceTemplates: [] }`) instead of rejecting. Callers that await `listTools()`, `listPrompts()`, `listResources()`, or `listResourceTemplates()` before `connect()` or after `close()` without handling errors will now reject with `Not connected`. Calling them on an active connection against a server that does not advertise the corresponding capability still returns an empty list unless `enforceStrictCapabilities` is enabled. +**Breaking change:** Previously, calling these four methods before `connect()` or after `close()` fell into the missing-capability leniency path and resolved with an empty list (`{ tools: [] }`, `{ prompts: [] }`, `{ resources: [] }`, `{ resourceTemplates: [] }`) instead of rejecting (and after a server-side transport close, an unexpired cached list could still be returned). Callers that await `listTools()`, `listPrompts()`, `listResources()`, or `listResourceTemplates()` while disconnected without handling errors will now reject with `Not connected`. Calling them on an active connection against a server that does not advertise the corresponding capability still returns an empty list unless `enforceStrictCapabilities` is enabled.