@tsed/platform-mcp 8.41.3 → 8.43.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.
- package/lib/esm/cli/services/mcpServerConnect.js +17 -1
- package/lib/esm/cli/services/mcpStreamableServer.js +1 -1
- package/lib/esm/common/domain/PlatformTokenVerifier.js +169 -0
- package/lib/esm/common/errors/PlatformInvalidToken.js +11 -0
- package/lib/esm/common/errors/PlatformServerError.js +11 -0
- package/lib/esm/common/index.js +12 -0
- package/lib/esm/common/interfaces/PlatformMcpAuthSettings.js +1 -0
- package/lib/esm/common/interfaces/PlatformMcpPreAuth.js +1 -0
- package/lib/esm/common/interfaces/PlatformMcpUpstreamSettings.js +1 -0
- package/lib/esm/common/services/PlatformMcpGatewayService.js +167 -0
- package/lib/esm/common/utils/attachUpstream.js +140 -0
- package/lib/esm/common/utils/createUpstreamTransport.js +21 -0
- package/lib/esm/common/utils/interpolate.js +24 -0
- package/lib/esm/common/utils/listAll.js +13 -0
- package/lib/esm/common/utils/resolveUpstream.js +35 -0
- package/lib/esm/http/index.js +1 -0
- package/lib/esm/http/services/PlatformMcpAuthService.js +131 -0
- package/lib/esm/http/services/PlatformMcpModule.js +74 -7
- package/lib/tsconfig.esm.tsbuildinfo +1 -1
- package/lib/types/cli/services/mcpStreamableServer.d.ts +1 -1
- package/lib/types/common/domain/PlatformTokenVerifier.d.ts +59 -0
- package/lib/types/common/errors/PlatformInvalidToken.d.ts +9 -0
- package/lib/types/common/errors/PlatformServerError.d.ts +9 -0
- package/lib/types/common/index.d.ts +12 -0
- package/lib/types/common/interfaces/PlatformMcpAuthSettings.d.ts +87 -0
- package/lib/types/common/interfaces/PlatformMcpPreAuth.d.ts +33 -0
- package/lib/types/common/interfaces/PlatformMcpSettings.d.ts +12 -0
- package/lib/types/common/interfaces/PlatformMcpUpstreamSettings.d.ts +77 -0
- package/lib/types/common/services/PlatformMcpGatewayService.d.ts +66 -0
- package/lib/types/common/utils/attachUpstream.d.ts +14 -0
- package/lib/types/common/utils/createUpstreamTransport.d.ts +10 -0
- package/lib/types/common/utils/interpolate.d.ts +19 -0
- package/lib/types/common/utils/listAll.d.ts +3 -0
- package/lib/types/common/utils/resolveUpstream.d.ts +14 -0
- package/lib/types/http/index.d.ts +1 -0
- package/lib/types/http/services/PlatformMcpAuthService.d.ts +71 -0
- package/lib/types/http/services/PlatformMcpModule.d.ts +9 -2
- package/package.json +12 -8
- package/readme.md +2 -0
- package/src/cli/services/mcpServerConnect.spec.ts +40 -4
- package/src/cli/services/mcpServerConnect.ts +21 -1
- package/src/cli/services/mcpStreamableServer.ts +2 -2
- package/src/common/domain/PlatformTokenVerifier.spec.ts +313 -0
- package/src/common/domain/PlatformTokenVerifier.ts +230 -0
- package/src/common/errors/PlatformInvalidToken.ts +12 -0
- package/src/common/errors/PlatformServerError.ts +12 -0
- package/src/common/index.ts +12 -0
- package/src/common/interfaces/PlatformMcpAuthSettings.ts +88 -0
- package/src/common/interfaces/PlatformMcpPreAuth.ts +37 -0
- package/src/common/interfaces/PlatformMcpSettings.ts +12 -0
- package/src/common/interfaces/PlatformMcpUpstreamSettings.ts +80 -0
- package/src/common/services/PlatformMcpGatewayService.spec.ts +282 -0
- package/src/common/services/PlatformMcpGatewayService.ts +247 -0
- package/src/common/utils/attachUpstream.spec.ts +305 -0
- package/src/common/utils/attachUpstream.ts +207 -0
- package/src/common/utils/createUpstreamTransport.spec.ts +94 -0
- package/src/common/utils/createUpstreamTransport.ts +29 -0
- package/src/common/utils/interpolate.spec.ts +33 -0
- package/src/common/utils/interpolate.ts +28 -0
- package/src/common/utils/listAll.spec.ts +28 -0
- package/src/common/utils/listAll.ts +17 -0
- package/src/common/utils/resolveUpstream.spec.ts +78 -0
- package/src/common/utils/resolveUpstream.ts +44 -0
- package/src/http/index.ts +1 -0
- package/src/http/services/PlatformMcpAuthService.spec.ts +297 -0
- package/src/http/services/PlatformMcpAuthService.ts +165 -0
- package/src/http/services/PlatformMcpModule.spec.ts +120 -0
- package/src/http/services/PlatformMcpModule.ts +97 -10
|
@@ -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
|
+
}
|
package/lib/esm/http/index.js
CHANGED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { bearerAuthChallengeResponse, buildOAuthProtectedResourceMetadata, getOAuthProtectedResourceMetadataUrl, verifyBearerToken } from "@modelcontextprotocol/server";
|
|
2
|
+
import { inject, injectable, injector, logger } from "@tsed/di";
|
|
3
|
+
import { PlatformTokenVerifier } from "../../common/index.js";
|
|
4
|
+
export const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
|
|
5
|
+
/**
|
|
6
|
+
* OAuth resource-server behavior of the protected MCP endpoints: configuration validation,
|
|
7
|
+
* protected resource metadata and bearer token verification.
|
|
8
|
+
*
|
|
9
|
+
* @module platform/mcp
|
|
10
|
+
*/
|
|
11
|
+
export class PlatformMcpAuthService {
|
|
12
|
+
constructor() {
|
|
13
|
+
this.verifiers = new WeakMap();
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Tells whether the endpoint is protected by an OAuth authorization server, and not only by a custom check.
|
|
17
|
+
*/
|
|
18
|
+
isOAuth(auth) {
|
|
19
|
+
return Boolean(auth?.issuer);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Runs the custom authentication check of an endpoint.
|
|
23
|
+
*
|
|
24
|
+
* @returns The identity of the caller, or `undefined` when the check does not apply to the request.
|
|
25
|
+
*/
|
|
26
|
+
async preAuth(preAuth, $ctx) {
|
|
27
|
+
if (!injector().providers.has(preAuth)) {
|
|
28
|
+
// not a registered provider: the option is the check itself
|
|
29
|
+
return preAuth($ctx);
|
|
30
|
+
}
|
|
31
|
+
const instance = inject(preAuth);
|
|
32
|
+
return instance.preAuth($ctx);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Returns the token verifier of an endpoint, created once per `auth` configuration.
|
|
36
|
+
*/
|
|
37
|
+
getVerifier(auth, resource) {
|
|
38
|
+
let verifier = this.verifiers.get(auth);
|
|
39
|
+
if (!verifier) {
|
|
40
|
+
verifier = new PlatformTokenVerifier(auth, resource);
|
|
41
|
+
this.verifiers.set(auth, verifier);
|
|
42
|
+
}
|
|
43
|
+
return verifier;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Verifies the bearer token of the incoming request.
|
|
47
|
+
*
|
|
48
|
+
* @returns The verified identity, or the `401`/`403` challenge to send back to the client.
|
|
49
|
+
*/
|
|
50
|
+
async verifyMcpRequest(auth, $ctx) {
|
|
51
|
+
const resource = this.getResourceUrl(auth);
|
|
52
|
+
const options = {
|
|
53
|
+
verifier: this.getVerifier(auth, resource),
|
|
54
|
+
requiredScopes: auth.requiredScopes,
|
|
55
|
+
resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(resource)
|
|
56
|
+
};
|
|
57
|
+
try {
|
|
58
|
+
return await verifyBearerToken($ctx.request.headers.authorization, options);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
return bearerAuthChallengeResponse(error, options);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Rejects an `auth` configuration that cannot work or would be unsafe, before any route is mounted.
|
|
66
|
+
*/
|
|
67
|
+
validate(path, auth) {
|
|
68
|
+
const mode = PlatformTokenVerifier.getMode(auth);
|
|
69
|
+
if (!auth.verifier && mode === "introspection" && !(auth.clientId && auth.clientSecret)) {
|
|
70
|
+
throw new Error(`MCP endpoint "${path}": the introspection mode requires auth.clientId and auth.clientSecret.`);
|
|
71
|
+
}
|
|
72
|
+
if (!auth.verifier && auth.audience === false) {
|
|
73
|
+
if (mode === "offline") {
|
|
74
|
+
throw new Error(`MCP endpoint "${path}": auth.audience cannot be disabled in offline mode.`);
|
|
75
|
+
}
|
|
76
|
+
logger().warn({
|
|
77
|
+
event: "MCP_AUTH_AUDIENCE_DISABLED",
|
|
78
|
+
message: `MCP endpoint "${path}": the audience check is disabled, any active token of ${auth.issuer} is accepted.`
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (!auth.resource) {
|
|
82
|
+
// the resource is never derived from the request: the Host header is controlled by the caller
|
|
83
|
+
throw new Error(`MCP endpoint "${path}": auth.resource is required.`);
|
|
84
|
+
}
|
|
85
|
+
if (!URL.canParse(auth.resource)) {
|
|
86
|
+
throw new Error(`MCP endpoint "${path}": auth.resource must be an absolute URL.`);
|
|
87
|
+
}
|
|
88
|
+
if (!URL.canParse(auth.issuer)) {
|
|
89
|
+
throw new Error(`MCP endpoint "${path}": auth.issuer must be an absolute URL.`);
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
// surfaces at startup what the metadata route would otherwise fail on (insecure issuer, invalid documentation URL)
|
|
93
|
+
this.getProtectedResourceMetadata(auth, this.getResourceUrl(auth));
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
throw new Error(`MCP endpoint "${path}": invalid auth configuration. ${error.message}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Builds the OAuth 2.0 Protected Resource Metadata (RFC 9728) advertised for the given resource.
|
|
101
|
+
*
|
|
102
|
+
* @throws When the issuer is not an HTTPS URL (outside localhost) and `allowInsecureRequests` is not set.
|
|
103
|
+
*/
|
|
104
|
+
getProtectedResourceMetadata(auth, resource) {
|
|
105
|
+
return buildOAuthProtectedResourceMetadata({
|
|
106
|
+
// the SDK builder only reads the issuer of the authorization server metadata
|
|
107
|
+
oauthMetadata: { issuer: auth.issuer },
|
|
108
|
+
resourceServerUrl: resource,
|
|
109
|
+
scopesSupported: auth.scopesSupported,
|
|
110
|
+
resourceName: auth.resourceName,
|
|
111
|
+
serviceDocumentationUrl: auth.resourceDocumentation ? new URL(auth.resourceDocumentation) : undefined,
|
|
112
|
+
dangerouslyAllowInsecureIssuerUrl: auth.allowInsecureRequests
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Path of the RFC 9728 metadata document describing the MCP endpoint mounted on `path`.
|
|
117
|
+
*/
|
|
118
|
+
getProtectedResourceMetadataPath(path) {
|
|
119
|
+
return `${PROTECTED_RESOURCE_METADATA_PATH}${path === "/" ? "" : path}`;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Canonical URL of the MCP endpoint, as configured in `auth.resource`.
|
|
123
|
+
*
|
|
124
|
+
* It is used for the metadata document, the bearer challenge and the expected audience, and is never
|
|
125
|
+
* derived from the incoming request.
|
|
126
|
+
*/
|
|
127
|
+
getResourceUrl(auth) {
|
|
128
|
+
return new URL(auth.resource);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
injectable(PlatformMcpAuthService);
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { application } from "@tsed/platform-http";
|
|
2
|
-
import { constant, injectable } from "@tsed/di";
|
|
2
|
+
import { constant, inject, injectable } from "@tsed/di";
|
|
3
3
|
import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node";
|
|
4
4
|
import { useContextHandler } from "@tsed/platform-router";
|
|
5
|
+
import { attachUpstream } from "../../common/utils/attachUpstream.js";
|
|
6
|
+
import { hasUpstreamPlaceholders } from "../../common/utils/resolveUpstream.js";
|
|
5
7
|
import { createMcpServer, resolveMcpServerOptions } from "../../common/utils/createMcpServer.js";
|
|
8
|
+
import { PlatformMcpAuthService } from "./PlatformMcpAuthService.js";
|
|
6
9
|
/**
|
|
7
10
|
* Platform module that mounts the MCP HTTP endpoint and forwards requests to the configured server instance.
|
|
8
11
|
*
|
|
@@ -14,6 +17,7 @@ export class PlatformMcpModule {
|
|
|
14
17
|
this.settings = constant("mcp", {});
|
|
15
18
|
this.app = application();
|
|
16
19
|
this.mcps = [];
|
|
20
|
+
this.platformAuthService = inject(PlatformMcpAuthService);
|
|
17
21
|
this.loaded = false;
|
|
18
22
|
}
|
|
19
23
|
$onRoutesInit() {
|
|
@@ -26,7 +30,20 @@ export class PlatformMcpModule {
|
|
|
26
30
|
continue;
|
|
27
31
|
}
|
|
28
32
|
const path = opts.path || "/mcp";
|
|
29
|
-
|
|
33
|
+
this.validate(path, opts);
|
|
34
|
+
const resolvedSettings = {
|
|
35
|
+
...resolveMcpServerOptions(opts),
|
|
36
|
+
path
|
|
37
|
+
};
|
|
38
|
+
if (this.platformAuthService.isOAuth(opts.auth)) {
|
|
39
|
+
const metadataPath = this.platformAuthService.getProtectedResourceMetadataPath(path);
|
|
40
|
+
this.app.get(metadataPath, useContextHandler(($ctx) => this.metadata(resolvedSettings, $ctx)));
|
|
41
|
+
this.mcps.push({
|
|
42
|
+
method: "GET",
|
|
43
|
+
name: "PlatformMcpModule.metadata()",
|
|
44
|
+
url: metadataPath
|
|
45
|
+
});
|
|
46
|
+
}
|
|
30
47
|
this.app.post(path, useContextHandler(async ($ctx) => this.dispatch(resolvedSettings, $ctx)));
|
|
31
48
|
this.mcps.push({
|
|
32
49
|
method: "POST",
|
|
@@ -39,15 +56,64 @@ export class PlatformMcpModule {
|
|
|
39
56
|
$logRoutes(routes) {
|
|
40
57
|
return [...routes, ...this.mcps].filter(Boolean);
|
|
41
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Rejects a configuration that cannot work or would be unsafe, before any route is mounted.
|
|
61
|
+
*/
|
|
62
|
+
validate(path, opts) {
|
|
63
|
+
const { auth } = opts;
|
|
64
|
+
if (this.platformAuthService.isOAuth(auth)) {
|
|
65
|
+
this.platformAuthService.validate(path, auth);
|
|
66
|
+
}
|
|
67
|
+
else if (auth && !auth.preAuth) {
|
|
68
|
+
throw new Error(`MCP endpoint "${path}": auth requires an issuer, a preAuth check, or both.`);
|
|
69
|
+
}
|
|
70
|
+
if (opts.upstream && !opts.auth && hasUpstreamPlaceholders(opts.upstream)) {
|
|
71
|
+
throw new Error(`MCP endpoint "${path}": the upstream uses \${OAUTH_*} placeholders but the endpoint declares no auth.`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
metadata(settings, $ctx) {
|
|
75
|
+
const auth = settings.auth;
|
|
76
|
+
const resource = this.platformAuthService.getResourceUrl(auth);
|
|
77
|
+
const body = this.platformAuthService.getProtectedResourceMetadata(auth, resource);
|
|
78
|
+
return $ctx.response
|
|
79
|
+
.status(200)
|
|
80
|
+
.setHeaders({
|
|
81
|
+
"content-type": "application/json",
|
|
82
|
+
"cache-control": "public, max-age=3600",
|
|
83
|
+
"access-control-allow-origin": "*"
|
|
84
|
+
})
|
|
85
|
+
.body(body);
|
|
86
|
+
}
|
|
42
87
|
async dispatch(settings, $ctx) {
|
|
88
|
+
const { auth } = settings;
|
|
89
|
+
let authInfo;
|
|
90
|
+
if (auth?.preAuth) {
|
|
91
|
+
authInfo = await this.platformAuthService.preAuth(auth.preAuth, $ctx);
|
|
92
|
+
}
|
|
93
|
+
if (auth && !authInfo) {
|
|
94
|
+
if (!this.platformAuthService.isOAuth(auth)) {
|
|
95
|
+
// the custom check did not authenticate the request and there is no OAuth to fall back on
|
|
96
|
+
return $ctx.response.status(401).body({ error: "unauthorized", error_description: "Authentication required" });
|
|
97
|
+
}
|
|
98
|
+
const result = await this.platformAuthService.verifyMcpRequest(auth, $ctx);
|
|
99
|
+
if (result instanceof Response) {
|
|
100
|
+
return $ctx.response
|
|
101
|
+
.status(result.status)
|
|
102
|
+
.setHeaders(Object.fromEntries(result.headers))
|
|
103
|
+
.body(await result.text());
|
|
104
|
+
}
|
|
105
|
+
authInfo = result;
|
|
106
|
+
}
|
|
107
|
+
if (authInfo) {
|
|
108
|
+
// the SDK transport reads `req.auth` and exposes it to handlers as `ctx.http.authInfo`
|
|
109
|
+
$ctx.getReq().auth = authInfo;
|
|
110
|
+
}
|
|
43
111
|
const server = createMcpServer(settings);
|
|
44
112
|
const transport = new NodeStreamableHTTPServerTransport({
|
|
45
113
|
sessionIdGenerator: undefined,
|
|
46
114
|
enableJsonResponse: true,
|
|
47
115
|
...settings.transportOptions
|
|
48
116
|
});
|
|
49
|
-
const { request, response } = $ctx;
|
|
50
|
-
const res = response.getRes();
|
|
51
117
|
let closed = false;
|
|
52
118
|
const closeServer = async () => {
|
|
53
119
|
if (closed) {
|
|
@@ -56,14 +122,15 @@ export class PlatformMcpModule {
|
|
|
56
122
|
closed = true;
|
|
57
123
|
await server.close();
|
|
58
124
|
};
|
|
59
|
-
|
|
125
|
+
$ctx.getRes()?.once("close", closeServer);
|
|
60
126
|
try {
|
|
127
|
+
await attachUpstream(server, settings, authInfo);
|
|
61
128
|
await server.connect(transport);
|
|
62
|
-
await transport.handleRequest(
|
|
129
|
+
await transport.handleRequest($ctx.getReq(), $ctx.getRes(), $ctx.request.body);
|
|
63
130
|
}
|
|
64
131
|
finally {
|
|
65
132
|
if (settings.transportOptions?.enableJsonResponse !== false) {
|
|
66
|
-
|
|
133
|
+
$ctx.getRes()?.off?.("close", closeServer);
|
|
67
134
|
await closeServer();
|
|
68
135
|
}
|
|
69
136
|
}
|