@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.
@@ -23,6 +23,7 @@ export * from "./utils/createMcpServer.js";
23
23
  export * from "./utils/createUpstreamTransport.js";
24
24
  export * from "./utils/fromJsonSchema.js";
25
25
  export * from "./utils/interpolate.js";
26
+ export * from "./utils/isUpstreamSessionLost.js";
26
27
  export * from "./utils/listAll.js";
27
28
  export * from "./utils/resolvePrompts.js";
28
29
  export * from "./utils/resolveResources.js";
@@ -21,9 +21,18 @@ export interface PlatformMcpUpstreamConnection {
21
21
  client: Client;
22
22
  getCatalog(): Promise<PlatformMcpUpstreamCatalog>;
23
23
  /**
24
- * Runs an upstream request, keeping the connection out of the pool eviction while it is pending.
24
+ * Runs an upstream request with the client given to `fn`, keeping the connection out of the pool eviction while
25
+ * it is pending. When the upstream lost the session of the connection, the request is replayed once on a new
26
+ * connection: `fn` must send the request with the client it is given.
25
27
  */
26
- run<T>(fn: () => Promise<T>): Promise<T>;
28
+ run<T>(fn: (client: Client) => Promise<T>): Promise<T>;
29
+ }
30
+ /**
31
+ * Requests running on a client, and whether it was replaced: it is closed once they are done.
32
+ */
33
+ interface ClientState {
34
+ running: number;
35
+ retired: boolean;
27
36
  }
