@tsed/platform-mcp 8.41.3 → 8.42.0

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.
Files changed (65) hide show
  1. package/lib/esm/cli/services/mcpServerConnect.js +17 -1
  2. package/lib/esm/cli/services/mcpStreamableServer.js +1 -1
  3. package/lib/esm/common/domain/PlatformTokenVerifier.js +169 -0
  4. package/lib/esm/common/errors/PlatformInvalidToken.js +11 -0
  5. package/lib/esm/common/errors/PlatformServerError.js +11 -0
  6. package/lib/esm/common/index.js +11 -0
  7. package/lib/esm/common/interfaces/PlatformMcpAuthSettings.js +1 -0
  8. package/lib/esm/common/interfaces/PlatformMcpUpstreamSettings.js +1 -0
  9. package/lib/esm/common/services/PlatformMcpGatewayService.js +167 -0
  10. package/lib/esm/common/utils/attachUpstream.js +140 -0
  11. package/lib/esm/common/utils/createUpstreamTransport.js +21 -0
  12. package/lib/esm/common/utils/interpolate.js +24 -0
  13. package/lib/esm/common/utils/listAll.js +13 -0
  14. package/lib/esm/common/utils/resolveUpstream.js +35 -0
  15. package/lib/esm/http/index.js +1 -0
  16. package/lib/esm/http/services/PlatformMcpAuthService.js +112 -0
  17. package/lib/esm/http/services/PlatformMcpModule.js +60 -7
  18. package/lib/tsconfig.esm.tsbuildinfo +1 -1
  19. package/lib/types/cli/services/mcpStreamableServer.d.ts +1 -1
  20. package/lib/types/common/domain/PlatformTokenVerifier.d.ts +59 -0
  21. package/lib/types/common/errors/PlatformInvalidToken.d.ts +9 -0
  22. package/lib/types/common/errors/PlatformServerError.d.ts +9 -0
  23. package/lib/types/common/index.d.ts +11 -0
  24. package/lib/types/common/interfaces/PlatformMcpAuthSettings.d.ts +81 -0
  25. package/lib/types/common/interfaces/PlatformMcpSettings.d.ts +10 -0
  26. package/lib/types/common/interfaces/PlatformMcpUpstreamSettings.d.ts +77 -0
  27. package/lib/types/common/services/PlatformMcpGatewayService.d.ts +66 -0
  28. package/lib/types/common/utils/attachUpstream.d.ts +14 -0
  29. package/lib/types/common/utils/createUpstreamTransport.d.ts +10 -0
  30. package/lib/types/common/utils/interpolate.d.ts +19 -0
  31. package/lib/types/common/utils/listAll.d.ts +3 -0
  32. package/lib/types/common/utils/resolveUpstream.d.ts +14 -0
  33. package/lib/types/http/index.d.ts +1 -0
  34. package/lib/types/http/services/PlatformMcpAuthService.d.ts +61 -0
  35. package/lib/types/http/services/PlatformMcpModule.d.ts +9 -2
  36. package/package.json +11 -8
  37. package/readme.md +2 -0
  38. package/src/cli/services/mcpServerConnect.spec.ts +40 -4
  39. package/src/cli/services/mcpServerConnect.ts +21 -1
  40. package/src/cli/services/mcpStreamableServer.ts +2 -2
  41. package/src/common/domain/PlatformTokenVerifier.spec.ts +313 -0
  42. package/src/common/domain/PlatformTokenVerifier.ts +230 -0
  43. package/src/common/errors/PlatformInvalidToken.ts +12 -0
  44. package/src/common/errors/PlatformServerError.ts +12 -0
  45. package/src/common/index.ts +11 -0
  46. package/src/common/interfaces/PlatformMcpAuthSettings.ts +82 -0
  47. package/src/common/interfaces/PlatformMcpSettings.ts +10 -0
  48. package/src/common/interfaces/PlatformMcpUpstreamSettings.ts +80 -0
  49. package/src/common/services/PlatformMcpGatewayService.spec.ts +282 -0
  50. package/src/common/services/PlatformMcpGatewayService.ts +247 -0
  51. package/src/common/utils/attachUpstream.spec.ts +305 -0
  52. package/src/common/utils/attachUpstream.ts +207 -0
  53. package/src/common/utils/createUpstreamTransport.spec.ts +94 -0
  54. package/src/common/utils/createUpstreamTransport.ts +29 -0
  55. package/src/common/utils/interpolate.spec.ts +33 -0
  56. package/src/common/utils/interpolate.ts +28 -0
  57. package/src/common/utils/listAll.spec.ts +28 -0
  58. package/src/common/utils/listAll.ts +17 -0
  59. package/src/common/utils/resolveUpstream.spec.ts +78 -0
  60. package/src/common/utils/resolveUpstream.ts +44 -0
  61. package/src/http/index.ts +1 -0
  62. package/src/http/services/PlatformMcpAuthService.spec.ts +239 -0
  63. package/src/http/services/PlatformMcpAuthService.ts +137 -0
  64. package/src/http/services/PlatformMcpModule.spec.ts +89 -0
  65. package/src/http/services/PlatformMcpModule.ts +79 -9
