@tsed/platform-mcp 8.45.0 → 8.45.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import type {Client, Prompt, Resource, ResourceTemplateType, Tool} from "@modelc
3
3
  import {constant, injectable, logger, type OnDestroy} from "@tsed/di";
4
4
  import type {PlatformMcpUpstreamSettings} from "../interfaces/PlatformMcpUpstreamSettings.js";
5
5
  import {createUpstreamTransport} from "../utils/createUpstreamTransport.js";
6
+ import {isUpstreamSessionLost} from "../utils/isUpstreamSessionLost.js";
6
7
  import {listAll} from "../utils/listAll.js";
7
8
 
8
9
  const DEFAULT_POOL_MAX = 100;
@@ -30,9 +31,19 @@ export interface PlatformMcpUpstreamConnection {
30
31
  client: Client;
31
32
  getCatalog(): Promise<PlatformMcpUpstreamCatalog>;
32
33
  /**
33
- * Runs an upstream request, keeping the connection out of the pool eviction while it is pending.
34
+ * Runs an upstream request with the client given to `fn`, keeping the connection out of the pool eviction while
35
+ * it is pending. When the upstream lost the session of the connection, the request is replayed once on a new
36
+ * connection: `fn` must send the request with the client it is given.
34
37
  */
35
- run<T>(fn: () => Promise<T>): Promise<T>;
38
+ run<T>(fn: (client: Client) => Promise<T>): Promise<T>;
39
+ }
40
+
41
+ /**
42
+ * Requests running on a client, and whether it was replaced: it is closed once they are done.
43
+ */
44
+ interface ClientState {
45
+ running: number;
46
+ retired: boolean;
36
47
  }
37
48
 
