@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.
@@ -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
+ }