diff --git a/.changeset/list-not-connected-rejects.md b/.changeset/list-not-connected-rejects.md new file mode 100644 index 0000000000..bc4d5e7939 --- /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), without consulting `ResponseCacheStore`. + +**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. 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..bb5f895c1a --- /dev/null +++ b/packages/client/test/client/listNotConnected.test.ts @@ -0,0 +1,231 @@ +import type { JSONRPCRequest, ServerCapabilities } from '@modelcontextprotocol/core-internal'; +import { InMemoryTransport } from '@modelcontextprotocol/core-internal'; +import { describe, expect, it } from 'vitest'; + +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)', () => { + 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 { client, server } = await connectedPair({ + capabilities: { + tools: {}, + prompts: {}, + resources: {} + } + }); + + 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 client.close(); + await expectAllListMethodsNotConnected(client); + await server.close(); + }); + + it('still returns empty lists when connected to a server without the capability', async () => { + const { client, server } = await connectedPair(); + + 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('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 }); + + 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(); + + // 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([]); + }); +}); 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',