@tsed/platform-mcp 8.42.0 → 8.43.1
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/mcpStreamableServer.js +9 -0
- package/lib/esm/common/index.js +1 -0
- package/lib/esm/common/interfaces/PlatformMcpPreAuth.js +1 -0
- package/lib/esm/http/services/PlatformMcpAuthService.js +21 -2
- package/lib/esm/http/services/PlatformMcpModule.js +32 -5
- package/lib/tsconfig.esm.tsbuildinfo +1 -1
- package/lib/types/common/index.d.ts +1 -0
- package/lib/types/common/interfaces/PlatformMcpAuthSettings.d.ts +6 -0
- package/lib/types/common/interfaces/PlatformMcpPreAuth.d.ts +33 -0
- package/lib/types/common/interfaces/PlatformMcpSettings.d.ts +4 -2
- package/lib/types/http/services/PlatformMcpAuthService.d.ts +12 -2
- package/lib/types/http/services/PlatformMcpModule.d.ts +5 -0
- package/package.json +9 -8
- package/src/cli/services/mcpStreamableServer.spec.ts +16 -0
- package/src/cli/services/mcpStreamableServer.ts +11 -0
- package/src/common/index.ts +1 -0
- package/src/common/interfaces/PlatformMcpAuthSettings.ts +6 -0
- package/src/common/interfaces/PlatformMcpPreAuth.ts +37 -0
- package/src/common/interfaces/PlatformMcpSettings.ts +4 -2
- package/src/http/services/PlatformMcpAuthService.spec.ts +59 -1
- package/src/http/services/PlatformMcpAuthService.ts +31 -3
- package/src/http/services/PlatformMcpModule.spec.ts +57 -0
- package/src/http/services/PlatformMcpModule.ts +45 -7
|
@@ -12,6 +12,7 @@ export * from "./fn/definePrompt.js";
|
|
|
12
12
|
export * from "./fn/defineResource.js";
|
|
13
13
|
export * from "./fn/defineTool.js";
|
|
14
14
|
export * from "./interfaces/PlatformMcpAuthSettings.js";
|
|
15
|
+
export * from "./interfaces/PlatformMcpPreAuth.js";
|
|
15
16
|
export * from "./interfaces/PlatformMcpSettings.js";
|
|
16
17
|
export * from "./interfaces/PlatformMcpUpstreamSettings.js";
|
|
17
18
|
export * from "./services/PlatformMcpGatewayService.js";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { OAuthTokenVerifier } from "@modelcontextprotocol/server";
|
|
2
2
|
import type { TokenProvider } from "@tsed/di";
|
|
3
|
+
import type { PlatformMcpPreAuthOption } from "./PlatformMcpPreAuth.js";
|
|
3
4
|
/**
|
|
4
5
|
* OAuth 2.1 resource-server configuration of a Ts.ED MCP endpoint.
|
|
5
6
|
*
|
|
@@ -9,6 +10,11 @@ import type { TokenProvider } from "@tsed/di";
|
|
|
9
10
|
* @module platform/mcp
|
|
10
11
|
*/
|
|
11
12
|
export interface PlatformMcpAuthSettings {
|
|
13
|
+
/**
|
|
14
|
+
* Custom authentication check run before the OAuth verification, for instance an API key.
|
|
15
|
+
* When it returns an identity, the OAuth verification is skipped: both methods are accepted on the endpoint.
|
|
16
|
+
*/
|
|
17
|
+
preAuth?: PlatformMcpPreAuthOption;
|
|
12
18
|
/**
|
|
13
19
|
* Issuer URL of the authorization server (OIDC provider) protecting the endpoint.
|
|
14
20
|
*/
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { AuthInfo } from "@modelcontextprotocol/server";
|
|
2
|
+
import type { TokenProvider } from "@tsed/di";
|
|
3
|
+
import type { PlatformContext } from "@tsed/platform-http";
|
|
4
|
+
export type PlatformMcpPreAuthResult = AuthInfo | undefined | Promise<AuthInfo | undefined>;
|
|
5
|
+
/**
|
|
6
|
+
* Custom authentication check of an MCP endpoint, run before the OAuth verification.
|
|
7
|
+
*
|
|
8
|
+
* - Return an `AuthInfo` to authenticate the request: the OAuth verification is skipped and the identity is exposed
|
|
9
|
+
* to the handlers.
|
|
10
|
+
* - Return `undefined` when the check does not apply to the request: the OAuth verification runs when the endpoint
|
|
11
|
+
* declares an issuer, and the request is rejected with `401` otherwise.
|
|
12
|
+
* - Throw to reject the request.
|
|
13
|
+
*
|
|
14
|
+
* @module platform/mcp
|
|
15
|
+
*/
|
|
16
|
+
export interface PlatformMcpPreAuth {
|
|
17
|
+
preAuth($ctx: PlatformContext): PlatformMcpPreAuthResult;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Accepted forms of the `auth.preAuth` option: a function, or a DI token resolving to a
|
|
21
|
+
* {@link PlatformMcpPreAuth} provider.
|
|
22
|
+
*
|
|
23
|
+
* @module platform/mcp
|
|
24
|
+
*/
|
|
25
|
+
export type PlatformMcpPreAuthOption = (($ctx: PlatformContext) => PlatformMcpPreAuthResult) | TokenProvider<PlatformMcpPreAuth>;
|
|
26
|
+
/**
|
|
27
|
+
* Auth configuration of an MCP endpoint only protected by a custom check, without OAuth.
|
|
28
|
+
*
|
|
29
|
+
* @module platform/mcp
|
|
30
|
+
*/
|
|
31
|
+
export interface PlatformMcpPreAuthSettings {
|
|
32
|
+
preAuth: PlatformMcpPreAuthOption;
|
|
33
|
+
}
|
|
@@ -2,6 +2,7 @@ import type { Implementation, ServerOptions } from "@modelcontextprotocol/server
|
|
|
2
2
|
import type { StreamableHTTPServerTransportOptions } from "@modelcontextprotocol/node";
|
|
3
3
|
import type { TokenProvider } from "@tsed/di";
|
|
4
4
|
import type { PlatformMcpAuthSettings } from "./PlatformMcpAuthSettings.js";
|
|
5
|
+
import type { PlatformMcpPreAuthSettings } from "./PlatformMcpPreAuth.js";
|
|
5
6
|
import type { PlatformMcpUpstreamSettings } from "./PlatformMcpUpstreamSettings.js";
|
|
6
7
|
/**
|
|
7
8
|
* Configuration fragment accepted under `configuration.mcp` to wire the Platform MCP module.
|
|
@@ -61,9 +62,10 @@ export interface PlatformMcpSettings {
|
|
|
61
62
|
*/
|
|
62
63
|
upstream?: PlatformMcpUpstreamSettings;
|
|
63
64
|
/**
|
|
64
|
-
* Protect the HTTP endpoint with an OAuth authorization server
|
|
65
|
+
* Protect the HTTP endpoint: with an OAuth authorization server (`issuer`, `resource`, ...), with a custom
|
|
66
|
+
* check (`preAuth`), or with both.
|
|
65
67
|
*/
|
|
66
|
-
auth?: PlatformMcpAuthSettings;
|
|
68
|
+
auth?: PlatformMcpAuthSettings | PlatformMcpPreAuthSettings;
|
|
67
69
|
}
|
|
68
70
|
declare global {
|
|
69
71
|
namespace TsED {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type AuthInfo } from "@modelcontextprotocol/server";
|
|
2
2
|
import type { PlatformContext } from "@tsed/platform-http";
|
|
3
|
-
import type { PlatformMcpAuthSettings } from "../../common/
|
|
4
|
-
import { PlatformTokenVerifier } from "../../common/
|
|
3
|
+
import type { PlatformMcpAuthSettings, PlatformMcpPreAuthOption, PlatformMcpPreAuthSettings } from "../../common/index.js";
|
|
4
|
+
import { PlatformTokenVerifier } from "../../common/index.js";
|
|
5
5
|
export declare const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
|
|
6
6
|
/**
|
|
7
7
|
* OAuth resource-server behavior of the protected MCP endpoints: configuration validation,
|
|
@@ -11,6 +11,16 @@ export declare const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-prot
|
|
|
11
11
|
*/
|
|
12
12
|
export declare class PlatformMcpAuthService {
|
|
13
13
|
protected verifiers: WeakMap<PlatformMcpAuthSettings, PlatformTokenVerifier>;
|
|
14
|
+
/**
|
|
15
|
+
* Tells whether the endpoint is protected by an OAuth authorization server, and not only by a custom check.
|
|
16
|
+
*/
|
|
17
|
+
isOAuth(auth?: PlatformMcpAuthSettings | PlatformMcpPreAuthSettings): auth is PlatformMcpAuthSettings;
|
|
18
|
+
/**
|
|
19
|
+
* Runs the custom authentication check of an endpoint.
|
|
20
|
+
*
|
|
21
|
+
* @returns The identity of the caller, or `undefined` when the check does not apply to the request.
|
|
22
|
+
*/
|
|
23
|
+
preAuth(preAuth: PlatformMcpPreAuthOption, $ctx: PlatformContext): Promise<AuthInfo | undefined>;
|
|
14
24
|
/**
|
|
15
25
|
* Returns the token verifier of an endpoint, created once per `auth` configuration.
|
|
16
26
|
*/
|
|
@@ -20,6 +20,11 @@ export declare class PlatformMcpModule implements OnRoutesInit {
|
|
|
20
20
|
* Rejects a configuration that cannot work or would be unsafe, before any route is mounted.
|
|
21
21
|
*/
|
|
22
22
|
protected validate(path: string, opts: PlatformMcpSettings): void;
|
|
23
|
+
/**
|
|
24
|
+
* Answers the methods of the Streamable HTTP transport that a stateless endpoint does not serve,
|
|
25
|
+
* so MCP clients know there is no event stream instead of receiving the application's 404 page.
|
|
26
|
+
*/
|
|
27
|
+
protected methodNotAllowed($ctx: PlatformContext): import("@tsed/platform-http").PlatformResponse<any>;
|
|
23
28
|
protected metadata(settings: CreateMcpServerOpts, $ctx: PlatformContext): import("@tsed/platform-http").PlatformResponse<any>;
|
|
24
29
|
protected dispatch(settings: CreateMcpServerOpts, $ctx: PlatformContext): Promise<import("@tsed/platform-http").PlatformResponse<any> | undefined>;
|
|
25
30
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tsed/platform-mcp",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.43.1",
|
|
4
4
|
"description": "Model Context Protocol integration for Ts.ED HTTP adapters.",
|
|
5
5
|
"source": "./src/http/index.ts",
|
|
6
6
|
"type": "module",
|
|
@@ -51,13 +51,14 @@
|
|
|
51
51
|
"uuid": ">=11.0.2"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
|
-
"@tsed/barrels": "8.
|
|
55
|
-
"@tsed/core": "8.
|
|
56
|
-
"@tsed/di": "8.
|
|
57
|
-
"@tsed/
|
|
58
|
-
"@tsed/
|
|
59
|
-
"@tsed/
|
|
60
|
-
"@tsed/
|
|
54
|
+
"@tsed/barrels": "8.43.1",
|
|
55
|
+
"@tsed/core": "8.43.1",
|
|
56
|
+
"@tsed/di": "8.43.1",
|
|
57
|
+
"@tsed/exceptions": "8.43.1",
|
|
58
|
+
"@tsed/json-mapper": "8.43.1",
|
|
59
|
+
"@tsed/platform-http": "8.43.1",
|
|
60
|
+
"@tsed/schema": "8.43.1",
|
|
61
|
+
"@tsed/typescript": "8.43.1",
|
|
61
62
|
"jose": "^6.1.3",
|
|
62
63
|
"typescript": "6.0.2",
|
|
63
64
|
"vitest": "4.1.4"
|
|
@@ -13,6 +13,8 @@ const {app, listenServer, NodeStreamableHTTPServerTransport, express, routeHandl
|
|
|
13
13
|
const app = {
|
|
14
14
|
use: vi.fn(),
|
|
15
15
|
post: vi.fn((path: string, handler: Function) => routeHandlers.set(path, handler)),
|
|
16
|
+
get: vi.fn((path: string, handler: Function) => routeHandlers.set(`GET ${path}`, handler)),
|
|
17
|
+
delete: vi.fn((path: string, handler: Function) => routeHandlers.set(`DELETE ${path}`, handler)),
|
|
16
18
|
listen: vi.fn((_: number, handler: Function) => {
|
|
17
19
|
handler();
|
|
18
20
|
return listenServer;
|
|
@@ -71,6 +73,20 @@ describe("mcpStreamableServer", () => {
|
|
|
71
73
|
expect(app.post).toHaveBeenCalledWith("/mcp", expect.any(Function));
|
|
72
74
|
});
|
|
73
75
|
|
|
76
|
+
it.each(["GET", "DELETE"])("answers 405 to %s requests, which a stateless endpoint does not serve", async (method) => {
|
|
77
|
+
void mcpStreamableServer(createServer);
|
|
78
|
+
await vi.waitFor(() => expect(routeHandlers.get(`${method} /mcp`)).toBeDefined());
|
|
79
|
+
|
|
80
|
+
const res = {status: vi.fn().mockReturnThis(), set: vi.fn().mockReturnThis(), json: vi.fn()};
|
|
81
|
+
|
|
82
|
+
routeHandlers.get(`${method} /mcp`)!({}, res);
|
|
83
|
+
|
|
84
|
+
expect(res.status).toHaveBeenCalledWith(405);
|
|
85
|
+
expect(res.set).toHaveBeenCalledWith("Allow", "POST");
|
|
86
|
+
expect(res.json).toHaveBeenCalledWith({jsonrpc: "2.0", error: {code: -32000, message: "Method not allowed."}, id: null});
|
|
87
|
+
expect(createServer).not.toHaveBeenCalled();
|
|
88
|
+
});
|
|
89
|
+
|
|
74
90
|
it("creates a transport and dispatches each MCP request", async () => {
|
|
75
91
|
void mcpStreamableServer(createServer);
|
|
76
92
|
await vi.waitFor(() => expect(routeHandlers.get("/mcp")).toBeDefined());
|
|
@@ -37,6 +37,17 @@ export async function mcpStreamableServer(createServer: () => McpServer | Promis
|
|
|
37
37
|
}
|
|
38
38
|
});
|
|
39
39
|
|
|
40
|
+
// the endpoint is stateless: there is no event stream to open nor session to delete
|
|
41
|
+
const methodNotAllowed = (_req: any, res: any) => {
|
|
42
|
+
res
|
|
43
|
+
.status(405)
|
|
44
|
+
.set("Allow", "POST")
|
|
45
|
+
.json({jsonrpc: "2.0", error: {code: -32000, message: "Method not allowed."}, id: null});
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
app.get("/mcp", methodNotAllowed);
|
|
49
|
+
app.delete("/mcp", methodNotAllowed);
|
|
50
|
+
|
|
40
51
|
const port = parseInt(process.env.PORT || "3000");
|
|
41
52
|
|
|
42
53
|
return new Promise((resolve, reject) => {
|
package/src/common/index.ts
CHANGED
|
@@ -12,6 +12,7 @@ export * from "./fn/definePrompt.js";
|
|
|
12
12
|
export * from "./fn/defineResource.js";
|
|
13
13
|
export * from "./fn/defineTool.js";
|
|
14
14
|
export * from "./interfaces/PlatformMcpAuthSettings.js";
|
|
15
|
+
export * from "./interfaces/PlatformMcpPreAuth.js";
|
|
15
16
|
export * from "./interfaces/PlatformMcpSettings.js";
|
|
16
17
|
export * from "./interfaces/PlatformMcpUpstreamSettings.js";
|
|
17
18
|
export * from "./services/PlatformMcpGatewayService.js";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type {OAuthTokenVerifier} from "@modelcontextprotocol/server";
|
|
2
2
|
import type {TokenProvider} from "@tsed/di";
|
|
3
|
+
import type {PlatformMcpPreAuthOption} from "./PlatformMcpPreAuth.js";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* OAuth 2.1 resource-server configuration of a Ts.ED MCP endpoint.
|
|
@@ -10,6 +11,11 @@ import type {TokenProvider} from "@tsed/di";
|
|
|
10
11
|
* @module platform/mcp
|
|
11
12
|
*/
|
|
12
13
|
export interface PlatformMcpAuthSettings {
|
|
14
|
+
/**
|
|
15
|
+
* Custom authentication check run before the OAuth verification, for instance an API key.
|
|
16
|
+
* When it returns an identity, the OAuth verification is skipped: both methods are accepted on the endpoint.
|
|
17
|
+
*/
|
|
18
|
+
preAuth?: PlatformMcpPreAuthOption;
|
|
13
19
|
/**
|
|
14
20
|
* Issuer URL of the authorization server (OIDC provider) protecting the endpoint.
|
|
15
21
|
*/
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type {AuthInfo} from "@modelcontextprotocol/server";
|
|
2
|
+
import type {TokenProvider} from "@tsed/di";
|
|
3
|
+
import type {PlatformContext} from "@tsed/platform-http";
|
|
4
|
+
|
|
5
|
+
export type PlatformMcpPreAuthResult = AuthInfo | undefined | Promise<AuthInfo | undefined>;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Custom authentication check of an MCP endpoint, run before the OAuth verification.
|
|
9
|
+
*
|
|
10
|
+
* - Return an `AuthInfo` to authenticate the request: the OAuth verification is skipped and the identity is exposed
|
|
11
|
+
* to the handlers.
|
|
12
|
+
* - Return `undefined` when the check does not apply to the request: the OAuth verification runs when the endpoint
|
|
13
|
+
* declares an issuer, and the request is rejected with `401` otherwise.
|
|
14
|
+
* - Throw to reject the request.
|
|
15
|
+
*
|
|
16
|
+
* @module platform/mcp
|
|
17
|
+
*/
|
|
18
|
+
export interface PlatformMcpPreAuth {
|
|
19
|
+
preAuth($ctx: PlatformContext): PlatformMcpPreAuthResult;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Accepted forms of the `auth.preAuth` option: a function, or a DI token resolving to a
|
|
24
|
+
* {@link PlatformMcpPreAuth} provider.
|
|
25
|
+
*
|
|
26
|
+
* @module platform/mcp
|
|
27
|
+
*/
|
|
28
|
+
export type PlatformMcpPreAuthOption = (($ctx: PlatformContext) => PlatformMcpPreAuthResult) | TokenProvider<PlatformMcpPreAuth>;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Auth configuration of an MCP endpoint only protected by a custom check, without OAuth.
|
|
32
|
+
*
|
|
33
|
+
* @module platform/mcp
|
|
34
|
+
*/
|
|
35
|
+
export interface PlatformMcpPreAuthSettings {
|
|
36
|
+
preAuth: PlatformMcpPreAuthOption;
|
|
37
|
+
}
|
|
@@ -2,6 +2,7 @@ import type {Implementation, ServerOptions} from "@modelcontextprotocol/server";
|
|
|
2
2
|
import type {StreamableHTTPServerTransportOptions} from "@modelcontextprotocol/node";
|
|
3
3
|
import type {TokenProvider} from "@tsed/di";
|
|
4
4
|
import type {PlatformMcpAuthSettings} from "./PlatformMcpAuthSettings.js";
|
|
5
|
+
import type {PlatformMcpPreAuthSettings} from "./PlatformMcpPreAuth.js";
|
|
5
6
|
import type {PlatformMcpUpstreamSettings} from "./PlatformMcpUpstreamSettings.js";
|
|
6
7
|
|
|
7
8
|
/**
|
|
@@ -62,9 +63,10 @@ export interface PlatformMcpSettings {
|
|
|
62
63
|
*/
|
|
63
64
|
upstream?: PlatformMcpUpstreamSettings;
|
|
64
65
|
/**
|
|
65
|
-
* Protect the HTTP endpoint with an OAuth authorization server
|
|
66
|
+
* Protect the HTTP endpoint: with an OAuth authorization server (`issuer`, `resource`, ...), with a custom
|
|
67
|
+
* check (`preAuth`), or with both.
|
|
66
68
|
*/
|
|
67
|
-
auth?: PlatformMcpAuthSettings;
|
|
69
|
+
auth?: PlatformMcpAuthSettings | PlatformMcpPreAuthSettings;
|
|
68
70
|
}
|
|
69
71
|
|
|
70
72
|
declare global {
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type {AuthInfo} from "@modelcontextprotocol/server";
|
|
2
|
-
import {inject, logger} from "@tsed/di";
|
|
2
|
+
import {inject, injectable, logger} from "@tsed/di";
|
|
3
|
+
import type {PlatformContext} from "@tsed/platform-http";
|
|
3
4
|
import {PlatformTest} from "@tsed/platform-http/testing";
|
|
4
5
|
import type {PlatformMcpAuthSettings} from "../../common/interfaces/PlatformMcpAuthSettings.js";
|
|
6
|
+
import type {PlatformMcpPreAuth} from "../../common/interfaces/PlatformMcpPreAuth.js";
|
|
5
7
|
import {PlatformTokenVerifier} from "../../common/domain/PlatformTokenVerifier.js";
|
|
6
8
|
import {PlatformMcpAuthService} from "./PlatformMcpAuthService.js";
|
|
7
9
|
|
|
@@ -12,6 +14,14 @@ const authInfo: AuthInfo = {
|
|
|
12
14
|
expiresAt: Math.floor(Date.now() / 1000) + 3600
|
|
13
15
|
};
|
|
14
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
|
+
|
|
15
25
|
function createAuth(opts: Partial<PlatformMcpAuthSettings> = {}): PlatformMcpAuthSettings {
|
|
16
26
|
return {issuer: "https://auth.example.com", resource: "https://api.example.com/mcp", ...opts};
|
|
17
27
|
}
|
|
@@ -32,6 +42,54 @@ describe("PlatformMcpAuthService", () => {
|
|
|
32
42
|
return PlatformTest.reset();
|
|
33
43
|
});
|
|
34
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
|
+
|
|
35
93
|
describe("getVerifier()", () => {
|
|
36
94
|
it("creates one verifier per auth configuration", () => {
|
|
37
95
|
const service = inject(PlatformMcpAuthService);
|
|
@@ -6,10 +6,15 @@ import {
|
|
|
6
6
|
getOAuthProtectedResourceMetadataUrl,
|
|
7
7
|
verifyBearerToken
|
|
8
8
|
} from "@modelcontextprotocol/server";
|
|
9
|
-
import {injectable, logger} from "@tsed/di";
|
|
9
|
+
import {inject, injectable, injector, logger, type TokenProvider} from "@tsed/di";
|
|
10
10
|
import type {PlatformContext} from "@tsed/platform-http";
|
|
11
|
-
import type {
|
|
12
|
-
|
|
11
|
+
import type {
|
|
12
|
+
PlatformMcpAuthSettings,
|
|
13
|
+
PlatformMcpPreAuth,
|
|
14
|
+
PlatformMcpPreAuthOption,
|
|
15
|
+
PlatformMcpPreAuthSettings
|
|
16
|
+
} from "../../common/index.js";
|
|
17
|
+
import {PlatformTokenVerifier} from "../../common/index.js";
|
|
13
18
|
|
|
14
19
|
export const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
|
|
15
20
|
|
|
@@ -22,6 +27,29 @@ export const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-re
|
|
|
22
27
|
export class PlatformMcpAuthService {
|
|
23
28
|
protected verifiers = new WeakMap<PlatformMcpAuthSettings, PlatformTokenVerifier>();
|
|
24
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
|
+
|
|
25
53
|
/**
|
|
26
54
|
* Returns the token verifier of an endpoint, created once per `auth` configuration.
|
|
27
55
|
*/
|
|
@@ -107,6 +107,32 @@ describe("PlatformMcpModule", () => {
|
|
|
107
107
|
});
|
|
108
108
|
|
|
109
109
|
describe("$onRoutesInit()", () => {
|
|
110
|
+
it("answers 405 to GET and DELETE on the MCP path without logging them as routes", async () => {
|
|
111
|
+
const {module} = await createModule();
|
|
112
|
+
module["settings"] = {path: "/ai/mcp"};
|
|
113
|
+
|
|
114
|
+
vi.spyOn(application(), "post").mockReturnValue(undefined as never);
|
|
115
|
+
vi.spyOn(application(), "get").mockReturnValue(undefined as never);
|
|
116
|
+
vi.spyOn(application(), "delete").mockReturnValue(undefined as never);
|
|
117
|
+
|
|
118
|
+
module.$onRoutesInit();
|
|
119
|
+
|
|
120
|
+
expect(application().get).toHaveBeenCalledExactlyOnceWith("/ai/mcp", expect.any(Function));
|
|
121
|
+
expect(application().delete).toHaveBeenCalledExactlyOnceWith("/ai/mcp", expect.any(Function));
|
|
122
|
+
expect(module.$logRoutes([])).toEqual([{method: "POST", name: "PlatformMcpModule.dispatch()", url: "/ai/mcp"}]);
|
|
123
|
+
|
|
124
|
+
const {$ctx} = createExpressContext();
|
|
125
|
+
const status = vi.spyOn($ctx.response, "status").mockReturnThis();
|
|
126
|
+
const setHeaders = vi.spyOn($ctx.response, "setHeaders").mockReturnThis();
|
|
127
|
+
const body = vi.spyOn($ctx.response, "body").mockReturnThis();
|
|
128
|
+
|
|
129
|
+
module["methodNotAllowed"]($ctx);
|
|
130
|
+
|
|
131
|
+
expect(status).toHaveBeenCalledWith(405);
|
|
132
|
+
expect(setHeaders).toHaveBeenCalledWith({allow: "POST"});
|
|
133
|
+
expect(body).toHaveBeenCalledWith({jsonrpc: "2.0", error: {code: -32000, message: "Method not allowed."}, id: null});
|
|
134
|
+
});
|
|
135
|
+
|
|
110
136
|
it("should register the MCP route only once", async () => {
|
|
111
137
|
const {module} = await createModule();
|
|
112
138
|
|
|
@@ -194,6 +220,37 @@ describe("PlatformMcpModule", () => {
|
|
|
194
220
|
expect(application().post).toHaveBeenCalledOnce();
|
|
195
221
|
});
|
|
196
222
|
|
|
223
|
+
it("fails when auth declares neither an issuer nor a custom check", async () => {
|
|
224
|
+
const {module} = await createModule();
|
|
225
|
+
module["settings"] = {auth: {} as PlatformMcpAuthSettings};
|
|
226
|
+
vi.spyOn(application(), "post").mockReturnValue(undefined as never);
|
|
227
|
+
|
|
228
|
+
expect(() => module.$onRoutesInit()).toThrow("auth requires an issuer, a preAuth check, or both");
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it("mounts an endpoint only protected by a custom check without OAuth metadata route", async () => {
|
|
232
|
+
const {module} = await createModule();
|
|
233
|
+
module["settings"] = {path: "/mcp/a", auth: {preAuth: vi.fn()}};
|
|
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).not.toHaveBeenCalledWith(expect.stringContaining("/.well-known/"), expect.any(Function));
|
|
240
|
+
expect(module.$logRoutes([])).toEqual([{method: "POST", name: "PlatformMcpModule.dispatch()", url: "/mcp/a"}]);
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
it("accepts upstream placeholders on an endpoint only protected by a custom check", async () => {
|
|
244
|
+
const {module} = await createModule();
|
|
245
|
+
module["settings"] = {
|
|
246
|
+
auth: {preAuth: vi.fn()},
|
|
247
|
+
upstream: {type: "http", url: "http://localhost/mcp", headers: {authorization: "Bearer ${OAUTH_TOKEN}"}}
|
|
248
|
+
};
|
|
249
|
+
vi.spyOn(application(), "post").mockReturnValue(undefined as never);
|
|
250
|
+
|
|
251
|
+
expect(() => module.$onRoutesInit()).not.toThrow();
|
|
252
|
+
});
|
|
253
|
+
|
|
197
254
|
it("registers the protected resource metadata route of protected endpoints", async () => {
|
|
198
255
|
const {module} = await createModule();
|
|
199
256
|
module["settings"] = {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {application, type OnRoutesInit, type PlatformContext, type PlatformRouteDetails} from "@tsed/platform-http";
|
|
2
2
|
import {constant, inject, injectable} from "@tsed/di";
|
|
3
|
-
import type {PlatformMcpSettings} from "../../common/index.js";
|
|
3
|
+
import type {PlatformMcpAuthSettings, PlatformMcpSettings} from "../../common/index.js";
|
|
4
4
|
import {NodeStreamableHTTPServerTransport} from "@modelcontextprotocol/node";
|
|
5
5
|
import type {AuthInfo} from "@modelcontextprotocol/server";
|
|
6
6
|
import {useContextHandler} from "@tsed/platform-router";
|
|
@@ -43,7 +43,7 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
43
43
|
path
|
|
44
44
|
};
|
|
45
45
|
|
|
46
|
-
if (opts.auth) {
|
|
46
|
+
if (this.platformAuthService.isOAuth(opts.auth)) {
|
|
47
47
|
const metadataPath = this.platformAuthService.getProtectedResourceMetadataPath(path);
|
|
48
48
|
|
|
49
49
|
this.app.get(
|
|
@@ -68,6 +68,16 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
68
68
|
name: "PlatformMcpModule.dispatch()",
|
|
69
69
|
url: path
|
|
70
70
|
} as PlatformRouteDetails);
|
|
71
|
+
|
|
72
|
+
// the endpoint is stateless: there is no event stream to open nor session to delete
|
|
73
|
+
this.app.get(
|
|
74
|
+
path,
|
|
75
|
+
useContextHandler(($ctx) => this.methodNotAllowed($ctx as PlatformContext))
|
|
76
|
+
);
|
|
77
|
+
this.app.delete(
|
|
78
|
+
path,
|
|
79
|
+
useContextHandler(($ctx) => this.methodNotAllowed($ctx as PlatformContext))
|
|
80
|
+
);
|
|
71
81
|
}
|
|
72
82
|
|
|
73
83
|
this.loaded = true;
|
|
@@ -81,8 +91,12 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
81
91
|
* Rejects a configuration that cannot work or would be unsafe, before any route is mounted.
|
|
82
92
|
*/
|
|
83
93
|
protected validate(path: string, opts: PlatformMcpSettings) {
|
|
84
|
-
|
|
85
|
-
|
|
94
|
+
const {auth} = opts;
|
|
95
|
+
|
|
96
|
+
if (this.platformAuthService.isOAuth(auth)) {
|
|
97
|
+
this.platformAuthService.validate(path, auth);
|
|
98
|
+
} else if (auth && !auth.preAuth) {
|
|
99
|
+
throw new Error(`MCP endpoint "${path}": auth requires an issuer, a preAuth check, or both.`);
|
|
86
100
|
}
|
|
87
101
|
|
|
88
102
|
if (opts.upstream && !opts.auth && hasUpstreamPlaceholders(opts.upstream)) {
|
|
@@ -90,8 +104,19 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
90
104
|
}
|
|
91
105
|
}
|
|
92
106
|
|
|
107
|
+
/**
|
|
108
|
+
* Answers the methods of the Streamable HTTP transport that a stateless endpoint does not serve,
|
|
109
|
+
* so MCP clients know there is no event stream instead of receiving the application's 404 page.
|
|
110
|
+
*/
|
|
111
|
+
protected methodNotAllowed($ctx: PlatformContext) {
|
|
112
|
+
return $ctx.response
|
|
113
|
+
.status(405)
|
|
114
|
+
.setHeaders({allow: "POST"})
|
|
115
|
+
.body({jsonrpc: "2.0", error: {code: -32000, message: "Method not allowed."}, id: null});
|
|
116
|
+
}
|
|
117
|
+
|
|
93
118
|
protected metadata(settings: CreateMcpServerOpts, $ctx: PlatformContext) {
|
|
94
|
-
const auth = settings.auth
|
|
119
|
+
const auth = settings.auth as PlatformMcpAuthSettings;
|
|
95
120
|
const resource = this.platformAuthService.getResourceUrl(auth);
|
|
96
121
|
const body = this.platformAuthService.getProtectedResourceMetadata(auth, resource);
|
|
97
122
|
|
|
@@ -106,10 +131,20 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
106
131
|
}
|
|
107
132
|
|
|
108
133
|
protected async dispatch(settings: CreateMcpServerOpts, $ctx: PlatformContext) {
|
|
134
|
+
const {auth} = settings;
|
|
109
135
|
let authInfo: AuthInfo | undefined;
|
|
110
136
|
|
|
111
|
-
if (
|
|
112
|
-
|
|
137
|
+
if (auth?.preAuth) {
|
|
138
|
+
authInfo = await this.platformAuthService.preAuth(auth.preAuth, $ctx);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (auth && !authInfo) {
|
|
142
|
+
if (!this.platformAuthService.isOAuth(auth)) {
|
|
143
|
+
// the custom check did not authenticate the request and there is no OAuth to fall back on
|
|
144
|
+
return $ctx.response.status(401).body({error: "unauthorized", error_description: "Authentication required"});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const result = await this.platformAuthService.verifyMcpRequest(auth, $ctx);
|
|
113
148
|
|
|
114
149
|
if (result instanceof Response) {
|
|
115
150
|
return $ctx.response
|
|
@@ -119,6 +154,9 @@ export class PlatformMcpModule implements OnRoutesInit {
|
|
|
119
154
|
}
|
|
120
155
|
|
|
121
156
|
authInfo = result;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (authInfo) {
|
|
122
160
|
// the SDK transport reads `req.auth` and exposes it to handlers as `ctx.http.authInfo`
|
|
123
161
|
($ctx.getReq() as {auth?: AuthInfo}).auth = authInfo;
|
|
124
162
|
}
|