@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.
Files changed (68) 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 +12 -0
  7. package/lib/esm/common/interfaces/PlatformMcpAuthSettings.js +1 -0
  8. package/lib/esm/common/interfaces/PlatformMcpPreAuth.js +1 -0
  9. package/lib/esm/common/interfaces/PlatformMcpUpstreamSettings.js +1 -0
  10. package/lib/esm/common/services/PlatformMcpGatewayService.js +167 -0
  11. package/lib/esm/common/utils/attachUpstream.js +140 -0
  12. package/lib/esm/common/utils/createUpstreamTransport.js +21 -0
  13. package/lib/esm/common/utils/interpolate.js +24 -0
  14. package/lib/esm/common/utils/listAll.js +13 -0
  15. package/lib/esm/common/utils/resolveUpstream.js +35 -0
  16. package/lib/esm/http/index.js +1 -0
  17. package/lib/esm/http/services/PlatformMcpAuthService.js +131 -0
  18. package/lib/esm/http/services/PlatformMcpModule.js +74 -7
  19. package/lib/tsconfig.esm.tsbuildinfo +1 -1
  20. package/lib/types/cli/services/mcpStreamableServer.d.ts +1 -1
  21. package/lib/types/common/domain/PlatformTokenVerifier.d.ts +59 -0
  22. package/lib/types/common/errors/PlatformInvalidToken.d.ts +9 -0
  23. package/lib/types/common/errors/PlatformServerError.d.ts +9 -0
  24. package/lib/types/common/index.d.ts +12 -0
  25. package/lib/types/common/interfaces/PlatformMcpAuthSettings.d.ts +87 -0
  26. package/lib/types/common/interfaces/PlatformMcpPreAuth.d.ts +33 -0
  27. package/lib/types/common/interfaces/PlatformMcpSettings.d.ts +12 -0
  28. package/lib/types/common/interfaces/PlatformMcpUpstreamSettings.d.ts +77 -0
  29. package/lib/types/common/services/PlatformMcpGatewayService.d.ts +66 -0
  30. package/lib/types/common/utils/attachUpstream.d.ts +14 -0
  31. package/lib/types/common/utils/createUpstreamTransport.d.ts +10 -0
  32. package/lib/types/common/utils/interpolate.d.ts +19 -0
  33. package/lib/types/common/utils/listAll.d.ts +3 -0
  34. package/lib/types/common/utils/resolveUpstream.d.ts +14 -0
  35. package/lib/types/http/index.d.ts +1 -0
  36. package/lib/types/http/services/PlatformMcpAuthService.d.ts +71 -0
  37. package/lib/types/http/services/PlatformMcpModule.d.ts +9 -2
  38. package/package.json +12 -8
  39. package/readme.md +2 -0
  40. package/src/cli/services/mcpServerConnect.spec.ts +40 -4
  41. package/src/cli/services/mcpServerConnect.ts +21 -1
  42. package/src/cli/services/mcpStreamableServer.ts +2 -2
  43. package/src/common/domain/PlatformTokenVerifier.spec.ts +313 -0
  44. package/src/common/domain/PlatformTokenVerifier.ts +230 -0
  45. package/src/common/errors/PlatformInvalidToken.ts +12 -0
  46. package/src/common/errors/PlatformServerError.ts +12 -0
  47. package/src/common/index.ts +12 -0
  48. package/src/common/interfaces/PlatformMcpAuthSettings.ts +88 -0
  49. package/src/common/interfaces/PlatformMcpPreAuth.ts +37 -0
  50. package/src/common/interfaces/PlatformMcpSettings.ts +12 -0
  51. package/src/common/interfaces/PlatformMcpUpstreamSettings.ts +80 -0
  52. package/src/common/services/PlatformMcpGatewayService.spec.ts +282 -0
  53. package/src/common/services/PlatformMcpGatewayService.ts +247 -0
  54. package/src/common/utils/attachUpstream.spec.ts +305 -0
  55. package/src/common/utils/attachUpstream.ts +207 -0
  56. package/src/common/utils/createUpstreamTransport.spec.ts +94 -0
  57. package/src/common/utils/createUpstreamTransport.ts +29 -0
  58. package/src/common/utils/interpolate.spec.ts +33 -0
  59. package/src/common/utils/interpolate.ts +28 -0
  60. package/src/common/utils/listAll.spec.ts +28 -0
  61. package/src/common/utils/listAll.ts +17 -0
  62. package/src/common/utils/resolveUpstream.spec.ts +78 -0
  63. package/src/common/utils/resolveUpstream.ts +44 -0
  64. package/src/http/index.ts +1 -0
  65. package/src/http/services/PlatformMcpAuthService.spec.ts +297 -0
  66. package/src/http/services/PlatformMcpAuthService.ts +165 -0
  67. package/src/http/services/PlatformMcpModule.spec.ts +120 -0
  68. package/src/http/services/PlatformMcpModule.ts +97 -10
