xmcp 0.6.6 → 0.6.8
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 +32 -0
- package/dist/cli.js +55 -36
- package/dist/compiler/config/index.d.ts +61 -54
- package/dist/compiler/config/schemas/template.d.ts +5 -0
- package/dist/compiler/config/schemas/transport/http.d.ts +82 -82
- package/dist/host-bridge.d.ts +4 -0
- package/dist/host-bridge.js +1 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.js +5 -5
- package/dist/runtime/adapter-express.js +45 -26
- package/dist/runtime/adapter-nestjs.js +45 -26
- package/dist/runtime/adapter-nextjs.js +44 -25
- package/dist/runtime/contexts/client-info-context.d.ts +8 -0
- package/dist/runtime/contexts/http-request-context.d.ts +3 -1
- package/dist/runtime/headers.js +1 -1
- package/dist/runtime/http.js +53 -34
- package/dist/runtime/stdio.js +32 -24
- package/dist/runtime/utils/elicitation.d.ts +4 -0
- package/dist/runtime/utils/ext-apps-registry.d.ts +132 -0
- package/dist/runtime/utils/mcp-app-protocol.d.ts +14 -0
- package/dist/runtime/utils/mcp-app-types.d.ts +103 -0
- package/dist/runtime/utils/mcp-host-bridge.d.ts +43 -0
- package/dist/runtime/utils/path-to-tool-name.d.ts +20 -0
- package/dist/runtime/utils/prompt-loader.d.ts +11 -0
- package/dist/runtime/utils/prompts.d.ts +8 -0
- package/dist/runtime/utils/react/generate-html.d.ts +1 -0
- package/dist/runtime/utils/react/index.d.ts +4 -0
- package/dist/runtime/utils/resource-loader.d.ts +11 -0
- package/dist/runtime/utils/resources.d.ts +4 -0
- package/dist/runtime/utils/server.d.ts +37 -0
- package/dist/runtime/utils/tool-loader.d.ts +11 -0
- package/dist/runtime/utils/tools.d.ts +11 -0
- package/dist/runtime/utils/transformers/prompt.d.ts +32 -0
- package/dist/runtime/utils/transformers/resource.d.ts +26 -0
- package/dist/runtime/utils/transformers/tool.d.ts +30 -0
- package/dist/runtime/utils/ui/flatten-meta.d.ts +6 -0
- package/dist/runtime/utils/ui/split-meta.d.ts +17 -0
- package/dist/runtime/utils/utils/resource-uri-composer.d.ts +60 -0
- package/dist/runtime/utils/validators/index.d.ts +13 -0
- package/dist/types/client-info.d.ts +12 -0
- package/dist/types/tool.d.ts +69 -14
- package/dist/types/ui-meta.d.ts +15 -0
- package/dist/utils/context.d.ts +1 -1
- package/package.json +20 -1
- package/src/client/index.ts +4 -1
- package/src/compiler/client/component-compiler.ts +26 -5
- package/src/compiler/config/injection.ts +1 -0
- package/src/compiler/config/schemas/template.ts +13 -0
- package/src/compiler/generate-tools-code.ts +4 -6
- package/src/compiler/get-bundler-config/index.ts +1 -0
- package/src/compiler/get-bundler-config/plugins/index.ts +0 -1
- package/src/compiler/index.ts +24 -7
- package/src/host-bridge.ts +36 -0
- package/src/index.ts +44 -1
- package/src/runtime/adapters/express/index.ts +45 -47
- package/src/runtime/adapters/nestjs/xmcp.service.ts +4 -3
- package/src/runtime/adapters/nextjs/handler/node-to-web-adapter.ts +40 -6
- package/src/runtime/adapters/nextjs/handler/request-converter.ts +20 -0
- package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +10 -6
- package/src/runtime/adapters/nextjs/index.ts +41 -25
- package/src/runtime/contexts/client-info-context.ts +16 -0
- package/src/runtime/contexts/http-request-context.ts +2 -0
- package/src/runtime/headers.ts +37 -2
- package/src/runtime/platforms/cloudflare/cors.ts +0 -1
- package/src/runtime/platforms/cloudflare/worker.ts +46 -44
- package/src/runtime/transports/http/index.ts +0 -4
- package/src/runtime/transports/http/stateless-streamable-http.ts +131 -233
- package/src/runtime/transports/stdio/index.ts +40 -9
- package/src/runtime/utils/__tests__/client-info.test.ts +99 -0
- package/src/runtime/utils/__tests__/tool-extra.test.ts +149 -0
- package/src/runtime/utils/client-info.ts +78 -0
- package/src/runtime/utils/elicitation.ts +396 -0
- package/src/runtime/utils/mcp-app-protocol.ts +16 -0
- package/src/runtime/utils/mcp-app-types.ts +113 -0
- package/src/runtime/utils/mcp-host-bridge.ts +473 -0
- package/src/runtime/utils/prompt-loader.ts +151 -0
- package/src/runtime/utils/react/generate-html.ts +12 -4
- package/src/runtime/utils/resource-loader.ts +151 -0
- package/src/runtime/utils/resources.ts +0 -8
- package/src/runtime/utils/server.ts +31 -40
- package/src/runtime/utils/tool-loader.ts +149 -0
- package/src/runtime/utils/tools.ts +9 -6
- package/src/runtime/utils/transformers/tool.ts +35 -5
- package/src/runtime/utils/ui/__tests__/split-meta.test.ts +42 -0
- package/src/runtime/utils/ui/split-meta.ts +4 -1
- package/src/types/client-info.ts +12 -0
- package/src/types/injected.d.ts +62 -0
- package/src/types/tool.ts +99 -17
- package/src/types/ui-meta.ts +17 -1
- package/src/utils/context.ts +2 -2
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp";
|
|
2
|
+
import { StreamableHTTPServerTransport as SdkStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp";
|
|
3
|
+
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types";
|
|
2
4
|
import express, {
|
|
3
5
|
Express,
|
|
4
6
|
Request,
|
|
@@ -8,8 +10,7 @@ import express, {
|
|
|
8
10
|
} from "express";
|
|
9
11
|
import http, { IncomingMessage, ServerResponse } from "http";
|
|
10
12
|
import { randomUUID } from "node:crypto";
|
|
11
|
-
import
|
|
12
|
-
import contentType from "content-type";
|
|
13
|
+
import type { TransportSendOptions } from "@modelcontextprotocol/sdk/shared/transport";
|
|
13
14
|
import {
|
|
14
15
|
BaseHttpServerTransport,
|
|
15
16
|
JsonRpcMessage,
|
|
@@ -20,253 +21,81 @@ import { greenCheck } from "../../../utils/cli-icons";
|
|
|
20
21
|
import { findAvailablePort } from "../../../utils/port-utils";
|
|
21
22
|
import { cors } from "./cors";
|
|
22
23
|
import { Provider } from "@/runtime/middlewares/utils";
|
|
23
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
httpRequestContextProvider,
|
|
26
|
+
setHttpRequestContext,
|
|
27
|
+
} from "@/runtime/contexts/http-request-context";
|
|
24
28
|
import {
|
|
25
29
|
extractToolNamesFromRequest,
|
|
26
30
|
storeToolNamesOnRequestHeaders,
|
|
27
31
|
} from "@/runtime/utils/request-tool-names";
|
|
28
32
|
import { CorsConfig, corsConfigSchema } from "@/compiler/config/schemas";
|
|
29
33
|
import { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
|
|
34
|
+
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
|
+
}
|
|
30
42
|
|
|
31
43
|
// Global type declarations for tool name context
|
|
32
44
|
declare global {
|
|
33
45
|
var __XMCP_CURRENT_TOOL_NAME: string | string[] | undefined;
|
|
34
46
|
}
|
|
35
47
|
|
|
36
|
-
//
|
|
48
|
+
// Stateless node transport that delegates protocol handling to the MCP SDK.
|
|
37
49
|
export class StatelessHttpServerTransport extends BaseHttpServerTransport {
|
|
38
|
-
debug: boolean;
|
|
39
|
-
|
|
40
|
-
private _started: boolean = false;
|
|
41
|
-
private _singleResponseCollectors: Map<
|
|
42
|
-
string,
|
|
43
|
-
{
|
|
44
|
-
res: ServerResponse;
|
|
45
|
-
requestIds: Set<string | number>;
|
|
46
|
-
responses: JsonRpcMessage[];
|
|
47
|
-
expectedCount: number;
|
|
48
|
-
}
|
|
49
|
-
> = new Map();
|
|
50
|
-
private _requestToCollectorMapping: Map<string | number, string> = new Map();
|
|
50
|
+
private readonly debug: boolean;
|
|
51
|
+
private readonly transport: SdkStreamableHTTPServerTransport;
|
|
51
52
|
|
|
52
|
-
constructor(debug: boolean,
|
|
53
|
+
constructor(debug: boolean, _bodySizeLimit: string) {
|
|
53
54
|
super();
|
|
54
55
|
this.debug = debug;
|
|
55
|
-
this.
|
|
56
|
+
this.transport = new SdkStreamableHTTPServerTransport({
|
|
57
|
+
sessionIdGenerator: undefined,
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
this.transport.onmessage = (message, extra) => {
|
|
61
|
+
this.onmessage?.(message as JsonRpcMessage, extra);
|
|
62
|
+
};
|
|
63
|
+
this.transport.onerror = (error) => {
|
|
64
|
+
this.onerror?.(error);
|
|
65
|
+
};
|
|
66
|
+
this.transport.onclose = () => {
|
|
67
|
+
this.onclose?.();
|
|
68
|
+
};
|
|
56
69
|
}
|
|
57
70
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (this._started) {
|
|
62
|
-
throw new Error("Transport already started");
|
|
71
|
+
private log(message: string, ...args: unknown[]): void {
|
|
72
|
+
if (this.debug) {
|
|
73
|
+
console.log(`[StatelessHTTP] ${message}`, ...args);
|
|
63
74
|
}
|
|
64
|
-
this._started = true;
|
|
65
75
|
}
|
|
66
76
|
|
|
67
|
-
async
|
|
68
|
-
this.
|
|
69
|
-
if (!collector.res.headersSent) {
|
|
70
|
-
collector.res.writeHead(503).end(
|
|
71
|
-
JSON.stringify({
|
|
72
|
-
jsonrpc: "2.0",
|
|
73
|
-
error: {
|
|
74
|
-
code: -32000,
|
|
75
|
-
message: "Service unavailable: Server shutting down",
|
|
76
|
-
},
|
|
77
|
-
id: null,
|
|
78
|
-
})
|
|
79
|
-
);
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
this._singleResponseCollectors?.clear();
|
|
83
|
-
this._requestToCollectorMapping?.clear();
|
|
77
|
+
async start(): Promise<void> {
|
|
78
|
+
await this.transport.start();
|
|
84
79
|
}
|
|
85
80
|
|
|
86
|
-
async
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
if (requestId === undefined || requestId === null) {
|
|
90
|
-
// In stateless mode, we can't handle notifications without request IDs
|
|
91
|
-
if (this.debug) {
|
|
92
|
-
console.log("[StatelessHTTP] Dropping notification without request ID");
|
|
93
|
-
}
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const collectorId = this._requestToCollectorMapping?.get(requestId);
|
|
98
|
-
if (collectorId) {
|
|
99
|
-
const collector = this._singleResponseCollectors?.get(collectorId);
|
|
100
|
-
if (
|
|
101
|
-
collector &&
|
|
102
|
-
(message.result !== undefined || message.error !== undefined)
|
|
103
|
-
) {
|
|
104
|
-
collector.responses.push(message);
|
|
105
|
-
collector.requestIds.delete(requestId);
|
|
106
|
-
|
|
107
|
-
if (collector.requestIds.size === 0) {
|
|
108
|
-
const headers: Record<string, string> = {
|
|
109
|
-
"Content-Type": "application/json",
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
const responseBody =
|
|
113
|
-
collector.responses.length === 1
|
|
114
|
-
? collector.responses[0]
|
|
115
|
-
: collector.responses;
|
|
116
|
-
|
|
117
|
-
collector.res
|
|
118
|
-
.writeHead(200, headers)
|
|
119
|
-
.end(JSON.stringify(responseBody));
|
|
120
|
-
|
|
121
|
-
this._singleResponseCollectors?.delete(collectorId);
|
|
122
|
-
for (const response of collector.responses) {
|
|
123
|
-
if (response.id !== undefined && response.id !== null) {
|
|
124
|
-
this._requestToCollectorMapping?.delete(response.id);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
}
|
|
81
|
+
async close(): Promise<void> {
|
|
82
|
+
await this.transport.close();
|
|
130
83
|
}
|
|
131
84
|
|
|
132
|
-
async
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
parsedBody?: unknown
|
|
85
|
+
async send(
|
|
86
|
+
message: JsonRpcMessage,
|
|
87
|
+
options?: TransportSendOptions
|
|
136
88
|
): Promise<void> {
|
|
137
|
-
|
|
138
|
-
if (req.method !== "POST") {
|
|
139
|
-
res.writeHead(405).end(
|
|
140
|
-
JSON.stringify({
|
|
141
|
-
jsonrpc: "2.0",
|
|
142
|
-
error: {
|
|
143
|
-
code: -32000,
|
|
144
|
-
message: "Method not allowed.",
|
|
145
|
-
},
|
|
146
|
-
id: null,
|
|
147
|
-
})
|
|
148
|
-
);
|
|
149
|
-
return;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
await this.handlePOST(req, res, parsedBody);
|
|
89
|
+
await this.transport.send(message as any, options);
|
|
153
90
|
}
|
|
154
91
|
|
|
155
|
-
|
|
92
|
+
async handleRequest(
|
|
156
93
|
req: IncomingMessage & { auth?: AuthInfo },
|
|
157
94
|
res: ServerResponse,
|
|
158
95
|
parsedBody?: unknown
|
|
159
96
|
): Promise<void> {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
const acceptsJson = acceptHeader?.includes("application/json");
|
|
163
|
-
|
|
164
|
-
if (!acceptsJson) {
|
|
165
|
-
res.writeHead(406).end(
|
|
166
|
-
JSON.stringify({
|
|
167
|
-
jsonrpc: "2.0",
|
|
168
|
-
error: {
|
|
169
|
-
code: -32000,
|
|
170
|
-
message: "Not Acceptable: Client must accept application/json",
|
|
171
|
-
},
|
|
172
|
-
id: null,
|
|
173
|
-
})
|
|
174
|
-
);
|
|
175
|
-
return;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
let rawMessage;
|
|
179
|
-
if (parsedBody !== undefined) {
|
|
180
|
-
rawMessage = parsedBody;
|
|
181
|
-
} else {
|
|
182
|
-
const ct = req.headers["content-type"];
|
|
183
|
-
if (!ct || !ct.includes("application/json")) {
|
|
184
|
-
res.writeHead(415).end(
|
|
185
|
-
JSON.stringify({
|
|
186
|
-
jsonrpc: "2.0",
|
|
187
|
-
error: {
|
|
188
|
-
code: -32000,
|
|
189
|
-
message:
|
|
190
|
-
"Unsupported Media Type: Content-Type must be application/json",
|
|
191
|
-
},
|
|
192
|
-
id: null,
|
|
193
|
-
})
|
|
194
|
-
);
|
|
195
|
-
return;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
const parsedCt = contentType.parse(ct);
|
|
199
|
-
const body = await getRawBody(req, {
|
|
200
|
-
limit: this.bodySizeLimit,
|
|
201
|
-
encoding: parsedCt.parameters.charset ?? "utf-8",
|
|
202
|
-
});
|
|
203
|
-
rawMessage = JSON.parse(body.toString());
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
const messages: JsonRpcMessage[] = Array.isArray(rawMessage)
|
|
207
|
-
? rawMessage
|
|
208
|
-
: [rawMessage];
|
|
209
|
-
|
|
210
|
-
const hasRequests = messages.some(
|
|
211
|
-
(msg) => msg.method && msg.id !== undefined
|
|
212
|
-
);
|
|
213
|
-
|
|
214
|
-
if (!hasRequests) {
|
|
215
|
-
// Handle notifications (no response expected)
|
|
216
|
-
res.writeHead(202).end();
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// Handle requests that expect responses
|
|
221
|
-
const requestIds = messages
|
|
222
|
-
.filter((msg) => msg.method && msg.id !== undefined)
|
|
223
|
-
.map((msg) => msg.id!);
|
|
224
|
-
|
|
225
|
-
if (requestIds.length === 0) {
|
|
226
|
-
res.writeHead(202).end();
|
|
227
|
-
return;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
const responseCollector: JsonRpcMessage[] = [];
|
|
231
|
-
const expectedResponses = requestIds.length;
|
|
232
|
-
|
|
233
|
-
const collectorId = randomUUID();
|
|
234
|
-
this._singleResponseCollectors =
|
|
235
|
-
this._singleResponseCollectors || new Map();
|
|
236
|
-
this._singleResponseCollectors.set(collectorId, {
|
|
237
|
-
res,
|
|
238
|
-
requestIds: new Set(requestIds),
|
|
239
|
-
responses: responseCollector,
|
|
240
|
-
expectedCount: expectedResponses,
|
|
241
|
-
});
|
|
242
|
-
|
|
243
|
-
for (const requestId of requestIds) {
|
|
244
|
-
this._requestToCollectorMapping =
|
|
245
|
-
this._requestToCollectorMapping || new Map();
|
|
246
|
-
this._requestToCollectorMapping.set(requestId, collectorId);
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
const authInfo: AuthInfo | undefined = req.auth;
|
|
250
|
-
|
|
251
|
-
// MCP SDK transport interface mandatory
|
|
252
|
-
for (const message of messages) {
|
|
253
|
-
if (this.onmessage) {
|
|
254
|
-
this.onmessage(message, { authInfo });
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
} catch (error) {
|
|
258
|
-
res.writeHead(400).end(
|
|
259
|
-
JSON.stringify({
|
|
260
|
-
jsonrpc: "2.0",
|
|
261
|
-
error: {
|
|
262
|
-
code: -32700,
|
|
263
|
-
message: "Parse error",
|
|
264
|
-
data: String(error),
|
|
265
|
-
},
|
|
266
|
-
id: null,
|
|
267
|
-
})
|
|
268
|
-
);
|
|
269
|
-
}
|
|
97
|
+
this.log(`${req.method} ${req.url ?? req.headers.host ?? "/mcp"}`);
|
|
98
|
+
await this.transport.handleRequest(req, res, parsedBody);
|
|
270
99
|
}
|
|
271
100
|
}
|
|
272
101
|
|
|
@@ -281,6 +110,7 @@ export class StatelessStreamableHTTPTransport {
|
|
|
281
110
|
private createServerFn: () => Promise<McpServer>;
|
|
282
111
|
private corsConfig: CorsConfig;
|
|
283
112
|
private providers: Provider[] | undefined;
|
|
113
|
+
private sessions = new Map<string, SessionLifecycle>();
|
|
284
114
|
|
|
285
115
|
constructor(
|
|
286
116
|
createServerFn: () => Promise<McpServer>,
|
|
@@ -345,7 +175,7 @@ export class StatelessStreamableHTTPTransport {
|
|
|
345
175
|
res.status(200).json({
|
|
346
176
|
status: "ok",
|
|
347
177
|
transport: "streamable-http",
|
|
348
|
-
mode: "
|
|
178
|
+
mode: "session",
|
|
349
179
|
});
|
|
350
180
|
});
|
|
351
181
|
|
|
@@ -429,27 +259,57 @@ export class StatelessStreamableHTTPTransport {
|
|
|
429
259
|
res: Response
|
|
430
260
|
): Promise<void> {
|
|
431
261
|
try {
|
|
432
|
-
|
|
433
|
-
const
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
this.options.bodySizeLimit || "10mb"
|
|
437
|
-
);
|
|
262
|
+
const requestClientInfo = extractClientInfoFromMessages(req.body);
|
|
263
|
+
const sessionId = this.getSessionId(req);
|
|
264
|
+
let lifecycle = sessionId ? this.sessions.get(sessionId) : undefined;
|
|
265
|
+
let clientInfo = requestClientInfo;
|
|
438
266
|
|
|
439
|
-
|
|
440
|
-
res.on("close", () => {
|
|
441
|
-
transport.close();
|
|
442
|
-
server.close();
|
|
267
|
+
res.on("finish", () => {
|
|
443
268
|
global.__XMCP_CURRENT_TOOL_NAME = undefined;
|
|
444
269
|
});
|
|
445
|
-
|
|
446
|
-
// clean up
|
|
447
|
-
res.on("finish", () => {
|
|
270
|
+
res.on("close", () => {
|
|
448
271
|
global.__XMCP_CURRENT_TOOL_NAME = undefined;
|
|
449
272
|
});
|
|
450
273
|
|
|
451
|
-
|
|
452
|
-
|
|
274
|
+
if (!lifecycle) {
|
|
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);
|
|
301
|
+
|
|
302
|
+
if (!sessionId && lifecycle.transport.sessionId) {
|
|
303
|
+
this.sessions.set(lifecycle.transport.sessionId, {
|
|
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
|
+
}
|
|
453
313
|
} catch (error) {
|
|
454
314
|
console.error("[HTTP-server] Error handling MCP request:", error);
|
|
455
315
|
if (!res.headersSent) {
|
|
@@ -465,6 +325,37 @@ export class StatelessStreamableHTTPTransport {
|
|
|
465
325
|
}
|
|
466
326
|
}
|
|
467
327
|
|
|
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
|
+
|
|
468
359
|
public async start(): Promise<void> {
|
|
469
360
|
const host = this.options.host || "127.0.0.1";
|
|
470
361
|
const port = await findAvailablePort(this.port, host);
|
|
@@ -485,6 +376,13 @@ export class StatelessStreamableHTTPTransport {
|
|
|
485
376
|
|
|
486
377
|
public shutdown(): void {
|
|
487
378
|
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();
|
|
488
386
|
this.server.close();
|
|
489
387
|
process.exit(0);
|
|
490
388
|
}
|
|
@@ -2,6 +2,11 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
2
2
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
3
|
import { createServer } from "../../utils/server";
|
|
4
4
|
import dotenv from "dotenv";
|
|
5
|
+
import {
|
|
6
|
+
clientInfoContextProvider,
|
|
7
|
+
setClientInfoContext,
|
|
8
|
+
} from "@/runtime/contexts/client-info-context";
|
|
9
|
+
import { mapImplementationToClientInfo } from "@/runtime/utils/client-info";
|
|
5
10
|
dotenv.config();
|
|
6
11
|
|
|
7
12
|
class StdioTransport {
|
|
@@ -17,6 +22,18 @@ class StdioTransport {
|
|
|
17
22
|
|
|
18
23
|
public start(): void {
|
|
19
24
|
try {
|
|
25
|
+
this.mcpServer.server.oninitialized = () => {
|
|
26
|
+
const implementation = this.mcpServer.server.getClientVersion();
|
|
27
|
+
const clientInfo = mapImplementationToClientInfo(implementation);
|
|
28
|
+
setClientInfoContext({ clientInfo });
|
|
29
|
+
|
|
30
|
+
if (this.debug && clientInfo) {
|
|
31
|
+
console.log(
|
|
32
|
+
`[STDIO] MCP client initialized: ${clientInfo.name}@${clientInfo.version}`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
20
37
|
this.mcpServer.connect(this.transport);
|
|
21
38
|
if (this.debug) {
|
|
22
39
|
console.log("[STDIO] MCP Server running with STDIO transport");
|
|
@@ -50,9 +67,7 @@ class StdioTransport {
|
|
|
50
67
|
}
|
|
51
68
|
}
|
|
52
69
|
|
|
53
|
-
// @ts-expect-error: injected by compiler
|
|
54
70
|
const debug = STDIO_CONFIG.debug || false;
|
|
55
|
-
// @ts-expect-error: injected by compiler
|
|
56
71
|
const silent = STDIO_CONFIG.silent || false;
|
|
57
72
|
|
|
58
73
|
if (silent) {
|
|
@@ -60,19 +75,35 @@ if (silent) {
|
|
|
60
75
|
// the MCP stdio protocol on stdout.
|
|
61
76
|
const stderrConsole = new console.Console(process.stderr, process.stderr);
|
|
62
77
|
const methods = [
|
|
63
|
-
"log",
|
|
64
|
-
"
|
|
65
|
-
"
|
|
66
|
-
"
|
|
67
|
-
"
|
|
78
|
+
"log",
|
|
79
|
+
"debug",
|
|
80
|
+
"info",
|
|
81
|
+
"warn",
|
|
82
|
+
"error",
|
|
83
|
+
"dir",
|
|
84
|
+
"table",
|
|
85
|
+
"trace",
|
|
86
|
+
"assert",
|
|
87
|
+
"time",
|
|
88
|
+
"timeEnd",
|
|
89
|
+
"timeLog",
|
|
90
|
+
"count",
|
|
91
|
+
"countReset",
|
|
92
|
+
"group",
|
|
93
|
+
"groupEnd",
|
|
94
|
+
"groupCollapsed",
|
|
68
95
|
"clear",
|
|
69
96
|
] as const;
|
|
70
97
|
for (const method of methods) {
|
|
71
|
-
(console as any)[method] = (stderrConsole as any)[method].bind(
|
|
98
|
+
(console as any)[method] = (stderrConsole as any)[method].bind(
|
|
99
|
+
stderrConsole
|
|
100
|
+
);
|
|
72
101
|
}
|
|
73
102
|
}
|
|
74
103
|
|
|
75
104
|
createServer().then((mcpServer) => {
|
|
76
105
|
const stdioTransport = new StdioTransport(mcpServer, debug);
|
|
77
|
-
|
|
106
|
+
clientInfoContextProvider({ clientInfo: undefined }, () => {
|
|
107
|
+
stdioTransport.start();
|
|
108
|
+
});
|
|
78
109
|
});
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert";
|
|
3
|
+
import {
|
|
4
|
+
extractClientInfoFromMessage,
|
|
5
|
+
extractClientInfoFromMessages,
|
|
6
|
+
mapImplementationToClientInfo,
|
|
7
|
+
} from "../client-info";
|
|
8
|
+
|
|
9
|
+
test("extractClientInfoFromMessage returns undefined for non-initialize methods", () => {
|
|
10
|
+
const result = extractClientInfoFromMessage({
|
|
11
|
+
jsonrpc: "2.0",
|
|
12
|
+
method: "tools/call",
|
|
13
|
+
params: {},
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
assert.strictEqual(result, undefined);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test("extractClientInfoFromMessage extracts required and optional fields", () => {
|
|
20
|
+
const result = extractClientInfoFromMessage({
|
|
21
|
+
jsonrpc: "2.0",
|
|
22
|
+
method: "initialize",
|
|
23
|
+
params: {
|
|
24
|
+
clientInfo: {
|
|
25
|
+
name: "cursor",
|
|
26
|
+
version: "0.50.1",
|
|
27
|
+
title: "Cursor",
|
|
28
|
+
websiteUrl: "https://cursor.com",
|
|
29
|
+
description: "AI code editor",
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
assert.deepStrictEqual(result, {
|
|
35
|
+
name: "cursor",
|
|
36
|
+
version: "0.50.1",
|
|
37
|
+
title: "Cursor",
|
|
38
|
+
websiteUrl: "https://cursor.com",
|
|
39
|
+
description: "AI code editor",
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("extractClientInfoFromMessage returns undefined for invalid clientInfo payload", () => {
|
|
44
|
+
const result = extractClientInfoFromMessage({
|
|
45
|
+
jsonrpc: "2.0",
|
|
46
|
+
method: "initialize",
|
|
47
|
+
params: {
|
|
48
|
+
clientInfo: {
|
|
49
|
+
name: "cursor",
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
assert.strictEqual(result, undefined);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("extractClientInfoFromMessages supports batch requests", () => {
|
|
58
|
+
const result = extractClientInfoFromMessages([
|
|
59
|
+
{
|
|
60
|
+
jsonrpc: "2.0",
|
|
61
|
+
method: "ping",
|
|
62
|
+
id: 1,
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
jsonrpc: "2.0",
|
|
66
|
+
method: "initialize",
|
|
67
|
+
id: 2,
|
|
68
|
+
params: {
|
|
69
|
+
clientInfo: {
|
|
70
|
+
name: "opencode",
|
|
71
|
+
version: "1.2.3",
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
]);
|
|
76
|
+
|
|
77
|
+
assert.deepStrictEqual(result, {
|
|
78
|
+
name: "opencode",
|
|
79
|
+
version: "1.2.3",
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("mapImplementationToClientInfo maps SDK implementation shape", () => {
|
|
84
|
+
const result = mapImplementationToClientInfo({
|
|
85
|
+
name: "claude-code",
|
|
86
|
+
version: "2.1.0",
|
|
87
|
+
title: "Claude Code",
|
|
88
|
+
websiteUrl: "https://claude.ai",
|
|
89
|
+
description: "CLI coding agent",
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
assert.deepStrictEqual(result, {
|
|
93
|
+
name: "claude-code",
|
|
94
|
+
version: "2.1.0",
|
|
95
|
+
title: "Claude Code",
|
|
96
|
+
websiteUrl: "https://claude.ai",
|
|
97
|
+
description: "CLI coding agent",
|
|
98
|
+
});
|
|
99
|
+
});
|