@tsed/platform-mcp 8.44.14 → 8.45.1

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 {
@@ -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.14",
3
+ "version": "8.45.1",
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.14",
55
- "@tsed/core": "8.44.14",
56
- "@tsed/di": "8.44.14",
57
- "@tsed/exceptions": "8.44.14",
58
- "@tsed/json-mapper": "8.44.14",
59
- "@tsed/platform-http": "8.44.14",
60
- "@tsed/schema": "8.44.14",
61
- "@tsed/typescript": "8.44.14",
54
+ "@tsed/barrels": "8.45.1",
55
+ "@tsed/core": "8.45.1",
56
+ "@tsed/di": "8.45.1",
57
+ "@tsed/exceptions": "8.45.1",
58
+ "@tsed/json-mapper": "8.45.1",
59
+ "@tsed/platform-http": "8.45.1",
60
+ "@tsed/schema": "8.45.1",
61
+ "@tsed/typescript": "8.45.1",
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 {
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);
@@ -0,0 +1,143 @@
1
+ import {PlatformTest} from "@tsed/platform-http/testing";
2
+ import {cors, getCorsHeaders, MCP_CORS_ALLOWED_HEADERS, MCP_CORS_EXPOSED_HEADERS, preflight, setCorsHeaders} from "./cors.js";
3
+
4
+ function createContext(method = "POST", headers: Record<string, string> = {}) {
5
+ return PlatformTest.createRequestContext({
6
+ event: {
7
+ request: PlatformTest.createRequest({method, headers})
8
+ }
9
+ });
10
+ }
11
+
12
+ describe("cors", () => {
13
+ beforeEach(() => PlatformTest.create());
14
+ afterEach(() => PlatformTest.reset());
15
+
16
+ describe("getCorsHeaders()", () => {
17
+ it.each([undefined, false])("returns nothing when CORS is disabled (%s)", (cors) => {
18
+ expect(getCorsHeaders(cors, createContext())).toBeUndefined();
19
+ });
20
+
21
+ it("allows any origin with `true`", () => {
22
+ expect(getCorsHeaders(true, createContext("POST", {origin: "https://app.example.com"}))).toEqual({
23
+ "access-control-allow-origin": "*",
24
+ "access-control-expose-headers": MCP_CORS_EXPOSED_HEADERS
25
+ });
26
+ });
27
+
28
+ it("echoes an origin of the list", () => {
29
+ expect(getCorsHeaders({origin: ["https://app.example.com"]}, createContext("POST", {origin: "https://app.example.com"}))).toEqual({
30
+ "access-control-allow-origin": "https://app.example.com",
31
+ "access-control-expose-headers": MCP_CORS_EXPOSED_HEADERS,
32
+ vary: "Origin"
33
+ });
34
+ });
35
+
36
+ it("does not allow an origin outside the list", () => {
37
+ const headers = getCorsHeaders({origin: ["https://app.example.com"]}, createContext("POST", {origin: "https://evil.example.com"}));
38
+
39
+ expect(headers).not.toHaveProperty("access-control-allow-origin");
40
+ expect(headers).toMatchObject({vary: "Origin"});
41
+ });
42
+
43
+ it.each([
44
+ ["Accept-Encoding", "Accept-Encoding, Origin"],
45
+ [["Accept-Encoding", "Cookie"], "Accept-Encoding, Cookie, Origin"],
46
+ ["Accept-Encoding, origin", "Accept-Encoding, origin"],
47
+ ["*", "*"]
48
+ ])("adds Origin to the Vary header already set (%s)", (vary, expected) => {
49
+ const $ctx = createContext("POST", {origin: "https://app.example.com"});
50
+
51
+ vi.spyOn($ctx.response, "get").mockReturnValue(vary);
52
+
53
+ expect(getCorsHeaders({origin: ["https://app.example.com"]}, $ctx)).toMatchObject({vary: expected});
54
+ expect($ctx.response.get).toHaveBeenCalledWith("vary");
55
+ });
56
+
57
+ it("adds the preflight headers to an OPTIONS request, allowing the requested headers", () => {
58
+ const $ctx = createContext("OPTIONS", {origin: "https://app.example.com", "access-control-request-headers": "authorization"});
59
+
60
+ expect(getCorsHeaders({maxAge: 60}, $ctx)).toMatchObject({
61
+ "access-control-allow-methods": "GET, POST, DELETE, OPTIONS",
62
+ "access-control-allow-headers": "authorization",
63
+ "access-control-max-age": "60"
64
+ });
65
+ });
66
+
67
+ it("allows the MCP headers by default in a preflight", () => {
68
+ expect(getCorsHeaders(true, createContext("OPTIONS"))).toMatchObject({
69
+ "access-control-allow-headers": MCP_CORS_ALLOWED_HEADERS,
70
+ "access-control-max-age": "600"
71
+ });
72
+ });
73
+ });
74
+
75
+ describe("setCorsHeaders()", () => {
76
+ it("sets the headers on the framework response and on the Node.js response", () => {
77
+ const $ctx = createContext();
78
+ const res = {setHeader: vi.fn()};
79
+
80
+ vi.spyOn($ctx.response, "setHeaders").mockReturnThis();
81
+ vi.spyOn($ctx, "getRes").mockReturnValue(res as never);
82
+
83
+ setCorsHeaders(true, $ctx);
84
+
85
+ expect($ctx.response.setHeaders).toHaveBeenCalledWith({
86
+ "access-control-allow-origin": "*",
87
+ "access-control-expose-headers": MCP_CORS_EXPOSED_HEADERS
88
+ });
89
+ expect(res.setHeader).toHaveBeenCalledWith("access-control-allow-origin", "*");
90
+ expect(res.setHeader).toHaveBeenCalledWith("access-control-expose-headers", MCP_CORS_EXPOSED_HEADERS);
91
+ });
92
+
93
+ it("leaves the response untouched when CORS is disabled", () => {
94
+ const $ctx = createContext();
95
+
96
+ vi.spyOn($ctx.response, "setHeaders");
97
+
98
+ setCorsHeaders(undefined, $ctx);
99
+
100
+ expect($ctx.response.setHeaders).not.toHaveBeenCalled();
101
+ });
102
+ });
103
+
104
+ describe("cors()", () => {
105
+ it("returns a handler that sets the CORS headers of the given option on each context", () => {
106
+ const handler = cors({origin: ["https://app.example.com"]});
107
+ const $ctx = createContext("POST", {origin: "https://app.example.com"});
108
+
109
+ vi.spyOn($ctx.response, "setHeaders").mockReturnThis();
110
+ vi.spyOn($ctx, "getRes").mockReturnValue({setHeader: vi.fn()} as never);
111
+
112
+ handler($ctx);
113
+
114
+ expect($ctx.response.setHeaders).toHaveBeenCalledWith({
115
+ "access-control-allow-origin": "https://app.example.com",
116
+ "access-control-expose-headers": MCP_CORS_EXPOSED_HEADERS,
117
+ vary: "Origin"
118
+ });
119
+ });
120
+
121
+ it("returns a handler that leaves the response untouched when CORS is disabled", () => {
122
+ const $ctx = createContext();
123
+
124
+ vi.spyOn($ctx.response, "setHeaders");
125
+
126
+ cors(undefined)($ctx);
127
+
128
+ expect($ctx.response.setHeaders).not.toHaveBeenCalled();
129
+ });
130
+ });
131
+
132
+ describe("preflight()", () => {
133
+ it("answers 204 without body", () => {
134
+ const $ctx = createContext("OPTIONS");
135
+ const status = vi.spyOn($ctx.response, "status").mockReturnThis();
136
+ const body = vi.spyOn($ctx.response, "body").mockReturnThis();
137
+
138
+ expect(preflight($ctx)).toBe($ctx.response);
139
+ expect(status).toHaveBeenCalledWith(204);
140
+ expect(body).toHaveBeenCalledWith(undefined);
141
+ });
142
+ });
143
+ });
@@ -0,0 +1,104 @@
1
+ import type {PlatformContext} from "@tsed/platform-http";
2
+ import type {PlatformMcpCorsSettings} from "../../common/interfaces/PlatformMcpSettings.js";
3
+
4
+ /**
5
+ * Response headers a browser MCP client must read: the OAuth challenge and the Streamable HTTP session/version.
6
+ *
7
+ * @module platform/mcp
8
+ */
9
+ export const MCP_CORS_EXPOSED_HEADERS = "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version";
10
+
11
+ /**
12
+ * Request headers allowed by the preflight when the browser does not list the ones it needs.
13
+ *
14
+ * @module platform/mcp
15
+ */
16
+ export const MCP_CORS_ALLOWED_HEADERS = "Authorization, Content-Type, Accept, Mcp-Protocol-Version, Mcp-Session-Id, Last-Event-ID";
17
+
18
+ const DEFAULT_MAX_AGE = 600;
19
+
20
+ function appendVary(vary: unknown) {
21
+ const values = [vary ?? []]
22
+ .flat()
23
+ .flatMap((value) => String(value).split(","))
24
+ .map((value) => value.trim())
25
+ .filter(Boolean);
26
+
27
+ return values.some((value) => value === "*" || value.toLowerCase() === "origin") ? values.join(", ") : [...values, "Origin"].join(", ");
28
+ }
29
+
30
+ function normalize(cors?: boolean | PlatformMcpCorsSettings): PlatformMcpCorsSettings | undefined {
31
+ if (!cors) {
32
+ return undefined;
33
+ }
34
+
35
+ return cors === true ? {} : cors;
36
+ }
37
+
38
+ /**
39
+ * Returns the CORS headers of a response of an MCP endpoint, or `undefined` when CORS is disabled.
40
+ *
41
+ * With a list of origins, the request origin is echoed back only when it belongs to the list, and `Origin` is added
42
+ * to the `Vary` header already set on the response.
43
+ *
44
+ * @param cors `cors` option of the endpoint.
45
+ * @param $ctx Context of the request.
46
+ * @module platform/mcp
47
+ */
48
+ export function getCorsHeaders(cors: boolean | PlatformMcpCorsSettings | undefined, $ctx: PlatformContext) {
49
+ const settings = normalize(cors);
50
+
51
+ if (!settings) {
52
+ return undefined;
53
+ }
54
+
55
+ const {origin: allowed = "*"} = settings;
56
+ const origin = $ctx.request.get("origin");
57
+ const headers: Record<string, string> = {"access-control-expose-headers": MCP_CORS_EXPOSED_HEADERS};
58
+
59
+ if (allowed === "*") {
60
+ headers["access-control-allow-origin"] = "*";
61
+ } else {
62
+ headers.vary = appendVary($ctx.response.get("vary"));
63
+
64
+ if (origin && allowed.includes(origin)) {
65
+ headers["access-control-allow-origin"] = origin;
66
+ }
67
+ }
68
+
69
+ if ($ctx.request.method === "OPTIONS") {
70
+ headers["access-control-allow-methods"] = "GET, POST, DELETE, OPTIONS";
71
+ headers["access-control-allow-headers"] = $ctx.request.get("access-control-request-headers") || MCP_CORS_ALLOWED_HEADERS;
72
+ headers["access-control-max-age"] = String(settings.maxAge ?? DEFAULT_MAX_AGE);
73
+ }
74
+
75
+ return headers;
76
+ }
77
+
78
+ /**
79
+ * Adds the CORS headers of an MCP endpoint to the response, on the framework response and on the Node.js one,
80
+ * which the MCP transport writes directly. Does nothing when CORS is disabled.
81
+ *
82
+ * @param cors `cors` option of the endpoint.
83
+ * @param $ctx Context of the request.
84
+ * @module platform/mcp
85
+ */
86
+ export function setCorsHeaders(cors: boolean | PlatformMcpCorsSettings | undefined, $ctx: PlatformContext) {
87
+ const headers = getCorsHeaders(cors, $ctx);
88
+
89
+ if (!headers) {
90
+ return;
91
+ }
92
+
93
+ $ctx.response.setHeaders(headers);
94
+
95
+ const res = $ctx.getRes();
96
+
97
+ Object.entries(headers).forEach(([name, value]) => res?.setHeader?.(name, value));
98
+ }
99
+
100
+ export const cors = (cors: boolean | PlatformMcpCorsSettings | undefined) => ($ctx: PlatformContext) => setCorsHeaders(cors, $ctx);
101
+
102
+ export function preflight($ctx: PlatformContext) {
103
+ return $ctx.response.status(204).body(undefined);
104
+ }
@@ -0,0 +1,31 @@
1
+ import {PlatformTest} from "@tsed/platform-http/testing";
2
+ import {methodNotAllowed} from "./methodNotAllowed.js";
3
+
4
+ describe("methodNotAllowed()", () => {
5
+ beforeEach(() => PlatformTest.create());
6
+ afterEach(() => PlatformTest.reset());
7
+
8
+ it("answers 405 with the allowed method and a JSON-RPC error", () => {
9
+ const $ctx = PlatformTest.createRequestContext();
10
+ const status = vi.spyOn($ctx.response, "status").mockReturnThis();
11
+ const setHeaders = vi.spyOn($ctx.response, "setHeaders").mockReturnThis();
12
+ const body = vi.spyOn($ctx.response, "body").mockReturnThis();
13
+
14
+ expect(methodNotAllowed($ctx)).toBe($ctx.response);
15
+ expect(status).toHaveBeenCalledWith(405);
16
+ expect(setHeaders).toHaveBeenCalledWith({allow: "POST"});
17
+ expect(body).toHaveBeenCalledWith({jsonrpc: "2.0", error: {code: -32000, message: "Method not allowed."}, id: null});
18
+ });
19
+
20
+ it("lists the given methods in the Allow header", () => {
21
+ const $ctx = PlatformTest.createRequestContext();
22
+ const setHeaders = vi.spyOn($ctx.response, "setHeaders").mockReturnThis();
23
+
24
+ vi.spyOn($ctx.response, "status").mockReturnThis();
25
+ vi.spyOn($ctx.response, "body").mockReturnThis();
26
+
27
+ methodNotAllowed($ctx, "POST, OPTIONS");
28
+
29
+ expect(setHeaders).toHaveBeenCalledWith({allow: "POST, OPTIONS"});
30
+ });
31
+ });
@@ -0,0 +1,15 @@
1
+ import type {PlatformContext} from "@tsed/platform-http";
2
+
3
+ /**
4
+ * Answers the methods of the Streamable HTTP transport that a stateless endpoint does not serve,
5
+ * so MCP clients know there is no event stream instead of receiving the application's 404 page.
6
+ *
7
+ * @param $ctx Context of the request.
8
+ * @param allow Methods served by the endpoint, sent in the `Allow` header.
9
+ */
10
+ export function methodNotAllowed($ctx: PlatformContext, allow = "POST") {
11
+ return $ctx.response
12
+ .status(405)
13
+ .setHeaders({allow})
14
+ .body({jsonrpc: "2.0", error: {code: -32000, message: "Method not allowed."}, id: null});
15
+ }