@tsed/platform-mcp 8.44.13 → 8.45.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.
@@ -66,6 +66,30 @@ export interface PlatformMcpSettings {
66
66
  * check (`preAuth`), or with both.
67
67
  */
68
68
  auth?: PlatformMcpAuthSettings | PlatformMcpPreAuthSettings;
69
+ /**
70
+ * Let MCP clients running in a browser (e.g. the MCP Inspector) call the endpoint: answers the CORS preflight
71
+ * and adds the CORS headers to every response of the endpoint, 401 challenges included, exposing the
72
+ * `WWW-Authenticate`, `Mcp-Session-Id` and `Mcp-Protocol-Version` headers.
73
+ *
74
+ * `true` allows any origin. Disabled by default, so an application keeps its own CORS middleware.
75
+ */
76
+ cors?: boolean | PlatformMcpCorsSettings;
77
+ }
78
+ /**
79
+ * CORS options of an MCP endpoint.
80
+ *
81
+ * @module platform/mcp
82
+ */
83
+ export interface PlatformMcpCorsSettings {
84
+ /**
85
+ * Origins allowed to call the endpoint: `"*"` (default) or a list of origins, echoed back when the request
86
+ * comes from one of them.
87
+ */
88
+ origin?: "*" | string[];
89
+ /**
90
+ * Seconds a browser may cache the preflight response. Defaults to `600`.
91
+ */
92
+ maxAge?: number;
69
93
  }
