@tsed/platform-mcp 8.45.1 → 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";
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { constant, injectable, logger } from "@tsed/di";
3
3
  import { createUpstreamTransport } from "../utils/createUpstreamTransport.js";
4
+ import { isUpstreamSessionLost } from "../utils/isUpstreamSessionLost.js";
4
5
  import { listAll } from "../utils/listAll.js";
5
6
  const DEFAULT_POOL_MAX = 100;
6
7
  const DEFAULT_IDLE_TIMEOUT = 300_000;
@@ -16,6 +17,7 @@ const MAX_RETRY_DELAY = 30_000;
16
17
  export class PlatformMcpGatewayService {
17
18
  constructor() {
18
19
  this.pools = new Map();
20
+ this.clients = new WeakMap();
19
21
  }
20
22
  /**
21
23
  * Returns the connection matching the resolved upstream definition, connecting lazily.
@@ -24,6 +26,41 @@ export class PlatformMcpGatewayService {
24
26
  * @param resolved Same definition with its placeholders interpolated for the caller.
25
27
  */
26
28
  getConnection(upstream, resolved = upstream) {
29
+ return this.acquire(upstream, resolved).connection;
30
+ }
31
+ /**
32
+ * Replaces a connection whose session the upstream lost, then returns the connection to use.
33
+ *
34
+ * The connection is replaced only while it is still the current one: the requests failing together share the
35
+ * connection opened by the first of them. Its client is closed once its running requests are done: closing it
36
+ * earlier would abort requests the upstream may have handled, which could then not be replayed safely.
37
+ *
38
+ * @param upstream Upstream declared in the configuration, identifying the pool.
39
+ * @param resolved Same definition with its placeholders interpolated for the caller.
40
+ * @param stale Connection whose session was lost.
41
+ */
42
+ async reconnect(upstream, resolved, stale) {
43
+ const entry = this.getPool(upstream).get(this.getKey(resolved));
44
+ if (entry?.client === stale.client) {
45
+ logger().warn({
46
+ event: "MCP_GATEWAY_SESSION_LOST",
47
+ message: `MCP upstream "${this.getLabel(resolved)}": the upstream lost the session, reconnecting.`
48
+ });
49
+ entry.client = undefined;
50
+ entry.connection = undefined;
51
+ await this.retire(stale.client);
52
+ }
53
+ return this.getConnection(upstream, resolved);
54
+ }
55
+ async $onDestroy() {
56
+ const entries = [...this.pools.values()].flatMap((pool) => [...pool.values()]);
57
+ this.pools.clear();
58
+ await Promise.all(entries.map((entry) => this.close(entry)));
59
+ }
60
+ /**
61
+ * Returns the pool entry matching the resolved upstream definition and its connection, connecting lazily.
62
+ */
63
+ acquire(upstream, resolved) {
27
64
  const pool = this.getPool(upstream);
28
65
  const key = this.getKey(resolved);
29
66
  const now = Date.now();
@@ -36,9 +73,9 @@ export class PlatformMcpGatewayService {
36
73
  this.evict(upstream, pool, entry, now);
37
74
  if (!entry.connection) {
38
75
  if (entry.retryAt > now) {
39
- return Promise.reject(entry.error);
76
+ return { entry, connection: Promise.reject(entry.error) };
40
77
  }
41
- entry.connection = this.connect(resolved, entry).catch((error) => {
78
+ entry.connection = this.connect(upstream, resolved, entry).catch((error) => {
42
79
  entry.connection = undefined;
43
80
  entry.failures++;
44
81
  entry.error = error;
@@ -46,17 +83,12 @@ export class PlatformMcpGatewayService {
46
83
  throw error;
47
84
  });
48
85
  }
49
- return entry.connection;
50
- }
51
- async $onDestroy() {
52
- const entries = [...this.pools.values()].flatMap((pool) => [...pool.values()]);
53
- this.pools.clear();
54
- await Promise.all(entries.map((entry) => this.close(entry)));
86
+ return { entry, connection: entry.connection };
55
87
  }
56
- async connect(upstream, entry) {
88
+ async connect(upstream, resolved, entry) {
57
89
  const { Client } = await import("@modelcontextprotocol/client");
58
- const transport = await createUpstreamTransport(upstream);
59
- const label = this.getLabel(upstream);
90
+ const transport = await createUpstreamTransport(resolved);
91
+ const label = this.getLabel(resolved);
60
92
  let catalog;
61
93
  const invalidate = () => {
62
94
  catalog = undefined;
@@ -88,8 +120,12 @@ export class PlatformMcpGatewayService {
88
120
  return {
89
121
  client,
90
122
  getCatalog: () => {
123
+ if (entry.client !== client) {
124
+ // the connection was replaced (lost session) or closed (eviction) after it was handed out
125
+ return this.getConnection(upstream, resolved).then((current) => current.getCatalog());
126
+ }
91
127
  if (!catalog) {
92
- const pending = this.loadCatalog(client, label).then(({ catalog: loaded, complete }) => {
128
+ const pending = this.track(client, () => this.loadCatalog(client, label)).then(({ catalog: loaded, complete }) => {
93
129
  // an incomplete catalog is served once and listed again on the next request
94
130
  if (!complete && catalog === pending) {
95
131
  catalog = undefined;
@@ -105,18 +141,46 @@ export class PlatformMcpGatewayService {
105
141
  }
106
142
  return catalog;
107
143
  },
108
- run: async (fn) => {
109
- entry.pending++;
110
- try {
111
- return await fn();
112
- }
113
- finally {
114
- entry.pending--;
115
- entry.lastUsed = Date.now();
116
- }
117
- }
144
+ run: (fn) => this.run(upstream, resolved, entry, client, fn)
118
145
  };
119
146
  }
147
+ /**
148
+ * Runs `fn` with the current client of the entry, and replays it once on a new connection when the upstream
149
+ * lost the session.
150
+ */
151
+ async run(upstream, resolved, entry, client, fn, replay = true) {
152
+ if (entry.client !== client) {
153
+ // the handler was attached before its connection was replaced (lost session) or closed (eviction)
154
+ const acquired = this.acquire(upstream, resolved);
155
+ entry = acquired.entry;
156
+ // keeps the entry out of the eviction while it connects
157
+ entry.pending++;
158
+ try {
159
+ client = (await acquired.connection).client;
160
+ }
161
+ finally {
162
+ entry.pending--;
163
+ }
164
+ }
165
+ // the client loses its transport once closed, which can happen as soon as the request is done
166
+ const { transport } = client;
167
+ entry.pending++;
168
+ try {
169
+ return await this.track(client, () => fn(client));
170
+ }
171
+ catch (error) {
172
+ if (!replay || !isUpstreamSessionLost(error, { transport })) {
173
+ throw error;
174
+ }
175
+ }
176
+ finally {
177
+ entry.pending--;
178
+ entry.lastUsed = Date.now();
179
+ }
180
+ // the upstream rejected the request without handling it: it can be replayed, once, on a new session
181
+ await this.reconnect(upstream, resolved, { client });
182
+ return this.run(upstream, resolved, entry, client, fn, false);
183
+ }
120
184
  /**
121
185
  * Lists every catalog the upstream advertises.
122
186
  *
@@ -126,6 +190,7 @@ export class PlatformMcpGatewayService {
126
190
  */
127
191
  async loadCatalog(client, label) {
128
192
  const capabilities = client.getServerCapabilities() || {};
193
+ const { transport } = client;
129
194
  const listings = [
130
195
  ["tools", capabilities.tools, (params) => client.listTools(params)],
131
196
  ["resources", capabilities.resources, (params) => client.listResources(params)],
@@ -135,6 +200,11 @@ export class PlatformMcpGatewayService {
135
200
  const results = await Promise.allSettled(listings.map(([key, enabled, list]) => listAll(enabled, list, key)));
136
201
  const failures = results.flatMap((result, index) => result.status === "rejected" ? [{ key: listings[index][0], error: result.reason }] : []);
137
202
  const advertised = listings.filter(([, enabled]) => enabled).length;
203
+ const lost = failures.find(({ error }) => isUpstreamSessionLost(error, { transport }));
204
+ if (lost) {
205
+ // the other listings may have succeeded: the whole catalog is listed again on a new session
206
+ throw lost.error;
207
+ }
138
208
  failures.forEach(({ key, error }) => {
139
209
  logger().warn({
140
210
  event: "MCP_GATEWAY_CATALOG_ERROR",
@@ -203,10 +273,56 @@ export class PlatformMcpGatewayService {
203
273
  void this.close(entry);
204
274
  }
205
275
  }
276
+ /**
277
+ * Counts the requests running on the client, and closes it after the last one when it was replaced.
278
+ */
279
+ async track(client, fn) {
280
+ const state = this.getClientState(client);
281
+ state.running++;
282
+ try {
283
+ return await fn();
284
+ }
285
+ finally {
286
+ state.running--;
287
+ if (state.retired && !state.running) {
288
+ void this.closeClient(client);
289
+ }
290
+ }
291
+ }
292
+ /**
293
+ * Closes a replaced client once its running requests are done.
294
+ */
295
+ async retire(client) {
296
+ const state = this.getClientState(client);
297
+ state.retired = true;
298
+ if (!state.running) {
299
+ await this.closeClient(client);
300
+ }
301
+ }
302
+ /**
303
+ * Returns the requests running on the client and whether it was replaced.
304
+ */
305
+ getClientState(client) {
306
+ let state = this.clients.get(client);
307
+ if (!state) {
308
+ state = { running: 0, retired: false };
309
+ this.clients.set(client, state);
310
+ }
311
+ return state;
312
+ }
313
+ /**
314
+ * Removes the connection of the entry and closes its client right away (eviction, destroy).
315
+ */
206
316
  async close(entry) {
207
317
  const { client } = entry;
208
318
  entry.client = undefined;
209
319
  entry.connection = undefined;
320
+ await this.closeClient(client);
321
+ }
322
+ /**
323
+ * Closes the client, logging a failure instead of throwing it.
324
+ */
325
+ async closeClient(client) {
210
326
  try {
211
327
  await client?.close();
212
328
  }
@@ -1,6 +1,7 @@
1
1
  import { fromJsonSchema, ResourceTemplate } from "@modelcontextprotocol/server";
2
2
  import { inject, logger } from "@tsed/di";
3
3
  import { PlatformMcpGatewayService } from "../services/PlatformMcpGatewayService.js";
4
+ import { isUpstreamSessionLost } from "./isUpstreamSessionLost.js";
4
5
  import { resolveUpstream } from "./resolveUpstream.js";
5
6
  // upstream catalogs are stable objects: compile each schema once instead of on every request
6
7
  const schemas = new WeakMap();
@@ -45,7 +46,7 @@ function getPromptArgsSchema(args) {
45
46
  required: args.filter(({ required }) => required).map(({ name }) => name)
46
47
  });
47
48
  }
48
- function registerCatalog(server, upstream, label, { client, run }, catalog, taken) {
49
+ function registerCatalog(server, upstream, label, { run }, catalog, taken) {
49
50
  const { prefix = "" } = upstream;
50
51
  const register = (kind, key, fn) => {
51
52
  if (taken[kind].has(key)) {
@@ -75,21 +76,21 @@ function registerCatalog(server, upstream, label, { client, run }, catalog, take
75
76
  ...opts,
76
77
  inputSchema: toSchema(inputSchema),
77
78
  ...(outputSchema && { outputSchema: toSchema(outputSchema) })
78
- }, ((args, ctx) => run(() => client.callTool({ name, arguments: args }, getRequestOptions(ctx)))));
79
+ }, ((args, ctx) => run((client) => client.callTool({ name, arguments: args }, getRequestOptions(ctx)))));
79
80
  });
80
81
  });
81
82
  catalog.resources
82
83
  .filter(({ uri }) => isAllowed(upstream.resources, uri))
83
84
  .forEach(({ name, uri, ...opts }) => {
84
85
  register("resource", uri, () => {
85
- server.registerResource(name, uri, opts, ((_, ctx) => run(() => client.readResource({ uri }, getRequestOptions(ctx)))));
86
+ server.registerResource(name, uri, opts, ((_, ctx) => run((client) => client.readResource({ uri }, getRequestOptions(ctx)))));
86
87
  });
87
88
  });
88
89
  catalog.resourceTemplates
89
90
  .filter(({ uriTemplate }) => isAllowed(upstream.resources, uriTemplate))
90
91
  .forEach(({ name, uriTemplate, ...opts }) => {
91
92
  register("resource template", name, () => {
92
- server.registerResource(name, new ResourceTemplate(uriTemplate, { list: undefined }), opts, ((uri, _, ctx) => run(() => client.readResource({ uri: uri.toString() }, getRequestOptions(ctx)))));
93
+ server.registerResource(name, new ResourceTemplate(uriTemplate, { list: undefined }), opts, ((uri, _, ctx) => run((client) => client.readResource({ uri: uri.toString() }, getRequestOptions(ctx)))));
93
94
  });
94
95
  });
95
96
  catalog.prompts
@@ -99,11 +100,31 @@ function registerCatalog(server, upstream, label, { client, run }, catalog, take
99
100
  const argsSchema = getPromptArgsSchema(args);
100
101
  server.registerPrompt(prefix + name, { ...opts, ...(argsSchema && { argsSchema }) }, ((...params) => {
101
102
  const ctx = params.at(-1);
102
- return run(() => client.getPrompt({ name, arguments: params.length > 1 ? params[0] : undefined }, getRequestOptions(ctx)));
103
+ return run((client) => client.getPrompt({ name, arguments: params.length > 1 ? params[0] : undefined }, getRequestOptions(ctx)));
103
104
  }));
104
105
  });
105
106
  });
106
107
  }
108
+ /**
109
+ * Returns the catalog of the upstream and the connection it was listed on, listing it again on a new connection
110
+ * when the upstream lost the session.
111
+ */
112
+ async function getCatalog(upstream, resolved) {
113
+ const gateway = inject(PlatformMcpGatewayService);
114
+ let connection = await gateway.getConnection(upstream, resolved);
115
+ // the client loses its transport once closed, by a concurrent request which saw the session lost
116
+ const { transport } = connection.client;
117
+ try {
118
+ return { connection, catalog: await connection.getCatalog() };
119
+ }
120
+ catch (error) {
121
+ if (!isUpstreamSessionLost(error, { transport })) {
122
+ throw error;
123
+ }
124
+ connection = await gateway.reconnect(upstream, resolved, connection);
125
+ return { connection, catalog: await connection.getCatalog() };
126
+ }
127
+ }
107
128
  /**
108
129
  * Registers the tools, resources and prompts of the endpoint's upstream MCP server on the given server.
109
130
  *
@@ -122,8 +143,8 @@ export async function attachUpstream(server, settings, authInfo) {
122
143
  }
123
144
  const label = settings.path || (upstream.type === "stdio" ? upstream.command : upstream.url);
124
145
  try {
125
- const connection = await inject(PlatformMcpGatewayService).getConnection(upstream, resolveUpstream(upstream, authInfo));
126
- registerCatalog(server, upstream, label, connection, await connection.getCatalog(), {
146
+ const { connection, catalog } = await getCatalog(upstream, resolveUpstream(upstream, authInfo));
147
+ registerCatalog(server, upstream, label, connection, catalog, {
127
148
  tool: new Set(settings.tools.map(({ name }) => name)),
128
149
  prompt: new Set(settings.prompts.map(({ name }) => name)),
129
150
  resource: new Set(settings.resources.map(({ uri }) => uri).filter(Boolean)),
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Tells whether the upstream no longer knows the session of the client.
3
+ *
4
+ * A Streamable HTTP server keeping its sessions in memory answers `404` to every request of a session it
5
+ * restarted without or closed (idle, request limit). The MCP client keeps sending the session and is never
6
+ * closed: the connection must be replaced.
7
+ *
8
+ * @param error Error thrown by the client.
9
+ * @param client Client which sent the request.
10
+ * @module platform/mcp
11
+ */
12
+ export function isUpstreamSessionLost(error, client) {
13
+ return Boolean(client.transport?.sessionId) && error?.status === 404;
14
+ }