@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
@@ -1,4 +1,6 @@
1
1
  import { constant, logger } from "@tsed/di";
2
+ import { attachUpstream } from "../../common/utils/attachUpstream.js";
3
+ import { hasUpstreamPlaceholders } from "../../common/utils/resolveUpstream.js";
2
4
  import { createMcpServer, resolveMcpServerOptions } from "../../common/utils/createMcpServer.js";
3
5
  import { mcpStdioServer } from "./mcpStdioServer.js";
4
6
  import { mcpStreamableServer } from "./mcpStreamableServer.js";
@@ -10,7 +12,21 @@ export async function mcpServerConnect(mode) {
10
12
  const options = resolveMcpServerOptions(settings);
11
13
  if (mode === "streamable-http") {
12
14
  logger().info({ event: "MCP_SERVER_CONNECT", mode });
13
- return mcpStreamableServer(() => createMcpServer(options));
15
+ if (options.upstream && hasUpstreamPlaceholders(options.upstream)) {
16
+ // the CLI endpoint is not protected by OAuth, so there is no caller identity to interpolate
17
+ throw new Error("The MCP CLI does not support ${OAUTH_*} placeholders in the upstream configuration.");
18
+ }
19
+ return mcpStreamableServer(async () => {
20
+ const server = createMcpServer(options);
21
+ await attachUpstream(server, options);
22
+ return server;
23
+ });
24
+ }
25
+ if (options.upstream) {
26
+ logger().warn({
27
+ event: "MCP_SERVER_CONNECT",
28
+ message: "The MCP upstream is only exposed in streamable-http mode and is ignored in stdio mode."
29
+ });
14
30
  }
15
31
  const server = createMcpServer(options);
16
32
  await mcpStdioServer(server);
@@ -6,7 +6,7 @@ export async function mcpStreamableServer(createServer) {
6
6
  const app = express();
7
7
  app.use(express.json());
8
8
  app.post("/mcp", async (req, res) => {
9
- const server = createServer();
9
+ const server = await createServer();
10
10
  const transport = new NodeStreamableHTTPServerTransport({
11
11
  sessionIdGenerator: undefined,
12
12
  enableJsonResponse: true
@@ -0,0 +1,169 @@
1
+ import { createHash } from "node:crypto";
2
+ import { OAuthError } from "@modelcontextprotocol/server";
3
+ import { isFunction } from "@tsed/core";
4
+ import { inject } from "@tsed/di";
5
+ import { PlatformInvalidToken } from "../errors/PlatformInvalidToken.js";
6
+ import { PlatformServerError } from "../errors/PlatformServerError.js";
7
+ const DEFAULT_CACHE_TTL = 60;
8
+ const MAX_CACHE_SIZE = 1000;
9
+ // oauth4webapi failures caused by the authorization server or the configuration, not by the presented token
10
+ const SERVER_ERROR_CODES = [
11
+ "OAUTH_RESPONSE_IS_NOT_JSON",
12
+ "OAUTH_RESPONSE_IS_NOT_CONFORM",
13
+ "OAUTH_MISSING_SERVER_METADATA",
14
+ "OAUTH_INVALID_SERVER_METADATA",
15
+ "OAUTH_HTTP_REQUEST_FORBIDDEN",
16
+ "OAUTH_REQUEST_PROTOCOL_FORBIDDEN"
17
+ ];
18
+ /**
19
+ * Access token verifier of a protected MCP endpoint.
20
+ *
21
+ * - `offline`: validates the JWT access token (RFC 9068) against the authorization server JWKS, plus issuer, audience and expiration.
22
+ * - `introspection`: asks the authorization server (RFC 7662) with the endpoint's client credentials.
23
+ * - `auth.verifier`: delegates to the custom verifier, replacing the built-in modes.
24
+ *
25
+ * The built-in modes rely on `oauth4webapi`, imported lazily.
26
+ *
27
+ * @module platform/mcp
28
+ */
29
+ export class PlatformTokenVerifier {
30
+ /**
31
+ * @param auth Auth settings of the endpoint.
32
+ * @param resource Canonical URL of the endpoint, used as the expected audience unless `auth.audience` is set.
33
+ */
34
+ constructor(auth, resource) {
35
+ this.auth = auth;
36
+ this.resource = resource;
37
+ this.cache = new Map();
38
+ this.audience = auth.audience ?? resource.href;
39
+ this.mode = PlatformTokenVerifier.getMode(auth);
40
+ }
41
+ /**
42
+ * Verification mode of an endpoint: explicit `mode`, else introspection when client credentials are configured.
43
+ */
44
+ static getMode(auth) {
45
+ return auth.mode || (auth.clientId ? "introspection" : "offline");
46
+ }
47
+ verifyAccessToken(token) {
48
+ if (this.auth.verifier) {
49
+ return this.verifyWithCustomVerifier(token);
50
+ }
51
+ return this.mode === "introspection" ? this.verifyWithIntrospection(token) : this.verifyOffline(token);
52
+ }
53
+ async verifyWithCustomVerifier(token) {
54
+ const { verifier } = this.auth;
55
+ const instance = isFunction(verifier.verifyAccessToken)
56
+ ? verifier
57
+ : inject(verifier);
58
+ try {
59
+ return await instance.verifyAccessToken(token);
60
+ }
61
+ catch (error) {
62
+ // any verifier failure means the token cannot be trusted: answer with a 401 challenge without leaking the cause
63
+ throw error instanceof OAuthError ? error : new PlatformInvalidToken("Invalid access token");
64
+ }
65
+ }
66
+ async verifyWithIntrospection(token) {
67
+ const key = createHash("sha256").update(token).digest("hex");
68
+ const now = Date.now();
69
+ const cached = this.cache.get(key);
70
+ if (cached && cached.until > now) {
71
+ return cached.authInfo;
72
+ }
73
+ this.cache.delete(key);
74
+ const authInfo = await this.introspect(token);
75
+ const ttl = (this.auth.cacheTtl ?? DEFAULT_CACHE_TTL) * 1000;
76
+ if (ttl > 0) {
77
+ if (this.cache.size >= MAX_CACHE_SIZE) {
78
+ this.cache.delete(this.cache.keys().next().value);
79
+ }
80
+ // RFC 7662 responses may omit `exp`: the result is then cached for the whole ttl
81
+ this.cache.set(key, { authInfo, until: authInfo.expiresAt ? Math.min(now + ttl, authInfo.expiresAt * 1000) : now + ttl });
82
+ }
83
+ return authInfo;
84
+ }
85
+ async verifyOffline(token) {
86
+ const audience = this.audience || this.resource.href;
87
+ const oauth = await import("oauth4webapi");
88
+ const as = await this.getAuthorizationServer(oauth);
89
+ // only the Authorization header of this request is read by the validation
90
+ const request = new Request("https://resource.invalid", { headers: { authorization: `Bearer ${token}` } });
91
+ try {
92
+ return this.toAuthInfo(token, await oauth.validateJwtAccessToken(as, request, audience, this.getRequestOptions(oauth)));
93
+ }
94
+ catch (error) {
95
+ const isTokenError = error instanceof oauth.UnsupportedOperationError ||
96
+ (error instanceof oauth.OperationProcessingError && !SERVER_ERROR_CODES.includes(error.code));
97
+ // an unreachable JWKS endpoint must not be reported to the client as an invalid token
98
+ throw isTokenError ? new PlatformInvalidToken("Invalid access token") : new PlatformServerError("Unable to verify the access token");
99
+ }
100
+ }
101
+ async introspect(token) {
102
+ const oauth = await import("oauth4webapi");
103
+ const as = await this.getAuthorizationServer(oauth);
104
+ let claims;
105
+ try {
106
+ const response = await oauth.introspectionRequest(as, { client_id: this.auth.clientId }, oauth.ClientSecretBasic(this.auth.clientSecret), token, this.getRequestOptions(oauth));
107
+ claims = (await oauth.processIntrospectionResponse(as, { client_id: this.auth.clientId }, response));
108
+ }
109
+ catch {
110
+ throw new PlatformServerError("Unable to introspect the access token");
111
+ }
112
+ const audiences = [].concat(claims.aud || []);
113
+ if (!claims.active) {
114
+ throw new PlatformInvalidToken("Inactive access token");
115
+ }
116
+ if (claims.iss && claims.iss !== this.auth.issuer) {
117
+ throw new PlatformInvalidToken("Unexpected access token issuer");
118
+ }
119
+ // a token without audience is rejected: it could have been issued for another resource
120
+ if (this.audience !== false && !audiences.includes(this.audience)) {
121
+ throw new PlatformInvalidToken("Unexpected access token audience");
122
+ }
123
+ return this.toAuthInfo(token, claims);
124
+ }
125
+ /**
126
+ * Resolves the authorization server metadata once per endpoint: OIDC discovery, then RFC 8414.
127
+ * Discovery is skipped when the endpoint needed by the verification mode is configured explicitly.
128
+ */
129
+ getAuthorizationServer(oauth) {
130
+ const load = async () => {
131
+ const overrides = {
132
+ ...(this.auth.jwksUri && { jwks_uri: this.auth.jwksUri }),
133
+ ...(this.auth.introspectionEndpoint && { introspection_endpoint: this.auth.introspectionEndpoint })
134
+ };
135
+ if (this.mode === "introspection" ? this.auth.introspectionEndpoint : this.auth.jwksUri) {
136
+ return { issuer: this.auth.issuer, ...overrides };
137
+ }
138
+ const issuer = new URL(this.auth.issuer);
139
+ for (const algorithm of ["oidc", "oauth2"]) {
140
+ try {
141
+ const response = await oauth.discoveryRequest(issuer, { algorithm, ...this.getRequestOptions(oauth) });
142
+ return { ...(await oauth.processDiscoveryResponse(issuer, response)), ...overrides };
143
+ }
144
+ catch {
145
+ // try the next discovery algorithm
146
+ }
147
+ }
148
+ throw new PlatformServerError(`Unable to load the authorization server metadata of ${this.auth.issuer}`);
149
+ };
150
+ this.authorizationServer ||= load().catch((error) => {
151
+ this.authorizationServer = undefined;
152
+ throw error;
153
+ });
154
+ return this.authorizationServer;
155
+ }
156
+ toAuthInfo(token, claims) {
157
+ const scopes = Array.isArray(claims.scp) ? claims.scp : String(claims.scope || "").split(" ");
158
+ return {
159
+ token,
160
+ clientId: String(claims.client_id || claims.azp || ""),
161
+ scopes: scopes.filter(Boolean),
162
+ expiresAt: claims.exp,
163
+ extra: claims
164
+ };
165
+ }
166
+ getRequestOptions(oauth) {
167
+ return this.auth.allowInsecureRequests ? { [oauth.allowInsecureRequests]: true } : {};
168
+ }
169
+ }
@@ -0,0 +1,11 @@
1
+ import { OAuthError, OAuthErrorCode } from "@modelcontextprotocol/server";
2
+ /**
3
+ * The presented access token cannot be trusted. Answered as a `401 invalid_token` challenge.
4
+ *
5
+ * @module platform/mcp
6
+ */
7
+ export class PlatformInvalidToken extends OAuthError {
8
+ constructor(message) {
9
+ super(OAuthErrorCode.InvalidToken, message);
10
+ }
11
+ }
@@ -0,0 +1,11 @@
1
+ import { OAuthError, OAuthErrorCode } from "@modelcontextprotocol/server";
2
+ /**
3
+ * The authorization server or the configuration failed, whatever the presented token. Answered as `500 server_error`.
4
+ *
5
+ * @module platform/mcp
6
+ */
7
+ export class PlatformServerError extends OAuthError {
8
+ constructor(message) {
9
+ super(OAuthErrorCode.ServerError, message);
10
+ }
11
+ }
@@ -5,14 +5,25 @@ export * from "./constants/constants.js";
5
5
  export * from "./decorators/prompt.js";
6
6
  export * from "./decorators/resource.js";
7
7
  export * from "./decorators/tool.js";
8
+ export * from "./domain/PlatformTokenVerifier.js";
9
+ export * from "./errors/PlatformInvalidToken.js";
10
+ export * from "./errors/PlatformServerError.js";
8
11
  export * from "./fn/definePrompt.js";
9
12
  export * from "./fn/defineResource.js";
10
13
  export * from "./fn/defineTool.js";
14
+ export * from "./interfaces/PlatformMcpAuthSettings.js";
11
15
  export * from "./interfaces/PlatformMcpSettings.js";
16
+ export * from "./interfaces/PlatformMcpUpstreamSettings.js";
17
+ export * from "./services/PlatformMcpGatewayService.js";
12
18
  export * from "./utils/asResourceResponse.js";
13
19
  export * from "./utils/asToolResponse.js";
20
+ export * from "./utils/attachUpstream.js";
14
21
  export * from "./utils/createMcpServer.js";
22
+ export * from "./utils/createUpstreamTransport.js";
15
23
  export * from "./utils/fromJsonSchema.js";
24
+ export * from "./utils/interpolate.js";
25
+ export * from "./utils/listAll.js";
16
26
  export * from "./utils/resolvePrompts.js";
17
27
  export * from "./utils/resolveResources.js";
18
28
  export * from "./utils/resolveTools.js";
29
+ export * from "./utils/resolveUpstream.js";
@@ -0,0 +1,167 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constant, injectable, logger } from "@tsed/di";
3
+ import { createUpstreamTransport } from "../utils/createUpstreamTransport.js";
4
+ import { listAll } from "../utils/listAll.js";
5
+ const DEFAULT_POOL_MAX = 100;
6
+ const DEFAULT_IDLE_TIMEOUT = 300_000;
7
+ const MAX_RETRY_DELAY = 30_000;
8
+ /**
9
+ * Owns the MCP clients connected to the upstream servers declared on the MCP endpoints.
10
+ *
11
+ * One connection is kept per upstream and per distinct set of interpolated values, so upstreams with
12
+ * caller-independent credentials share a single connection while forwarded identities get their own.
13
+ *
14
+ * @module platform/mcp
15
+ */
16
+ export class PlatformMcpGatewayService {
17
+ constructor() {
18
+ this.pools = new Map();
19
+ }
20
+ /**
21
+ * Returns the connection matching the resolved upstream definition, connecting lazily.
22
+ *
23
+ * @param upstream Upstream declared in the configuration, identifying the pool.
24
+ * @param resolved Same definition with its placeholders interpolated for the caller.
25
+ */
26
+ getConnection(upstream, resolved = upstream) {
27
+ const pool = this.getPool(upstream);
28
+ const key = this.getKey(resolved);
29
+ const now = Date.now();
30
+ let entry = pool.get(key);
31
+ if (!entry) {
32
+ entry = { lastUsed: now, pending: 0, failures: 0, retryAt: 0 };
33
+ pool.set(key, entry);
34
+ }
35
+ entry.lastUsed = now;
36
+ this.evict(upstream, pool, entry, now);
37
+ if (!entry.connection) {
38
+ if (entry.retryAt > now) {
39
+ return Promise.reject(entry.error);
40
+ }
41
+ entry.connection = this.connect(resolved, entry).catch((error) => {
42
+ entry.connection = undefined;
43
+ entry.failures++;
44
+ entry.error = error;
45
+ entry.retryAt = Date.now() + Math.min(1000 * 2 ** (entry.failures - 1), MAX_RETRY_DELAY);
46
+ throw error;
47
+ });
48
+ }
49
+ return entry.connection;
50
+ }
51
+ async $onDestroy() {
52
+ const entries = [...this.pools.values()].flatMap((pool) => [...pool.values()]);
53
+ this.pools.clear();
54
+ await Promise.all(entries.map((entry) => this.close(entry)));
55
+ }
56
+ async connect(upstream, entry) {
57
+ const { Client } = await import("@modelcontextprotocol/client");
58
+ const transport = await createUpstreamTransport(upstream);
59
+ let catalog;
60
+ const invalidate = () => {
61
+ catalog = undefined;
62
+ };
63
+ const listChanged = { autoRefresh: false, onChanged: invalidate };
64
+ const client = new Client({
65
+ name: constant("name") || "tsed-mcp-gateway",
66
+ version: constant("version") || "0.0.0"
67
+ }, {
68
+ listChanged: { tools: listChanged, prompts: listChanged, resources: listChanged }
69
+ });
70
+ entry.client = client;
71
+ client.onclose = () => {
72
+ // drop the connection so the next request reconnects
73
+ if (entry.client === client) {
74
+ entry.connection = undefined;
75
+ entry.client = undefined;
76
+ }
77
+ };
78
+ try {
79
+ await client.connect(transport);
80
+ }
81
+ catch (error) {
82
+ entry.client = undefined;
83
+ await client.close().catch(() => undefined);
84
+ throw error;
85
+ }
86
+ entry.failures = 0;
87
+ return {
88
+ client,
89
+ getCatalog: () => {
90
+ catalog ||= this.loadCatalog(client).catch((error) => {
91
+ catalog = undefined;
92
+ throw error;
93
+ });
94
+ return catalog;
95
+ },
96
+ run: async (fn) => {
97
+ entry.pending++;
98
+ try {
99
+ return await fn();
100
+ }
101
+ finally {
102
+ entry.pending--;
103
+ entry.lastUsed = Date.now();
104
+ }
105
+ }
106
+ };
107
+ }
108
+ async loadCatalog(client) {
109
+ 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 };
117
+ }
118
+ getPool(upstream) {
119
+ let pool = this.pools.get(upstream);
120
+ if (!pool) {
121
+ pool = new Map();
122
+ this.pools.set(upstream, pool);
123
+ }
124
+ return pool;
125
+ }
126
+ getKey(upstream) {
127
+ const values = upstream.type === "stdio" ? [upstream.args, upstream.env] : [upstream.headers];
128
+ return createHash("sha256").update(JSON.stringify(values)).digest("hex");
129
+ }
130
+ /**
131
+ * Closes idle connections, then the least recently used ones while the pool is full.
132
+ * Connections serving a request and the requested one are kept, so the pool can temporarily exceed `max`.
133
+ */
134
+ evict(upstream, pool, current, now) {
135
+ const { max = DEFAULT_POOL_MAX, idleTimeout = DEFAULT_IDLE_TIMEOUT } = upstream.pool || {};
136
+ if (pool.size <= 1) {
137
+ // a single connection (static credentials, stdio) is kept alive
138
+ return;
139
+ }
140
+ const entries = [...pool.entries()].sort(([, a], [, b]) => a.lastUsed - b.lastUsed);
141
+ let size = entries.length;
142
+ for (const [key, entry] of entries) {
143
+ if (now - entry.lastUsed < idleTimeout && size <= max) {
144
+ break;
145
+ }
146
+ if (entry.pending || entry === current) {
147
+ // never close a connection that is serving a request, nor the one being requested
148
+ continue;
149
+ }
150
+ size--;
151
+ pool.delete(key);
152
+ void this.close(entry);
153
+ }
154
+ }
155
+ async close(entry) {
156
+ const { client } = entry;
157
+ entry.client = undefined;
158
+ entry.connection = undefined;
159
+ try {
160
+ await client?.close();
161
+ }
162
+ catch (error) {
163
+ logger().warn({ event: "MCP_GATEWAY_CLOSE_ERROR", error });
164
+ }
165
+ }
166
+ }
167
+ injectable(PlatformMcpGatewayService);
@@ -0,0 +1,140 @@
1
+ import { fromJsonSchema, ResourceTemplate } from "@modelcontextprotocol/server";
2
+ import { inject, logger } from "@tsed/di";
3
+ import { PlatformMcpGatewayService } from "../services/PlatformMcpGatewayService.js";
4
+ import { resolveUpstream } from "./resolveUpstream.js";
5
+ // upstream catalogs are stable objects: compile each schema once instead of on every request
6
+ const schemas = new WeakMap();
7
+ function toSchema(key, schema = key) {
8
+ let compiled = schemas.get(key);
9
+ if (!compiled) {
10
+ compiled = fromJsonSchema(schema);
11
+ schemas.set(key, compiled);
12
+ }
13
+ return compiled;
14
+ }
15
+ function isAllowed(filter, value) {
16
+ const match = (pattern) => {
17
+ if (typeof pattern === "string") {
18
+ return pattern === value;
19
+ }
20
+ // a `g` or `y` pattern keeps its position between calls and would match intermittently
21
+ pattern.lastIndex = 0;
22
+ return pattern.test(value);
23
+ };
24
+ if (filter?.exclude?.some(match)) {
25
+ return false;
26
+ }
27
+ return !filter?.include || filter.include.some(match);
28
+ }
29
+ function getRequestOptions(ctx) {
30
+ const progressToken = ctx.mcpReq._meta?.progressToken;
31
+ return {
32
+ signal: ctx.mcpReq.signal,
33
+ ...(progressToken !== undefined && {
34
+ onprogress: (progress) => ctx.mcpReq.notify({ method: "notifications/progress", params: { ...progress, progressToken } })
35
+ })
36
+ };
37
+ }
38
+ function getPromptArgsSchema(args) {
39
+ if (!args?.length) {
40
+ return undefined;
41
+ }
42
+ return toSchema(args, {
43
+ type: "object",
44
+ properties: Object.fromEntries(args.map(({ name, description }) => [name, { type: "string", ...(description && { description }) }])),
45
+ required: args.filter(({ required }) => required).map(({ name }) => name)
46
+ });
47
+ }
48
+ function registerCatalog(server, upstream, label, { client, run }, catalog, taken) {
49
+ const { prefix = "" } = upstream;
50
+ const register = (kind, key, fn) => {
51
+ if (taken[kind].has(key)) {
52
+ logger().warn({
53
+ event: "MCP_GATEWAY_COLLISION",
54
+ message: `MCP upstream "${label}": ${kind} "${key}" is already registered and is skipped.`
55
+ });
56
+ return;
57
+ }
58
+ try {
59
+ fn();
60
+ taken[kind].add(key);
61
+ }
62
+ catch (error) {
63
+ logger().warn({
64
+ event: "MCP_GATEWAY_REGISTER_ERROR",
65
+ message: `MCP upstream "${label}": unable to register ${kind} "${key}".`,
66
+ error
67
+ });
68
+ }
69
+ };
70
+ catalog.tools
71
+ .filter(({ name }) => isAllowed(upstream.tools, name))
72
+ .forEach(({ name, inputSchema, outputSchema, ...opts }) => {
73
+ register("tool", prefix + name, () => {
74
+ server.registerTool(prefix + name, {
75
+ ...opts,
76
+ inputSchema: toSchema(inputSchema),
77
+ ...(outputSchema && { outputSchema: toSchema(outputSchema) })
78
+ }, ((args, ctx) => run(() => client.callTool({ name, arguments: args }, getRequestOptions(ctx)))));
79
+ });
80
+ });
81
+ catalog.resources
82
+ .filter(({ uri }) => isAllowed(upstream.resources, uri))
83
+ .forEach(({ name, uri, ...opts }) => {
84
+ register("resource", uri, () => {
85
+ server.registerResource(name, uri, opts, ((_, ctx) => run(() => client.readResource({ uri }, getRequestOptions(ctx)))));
86
+ });
87
+ });
88
+ catalog.resourceTemplates
89
+ .filter(({ uriTemplate }) => isAllowed(upstream.resources, uriTemplate))
90
+ .forEach(({ name, uriTemplate, ...opts }) => {
91
+ register("resource template", name, () => {
92
+ server.registerResource(name, new ResourceTemplate(uriTemplate, { list: undefined }), opts, ((uri, _, ctx) => run(() => client.readResource({ uri: uri.toString() }, getRequestOptions(ctx)))));
93
+ });
94
+ });
95
+ catalog.prompts
96
+ .filter(({ name }) => isAllowed(upstream.prompts, name))
97
+ .forEach(({ name, arguments: args, ...opts }) => {
98
+ register("prompt", prefix + name, () => {
99
+ const argsSchema = getPromptArgsSchema(args);
100
+ server.registerPrompt(prefix + name, { ...opts, ...(argsSchema && { argsSchema }) }, ((...params) => {
101
+ const ctx = params.at(-1);
102
+ return run(() => client.getPrompt({ name, arguments: params.length > 1 ? params[0] : undefined }, getRequestOptions(ctx)));
103
+ }));
104
+ });
105
+ });
106
+ }
107
+ /**
108
+ * Registers the tools, resources and prompts of the endpoint's upstream MCP server on the given server.
109
+ *
110
+ * Local declarations take precedence over upstream entries. An unreachable upstream is logged and
111
+ * skipped so the endpoint keeps serving its local declarations.
112
+ *
113
+ * @param server Server already holding the local declarations.
114
+ * @param settings Resolved settings of the MCP endpoint.
115
+ * @param authInfo Verified identity of the caller, used to interpolate the upstream placeholders.
116
+ * @module platform/mcp
117
+ */
118
+ export async function attachUpstream(server, settings, authInfo) {
119
+ const { upstream } = settings;
120
+ if (!upstream) {
121
+ return;
122
+ }
123
+ const label = settings.path || (upstream.type === "stdio" ? upstream.command : upstream.url);
124
+ try {
125
+ const connection = await inject(PlatformMcpGatewayService).getConnection(upstream, resolveUpstream(upstream, authInfo));
126
+ registerCatalog(server, upstream, label, connection, await connection.getCatalog(), {
127
+ tool: new Set(settings.tools.map(({ name }) => name)),
128
+ prompt: new Set(settings.prompts.map(({ name }) => name)),
129
+ resource: new Set(settings.resources.map(({ uri }) => uri).filter(Boolean)),
130
+ "resource template": new Set(settings.resources.filter(({ uri }) => !uri).map(({ name }) => name))
131
+ });
132
+ }
133
+ catch (error) {
134
+ logger().error({
135
+ event: "MCP_GATEWAY_UPSTREAM_ERROR",
136
+ message: `MCP upstream "${label}" is unavailable.`,
137
+ error
138
+ });
139
+ }
140
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Creates the MCP client transport matching a resolved upstream definition.
3
+ *
4
+ * The client package is imported lazily so applications without upstream never load it.
5
+ *
6
+ * @module platform/mcp
7
+ */
8
+ export async function createUpstreamTransport(upstream) {
9
+ if (upstream.type === "stdio") {
10
+ const { StdioClientTransport, getDefaultEnvironment } = await import("@modelcontextprotocol/client/stdio");
11
+ const { command, args, env, cwd } = upstream;
12
+ return new StdioClientTransport({ command, args, cwd, ...(env && { env: { ...getDefaultEnvironment(), ...env } }) });
13
+ }
14
+ const { StreamableHTTPClientTransport, SSEClientTransport } = await import("@modelcontextprotocol/client");
15
+ // `requestInit.headers` may be a record, a list of tuples or a `Headers` instance
16
+ const headers = new Headers(upstream.requestInit?.headers);
17
+ Object.entries(upstream.headers || {}).forEach(([name, value]) => headers.set(name, value));
18
+ const requestInit = { ...upstream.requestInit, headers: Object.fromEntries(headers) };
19
+ const url = new URL(upstream.url);
20
+ return upstream.type === "sse" ? new SSEClientTransport(url, { requestInit }) : new StreamableHTTPClientTransport(url, { requestInit });
21
+ }
@@ -0,0 +1,24 @@
1
+ const PLACEHOLDER = /\$\{([A-Za-z0-9_]+)\}/g;
2
+ /**
3
+ * Replaces the `${NAME}` placeholders of a string with the matching variables.
4
+ *
5
+ * Placeholders without a matching variable are left untouched, and a variable set to `undefined` is replaced
6
+ * with an empty string.
7
+ *
8
+ * @param value String holding the placeholders.
9
+ * @param variables Values indexed by placeholder name.
10
+ * @module platform/mcp
11
+ */
12
+ export function interpolate(value, variables) {
13
+ return value.replace(PLACEHOLDER, (placeholder, name) => Object.hasOwn(variables, name) ? (variables[name] ?? "") : placeholder);
14
+ }
15
+ /**
16
+ * Tells whether a string references at least one of the given placeholder names.
17
+ *
18
+ * @param value String to inspect.
19
+ * @param names Placeholder names to look for.
20
+ * @module platform/mcp
21
+ */
22
+ export function hasPlaceholders(value, names) {
23
+ return [...value.matchAll(PLACEHOLDER)].some(([, name]) => names.includes(name));
24
+ }
@@ -0,0 +1,13 @@
1
+ export async function listAll(enabled, list, key) {
2
+ const items = [];
3
+ let cursor;
4
+ if (!enabled) {
5
+ return items;
6
+ }
7
+ do {
8
+ const page = await list(cursor ? { cursor } : {});
9
+ items.push(...page[key]);
10
+ cursor = page.nextCursor;
11
+ } while (cursor);
12
+ return items;
13
+ }
@@ -0,0 +1,35 @@
1
+ import { hasPlaceholders, interpolate } from "./interpolate.js";
2
+ const OAUTH_PLACEHOLDERS = ["OAUTH_TOKEN", "OAUTH_CLIENT_ID", "OAUTH_SCOPES"];
3
+ function mapValues(record, fn) {
4
+ return record && Object.fromEntries(Object.entries(record).map(([key, value]) => [key, fn(value)]));
5
+ }
6
+ function getValues(upstream) {
7
+ return upstream.type === "stdio"
8
+ ? [...(upstream.args || []), ...Object.values(upstream.env || {})]
9
+ : Object.values(upstream.headers || {});
10
+ }
11
+ /**
12
+ * Tells whether the upstream definition references the identity of the caller.
13
+ */
14
+ export function hasUpstreamPlaceholders(upstream) {
15
+ return getValues(upstream).some((value) => hasPlaceholders(value, OAUTH_PLACEHOLDERS));
16
+ }
17
+ /**
18
+ * Replaces the `${OAUTH_*}` placeholders of an upstream definition with the verified identity of the caller.
19
+ *
20
+ * Headers are interpolated for `http` and `sse` upstreams, `args` and `env` for `stdio` upstreams.
21
+ *
22
+ * @module platform/mcp
23
+ */
24
+ export function resolveUpstream(upstream, authInfo) {
25
+ const variables = {
26
+ OAUTH_TOKEN: authInfo?.token,
27
+ OAUTH_CLIENT_ID: authInfo?.clientId,
28
+ OAUTH_SCOPES: authInfo?.scopes?.join(" ")
29
+ };
30
+ const resolve = (value) => interpolate(value, variables);
31
+ if (upstream.type === "stdio") {
32
+ return { ...upstream, args: upstream.args?.map(resolve), env: mapValues(upstream.env, resolve) };
33
+ }
34
+ return { ...upstream, headers: mapValues(upstream.headers, resolve) };
35
+ }