@@ -0,0 +1,82 @@
1
+ import type {OAuthTokenVerifier} from "@modelcontextprotocol/server";
2
+ import type {TokenProvider} from "@tsed/di";
3
+
4
+ /**
5
+ * OAuth 2.1 resource-server configuration of a Ts.ED MCP endpoint.
6
+ *
7
+ * The endpoint never issues tokens: clients are redirected to the configured authorization server,
8
+ * where registration and consent happen.
9
+ *
10
+ * @module platform/mcp
11
+ */
12
+ export interface PlatformMcpAuthSettings {
13
+ /**
14
+ * Issuer URL of the authorization server (OIDC provider) protecting the endpoint.
15
+ */
16
+ issuer: string;
17
+ /**
18
+ * How access tokens are verified:
19
+ *
20
+ * - `offline`: the JWT access token (RFC 9068, `typ: at+jwt`) is validated locally against the authorization server JWKS.
21
+ * - `introspection`: the authorization server is asked for each token (RFC 7662). Requires `clientId` and `clientSecret`.
22
+ *
23
+ * Defaults to `introspection` when `clientId` is set, `offline` otherwise.
24
+ */
25
+ mode?: "offline" | "introspection";
26
+ /**
27
+ * Credentials of the MCP endpoint on the authorization server, used to call the introspection endpoint.
28
+ */
29
+ clientId?: string;
30
+ clientSecret?: string;
31
+ /**
32
+ * Expected audience of the access tokens. Defaults to `resource`.
33
+ *
34
+ * `false` disables the audience check. It is only accepted by the `introspection` mode and makes the endpoint
35
+ * accept any active token of the issuer, whatever the resource it was issued for.
36
+ */
37
+ audience?: string | false;
38
+ /**
39
+ * JWKS URL used by the `offline` mode. Discovered from the issuer metadata by default.
40
+ */
41
+ jwksUri?: string;
42
+ /**
43
+ * Introspection URL used by the `introspection` mode. Discovered from the issuer metadata by default.
44
+ */
45
+ introspectionEndpoint?: string;
46
+ /**
47
+ * Time in seconds an introspection result is reused. Defaults to `60`; `0` disables the cache.
48
+ */
49
+ cacheTtl?: number;
50
+ /**
51
+ * Allow a non-HTTPS issuer (other than `localhost`). For local development only.
52
+ */
53
+ allowInsecureRequests?: boolean;
54
+ /**
55
+ * Custom access token verifier replacing the built-in modes: an object implementing
56
+ * `verifyAccessToken(token)` or a DI token resolving to one.
57
+ */
58
+ verifier?: OAuthTokenVerifier | TokenProvider<OAuthTokenVerifier>;
59
+ /**
60
+ * Canonical public URL of the MCP endpoint. It is advertised in the protected resource metadata and in the
61
+ * bearer challenge, and is the expected audience of access tokens unless `audience` is set.
62
+ *
63
+ * It is required and never derived from the incoming request, whose `Host` header is controlled by the caller.
64
+ */
65
+ resource: string;
66
+ /**
67
+ * Scopes advertised in the protected resource metadata.
68
+ */
69
+ scopesSupported?: string[];
70
+ /**
71
+ * Scopes a token must carry to reach the endpoint.
72
+ */
73
+ requiredScopes?: string[];
74
+ /**
75
+ * Human-readable name advertised in the protected resource metadata.
76
+ */
77
+ resourceName?: string;
78
+ /**
79
+ * Documentation URL advertised in the protected resource metadata.
80
+ */
81
+ resourceDocumentation?: string;
82
+ }
@@ -1,6 +1,8 @@
1
1
  import type {Implementation, ServerOptions} from "@modelcontextprotocol/server";
