xmcp 0.6.6 → 0.6.7
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 +30 -32
- package/dist/compiler/config/index.d.ts +54 -54
- package/dist/compiler/config/schemas/transport/http.d.ts +82 -82
- package/dist/index.d.ts +4 -2
- package/dist/index.js +3 -3
- package/dist/runtime/adapter-express.js +39 -22
- package/dist/runtime/adapter-nestjs.js +39 -22
- package/dist/runtime/adapter-nextjs.js +38 -21
- package/dist/runtime/contexts/http-request-context.d.ts +3 -1
- package/dist/runtime/headers.js +1 -1
- package/dist/runtime/http.js +47 -30
- package/dist/runtime/stdio.js +17 -11
- package/dist/runtime/utils/elicitation.d.ts +4 -0
- package/dist/runtime/utils/ext-apps-registry.d.ts +132 -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 +35 -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/utils/context.d.ts +1 -1
- package/package.json +9 -1
- package/src/client/index.ts +4 -1
- package/src/compiler/generate-tools-code.ts +4 -6
- package/src/compiler/get-bundler-config/plugins/index.ts +0 -1
- package/src/compiler/index.ts +24 -7
- package/src/index.ts +8 -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 +8 -5
- package/src/runtime/adapters/nextjs/index.ts +41 -25
- 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 +0 -2
- package/src/runtime/utils/__tests__/client-info.test.ts +80 -0
- package/src/runtime/utils/__tests__/tool-extra.test.ts +110 -0
- package/src/runtime/utils/client-info.ts +71 -0
- package/src/runtime/utils/elicitation.ts +396 -0
- package/src/runtime/utils/prompt-loader.ts +151 -0
- package/src/runtime/utils/resource-loader.ts +151 -0
- package/src/runtime/utils/resources.ts +0 -8
- package/src/runtime/utils/server.ts +28 -38
- package/src/runtime/utils/tool-loader.ts +149 -0
- package/src/runtime/utils/tools.ts +9 -6
- package/src/runtime/utils/transformers/tool.ts +26 -5
- 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/utils/context.ts +2 -2
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createServer } from "@/runtime/utils/server";
|
|
2
2
|
import { WebStatelessHttpTransport } from "@/runtime/transports/http/web-stateless-http";
|
|
3
3
|
import { httpRequestContextProvider } from "@/runtime/contexts/http-request-context";
|
|
4
|
+
import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
|
|
4
5
|
import homeTemplate from "../../templates/home";
|
|
5
6
|
|
|
6
7
|
import { addCorsHeaders, handleCorsPreflightRequest } from "./cors";
|
|
@@ -8,23 +9,20 @@ import type { Env, ExecutionContext } from "./types";
|
|
|
8
9
|
import type { WebMiddleware, WebMiddlewareContext } from "@/types/middleware";
|
|
9
10
|
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
|
|
10
11
|
|
|
11
|
-
// @ts-expect-error: injected by compiler
|
|
12
12
|
const httpConfig = HTTP_CONFIG as {
|
|
13
13
|
port: number;
|
|
14
14
|
host: string;
|
|
15
|
-
bodySizeLimit:
|
|
15
|
+
bodySizeLimit: number;
|
|
16
16
|
endpoint: string;
|
|
17
17
|
debug: boolean;
|
|
18
18
|
};
|
|
19
19
|
|
|
20
|
-
// @ts-expect-error: injected by compiler
|
|
21
20
|
const templateConfig = TEMPLATE_CONFIG as {
|
|
22
21
|
name?: string;
|
|
23
22
|
description?: string;
|
|
24
23
|
homePage?: string;
|
|
25
24
|
};
|
|
26
25
|
|
|
27
|
-
// @ts-expect-error: injected by compiler
|
|
28
26
|
const middleware = INJECTED_MIDDLEWARE as
|
|
29
27
|
| (() => Promise<{ default?: WebMiddleware | WebMiddleware[] }>)
|
|
30
28
|
| undefined;
|
|
@@ -51,9 +49,7 @@ async function resolveWebMiddleware(): Promise<WebMiddleware[]> {
|
|
|
51
49
|
return resolvedMiddlewarePromise;
|
|
52
50
|
}
|
|
53
51
|
|
|
54
|
-
function normalizeWebMiddleware(
|
|
55
|
-
defaultExport: unknown
|
|
56
|
-
): WebMiddleware[] {
|
|
52
|
+
function normalizeWebMiddleware(defaultExport: unknown): WebMiddleware[] {
|
|
57
53
|
if (Array.isArray(defaultExport)) {
|
|
58
54
|
return defaultExport.filter(isWebMiddleware);
|
|
59
55
|
}
|
|
@@ -68,9 +64,7 @@ function normalizeWebMiddleware(
|
|
|
68
64
|
"middleware" in defaultExport &&
|
|
69
65
|
typeof (defaultExport as { middleware?: unknown }).middleware === "function"
|
|
70
66
|
) {
|
|
71
|
-
return [
|
|
72
|
-
(defaultExport as { middleware: WebMiddleware }).middleware,
|
|
73
|
-
];
|
|
67
|
+
return [(defaultExport as { middleware: WebMiddleware }).middleware];
|
|
74
68
|
}
|
|
75
69
|
|
|
76
70
|
return [];
|
|
@@ -125,6 +119,11 @@ async function handleMcpRequest(
|
|
|
125
119
|
authInfo?: AuthInfo
|
|
126
120
|
): Promise<Response> {
|
|
127
121
|
const requestId = crypto.randomUUID();
|
|
122
|
+
const requestPayload = await request
|
|
123
|
+
.clone()
|
|
124
|
+
.json()
|
|
125
|
+
.catch(() => undefined);
|
|
126
|
+
const clientInfo = extractClientInfoFromMessages(requestPayload);
|
|
128
127
|
|
|
129
128
|
// Use the http request context provider to maintain request isolation
|
|
130
129
|
return new Promise<Response>((resolve) => {
|
|
@@ -134,43 +133,46 @@ async function handleMcpRequest(
|
|
|
134
133
|
headers[key] = value;
|
|
135
134
|
});
|
|
136
135
|
|
|
137
|
-
httpRequestContextProvider(
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
} finally {
|
|
167
|
-
if (server && transport) {
|
|
168
|
-
ctx.waitUntil(
|
|
169
|
-
Promise.allSettled([transport.close(), server.close()])
|
|
136
|
+
httpRequestContextProvider(
|
|
137
|
+
{ id: requestId, headers, clientInfo },
|
|
138
|
+
async () => {
|
|
139
|
+
let server: Awaited<ReturnType<typeof createServer>> | null = null;
|
|
140
|
+
let transport: WebStatelessHttpTransport | null = null;
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
server = await createServer();
|
|
144
|
+
transport = new WebStatelessHttpTransport(httpConfig.debug);
|
|
145
|
+
|
|
146
|
+
await server.connect(transport);
|
|
147
|
+
const response = await transport.handleRequest(request, authInfo);
|
|
148
|
+
|
|
149
|
+
resolve(addCorsHeaders(response, requestOrigin));
|
|
150
|
+
} catch (error) {
|
|
151
|
+
console.error("[Cloudflare-MCP] Error handling MCP request:", error);
|
|
152
|
+
const errorResponse = new Response(
|
|
153
|
+
JSON.stringify({
|
|
154
|
+
jsonrpc: "2.0",
|
|
155
|
+
error: {
|
|
156
|
+
code: -32603,
|
|
157
|
+
message: "Internal server error",
|
|
158
|
+
},
|
|
159
|
+
id: null,
|
|
160
|
+
}),
|
|
161
|
+
{
|
|
162
|
+
status: 500,
|
|
163
|
+
headers: { "Content-Type": "application/json" },
|
|
164
|
+
}
|
|
170
165
|
);
|
|
166
|
+
resolve(addCorsHeaders(errorResponse, requestOrigin));
|
|
167
|
+
} finally {
|
|
168
|
+
if (server && transport) {
|
|
169
|
+
ctx.waitUntil(
|
|
170
|
+
Promise.allSettled([transport.close(), server.close()])
|
|
171
|
+
);
|
|
172
|
+
}
|
|
171
173
|
}
|
|
172
174
|
}
|
|
173
|
-
|
|
175
|
+
);
|
|
174
176
|
});
|
|
175
177
|
}
|
|
176
178
|
|
|
@@ -14,15 +14,11 @@ dotenv.config();
|
|
|
14
14
|
// by the time this is run, the config is already parsed and injected as object
|
|
15
15
|
// the injection handles the boolean case
|
|
16
16
|
|
|
17
|
-
// @ts-expect-error: injected by compiler
|
|
18
17
|
const httpConfig = HTTP_CONFIG as ResolvedHttpConfig;
|
|
19
|
-
// @ts-expect-error: injected by compiler
|
|
20
18
|
const corsConfig = HTTP_CORS_CONFIG as CorsConfig;
|
|
21
|
-
// @ts-expect-error: injected by compiler
|
|
22
19
|
const templateConfig = TEMPLATE_CONFIG as TemplateConfig;
|
|
23
20
|
|
|
24
21
|
// middleware
|
|
25
|
-
// @ts-expect-error: injected by compiler
|
|
26
22
|
const middleware = INJECTED_MIDDLEWARE as () =>
|
|
27
23
|
| Promise<{
|
|
28
24
|
default: Middleware | Middleware[];
|
|
@@ -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
|
}
|