@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.
- 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
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import {constant, logger} from "@tsed/di";
|
|
2
2
|
|
|
3
|
+
import {attachUpstream} from "../../common/utils/attachUpstream.js";
|
|
4
|
+
import {hasUpstreamPlaceholders} from "../../common/utils/resolveUpstream.js";
|
|
3
5
|
import type {PlatformMcpSettings} from "../../common/interfaces/PlatformMcpSettings.js";
|
|
4
6
|
import {createMcpServer, resolveMcpServerOptions} from "../../common/utils/createMcpServer.js";
|
|
5
7
|
import {mcpStdioServer} from "./mcpStdioServer.js";
|
|
@@ -17,7 +19,25 @@ export async function mcpServerConnect(mode: "streamable-http" | "stdio") {
|
|
|
17
19
|
if (mode === "streamable-http") {
|
|
18
20
|
logger().info({event: "MCP_SERVER_CONNECT", mode});
|
|
19
21
|
|
|
20
|
-
|
|
22
|
+
if (options.upstream && hasUpstreamPlaceholders(options.upstream)) {
|
|
23
|
+
// the CLI endpoint is not protected by OAuth, so there is no caller identity to interpolate
|
|
24
|
+
throw new Error("The MCP CLI does not support ${OAUTH_*} placeholders in the upstream configuration.");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return mcpStreamableServer(async () => {
|
|
28
|
+
const server = createMcpServer(options);
|
|
29
|
+
|
|
30
|
+
await attachUpstream(server, options);
|
|
31
|
+
|
|
32
|
+
return server;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (options.upstream) {
|
|
37
|
+
logger().warn({
|
|
38
|
+
event: "MCP_SERVER_CONNECT",
|
|
39
|
+
message: "The MCP upstream is only exposed in streamable-http mode and is ignored in stdio mode."
|
|
40
|
+
});
|
|
21
41
|
}
|
|
22
42
|
|
|
23
43
|
const server = createMcpServer(options);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type {McpServer} from "@modelcontextprotocol/server";
|
|
2
2
|
import {logger} from "@tsed/di";
|
|
3
3
|
|
|
4
|
-
export async function mcpStreamableServer(createServer: () => McpServer) {
|
|
4
|
+
export async function mcpStreamableServer(createServer: () => McpServer | Promise<McpServer>) {
|
|
5
5
|
const {NodeStreamableHTTPServerTransport} = await import("@modelcontextprotocol/node");
|
|
6
6
|
// @ts-ignore
|
|
7
7
|
const {default: express} = await import("express");
|
|
@@ -10,7 +10,7 @@ export async function mcpStreamableServer(createServer: () => McpServer) {
|
|
|
10
10
|
app.use(express.json());
|
|
11
11
|
|
|
12
12
|
app.post("/mcp", async (req: any, res: any) => {
|
|
13
|
-
const server = createServer();
|
|
13
|
+
const server = await createServer();
|
|
14
14
|
const transport = new NodeStreamableHTTPServerTransport({
|
|
15
15
|
sessionIdGenerator: undefined,
|
|
16
16
|
enableJsonResponse: true
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import {createServer, type Server} from "node:http";
|
|
2
|
+
import type {AddressInfo} from "node:net";
|
|
3
|
+
import {exportJWK, generateKeyPair, SignJWT} from "jose";
|
|
4
|
+
import type {PlatformMcpAuthSettings} from "../interfaces/PlatformMcpAuthSettings.js";
|
|
5
|
+
import {PlatformTokenVerifier} from "./PlatformTokenVerifier.js";
|
|
6
|
+
|
|
7
|
+
function createVerifier(auth: PlatformMcpAuthSettings, resource: URL) {
|
|
8
|
+
return new PlatformTokenVerifier(auth, resource);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const resource = new URL("https://api.example.com/mcp");
|
|
12
|
+
|
|
13
|
+
describe("PlatformTokenVerifier", () => {
|
|
14
|
+
let server: Server;
|
|
15
|
+
let issuer: string;
|
|
16
|
+
let keys: Awaited<ReturnType<typeof generateKeyPair>>;
|
|
17
|
+
let requests: {url: string; authorization?: string; body: string}[];
|
|
18
|
+
let introspection: Record<string, unknown>;
|
|
19
|
+
let failing: string[];
|
|
20
|
+
|
|
21
|
+
const exp = () => Math.floor(Date.now() / 1000) + 3600;
|
|
22
|
+
|
|
23
|
+
function sign({aud = resource.href, ...claims}: Record<string, unknown> = {}, key = keys.privateKey) {
|
|
24
|
+
return new SignJWT({client_id: "client", scope: "mcp:read mcp:write", ...claims})
|
|
25
|
+
.setProtectedHeader({alg: "RS256", kid: "key", typ: "at+jwt"})
|
|
26
|
+
.setIssuedAt()
|
|
27
|
+
.setJti(String(Math.random()))
|
|
28
|
+
.setIssuer(issuer)
|
|
29
|
+
.setAudience(aud as string)
|
|
30
|
+
.setSubject("user-1")
|
|
31
|
+
.setExpirationTime(exp())
|
|
32
|
+
.sign(key);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function auth(opts: Partial<PlatformMcpAuthSettings> = {}): PlatformMcpAuthSettings {
|
|
36
|
+
return {issuer, resource: resource.href, allowInsecureRequests: true, ...opts};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
beforeAll(async () => {
|
|
40
|
+
keys = await generateKeyPair("RS256");
|
|
41
|
+
|
|
42
|
+
const jwk = {...(await exportJWK(keys.publicKey)), kid: "key", alg: "RS256", use: "sig"};
|
|
43
|
+
|
|
44
|
+
server = createServer((req, res) => {
|
|
45
|
+
let body = "";
|
|
46
|
+
|
|
47
|
+
req.on("data", (chunk) => (body += chunk));
|
|
48
|
+
req.on("end", () => {
|
|
49
|
+
requests.push({url: req.url!, authorization: req.headers.authorization, body});
|
|
50
|
+
|
|
51
|
+
const routes: Record<string, unknown> = {
|
|
52
|
+
"/.well-known/openid-configuration": {
|
|
53
|
+
issuer,
|
|
54
|
+
jwks_uri: `${issuer}/jwks`,
|
|
55
|
+
introspection_endpoint: `${issuer}/introspect`
|
|
56
|
+
},
|
|
57
|
+
"/jwks": {keys: [jwk]},
|
|
58
|
+
"/introspect": introspection
|
|
59
|
+
};
|
|
60
|
+
const found = !failing.includes(req.url!) && routes[req.url!];
|
|
61
|
+
|
|
62
|
+
res.writeHead(found ? 200 : 500, {"content-type": "application/json"}).end(JSON.stringify(found || {}));
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
67
|
+
|
|
68
|
+
issuer = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
beforeEach(() => {
|
|
72
|
+
requests = [];
|
|
73
|
+
failing = [];
|
|
74
|
+
introspection = {active: true, client_id: "client", scope: "mcp:read", exp: exp(), sub: "user-1", aud: resource.href};
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
afterAll(() => new Promise((resolve) => server.close(resolve)));
|
|
78
|
+
|
|
79
|
+
describe("getMode()", () => {
|
|
80
|
+
it("defaults to offline, and to introspection when client credentials are configured", () => {
|
|
81
|
+
expect(PlatformTokenVerifier.getMode({issuer: "https://auth", resource: "https://api"})).toBe("offline");
|
|
82
|
+
expect(PlatformTokenVerifier.getMode({issuer: "https://auth", resource: "https://api", clientId: "id", clientSecret: "secret"})).toBe(
|
|
83
|
+
"introspection"
|
|
84
|
+
);
|
|
85
|
+
expect(PlatformTokenVerifier.getMode({issuer: "https://auth", resource: "https://api", clientId: "id", mode: "offline"})).toBe(
|
|
86
|
+
"offline"
|
|
87
|
+
);
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
describe("offline", () => {
|
|
92
|
+
it("verifies a JWT against the issuer JWKS", async () => {
|
|
93
|
+
const token = await sign();
|
|
94
|
+
const authInfo = await createVerifier(auth(), resource).verifyAccessToken(token);
|
|
95
|
+
|
|
96
|
+
expect(authInfo).toMatchObject({
|
|
97
|
+
token,
|
|
98
|
+
clientId: "client",
|
|
99
|
+
scopes: ["mcp:read", "mcp:write"],
|
|
100
|
+
expiresAt: expect.any(Number),
|
|
101
|
+
extra: {sub: "user-1", iss: issuer}
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("discovers and fetches the JWKS once per endpoint", async () => {
|
|
106
|
+
const settings = auth();
|
|
107
|
+
|
|
108
|
+
const verifier = createVerifier(settings, resource);
|
|
109
|
+
|
|
110
|
+
await verifier.verifyAccessToken(await sign());
|
|
111
|
+
await verifier.verifyAccessToken(await sign());
|
|
112
|
+
|
|
113
|
+
expect(requests.map(({url}) => url)).toEqual(["/.well-known/openid-configuration", "/jwks"]);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it("skips the discovery when the JWKS URL is configured", async () => {
|
|
117
|
+
const verifier = createVerifier(auth({jwksUri: `${issuer}/jwks`}), resource);
|
|
118
|
+
|
|
119
|
+
await expect(verifier.verifyAccessToken(await sign())).resolves.toBeDefined();
|
|
120
|
+
expect(requests.map(({url}) => url)).toEqual(["/jwks"]);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it("rejects a token issued for another audience", async () => {
|
|
124
|
+
const verifier = createVerifier(auth(), new URL("https://api.example.com/other"));
|
|
125
|
+
|
|
126
|
+
await expect(verifier.verifyAccessToken(await sign())).rejects.toMatchObject({code: "invalid_token"});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("accepts the configured audience", async () => {
|
|
130
|
+
const verifier = createVerifier(auth({audience: "custom"}), resource);
|
|
131
|
+
|
|
132
|
+
await expect(verifier.verifyAccessToken(await sign({aud: "custom"}))).resolves.toBeDefined();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("rejects a token signed with an unknown key", async () => {
|
|
136
|
+
const other = await generateKeyPair("RS256");
|
|
137
|
+
const verifier = createVerifier(auth(), resource);
|
|
138
|
+
|
|
139
|
+
await expect(verifier.verifyAccessToken(await sign({}, other.privateKey))).rejects.toMatchObject({code: "invalid_token"});
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it("rejects opaque tokens", async () => {
|
|
143
|
+
await expect(createVerifier(auth(), resource).verifyAccessToken("opaque")).rejects.toMatchObject({code: "invalid_token"});
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("reports a server error when the issuer metadata cannot be loaded, then retries", async () => {
|
|
147
|
+
const settings = auth();
|
|
148
|
+
failing = ["/.well-known/openid-configuration", "/.well-known/oauth-authorization-server"];
|
|
149
|
+
|
|
150
|
+
const verifier = createVerifier(settings, resource);
|
|
151
|
+
|
|
152
|
+
await expect(verifier.verifyAccessToken(await sign())).rejects.toMatchObject({code: "server_error"});
|
|
153
|
+
|
|
154
|
+
failing = [];
|
|
155
|
+
|
|
156
|
+
await expect(verifier.verifyAccessToken(await sign())).resolves.toBeDefined();
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("reports a server error when the JWKS cannot be fetched", async () => {
|
|
160
|
+
failing = ["/jwks"];
|
|
161
|
+
|
|
162
|
+
await expect(createVerifier(auth(), resource).verifyAccessToken(await sign())).rejects.toMatchObject({code: "server_error"});
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
describe("custom verifier", () => {
|
|
167
|
+
const authInfo = {token: "abc", clientId: "client", scopes: [], expiresAt: 1};
|
|
168
|
+
|
|
169
|
+
it("delegates to the configured verifier instead of the built-in modes", async () => {
|
|
170
|
+
const verifyAccessToken = vi.fn().mockResolvedValue(authInfo);
|
|
171
|
+
const verifier = createVerifier(auth({verifier: {verifyAccessToken}}), resource);
|
|
172
|
+
|
|
173
|
+
await expect(verifier.verifyAccessToken("abc")).resolves.toBe(authInfo);
|
|
174
|
+
expect(verifyAccessToken).toHaveBeenCalledExactlyOnceWith("abc");
|
|
175
|
+
expect(requests).toEqual([]);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it("reports any verifier failure as an invalid token without leaking its message", async () => {
|
|
179
|
+
const verifier = createVerifier(auth({verifier: {verifyAccessToken: vi.fn().mockRejectedValue(new Error("db down"))}}), resource);
|
|
180
|
+
|
|
181
|
+
await expect(verifier.verifyAccessToken("abc")).rejects.toMatchObject({code: "invalid_token", message: "Invalid access token"});
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
describe("introspection", () => {
|
|
186
|
+
const credentials = {clientId: "gateway", clientSecret: "s3cret"};
|
|
187
|
+
|
|
188
|
+
it("asks the authorization server with the endpoint credentials", async () => {
|
|
189
|
+
const authInfo = await createVerifier(auth(credentials), resource).verifyAccessToken("opaque");
|
|
190
|
+
|
|
191
|
+
expect(authInfo).toMatchObject({token: "opaque", clientId: "client", scopes: ["mcp:read"], extra: {sub: "user-1"}});
|
|
192
|
+
expect(requests.at(-1)).toMatchObject({
|
|
193
|
+
url: "/introspect",
|
|
194
|
+
authorization: `Basic ${Buffer.from("gateway:s3cret").toString("base64")}`,
|
|
195
|
+
body: expect.stringContaining("token=opaque")
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("skips the discovery when the introspection endpoint is configured", async () => {
|
|
200
|
+
const verifier = createVerifier(auth({...credentials, introspectionEndpoint: `${issuer}/introspect`}), resource);
|
|
201
|
+
|
|
202
|
+
await expect(verifier.verifyAccessToken("opaque")).resolves.toBeDefined();
|
|
203
|
+
expect(requests.map(({url}) => url)).toEqual(["/introspect"]);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it("drops the oldest cached result when the cache is full", async () => {
|
|
207
|
+
const verifier = createVerifier(auth(credentials), resource);
|
|
208
|
+
const cache: Map<string, unknown> = verifier["cache"];
|
|
209
|
+
|
|
210
|
+
for (let index = 0; index < 1000; index++) {
|
|
211
|
+
cache.set(`token-${index}`, {authInfo: {}, until: Date.now() + 60_000});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
await verifier.verifyAccessToken("opaque");
|
|
215
|
+
|
|
216
|
+
expect(cache.size).toBe(1000);
|
|
217
|
+
expect(cache.has("token-0")).toBe(false);
|
|
218
|
+
expect(cache.has("token-1")).toBe(true);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it("maps the scp, azp and multi-valued aud claims of the introspection response", async () => {
|
|
222
|
+
introspection = {active: true, azp: "authorized-party", scp: ["mcp:read", "mcp:write"], exp: exp(), aud: ["other", resource.href]};
|
|
223
|
+
|
|
224
|
+
await expect(createVerifier(auth(credentials), resource).verifyAccessToken("opaque")).resolves.toMatchObject({
|
|
225
|
+
clientId: "authorized-party",
|
|
226
|
+
scopes: ["mcp:read", "mcp:write"]
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("rejects inactive tokens", async () => {
|
|
231
|
+
introspection = {active: false};
|
|
232
|
+
|
|
233
|
+
await expect(createVerifier(auth(credentials), resource).verifyAccessToken("opaque")).rejects.toMatchObject({
|
|
234
|
+
code: "invalid_token"
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it("rejects tokens reported for another issuer or audience", async () => {
|
|
239
|
+
introspection = {...introspection, iss: "https://other"};
|
|
240
|
+
|
|
241
|
+
await expect(createVerifier(auth(credentials), resource).verifyAccessToken("a")).rejects.toMatchObject({
|
|
242
|
+
code: "invalid_token"
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
introspection = {...introspection, iss: issuer, aud: "https://api.example.com/other"};
|
|
246
|
+
|
|
247
|
+
await expect(createVerifier(auth(credentials), resource).verifyAccessToken("b")).rejects.toMatchObject({
|
|
248
|
+
code: "invalid_token"
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
introspection = {...introspection, aud: [resource.href]};
|
|
252
|
+
|
|
253
|
+
await expect(createVerifier(auth(credentials), resource).verifyAccessToken("c")).resolves.toBeDefined();
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it("rejects tokens reported without audience", async () => {
|
|
257
|
+
introspection = {...introspection, aud: undefined};
|
|
258
|
+
|
|
259
|
+
await expect(createVerifier(auth(credentials), resource).verifyAccessToken("opaque")).rejects.toMatchObject({
|
|
260
|
+
code: "invalid_token"
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it("accepts tokens without audience when the audience check is disabled", async () => {
|
|
265
|
+
introspection = {...introspection, aud: undefined};
|
|
266
|
+
|
|
267
|
+
const verifier = createVerifier(auth({...credentials, audience: false}), resource);
|
|
268
|
+
|
|
269
|
+
await expect(verifier.verifyAccessToken("opaque")).resolves.toMatchObject({clientId: "client"});
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
it("caches the introspection result", async () => {
|
|
273
|
+
const settings = auth(credentials);
|
|
274
|
+
|
|
275
|
+
const verifier = createVerifier(settings, resource);
|
|
276
|
+
|
|
277
|
+
await verifier.verifyAccessToken("opaque");
|
|
278
|
+
await verifier.verifyAccessToken("opaque");
|
|
279
|
+
|
|
280
|
+
expect(requests.filter(({url}) => url === "/introspect")).toHaveLength(1);
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
it("caches a response without expiration for the whole ttl", async () => {
|
|
284
|
+
introspection = {...introspection, exp: undefined};
|
|
285
|
+
|
|
286
|
+
const verifier = createVerifier(auth(credentials), resource);
|
|
287
|
+
|
|
288
|
+
await verifier.verifyAccessToken("opaque");
|
|
289
|
+
await verifier.verifyAccessToken("opaque");
|
|
290
|
+
|
|
291
|
+
expect(requests.filter(({url}) => url === "/introspect")).toHaveLength(1);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it("does not cache when cacheTtl is 0", async () => {
|
|
295
|
+
const settings = auth({...credentials, cacheTtl: 0});
|
|
296
|
+
|
|
297
|
+
const verifier = createVerifier(settings, resource);
|
|
298
|
+
|
|
299
|
+
await verifier.verifyAccessToken("opaque");
|
|
300
|
+
await verifier.verifyAccessToken("opaque");
|
|
301
|
+
|
|
302
|
+
expect(requests.filter(({url}) => url === "/introspect")).toHaveLength(2);
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it("reports a server error when the introspection endpoint fails", async () => {
|
|
306
|
+
failing = ["/introspect"];
|
|
307
|
+
|
|
308
|
+
await expect(createVerifier(auth(credentials), resource).verifyAccessToken("opaque")).rejects.toMatchObject({
|
|
309
|
+
code: "server_error"
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
});
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import {createHash} from "node:crypto";
|
|
2
|
+
import {type AuthInfo, OAuthError, type OAuthTokenVerifier} 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
|
+
import type {PlatformMcpAuthSettings} from "../interfaces/PlatformMcpAuthSettings.js";
|
|
8
|
+
|
|
9
|
+
const DEFAULT_CACHE_TTL = 60;
|
|
10
|
+
const MAX_CACHE_SIZE = 1000;
|
|
11
|
+
// oauth4webapi failures caused by the authorization server or the configuration, not by the presented token
|
|
12
|
+
const SERVER_ERROR_CODES = [
|
|
13
|
+
"OAUTH_RESPONSE_IS_NOT_JSON",
|
|
14
|
+
"OAUTH_RESPONSE_IS_NOT_CONFORM",
|
|
15
|
+
"OAUTH_MISSING_SERVER_METADATA",
|
|
16
|
+
"OAUTH_INVALID_SERVER_METADATA",
|
|
17
|
+
"OAUTH_HTTP_REQUEST_FORBIDDEN",
|
|
18
|
+
"OAUTH_REQUEST_PROTOCOL_FORBIDDEN"
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
type Claims = Record<string, unknown> & {
|
|
22
|
+
aud?: string | string[];
|
|
23
|
+
iss?: string;
|
|
24
|
+
exp?: number;
|
|
25
|
+
scope?: string;
|
|
26
|
+
client_id?: string;
|
|
27
|
+
azp?: string;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
type OAuth = typeof import("oauth4webapi");
|
|
31
|
+
type AuthorizationServer = import("oauth4webapi").AuthorizationServer;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Access token verifier of a protected MCP endpoint.
|
|
35
|
+
*
|
|
36
|
+
* - `offline`: validates the JWT access token (RFC 9068) against the authorization server JWKS, plus issuer, audience and expiration.
|
|
37
|
+
* - `introspection`: asks the authorization server (RFC 7662) with the endpoint's client credentials.
|
|
38
|
+
* - `auth.verifier`: delegates to the custom verifier, replacing the built-in modes.
|
|
39
|
+
*
|
|
40
|
+
* The built-in modes rely on `oauth4webapi`, imported lazily.
|
|
41
|
+
*
|
|
42
|
+
* @module platform/mcp
|
|
43
|
+
*/
|
|
44
|
+
export class PlatformTokenVerifier implements OAuthTokenVerifier {
|
|
45
|
+
readonly mode: "offline" | "introspection";
|
|
46
|
+
readonly audience: string | false;
|
|
47
|
+
/**
|
|
48
|
+
* Kept as a single instance per endpoint: oauth4webapi caches the JWKS against it.
|
|
49
|
+
*/
|
|
50
|
+
protected authorizationServer?: Promise<AuthorizationServer>;
|
|
51
|
+
protected cache = new Map<string, {authInfo: AuthInfo; until: number}>();
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param auth Auth settings of the endpoint.
|
|
55
|
+
* @param resource Canonical URL of the endpoint, used as the expected audience unless `auth.audience` is set.
|
|
56
|
+
*/
|
|
57
|
+
constructor(
|
|
58
|
+
protected auth: PlatformMcpAuthSettings,
|
|
59
|
+
protected resource: URL
|
|
60
|
+
) {
|
|
61
|
+
this.audience = auth.audience ?? resource.href;
|
|
62
|
+
this.mode = PlatformTokenVerifier.getMode(auth);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Verification mode of an endpoint: explicit `mode`, else introspection when client credentials are configured.
|
|
67
|
+
*/
|
|
68
|
+
static getMode(auth: PlatformMcpAuthSettings): "offline" | "introspection" {
|
|
69
|
+
return auth.mode || (auth.clientId ? "introspection" : "offline");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
verifyAccessToken(token: string): Promise<AuthInfo> {
|
|
73
|
+
if (this.auth.verifier) {
|
|
74
|
+
return this.verifyWithCustomVerifier(token);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return this.mode === "introspection" ? this.verifyWithIntrospection(token) : this.verifyOffline(token);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
protected async verifyWithCustomVerifier(token: string) {
|
|
81
|
+
const {verifier} = this.auth;
|
|
82
|
+
const instance = isFunction((verifier as OAuthTokenVerifier).verifyAccessToken)
|
|
83
|
+
? (verifier as OAuthTokenVerifier)
|
|
84
|
+
: inject<OAuthTokenVerifier>(verifier as never);
|
|
85
|
+
|
|
86
|
+
try {
|
|
87
|
+
return await instance.verifyAccessToken(token);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
// any verifier failure means the token cannot be trusted: answer with a 401 challenge without leaking the cause
|
|
90
|
+
throw error instanceof OAuthError ? error : new PlatformInvalidToken("Invalid access token");
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
protected async verifyWithIntrospection(token: string) {
|
|
95
|
+
const key = createHash("sha256").update(token).digest("hex");
|
|
96
|
+
const now = Date.now();
|
|
97
|
+
const cached = this.cache.get(key);
|
|
98
|
+
|
|
99
|
+
if (cached && cached.until > now) {
|
|
100
|
+
return cached.authInfo;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
this.cache.delete(key);
|
|
104
|
+
|
|
105
|
+
const authInfo = await this.introspect(token);
|
|
106
|
+
const ttl = (this.auth.cacheTtl ?? DEFAULT_CACHE_TTL) * 1000;
|
|
107
|
+
|
|
108
|
+
if (ttl > 0) {
|
|
109
|
+
if (this.cache.size >= MAX_CACHE_SIZE) {
|
|
110
|
+
this.cache.delete(this.cache.keys().next().value!);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// RFC 7662 responses may omit `exp`: the result is then cached for the whole ttl
|
|
114
|
+
this.cache.set(key, {authInfo, until: authInfo.expiresAt ? Math.min(now + ttl, authInfo.expiresAt * 1000) : now + ttl});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return authInfo;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
protected async verifyOffline(token: string) {
|
|
121
|
+
const audience = this.audience || this.resource.href;
|
|
122
|
+
const oauth = await import("oauth4webapi");
|
|
123
|
+
const as = await this.getAuthorizationServer(oauth);
|
|
124
|
+
// only the Authorization header of this request is read by the validation
|
|
125
|
+
const request = new Request("https://resource.invalid", {headers: {authorization: `Bearer ${token}`}});
|
|
126
|
+
|
|
127
|
+
try {
|
|
128
|
+
return this.toAuthInfo(token, await oauth.validateJwtAccessToken(as, request, audience, this.getRequestOptions(oauth)));
|
|
129
|
+
} catch (error) {
|
|
130
|
+
const isTokenError =
|
|
131
|
+
error instanceof oauth.UnsupportedOperationError ||
|
|
132
|
+
(error instanceof oauth.OperationProcessingError && !SERVER_ERROR_CODES.includes(error.code!));
|
|
133
|
+
|
|
134
|
+
// an unreachable JWKS endpoint must not be reported to the client as an invalid token
|
|
135
|
+
throw isTokenError ? new PlatformInvalidToken("Invalid access token") : new PlatformServerError("Unable to verify the access token");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
protected async introspect(token: string) {
|
|
140
|
+
const oauth = await import("oauth4webapi");
|
|
141
|
+
const as = await this.getAuthorizationServer(oauth);
|
|
142
|
+
let claims: Claims & {active: boolean};
|
|
143
|
+
|
|
144
|
+
try {
|
|
145
|
+
const response = await oauth.introspectionRequest(
|
|
146
|
+
as,
|
|
147
|
+
{client_id: this.auth.clientId!},
|
|
148
|
+
oauth.ClientSecretBasic(this.auth.clientSecret!),
|
|
149
|
+
token,
|
|
150
|
+
this.getRequestOptions(oauth)
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
claims = (await oauth.processIntrospectionResponse(as, {client_id: this.auth.clientId!}, response)) as never;
|
|
154
|
+
} catch {
|
|
155
|
+
throw new PlatformServerError("Unable to introspect the access token");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const audiences = ([] as string[]).concat(claims.aud || []);
|
|
159
|
+
|
|
160
|
+
if (!claims.active) {
|
|
161
|
+
throw new PlatformInvalidToken("Inactive access token");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (claims.iss && claims.iss !== this.auth.issuer) {
|
|
165
|
+
throw new PlatformInvalidToken("Unexpected access token issuer");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// a token without audience is rejected: it could have been issued for another resource
|
|
169
|
+
if (this.audience !== false && !audiences.includes(this.audience)) {
|
|
170
|
+
throw new PlatformInvalidToken("Unexpected access token audience");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return this.toAuthInfo(token, claims);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Resolves the authorization server metadata once per endpoint: OIDC discovery, then RFC 8414.
|
|
178
|
+
* Discovery is skipped when the endpoint needed by the verification mode is configured explicitly.
|
|
179
|
+
*/
|
|
180
|
+
protected getAuthorizationServer(oauth: OAuth): Promise<AuthorizationServer> {
|
|
181
|
+
const load = async (): Promise<AuthorizationServer> => {
|
|
182
|
+
const overrides = {
|
|
183
|
+
...(this.auth.jwksUri && {jwks_uri: this.auth.jwksUri}),
|
|
184
|
+
...(this.auth.introspectionEndpoint && {introspection_endpoint: this.auth.introspectionEndpoint})
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
if (this.mode === "introspection" ? this.auth.introspectionEndpoint : this.auth.jwksUri) {
|
|
188
|
+
return {issuer: this.auth.issuer, ...overrides};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const issuer = new URL(this.auth.issuer);
|
|
192
|
+
|
|
193
|
+
for (const algorithm of ["oidc", "oauth2"] as const) {
|
|
194
|
+
try {
|
|
195
|
+
const response = await oauth.discoveryRequest(issuer, {algorithm, ...this.getRequestOptions(oauth)});
|
|
196
|
+
|
|
197
|
+
return {...(await oauth.processDiscoveryResponse(issuer, response)), ...overrides};
|
|
198
|
+
} catch {
|
|
199
|
+
// try the next discovery algorithm
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
throw new PlatformServerError(`Unable to load the authorization server metadata of ${this.auth.issuer}`);
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
this.authorizationServer ||= load().catch((error) => {
|
|
207
|
+
this.authorizationServer = undefined;
|
|
208
|
+
|
|
209
|
+
throw error;
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
return this.authorizationServer;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
protected toAuthInfo(token: string, claims: Claims): AuthInfo {
|
|
216
|
+
const scopes = Array.isArray(claims.scp) ? (claims.scp as string[]) : String(claims.scope || "").split(" ");
|
|
217
|
+
|
|
218
|
+
return {
|
|
219
|
+
token,
|
|
220
|
+
clientId: String(claims.client_id || claims.azp || ""),
|
|
221
|
+
scopes: scopes.filter(Boolean),
|
|
222
|
+
expiresAt: claims.exp,
|
|
223
|
+
extra: claims
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private getRequestOptions(oauth: OAuth) {
|
|
228
|
+
return this.auth.allowInsecureRequests ? {[oauth.allowInsecureRequests]: true} : {};
|
|
229
|
+
}
|
|
230
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import {OAuthError, OAuthErrorCode} from "@modelcontextprotocol/server";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The presented access token cannot be trusted. Answered as a `401 invalid_token` challenge.
|
|
5
|
+
*
|
|
6
|
+
* @module platform/mcp
|
|
7
|
+
*/
|
|
8
|
+
export class PlatformInvalidToken extends OAuthError {
|
|
9
|
+
constructor(message: string) {
|
|
10
|
+
super(OAuthErrorCode.InvalidToken, message);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import {OAuthError, OAuthErrorCode} from "@modelcontextprotocol/server";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The authorization server or the configuration failed, whatever the presented token. Answered as `500 server_error`.
|
|
5
|
+
*
|
|
6
|
+
* @module platform/mcp
|
|
7
|
+
*/
|
|
8
|
+
export class PlatformServerError extends OAuthError {
|
|
9
|
+
constructor(message: string) {
|
|
10
|
+
super(OAuthErrorCode.ServerError, message);
|
|
11
|
+
}
|
|
12
|
+
}
|
package/src/common/index.ts
CHANGED
|
@@ -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";
|