2
2
  import type {StreamableHTTPServerTransportOptions} from "@modelcontextprotocol/node";
3
3
  import type {TokenProvider} from "@tsed/di";
4
+ import type {PlatformMcpAuthSettings} from "./PlatformMcpAuthSettings.js";
5
+ import type {PlatformMcpUpstreamSettings} from "./PlatformMcpUpstreamSettings.js";
4
6
 
5
7
  /**
6
8
  * Configuration fragment accepted under `configuration.mcp` to wire the Platform MCP module.
@@ -55,6 +57,14 @@ export interface PlatformMcpSettings {
55
57
  * Optional transport options for the MCP server.
56
58
  */
57
59
  transportOptions?: StreamableHTTPServerTransportOptions;
60
+ /**
61
+ * Third-party MCP server exposed through this endpoint (gateway mode).
62
+ */
63
+ upstream?: PlatformMcpUpstreamSettings;
64
+ /**
65
+ * Protect the HTTP endpoint with an OAuth authorization server.
66
+ */
67
+ auth?: PlatformMcpAuthSettings;
58
68
  }
59
69
 
60
70
  declare global {
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Include/exclude filter evaluated on upstream names (tools, prompts) or URIs (resources).
3
+ *
4
+ * @module platform/mcp
5
+ */
6
+ export interface McpUpstreamFilter {
7
+ include?: (string | RegExp)[];
8
+ exclude?: (string | RegExp)[];
9
+ }
10
+
11
+ interface McpUpstreamBaseSettings {
12
+ /**
13
+ * Optional prefix applied to the exposed tool and prompt names. No prefix by default.
14
+ */
15
+ prefix?: string;
16
+ tools?: McpUpstreamFilter;
17
+ resources?: McpUpstreamFilter;
18
+ prompts?: McpUpstreamFilter;
19
+ /**
20
+ * Bounds of the upstream connection pool. One connection (or process, for stdio) is kept per distinct
21
+ * set of interpolated values.
22
+ */
23
+ pool?: {
24
+ /**
25
+ * Maximum number of live connections. Defaults to `100`.
26
+ */
27
+ max?: number;
28
+ /**
29
+ * Idle time in milliseconds before a connection is closed. Defaults to `300000`.
30
+ */
31
+ idleTimeout?: number;
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Upstream reached over Streamable HTTP (`http`) or legacy HTTP+SSE (`sse`).
37
+ *
38
+ * @module platform/mcp
39
+ */
40
+ export interface McpHttpUpstreamSettings extends McpUpstreamBaseSettings {
41
+ type: "http" | "sse";
42
+ url: string;
43
+ /**
44
+ * Headers sent with every upstream request. Values support the `${OAUTH_TOKEN}`, `${OAUTH_CLIENT_ID}`
45
+ * and `${OAUTH_SCOPES}` placeholders, replaced with the verified identity of the caller.
46
+ */
47
+ headers?: Record<string, string>;
48
+ /**
49
+ * Extra `fetch` options sent with every upstream request.
50
+ */
51
+ requestInit?: RequestInit;
52
+ }
53
+
54
+ /**
55
+ * Upstream started as a local process speaking MCP over stdio (for instance a server started with `npx`).
56
+ *
57
+ * @module platform/mcp
58
+ */
59
+ export interface McpStdioUpstreamSettings extends McpUpstreamBaseSettings {
60
+ type: "stdio";
61
+ command: string;
62
+ /**
63
+ * Arguments of the command. Values support the same placeholders as `headers`.
64
+ * One process is started per distinct set of interpolated values.
65
+ */
66
+ args?: string[];
67
+ /**
68
+ * Environment of the child process, merged over the SDK safe environment subset.
69
+ * Values support the same placeholders as `headers`.
70
+ */
71
+ env?: Record<string, string>;
72
+ cwd?: string;
73
+ }
74
+
75
+ /**
76
+ * Third-party MCP server exposed through a Ts.ED MCP endpoint.
77
+ *
78
+ * @module platform/mcp
79
+ */
80
+ export type PlatformMcpUpstreamSettings = McpHttpUpstreamSettings | McpStdioUpstreamSettings;
@@ -0,0 +1,282 @@
1
+ import {InMemoryTransport} from "@modelcontextprotocol/client";
2
+ import {McpServer, ResourceTemplate} from "@modelcontextprotocol/server";
3
+ import {DITest, inject, logger} from "@tsed/di";
4
+ import type {PlatformMcpUpstreamSettings} from "../interfaces/PlatformMcpUpstreamSettings.js";
5
+ import {PlatformMcpGatewayService} from "./PlatformMcpGatewayService.js";
6
+
7
+ const {createUpstreamTransport} = vi.hoisted(() => ({createUpstreamTransport: vi.fn()}));
8
+
9
+ vi.mock("../utils/createUpstreamTransport.js", () => ({createUpstreamTransport}));
10
+
11
+ function withHeaders(upstream: PlatformMcpUpstreamSettings, headers: Record<string, string>) {
12
+ return {...upstream, headers} as PlatformMcpUpstreamSettings;
13
+ }
14
+
15
+ function createUpstream(opts: Partial<PlatformMcpUpstreamSettings> = {}): PlatformMcpUpstreamSettings {
16
+ return {type: "http", url: "http://localhost/mcp", ...opts} as PlatformMcpUpstreamSettings;
17
+ }
18
+
19
+ function mockUpstreamServers() {
20
+ const servers: McpServer[] = [];
21
+
22
+ createUpstreamTransport.mockImplementation(async () => {
23
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
24
+ const server = new McpServer({name: "upstream", version: "1.0.0"});
25
+
26
+ server.registerTool("first", {description: "First tool"}, () => ({content: []}));
27
+ servers.push(server);
28
+
29
+ await server.connect(serverTransport);
30
+
31
+ return clientTransport;
32
+ });
33
+
34
+ return servers;
35
+ }
36
+
37
+ describe("PlatformMcpGatewayService", () => {
38
+ beforeEach(() => DITest.create());
39
+ afterEach(async () => {
40
+ vi.useRealTimers();
41
+ vi.resetAllMocks();
42
+ await DITest.reset();
43
+ });
44
+
45
+ it("connects lazily and reuses the connection for the same headers", async () => {
46
+ mockUpstreamServers();
47
+
48
+ const service = inject(PlatformMcpGatewayService);
49
+ const upstream = createUpstream();
50
+
51
+ const [first, second] = await Promise.all([
52
+ service.getConnection(upstream, withHeaders(upstream, {"x-api-key": "a"})),
53
+ service.getConnection(upstream, withHeaders(upstream, {"x-api-key": "a"}))
54
+ ]);
55
+
56
+ expect(first).toBe(second);
57
+ expect(createUpstreamTransport).toHaveBeenCalledExactlyOnceWith(withHeaders(upstream, {"x-api-key": "a"}));
58
+ });
59
+
60
+ it("opens one connection per distinct set of headers", async () => {
61
+ mockUpstreamServers();
62
+
63
+ const service = inject(PlatformMcpGatewayService);
64
+ const upstream = createUpstream();
65
+
66
+ const first = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer a"}));
67
+ const second = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}));
68
+
69
+ expect(first).not.toBe(second);
70
+ expect(createUpstreamTransport).toHaveBeenCalledTimes(2);
71
+ });
72
+
73
+ it("loads and caches the upstream catalog", async () => {
74
+ mockUpstreamServers();
75
+
76
+ const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
77
+ const listTools = vi.spyOn(connection.client, "listTools");
78
+
79
+ const catalog = await connection.getCatalog();
80
+
81
+ expect(catalog.tools.map(({name}) => name)).toEqual(["first"]);
82
+ expect(catalog).toMatchObject({resources: [], resourceTemplates: [], prompts: []});
83
+ expect(await connection.getCatalog()).toBe(catalog);
84
+ expect(listTools).toHaveBeenCalledOnce();
85
+ });
86
+
87
+ it("loads the resources, resource templates and prompts advertised by the upstream", async () => {
88
+ createUpstreamTransport.mockImplementation(async () => {
89
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
90
+ const server = new McpServer({name: "upstream", version: "1.0.0"});
91
+
92
+ server.registerResource("readme", "upstream://readme", {}, (uri) => ({contents: [{uri: uri.href, text: "readme"}]}));
93
+ server.registerResource("doc", new ResourceTemplate("upstream://docs/{id}", {list: undefined}), {}, (uri) => ({
94
+ contents: [{uri: uri.href, text: "doc"}]
95
+ }));
96
+ server.registerPrompt("greet", {description: "Greet"}, () => ({messages: []}));
97
+
98
+ await server.connect(serverTransport);
99
+
100
+ return clientTransport;
101
+ });
102
+
103
+ const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
104
+
105
+ await expect(connection.getCatalog()).resolves.toMatchObject({
106
+ tools: [],
107
+ resources: [{name: "readme", uri: "upstream://readme"}],
108
+ resourceTemplates: [{name: "doc", uriTemplate: "upstream://docs/{id}"}],
109
+ prompts: [{name: "greet", description: "Greet"}]
110
+ });
111
+ });
112
+
113
+ it("retries the catalog after a listing failure", async () => {
114
+ mockUpstreamServers();
115
+
116
+ const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
117
+ const listTools = vi.spyOn(connection.client, "listTools").mockRejectedValueOnce(new Error("list failed"));
118
+
119
+ await expect(connection.getCatalog()).rejects.toThrow("list failed");
120
+ await expect(connection.getCatalog()).resolves.toMatchObject({tools: [expect.objectContaining({name: "first"})]});
121
+ expect(listTools).toHaveBeenCalledTimes(2);
122
+ });
123
+
124
+ it("refreshes the catalog when the upstream notifies a list change", async () => {
125
+ const servers = mockUpstreamServers();
126
+ const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
127
+
128
+ await connection.getCatalog();
129
+
130
+ servers[0].registerTool("second", {description: "Second tool"}, () => ({content: []}));
131
+
132
+ await vi.waitFor(async () => {
133
+ expect((await connection.getCatalog()).tools.map(({name}) => name)).toEqual(["first", "second"]);
134
+ });
135
+ });
136
+
137
+ it("reconnects after the upstream connection is closed", async () => {
138
+ const servers = mockUpstreamServers();
139
+ const service = inject(PlatformMcpGatewayService);
140
+ const upstream = createUpstream();
141
+ const first = await service.getConnection(upstream);
142
+
143
+ await servers[0].close();
144
+
145
+ await vi.waitFor(async () => {
146
+ expect(await service.getConnection(upstream)).not.toBe(first);
147
+ });
148
+ });
149
+
150
+ it("backs off before retrying a failing upstream", async () => {
151
+ vi.useFakeTimers();
152
+ createUpstreamTransport.mockRejectedValue(new Error("connect ECONNREFUSED"));
153
+
154
+ const service = inject(PlatformMcpGatewayService);
155
+ const upstream = createUpstream();
156
+
157
+ await expect(service.getConnection(upstream)).rejects.toThrow("ECONNREFUSED");
158
+ await expect(service.getConnection(upstream)).rejects.toThrow("ECONNREFUSED");
159
+
160
+ expect(createUpstreamTransport).toHaveBeenCalledOnce();
161
+
162
+ vi.advanceTimersByTime(1001);
163
+ mockUpstreamServers();
164
+
165
+ await expect(service.getConnection(upstream)).resolves.toBeDefined();
166
+ });
167
+
168
+ it("closes the least recently used connection when the pool is full", async () => {
169
+ vi.useFakeTimers();
170
+ mockUpstreamServers();
171
+
172
+ const service = inject(PlatformMcpGatewayService);
173
+ const upstream = createUpstream({pool: {max: 2}});
174
+
175
+ const first = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer a"}));
176
+ const close = vi.spyOn(first.client, "close");
177
+
178
+ vi.advanceTimersByTime(10);
179
+ await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}));
180
+ vi.advanceTimersByTime(10);
181
+ await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer c"}));
182
+
183
+ expect(close).toHaveBeenCalledOnce();
184
+ });
185
+
186
+ it("keeps a connection that is serving a request", async () => {
187
+ vi.useFakeTimers();
188
+ mockUpstreamServers();
189
+
190
+ const service = inject(PlatformMcpGatewayService);
191
+ const upstream = createUpstream({pool: {idleTimeout: 1000}});
192
+ const first = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer a"}));
193
+ const close = vi.spyOn(first.client, "close");
194
+ let release!: () => void;
195
+ const pending = first.run(() => new Promise<void>((resolve) => (release = resolve)));
196
+
197
+ vi.advanceTimersByTime(1001);
198
+ await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}));
199
+
200
+ expect(close).not.toHaveBeenCalled();
201
+
202
+ release();
203
+ await pending;
204
+ vi.advanceTimersByTime(1001);
205
+ await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}));
206
+
207
+ expect(close).toHaveBeenCalledOnce();
208
+ });
209
+
210
+ it("keeps the requested connection tracked when the pool is full of busy connections", async () => {
211
+ vi.useFakeTimers();
212
+ mockUpstreamServers();
213
+
214
+ const service = inject(PlatformMcpGatewayService);
215
+ const upstream = createUpstream({pool: {max: 1}});
216
+ const busy = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer a"}));
217
+ let release!: () => void;
218
+ const pending = busy.run(() => new Promise<void>((resolve) => (release = resolve)));
219
+
220
+ vi.advanceTimersByTime(10);
221
+
222
+ const added = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}));
223
+ const close = vi.spyOn(added.client, "close");
224
+
225
+ // the pool temporarily exceeds `max`: the new connection is reused and closed with the application
226
+ expect(await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}))).toBe(added);
227
+ expect(createUpstreamTransport).toHaveBeenCalledTimes(2);
228
+
229
+ release();
230
+ await pending;
231
+ await service.$onDestroy();
232
+
233
+ expect(close).toHaveBeenCalledOnce();
234
+ });
235
+
236
+ it("closes idle connections", async () => {
237
+ vi.useFakeTimers();
238
+ mockUpstreamServers();
239
+
240
+ const service = inject(PlatformMcpGatewayService);
241
+ const upstream = createUpstream({pool: {idleTimeout: 1000}});
242
+
243
+ const first = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer a"}));
244
+ const close = vi.spyOn(first.client, "close");
245
+
246
+ vi.advanceTimersByTime(1001);
247
+ await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}));
248
+
249
+ expect(close).toHaveBeenCalledOnce();
250
+ });
251
+
252
+ it("logs a client that fails to close and keeps destroying the others", async () => {
253
+ mockUpstreamServers();
254
+
255
+ const service = inject(PlatformMcpGatewayService);
256
+ const upstream = createUpstream();
257
+ const first = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer a"}));
258
+ const second = await service.getConnection(upstream, withHeaders(upstream, {authorization: "Bearer b"}));
259
+ const error = new Error("close failed");
260
+ const close = vi.spyOn(second.client, "close");
261
+
262
+ vi.spyOn(first.client, "close").mockRejectedValue(error);
263
+ vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
264
+
265
+ await expect(service.$onDestroy()).resolves.toBeUndefined();
266
+
267
+ expect(logger().warn).toHaveBeenCalledWith({event: "MCP_GATEWAY_CLOSE_ERROR", error});
268
+ expect(close).toHaveBeenCalledOnce();
269
+ });
270
+
271
+ it("closes every upstream client when the application is destroyed", async () => {
272
+ mockUpstreamServers();
273
+
274
+ const service = inject(PlatformMcpGatewayService);
275
+ const connection = await service.getConnection(createUpstream());
276
+ const close = vi.spyOn(connection.client, "close");
277
+
278
+ await service.$onDestroy();
279
+
280
+ expect(close).toHaveBeenCalledOnce();
281
+ });
282
+ });