28
37
  interface PoolEntry {
29
38
  lastUsed: number;
@@ -44,6 +53,7 @@ interface PoolEntry {
44
53
  */
45
54
  export declare class PlatformMcpGatewayService implements OnDestroy {
46
55
  protected pools: Map<PlatformMcpUpstreamSettings, Map<string, PoolEntry>>;
56
+ protected clients: WeakMap<Client, ClientState>;
47
57
  /**
48
58
  * Returns the connection matching the resolved upstream definition, connecting lazily.
49
59
  *
@@ -51,8 +61,32 @@ export declare class PlatformMcpGatewayService implements OnDestroy {
51
61
  * @param resolved Same definition with its placeholders interpolated for the caller.
52
62
  */
53
63
  getConnection(upstream: PlatformMcpUpstreamSettings, resolved?: PlatformMcpUpstreamSettings): Promise<PlatformMcpUpstreamConnection>;
64
+ /**
65
+ * Replaces a connection whose session the upstream lost, then returns the connection to use.
66
+ *
67
+ * The connection is replaced only while it is still the current one: the requests failing together share the
68
+ * connection opened by the first of them. Its client is closed once its running requests are done: closing it
69
+ * earlier would abort requests the upstream may have handled, which could then not be replayed safely.
70
+ *
71
+ * @param upstream Upstream declared in the configuration, identifying the pool.
72
+ * @param resolved Same definition with its placeholders interpolated for the caller.
73
+ * @param stale Connection whose session was lost.
74
+ */
75
+ reconnect(upstream: PlatformMcpUpstreamSettings, resolved: PlatformMcpUpstreamSettings, stale: Pick<PlatformMcpUpstreamConnection, "client">): Promise<PlatformMcpUpstreamConnection>;
54
76
  $onDestroy(): Promise<void>;
55
- protected connect(upstream: PlatformMcpUpstreamSettings, entry: PoolEntry): Promise<PlatformMcpUpstreamConnection>;
77
+ /**
78
+ * Returns the pool entry matching the resolved upstream definition and its connection, connecting lazily.
79
+ */
80
+ protected acquire(upstream: PlatformMcpUpstreamSettings, resolved: PlatformMcpUpstreamSettings): {
81
+ entry: PoolEntry;
82
+ connection: Promise<PlatformMcpUpstreamConnection>;
83
+ };
84
+ protected connect(upstream: PlatformMcpUpstreamSettings, resolved: PlatformMcpUpstreamSettings, entry: PoolEntry): Promise<PlatformMcpUpstreamConnection>;
85
+ /**
86
+ * Runs `fn` with the current client of the entry, and replays it once on a new connection when the upstream
87
+ * lost the session.
88
+ */
89
+ protected run<T>(upstream: PlatformMcpUpstreamSettings, resolved: PlatformMcpUpstreamSettings, entry: PoolEntry, client: Client, fn: (client: Client) => Promise<T>, replay?: boolean): Promise<T>;
56
90
  /**
57
91
  * Lists every catalog the upstream advertises.
58
92
  *
@@ -75,6 +109,25 @@ export declare class PlatformMcpGatewayService implements OnDestroy {
75
109
  * Connections serving a request and the requested one are kept, so the pool can temporarily exceed `max`.
76
110
  */
77
111
  protected evict(upstream: PlatformMcpUpstreamSettings, pool: Map<string, PoolEntry>, current: PoolEntry, now: number): void;
112
+ /**
113
+ * Counts the requests running on the client, and closes it after the last one when it was replaced.
114
+ */
115
+ protected track<T>(client: Client, fn: () => Promise<T>): Promise<T>;
116
+ /**
117
+ * Closes a replaced client once its running requests are done.
118
+ */
119
+ protected retire(client: Client): Promise<void>;
120
+ /**
121
+ * Returns the requests running on the client and whether it was replaced.
122
+ */
123
+ protected getClientState(client: Client): ClientState;
124
+ /**
125
+ * Removes the connection of the entry and closes its client right away (eviction, destroy).
126
+ */
78
127
  protected close(entry: PoolEntry): Promise<void>;
128
+ /**
129
+ * Closes the client, logging a failure instead of throwing it.
130
+ */
131
+ protected closeClient(client: Client | undefined): Promise<void>;
79
132
  }
80
133
  export {};
@@ -0,0 +1,13 @@
1
+ import type { Client } from "@modelcontextprotocol/client";
2
+ /**
3
+ * Tells whether the upstream no longer knows the session of the client.
4
+ *
5
+ * A Streamable HTTP server keeping its sessions in memory answers `404` to every request of a session it
6
+ * restarted without or closed (idle, request limit). The MCP client keeps sending the session and is never
7
+ * closed: the connection must be replaced.
8
+ *
9
+ * @param error Error thrown by the client.
10
+ * @param client Client which sent the request.
11
+ * @module platform/mcp
12
+ */
13
+ export declare function isUpstreamSessionLost(error: unknown, client: Pick<Client, "transport">): boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsed/platform-mcp",
3
- "version": "8.45.0",
3
+ "version": "8.45.2",
4
4
  "description": "Model Context Protocol integration for Ts.ED HTTP adapters.",
5
5
  "source": "./src/http/index.ts",
6
6
  "type": "module",
@@ -51,14 +51,14 @@
51
51
  "uuid": ">=11.0.2"
52
52
  },
53
53
  "devDependencies": {
54
- "@tsed/barrels": "8.45.0",
55
- "@tsed/core": "8.45.0",
56
- "@tsed/di": "8.45.0",
57
- "@tsed/exceptions": "8.45.0",
58
- "@tsed/json-mapper": "8.45.0",
59
- "@tsed/platform-http": "8.45.0",
60
- "@tsed/schema": "8.45.0",
61
- "@tsed/typescript": "8.45.0",
54
+ "@tsed/barrels": "8.45.2",
55
+ "@tsed/core": "8.45.2",
56
+ "@tsed/di": "8.45.2",
57
+ "@tsed/exceptions": "8.45.2",
58
+ "@tsed/json-mapper": "8.45.2",
59
+ "@tsed/platform-http": "8.45.2",
60
+ "@tsed/schema": "8.45.2",
61
+ "@tsed/typescript": "8.45.2",
62
62
  "jose": "^6.1.3",
63
63
  "typescript": "6.0.2",
64
64
  "vitest": "4.1.4"
@@ -23,6 +23,7 @@ export * from "./utils/createMcpServer.js";
23
23
  export * from "./utils/createUpstreamTransport.js";
24
24
  export * from "./utils/fromJsonSchema.js";
25
25
  export * from "./utils/interpolate.js";
26
+ export * from "./utils/isUpstreamSessionLost.js";
26
27
  export * from "./utils/listAll.js";
27
28
  export * from "./utils/resolvePrompts.js";
28
29
  export * from "./utils/resolveResources.js";
@@ -1,4 +1,4 @@
1
- import {InMemoryTransport} from "@modelcontextprotocol/client";
1
+ import {type Client, InMemoryTransport, SdkErrorCode, SdkHttpError} from "@modelcontextprotocol/client";
2
2
  import {McpServer, ResourceTemplate} from "@modelcontextprotocol/server";
3
3
  import {DITest, inject, logger} from "@tsed/di";
4
4
  import type {PlatformMcpUpstreamSettings} from "../interfaces/PlatformMcpUpstreamSettings.js";
@@ -34,6 +34,26 @@ function mockUpstreamServers() {
34
34
  return servers;
35
35
  }
36
36
 
37
+ /**
38
+ * Session given by the upstream on initialize (Streamable HTTP), kept by the client on every request.
39
+ */
40
+ function setSession(client: Client, sessionId = "upstream-session") {
41
+ (client.transport as {sessionId?: string}).sessionId = sessionId;
42
+ }
43
+
44
+ /**
45
+ * What the MCP client throws when the upstream no longer knows its session (restarted, closed the session).
46
+ */
47
+ function sessionNotFound(status = 404) {
48
+ const text = '{"jsonrpc":"2.0","id":null,"error":{"code":-32001,"message":"Session not found"}}';
49
+
50
+ return new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, `Error POSTing to endpoint: ${text}`, {
51
+ status,
52
+ statusText: "Not Found",
53
+ text
54
+ });
55
+ }
56
+
37
57
  describe("PlatformMcpGatewayService", () => {
38
58
  beforeEach(() => DITest.create());
39
59
  afterEach(async () => {
@@ -205,6 +225,279 @@ describe("PlatformMcpGatewayService", () => {
205
225
  });
206
226
  });
207
227
 
228
+ describe("when the upstream lost the session", () => {
229
+ beforeEach(() => {
230
+ vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
231
+ });
232
+
233
+ it("reconnects and replays the request", async () => {
234
+ mockUpstreamServers();
235
+
236
+ const service = inject(PlatformMcpGatewayService);
237
+ const upstream = createUpstream();
238
+ const stale = await service.getConnection(upstream);
239
+ const close = vi.spyOn(stale.client, "close");
240
+
241
+ setSession(stale.client);
242
+
243
+ const result = await stale.run((client) =>
244
+ client === stale.client ? Promise.reject(sessionNotFound()) : client.callTool({name: "first", arguments: {}})
245
+ );
246
+
247
+ expect(result).toEqual({content: []});
248
+ expect(close).toHaveBeenCalledOnce();
249
+ expect(createUpstreamTransport).toHaveBeenCalledTimes(2);
250
+ expect(await service.getConnection(upstream)).not.toBe(stale);
251
+ expect(logger().warn).toHaveBeenCalledWith({
252
+ event: "MCP_GATEWAY_SESSION_LOST",
253
+ message: 'MCP upstream "http://localhost/mcp": the upstream lost the session, reconnecting.'
254
+ });
255
+ });
256
+
257
+ it("replays a request failing after another one closed the connection", async () => {
258
+ mockUpstreamServers();
259
+
260
+ const service = inject(PlatformMcpGatewayService);
261
+ const stale = await service.getConnection(createUpstream());
262
+ const fast = (client: Client) => (client === stale.client ? Promise.reject(sessionNotFound()) : Promise.resolve(client));
263
+ // fails once the first request has closed the client, which then has no transport any more
264
+ const slow = (client: Client) =>
265
+ client === stale.client
266
+ ? new Promise<Client>((_, reject) => setTimeout(() => reject(sessionNotFound()), 20))
267
+ : Promise.resolve(client);
268
+
269
+ setSession(stale.client);
270
+
271
+ const [first, second] = await Promise.all([stale.run(fast), stale.run(slow)]);
272
+
273
+ expect(second).toBe(first);
274
+ expect(stale.client.transport).toBeUndefined();
275
+ expect(createUpstreamTransport).toHaveBeenCalledTimes(2);
276
+ });
277
+
278
+ it("closes the replaced client once its running requests are done, without aborting them", async () => {
279
+ const servers = mockUpstreamServers();
280
+ const service = inject(PlatformMcpGatewayService);
281
+ const upstream = createUpstream();
282
+ const stale = await service.getConnection(upstream);
283
+ const close = vi.spyOn(stale.client, "close");
284
+ let answer: (() => void) | undefined;
285
+
286
+ servers[0].registerTool(
287
+ "slow",
288
+ {description: "Answers on demand"},
289
+ () => new Promise((resolve) => (answer = () => resolve({content: [{type: "text", text: "done"}]})))
290
+ );
291
+ setSession(stale.client);
292
+
293
+ const running = stale.run((client) => client.callTool({name: "slow", arguments: {}}));
294
+
295
+ await vi.waitFor(() => expect(answer).toBeDefined());
296
+ await stale.run((client) => (client === stale.client ? Promise.reject(sessionNotFound()) : Promise.resolve(client)));
297
+
298
+ // the upstream may handle the running request: aborting it would leave its outcome unknown
299
+ expect(close).not.toHaveBeenCalled();
300
+
301
+ answer!();
302
+
303
+ await expect(running).resolves.toEqual({content: [{type: "text", text: "done"}]});
304
+ await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());
305
+ });
306
+
307
+ it("lists the catalog on the current connection when it was replaced after being handed out", async () => {
308
+ mockUpstreamServers();
309
+
310
+ const service = inject(PlatformMcpGatewayService);
311
+ const upstream = createUpstream();
312
+ const stale = await service.getConnection(upstream);
313
+
314
+ setSession(stale.client);
315
+ // a concurrent request saw the session lost before this one listed the catalog
316
+ await service.reconnect(upstream, upstream, stale);
317
+
318
+ await expect(stale.getCatalog()).resolves.toMatchObject({tools: [{name: "first"}]});
319
+ expect(createUpstreamTransport).toHaveBeenCalledTimes(2);
320
+ });
321
+
322
+ it("closes the replaced client once its catalog is listed", async () => {
323
+ mockUpstreamServers();
324
+
325
+ const service = inject(PlatformMcpGatewayService);
326
+ const upstream = createUpstream();
327
+ const stale = await service.getConnection(upstream);
328
+ const close = vi.spyOn(stale.client, "close");
329
+ let release!: () => void;
330
+
331
+ vi.spyOn(stale.client, "listTools").mockImplementationOnce(() => new Promise((resolve) => (release = () => resolve({tools: []}))));
332
+ setSession(stale.client);
333
+
334
+ const catalog = stale.getCatalog();
335
+
336
+ await vi.waitFor(() => expect(release).toBeDefined());
337
+ await service.reconnect(upstream, upstream, stale);
338
+
339
+ expect(close).not.toHaveBeenCalled();
340
+
341
+ release();
342
+
343
+ await expect(catalog).resolves.toMatchObject({tools: []});
344
+ await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());
345
+ });
346
+
347
+ it("does not replay another error of a request running when the session was lost", async () => {
348
+ mockUpstreamServers();
349
+
350
+ const stale = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
351
+ const fast = (client: Client) => (client === stale.client ? Promise.reject(sessionNotFound()) : Promise.resolve(client));
352
+ // the upstream may have handled this request before failing: it must not run twice
353
+ const failing = vi.fn((client: Client) =>
354
+ client === stale.client
355
+ ? new Promise<Client>((_, reject) => setTimeout(() => reject(sessionNotFound(500)), 20))
356
+ : Promise.resolve(client)
357
+ );
358
+
359
+ setSession(stale.client);
360
+
361
+ const [, second] = await Promise.allSettled([stale.run(fast), stale.run(failing)]);
362
+
363
+ expect(second).toMatchObject({status: "rejected", reason: expect.objectContaining({status: 500})});
364
+ expect(failing).toHaveBeenCalledOnce();
365
+ });
366
+
367
+ it("rejects the catalog when a listing lost the session, even if the others succeed", async () => {
368
+ createUpstreamTransport.mockImplementation(async () => {
369
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
370
+ const server = new McpServer({name: "upstream", version: "1.0.0"});
371
+
372
+ server.registerTool("first", {description: "First tool"}, () => ({content: []}));
373
+ server.registerPrompt("greet", {description: "Greet"}, () => ({messages: []}));
374
+
375
+ await server.connect(serverTransport);
376
+
377
+ return clientTransport;
378
+ });
379
+
380
+ const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
381
+
382
+ setSession(connection.client);
383
+ vi.spyOn(connection.client, "listPrompts").mockRejectedValueOnce(sessionNotFound());
384
+
385
+ await expect(connection.getCatalog()).rejects.toThrow("Session not found");
386
+ expect(logger().warn).not.toHaveBeenCalled();
387
+ });
388
+
389
+ it("keeps the connection of a handler out of the eviction while it reconnects", async () => {
390
+ vi.useFakeTimers();
391
+ mockUpstreamServers();
392
+
393
+ const service = inject(PlatformMcpGatewayService);
394
+ const upstream = createUpstream({pool: {max: 1}});
395
+ const evicted = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer a"}));
396
+
397
+ vi.advanceTimersByTime(10);
398
+ await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}));
399
+ vi.advanceTimersByTime(10);
400
+
401
+ const running = evicted.run((client) => Promise.resolve(client));
402
+ // the pool is full: the least recently used connections are evicted while the handler reconnects
403
+ await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer c"}));
404
+
405
+ const client = await running;
406
+
407
+ expect(client).not.toBe(evicted.client);
408
+ expect((await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer a"}))).client).toBe(client);
409
+ });
410
+
411
+ it("runs a handler attached before the reconnection on the new connection", async () => {
412
+ mockUpstreamServers();
413
+
414
+ const service = inject(PlatformMcpGatewayService);
415
+ const upstream = createUpstream();
416
+ // two requests attached the same connection, the first one replaces it
417
+ const stale = await service.getConnection(upstream);
418
+
419
+ setSession(stale.client);
420
+
421
+ await stale.run((client) => (client === stale.client ? Promise.reject(sessionNotFound()) : Promise.resolve()));
422
+
423
+ const client = await stale.run((client) => Promise.resolve(client));
424
+
425
+ expect(client).not.toBe(stale.client);
426
+ expect(client).toBe((await service.getConnection(upstream)).client);
427
+ expect(createUpstreamTransport).toHaveBeenCalledTimes(2);
428
+ });
429
+
430
+ it("runs a handler on a new connection when its connection was evicted", async () => {
431
+ vi.useFakeTimers();
432
+ mockUpstreamServers();
433
+
434
+ const service = inject(PlatformMcpGatewayService);
435
+ const upstream = createUpstream({pool: {idleTimeout: 1000}});
436
+ const evicted = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer a"}));
437
+
438
+ vi.advanceTimersByTime(1001);
439
+ await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}));
440
+
441
+ const client = await evicted.run((client) => Promise.resolve(client));
442
+
443
+ expect(client).not.toBe(evicted.client);
444
+ expect(createUpstreamTransport).toHaveBeenCalledTimes(3);
445
+ });
446
+
447
+ it("replays the request only once", async () => {
448
+ mockUpstreamServers();
449
+
450
+ const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
451
+ const fn = vi.fn((client: Client) => {
452
+ setSession(client);
453
+
454
+ return Promise.reject(sessionNotFound());
455
+ });
456
+
457
+ setSession(connection.client);
458
+
459
+ await expect(connection.run(fn)).rejects.toThrow("Session not found");
460
+ expect(fn).toHaveBeenCalledTimes(2);
461
+ expect(createUpstreamTransport).toHaveBeenCalledTimes(2);
462
+ });
463
+
464
+ it("opens a single connection for the requests failing together", async () => {
465
+ mockUpstreamServers();
466
+
467
+ const service = inject(PlatformMcpGatewayService);
468
+ const upstream = createUpstream();
469
+ const stale = await service.getConnection(upstream);
470
+ const fn = (client: Client) => (client === stale.client ? Promise.reject(sessionNotFound()) : Promise.resolve(client));
471
+
472
+ setSession(stale.client);
473
+
474
+ const [first, second] = await Promise.all([stale.run(fn), stale.run(fn)]);
475
+
476
+ expect(first).toBe(second);
477
+ expect(createUpstreamTransport).toHaveBeenCalledTimes(2);
478
+ });
479
+
480
+ it("keeps the connection on another error", async () => {
481
+ mockUpstreamServers();
482
+
483
+ const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
484
+
485
+ setSession(connection.client);
486
+
487
+ await expect(connection.run(() => Promise.reject(sessionNotFound(500)))).rejects.toThrow("Session not found");
488
+ expect(createUpstreamTransport).toHaveBeenCalledOnce();
489
+ });
490
+
491
+ it("keeps the connection on a 404 of an upstream without session", async () => {
492
+ mockUpstreamServers();
493
+
494
+ const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
495
+
496
+ await expect(connection.run(() => Promise.reject(sessionNotFound()))).rejects.toThrow("Session not found");
497
+ expect(createUpstreamTransport).toHaveBeenCalledOnce();
498
+ });
499
+ });
500
+
208
501
  it("backs off before retrying a failing upstream", async () => {
209
502
  vi.useFakeTimers();
210
503
  createUpstreamTransport.mockRejectedValue(new Error("connect ECONNREFUSED"));