38
49
  interface PoolEntry {
@@ -55,6 +66,7 @@ interface PoolEntry {
55
66
  */
56
67
  export class PlatformMcpGatewayService implements OnDestroy {
57
68
  protected pools = new Map<PlatformMcpUpstreamSettings, Map<string, PoolEntry>>();
69
+ protected clients = new WeakMap<Client, ClientState>();
58
70
 
59
71
  /**
60
72
  * Returns the connection matching the resolved upstream definition, connecting lazily.
@@ -66,6 +78,57 @@ export class PlatformMcpGatewayService implements OnDestroy {
66
78
  upstream: PlatformMcpUpstreamSettings,
67
79
  resolved: PlatformMcpUpstreamSettings = upstream
68
80
  ): Promise<PlatformMcpUpstreamConnection> {
81
+ return this.acquire(upstream, resolved).connection;
82
+ }
83
+
84
+ /**
85
+ * Replaces a connection whose session the upstream lost, then returns the connection to use.
86
+ *
87
+ * The connection is replaced only while it is still the current one: the requests failing together share the
88
+ * connection opened by the first of them. Its client is closed once its running requests are done: closing it
89
+ * earlier would abort requests the upstream may have handled, which could then not be replayed safely.
90
+ *
91
+ * @param upstream Upstream declared in the configuration, identifying the pool.
92
+ * @param resolved Same definition with its placeholders interpolated for the caller.
93
+ * @param stale Connection whose session was lost.
94
+ */
95
+ async reconnect(
96
+ upstream: PlatformMcpUpstreamSettings,
97
+ resolved: PlatformMcpUpstreamSettings,
98
+ stale: Pick<PlatformMcpUpstreamConnection, "client">
99
+ ): Promise<PlatformMcpUpstreamConnection> {
100
+ const entry = this.getPool(upstream).get(this.getKey(resolved));
101
+
102
+ if (entry?.client === stale.client) {
103
+ logger().warn({
104
+ event: "MCP_GATEWAY_SESSION_LOST",
105
+ message: `MCP upstream "${this.getLabel(resolved)}": the upstream lost the session, reconnecting.`
106
+ });
107
+
108
+ entry.client = undefined;
109
+ entry.connection = undefined;
110
+
111
+ await this.retire(stale.client);
112
+ }
113
+
114
+ return this.getConnection(upstream, resolved);
115
+ }
116
+
117
+ async $onDestroy() {
118
+ const entries = [...this.pools.values()].flatMap((pool) => [...pool.values()]);
119
+
120
+ this.pools.clear();
121
+
122
+ await Promise.all(entries.map((entry) => this.close(entry)));
123
+ }
124
+
125
+ /**
126
+ * Returns the pool entry matching the resolved upstream definition and its connection, connecting lazily.
127
+ */
128
+ protected acquire(
129
+ upstream: PlatformMcpUpstreamSettings,
130
+ resolved: PlatformMcpUpstreamSettings
131
+ ): {entry: PoolEntry; connection: Promise<PlatformMcpUpstreamConnection>} {
69
132
  const pool = this.getPool(upstream);
70
133
  const key = this.getKey(resolved);
71
134
  const now = Date.now();
@@ -81,10 +144,10 @@ export class PlatformMcpGatewayService implements OnDestroy {
81
144
 
82
145
  if (!entry.connection) {
83
146
  if (entry.retryAt > now) {
84
- return Promise.reject(entry.error);
147
+ return {entry, connection: Promise.reject(entry.error)};
85
148
  }
86
149
 
87
- entry.connection = this.connect(resolved, entry).catch((error) => {
150
+ entry.connection = this.connect(upstream, resolved, entry).catch((error) => {
88
151
  entry.connection = undefined;
89
152
  entry.failures++;
90
153
  entry.error = error;
@@ -94,21 +157,17 @@ export class PlatformMcpGatewayService implements OnDestroy {
94
157
  });
95
158
  }
96
159
 
97
- return entry.connection;
98
- }
99
-
100
- async $onDestroy() {
101
- const entries = [...this.pools.values()].flatMap((pool) => [...pool.values()]);
102
-
103
- this.pools.clear();
104
-
105
- await Promise.all(entries.map((entry) => this.close(entry)));
160
+ return {entry, connection: entry.connection};
106
161
  }
107
162
 
108
- protected async connect(upstream: PlatformMcpUpstreamSettings, entry: PoolEntry): Promise<PlatformMcpUpstreamConnection> {
163
+ protected async connect(
164
+ upstream: PlatformMcpUpstreamSettings,
165
+ resolved: PlatformMcpUpstreamSettings,
166
+ entry: PoolEntry
167
+ ): Promise<PlatformMcpUpstreamConnection> {
109
168
  const {Client} = await import("@modelcontextprotocol/client");
110
- const transport = await createUpstreamTransport(upstream);
111
- const label = this.getLabel(upstream);
169
+ const transport = await createUpstreamTransport(resolved);
170
+ const label = this.getLabel(resolved);
112
171
  let catalog: Promise<PlatformMcpUpstreamCatalog> | undefined;
113
172
  const invalidate = () => {
114
173
  catalog = undefined;
@@ -149,8 +208,13 @@ export class PlatformMcpGatewayService implements OnDestroy {
149
208
  return {
150
209
  client,
151
210
  getCatalog: () => {
211
+ if (entry.client !== client) {
212
+ // the connection was replaced (lost session) or closed (eviction) after it was handed out
213
+ return this.getConnection(upstream, resolved).then((current) => current.getCatalog());
214
+ }
215
+
152
216
  if (!catalog) {
153
- const pending: Promise<PlatformMcpUpstreamCatalog> = this.loadCatalog(client, label).then(
217
+ const pending: Promise<PlatformMcpUpstreamCatalog> = this.track(client, () => this.loadCatalog(client, label)).then(
154
218
  ({catalog: loaded, complete}) => {
155
219
  // an incomplete catalog is served once and listed again on the next request
156
220
  if (!complete && catalog === pending) {
@@ -173,19 +237,59 @@ export class PlatformMcpGatewayService implements OnDestroy {
173
237
 
174
238
  return catalog;
175
239
  },
176
- run: async (fn) => {
177
- entry.pending++;
178
-
179
- try {
180
- return await fn();
181
- } finally {
182
- entry.pending--;
183
- entry.lastUsed = Date.now();
184
- }
185
- }
240
+ run: (fn) => this.run(upstream, resolved, entry, client, fn)
186
241
  };
187
242
  }
188
243
 
244
+ /**
245
+ * Runs `fn` with the current client of the entry, and replays it once on a new connection when the upstream
246
+ * lost the session.
247
+ */
248
+ protected async run<T>(
249
+ upstream: PlatformMcpUpstreamSettings,
250
+ resolved: PlatformMcpUpstreamSettings,
251
+ entry: PoolEntry,
252
+ client: Client,
253
+ fn: (client: Client) => Promise<T>,
254
+ replay = true
255
+ ): Promise<T> {
256
+ if (entry.client !== client) {
257
+ // the handler was attached before its connection was replaced (lost session) or closed (eviction)
258
+ const acquired = this.acquire(upstream, resolved);
259
+
260
+ entry = acquired.entry;
261
+ // keeps the entry out of the eviction while it connects
262
+ entry.pending++;
263
+
264
+ try {
265
+ client = (await acquired.connection).client;
266
+ } finally {
267
+ entry.pending--;
268
+ }
269
+ }
270
+
271
+ // the client loses its transport once closed, which can happen as soon as the request is done
272
+ const {transport} = client;
273
+
274
+ entry.pending++;
275
+
276
+ try {
277
+ return await this.track(client, () => fn(client));
278
+ } catch (error) {
279
+ if (!replay || !isUpstreamSessionLost(error, {transport})) {
280
+ throw error;
281
+ }
282
+ } finally {
283
+ entry.pending--;
284
+ entry.lastUsed = Date.now();
285
+ }
286
+
287
+ // the upstream rejected the request without handling it: it can be replayed, once, on a new session
288
+ await this.reconnect(upstream, resolved, {client});
289
+
290
+ return this.run(upstream, resolved, entry, client, fn, false);
291
+ }
292
+
189
293
  /**
190
294
  * Lists every catalog the upstream advertises.
191
295
  *
@@ -195,6 +299,7 @@ export class PlatformMcpGatewayService implements OnDestroy {
195
299
  */
196
300
  protected async loadCatalog(client: Client, label: string): Promise<{catalog: PlatformMcpUpstreamCatalog; complete: boolean}> {
197
301
  const capabilities = client.getServerCapabilities() || {};
302
+ const {transport} = client;
198
303
  const listings = [
199
304
  ["tools", capabilities.tools, (params: {cursor?: string}) => client.listTools(params)],
200
305
  ["resources", capabilities.resources, (params: {cursor?: string}) => client.listResources(params)],
@@ -207,6 +312,12 @@ export class PlatformMcpGatewayService implements OnDestroy {
207
312
  result.status === "rejected" ? [{key: listings[index][0], error: result.reason}] : []
208
313
  );
209
314
  const advertised = listings.filter(([, enabled]) => enabled).length;
315
+ const lost = failures.find(({error}) => isUpstreamSessionLost(error, {transport}));
316
+
317
+ if (lost) {
318
+ // the other listings may have succeeded: the whole catalog is listed again on a new session
319
+ throw lost.error;
320
+ }
210
321
 
211
322
  failures.forEach(({key, error}) => {
212
323
  logger().warn({
@@ -294,12 +405,68 @@ export class PlatformMcpGatewayService implements OnDestroy {
294
405
  }
295
406
  }
296
407
 
408
+ /**
409
+ * Counts the requests running on the client, and closes it after the last one when it was replaced.
410
+ */
411
+ protected async track<T>(client: Client, fn: () => Promise<T>): Promise<T> {
412
+ const state = this.getClientState(client);
413
+
414
+ state.running++;
415
+
416
+ try {
417
+ return await fn();
418
+ } finally {
419
+ state.running--;
420
+
421
+ if (state.retired && !state.running) {
422
+ void this.closeClient(client);
423
+ }
424
+ }
425
+ }
426
+
427
+ /**
428
+ * Closes a replaced client once its running requests are done.
429
+ */
430
+ protected async retire(client: Client) {
431
+ const state = this.getClientState(client);
432
+
433
+ state.retired = true;
434
+
435
+ if (!state.running) {
436
+ await this.closeClient(client);
437
+ }
438
+ }
439
+
440
+ /**
441
+ * Returns the requests running on the client and whether it was replaced.
442
+ */
443
+ protected getClientState(client: Client) {
444
+ let state = this.clients.get(client);
445
+
446
+ if (!state) {
447
+ state = {running: 0, retired: false};
448
+ this.clients.set(client, state);
449
+ }
450
+
451
+ return state;
452
+ }
453
+
454
+ /**
455
+ * Removes the connection of the entry and closes its client right away (eviction, destroy).
456
+ */
297
457
  protected async close(entry: PoolEntry) {
298
458
  const {client} = entry;
299
459
 
300
460
  entry.client = undefined;
301
461
  entry.connection = undefined;
302
462
 
463
+ await this.closeClient(client);
464
+ }
465
+
466
+ /**
467
+ * Closes the client, logging a failure instead of throwing it.
468
+ */
469
+ protected async closeClient(client: Client | undefined) {
303
470
  try {
304
471
  await client?.close();
305
472
  } catch (error) {
@@ -41,7 +41,11 @@ function setup(catalog = createCatalog()) {
41
41
  readResource: vi.fn().mockResolvedValue({contents: []}),
42
42
  getPrompt: vi.fn().mockResolvedValue({messages: []})
43
43
  };
44
- const connection = {client, getCatalog: vi.fn().mockResolvedValue(catalog), run: vi.fn((fn: () => unknown) => fn())};
44
+ const connection = {
45
+ client,
46
+ getCatalog: vi.fn().mockResolvedValue(catalog),
47
+ run: vi.fn((fn: (c: typeof client) => unknown) => fn(client))
48
+ };
45
49
  const server = {registerTool: vi.fn(), registerResource: vi.fn(), registerPrompt: vi.fn()};
46
50
  const getConnection = vi.spyOn(inject(PlatformMcpGatewayService), "getConnection").mockResolvedValue(connection as never);
47
51
 
@@ -270,6 +274,65 @@ describe("attachUpstream()", () => {
270
274
  });
271
275
  });
272
276
 
277
+ describe("upstream which lost the session", () => {
278
+ it("reconnects to list the catalog and registers it on the new connection", async () => {
279
+ const {server, connection, getHandler} = setup();
280
+ const freshClient = {callTool: vi.fn().mockResolvedValue({content: [{type: "text", text: "fresh"}]})};
281
+ const fresh = {
282
+ client: freshClient,
283
+ getCatalog: vi.fn().mockResolvedValue(createCatalog()),
284
+ run: vi.fn((fn: (c: typeof freshClient) => unknown) => fn(freshClient))
285
+ };
286
+ const reconnect = vi.spyOn(inject(PlatformMcpGatewayService), "reconnect").mockResolvedValue(fresh as never);
287
+
288
+ Object.assign(connection.client, {transport: {sessionId: "upstream-session"}});
289
+ connection.getCatalog.mockRejectedValue(Object.assign(new Error("Session not found"), {status: 404}));
290
+
291
+ await attachUpstream(server as never, createSettings(http));
292
+
293
+ expect(reconnect).toHaveBeenCalledExactlyOnceWith(http, http, connection);
294
+ await expect(getHandler("registerTool", "echo")({message: "hi"}, createContext())).resolves.toEqual({
295
+ content: [{type: "text", text: "fresh"}]
296
+ });
297
+ expect(logger().error).not.toHaveBeenCalled();
298
+ });
299
+
300
+ it("reconnects when a concurrent request closed the client while the catalog was listed", async () => {
301
+ const {server, connection} = setup();
302
+ const reconnect = vi.spyOn(inject(PlatformMcpGatewayService), "reconnect").mockResolvedValue({
303
+ ...connection,
304
+ client: {},
305
+ getCatalog: vi.fn().mockResolvedValue(createCatalog())
306
+ } as never);
307
+
308
+ Object.assign(connection.client, {transport: {sessionId: "upstream-session"}});
309
+ connection.getCatalog.mockImplementation(async () => {
310
+ // the closed client has no transport any more
311
+ Object.assign(connection.client, {transport: undefined});
312
+
313
+ throw Object.assign(new Error("Session not found"), {status: 404});
314
+ });
315
+
316
+ await attachUpstream(server as never, createSettings(http));
317
+
318
+ expect(reconnect).toHaveBeenCalledOnce();
319
+ expect(server.registerTool).toHaveBeenCalled();
320
+ });
321
+
322
+ it("does not reconnect on another catalog failure", async () => {
323
+ const {server, connection} = setup();
324
+ const reconnect = vi.spyOn(inject(PlatformMcpGatewayService), "reconnect");
325
+
326
+ Object.assign(connection.client, {transport: {sessionId: "upstream-session"}});
327
+ connection.getCatalog.mockRejectedValue(Object.assign(new Error("server error"), {status: 500}));
328
+
329
+ await attachUpstream(server as never, createSettings(http));
330
+
331
+ expect(reconnect).not.toHaveBeenCalled();
332
+ expect(server.registerTool).not.toHaveBeenCalled();
333
+ });
334
+ });
335
+
273
336
  describe("unavailable upstream", () => {
274
337
  it.each([
275
338
  ["the endpoint path", createSettings(http), "/mcp/gateway"],
@@ -7,6 +7,7 @@ import {
7
7
  type PlatformMcpUpstreamCatalog,
8
8
  type PlatformMcpUpstreamConnection
9
9
  } from "../services/PlatformMcpGatewayService.js";
10
+ import {isUpstreamSessionLost} from "./isUpstreamSessionLost.js";
10
11
  import {resolveUpstream} from "./resolveUpstream.js";
11
12
 
12
13
  // upstream catalogs are stable objects: compile each schema once instead of on every request
@@ -72,7 +73,7 @@ function registerCatalog(
72
73
  server: McpServer,
73
74
  upstream: PlatformMcpUpstreamSettings,
74
75
  label: string,
75
- {client, run}: PlatformMcpUpstreamConnection,
76
+ {run}: PlatformMcpUpstreamConnection,
76
77
  catalog: PlatformMcpUpstreamCatalog,
77
78
  taken: Record<Kind, Set<string>>
78
79
  ) {
@@ -112,7 +113,7 @@ function registerCatalog(
112
113
  ...(outputSchema && {outputSchema: toSchema(outputSchema)})
113
114
  } as never,
114
115
  ((args: Record<string, unknown>, ctx: ServerContext) =>
115
- run(() => client.callTool({name, arguments: args}, getRequestOptions(ctx)))) as never
116
+ run((client) => client.callTool({name, arguments: args}, getRequestOptions(ctx)))) as never
116
117
  );
117
118
  });
118
119
  });
@@ -125,7 +126,7 @@ function registerCatalog(
125
126
  name,
126
127
  uri,
127
128
  opts as never,
128
- ((_: URL, ctx: ServerContext) => run(() => client.readResource({uri}, getRequestOptions(ctx)))) as never
129
+ ((_: URL, ctx: ServerContext) => run((client) => client.readResource({uri}, getRequestOptions(ctx)))) as never
129
130
  );
130
131
  });
131
132
  });
@@ -139,7 +140,7 @@ function registerCatalog(
139
140
  new ResourceTemplate(uriTemplate, {list: undefined}),
140
141
  opts as never,
141
142
  ((uri: URL, _: unknown, ctx: ServerContext) =>
142
- run(() => client.readResource({uri: uri.toString()}, getRequestOptions(ctx)))) as never
143
+ run((client) => client.readResource({uri: uri.toString()}, getRequestOptions(ctx)))) as never
143
144
  );
144
145
  });
145
146
  });
@@ -156,7 +157,7 @@ function registerCatalog(
156
157
  ((...params: unknown[]) => {
157
158
  const ctx = params.at(-1) as ServerContext;
158
159
 
159
- return run(() =>
160
+ return run((client) =>
160
161
  client.getPrompt(
161
162
  {name, arguments: params.length > 1 ? (params[0] as Record<string, string>) : undefined},
162
163
  getRequestOptions(ctx)
@@ -168,6 +169,29 @@ function registerCatalog(
168
169
  });
169
170
  }
170
171
 
172
+ /**
173
+ * Returns the catalog of the upstream and the connection it was listed on, listing it again on a new connection
174
+ * when the upstream lost the session.
175
+ */
176
+ async function getCatalog(upstream: PlatformMcpUpstreamSettings, resolved: PlatformMcpUpstreamSettings) {
177
+ const gateway = inject(PlatformMcpGatewayService);
178
+ let connection = await gateway.getConnection(upstream, resolved);
179
+ // the client loses its transport once closed, by a concurrent request which saw the session lost
180
+ const {transport} = connection.client;
181
+
182
+ try {
183
+ return {connection, catalog: await connection.getCatalog()};
184
+ } catch (error) {
185
+ if (!isUpstreamSessionLost(error, {transport})) {
186
+ throw error;
187
+ }
188
+
189
+ connection = await gateway.reconnect(upstream, resolved, connection);
190
+
191
+ return {connection, catalog: await connection.getCatalog()};
192
+ }
193
+ }
194
+
171
195
  /**
172
196
  * Registers the tools, resources and prompts of the endpoint's upstream MCP server on the given server.
173
197
  *
@@ -189,9 +213,9 @@ export async function attachUpstream(server: McpServer, settings: CreateMcpServe
189
213
  const label = settings.path || (upstream.type === "stdio" ? upstream.command : upstream.url);
190
214
 
191
215
  try {
192
- const connection = await inject(PlatformMcpGatewayService).getConnection(upstream, resolveUpstream(upstream, authInfo));
216
+ const {connection, catalog} = await getCatalog(upstream, resolveUpstream(upstream, authInfo));
193
217
 
194
- registerCatalog(server, upstream, label, connection, await connection.getCatalog(), {
218
+ registerCatalog(server, upstream, label, connection, catalog, {
195
219
  tool: new Set(settings.tools.map(({name}) => name)),
196
220
  prompt: new Set(settings.prompts.map(({name}) => name)),
197
221
  resource: new Set(settings.resources.map(({uri}) => uri!).filter(Boolean)),
@@ -0,0 +1,22 @@
1
+ import {SdkErrorCode, SdkHttpError} from "@modelcontextprotocol/client";
2
+ import {isUpstreamSessionLost} from "./isUpstreamSessionLost.js";
3
+
4
+ function httpError(status: number) {
5
+ return new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, "Error POSTing to endpoint", {status, statusText: ""});
6
+ }
7
+
8
+ describe("isUpstreamSessionLost()", () => {
9
+ it.each([
10
+ ["a 404 on a session", httpError(404), "session", true],
11
+ ["a 404 without session", httpError(404), undefined, false],
12
+ ["another status on a session", httpError(500), "session", false],
13
+ ["an error without status", new Error("boom"), "session", false],
14
+ ["no error", undefined, "session", false]
15
+ ])("should return %s", (_, error, sessionId, expected) => {
16
+ expect(isUpstreamSessionLost(error, {transport: {sessionId} as never})).toBe(expected);
17
+ });
18
+
19
+ it("should return false for a client without transport", () => {
20
+ expect(isUpstreamSessionLost(httpError(404), {transport: undefined})).toBe(false);
21
+ });
22
+ });
@@ -0,0 +1,16 @@
1
+ import type {Client} from "@modelcontextprotocol/client";
2
+
3
+ /**
4
+ * Tells whether the upstream no longer knows the session of the client.
5
+ *
6
+ * A Streamable HTTP server keeping its sessions in memory answers `404` to every request of a session it
7
+ * restarted without or closed (idle, request limit). The MCP client keeps sending the session and is never
8
+ * closed: the connection must be replaced.
9
+ *
10
+ * @param error Error thrown by the client.
11
+ * @param client Client which sent the request.
12
+ * @module platform/mcp
13
+ */
14
+ export function isUpstreamSessionLost(error: unknown, client: Pick<Client, "transport">): boolean {
15
+ return Boolean(client.transport?.sessionId) && (error as {status?: unknown} | null)?.status === 404;
16
+ }