@@ -0,0 +1,297 @@
1
+ import type {AuthInfo} from "@modelcontextprotocol/server";
2
+ import {inject, injectable, logger} from "@tsed/di";
3
+ import type {PlatformContext} from "@tsed/platform-http";
4
+ import {PlatformTest} from "@tsed/platform-http/testing";
5
+ import type {PlatformMcpAuthSettings} from "../../common/interfaces/PlatformMcpAuthSettings.js";
6
+ import type {PlatformMcpPreAuth} from "../../common/interfaces/PlatformMcpPreAuth.js";
7
+ import {PlatformTokenVerifier} from "../../common/domain/PlatformTokenVerifier.js";
8
+ import {PlatformMcpAuthService} from "./PlatformMcpAuthService.js";
9
+
10
+ const authInfo: AuthInfo = {
11
+ token: "valid",
12
+ clientId: "client",
13
+ scopes: ["mcp:read"],
14
+ expiresAt: Math.floor(Date.now() / 1000) + 3600
15
+ };
16
+
17
+ class ApiKeyPreAuth implements PlatformMcpPreAuth {
18
+ preAuth($ctx: PlatformContext) {
19
+ return {token: String($ctx.request.headers["x-api-key"]), clientId: "api-key", scopes: []};
20
+ }
21
+ }
22
+
23
+ injectable(ApiKeyPreAuth);
24
+
25
+ function createAuth(opts: Partial<PlatformMcpAuthSettings> = {}): PlatformMcpAuthSettings {
26
+ return {issuer: "https://auth.example.com", resource: "https://api.example.com/mcp", ...opts};
27
+ }
28
+
29
+ function createContext(headers: Record<string, string> = {}) {
30
+ return PlatformTest.createRequestContext({
31
+ event: {
32
+ request: PlatformTest.createRequest({protocol: "https", headers: {host: "gateway.example.com", ...headers}})
33
+ }
34
+ });
35
+ }
36
+
37
+ describe("PlatformMcpAuthService", () => {
38
+ beforeEach(() => PlatformTest.create());
39
+ afterEach(() => {
40
+ vi.restoreAllMocks();
41
+
42
+ return PlatformTest.reset();
43
+ });
44
+
45
+ describe("isOAuth()", () => {
46
+ it("tells an OAuth configuration from a configuration only declaring a custom check", () => {
47
+ const service = inject(PlatformMcpAuthService);
48
+
49
+ expect(service.isOAuth(createAuth())).toBe(true);
50
+ expect(service.isOAuth(createAuth({preAuth: vi.fn()}))).toBe(true);
51
+ expect(service.isOAuth({preAuth: vi.fn()})).toBe(false);
52
+ });
53
+ });
54
+
55
+ describe("preAuth()", () => {
56
+ it("runs a function", async () => {
57
+ const service = inject(PlatformMcpAuthService);
58
+ const $ctx = createContext();
59
+ const preAuth = vi.fn().mockResolvedValue(authInfo);
60
+
61
+ await expect(service.preAuth(preAuth, $ctx)).resolves.toBe(authInfo);
62
+ expect(preAuth).toHaveBeenCalledExactlyOnceWith($ctx);
63
+ });
64
+
65
+ it("runs a function declared with the function keyword", async () => {
66
+ const service = inject(PlatformMcpAuthService);
67
+
68
+ function preAuth() {
69
+ return authInfo;
70
+ }
71
+
72
+ await expect(service.preAuth(preAuth, createContext())).resolves.toBe(authInfo);
73
+ });
74
+
75
+ it("resolves an injectable class through the injector", async () => {
76
+ const service = inject(PlatformMcpAuthService);
77
+
78
+ await expect(service.preAuth(ApiKeyPreAuth, createContext({"x-api-key": "key"}))).resolves.toEqual({
79
+ token: "key",
80
+ clientId: "api-key",
81
+ scopes: []
82
+ });
83
+ });
84
+
85
+ it("propagates the error thrown by the check", async () => {
86
+ const service = inject(PlatformMcpAuthService);
87
+ const error = new Error("Unknown API key");
88
+
89
+ await expect(service.preAuth(() => Promise.reject(error), createContext())).rejects.toBe(error);
90
+ });
91
+ });
92
+
93
+ describe("getVerifier()", () => {
94
+ it("creates one verifier per auth configuration", () => {
95
+ const service = inject(PlatformMcpAuthService);
96
+ const auth = createAuth();
97
+ const resource = new URL(auth.resource!);
98
+
99
+ const verifier = service.getVerifier(auth, resource);
100
+
101
+ expect(verifier).toBeInstanceOf(PlatformTokenVerifier);
102
+ expect(service.getVerifier(auth, resource)).toBe(verifier);
103
+ expect(service.getVerifier(createAuth(), resource)).not.toBe(verifier);
104
+ });
105
+ });
106
+
107
+ describe("getProtectedResourceMetadataPath()", () => {
108
+ it("suffixes the well-known path with the endpoint path", () => {
109
+ const service = inject(PlatformMcpAuthService);
110
+
111
+ expect(service.getProtectedResourceMetadataPath("/mcp/directus")).toBe("/.well-known/oauth-protected-resource/mcp/directus");
112
+ expect(service.getProtectedResourceMetadataPath("/")).toBe("/.well-known/oauth-protected-resource");
113
+ });
114
+ });
115
+
116
+ describe("getResourceUrl()", () => {
117
+ it("returns the configured resource", () => {
118
+ const service = inject(PlatformMcpAuthService);
119
+
120
+ expect(service.getResourceUrl(createAuth()).href).toBe("https://api.example.com/mcp");
121
+ });
122
+ });
123
+
124
+ describe("getProtectedResourceMetadata()", () => {
125
+ it("advertises the resource and its authorization server", () => {
126
+ const service = inject(PlatformMcpAuthService);
127
+ const auth = createAuth({
128
+ scopesSupported: ["mcp:read", "mcp:write"],
129
+ resourceName: "Orders MCP",
130
+ resourceDocumentation: "https://docs.example.com/mcp"
131
+ });
132
+
133
+ expect(service.getProtectedResourceMetadata(auth, new URL(auth.resource!))).toEqual({
134
+ resource: "https://api.example.com/mcp",
135
+ authorization_servers: ["https://auth.example.com"],
136
+ scopes_supported: ["mcp:read", "mcp:write"],
137
+ resource_name: "Orders MCP",
138
+ resource_documentation: "https://docs.example.com/mcp"
139
+ });
140
+ });
141
+
142
+ it("refuses a non-HTTPS issuer unless insecure requests are allowed", () => {
143
+ const service = inject(PlatformMcpAuthService);
144
+ const resource = new URL("https://api.example.com/mcp");
145
+
146
+ expect(() => service.getProtectedResourceMetadata(createAuth({issuer: "http://auth.example.com"}), resource)).toThrow(
147
+ "Issuer URL must be HTTPS"
148
+ );
149
+ expect(
150
+ service.getProtectedResourceMetadata(createAuth({issuer: "http://auth.example.com", allowInsecureRequests: true}), resource)
151
+ ).toMatchObject({authorization_servers: ["http://auth.example.com"]});
152
+ expect(service.getProtectedResourceMetadata(createAuth({issuer: "http://localhost:3000"}), resource)).toMatchObject({
153
+ authorization_servers: ["http://localhost:3000"]
154
+ });
155
+ });
156
+ });
157
+
158
+ describe("validate()", () => {
159
+ const verifier = {verifyAccessToken: vi.fn()};
160
+
161
+ it.each([
162
+ ["the introspection mode requires auth.clientId and auth.clientSecret", {mode: "introspection"}],
163
+ ["the introspection mode requires auth.clientId and auth.clientSecret", {clientId: "gateway"}],
164
+ ["auth.audience cannot be disabled in offline mode", {audience: false}],
165
+ ["auth.resource is required", {resource: undefined}],
166
+ ["auth.resource is required", {resource: undefined, audience: "mcp"}],
167
+ ["auth.resource is required", {resource: undefined, verifier}],
168
+ ["auth.issuer must be an absolute URL", {issuer: "auth.example.com"}],
169
+ ["auth.resource must be an absolute URL", {resource: "/mcp"}],
170
+ ["invalid auth configuration. Issuer URL must be HTTPS", {issuer: "http://auth.example.com"}],
171
+ ["invalid auth configuration.", {resourceDocumentation: "not a url"}]
172
+ ] as [string, Partial<PlatformMcpAuthSettings>][])("throws when %s (%j)", (message, opts) => {
173
+ const service = inject(PlatformMcpAuthService);
174
+
175
+ expect(() => service.validate("/mcp", createAuth(opts))).toThrow(`MCP endpoint "/mcp": ${message}`);
176
+ });
177
+
178
+ it.each([
179
+ ["offline mode with a resource", {}],
180
+ ["offline mode with a custom audience", {audience: "mcp"}],
181
+ ["introspection mode with client credentials", {clientId: "gateway", clientSecret: "secret"}],
182
+ ["a custom verifier", {verifier}],
183
+ ["a custom verifier in introspection mode without credentials", {mode: "introspection", verifier}]
184
+ ] as [string, Partial<PlatformMcpAuthSettings>][])("accepts %s", (_, opts) => {
185
+ const service = inject(PlatformMcpAuthService);
186
+
187
+ expect(() => service.validate("/mcp", createAuth(opts))).not.toThrow();
188
+ });
189
+
190
+ it("warns when the audience check is disabled in introspection mode", () => {
191
+ const service = inject(PlatformMcpAuthService);
192
+ vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
193
+
194
+ service.validate("/mcp", createAuth({clientId: "gateway", clientSecret: "secret", audience: false}));
195
+
196
+ expect(logger().warn).toHaveBeenCalledWith(
197
+ expect.objectContaining({event: "MCP_AUTH_AUDIENCE_DISABLED", message: expect.stringContaining('"/mcp"')})
198
+ );
199
+ });
200
+
201
+ it("does not warn when a custom verifier owns the audience check", () => {
202
+ const service = inject(PlatformMcpAuthService);
203
+ vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
204
+
205
+ service.validate("/mcp", createAuth({audience: false, verifier}));
206
+
207
+ expect(logger().warn).not.toHaveBeenCalled();
208
+ });
209
+ });
210
+
211
+ describe("verifyMcpRequest()", () => {
212
+ function createVerifier() {
213
+ return {
214
+ verifyAccessToken: vi.fn(async (token: string): Promise<AuthInfo> => {
215
+ if (token !== "valid") {
216
+ throw new Error("Unknown token");
217
+ }
218
+
219
+ return authInfo;
220
+ })
221
+ };
222
+ }
223
+
224
+ it("returns the verified identity", async () => {
225
+ const service = inject(PlatformMcpAuthService);
226
+ const verifier = createVerifier();
227
+
228
+ const result = await service.verifyMcpRequest(createAuth({verifier}), createContext({authorization: "Bearer valid"}));
229
+
230
+ expect(result).toEqual(authInfo);
231
+ expect(verifier.verifyAccessToken).toHaveBeenCalledExactlyOnceWith("valid");
232
+ });
233
+
234
+ it("challenges a request without token and points to the resource metadata", async () => {
235
+ const service = inject(PlatformMcpAuthService);
236
+ const verifier = createVerifier();
237
+
238
+ const result = (await service.verifyMcpRequest(createAuth({verifier}), createContext())) as Response;
239
+
240
+ expect(result).toBeInstanceOf(Response);
241
+ expect(result.status).toBe(401);
242
+ expect(result.headers.get("www-authenticate")).toContain(
243
+ 'resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"'
244
+ );
245
+ expect(verifier.verifyAccessToken).not.toHaveBeenCalled();
246
+ });
247
+
248
+ it("challenges a request with an invalid token without leaking the verifier error", async () => {
249
+ const service = inject(PlatformMcpAuthService);
250
+
251
+ const result = (await service.verifyMcpRequest(
252
+ createAuth({verifier: createVerifier()}),
253
+ createContext({authorization: "Bearer nope"})
254
+ )) as Response;
255
+
256
+ expect(result.status).toBe(401);
257
+ expect(result.headers.get("www-authenticate")).toContain('error="invalid_token"');
258
+ expect(await result.text()).not.toContain("Unknown token");
259
+ });
260
+
261
+ it("rejects a token lacking a required scope", async () => {
262
+ const service = inject(PlatformMcpAuthService);
263
+ const auth = createAuth({verifier: createVerifier(), requiredScopes: ["mcp:write"]});
264
+
265
+ const result = (await service.verifyMcpRequest(auth, createContext({authorization: "Bearer valid"}))) as Response;
266
+
267
+ expect(result.status).toBe(403);
268
+ expect(result.headers.get("www-authenticate")).toContain('error="insufficient_scope"');
269
+ expect(result.headers.get("www-authenticate")).toContain('scope="mcp:write"');
270
+ });
271
+
272
+ it("ignores the Host header of the request in the challenge", async () => {
273
+ const service = inject(PlatformMcpAuthService);
274
+ const auth = createAuth({verifier: createVerifier()});
275
+
276
+ const result = (await service.verifyMcpRequest(auth, createContext({host: "attacker.example.com"}))) as Response;
277
+
278
+ expect(result.headers.get("www-authenticate")).toContain(
279
+ 'resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"'
280
+ );
281
+ expect(result.headers.get("www-authenticate")).not.toContain("attacker.example.com");
282
+ });
283
+
284
+ it("reuses the same verifier across requests", async () => {
285
+ const service = inject(PlatformMcpAuthService);
286
+ const auth = createAuth({verifier: createVerifier()});
287
+ vi.spyOn(service, "getVerifier");
288
+
289
+ await service.verifyMcpRequest(auth, createContext({authorization: "Bearer valid"}));
290
+ await service.verifyMcpRequest(auth, createContext({authorization: "Bearer valid"}));
291
+
292
+ const [first, second] = vi.mocked(service.getVerifier).mock.results;
293
+
294
+ expect(first.value).toBe(second.value);
295
+ });
296
+ });
297
+ });
@@ -0,0 +1,165 @@
1
+ import {
2
+ type AuthInfo,
3
+ bearerAuthChallengeResponse,
4
+ type BearerAuthOptions,
5
+ buildOAuthProtectedResourceMetadata,
6
+ getOAuthProtectedResourceMetadataUrl,
7
+ verifyBearerToken
8
+ } from "@modelcontextprotocol/server";
9
+ import {inject, injectable, injector, logger, type TokenProvider} from "@tsed/di";
10
+ import type {PlatformContext} from "@tsed/platform-http";
11
+ import type {
12
+ PlatformMcpAuthSettings,
13
+ PlatformMcpPreAuth,
14
+ PlatformMcpPreAuthOption,
15
+ PlatformMcpPreAuthSettings
16
+ } from "../../common/index.js";
17
+ import {PlatformTokenVerifier} from "../../common/index.js";
18
+
19
+ export const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
20
+
21
+ /**
22
+ * OAuth resource-server behavior of the protected MCP endpoints: configuration validation,
23
+ * protected resource metadata and bearer token verification.
24
+ *
25
+ * @module platform/mcp
26
+ */
27
+ export class PlatformMcpAuthService {
28
+ protected verifiers = new WeakMap<PlatformMcpAuthSettings, PlatformTokenVerifier>();
29
+
30
+ /**
31
+ * Tells whether the endpoint is protected by an OAuth authorization server, and not only by a custom check.
32
+ */
33
+ isOAuth(auth?: PlatformMcpAuthSettings | PlatformMcpPreAuthSettings): auth is PlatformMcpAuthSettings {
34
+ return Boolean((auth as PlatformMcpAuthSettings)?.issuer);
35
+ }
36
+
37
+ /**
38
+ * Runs the custom authentication check of an endpoint.
39
+ *
40
+ * @returns The identity of the caller, or `undefined` when the check does not apply to the request.
41
+ */
42
+ async preAuth(preAuth: PlatformMcpPreAuthOption, $ctx: PlatformContext): Promise<AuthInfo | undefined> {
43
+ if (!injector().providers.has(preAuth)) {
44
+ // not a registered provider: the option is the check itself
45
+ return (preAuth as ($ctx: PlatformContext) => AuthInfo | undefined)($ctx);
46
+ }
47
+
48
+ const instance = inject(preAuth as TokenProvider<PlatformMcpPreAuth>);
49
+
50
+ return instance.preAuth($ctx);
51
+ }
52
+
53
+ /**
54
+ * Returns the token verifier of an endpoint, created once per `auth` configuration.
55
+ */
56
+ getVerifier(auth: PlatformMcpAuthSettings, resource: URL): PlatformTokenVerifier {
57
+ let verifier = this.verifiers.get(auth);
58
+
59
+ if (!verifier) {
60
+ verifier = new PlatformTokenVerifier(auth, resource);
61
+ this.verifiers.set(auth, verifier);
62
+ }
63
+
64
+ return verifier;
65
+ }
66
+
67
+ /**
68
+ * Verifies the bearer token of the incoming request.
69
+ *
70
+ * @returns The verified identity, or the `401`/`403` challenge to send back to the client.
71
+ */
72
+ async verifyMcpRequest(auth: PlatformMcpAuthSettings, $ctx: PlatformContext): Promise<AuthInfo | Response> {
73
+ const resource = this.getResourceUrl(auth);
74
+
75
+ const options = {
76
+ verifier: this.getVerifier(auth, resource),
77
+ requiredScopes: auth.requiredScopes,
78
+ resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(resource)
79
+ } satisfies BearerAuthOptions;
80
+
81
+ try {
82
+ return await verifyBearerToken($ctx.request.headers.authorization, options);
83
+ } catch (error) {
84
+ return bearerAuthChallengeResponse(error, options);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Rejects an `auth` configuration that cannot work or would be unsafe, before any route is mounted.
90
+ */
91
+ validate(path: string, auth: PlatformMcpAuthSettings) {
92
+ const mode = PlatformTokenVerifier.getMode(auth);
93
+
94
+ if (!auth.verifier && mode === "introspection" && !(auth.clientId && auth.clientSecret)) {
95
+ throw new Error(`MCP endpoint "${path}": the introspection mode requires auth.clientId and auth.clientSecret.`);
96
+ }
97
+
98
+ if (!auth.verifier && auth.audience === false) {
99
+ if (mode === "offline") {
100
+ throw new Error(`MCP endpoint "${path}": auth.audience cannot be disabled in offline mode.`);
101
+ }
102
+
103
+ logger().warn({
104
+ event: "MCP_AUTH_AUDIENCE_DISABLED",
105
+ message: `MCP endpoint "${path}": the audience check is disabled, any active token of ${auth.issuer} is accepted.`
106
+ });
107
+ }
108
+
109
+ if (!auth.resource) {
110
+ // the resource is never derived from the request: the Host header is controlled by the caller
111
+ throw new Error(`MCP endpoint "${path}": auth.resource is required.`);
112
+ }
113
+
114
+ if (!URL.canParse(auth.resource)) {
115
+ throw new Error(`MCP endpoint "${path}": auth.resource must be an absolute URL.`);
116
+ }
117
+
118
+ if (!URL.canParse(auth.issuer)) {
119
+ throw new Error(`MCP endpoint "${path}": auth.issuer must be an absolute URL.`);
120
+ }
121
+
122
+ try {
123
+ // surfaces at startup what the metadata route would otherwise fail on (insecure issuer, invalid documentation URL)
124
+ this.getProtectedResourceMetadata(auth, this.getResourceUrl(auth));
125
+ } catch (error) {
126
+ throw new Error(`MCP endpoint "${path}": invalid auth configuration. ${(error as Error).message}`);
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Builds the OAuth 2.0 Protected Resource Metadata (RFC 9728) advertised for the given resource.
132
+ *
133
+ * @throws When the issuer is not an HTTPS URL (outside localhost) and `allowInsecureRequests` is not set.
134
+ */
135
+ getProtectedResourceMetadata(auth: PlatformMcpAuthSettings, resource: URL) {
136
+ return buildOAuthProtectedResourceMetadata({
137
+ // the SDK builder only reads the issuer of the authorization server metadata
138
+ oauthMetadata: {issuer: auth.issuer} as never,
139
+ resourceServerUrl: resource,
140
+ scopesSupported: auth.scopesSupported,
141
+ resourceName: auth.resourceName,
142
+ serviceDocumentationUrl: auth.resourceDocumentation ? new URL(auth.resourceDocumentation) : undefined,
143
+ dangerouslyAllowInsecureIssuerUrl: auth.allowInsecureRequests
144
+ });
145
+ }
146
+
147
+ /**
148
+ * Path of the RFC 9728 metadata document describing the MCP endpoint mounted on `path`.
149
+ */
150
+ getProtectedResourceMetadataPath(path: string) {
151
+ return `${PROTECTED_RESOURCE_METADATA_PATH}${path === "/" ? "" : path}`;
152
+ }
153
+
154
+ /**
155
+ * Canonical URL of the MCP endpoint, as configured in `auth.resource`.
156
+ *
157
+ * It is used for the metadata document, the bearer challenge and the expected audience, and is never
158
+ * derived from the incoming request.
159
+ */
160
+ getResourceUrl(auth: PlatformMcpAuthSettings) {
161
+ return new URL(auth.resource);
162
+ }
163
+ }
164
+
165
+ injectable(PlatformMcpAuthService);
@@ -2,8 +2,10 @@ import {afterEach, beforeEach, describe, expect, it, vi} from "vitest";
2
2
  import {EventEmitter} from "node:events";
3
3
  import {PlatformFastifyResponse} from "@tsed/platform-fastify";
4
4
  import {PlatformMcpModule} from "./PlatformMcpModule.js";
5
+ import type {PlatformMcpAuthSettings} from "../../common/interfaces/PlatformMcpAuthSettings.js";
5
6
  import {PlatformTest} from "@tsed/platform-http/testing";
6
7
  import {application} from "@tsed/platform-http";
8
+ import {logger} from "@tsed/di";
7
9
 
8
10
  const {createMcpServer, resolveMcpServerOptions} = vi.hoisted(() => ({
9
11
  createMcpServer: vi.fn(),
@@ -136,6 +138,112 @@ describe("PlatformMcpModule", () => {
136
138
  });
137
139
  });
138
140
 
141
+ describe("upstream validation", () => {
142
+ it("fails when the upstream uses identity placeholders without auth", async () => {
143
+ const {module} = await createModule();
144
+ module["settings"] = {upstream: {type: "http", url: "http://localhost/mcp", headers: {authorization: "Bearer ${OAUTH_TOKEN}"}}};
145
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
146
+
147
+ expect(() => module.$onRoutesInit()).toThrow("declares no auth");
148
+ expect(application().post).not.toHaveBeenCalled();
149
+ });
150
+
151
+ it("fails when the introspection mode has no client credentials", async () => {
152
+ const {module} = await createModule();
153
+ module["settings"] = {auth: {issuer: "https://auth.example.com", resource: "https://api.example.com/mcp", mode: "introspection"}};
154
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
155
+
156
+ expect(() => module.$onRoutesInit()).toThrow("requires auth.clientId and auth.clientSecret");
157
+ });
158
+
159
+ it.each([
160
+ ["auth.resource is required", {issuer: "https://auth.example.com"}],
161
+ [
162
+ "auth.audience cannot be disabled in offline mode",
163
+ {issuer: "https://auth.example.com", resource: "https://api.example.com/mcp", audience: false}
164
+ ],
165
+ ["auth.issuer must be an absolute URL", {issuer: "auth.example.com", resource: "https://api.example.com/mcp"}],
166
+ ["Issuer URL must be HTTPS", {issuer: "http://auth.example.com", resource: "https://api.example.com/mcp"}],
167
+ ["auth.resource must be an absolute URL", {issuer: "https://auth.example.com", resource: "/mcp"}]
168
+ ] as [string, Partial<PlatformMcpAuthSettings>][])("fails when %s", async (message, auth) => {
169
+ const {module} = await createModule();
170
+ module["settings"] = {auth: auth as PlatformMcpAuthSettings};
171
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
172
+
173
+ expect(() => module.$onRoutesInit()).toThrow(message);
174
+ });
175
+
176
+ it("warns when the audience check is disabled in introspection mode", async () => {
177
+ const {module} = await createModule();
178
+ module["settings"] = {
179
+ auth: {
180
+ issuer: "https://auth.example.com",
181
+ resource: "https://api.example.com/mcp",
182
+ clientId: "id",
183
+ clientSecret: "secret",
184
+ audience: false
185
+ }
186
+ };
187
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
188
+ vi.spyOn(application(), "get").mockReturnValue(undefined as never);
189
+ vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
190
+
191
+ module.$onRoutesInit();
192
+
193
+ expect(logger().warn).toHaveBeenCalledWith(expect.objectContaining({event: "MCP_AUTH_AUDIENCE_DISABLED"}));
194
+ expect(application().post).toHaveBeenCalledOnce();
195
+ });
196
+
197
+ it("fails when auth declares neither an issuer nor a custom check", async () => {
198
+ const {module} = await createModule();
199
+ module["settings"] = {auth: {} as PlatformMcpAuthSettings};
200
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
201
+
202
+ expect(() => module.$onRoutesInit()).toThrow("auth requires an issuer, a preAuth check, or both");
203
+ });
204
+
205
+ it("mounts an endpoint only protected by a custom check without OAuth metadata route", async () => {
206
+ const {module} = await createModule();
207
+ module["settings"] = {path: "/mcp/a", auth: {preAuth: vi.fn()}};
208
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
209
+ vi.spyOn(application(), "get").mockReturnValue(undefined as never);
210
+
211
+ module.$onRoutesInit();
212
+
213
+ expect(application().get).not.toHaveBeenCalled();
214
+ expect(module.$logRoutes([])).toEqual([{method: "POST", name: "PlatformMcpModule.dispatch()", url: "/mcp/a"}]);
215
+ });
216
+
217
+ it("accepts upstream placeholders on an endpoint only protected by a custom check", async () => {
218
+ const {module} = await createModule();
219
+ module["settings"] = {
220
+ auth: {preAuth: vi.fn()},
221
+ upstream: {type: "http", url: "http://localhost/mcp", headers: {authorization: "Bearer ${OAUTH_TOKEN}"}}
222
+ };
223
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
224
+
225
+ expect(() => module.$onRoutesInit()).not.toThrow();
226
+ });
227
+
228
+ it("registers the protected resource metadata route of protected endpoints", async () => {
229
+ const {module} = await createModule();
230
+ module["settings"] = {
231
+ path: "/mcp/a",
232
+ auth: {issuer: "https://auth.example.com", resource: "https://api.example.com/mcp/a", verifier: {verifyAccessToken: vi.fn()}}
233
+ };
234
+ vi.spyOn(application(), "post").mockReturnValue(undefined as never);
235
+ vi.spyOn(application(), "get").mockReturnValue(undefined as never);
236
+
237
+ module.$onRoutesInit();
238
+
239
+ expect(application().get).toHaveBeenCalledWith("/.well-known/oauth-protected-resource/mcp/a", expect.any(Function));
240
+ expect(module.$logRoutes([])).toEqual([
241
+ {method: "GET", name: "PlatformMcpModule.metadata()", url: "/.well-known/oauth-protected-resource/mcp/a"},
242
+ {method: "POST", name: "PlatformMcpModule.dispatch()", url: "/mcp/a"}
243
+ ]);
244
+ });
245
+ });
246
+
139
247
  describe.each([
140
248
  ["express", createExpressContext],
141
249
  ["fastify", createFastifyContext]
@@ -196,6 +304,18 @@ describe("PlatformMcpModule", () => {
196
304
  expect(transportInstances[0].close).toHaveBeenCalledOnce();
197
305
  });
198
306
 
307
+ it("should close the request server only once when the response closes during the request", async () => {
308
+ const {module} = await createModule();
309
+ const {$ctx, res} = createContext();
310
+ const close = vi.fn();
311
+
312
+ createMcpServer.mockImplementation(() => ({connect: vi.fn().mockImplementation(() => res.emit("close")), close}));
313
+
314
+ await module["dispatch"]({tools: [], prompts: [], resources: []}, $ctx);
315
+
316
+ expect(close).toHaveBeenCalledOnce();
317
+ });
318
+
199
319
  it("should resolve an isolated server for each request", async () => {
200
320
  const {module, servers} = await createModule();
201
321
  const first = createContext();