xmcp 0.6.8 → 0.6.10
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/README.md +0 -32
- package/dist/cli.js +27 -24
- package/dist/compiler/config/index.d.ts +11 -11
- package/dist/compiler/config/schemas/experimental/index.d.ts +4 -4
- package/dist/compiler/config/schemas/transport/http.d.ts +13 -13
- package/dist/index.js +5 -5
- package/dist/runtime/adapter-express.js +16 -16
- package/dist/runtime/adapter-fastify.js +488 -0
- package/dist/runtime/adapter-nestjs.js +16 -16
- package/dist/runtime/adapter-nextjs.js +14 -14
- package/dist/runtime/http.js +24 -24
- package/dist/runtime/stdio.js +17 -17
- package/dist/runtime/utils/client-info.d.ts +8 -0
- package/dist/types/client-info.d.ts +1 -0
- package/package.json +4 -2
- package/src/compiler/config/__tests__/config.test.ts +56 -0
- package/src/compiler/config/schemas/experimental/index.ts +6 -1
- package/src/compiler/config/schemas/transport/http.ts +5 -0
- package/src/compiler/get-bundler-config/get-entries.ts +3 -0
- package/src/compiler/get-bundler-config/get-externals.ts +10 -0
- package/src/compiler/get-bundler-config/plugins/index.ts +8 -3
- package/src/compiler/get-bundler-config/plugins/types/fastify.ts +4 -0
- package/src/compiler/get-bundler-config/plugins/types/index.ts +1 -0
- package/src/runtime/adapters/fastify/__tests__/fastify.test.ts +115 -0
- package/src/runtime/adapters/fastify/index.ts +78 -0
- package/src/runtime/transports/http/cors/index.ts +4 -2
- package/src/runtime/transports/http/stateless-streamable-http.ts +11 -89
- package/src/runtime/utils/__tests__/client-info.test.ts +47 -0
- package/src/runtime/utils/__tests__/tool-extra.test.ts +91 -1
- package/src/runtime/utils/client-info.ts +36 -0
- package/src/runtime/utils/transformers/tool.ts +5 -1
- package/src/telemetry/events/definitions.ts +2 -0
- package/src/types/client-info.ts +8 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { JsonRpcMessage } from "@/runtime/transports/http/base-streamable-http";
|
|
2
|
+
import type { HttpHeaders } from "@/runtime/contexts/http-request-context";
|
|
3
|
+
import type { McpClientInfo } from "@/types/client-info";
|
|
4
|
+
import type { Implementation } from "@modelcontextprotocol/sdk/types";
|
|
5
|
+
export declare const mapImplementationToClientInfo: (implementation: Implementation | undefined) => McpClientInfo | undefined;
|
|
6
|
+
export declare const extractClientInfoFromMessage: (message: JsonRpcMessage | undefined) => McpClientInfo | undefined;
|
|
7
|
+
export declare const extractClientInfoFromMessages: (payload: unknown) => McpClientInfo | undefined;
|
|
8
|
+
export declare const extractClientInfoFromHeaders: (headers: HttpHeaders) => McpClientInfo | undefined;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export declare const CLIENT_INFO_HEADER_NAMES: readonly ["x-mcp-client-name", "x-mcp-client-version", "x-mcp-client-title", "x-mcp-client-website-url", "x-mcp-client-description"];
|
|
1
2
|
export interface McpClientInfo {
|
|
2
3
|
/** MCP client implementation name from initialize.params.clientInfo.name */
|
|
3
4
|
name: string;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "xmcp",
|
|
3
3
|
"description": "The MCP framework",
|
|
4
|
-
"version": "0.6.
|
|
4
|
+
"version": "0.6.10",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "xmcp",
|
|
7
7
|
"email": "support@xmcp.dev",
|
|
@@ -84,7 +84,8 @@
|
|
|
84
84
|
"dev": "cross-env NODE_ENV=development tsx --watch --tsconfig ./bundler.tsconfig.json ./bundler/index.ts",
|
|
85
85
|
"build": "cross-env NODE_ENV=production tsx --tsconfig ./bundler.tsconfig.json ./bundler/index.ts",
|
|
86
86
|
"analyze": "cross-env GENERATE_STATS=true pnpm build && pnpm tsx scripts/analyze-rspack-stats.ts",
|
|
87
|
-
"test:config": "node --import tsx --test src/compiler/config/__tests__/*.test.ts"
|
|
87
|
+
"test:config": "node --import tsx --test src/compiler/config/__tests__/*.test.ts",
|
|
88
|
+
"test:adapters": "node --import tsx --test src/runtime/adapters/fastify/__tests__/*.test.ts"
|
|
88
89
|
},
|
|
89
90
|
"dependencies": {
|
|
90
91
|
"@modelcontextprotocol/sdk": "^1.26.0",
|
|
@@ -114,6 +115,7 @@
|
|
|
114
115
|
"del": "^7.1.0",
|
|
115
116
|
"dotenv": "^16.6.1",
|
|
116
117
|
"express": "^4.22.1",
|
|
118
|
+
"fastify": "^5.0.0",
|
|
117
119
|
"fs-extra": "^11.3.2",
|
|
118
120
|
"glob": "^11.1.0",
|
|
119
121
|
"is-docker": "^4.0.0",
|
|
@@ -71,10 +71,45 @@ describe("Config System - Zod Defaults", () => {
|
|
|
71
71
|
const corsConfig = getResolvedCorsConfig(httpConfig);
|
|
72
72
|
assert.equal(corsConfig.origin, "*");
|
|
73
73
|
assert.deepEqual(corsConfig.methods, ["GET", "POST"]);
|
|
74
|
+
assert.deepEqual(corsConfig.allowedHeaders, [
|
|
75
|
+
"Content-Type",
|
|
76
|
+
"Authorization",
|
|
77
|
+
"mcp-session-id",
|
|
78
|
+
"mcp-protocol-version",
|
|
79
|
+
"x-mcp-client-name",
|
|
80
|
+
"x-mcp-client-version",
|
|
81
|
+
"x-mcp-client-title",
|
|
82
|
+
"x-mcp-client-website-url",
|
|
83
|
+
"x-mcp-client-description",
|
|
84
|
+
]);
|
|
74
85
|
assert.equal(corsConfig.credentials, false);
|
|
75
86
|
assert.equal(corsConfig.maxAge, 86400);
|
|
76
87
|
}
|
|
77
88
|
});
|
|
89
|
+
|
|
90
|
+
it("should preserve client info headers when merging CORS allowedHeaders arrays", () => {
|
|
91
|
+
const httpConfig = getResolvedHttpConfig({
|
|
92
|
+
cors: {
|
|
93
|
+
allowedHeaders: ["Content-Type", "Authorization"],
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
assert.notEqual(httpConfig, null);
|
|
97
|
+
|
|
98
|
+
if (httpConfig) {
|
|
99
|
+
const corsConfig = getResolvedCorsConfig(httpConfig);
|
|
100
|
+
assert.deepEqual(corsConfig.allowedHeaders, [
|
|
101
|
+
"Content-Type",
|
|
102
|
+
"Authorization",
|
|
103
|
+
"mcp-session-id",
|
|
104
|
+
"mcp-protocol-version",
|
|
105
|
+
"x-mcp-client-name",
|
|
106
|
+
"x-mcp-client-version",
|
|
107
|
+
"x-mcp-client-title",
|
|
108
|
+
"x-mcp-client-website-url",
|
|
109
|
+
"x-mcp-client-description",
|
|
110
|
+
]);
|
|
111
|
+
}
|
|
112
|
+
});
|
|
78
113
|
});
|
|
79
114
|
|
|
80
115
|
describe("Config System - Boolean Transformations", () => {
|
|
@@ -169,6 +204,27 @@ describe("Config System - Resolution Functions", () => {
|
|
|
169
204
|
|
|
170
205
|
assert.equal(resolved.adapter, "express");
|
|
171
206
|
});
|
|
207
|
+
|
|
208
|
+
it("should resolve fastify adapter", () => {
|
|
209
|
+
const config = configSchema.parse({
|
|
210
|
+
experimental: {
|
|
211
|
+
adapter: "fastify",
|
|
212
|
+
},
|
|
213
|
+
});
|
|
214
|
+
const resolved = getResolvedExperimentalConfig(config);
|
|
215
|
+
|
|
216
|
+
assert.equal(resolved.adapter, "fastify");
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("should reject unknown adapter values", () => {
|
|
220
|
+
assert.throws(() => {
|
|
221
|
+
configSchema.parse({
|
|
222
|
+
experimental: {
|
|
223
|
+
adapter: "unknown-framework",
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
});
|
|
172
228
|
});
|
|
173
229
|
|
|
174
230
|
describe("Config System - Injection Functions", () => {
|
|
@@ -3,7 +3,12 @@ import { z } from "zod/v3";
|
|
|
3
3
|
// ------------------------------------------------------------
|
|
4
4
|
// Adapter config schema (perhaps a separate file but it's small yet)
|
|
5
5
|
// ------------------------------------------------------------
|
|
6
|
-
export const adapterConfigSchema = z.enum([
|
|
6
|
+
export const adapterConfigSchema = z.enum([
|
|
7
|
+
"express",
|
|
8
|
+
"nextjs",
|
|
9
|
+
"nestjs",
|
|
10
|
+
"fastify",
|
|
11
|
+
]);
|
|
7
12
|
|
|
8
13
|
export type AdapterConfig = z.infer<typeof adapterConfigSchema>;
|
|
9
14
|
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod/v3";
|
|
2
|
+
import { CLIENT_INFO_HEADER_NAMES } from "@/types/client-info";
|
|
2
3
|
|
|
3
4
|
// ------------------------------------------------------------
|
|
4
5
|
// Cors config schema
|
|
@@ -14,6 +15,7 @@ const corsConfigBaseSchema = z.object({
|
|
|
14
15
|
"Authorization",
|
|
15
16
|
"mcp-session-id",
|
|
16
17
|
"mcp-protocol-version",
|
|
18
|
+
...CLIENT_INFO_HEADER_NAMES,
|
|
17
19
|
]),
|
|
18
20
|
exposedHeaders: z
|
|
19
21
|
.union([z.string(), z.array(z.string())])
|
|
@@ -40,6 +42,9 @@ export const corsConfigSchema = corsConfigBaseSchema
|
|
|
40
42
|
const headers = new Set(result.allowedHeaders);
|
|
41
43
|
headers.add("mcp-session-id");
|
|
42
44
|
headers.add("mcp-protocol-version");
|
|
45
|
+
for (const clientInfoHeaderName of CLIENT_INFO_HEADER_NAMES) {
|
|
46
|
+
headers.add(clientInfoHeaderName);
|
|
47
|
+
}
|
|
43
48
|
result.allowedHeaders = Array.from(headers);
|
|
44
49
|
}
|
|
45
50
|
if (Array.isArray(result.exposedHeaders)) {
|
|
@@ -36,6 +36,9 @@ export function getEntries(
|
|
|
36
36
|
if (xmcpConfig.experimental?.adapter === "nestjs") {
|
|
37
37
|
entries["adapter"] = path.join(runtimeFolderPath, "adapter-nestjs.js");
|
|
38
38
|
}
|
|
39
|
+
if (xmcpConfig.experimental?.adapter === "fastify") {
|
|
40
|
+
entries["adapter"] = path.join(runtimeFolderPath, "adapter-fastify.js");
|
|
41
|
+
}
|
|
39
42
|
}
|
|
40
43
|
return entries;
|
|
41
44
|
}
|
|
@@ -74,6 +74,16 @@ export function getExternals(): RspackOptions["externals"] {
|
|
|
74
74
|
return callback(undefined, `commonjs ${pathRequest}`);
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
+
/**
|
|
78
|
+
* When using Fastify, externalize fastify since it should come from
|
|
79
|
+
* the user's node_modules
|
|
80
|
+
*/
|
|
81
|
+
if (xmcpConfig.experimental?.adapter === "fastify") {
|
|
82
|
+
if (request === "fastify" || request.startsWith("fastify/")) {
|
|
83
|
+
return callback(undefined, `commonjs ${request}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
77
87
|
/**
|
|
78
88
|
* When using NestJS, externalize NestJS-related packages
|
|
79
89
|
* since they should come from the user's node_modules
|
|
@@ -6,6 +6,7 @@ import { XmcpConfigOutputSchema } from "@/compiler/config";
|
|
|
6
6
|
import { getXmcpConfig } from "@/compiler/compiler-context";
|
|
7
7
|
import {
|
|
8
8
|
expressTypeDefinition,
|
|
9
|
+
fastifyTypeDefinition,
|
|
9
10
|
nestJsTypeDefinition,
|
|
10
11
|
nextJsTypeDefinition,
|
|
11
12
|
} from "./types";
|
|
@@ -70,6 +71,8 @@ function getNeededRuntimeFiles(xmcpConfig: XmcpConfigOutputSchema): string[] {
|
|
|
70
71
|
neededFiles.push("adapter-nextjs.js");
|
|
71
72
|
} else if (xmcpConfig.experimental?.adapter === "nestjs") {
|
|
72
73
|
neededFiles.push("adapter-nestjs.js");
|
|
74
|
+
} else if (xmcpConfig.experimental?.adapter === "fastify") {
|
|
75
|
+
neededFiles.push("adapter-fastify.js");
|
|
73
76
|
} else {
|
|
74
77
|
neededFiles.push("http.js");
|
|
75
78
|
}
|
|
@@ -117,12 +120,14 @@ export class CreateTypeDefinitionPlugin {
|
|
|
117
120
|
// Manually type the .xmcp/adapter/index.js file using a .xmcp/adapter/index.d.ts file
|
|
118
121
|
if (xmcpConfig.experimental?.adapter) {
|
|
119
122
|
let typeDefinitionContent = "";
|
|
120
|
-
if (xmcpConfig.experimental?.adapter
|
|
123
|
+
if (xmcpConfig.experimental?.adapter === "nextjs") {
|
|
121
124
|
typeDefinitionContent = nextJsTypeDefinition;
|
|
122
|
-
} else if (xmcpConfig.experimental?.adapter
|
|
125
|
+
} else if (xmcpConfig.experimental?.adapter === "express") {
|
|
123
126
|
typeDefinitionContent = expressTypeDefinition;
|
|
124
|
-
} else if (xmcpConfig.experimental?.adapter
|
|
127
|
+
} else if (xmcpConfig.experimental?.adapter === "nestjs") {
|
|
125
128
|
typeDefinitionContent = nestJsTypeDefinition;
|
|
129
|
+
} else if (xmcpConfig.experimental?.adapter === "fastify") {
|
|
130
|
+
typeDefinitionContent = fastifyTypeDefinition;
|
|
126
131
|
}
|
|
127
132
|
fs.writeFileSync(
|
|
128
133
|
path.join(adapterOutputPath, "index.d.ts"),
|
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,78 @@
|
|
|
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,12 +1,14 @@
|
|
|
1
1
|
import { CorsConfig } from "@/compiler/config";
|
|
2
|
+
import { ServerResponse } from "http";
|
|
2
3
|
import { Request, Response, NextFunction, RequestHandler } from "express";
|
|
3
4
|
import { buildCorsHeaders } from "./headers";
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
|
-
* Sets CORS headers on the response based on the provided configuration
|
|
7
|
+
* Sets CORS headers on the response based on the provided configuration.
|
|
8
|
+
* Accepts any Node ServerResponse (or Express Response, which extends it).
|
|
7
9
|
*/
|
|
8
10
|
export function setHeaders(
|
|
9
|
-
res:
|
|
11
|
+
res: ServerResponse,
|
|
10
12
|
config: CorsConfig,
|
|
11
13
|
origin?: string
|
|
12
14
|
): void {
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp";
|
|
2
2
|
import { StreamableHTTPServerTransport as SdkStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp";
|
|
3
|
-
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types";
|
|
4
3
|
import express, {
|
|
5
4
|
Express,
|
|
6
5
|
Request,
|
|
@@ -32,13 +31,6 @@ import {
|
|
|
32
31
|
import { CorsConfig, corsConfigSchema } from "@/compiler/config/schemas";
|
|
33
32
|
import { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
|
|
34
33
|
import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
|
|
35
|
-
import type { McpClientInfo } from "@/types/client-info";
|
|
36
|
-
|
|
37
|
-
interface SessionLifecycle {
|
|
38
|
-
server: McpServer;
|
|
39
|
-
transport: SdkStreamableHTTPServerTransport;
|
|
40
|
-
clientInfo?: McpClientInfo;
|
|
41
|
-
}
|
|
42
34
|
|
|
43
35
|
// Global type declarations for tool name context
|
|
44
36
|
declare global {
|
|
@@ -110,7 +102,6 @@ export class StatelessStreamableHTTPTransport {
|
|
|
110
102
|
private createServerFn: () => Promise<McpServer>;
|
|
111
103
|
private corsConfig: CorsConfig;
|
|
112
104
|
private providers: Provider[] | undefined;
|
|
113
|
-
private sessions = new Map<string, SessionLifecycle>();
|
|
114
105
|
|
|
115
106
|
constructor(
|
|
116
107
|
createServerFn: () => Promise<McpServer>,
|
|
@@ -175,7 +166,7 @@ export class StatelessStreamableHTTPTransport {
|
|
|
175
166
|
res.status(200).json({
|
|
176
167
|
status: "ok",
|
|
177
168
|
transport: "streamable-http",
|
|
178
|
-
mode: "
|
|
169
|
+
mode: "stateless",
|
|
179
170
|
});
|
|
180
171
|
});
|
|
181
172
|
|
|
@@ -260,56 +251,25 @@ export class StatelessStreamableHTTPTransport {
|
|
|
260
251
|
): Promise<void> {
|
|
261
252
|
try {
|
|
262
253
|
const requestClientInfo = extractClientInfoFromMessages(req.body);
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
254
|
+
const server = await this.createServerFn();
|
|
255
|
+
const transport = new StatelessHttpServerTransport(
|
|
256
|
+
this.debug,
|
|
257
|
+
this.options.bodySizeLimit || "10mb"
|
|
258
|
+
);
|
|
266
259
|
|
|
267
260
|
res.on("finish", () => {
|
|
268
261
|
global.__XMCP_CURRENT_TOOL_NAME = undefined;
|
|
269
262
|
});
|
|
270
263
|
res.on("close", () => {
|
|
264
|
+
void transport.close();
|
|
265
|
+
void server.close();
|
|
271
266
|
global.__XMCP_CURRENT_TOOL_NAME = undefined;
|
|
272
267
|
});
|
|
273
268
|
|
|
274
|
-
|
|
275
|
-
if (
|
|
276
|
-
sessionId ||
|
|
277
|
-
req.method !== "POST" ||
|
|
278
|
-
!isInitializeRequest(req.body)
|
|
279
|
-
) {
|
|
280
|
-
res.status(400).json({
|
|
281
|
-
jsonrpc: "2.0",
|
|
282
|
-
error: {
|
|
283
|
-
code: -32000,
|
|
284
|
-
message: "Bad Request: No valid session ID provided",
|
|
285
|
-
},
|
|
286
|
-
id: null,
|
|
287
|
-
});
|
|
288
|
-
return;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
lifecycle = await this.createSessionLifecycle();
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
if (!clientInfo) {
|
|
295
|
-
clientInfo = lifecycle.clientInfo;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
setHttpRequestContext({ clientInfo });
|
|
299
|
-
|
|
300
|
-
await lifecycle.transport.handleRequest(req, res, req.body);
|
|
269
|
+
setHttpRequestContext({ clientInfo: requestClientInfo });
|
|
301
270
|
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
...lifecycle,
|
|
305
|
-
clientInfo,
|
|
306
|
-
});
|
|
307
|
-
} else if (sessionId && lifecycle.transport.sessionId) {
|
|
308
|
-
this.sessions.set(lifecycle.transport.sessionId, {
|
|
309
|
-
...lifecycle,
|
|
310
|
-
clientInfo,
|
|
311
|
-
});
|
|
312
|
-
}
|
|
271
|
+
await server.connect(transport);
|
|
272
|
+
await transport.handleRequest(req, res, req.body);
|
|
313
273
|
} catch (error) {
|
|
314
274
|
console.error("[HTTP-server] Error handling MCP request:", error);
|
|
315
275
|
if (!res.headersSent) {
|
|
@@ -325,37 +285,6 @@ export class StatelessStreamableHTTPTransport {
|
|
|
325
285
|
}
|
|
326
286
|
}
|
|
327
287
|
|
|
328
|
-
private getSessionId(req: Request): string | undefined {
|
|
329
|
-
const header = req.headers["mcp-session-id"];
|
|
330
|
-
|
|
331
|
-
if (Array.isArray(header)) {
|
|
332
|
-
return header[0];
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
return typeof header === "string" && header.length > 0 ? header : undefined;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
private async createSessionLifecycle(): Promise<SessionLifecycle> {
|
|
339
|
-
const server = await this.createServerFn();
|
|
340
|
-
const transport = new SdkStreamableHTTPServerTransport({
|
|
341
|
-
sessionIdGenerator: () => randomUUID(),
|
|
342
|
-
});
|
|
343
|
-
|
|
344
|
-
transport.onclose = () => {
|
|
345
|
-
const sessionId = transport.sessionId;
|
|
346
|
-
|
|
347
|
-
if (sessionId) {
|
|
348
|
-
this.sessions.delete(sessionId);
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
void server.close();
|
|
352
|
-
};
|
|
353
|
-
|
|
354
|
-
await server.connect(transport);
|
|
355
|
-
|
|
356
|
-
return { server, transport };
|
|
357
|
-
}
|
|
358
|
-
|
|
359
288
|
public async start(): Promise<void> {
|
|
360
289
|
const host = this.options.host || "127.0.0.1";
|
|
361
290
|
const port = await findAvailablePort(this.port, host);
|
|
@@ -376,13 +305,6 @@ export class StatelessStreamableHTTPTransport {
|
|
|
376
305
|
|
|
377
306
|
public shutdown(): void {
|
|
378
307
|
this.log("Shutting down server");
|
|
379
|
-
|
|
380
|
-
for (const { server, transport } of this.sessions.values()) {
|
|
381
|
-
void transport.close();
|
|
382
|
-
void server.close();
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
this.sessions.clear();
|
|
386
308
|
this.server.close();
|
|
387
309
|
process.exit(0);
|
|
388
310
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { test } from "node:test";
|
|
2
2
|
import assert from "node:assert";
|
|
3
3
|
import {
|
|
4
|
+
extractClientInfoFromHeaders,
|
|
4
5
|
extractClientInfoFromMessage,
|
|
5
6
|
extractClientInfoFromMessages,
|
|
6
7
|
mapImplementationToClientInfo,
|
|
@@ -97,3 +98,49 @@ test("mapImplementationToClientInfo maps SDK implementation shape", () => {
|
|
|
97
98
|
description: "CLI coding agent",
|
|
98
99
|
});
|
|
99
100
|
});
|
|
101
|
+
|
|
102
|
+
test("extractClientInfoFromHeaders extracts required and optional fields", () => {
|
|
103
|
+
const result = extractClientInfoFromHeaders({
|
|
104
|
+
"x-mcp-client-name": "cursor",
|
|
105
|
+
"x-mcp-client-version": "0.50.1",
|
|
106
|
+
"x-mcp-client-title": "Cursor",
|
|
107
|
+
"x-mcp-client-website-url": "https://cursor.com",
|
|
108
|
+
"x-mcp-client-description": "AI code editor",
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
assert.deepStrictEqual(result, {
|
|
112
|
+
name: "cursor",
|
|
113
|
+
version: "0.50.1",
|
|
114
|
+
title: "Cursor",
|
|
115
|
+
websiteUrl: "https://cursor.com",
|
|
116
|
+
description: "AI code editor",
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("extractClientInfoFromHeaders handles case-insensitive header names", () => {
|
|
121
|
+
const result = extractClientInfoFromHeaders({
|
|
122
|
+
"X-MCP-Client-Name": "claude-code",
|
|
123
|
+
"X-MCP-Client-Version": "2.1.0",
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
assert.deepStrictEqual(result, {
|
|
127
|
+
name: "claude-code",
|
|
128
|
+
version: "2.1.0",
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("extractClientInfoFromHeaders returns undefined without name and version", () => {
|
|
133
|
+
assert.strictEqual(
|
|
134
|
+
extractClientInfoFromHeaders({
|
|
135
|
+
"x-mcp-client-name": "cursor",
|
|
136
|
+
}),
|
|
137
|
+
undefined
|
|
138
|
+
);
|
|
139
|
+
|
|
140
|
+
assert.strictEqual(
|
|
141
|
+
extractClientInfoFromHeaders({
|
|
142
|
+
"x-mcp-client-version": "0.50.1",
|
|
143
|
+
}),
|
|
144
|
+
undefined
|
|
145
|
+
);
|
|
146
|
+
});
|