@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.
@@ -56,6 +56,7 @@ export class PlatformMcpGatewayService {
56
56
  async connect(upstream, entry) {
57
57
  const { Client } = await import("@modelcontextprotocol/client");
58
58
  const transport = await createUpstreamTransport(upstream);
59
+ const label = this.getLabel(upstream);
59
60
  let catalog;
60
61
  const invalidate = () => {
61
62
  catalog = undefined;
@@ -87,10 +88,21 @@ export class PlatformMcpGatewayService {
87
88
  return {
88
89
  client,
89
90
  getCatalog: () => {
90
- catalog ||= this.loadCatalog(client).catch((error) => {
91
- catalog = undefined;
92
- throw error;
93
- });
91
+ if (!catalog) {
92
+ const pending = this.loadCatalog(client, label).then(({ catalog: loaded, complete }) => {
93
+ // an incomplete catalog is served once and listed again on the next request
94
+ if (!complete && catalog === pending) {
95
+ catalog = undefined;
96
+ }
97
+ return loaded;
98
+ }, (error) => {
99
+ if (catalog === pending) {
100
+ catalog = undefined;
101
+ }
102
+ throw error;
103
+ });
104
+ catalog = pending;
105
+ }
94
106
  return catalog;
95
107
  },
96
108
  run: async (fn) => {
@@ -105,15 +117,54 @@ export class PlatformMcpGatewayService {
105
117
  }
106
118
  };
107
119
  }
108
- async loadCatalog(client) {
120
+ /**
121
+ * Lists every catalog the upstream advertises.
122
+ *
123
+ * A listing that fails is logged and left empty so the others stay available: an upstream may advertise
124
+ * a capability it cannot serve (e.g. prompts without any prompt configured). The catalog is then flagged
125
+ * incomplete so the next request lists it again. It rejects only when every advertised listing fails.
126
+ */
127
+ async loadCatalog(client, label) {
109
128
  const capabilities = client.getServerCapabilities() || {};
110
- const [tools, resources, resourceTemplates, prompts] = await Promise.all([
111
- listAll(capabilities.tools, (params) => client.listTools(params), "tools"),
112
- listAll(capabilities.resources, (params) => client.listResources(params), "resources"),
113
- listAll(capabilities.resources, (params) => client.listResourceTemplates(params), "resourceTemplates"),
114
- listAll(capabilities.prompts, (params) => client.listPrompts(params), "prompts")
115
- ]);
116
- return { tools, resources, resourceTemplates, prompts };
129
+ const listings = [
130
+ ["tools", capabilities.tools, (params) => client.listTools(params)],
131
+ ["resources", capabilities.resources, (params) => client.listResources(params)],
132
+ ["resourceTemplates", capabilities.resources, (params) => client.listResourceTemplates(params)],
133
+ ["prompts", capabilities.prompts, (params) => client.listPrompts(params)]
134
+ ];
135
+ const results = await Promise.allSettled(listings.map(([key, enabled, list]) => listAll(enabled, list, key)));
136
+ const failures = results.flatMap((result, index) => result.status === "rejected" ? [{ key: listings[index][0], error: result.reason }] : []);
137
+ const advertised = listings.filter(([, enabled]) => enabled).length;
138
+ failures.forEach(({ key, error }) => {
139
+ logger().warn({
140
+ event: "MCP_GATEWAY_CATALOG_ERROR",
141
+ message: `MCP upstream "${label}": unable to list ${key}, they are skipped.`,
142
+ error
143
+ });
144
+ });
145
+ if (failures.length && failures.length === advertised) {
146
+ throw failures[0].error;
147
+ }
148
+ const [tools, resources, resourceTemplates, prompts] = results.map((result) => (result.status === "fulfilled" ? result.value : []));
149
+ return {
150
+ catalog: {
151
+ tools: tools,
152
+ resources: resources,
153
+ resourceTemplates: resourceTemplates,
154
+ prompts: prompts
155
+ },
156
+ complete: !failures.length
157
+ };
158
+ }
159
+ /**
160
+ * Names the upstream in the logs without the credentials its URL may carry (userinfo, query, hash).
161
+ */
162
+ getLabel(upstream) {
163
+ if (upstream.type === "stdio") {
164
+ return upstream.command;
165
+ }
166
+ const { origin, pathname } = new URL(upstream.url);
167
+ return `${origin}${pathname}`;
117
168
  }
118
169
  getPool(upstream) {
119
170
  let pool = this.pools.get(upstream);
@@ -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";
@@ -5,7 +5,9 @@ import { useContextHandler } from "@tsed/platform-router";
5
5
  import { attachUpstream } from "../../common/utils/attachUpstream.js";
6
6
  import { hasUpstreamPlaceholders } from "../../common/utils/resolveUpstream.js";
7
7
  import { createMcpServer, resolveMcpServerOptions } from "../../common/utils/createMcpServer.js";
8
+ import { cors, preflight } from "../utils/cors.js";
8
9
  import { PlatformMcpAuthService } from "./PlatformMcpAuthService.js";
10
+ import { methodNotAllowed } from "../utils/methodNotAllowed.js";
9
11
  /**
10
12
  * Platform module that mounts the MCP HTTP endpoint and forwards requests to the configured server instance.
11
13
  *
@@ -44,15 +46,32 @@ export class PlatformMcpModule {
44
46
  url: metadataPath
45
47
  });
46
48
  }
47
- this.app.post(path, useContextHandler(async ($ctx) => this.dispatch(resolvedSettings, $ctx)));
49
+ const corsMiddleware = cors(resolvedSettings.cors);
50
+ const allow = opts.cors ? "POST, OPTIONS" : "POST";
51
+ this.app.post(path, useContextHandler(async ($ctx) => {
52
+ corsMiddleware($ctx);
53
+ return this.dispatch(resolvedSettings, $ctx);
54
+ }));
48
55
  this.mcps.push({
49
56
  method: "POST",
50
57
  name: "PlatformMcpModule.dispatch()",
51
58
  url: path
52
59
  });
53
60
  // the endpoint is stateless: there is no event stream to open nor session to delete
54
- this.app.get(path, useContextHandler(($ctx) => this.methodNotAllowed($ctx)));
55
- this.app.delete(path, useContextHandler(($ctx) => this.methodNotAllowed($ctx)));
61
+ this.app.get(path, useContextHandler(($ctx) => {
62
+ corsMiddleware($ctx);
63
+ return methodNotAllowed($ctx, allow);
64
+ }));
65
+ this.app.delete(path, useContextHandler(($ctx) => {
66
+ corsMiddleware($ctx);
67
+ return methodNotAllowed($ctx, allow);
68
+ }));
69
+ if (opts.cors) {
70
+ this.app.options(path, useContextHandler(($ctx) => {
71
+ corsMiddleware($ctx);
72
+ return preflight($ctx);
73
+ }));
74
+ }
56
75
  }
57
76
  this.loaded = true;
58
77
  }
@@ -74,16 +93,6 @@ export class PlatformMcpModule {
74
93
  throw new Error(`MCP endpoint "${path}": the upstream uses \${OAUTH_*} placeholders but the endpoint declares no auth.`);
75
94
  }
76
95
  }
77
- /**
78
- * Answers the methods of the Streamable HTTP transport that a stateless endpoint does not serve,
79
- * so MCP clients know there is no event stream instead of receiving the application's 404 page.
80
- */
81
- methodNotAllowed($ctx) {
82
- return $ctx.response
83
- .status(405)
84
- .setHeaders({ allow: "POST" })
85
- .body({ jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed." }, id: null });
86
- }
87
96
  metadata(settings, $ctx) {
88
97
  const auth = settings.auth;
89
98
  const resource = this.platformAuthService.getResourceUrl(auth);
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Response headers a browser MCP client must read: the OAuth challenge and the Streamable HTTP session/version.
3
+ *
4
+ * @module platform/mcp
5
+ */
6
+ export const MCP_CORS_EXPOSED_HEADERS = "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version";
7
+ /**
8
+ * Request headers allowed by the preflight when the browser does not list the ones it needs.
9
+ *
10
+ * @module platform/mcp
11
+ */
12
+ export const MCP_CORS_ALLOWED_HEADERS = "Authorization, Content-Type, Accept, Mcp-Protocol-Version, Mcp-Session-Id, Last-Event-ID";
13
+ const DEFAULT_MAX_AGE = 600;
14
+ function appendVary(vary) {
15
+ const values = [vary ?? []]
16
+ .flat()
17
+ .flatMap((value) => String(value).split(","))
18
+ .map((value) => value.trim())
19
+ .filter(Boolean);
20
+ return values.some((value) => value === "*" || value.toLowerCase() === "origin") ? values.join(", ") : [...values, "Origin"].join(", ");
21
+ }
22
+ function normalize(cors) {
23
+ if (!cors) {
24
+ return undefined;
25
+ }
26
+ return cors === true ? {} : cors;
27
+ }
28
+ /**
29
+ * Returns the CORS headers of a response of an MCP endpoint, or `undefined` when CORS is disabled.
30
+ *
31
+ * With a list of origins, the request origin is echoed back only when it belongs to the list, and `Origin` is added
32
+ * to the `Vary` header already set on the response.
33
+ *
34
+ * @param cors `cors` option of the endpoint.
35
+ * @param $ctx Context of the request.
36
+ * @module platform/mcp
37
+ */
38
+ export function getCorsHeaders(cors, $ctx) {
39
+ const settings = normalize(cors);
40
+ if (!settings) {
41
+ return undefined;
42
+ }
43
+ const { origin: allowed = "*" } = settings;
44
+ const origin = $ctx.request.get("origin");
45
+ const headers = { "access-control-expose-headers": MCP_CORS_EXPOSED_HEADERS };
46
+ if (allowed === "*") {
47
+ headers["access-control-allow-origin"] = "*";
48
+ }
49
+ else {
50
+ headers.vary = appendVary($ctx.response.get("vary"));
51
+ if (origin && allowed.includes(origin)) {
52
+ headers["access-control-allow-origin"] = origin;
53
+ }
54
+ }
55
+ if ($ctx.request.method === "OPTIONS") {
56
+ headers["access-control-allow-methods"] = "GET, POST, DELETE, OPTIONS";
57
+ headers["access-control-allow-headers"] = $ctx.request.get("access-control-request-headers") || MCP_CORS_ALLOWED_HEADERS;
58
+ headers["access-control-max-age"] = String(settings.maxAge ?? DEFAULT_MAX_AGE);
59
+ }
60
+ return headers;
61
+ }
62
+ /**
63
+ * Adds the CORS headers of an MCP endpoint to the response, on the framework response and on the Node.js one,
64
+ * which the MCP transport writes directly. Does nothing when CORS is disabled.
65
+ *
66
+ * @param cors `cors` option of the endpoint.
67
+ * @param $ctx Context of the request.
68
+ * @module platform/mcp
69
+ */
70
+ export function setCorsHeaders(cors, $ctx) {
71
+ const headers = getCorsHeaders(cors, $ctx);
72
+ if (!headers) {
73
+ return;
74
+ }
75
+ $ctx.response.setHeaders(headers);
76
+ const res = $ctx.getRes();
77
+ Object.entries(headers).forEach(([name, value]) => res?.setHeader?.(name, value));
78
+ }
79
+ export const cors = (cors) => ($ctx) => setCorsHeaders(cors, $ctx);
80
+ export function preflight($ctx) {
81
+ return $ctx.response.status(204).body(undefined);
82
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Answers the methods of the Streamable HTTP transport that a stateless endpoint does not serve,
3
+ * so MCP clients know there is no event stream instead of receiving the application's 404 page.
4
+ *
5
+ * @param $ctx Context of the request.
6
+ * @param allow Methods served by the endpoint, sent in the `Allow` header.
7
+ */
8
+ export function methodNotAllowed($ctx, allow = "POST") {
9
+ return $ctx.response
10
+ .status(405)
11
+ .setHeaders({ allow })
12
+ .body({ jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed." }, id: null });
13
+ }