xmcp 0.6.13 → 0.7.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/dist/cli.js +8 -8
- package/dist/index.js +2 -2
- package/dist/runtime/adapter-express.js +2 -2
- package/dist/runtime/adapter-fastify.js +2 -2
- package/dist/runtime/adapter-nestjs.js +7 -7
- package/dist/runtime/adapter-nextjs.js +11 -11
- package/dist/runtime/http.js +3 -3
- package/dist/runtime/stdio.js +8 -8
- package/package.json +10 -11
- package/src/auth/api-key.ts +0 -120
- package/src/auth/jwt.ts +0 -52
- package/src/cli/commands/create/__tests__/create.test.ts +0 -99
- package/src/cli/commands/create/index.ts +0 -74
- package/src/cli/commands/create/templates/index.ts +0 -4
- package/src/cli/commands/create/templates/prompt.ts +0 -30
- package/src/cli/commands/create/templates/resource.ts +0 -20
- package/src/cli/commands/create/templates/tool.ts +0 -34
- package/src/cli/commands/create/templates/widget.ts +0 -33
- package/src/cli/utils/naming.ts +0 -39
- package/src/cli.ts +0 -125
- package/src/client/headers.ts +0 -61
- package/src/client/index.ts +0 -180
- package/src/client/types.ts +0 -122
- package/src/client/utils.ts +0 -133
- package/src/cloudflare.ts +0 -6
- package/src/compiler/build-telemetry.ts +0 -88
- package/src/compiler/client/component-compiler.ts +0 -250
- package/src/compiler/client/transpile.ts +0 -21
- package/src/compiler/compiler-context.ts +0 -61
- package/src/compiler/config/__tests__/config.test.ts +0 -459
- package/src/compiler/config/index.ts +0 -62
- package/src/compiler/config/injection.ts +0 -210
- package/src/compiler/config/schemas/bundler.ts +0 -12
- package/src/compiler/config/schemas/experimental/index.ts +0 -22
- package/src/compiler/config/schemas/index.ts +0 -20
- package/src/compiler/config/schemas/paths.ts +0 -35
- package/src/compiler/config/schemas/template.ts +0 -80
- package/src/compiler/config/schemas/transport/http.ts +0 -116
- package/src/compiler/config/schemas/transport/stdio.ts +0 -31
- package/src/compiler/config/schemas/typescript.ts +0 -26
- package/src/compiler/config/utils.ts +0 -168
- package/src/compiler/generate-env-code.ts +0 -5
- package/src/compiler/generate-import-code.ts +0 -187
- package/src/compiler/generate-tools-code.ts +0 -174
- package/src/compiler/get-bundler-config/get-entries.ts +0 -44
- package/src/compiler/get-bundler-config/get-externals.ts +0 -114
- package/src/compiler/get-bundler-config/get-injected-variables.ts +0 -46
- package/src/compiler/get-bundler-config/index.ts +0 -288
- package/src/compiler/get-bundler-config/plugins/index.ts +0 -140
- package/src/compiler/get-bundler-config/plugins/types/express.ts +0 -3
- package/src/compiler/get-bundler-config/plugins/types/fastify.ts +0 -4
- package/src/compiler/get-bundler-config/plugins/types/index.ts +0 -5
- package/src/compiler/get-bundler-config/plugins/types/nest.ts +0 -65
- package/src/compiler/get-bundler-config/plugins/types/next.ts +0 -52
- package/src/compiler/get-bundler-config/resolve-tsconfig-paths.ts +0 -51
- package/src/compiler/index.ts +0 -484
- package/src/compiler/on-first-build.ts +0 -54
- package/src/compiler/parse-xmcp-config.ts +0 -200
- package/src/compiler/start-http-server.ts +0 -42
- package/src/compiler/utils/__tests__/config-detection.test.ts +0 -307
- package/src/compiler/utils/__tests__/path-utils.test.ts +0 -137
- package/src/compiler/utils/config-detection.ts +0 -34
- package/src/compiler/utils/path-utils.ts +0 -22
- package/src/compiler/watcher-recovery.ts +0 -72
- package/src/host-bridge.ts +0 -36
- package/src/index.ts +0 -94
- package/src/platforms/build-cloudflare-output.ts +0 -116
- package/src/platforms/build-vercel-output.ts +0 -131
- package/src/plugins/index.ts +0 -1
- package/src/plugins/x402/index.ts +0 -24
- package/src/runtime/adapters/express/index.ts +0 -75
- package/src/runtime/adapters/fastify/__tests__/fastify.test.ts +0 -115
- package/src/runtime/adapters/fastify/index.ts +0 -78
- package/src/runtime/adapters/nestjs/index.ts +0 -16
- package/src/runtime/adapters/nestjs/xmcp.controller.ts +0 -34
- package/src/runtime/adapters/nestjs/xmcp.guard.ts +0 -101
- package/src/runtime/adapters/nestjs/xmcp.oauth.controller.ts +0 -36
- package/src/runtime/adapters/nestjs/xmcp.oauth.module.ts +0 -21
- package/src/runtime/adapters/nestjs/xmcp.oauth.service.ts +0 -36
- package/src/runtime/adapters/nestjs/xmcp.service.ts +0 -96
- package/src/runtime/adapters/nestjs/xmcp.utils.ts +0 -11
- package/src/runtime/adapters/nextjs/auth.ts +0 -265
- package/src/runtime/adapters/nextjs/handler/error-handler.ts +0 -67
- package/src/runtime/adapters/nextjs/handler/node-to-web-adapter.ts +0 -143
- package/src/runtime/adapters/nextjs/handler/request-converter.ts +0 -74
- package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +0 -69
- package/src/runtime/adapters/nextjs/index.ts +0 -82
- package/src/runtime/contexts/client-info-context.ts +0 -16
- package/src/runtime/contexts/http-request-context.ts +0 -21
- package/src/runtime/contexts/http-transport-context.ts +0 -18
- package/src/runtime/headers.ts +0 -42
- package/src/runtime/middlewares/utils.ts +0 -72
- package/src/runtime/platforms/cloudflare/cors.ts +0 -44
- package/src/runtime/platforms/cloudflare/middlewares/api-key.ts +0 -102
- package/src/runtime/platforms/cloudflare/middlewares/jwt.ts +0 -127
- package/src/runtime/platforms/cloudflare/types.ts +0 -23
- package/src/runtime/platforms/cloudflare/worker.ts +0 -270
- package/src/runtime/templates/home.ts +0 -746
- package/src/runtime/transports/http/base-streamable-http.ts +0 -46
- package/src/runtime/transports/http/cors/headers.ts +0 -58
- package/src/runtime/transports/http/cors/index.ts +0 -34
- package/src/runtime/transports/http/index.ts +0 -78
- package/src/runtime/transports/http/stateless-streamable-http.ts +0 -311
- package/src/runtime/transports/http/web-stateless-http.ts +0 -288
- package/src/runtime/transports/stdio/index.ts +0 -109
- package/src/runtime/utils/__tests__/client-info.test.ts +0 -146
- package/src/runtime/utils/__tests__/tool-extra.test.ts +0 -239
- package/src/runtime/utils/client-info.ts +0 -114
- package/src/runtime/utils/elicitation.ts +0 -396
- package/src/runtime/utils/ext-apps-registry.ts +0 -151
- package/src/runtime/utils/mcp-app-protocol.ts +0 -16
- package/src/runtime/utils/mcp-app-types.ts +0 -113
- package/src/runtime/utils/mcp-host-bridge.ts +0 -473
- package/src/runtime/utils/path-to-tool-name.ts +0 -69
- package/src/runtime/utils/prompt-loader.ts +0 -151
- package/src/runtime/utils/prompts.ts +0 -69
- package/src/runtime/utils/react/generate-html.ts +0 -69
- package/src/runtime/utils/react/index.ts +0 -6
- package/src/runtime/utils/request-tool-names.ts +0 -48
- package/src/runtime/utils/resource-loader.ts +0 -151
- package/src/runtime/utils/resources.ts +0 -331
- package/src/runtime/utils/server.ts +0 -107
- package/src/runtime/utils/tool-loader.ts +0 -149
- package/src/runtime/utils/tools.ts +0 -183
- package/src/runtime/utils/transformers/prompt.ts +0 -120
- package/src/runtime/utils/transformers/resource.ts +0 -196
- package/src/runtime/utils/transformers/tool.ts +0 -400
- package/src/runtime/utils/ui/__tests__/split-meta.test.ts +0 -803
- package/src/runtime/utils/ui/flatten-meta.ts +0 -44
- package/src/runtime/utils/ui/split-meta.ts +0 -78
- package/src/runtime/utils/utils/resource-uri-composer.ts +0 -204
- package/src/runtime/utils/validators/index.ts +0 -138
- package/src/telemetry/ci-info.ts +0 -6
- package/src/telemetry/debug.ts +0 -8
- package/src/telemetry/events/definitions.ts +0 -52
- package/src/telemetry/events/detached-flush.ts +0 -83
- package/src/telemetry/events/post-payload.ts +0 -141
- package/src/telemetry/events/tracker.ts +0 -281
- package/src/telemetry/index.ts +0 -7
- package/src/telemetry/metadata.ts +0 -49
- package/src/telemetry/project-id.ts +0 -35
- package/src/telemetry/storage.ts +0 -218
- package/src/types/adapter.d.ts +0 -5
- package/src/types/client-info.ts +0 -20
- package/src/types/declarations.ts +0 -37
- package/src/types/injected.d.ts +0 -62
- package/src/types/middleware.ts +0 -19
- package/src/types/prompt.ts +0 -6
- package/src/types/resource.ts +0 -15
- package/src/types/tool.ts +0 -192
- package/src/types/ui-meta.ts +0 -42
- package/src/utils/cli-icons.ts +0 -5
- package/src/utils/constants.ts +0 -31
- package/src/utils/context.ts +0 -105
- package/src/utils/detect-package-manager.ts +0 -46
- package/src/utils/file-watcher.ts +0 -66
- package/src/utils/fs-utils.ts +0 -16
- package/src/utils/path-validation.ts +0 -66
- package/src/utils/port-utils.ts +0 -43
- package/src/utils/spawn-process.ts +0 -49
- package/src/utils/subscribable.ts +0 -62
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
import { describe, it, before } from "node:test";
|
|
2
|
-
import assert from "node:assert";
|
|
3
|
-
import Fastify from "fastify";
|
|
4
|
-
|
|
5
|
-
// All DefinePlugin globals must be set before the adapter and server modules are
|
|
6
|
-
// loaded. HTTP_CONFIG and HTTP_CORS_CONFIG are captured at module evaluation
|
|
7
|
-
// time inside the adapter; INJECTED_* and SERVER_INFO are captured in
|
|
8
|
-
// utils/server.ts. The modules are loaded via dynamic import() inside before(),
|
|
9
|
-
// which runs after this synchronous initialisation.
|
|
10
|
-
const g = globalThis as Record<string, unknown>;
|
|
11
|
-
g["HTTP_CONFIG"] = {
|
|
12
|
-
port: 3001,
|
|
13
|
-
host: "127.0.0.1",
|
|
14
|
-
bodySizeLimit: 10 * 1024 * 1024,
|
|
15
|
-
endpoint: "/mcp",
|
|
16
|
-
debug: false,
|
|
17
|
-
};
|
|
18
|
-
g["HTTP_CORS_CONFIG"] = {
|
|
19
|
-
origin: "*",
|
|
20
|
-
methods: ["GET", "POST"],
|
|
21
|
-
credentials: false,
|
|
22
|
-
maxAge: 86400,
|
|
23
|
-
};
|
|
24
|
-
g["INJECTED_TOOLS"] = {};
|
|
25
|
-
g["INJECTED_PROMPTS"] = {};
|
|
26
|
-
g["INJECTED_RESOURCES"] = {};
|
|
27
|
-
g["SERVER_INFO"] = { name: "test-server", version: "0.0.0" };
|
|
28
|
-
|
|
29
|
-
const HEADERS = {
|
|
30
|
-
"content-type": "application/json",
|
|
31
|
-
accept: "text/event-stream, application/json",
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
describe("Fastify adapter", () => {
|
|
35
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
36
|
-
let xmcpHandler!: (req: any, reply: any) => Promise<void>;
|
|
37
|
-
let injectedTools!: Record<string, () => Promise<unknown>>;
|
|
38
|
-
|
|
39
|
-
before(async () => {
|
|
40
|
-
// Dynamically import AFTER globals are set so module-level initialisers see
|
|
41
|
-
// the correct values.
|
|
42
|
-
({ xmcpHandler } = (await import("../index")) as {
|
|
43
|
-
xmcpHandler: typeof xmcpHandler;
|
|
44
|
-
});
|
|
45
|
-
({ injectedTools } = (await import("../../../utils/server")) as {
|
|
46
|
-
injectedTools: Record<string, () => Promise<unknown>>;
|
|
47
|
-
});
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
it("handles an initialize request successfully", async () => {
|
|
51
|
-
const app = Fastify();
|
|
52
|
-
app.post("/mcp", xmcpHandler);
|
|
53
|
-
|
|
54
|
-
const response = await app.inject({
|
|
55
|
-
method: "POST",
|
|
56
|
-
url: "/mcp",
|
|
57
|
-
headers: HEADERS,
|
|
58
|
-
payload: {
|
|
59
|
-
jsonrpc: "2.0",
|
|
60
|
-
id: 1,
|
|
61
|
-
method: "initialize",
|
|
62
|
-
params: {
|
|
63
|
-
protocolVersion: "2025-03-26",
|
|
64
|
-
capabilities: {},
|
|
65
|
-
clientInfo: { name: "test", version: "1.0.0" },
|
|
66
|
-
},
|
|
67
|
-
},
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
assert.strictEqual(response.statusCode, 200);
|
|
71
|
-
assert.ok(
|
|
72
|
-
response.body.includes('"serverInfo"'),
|
|
73
|
-
'response body must contain "serverInfo"'
|
|
74
|
-
);
|
|
75
|
-
assert.ok(
|
|
76
|
-
response.body.includes("test-server"),
|
|
77
|
-
"response body must contain the server name"
|
|
78
|
-
);
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
it("writes a 500 JSON-RPC error to reply.raw when createServer throws", async () => {
|
|
82
|
-
// Inject a broken loader into the live injectedTools object so that the next
|
|
83
|
-
// loadToolModules() call rejects, propagating up through createServer() and
|
|
84
|
-
// into the catch block inside xmcpHandler. This works because injectedTools
|
|
85
|
-
// is the same object reference that was captured from INJECTED_TOOLS above —
|
|
86
|
-
// adding a key here is visible to loadTools() on the next invocation.
|
|
87
|
-
injectedTools["__test_error__"] = async () => {
|
|
88
|
-
throw new Error("forced load failure");
|
|
89
|
-
};
|
|
90
|
-
|
|
91
|
-
try {
|
|
92
|
-
const app = Fastify();
|
|
93
|
-
app.post("/mcp", xmcpHandler);
|
|
94
|
-
|
|
95
|
-
const response = await app.inject({
|
|
96
|
-
method: "POST",
|
|
97
|
-
url: "/mcp",
|
|
98
|
-
headers: HEADERS,
|
|
99
|
-
payload: { jsonrpc: "2.0", id: 1, method: "tools/list" },
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
// After reply.hijack() the catch block writes directly to reply.raw.
|
|
103
|
-
assert.strictEqual(response.statusCode, 500);
|
|
104
|
-
const body = JSON.parse(response.body) as {
|
|
105
|
-
jsonrpc: string;
|
|
106
|
-
error: { code: number; message: string };
|
|
107
|
-
id: unknown;
|
|
108
|
-
};
|
|
109
|
-
assert.strictEqual(body.jsonrpc, "2.0");
|
|
110
|
-
assert.strictEqual(body.error.code, -32603);
|
|
111
|
-
} finally {
|
|
112
|
-
delete injectedTools["__test_error__"];
|
|
113
|
-
}
|
|
114
|
-
});
|
|
115
|
-
});
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import type { FastifyRequest, FastifyReply } from "fastify";
|
|
2
|
-
import { createServer } from "@/runtime/utils/server";
|
|
3
|
-
import { StatelessHttpServerTransport } from "@/runtime/transports/http/stateless-streamable-http";
|
|
4
|
-
import { setHeaders } from "@/runtime/transports/http/cors";
|
|
5
|
-
import { httpRequestContextProvider } from "@/runtime/contexts/http-request-context";
|
|
6
|
-
import { randomUUID } from "node:crypto";
|
|
7
|
-
import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
|
|
8
|
-
import type { CorsConfig } from "@/compiler/config";
|
|
9
|
-
|
|
10
|
-
const httpConfig = HTTP_CONFIG as {
|
|
11
|
-
port: number;
|
|
12
|
-
host: string;
|
|
13
|
-
bodySizeLimit: number;
|
|
14
|
-
endpoint: string;
|
|
15
|
-
debug: boolean;
|
|
16
|
-
};
|
|
17
|
-
const corsConfig = HTTP_CORS_CONFIG as CorsConfig;
|
|
18
|
-
|
|
19
|
-
export async function xmcpHandler(
|
|
20
|
-
request: FastifyRequest,
|
|
21
|
-
reply: FastifyReply
|
|
22
|
-
): Promise<void> {
|
|
23
|
-
return new Promise<void>((resolve) => {
|
|
24
|
-
const id = randomUUID();
|
|
25
|
-
const clientInfo = extractClientInfoFromMessages(request.body);
|
|
26
|
-
|
|
27
|
-
httpRequestContextProvider(
|
|
28
|
-
{ id, headers: request.headers, clientInfo },
|
|
29
|
-
async () => {
|
|
30
|
-
try {
|
|
31
|
-
// Claim the raw stream before any await so Fastify never attempts its
|
|
32
|
-
// own finalisation after the transport has already written to reply.raw.
|
|
33
|
-
// This MUST remain the first statement in the try block — after hijack,
|
|
34
|
-
// any throw is caught here and written directly to reply.raw, with no
|
|
35
|
-
// risk of Fastify also sending a response.
|
|
36
|
-
reply.hijack();
|
|
37
|
-
|
|
38
|
-
setHeaders(reply.raw, corsConfig, request.headers.origin);
|
|
39
|
-
|
|
40
|
-
const server = await createServer();
|
|
41
|
-
const transport = new StatelessHttpServerTransport(
|
|
42
|
-
httpConfig.debug,
|
|
43
|
-
httpConfig.bodySizeLimit.toString()
|
|
44
|
-
);
|
|
45
|
-
|
|
46
|
-
// Release transport + server when the connection closes (normal
|
|
47
|
-
// completion or client abort). Without this, warm containers leak
|
|
48
|
-
// instances per request.
|
|
49
|
-
reply.raw.on("close", () => {
|
|
50
|
-
transport.close();
|
|
51
|
-
server.close();
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
await server.connect(transport);
|
|
55
|
-
|
|
56
|
-
// The transport writes directly to reply.raw via Node's ServerResponse
|
|
57
|
-
// API. request.raw has already had its body consumed by Fastify, so
|
|
58
|
-
// we pass request.body as parsedBody rather than re-reading the stream.
|
|
59
|
-
await transport.handleRequest(request.raw, reply.raw, request.body);
|
|
60
|
-
resolve();
|
|
61
|
-
} catch (error) {
|
|
62
|
-
console.error("[HTTP-server] Error handling MCP request:", error);
|
|
63
|
-
if (!reply.raw.headersSent) {
|
|
64
|
-
reply.raw.writeHead(500, { "content-type": "application/json" });
|
|
65
|
-
reply.raw.end(
|
|
66
|
-
JSON.stringify({
|
|
67
|
-
jsonrpc: "2.0",
|
|
68
|
-
error: { code: -32603, message: "Internal server error" },
|
|
69
|
-
id: null,
|
|
70
|
-
})
|
|
71
|
-
);
|
|
72
|
-
}
|
|
73
|
-
resolve();
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
);
|
|
77
|
-
});
|
|
78
|
-
}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
export { XmcpService } from "./xmcp.service";
|
|
2
|
-
export { XmcpController } from "./xmcp.controller";
|
|
3
|
-
export {
|
|
4
|
-
createMcpAuthGuard,
|
|
5
|
-
type AuthInfo,
|
|
6
|
-
type McpAuthConfig,
|
|
7
|
-
} from "./xmcp.guard";
|
|
8
|
-
export {
|
|
9
|
-
OAuthService,
|
|
10
|
-
OAUTH_CONFIG,
|
|
11
|
-
type OAuthConfig,
|
|
12
|
-
type OAuthProtectedResourceMetadata,
|
|
13
|
-
} from "./xmcp.oauth.service";
|
|
14
|
-
export { OAuthController } from "./xmcp.oauth.controller";
|
|
15
|
-
export { OAuthModule } from "./xmcp.oauth.module";
|
|
16
|
-
export { buildBaseUrl, buildResourceMetadataUrl } from "./xmcp.utils";
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { Post, Get, Options, Req, Res, Header, Injectable } from "@nestjs/common";
|
|
2
|
-
import { Request, Response } from "express";
|
|
3
|
-
import { XmcpService } from "./xmcp.service";
|
|
4
|
-
|
|
5
|
-
@Injectable()
|
|
6
|
-
export class XmcpController {
|
|
7
|
-
constructor(private readonly xmcpService: XmcpService) {}
|
|
8
|
-
|
|
9
|
-
@Post()
|
|
10
|
-
async handleMcp(@Req() req: Request, @Res() res: Response): Promise<void> {
|
|
11
|
-
return this.xmcpService.handleRequest(req, res);
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
@Get()
|
|
15
|
-
handleGet(@Res() res: Response): void {
|
|
16
|
-
res.status(200).json({
|
|
17
|
-
jsonrpc: "2.0",
|
|
18
|
-
error: {
|
|
19
|
-
code: -32000,
|
|
20
|
-
message: "Method not allowed. MCP requires POST requests.",
|
|
21
|
-
},
|
|
22
|
-
id: null,
|
|
23
|
-
});
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
@Options()
|
|
27
|
-
@Header("Access-Control-Allow-Origin", "*")
|
|
28
|
-
@Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
29
|
-
@Header("Access-Control-Allow-Headers", "*")
|
|
30
|
-
@Header("Access-Control-Max-Age", "86400")
|
|
31
|
-
handleOptions(@Res() res: Response): void {
|
|
32
|
-
res.status(204).send();
|
|
33
|
-
}
|
|
34
|
-
}
|
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
Injectable,
|
|
3
|
-
CanActivate,
|
|
4
|
-
ExecutionContext,
|
|
5
|
-
HttpException,
|
|
6
|
-
HttpStatus,
|
|
7
|
-
mixin,
|
|
8
|
-
Type,
|
|
9
|
-
} from "@nestjs/common";
|
|
10
|
-
import { Request, Response } from "express";
|
|
11
|
-
import { buildResourceMetadataUrl } from "./xmcp.utils";
|
|
12
|
-
|
|
13
|
-
export interface AuthInfo {
|
|
14
|
-
token: string;
|
|
15
|
-
clientId: string;
|
|
16
|
-
scopes: string[];
|
|
17
|
-
expiresAt?: number;
|
|
18
|
-
extra?: Record<string, unknown>;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export interface McpAuthConfig {
|
|
22
|
-
/** Verify token and return auth info. Throw an error if invalid. */
|
|
23
|
-
verifyToken: (
|
|
24
|
-
token: string
|
|
25
|
-
) => Promise<Omit<AuthInfo, "token">> | Omit<AuthInfo, "token">;
|
|
26
|
-
/** If true, requests without tokens will be rejected. Default: false */
|
|
27
|
-
required?: boolean;
|
|
28
|
-
/** Scopes required for access. If not provided, any valid token is accepted. */
|
|
29
|
-
requiredScopes?: string[];
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function createMcpAuthGuard(config: McpAuthConfig): Type<CanActivate> {
|
|
33
|
-
@Injectable()
|
|
34
|
-
class McpAuthGuardMixin implements CanActivate {
|
|
35
|
-
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
36
|
-
const request = context.switchToHttp().getRequest<Request>();
|
|
37
|
-
const response = context.switchToHttp().getResponse<Response>();
|
|
38
|
-
const authHeader = request.headers.authorization;
|
|
39
|
-
|
|
40
|
-
const resourceMetadataUrl = buildResourceMetadataUrl(request);
|
|
41
|
-
|
|
42
|
-
// No token provided
|
|
43
|
-
if (!authHeader?.startsWith("Bearer ")) {
|
|
44
|
-
if (config.required) {
|
|
45
|
-
const scopeParam = config.requiredScopes?.length
|
|
46
|
-
? `, scope="${config.requiredScopes.join(" ")}"`
|
|
47
|
-
: "";
|
|
48
|
-
response.setHeader(
|
|
49
|
-
"WWW-Authenticate",
|
|
50
|
-
`Bearer resource_metadata="${resourceMetadataUrl}"${scopeParam}`
|
|
51
|
-
);
|
|
52
|
-
throw new HttpException(
|
|
53
|
-
"Authentication required",
|
|
54
|
-
HttpStatus.UNAUTHORIZED
|
|
55
|
-
);
|
|
56
|
-
}
|
|
57
|
-
return true; // Allow without auth
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const token = authHeader.slice(7);
|
|
61
|
-
|
|
62
|
-
try {
|
|
63
|
-
const authResult = await config.verifyToken(token);
|
|
64
|
-
|
|
65
|
-
// Check required scopes
|
|
66
|
-
if (config.requiredScopes?.length) {
|
|
67
|
-
const hasAllScopes = config.requiredScopes.every((scope) =>
|
|
68
|
-
authResult.scopes.includes(scope)
|
|
69
|
-
);
|
|
70
|
-
if (!hasAllScopes) {
|
|
71
|
-
response.setHeader(
|
|
72
|
-
"WWW-Authenticate",
|
|
73
|
-
`Bearer error="insufficient_scope", scope="${config.requiredScopes.join(" ")}", resource_metadata="${resourceMetadataUrl}"`
|
|
74
|
-
);
|
|
75
|
-
throw new HttpException("Insufficient scope", HttpStatus.FORBIDDEN);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// Attach auth info to request
|
|
80
|
-
(request as any).auth = {
|
|
81
|
-
token,
|
|
82
|
-
...authResult,
|
|
83
|
-
} satisfies AuthInfo;
|
|
84
|
-
|
|
85
|
-
return true;
|
|
86
|
-
} catch (error) {
|
|
87
|
-
if (error instanceof HttpException) throw error;
|
|
88
|
-
response.setHeader(
|
|
89
|
-
"WWW-Authenticate",
|
|
90
|
-
`Bearer error="invalid_token", resource_metadata="${resourceMetadataUrl}"`
|
|
91
|
-
);
|
|
92
|
-
throw new HttpException(
|
|
93
|
-
error instanceof Error ? error.message : "Invalid token",
|
|
94
|
-
HttpStatus.UNAUTHORIZED
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
return mixin(McpAuthGuardMixin);
|
|
101
|
-
}
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
Controller,
|
|
3
|
-
Get,
|
|
4
|
-
Options,
|
|
5
|
-
Req,
|
|
6
|
-
Res,
|
|
7
|
-
Header,
|
|
8
|
-
Injectable,
|
|
9
|
-
} from "@nestjs/common";
|
|
10
|
-
import { Request, Response } from "express";
|
|
11
|
-
import { OAuthService } from "./xmcp.oauth.service";
|
|
12
|
-
|
|
13
|
-
@Controller(".well-known")
|
|
14
|
-
@Injectable()
|
|
15
|
-
export class OAuthController {
|
|
16
|
-
constructor(private readonly oauthService: OAuthService) {}
|
|
17
|
-
|
|
18
|
-
@Get(["oauth-protected-resource", "oauth-protected-resource/*path"])
|
|
19
|
-
@Header("Content-Type", "application/json")
|
|
20
|
-
@Header("Access-Control-Allow-Origin", "*")
|
|
21
|
-
@Header("Access-Control-Allow-Methods", "GET, OPTIONS")
|
|
22
|
-
@Header("Access-Control-Allow-Headers", "*")
|
|
23
|
-
@Header("Cache-Control", "public, max-age=3600")
|
|
24
|
-
getResourceMetadata(@Req() req: Request) {
|
|
25
|
-
return this.oauthService.getResourceMetadata(req);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
@Options(["oauth-protected-resource", "oauth-protected-resource/*path"])
|
|
29
|
-
@Header("Access-Control-Allow-Origin", "*")
|
|
30
|
-
@Header("Access-Control-Allow-Methods", "GET, OPTIONS")
|
|
31
|
-
@Header("Access-Control-Allow-Headers", "*")
|
|
32
|
-
@Header("Access-Control-Max-Age", "86400")
|
|
33
|
-
handleOptions(@Res() res: Response) {
|
|
34
|
-
res.status(204).send();
|
|
35
|
-
}
|
|
36
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { Module, DynamicModule } from "@nestjs/common";
|
|
2
|
-
import { OAuthService, OAuthConfig, OAUTH_CONFIG } from "./xmcp.oauth.service";
|
|
3
|
-
import { OAuthController } from "./xmcp.oauth.controller";
|
|
4
|
-
|
|
5
|
-
@Module({})
|
|
6
|
-
export class OAuthModule {
|
|
7
|
-
static forRoot(config: OAuthConfig): DynamicModule {
|
|
8
|
-
return {
|
|
9
|
-
module: OAuthModule,
|
|
10
|
-
controllers: [OAuthController],
|
|
11
|
-
providers: [
|
|
12
|
-
{
|
|
13
|
-
provide: OAUTH_CONFIG,
|
|
14
|
-
useValue: config,
|
|
15
|
-
},
|
|
16
|
-
OAuthService,
|
|
17
|
-
],
|
|
18
|
-
exports: [OAuthService],
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
}
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { Injectable, Inject } from "@nestjs/common";
|
|
2
|
-
import { Request } from "express";
|
|
3
|
-
import { buildBaseUrl } from "./xmcp.utils";
|
|
4
|
-
|
|
5
|
-
export const OAUTH_CONFIG = Symbol("OAUTH_CONFIG");
|
|
6
|
-
|
|
7
|
-
export interface OAuthConfig {
|
|
8
|
-
authorizationServers: string[];
|
|
9
|
-
scopesSupported?: string[];
|
|
10
|
-
bearerMethodsSupported?: string[];
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export interface OAuthProtectedResourceMetadata {
|
|
14
|
-
resource: string;
|
|
15
|
-
authorizationServers: string[];
|
|
16
|
-
scopesSupported?: string[];
|
|
17
|
-
bearerMethodsSupported?: string[];
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
@Injectable()
|
|
21
|
-
export class OAuthService {
|
|
22
|
-
constructor(@Inject(OAUTH_CONFIG) private readonly config: OAuthConfig) {}
|
|
23
|
-
|
|
24
|
-
getResourceMetadata(req: Request): OAuthProtectedResourceMetadata {
|
|
25
|
-
const resource = buildBaseUrl(req);
|
|
26
|
-
|
|
27
|
-
return {
|
|
28
|
-
resource,
|
|
29
|
-
authorizationServers: this.config.authorizationServers,
|
|
30
|
-
...(this.config.scopesSupported && {
|
|
31
|
-
scopesSupported: this.config.scopesSupported,
|
|
32
|
-
}),
|
|
33
|
-
bearerMethodsSupported: this.config.bearerMethodsSupported || ["header"],
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
}
|
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
Injectable,
|
|
3
|
-
Logger,
|
|
4
|
-
OnModuleInit,
|
|
5
|
-
OnModuleDestroy,
|
|
6
|
-
} from "@nestjs/common";
|
|
7
|
-
import { Request, Response } from "express";
|
|
8
|
-
import { createServer } from "@/runtime/utils/server";
|
|
9
|
-
import { StatelessHttpServerTransport } from "@/runtime/transports/http/stateless-streamable-http";
|
|
10
|
-
import { setHeaders } from "@/runtime/transports/http/cors";
|
|
11
|
-
import { httpRequestContextProvider } from "@/runtime/contexts/http-request-context";
|
|
12
|
-
import { randomUUID } from "node:crypto";
|
|
13
|
-
import type { CorsConfig } from "@/compiler/config";
|
|
14
|
-
import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
|
|
15
|
-
|
|
16
|
-
const corsConfig = HTTP_CORS_CONFIG as CorsConfig;
|
|
17
|
-
|
|
18
|
-
const httpConfig = HTTP_CONFIG as {
|
|
19
|
-
port: number;
|
|
20
|
-
host: string;
|
|
21
|
-
bodySizeLimit: number;
|
|
22
|
-
endpoint: string;
|
|
23
|
-
debug: boolean;
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
@Injectable()
|
|
27
|
-
export class XmcpService implements OnModuleInit, OnModuleDestroy {
|
|
28
|
-
private readonly logger = new Logger(XmcpService.name);
|
|
29
|
-
|
|
30
|
-
onModuleInit() {
|
|
31
|
-
this.logger.log("xmcp service initialized");
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
onModuleDestroy() {
|
|
35
|
-
this.logger.log("xmcp service shutting down");
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
async handleRequest(req: Request, res: Response): Promise<void> {
|
|
39
|
-
const requestId = randomUUID();
|
|
40
|
-
const startTime = Date.now();
|
|
41
|
-
|
|
42
|
-
this.logger.debug(`Request ${requestId} started`);
|
|
43
|
-
|
|
44
|
-
return new Promise((resolve) => {
|
|
45
|
-
const clientInfo = extractClientInfoFromMessages(req.body);
|
|
46
|
-
|
|
47
|
-
httpRequestContextProvider(
|
|
48
|
-
{ id: requestId, headers: req.headers, clientInfo },
|
|
49
|
-
async () => {
|
|
50
|
-
try {
|
|
51
|
-
setHeaders(res, corsConfig, req.headers.origin);
|
|
52
|
-
|
|
53
|
-
const server = await createServer();
|
|
54
|
-
const transport = new StatelessHttpServerTransport(
|
|
55
|
-
httpConfig.debug,
|
|
56
|
-
String(httpConfig.bodySizeLimit) || "10mb"
|
|
57
|
-
);
|
|
58
|
-
|
|
59
|
-
// cleanup when request/connection closes
|
|
60
|
-
res.on("close", () => {
|
|
61
|
-
transport.close();
|
|
62
|
-
server.close();
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
await server.connect(transport);
|
|
66
|
-
|
|
67
|
-
await transport.handleRequest(req, res, req.body).then(() => {
|
|
68
|
-
const duration = Date.now() - startTime;
|
|
69
|
-
this.logger.debug(
|
|
70
|
-
`Request ${requestId} completed in ${duration}ms`
|
|
71
|
-
);
|
|
72
|
-
resolve();
|
|
73
|
-
});
|
|
74
|
-
} catch (error) {
|
|
75
|
-
const duration = Date.now() - startTime;
|
|
76
|
-
this.logger.error(
|
|
77
|
-
`Request ${requestId} failed after ${duration}ms`,
|
|
78
|
-
error instanceof Error ? error.stack : String(error)
|
|
79
|
-
);
|
|
80
|
-
if (!res.headersSent) {
|
|
81
|
-
res.status(500).json({
|
|
82
|
-
jsonrpc: "2.0",
|
|
83
|
-
error: {
|
|
84
|
-
code: -32603,
|
|
85
|
-
message: "Internal server error",
|
|
86
|
-
},
|
|
87
|
-
id: null,
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
resolve();
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
);
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { Request } from "express";
|
|
2
|
-
|
|
3
|
-
export function buildBaseUrl(req: Request): string {
|
|
4
|
-
const protocol = req.headers["x-forwarded-proto"] || req.protocol;
|
|
5
|
-
const host = req.headers["x-forwarded-host"] || req.get("host");
|
|
6
|
-
return `${protocol}://${host}`;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export function buildResourceMetadataUrl(req: Request): string {
|
|
10
|
-
return `${buildBaseUrl(req)}/.well-known/oauth-protected-resource`;
|
|
11
|
-
}
|