@tsed/platform-mcp 8.41.2 → 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.
- 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 +11 -0
- package/lib/esm/common/interfaces/PlatformMcpAuthSettings.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 +112 -0
- package/lib/esm/http/services/PlatformMcpModule.js +60 -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 +11 -0
- package/lib/types/common/interfaces/PlatformMcpAuthSettings.d.ts +81 -0
- package/lib/types/common/interfaces/PlatformMcpSettings.d.ts +10 -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 +61 -0
- package/lib/types/http/services/PlatformMcpModule.d.ts +9 -2
- package/package.json +11 -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 +11 -0
- package/src/common/interfaces/PlatformMcpAuthSettings.ts +82 -0
- package/src/common/interfaces/PlatformMcpSettings.ts +10 -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 +239 -0
- package/src/http/services/PlatformMcpAuthService.ts +137 -0
- package/src/http/services/PlatformMcpModule.spec.ts +89 -0
- package/src/http/services/PlatformMcpModule.ts +79 -9
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import type {AuthInfo} from "@modelcontextprotocol/server";
|
|
2
|
+
import {inject, logger} from "@tsed/di";
|
|
3
|
+
import {PlatformTest} from "@tsed/platform-http/testing";
|
|
4
|
+
import type {PlatformMcpAuthSettings} from "../../common/interfaces/PlatformMcpAuthSettings.js";
|
|
5
|
+
import {PlatformTokenVerifier} from "../../common/domain/PlatformTokenVerifier.js";
|
|
6
|
+
import {PlatformMcpAuthService} from "./PlatformMcpAuthService.js";
|
|
7
|
+
|
|
8
|
+
const authInfo: AuthInfo = {
|
|
9
|
+
token: "valid",
|
|
10
|
+
clientId: "client",
|
|
11
|
+
scopes: ["mcp:read"],
|
|
12
|
+
expiresAt: Math.floor(Date.now() / 1000) + 3600
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function createAuth(opts: Partial<PlatformMcpAuthSettings> = {}): PlatformMcpAuthSettings {
|
|
16
|
+
return {issuer: "https://auth.example.com", resource: "https://api.example.com/mcp", ...opts};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function createContext(headers: Record<string, string> = {}) {
|
|
20
|
+
return PlatformTest.createRequestContext({
|
|
21
|
+
event: {
|
|
22
|
+
request: PlatformTest.createRequest({protocol: "https", headers: {host: "gateway.example.com", ...headers}})
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe("PlatformMcpAuthService", () => {
|
|
28
|
+
beforeEach(() => PlatformTest.create());
|
|
29
|
+
afterEach(() => {
|
|
30
|
+
vi.restoreAllMocks();
|
|
31
|
+
|
|
32
|
+
return PlatformTest.reset();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe("getVerifier()", () => {
|
|
36
|
+
it("creates one verifier per auth configuration", () => {
|
|
37
|
+
const service = inject(PlatformMcpAuthService);
|
|
38
|
+
const auth = createAuth();
|
|
39
|
+
const resource = new URL(auth.resource!);
|
|
40
|
+
|
|
41
|
+
const verifier = service.getVerifier(auth, resource);
|
|
42
|
+
|
|
43
|
+
expect(verifier).toBeInstanceOf(PlatformTokenVerifier);
|
|
44
|
+
expect(service.getVerifier(auth, resource)).toBe(verifier);
|
|
45
|
+
expect(service.getVerifier(createAuth(), resource)).not.toBe(verifier);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe("getProtectedResourceMetadataPath()", () => {
|
|
50
|
+
it("suffixes the well-known path with the endpoint path", () => {
|
|
51
|
+
const service = inject(PlatformMcpAuthService);
|
|
52
|
+
|
|
53
|
+
expect(service.getProtectedResourceMetadataPath("/mcp/directus")).toBe("/.well-known/oauth-protected-resource/mcp/directus");
|
|
54
|
+
expect(service.getProtectedResourceMetadataPath("/")).toBe("/.well-known/oauth-protected-resource");
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe("getResourceUrl()", () => {
|
|
59
|
+
it("returns the configured resource", () => {
|
|
60
|
+
const service = inject(PlatformMcpAuthService);
|
|
61
|
+
|
|
62
|
+
expect(service.getResourceUrl(createAuth()).href).toBe("https://api.example.com/mcp");
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe("getProtectedResourceMetadata()", () => {
|
|
67
|
+
it("advertises the resource and its authorization server", () => {
|
|
68
|
+
const service = inject(PlatformMcpAuthService);
|
|
69
|
+
const auth = createAuth({
|
|
70
|
+
scopesSupported: ["mcp:read", "mcp:write"],
|
|
71
|
+
resourceName: "Orders MCP",
|
|
72
|
+
resourceDocumentation: "https://docs.example.com/mcp"
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
expect(service.getProtectedResourceMetadata(auth, new URL(auth.resource!))).toEqual({
|
|
76
|
+
resource: "https://api.example.com/mcp",
|
|
77
|
+
authorization_servers: ["https://auth.example.com"],
|
|
78
|
+
scopes_supported: ["mcp:read", "mcp:write"],
|
|
79
|
+
resource_name: "Orders MCP",
|
|
80
|
+
resource_documentation: "https://docs.example.com/mcp"
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("refuses a non-HTTPS issuer unless insecure requests are allowed", () => {
|
|
85
|
+
const service = inject(PlatformMcpAuthService);
|
|
86
|
+
const resource = new URL("https://api.example.com/mcp");
|
|
87
|
+
|
|
88
|
+
expect(() => service.getProtectedResourceMetadata(createAuth({issuer: "http://auth.example.com"}), resource)).toThrow(
|
|
89
|
+
"Issuer URL must be HTTPS"
|
|
90
|
+
);
|
|
91
|
+
expect(
|
|
92
|
+
service.getProtectedResourceMetadata(createAuth({issuer: "http://auth.example.com", allowInsecureRequests: true}), resource)
|
|
93
|
+
).toMatchObject({authorization_servers: ["http://auth.example.com"]});
|
|
94
|
+
expect(service.getProtectedResourceMetadata(createAuth({issuer: "http://localhost:3000"}), resource)).toMatchObject({
|
|
95
|
+
authorization_servers: ["http://localhost:3000"]
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe("validate()", () => {
|
|
101
|
+
const verifier = {verifyAccessToken: vi.fn()};
|
|
102
|
+
|
|
103
|
+
it.each([
|
|
104
|
+
["the introspection mode requires auth.clientId and auth.clientSecret", {mode: "introspection"}],
|
|
105
|
+
["the introspection mode requires auth.clientId and auth.clientSecret", {clientId: "gateway"}],
|
|
106
|
+
["auth.audience cannot be disabled in offline mode", {audience: false}],
|
|
107
|
+
["auth.resource is required", {resource: undefined}],
|
|
108
|
+
["auth.resource is required", {resource: undefined, audience: "mcp"}],
|
|
109
|
+
["auth.resource is required", {resource: undefined, verifier}],
|
|
110
|
+
["auth.issuer must be an absolute URL", {issuer: "auth.example.com"}],
|
|
111
|
+
["auth.resource must be an absolute URL", {resource: "/mcp"}],
|
|
112
|
+
["invalid auth configuration. Issuer URL must be HTTPS", {issuer: "http://auth.example.com"}],
|
|
113
|
+
["invalid auth configuration.", {resourceDocumentation: "not a url"}]
|
|
114
|
+
] as [string, Partial<PlatformMcpAuthSettings>][])("throws when %s (%j)", (message, opts) => {
|
|
115
|
+
const service = inject(PlatformMcpAuthService);
|
|
116
|
+
|
|
117
|
+
expect(() => service.validate("/mcp", createAuth(opts))).toThrow(`MCP endpoint "/mcp": ${message}`);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it.each([
|
|
121
|
+
["offline mode with a resource", {}],
|
|
122
|
+
["offline mode with a custom audience", {audience: "mcp"}],
|
|
123
|
+
["introspection mode with client credentials", {clientId: "gateway", clientSecret: "secret"}],
|
|
124
|
+
["a custom verifier", {verifier}],
|
|
125
|
+
["a custom verifier in introspection mode without credentials", {mode: "introspection", verifier}]
|
|
126
|
+
] as [string, Partial<PlatformMcpAuthSettings>][])("accepts %s", (_, opts) => {
|
|
127
|
+
const service = inject(PlatformMcpAuthService);
|
|
128
|
+
|
|
129
|
+
expect(() => service.validate("/mcp", createAuth(opts))).not.toThrow();
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("warns when the audience check is disabled in introspection mode", () => {
|
|
133
|
+
const service = inject(PlatformMcpAuthService);
|
|
134
|
+
vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
|
|
135
|
+
|
|
136
|
+
service.validate("/mcp", createAuth({clientId: "gateway", clientSecret: "secret", audience: false}));
|
|
137
|
+
|
|
138
|
+
expect(logger().warn).toHaveBeenCalledWith(
|
|
139
|
+
expect.objectContaining({event: "MCP_AUTH_AUDIENCE_DISABLED", message: expect.stringContaining('"/mcp"')})
|
|
140
|
+
);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("does not warn when a custom verifier owns the audience check", () => {
|
|
144
|
+
const service = inject(PlatformMcpAuthService);
|
|
145
|
+
vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
|
|
146
|
+
|
|
147
|
+
service.validate("/mcp", createAuth({audience: false, verifier}));
|
|
148
|
+
|
|
149
|
+
expect(logger().warn).not.toHaveBeenCalled();
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
describe("verifyMcpRequest()", () => {
|
|
154
|
+
function createVerifier() {
|
|
155
|
+
return {
|
|
156
|
+
verifyAccessToken: vi.fn(async (token: string): Promise<AuthInfo> => {
|
|
157
|
+
if (token !== "valid") {
|
|
158
|
+
throw new Error("Unknown token");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return authInfo;
|
|
162
|
+
})
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
it("returns the verified identity", async () => {
|
|
167
|
+
const service = inject(PlatformMcpAuthService);
|
|
168
|
+
const verifier = createVerifier();
|
|
169
|
+
|
|
170
|
+
const result = await service.verifyMcpRequest(createAuth({verifier}), createContext({authorization: "Bearer valid"}));
|
|
171
|
+
|
|
172
|
+
expect(result).toEqual(authInfo);
|
|
173
|
+
expect(verifier.verifyAccessToken).toHaveBeenCalledExactlyOnceWith("valid");
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("challenges a request without token and points to the resource metadata", async () => {
|
|
177
|
+
const service = inject(PlatformMcpAuthService);
|
|
178
|
+
const verifier = createVerifier();
|
|
179
|
+
|
|
180
|
+
const result = (await service.verifyMcpRequest(createAuth({verifier}), createContext())) as Response;
|
|
181
|
+
|
|
182
|
+
expect(result).toBeInstanceOf(Response);
|
|
183
|
+
expect(result.status).toBe(401);
|
|
184
|
+
expect(result.headers.get("www-authenticate")).toContain(
|
|
185
|
+
'resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"'
|
|
186
|
+
);
|
|
187
|
+
expect(verifier.verifyAccessToken).not.toHaveBeenCalled();
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("challenges a request with an invalid token without leaking the verifier error", async () => {
|
|
191
|
+
const service = inject(PlatformMcpAuthService);
|
|
192
|
+
|
|
193
|
+
const result = (await service.verifyMcpRequest(
|
|
194
|
+
createAuth({verifier: createVerifier()}),
|
|
195
|
+
createContext({authorization: "Bearer nope"})
|
|
196
|
+
)) as Response;
|
|
197
|
+
|
|
198
|
+
expect(result.status).toBe(401);
|
|
199
|
+
expect(result.headers.get("www-authenticate")).toContain('error="invalid_token"');
|
|
200
|
+
expect(await result.text()).not.toContain("Unknown token");
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it("rejects a token lacking a required scope", async () => {
|
|
204
|
+
const service = inject(PlatformMcpAuthService);
|
|
205
|
+
const auth = createAuth({verifier: createVerifier(), requiredScopes: ["mcp:write"]});
|
|
206
|
+
|
|
207
|
+
const result = (await service.verifyMcpRequest(auth, createContext({authorization: "Bearer valid"}))) as Response;
|
|
208
|
+
|
|
209
|
+
expect(result.status).toBe(403);
|
|
210
|
+
expect(result.headers.get("www-authenticate")).toContain('error="insufficient_scope"');
|
|
211
|
+
expect(result.headers.get("www-authenticate")).toContain('scope="mcp:write"');
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("ignores the Host header of the request in the challenge", async () => {
|
|
215
|
+
const service = inject(PlatformMcpAuthService);
|
|
216
|
+
const auth = createAuth({verifier: createVerifier()});
|
|
217
|
+
|
|
218
|
+
const result = (await service.verifyMcpRequest(auth, createContext({host: "attacker.example.com"}))) as Response;
|
|
219
|
+
|
|
220
|
+
expect(result.headers.get("www-authenticate")).toContain(
|
|
221
|
+
'resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"'
|
|
222
|
+
);
|
|
223
|
+
expect(result.headers.get("www-authenticate")).not.toContain("attacker.example.com");
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it("reuses the same verifier across requests", async () => {
|
|
227
|
+
const service = inject(PlatformMcpAuthService);
|
|
228
|
+
const auth = createAuth({verifier: createVerifier()});
|
|
229
|
+
vi.spyOn(service, "getVerifier");
|
|
230
|
+
|
|
231
|
+
await service.verifyMcpRequest(auth, createContext({authorization: "Bearer valid"}));
|
|
232
|
+
await service.verifyMcpRequest(auth, createContext({authorization: "Bearer valid"}));
|
|
233
|
+
|
|
234
|
+
const [first, second] = vi.mocked(service.getVerifier).mock.results;
|
|
235
|
+
|
|
236
|
+
expect(first.value).toBe(second.value);
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
});
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AuthInfo,
|
|
3
|
+
bearerAuthChallengeResponse,
|
|
4
|
+
type BearerAuthOptions,
|
|
5
|
+
buildOAuthProtectedResourceMetadata,
|
|
6
|
+
getOAuthProtectedResourceMetadataUrl,
|
|
7
|
+
verifyBearerToken
|
|
8
|
+
} from "@modelcontextprotocol/server";
|
|
9
|
+
import {injectable, logger} from "@tsed/di";
|
|
10
|
+
import type {PlatformContext} from "@tsed/platform-http";
|
|
11
|
+
import type {PlatformMcpAuthSettings} from "../../common/interfaces/PlatformMcpAuthSettings.js";
|
|
12
|
+
import {PlatformTokenVerifier} from "../../common/domain/PlatformTokenVerifier.js";
|
|
13
|
+
|
|
14
|
+
export const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* OAuth resource-server behavior of the protected MCP endpoints: configuration validation,
|
|
18
|
+
* protected resource metadata and bearer token verification.
|
|
19
|
+
*
|
|
20
|
+
* @module platform/mcp
|
|
21
|
+
*/
|
|
22
|
+
export class PlatformMcpAuthService {
|
|
23
|
+
protected verifiers = new WeakMap<PlatformMcpAuthSettings, PlatformTokenVerifier>();
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Returns the token verifier of an endpoint, created once per `auth` configuration.
|
|
27
|
+
*/
|
|
28
|
+
getVerifier(auth: PlatformMcpAuthSettings, resource: URL): PlatformTokenVerifier {
|
|
29
|
+
let verifier = this.verifiers.get(auth);
|
|
30
|
+
|
|
31
|
+
if (!verifier) {
|
|
32
|
+
verifier = new PlatformTokenVerifier(auth, resource);
|
|
33
|
+
this.verifiers.set(auth, verifier);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return verifier;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Verifies the bearer token of the incoming request.
|
|
41
|
+
*
|
|
42
|
+
* @returns The verified identity, or the `401`/`403` challenge to send back to the client.
|
|
43
|
+
*/
|
|
44
|
+
async verifyMcpRequest(auth: PlatformMcpAuthSettings, $ctx: PlatformContext): Promise<AuthInfo | Response> {
|
|
45
|
+
const resource = this.getResourceUrl(auth);
|
|
46
|
+
|
|
47
|
+
const options = {
|
|
48
|
+
verifier: this.getVerifier(auth, resource),
|
|
49
|
+
requiredScopes: auth.requiredScopes,
|
|
50
|
+
resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(resource)
|
|
51
|
+
} satisfies BearerAuthOptions;
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
return await verifyBearerToken($ctx.request.headers.authorization, options);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
return bearerAuthChallengeResponse(error, options);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Rejects an `auth` configuration that cannot work or would be unsafe, before any route is mounted.
|
|
62
|
+
*/
|
|
63
|
+
validate(path: string, auth: PlatformMcpAuthSettings) {
|
|
64
|
+
const mode = PlatformTokenVerifier.getMode(auth);
|
|
65
|
+
|
|
66
|
+
if (!auth.verifier && mode === "introspection" && !(auth.clientId && auth.clientSecret)) {
|
|
67
|
+
throw new Error(`MCP endpoint "${path}": the introspection mode requires auth.clientId and auth.clientSecret.`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (!auth.verifier && auth.audience === false) {
|
|
71
|
+
if (mode === "offline") {
|
|
72
|
+
throw new Error(`MCP endpoint "${path}": auth.audience cannot be disabled in offline mode.`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
logger().warn({
|
|
76
|
+
event: "MCP_AUTH_AUDIENCE_DISABLED",
|
|
77
|
+
message: `MCP endpoint "${path}": the audience check is disabled, any active token of ${auth.issuer} is accepted.`
|
|
78
|
+
});
|
|
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
|
+
|
|
86
|
+
if (!URL.canParse(auth.resource)) {
|
|
87
|
+
throw new Error(`MCP endpoint "${path}": auth.resource must be an absolute URL.`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (!URL.canParse(auth.issuer)) {
|
|
91
|
+
throw new Error(`MCP endpoint "${path}": auth.issuer must be an absolute URL.`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
// surfaces at startup what the metadata route would otherwise fail on (insecure issuer, invalid documentation URL)
|
|
96
|
+
this.getProtectedResourceMetadata(auth, this.getResourceUrl(auth));
|
|
97
|
+
} catch (error) {
|
|
98
|
+
throw new Error(`MCP endpoint "${path}": invalid auth configuration. ${(error as Error).message}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Builds the OAuth 2.0 Protected Resource Metadata (RFC 9728) advertised for the given resource.
|
|
104
|
+
*
|
|
105
|
+
* @throws When the issuer is not an HTTPS URL (outside localhost) and `allowInsecureRequests` is not set.
|
|
106
|
+
*/
|
|
107
|
+
getProtectedResourceMetadata(auth: PlatformMcpAuthSettings, resource: URL) {
|
|
108
|
+
return buildOAuthProtectedResourceMetadata({
|
|
109
|
+
// the SDK builder only reads the issuer of the authorization server metadata
|
|
110
|
+
oauthMetadata: {issuer: auth.issuer} as never,
|
|
111
|
+
resourceServerUrl: resource,
|
|
112
|
+
scopesSupported: auth.scopesSupported,
|
|
113
|
+
resourceName: auth.resourceName,
|
|
114
|
+
serviceDocumentationUrl: auth.resourceDocumentation ? new URL(auth.resourceDocumentation) : undefined,
|
|
115
|
+
dangerouslyAllowInsecureIssuerUrl: auth.allowInsecureRequests
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Path of the RFC 9728 metadata document describing the MCP endpoint mounted on `path`.
|
|
121
|
+
*/
|
|
122
|
+
getProtectedResourceMetadataPath(path: string) {
|
|
123
|
+
return `${PROTECTED_RESOURCE_METADATA_PATH}${path === "/" ? "" : path}`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Canonical URL of the MCP endpoint, as configured in `auth.resource`.
|
|
128
|
+
*
|
|
129
|
+
* It is used for the metadata document, the bearer challenge and the expected audience, and is never
|
|
130
|
+
* derived from the incoming request.
|
|
131
|
+
*/
|
|
132
|
+
getResourceUrl(auth: PlatformMcpAuthSettings) {
|
|
133
|
+
return new URL(auth.resource);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
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,81 @@ 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("registers the protected resource metadata route of protected endpoints", async () => {
|
|
198
|
+
const {module} = await createModule();
|
|
199
|
+
module["settings"] = {
|
|
200
|
+
path: "/mcp/a",
|
|
201
|
+
auth: {issuer: "https://auth.example.com", resource: "https://api.example.com/mcp/a", verifier: {verifyAccessToken: vi.fn()}}
|
|
202
|
+
};
|
|
203
|
+
vi.spyOn(application(), "post").mockReturnValue(undefined as never);
|
|
204
|
+
vi.spyOn(application(), "get").mockReturnValue(undefined as never);
|
|
205
|
+
|
|
206
|
+
module.$onRoutesInit();
|
|
207
|
+
|
|
208
|
+
expect(application().get).toHaveBeenCalledWith("/.well-known/oauth-protected-resource/mcp/a", expect.any(Function));
|
|
209
|
+
expect(module.$logRoutes([])).toEqual([
|
|
210
|
+
{method: "GET", name: "PlatformMcpModule.metadata()", url: "/.well-known/oauth-protected-resource/mcp/a"},
|
|
211
|
+
{method: "POST", name: "PlatformMcpModule.dispatch()", url: "/mcp/a"}
|
|
212
|
+
]);
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
|
|
139
216
|
describe.each([
|
|
140
217
|
["express", createExpressContext],
|
|
141
218
|
["fastify", createFastifyContext]
|
|
@@ -196,6 +273,18 @@ describe("PlatformMcpModule", () => {
|
|
|
196
273
|
expect(transportInstances[0].close).toHaveBeenCalledOnce();
|
|
197
274
|
});
|
|
198
275
|
|
|
276
|
+
it("should close the request server only once when the response closes during the request", async () => {
|
|
277
|
+
const {module} = await createModule();
|
|
278
|
+
const {$ctx, res} = createContext();
|
|
279
|
+
const close = vi.fn();
|
|
280
|
+
|
|
281
|
+
createMcpServer.mockImplementation(() => ({connect: vi.fn().mockImplementation(() => res.emit("close")), close}));
|
|
282
|
+
|
|
283
|
+
await module["dispatch"]({tools: [], prompts: [], resources: []}, $ctx);
|
|
284
|
+
|
|
285
|
+
expect(close).toHaveBeenCalledOnce();
|
|
286
|
+
});
|
|
287
|
+
|
|
199
288
|
it("should resolve an isolated server for each request", async () => {
|
|
200
289
|
const {module, servers} = await createModule();
|
|
201
290
|
const first = createContext();
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import {application, type OnRoutesInit, PlatformContext, type PlatformRouteDetails} from "@tsed/platform-http";
|
|
2
|
-
import {constant, injectable} from "@tsed/di";
|
|
1
|
+
import {application, type OnRoutesInit, type PlatformContext, type PlatformRouteDetails} from "@tsed/platform-http";
|
|
2
|
+
import {constant, inject, injectable} from "@tsed/di";
|
|
3
3
|
import type {PlatformMcpSettings} from "../../common/index.js";
|
|
4
4
|
import {NodeStreamableHTTPServerTransport} from "@modelcontextprotocol/node";
|
|
5
|
+
import type {AuthInfo} from "@modelcontextprotocol/server";
|
|
5
6
|
import {useContextHandler} from "@tsed/platform-router";
|
|
6
|
-
import {
|
|
7
|
+
import {attachUpstream} from "../../common/utils/attachUpstream.js";
|
|
8
|
+
import {hasUpstreamPlaceholders} from "../../common/utils/resolveUpstream.js";
|
|
9
|
+
import {createMcpServer, type CreateMcpServerOpts, resolveMcpServerOptions} from "../../common/utils/createMcpServer.js";
|
|
10
|
+
import {PlatformMcpAuthService} from "./PlatformMcpAuthService.js";
|
|
7
11
|
|
|
8
12
|
/**
|
|
9
13
|
* Platform module that mounts the MCP HTTP endpoint and forwards requests to the configured server instance.
|
|
@@ -15,6 +19,7 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
15
19
|
protected settings = constant<PlatformMcpSettings | PlatformMcpSettings[]>("mcp", {});
|
|
16
20
|
protected app = application();
|
|
17
21
|
protected mcps: PlatformRouteDetails[] = [];
|
|
22
|
+
protected platformAuthService = inject(PlatformMcpAuthService);
|
|
18
23
|
private loaded = false;
|
|
19
24
|
|
|
20
25
|
$onRoutesInit() {
|
|
@@ -30,7 +35,28 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
30
35
|
}
|
|
31
36
|
|
|
32
37
|
const path = opts.path || "/mcp";
|
|
33
|
-
|
|
38
|
+
|
|
39
|
+
this.validate(path, opts);
|
|
40
|
+
|
|
41
|
+
const resolvedSettings = {
|
|
42
|
+
...resolveMcpServerOptions(opts),
|
|
43
|
+
path
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
if (opts.auth) {
|
|
47
|
+
const metadataPath = this.platformAuthService.getProtectedResourceMetadataPath(path);
|
|
48
|
+
|
|
49
|
+
this.app.get(
|
|
50
|
+
metadataPath,
|
|
51
|
+
useContextHandler(($ctx) => this.metadata(resolvedSettings, $ctx as PlatformContext))
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
this.mcps.push({
|
|
55
|
+
method: "GET",
|
|
56
|
+
name: "PlatformMcpModule.metadata()",
|
|
57
|
+
url: metadataPath
|
|
58
|
+
} as PlatformRouteDetails);
|
|
59
|
+
}
|
|
34
60
|
|
|
35
61
|
this.app.post(
|
|
36
62
|
path,
|
|
@@ -51,7 +77,52 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
51
77
|
return [...routes, ...this.mcps].filter(Boolean);
|
|
52
78
|
}
|
|
53
79
|
|
|
80
|
+
/**
|
|
81
|
+
* Rejects a configuration that cannot work or would be unsafe, before any route is mounted.
|
|
82
|
+
*/
|
|
83
|
+
protected validate(path: string, opts: PlatformMcpSettings) {
|
|
84
|
+
if (opts.auth) {
|
|
85
|
+
this.platformAuthService.validate(path, opts.auth);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (opts.upstream && !opts.auth && hasUpstreamPlaceholders(opts.upstream)) {
|
|
89
|
+
throw new Error(`MCP endpoint "${path}": the upstream uses \${OAUTH_*} placeholders but the endpoint declares no auth.`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
protected metadata(settings: CreateMcpServerOpts, $ctx: PlatformContext) {
|
|
94
|
+
const auth = settings.auth!;
|
|
95
|
+
const resource = this.platformAuthService.getResourceUrl(auth);
|
|
96
|
+
const body = this.platformAuthService.getProtectedResourceMetadata(auth, resource);
|
|
97
|
+
|
|
98
|
+
return $ctx.response
|
|
99
|
+
.status(200)
|
|
100
|
+
.setHeaders({
|
|
101
|
+
"content-type": "application/json",
|
|
102
|
+
"cache-control": "public, max-age=3600",
|
|
103
|
+
"access-control-allow-origin": "*"
|
|
104
|
+
})
|
|
105
|
+
.body(body);
|
|
106
|
+
}
|
|
107
|
+
|
|
54
108
|
protected async dispatch(settings: CreateMcpServerOpts, $ctx: PlatformContext) {
|
|
109
|
+
let authInfo: AuthInfo | undefined;
|
|
110
|
+
|
|
111
|
+
if (settings.auth) {
|
|
112
|
+
const result = await this.platformAuthService.verifyMcpRequest(settings.auth, $ctx);
|
|
113
|
+
|
|
114
|
+
if (result instanceof Response) {
|
|
115
|
+
return $ctx.response
|
|
116
|
+
.status(result.status)
|
|
117
|
+
.setHeaders(Object.fromEntries(result.headers))
|
|
118
|
+
.body(await result.text());
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
authInfo = result;
|
|
122
|
+
// the SDK transport reads `req.auth` and exposes it to handlers as `ctx.http.authInfo`
|
|
123
|
+
($ctx.getReq() as {auth?: AuthInfo}).auth = authInfo;
|
|
124
|
+
}
|
|
125
|
+
|
|
55
126
|
const server = createMcpServer(settings);
|
|
56
127
|
|
|
57
128
|
const transport = new NodeStreamableHTTPServerTransport({
|
|
@@ -60,8 +131,6 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
60
131
|
...settings.transportOptions
|
|
61
132
|
});
|
|
62
133
|
|
|
63
|
-
const {request, response} = $ctx;
|
|
64
|
-
const res = response.getRes() as any;
|
|
65
134
|
let closed = false;
|
|
66
135
|
|
|
67
136
|
const closeServer = async () => {
|
|
@@ -73,14 +142,15 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
73
142
|
await server.close();
|
|
74
143
|
};
|
|
75
144
|
|
|
76
|
-
|
|
145
|
+
$ctx.getRes()?.once("close", closeServer);
|
|
77
146
|
|
|
78
147
|
try {
|
|
148
|
+
await attachUpstream(server, settings, authInfo);
|
|
79
149
|
await server.connect(transport as any);
|
|
80
|
-
await transport.handleRequest(
|
|
150
|
+
await transport.handleRequest($ctx.getReq(), $ctx.getRes(), $ctx.request.body);
|
|
81
151
|
} finally {
|
|
82
152
|
if (settings.transportOptions?.enableJsonResponse !== false) {
|
|
83
|
-
|
|
153
|
+
$ctx.getRes()?.off?.("close", closeServer);
|
|
84
154
|
await closeServer();
|
|
85
155
|
}
|
|
86
156
|
}
|