70
94
  declare global {
71
95
  namespace TsED {
@@ -53,7 +53,21 @@ export declare class PlatformMcpGatewayService implements OnDestroy {
53
53
  getConnection(upstream: PlatformMcpUpstreamSettings, resolved?: PlatformMcpUpstreamSettings): Promise<PlatformMcpUpstreamConnection>;
54
54
  $onDestroy(): Promise<void>;
55
55
  protected connect(upstream: PlatformMcpUpstreamSettings, entry: PoolEntry): Promise<PlatformMcpUpstreamConnection>;
56
- protected loadCatalog(client: Client): Promise<PlatformMcpUpstreamCatalog>;
56
+ /**
57
+ * Lists every catalog the upstream advertises.
58
+ *
59
+ * A listing that fails is logged and left empty so the others stay available: an upstream may advertise
60
+ * a capability it cannot serve (e.g. prompts without any prompt configured). The catalog is then flagged
61
+ * incomplete so the next request lists it again. It rejects only when every advertised listing fails.
62
+ */
63
+ protected loadCatalog(client: Client, label: string): Promise<{
64
+ catalog: PlatformMcpUpstreamCatalog;
65
+ complete: boolean;
66
+ }>;
67
+ /**
68
+ * Names the upstream in the logs without the credentials its URL may carry (userinfo, query, hash).
69
+ */
70
+ protected getLabel(upstream: PlatformMcpUpstreamSettings): string;
57
71
  protected getPool(upstream: PlatformMcpUpstreamSettings): Map<string, PoolEntry>;
58
72
  protected getKey(upstream: PlatformMcpUpstreamSettings): string;
59
73
  /**
@@ -4,3 +4,5 @@
4
4
  export * from "./exports.js";
5
5
  export * from "./services/PlatformMcpAuthService.js";
6
6
  export * from "./services/PlatformMcpModule.js";
7
+ export * from "./utils/cors.js";
8
+ export * from "./utils/methodNotAllowed.js";
@@ -20,11 +20,6 @@ export declare class PlatformMcpModule implements OnRoutesInit {
20
20
  * Rejects a configuration that cannot work or would be unsafe, before any route is mounted.
21
21
  */
22
22
  protected validate(path: string, opts: PlatformMcpSettings): void;
23
- /**
24
- * Answers the methods of the Streamable HTTP transport that a stateless endpoint does not serve,
25
- * so MCP clients know there is no event stream instead of receiving the application's 404 page.
26
- */
27
- protected methodNotAllowed($ctx: PlatformContext): import("@tsed/platform-http").PlatformResponse<any>;
28
23
  protected metadata(settings: CreateMcpServerOpts, $ctx: PlatformContext): import("@tsed/platform-http").PlatformResponse<any>;
29
24
  protected dispatch(settings: CreateMcpServerOpts, $ctx: PlatformContext): Promise<import("@tsed/platform-http").PlatformResponse<any> | undefined>;
30
25
  }
@@ -0,0 +1,36 @@
1
+ import type { PlatformContext } from "@tsed/platform-http";
2
+ import type { PlatformMcpCorsSettings } from "../../common/interfaces/PlatformMcpSettings.js";
3
+ /**
4
+ * Response headers a browser MCP client must read: the OAuth challenge and the Streamable HTTP session/version.
5
+ *
6
+ * @module platform/mcp
7
+ */
8
+ export declare const MCP_CORS_EXPOSED_HEADERS = "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version";
9
+ /**
10
+ * Request headers allowed by the preflight when the browser does not list the ones it needs.
11
+ *
12
+ * @module platform/mcp
13
+ */
14
+ export declare const MCP_CORS_ALLOWED_HEADERS = "Authorization, Content-Type, Accept, Mcp-Protocol-Version, Mcp-Session-Id, Last-Event-ID";
15
+ /**
16
+ * Returns the CORS headers of a response of an MCP endpoint, or `undefined` when CORS is disabled.
17
+ *
18
+ * With a list of origins, the request origin is echoed back only when it belongs to the list, and `Origin` is added
19
+ * to the `Vary` header already set on the response.
20
+ *
21
+ * @param cors `cors` option of the endpoint.
22
+ * @param $ctx Context of the request.
23
+ * @module platform/mcp
24
+ */
25
+ export declare function getCorsHeaders(cors: boolean | PlatformMcpCorsSettings | undefined, $ctx: PlatformContext): Record<string, string> | undefined;
26
+ /**
27
+ * Adds the CORS headers of an MCP endpoint to the response, on the framework response and on the Node.js one,
28
+ * which the MCP transport writes directly. Does nothing when CORS is disabled.
29
+ *
30
+ * @param cors `cors` option of the endpoint.
31
+ * @param $ctx Context of the request.
32
+ * @module platform/mcp
33
+ */
34
+ export declare function setCorsHeaders(cors: boolean | PlatformMcpCorsSettings | undefined, $ctx: PlatformContext): void;
35
+ export declare const cors: (cors: boolean | PlatformMcpCorsSettings | undefined) => ($ctx: PlatformContext) => void;
36
+ export declare function preflight($ctx: PlatformContext): import("@tsed/platform-http").PlatformResponse<any>;
@@ -0,0 +1,9 @@
1
+ import type { PlatformContext } from "@tsed/platform-http";
2
+ /**
3
+ * Answers the methods of the Streamable HTTP transport that a stateless endpoint does not serve,
4
+ * so MCP clients know there is no event stream instead of receiving the application's 404 page.
5
+ *
6
+ * @param $ctx Context of the request.
7
+ * @param allow Methods served by the endpoint, sent in the `Allow` header.
8
+ */
9
+ export declare function methodNotAllowed($ctx: PlatformContext, allow?: string): import("@tsed/platform-http").PlatformResponse<any>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsed/platform-mcp",
3
- "version": "8.44.13",
3
+ "version": "8.45.0",
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.44.13",
55
- "@tsed/core": "8.44.13",
56
- "@tsed/di": "8.44.13",
57
- "@tsed/exceptions": "8.44.13",
58
- "@tsed/json-mapper": "8.44.13",
59
- "@tsed/platform-http": "8.44.13",
60
- "@tsed/schema": "8.44.13",
61
- "@tsed/typescript": "8.44.13",
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",
62
62
  "jose": "^6.1.3",
63
63
  "typescript": "6.0.2",
64
64
  "vitest": "4.1.4"
@@ -67,6 +67,31 @@ export interface PlatformMcpSettings {
67
67
  * check (`preAuth`), or with both.
68
68
  */
69
69
  auth?: PlatformMcpAuthSettings | PlatformMcpPreAuthSettings;
70
+ /**
71
+ * Let MCP clients running in a browser (e.g. the MCP Inspector) call the endpoint: answers the CORS preflight
72
+ * and adds the CORS headers to every response of the endpoint, 401 challenges included, exposing the
73
+ * `WWW-Authenticate`, `Mcp-Session-Id` and `Mcp-Protocol-Version` headers.
74
+ *
75
+ * `true` allows any origin. Disabled by default, so an application keeps its own CORS middleware.
76
+ */
77
+ cors?: boolean | PlatformMcpCorsSettings;
78
+ }
79
+
80
+ /**
81
+ * CORS options of an MCP endpoint.
82
+ *
83
+ * @module platform/mcp
84
+ */
85
+ export interface PlatformMcpCorsSettings {
86
+ /**
87
+ * Origins allowed to call the endpoint: `"*"` (default) or a list of origins, echoed back when the request
88
+ * comes from one of them.
89
+ */
90
+ origin?: "*" | string[];
91
+ /**
92
+ * Seconds a browser may cache the preflight response. Defaults to `600`.
93
+ */
94
+ maxAge?: number;
70
95
  }
71
96
 
72
97
  declare global {
@@ -121,6 +121,64 @@ describe("PlatformMcpGatewayService", () => {
121
121
  expect(listTools).toHaveBeenCalledTimes(2);
122
122
  });
123
123
 
124
+ it("keeps the other listings when an advertised listing fails, and lists it again on the next request", async () => {
125
+ createUpstreamTransport.mockImplementation(async () => {
126
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
127
+ const server = new McpServer({name: "upstream", version: "1.0.0"});
128
+
129
+ server.registerTool("first", {description: "First tool"}, () => ({content: []}));
130
+ server.registerPrompt("greet", {description: "Greet"}, () => ({messages: []}));
131
+
132
+ await server.connect(serverTransport);
133
+
134
+ return clientTransport;
135
+ });
136
+ vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
137
+
138
+ const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
139
+ const error = new Error("A prompts collection must be set in settings");
140
+ const listPrompts = vi.spyOn(connection.client, "listPrompts").mockRejectedValueOnce(error);
141
+
142
+ await expect(connection.getCatalog()).resolves.toMatchObject({tools: [{name: "first"}], prompts: []});
143
+ expect(logger().warn).toHaveBeenCalledWith({
144
+ event: "MCP_GATEWAY_CATALOG_ERROR",
145
+ message: 'MCP upstream "http://localhost/mcp": unable to list prompts, they are skipped.',
146
+ error
147
+ });
148
+
149
+ await expect(connection.getCatalog()).resolves.toMatchObject({tools: [{name: "first"}], prompts: [{name: "greet"}]});
150
+ expect(listPrompts).toHaveBeenCalledTimes(2);
151
+ });
152
+
153
+ it("rejects the catalog when every advertised listing fails", async () => {
154
+ createUpstreamTransport.mockImplementation(async () => {
155
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
156
+ const server = new McpServer({name: "upstream", version: "1.0.0"});
157
+
158
+ server.registerTool("first", {description: "First tool"}, () => ({content: []}));
159
+ server.registerPrompt("greet", {description: "Greet"}, () => ({messages: []}));
160
+
161
+ await server.connect(serverTransport);
162
+
163
+ return clientTransport;
164
+ });
165
+
166
+ vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
167
+
168
+ const upstream = createUpstream({url: "https://user:secret@localhost/mcp?token=secret#hash"});
169
+ const connection = await inject(PlatformMcpGatewayService).getConnection(upstream);
170
+
171
+ vi.spyOn(connection.client, "listTools").mockRejectedValueOnce(new Error("tools failed"));
172
+ vi.spyOn(connection.client, "listPrompts").mockRejectedValueOnce(new Error("prompts failed"));
173
+
174
+ await expect(connection.getCatalog()).rejects.toThrow("tools failed");
175
+ // every failure is logged, and the label carries no credential of the URL
176
+ expect(vi.mocked(logger().warn).mock.calls.map(([log]) => (log as any).message)).toEqual([
177
+ 'MCP upstream "https://localhost/mcp": unable to list tools, they are skipped.',
178
+ 'MCP upstream "https://localhost/mcp": unable to list prompts, they are skipped.'
179
+ ]);
180
+ });
181
+
124
182
  it("refreshes the catalog when the upstream notifies a list change", async () => {
125
183
  const servers = mockUpstreamServers();
126
184
  const connection = await inject(PlatformMcpGatewayService).getConnection(createUpstream());
@@ -108,6 +108,7 @@ export class PlatformMcpGatewayService implements OnDestroy {
108
108
  protected async connect(upstream: PlatformMcpUpstreamSettings, entry: PoolEntry): Promise<PlatformMcpUpstreamConnection> {
109
109
  const {Client} = await import("@modelcontextprotocol/client");
110
110
  const transport = await createUpstreamTransport(upstream);
111
+ const label = this.getLabel(upstream);
111
112
  let catalog: Promise<PlatformMcpUpstreamCatalog> | undefined;
112
113
  const invalidate = () => {
113
114
  catalog = undefined;
@@ -148,11 +149,27 @@ export class PlatformMcpGatewayService implements OnDestroy {
148
149
  return {
149
150
  client,
150
151
  getCatalog: () => {
151
- catalog ||= this.loadCatalog(client).catch((error) => {
152
- catalog = undefined;
153
-
154
- throw error;
155
- });
152
+ if (!catalog) {
153
+ const pending: Promise<PlatformMcpUpstreamCatalog> = this.loadCatalog(client, label).then(
154
+ ({catalog: loaded, complete}) => {
155
+ // an incomplete catalog is served once and listed again on the next request
156
+ if (!complete && catalog === pending) {
157
+ catalog = undefined;
158
+ }
159
+
160
+ return loaded;
161
+ },
162
+ (error) => {
163
+ if (catalog === pending) {
164
+ catalog = undefined;
165
+ }
166
+
167
+ throw error;
168
+ }
169
+ );
170
+
171
+ catalog = pending;
172
+ }
156
173
 
157
174
  return catalog;
158
175
  },
@@ -169,17 +186,64 @@ export class PlatformMcpGatewayService implements OnDestroy {
169
186
  };
170
187
  }
171
188
 
172
- protected async loadCatalog(client: Client): Promise<PlatformMcpUpstreamCatalog> {
189
+ /**
190
+ * Lists every catalog the upstream advertises.
191
+ *
192
+ * A listing that fails is logged and left empty so the others stay available: an upstream may advertise
193
+ * a capability it cannot serve (e.g. prompts without any prompt configured). The catalog is then flagged
194
+ * incomplete so the next request lists it again. It rejects only when every advertised listing fails.
195
+ */
196
+ protected async loadCatalog(client: Client, label: string): Promise<{catalog: PlatformMcpUpstreamCatalog; complete: boolean}> {
173
197
  const capabilities = client.getServerCapabilities() || {};
198
+ const listings = [
199
+ ["tools", capabilities.tools, (params: {cursor?: string}) => client.listTools(params)],
200
+ ["resources", capabilities.resources, (params: {cursor?: string}) => client.listResources(params)],
201
+ ["resourceTemplates", capabilities.resources, (params: {cursor?: string}) => client.listResourceTemplates(params)],
202
+ ["prompts", capabilities.prompts, (params: {cursor?: string}) => client.listPrompts(params)]
203
+ ] as const;
204
+
205
+ const results = await Promise.allSettled(listings.map(([key, enabled, list]) => listAll(enabled, list, key)));
206
+ const failures = results.flatMap((result, index) =>
207
+ result.status === "rejected" ? [{key: listings[index][0], error: result.reason}] : []
208
+ );
209
+ const advertised = listings.filter(([, enabled]) => enabled).length;
210
+
211
+ failures.forEach(({key, error}) => {
212
+ logger().warn({
213
+ event: "MCP_GATEWAY_CATALOG_ERROR",
214
+ message: `MCP upstream "${label}": unable to list ${key}, they are skipped.`,
215
+ error
216
+ });
217
+ });
218
+
219
+ if (failures.length && failures.length === advertised) {
220
+ throw failures[0].error;
221
+ }
222
+
223
+ const [tools, resources, resourceTemplates, prompts] = results.map((result) => (result.status === "fulfilled" ? result.value : []));
224
+
225
+ return {
226
+ catalog: {
227
+ tools: tools as Tool[],
228
+ resources: resources as Resource[],
229
+ resourceTemplates: resourceTemplates as ResourceTemplateType[],
230
+ prompts: prompts as Prompt[]
231
+ },
232
+ complete: !failures.length
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Names the upstream in the logs without the credentials its URL may carry (userinfo, query, hash).
238
+ */
239
+ protected getLabel(upstream: PlatformMcpUpstreamSettings) {
240
+ if (upstream.type === "stdio") {
241
+ return upstream.command;
242
+ }
174
243
 
175
- const [tools, resources, resourceTemplates, prompts] = await Promise.all([
176
- listAll<Tool>(capabilities.tools, (params) => client.listTools(params), "tools"),
177
- listAll<Resource>(capabilities.resources, (params) => client.listResources(params), "resources"),
178
- listAll<ResourceTemplateType>(capabilities.resources, (params) => client.listResourceTemplates(params), "resourceTemplates"),
179
- listAll<Prompt>(capabilities.prompts, (params) => client.listPrompts(params), "prompts")
180
- ]);
244
+ const {origin, pathname} = new URL(upstream.url);
181
245
 
182
- return {tools, resources, resourceTemplates, prompts};
246
+ return `${origin}${pathname}`;
183
247
  }
184
248
 
185
249
  protected getPool(upstream: PlatformMcpUpstreamSettings) {
package/src/http/index.ts CHANGED
@@ -4,3 +4,5 @@
4
4
  export * from "./exports.js";
5
5
  export * from "./services/PlatformMcpAuthService.js";
6
6
  export * from "./services/PlatformMcpModule.js";
7
+ export * from "./utils/cors.js";
8
+ export * from "./utils/methodNotAllowed.js";
@@ -125,14 +125,92 @@ describe("PlatformMcpModule", () => {
125
125
  const status = vi.spyOn($ctx.response, "status").mockReturnThis();
126
126
  const setHeaders = vi.spyOn($ctx.response, "setHeaders").mockReturnThis();
127
127
  const body = vi.spyOn($ctx.response, "body").mockReturnThis();
128
+ const getHandler = vi.mocked(application().get).mock.calls[0][1] as unknown as (ctx: unknown) => unknown;
128
129
 
129
- module["methodNotAllowed"]($ctx);
130
+ getHandler($ctx);
130
131
 
131
132
  expect(status).toHaveBeenCalledWith(405);
132
- expect(setHeaders).toHaveBeenCalledWith({allow: "POST"});
133
+ expect(setHeaders).toHaveBeenCalledExactlyOnceWith({allow: "POST"});
133
134
  expect(body).toHaveBeenCalledWith({jsonrpc: "2.0", error: {code: -32000, message: "Method not allowed."}, id: null});
134
135
  });
135
136
 
137
+ it("does not mount the preflight route when CORS is disabled", async () => {
138
+ const {module} = await createModule();
139
+ module["settings"] = {path: "/ai/mcp"};
140
+
141
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
142
+ vi.spyOn(application(), "get").mockReturnValue(undefined as never);
143
+ vi.spyOn(application(), "delete").mockReturnValue(undefined as never);
144
+ vi.spyOn(application(), "options").mockReturnValue(undefined as never);
145
+
146
+ module.$onRoutesInit();
147
+
148
+ expect(application().options).not.toHaveBeenCalled();
149
+ });
150
+
151
+ it("adds the CORS headers on every route and answers the preflight when CORS is enabled", async () => {
152
+ const {module} = await createModule();
153
+ module["settings"] = {path: "/ai/mcp", cors: true};
154
+
155
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
156
+ vi.spyOn(application(), "get").mockReturnValue(undefined as never);
157
+ vi.spyOn(application(), "delete").mockReturnValue(undefined as never);
158
+ vi.spyOn(application(), "options").mockReturnValue(undefined as never);
159
+
160
+ module.$onRoutesInit();
161
+
162
+ expect(application().options).toHaveBeenCalledExactlyOnceWith("/ai/mcp", expect.any(Function));
163
+
164
+ const handlers = {
165
+ get: vi.mocked(application().get).mock.calls[0][1],
166
+ delete: vi.mocked(application().delete).mock.calls[0][1],
167
+ options: vi.mocked(application().options).mock.calls[0][1]
168
+ } as unknown as Record<string, (ctx: unknown) => unknown>;
169
+
170
+ for (const [method, handler] of Object.entries(handlers)) {
171
+ const {$ctx, res} = createExpressContext();
172
+ const status = vi.spyOn($ctx.response, "status").mockReturnThis();
173
+ const setHeaders = vi.spyOn($ctx.response, "setHeaders").mockReturnThis();
174
+
175
+ vi.spyOn($ctx.response, "body").mockReturnThis();
176
+ (res as unknown as {setHeader: unknown}).setHeader = vi.fn();
177
+
178
+ handler($ctx);
179
+
180
+ expect(setHeaders).toHaveBeenCalledWith(expect.objectContaining({"access-control-allow-origin": "*"}));
181
+ expect(status).toHaveBeenCalledWith(method === "options" ? 204 : 405);
182
+
183
+ if (method !== "options") {
184
+ expect(setHeaders).toHaveBeenCalledWith({allow: "POST, OPTIONS"});
185
+ }
186
+ }
187
+ });
188
+
189
+ it("adds the CORS headers before dispatching the MCP request", async () => {
190
+ const {module} = await createModule();
191
+ module["settings"] = {path: "/ai/mcp", cors: true};
192
+
193
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
194
+ vi.spyOn(application(), "get").mockReturnValue(undefined as never);
195
+ vi.spyOn(application(), "delete").mockReturnValue(undefined as never);
196
+ vi.spyOn(application(), "options").mockReturnValue(undefined as never);
197
+ const dispatch = vi.spyOn(module as any, "dispatch").mockResolvedValue(undefined);
198
+
199
+ module.$onRoutesInit();
200
+
201
+ const postHandler = vi.mocked(application().post).mock.calls[0][1] as unknown as (ctx: unknown) => Promise<unknown>;
202
+ const {$ctx, res} = createExpressContext();
203
+ const setHeaders = vi.spyOn($ctx.response, "setHeaders").mockReturnThis();
204
+
205
+ (res as unknown as {setHeader: unknown}).setHeader = vi.fn();
206
+
207
+ await postHandler($ctx);
208
+
209
+ expect(setHeaders).toHaveBeenCalledWith(expect.objectContaining({"access-control-allow-origin": "*"}));
210
+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({path: "/ai/mcp", cors: true}), $ctx);
211
+ expect(setHeaders.mock.invocationCallOrder[0]).toBeLessThan(dispatch.mock.invocationCallOrder[0]);
212
+ });
213
+
136
214
  it("should register the MCP route only once", async () => {
137
215
  const {module} = await createModule();
138
216
 
@@ -7,7 +7,9 @@ import {useContextHandler} from "@tsed/platform-router";
7
7
  import {attachUpstream} from "../../common/utils/attachUpstream.js";
8
8
  import {hasUpstreamPlaceholders} from "../../common/utils/resolveUpstream.js";
9
9
  import {createMcpServer, type CreateMcpServerOpts, resolveMcpServerOptions} from "../../common/utils/createMcpServer.js";
10
+ import {cors, preflight} from "../utils/cors.js";
10
11
  import {PlatformMcpAuthService} from "./PlatformMcpAuthService.js";
12
+ import {methodNotAllowed} from "../utils/methodNotAllowed.js";
11
13
 
12
14
  /**
13
15
  * Platform module that mounts the MCP HTTP endpoint and forwards requests to the configured server instance.
@@ -58,9 +60,15 @@ export class PlatformMcpModule implements OnRoutesInit {
58
60
  } as PlatformRouteDetails);
59
61
  }
60
62
 
63
+ const corsMiddleware = cors(resolvedSettings.cors);
64
+ const allow = opts.cors ? "POST, OPTIONS" : "POST";
65
+
61
66
  this.app.post(
62
67
  path,
63
- useContextHandler(async ($ctx) => this.dispatch(resolvedSettings, $ctx as PlatformContext))
68
+ useContextHandler(async ($ctx) => {
69
+ corsMiddleware($ctx as PlatformContext);
70
+ return this.dispatch(resolvedSettings, $ctx as PlatformContext);
71
+ })
64
72
  );
65
73
 
66
74
  this.mcps.push({
@@ -72,12 +80,32 @@ export class PlatformMcpModule implements OnRoutesInit {
72
80
  // the endpoint is stateless: there is no event stream to open nor session to delete
73
81
  this.app.get(
74
82
  path,
75
- useContextHandler(($ctx) => this.methodNotAllowed($ctx as PlatformContext))
83
+ useContextHandler(($ctx) => {
84
+ corsMiddleware($ctx as PlatformContext);
85
+
86
+ return methodNotAllowed($ctx as PlatformContext, allow);
87
+ })
76
88
  );
89
+
77
90
  this.app.delete(
78
91
  path,
79
- useContextHandler(($ctx) => this.methodNotAllowed($ctx as PlatformContext))
92
+ useContextHandler(($ctx) => {
93
+ corsMiddleware($ctx as PlatformContext);
94
+
95
+ return methodNotAllowed($ctx as PlatformContext, allow);
96
+ })
80
97
  );
98
+
99
+ if (opts.cors) {
100
+ this.app.options(
101
+ path,
102
+ useContextHandler(($ctx) => {
103
+ corsMiddleware($ctx as PlatformContext);
104
+
105
+ return preflight($ctx as PlatformContext);
106
+ })
107
+ );
108
+ }
81
109
  }
82
110
 
83
111
  this.loaded = true;
@@ -104,17 +132,6 @@ export class PlatformMcpModule implements OnRoutesInit {
104
132
  }
105
133
  }
106
134
 
107
- /**
108
- * Answers the methods of the Streamable HTTP transport that a stateless endpoint does not serve,
109
- * so MCP clients know there is no event stream instead of receiving the application's 404 page.
110
- */
111
- protected methodNotAllowed($ctx: PlatformContext) {
112
- return $ctx.response
113
- .status(405)
114
- .setHeaders({allow: "POST"})
115
- .body({jsonrpc: "2.0", error: {code: -32000, message: "Method not allowed."}, id: null});
116
- }
117
-
118
135
  protected metadata(settings: CreateMcpServerOpts, $ctx: PlatformContext) {
119
136
  const auth = settings.auth as PlatformMcpAuthSettings;
120
137
  const resource = this.platformAuthService.getResourceUrl(auth);