xmcp 0.6.5 → 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 +58 -40
- package/dist/compiler/config/index.d.ts +106 -47
- package/dist/compiler/config/schemas/template.d.ts +40 -0
- package/dist/compiler/config/schemas/transport/http.d.ts +82 -82
- package/dist/compiler/config/schemas/transport/stdio.d.ts +5 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +5 -5
- package/dist/runtime/adapter-express.js +40 -23
- package/dist/runtime/adapter-nestjs.js +40 -23
- package/dist/runtime/adapter-nextjs.js +39 -22
- package/dist/runtime/contexts/http-request-context.d.ts +3 -1
- package/dist/runtime/headers.js +1 -1
- package/dist/runtime/http.js +48 -31
- package/dist/runtime/stdio.js +19 -13
- 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 +70 -14
- package/dist/utils/context.d.ts +1 -1
- package/package.json +9 -1
- package/src/client/index.ts +4 -1
- package/src/compiler/config/__tests__/config.test.ts +36 -0
- package/src/compiler/config/injection.ts +63 -1
- package/src/compiler/config/schemas/template.ts +17 -0
- package/src/compiler/config/schemas/transport/stdio.ts +1 -0
- package/src/compiler/generate-tools-code.ts +24 -6
- package/src/compiler/get-bundler-config/get-injected-variables.ts +3 -0
- package/src/compiler/get-bundler-config/plugins/index.ts +0 -1
- package/src/compiler/index.ts +123 -30
- package/src/compiler/start-http-server.ts +11 -4
- package/src/compiler/watcher-recovery.ts +72 -0
- package/src/index.ts +9 -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 +18 -1
- 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 +30 -42
- package/src/runtime/utils/tool-loader.ts +149 -0
- package/src/runtime/utils/tools.ts +31 -9
- package/src/runtime/utils/transformers/tool.ts +149 -10
- package/src/types/client-info.ts +12 -0
- package/src/types/injected.d.ts +62 -0
- package/src/types/tool.ts +100 -17
- package/src/utils/context.ts +2 -2
|
@@ -4,74 +4,72 @@ import { StatelessHttpServerTransport } from "@/runtime/transports/http/stateles
|
|
|
4
4
|
import { setHeaders } from "@/runtime/transports/http/cors";
|
|
5
5
|
import { httpRequestContextProvider } from "@/runtime/contexts/http-request-context";
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
|
|
7
8
|
|
|
8
9
|
// cors config
|
|
9
|
-
// @ts-expect-error: injected by compiler
|
|
10
10
|
const corsOrigin = HTTP_CORS_ORIGIN as string;
|
|
11
|
-
// @ts-expect-error: injected by compiler
|
|
12
11
|
const corsMethods = HTTP_CORS_METHODS as string;
|
|
13
|
-
// @ts-expect-error: injected by compiler
|
|
14
12
|
const corsAllowedHeaders = HTTP_CORS_ALLOWED_HEADERS as string;
|
|
15
|
-
// @ts-expect-error: injected by compiler
|
|
16
13
|
const corsExposedHeaders = HTTP_CORS_EXPOSED_HEADERS as string;
|
|
17
|
-
// @ts-expect-error: injected by compiler
|
|
18
14
|
const corsCredentials = HTTP_CORS_CREDENTIALS as boolean;
|
|
19
|
-
// @ts-expect-error: injected by compiler
|
|
20
15
|
const corsMaxAge = HTTP_CORS_MAX_AGE as number;
|
|
21
16
|
|
|
22
|
-
// @ts-expect-error: injected by compiler
|
|
23
17
|
const debug = HTTP_DEBUG as boolean;
|
|
24
|
-
// @ts-expect-error: injected by compiler
|
|
25
18
|
const bodySizeLimit = HTTP_BODY_SIZE_LIMIT as string;
|
|
26
19
|
|
|
27
20
|
export async function xmcpHandler(req: Request, res: Response) {
|
|
28
21
|
return new Promise((resolve) => {
|
|
29
22
|
const id = randomUUID();
|
|
30
|
-
|
|
31
|
-
try {
|
|
32
|
-
setHeaders(
|
|
33
|
-
res,
|
|
34
|
-
{
|
|
35
|
-
origin: corsOrigin,
|
|
36
|
-
methods: corsMethods,
|
|
37
|
-
allowedHeaders: corsAllowedHeaders,
|
|
38
|
-
exposedHeaders: corsExposedHeaders,
|
|
39
|
-
credentials: corsCredentials,
|
|
40
|
-
maxAge: corsMaxAge,
|
|
41
|
-
},
|
|
42
|
-
req.headers.origin
|
|
43
|
-
);
|
|
23
|
+
const clientInfo = extractClientInfoFromMessages(req.body);
|
|
44
24
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
25
|
+
httpRequestContextProvider(
|
|
26
|
+
{ id, headers: req.headers, clientInfo },
|
|
27
|
+
async () => {
|
|
28
|
+
try {
|
|
29
|
+
setHeaders(
|
|
30
|
+
res,
|
|
31
|
+
{
|
|
32
|
+
origin: corsOrigin,
|
|
33
|
+
methods: corsMethods,
|
|
34
|
+
allowedHeaders: corsAllowedHeaders,
|
|
35
|
+
exposedHeaders: corsExposedHeaders,
|
|
36
|
+
credentials: corsCredentials,
|
|
37
|
+
maxAge: corsMaxAge,
|
|
38
|
+
},
|
|
39
|
+
req.headers.origin
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
const server = await createServer();
|
|
43
|
+
const transport = new StatelessHttpServerTransport(
|
|
44
|
+
debug,
|
|
45
|
+
bodySizeLimit || "10mb"
|
|
46
|
+
);
|
|
50
47
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
48
|
+
// cleanup when request/connection closes
|
|
49
|
+
res.on("close", () => {
|
|
50
|
+
transport.close();
|
|
51
|
+
server.close();
|
|
52
|
+
});
|
|
56
53
|
|
|
57
|
-
|
|
54
|
+
await server.connect(transport);
|
|
58
55
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
});
|
|
62
|
-
} catch (error) {
|
|
63
|
-
console.error("[HTTP-server] Error handling MCP request:", error);
|
|
64
|
-
if (!res.headersSent) {
|
|
65
|
-
res.status(500).json({
|
|
66
|
-
jsonrpc: "2.0",
|
|
67
|
-
error: {
|
|
68
|
-
code: -32603,
|
|
69
|
-
message: "Internal server error",
|
|
70
|
-
},
|
|
71
|
-
id: null,
|
|
56
|
+
await transport.handleRequest(req, res, req.body).then(() => {
|
|
57
|
+
resolve(res);
|
|
72
58
|
});
|
|
59
|
+
} catch (error) {
|
|
60
|
+
console.error("[HTTP-server] Error handling MCP request:", error);
|
|
61
|
+
if (!res.headersSent) {
|
|
62
|
+
res.status(500).json({
|
|
63
|
+
jsonrpc: "2.0",
|
|
64
|
+
error: {
|
|
65
|
+
code: -32603,
|
|
66
|
+
message: "Internal server error",
|
|
67
|
+
},
|
|
68
|
+
id: null,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
73
71
|
}
|
|
74
72
|
}
|
|
75
|
-
|
|
73
|
+
);
|
|
76
74
|
});
|
|
77
75
|
}
|
|
@@ -11,11 +11,10 @@ import { setHeaders } from "@/runtime/transports/http/cors";
|
|
|
11
11
|
import { httpRequestContextProvider } from "@/runtime/contexts/http-request-context";
|
|
12
12
|
import { randomUUID } from "node:crypto";
|
|
13
13
|
import type { CorsConfig } from "@/compiler/config";
|
|
14
|
+
import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
|
|
14
15
|
|
|
15
|
-
// @ts-expect-error: injected by compiler
|
|
16
16
|
const corsConfig = HTTP_CORS_CONFIG as CorsConfig;
|
|
17
17
|
|
|
18
|
-
// @ts-expect-error: injected by compiler
|
|
19
18
|
const httpConfig = HTTP_CONFIG as {
|
|
20
19
|
port: number;
|
|
21
20
|
host: string;
|
|
@@ -43,8 +42,10 @@ export class XmcpService implements OnModuleInit, OnModuleDestroy {
|
|
|
43
42
|
this.logger.debug(`Request ${requestId} started`);
|
|
44
43
|
|
|
45
44
|
return new Promise((resolve) => {
|
|
45
|
+
const clientInfo = extractClientInfoFromMessages(req.body);
|
|
46
|
+
|
|
46
47
|
httpRequestContextProvider(
|
|
47
|
-
{ id: requestId, headers: req.headers },
|
|
48
|
+
{ id: requestId, headers: req.headers, clientInfo },
|
|
48
49
|
async () => {
|
|
49
50
|
try {
|
|
50
51
|
setHeaders(res, corsConfig, req.headers.origin);
|
|
@@ -18,9 +18,19 @@ export function nodeToWebAdapter(
|
|
|
18
18
|
const emitter = new EventEmitter();
|
|
19
19
|
let statusCode = 200;
|
|
20
20
|
let headers: OutgoingHttpHeaders | undefined;
|
|
21
|
-
|
|
21
|
+
const bodyChunks: Uint8Array[] = [];
|
|
22
22
|
let headersWritten = false;
|
|
23
23
|
let resolved = false;
|
|
24
|
+
let destroyed = false;
|
|
25
|
+
|
|
26
|
+
const appendBodyChunk = (chunk: Buffer | Uint8Array | string) => {
|
|
27
|
+
if (typeof chunk === "string") {
|
|
28
|
+
bodyChunks.push(Buffer.from(chunk));
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
33
|
+
};
|
|
24
34
|
|
|
25
35
|
// Setup abort signal handling
|
|
26
36
|
signal.addEventListener("abort", () => {
|
|
@@ -44,20 +54,20 @@ export function nodeToWebAdapter(
|
|
|
44
54
|
return mockResponse;
|
|
45
55
|
},
|
|
46
56
|
|
|
47
|
-
write(chunk: Buffer | string): boolean {
|
|
57
|
+
write(chunk: Buffer | Uint8Array | string): boolean {
|
|
48
58
|
if (!resolved) {
|
|
49
|
-
|
|
59
|
+
appendBodyChunk(chunk);
|
|
50
60
|
}
|
|
51
61
|
return true;
|
|
52
62
|
},
|
|
53
63
|
|
|
54
|
-
end(data?: Buffer | string) {
|
|
64
|
+
end(data?: Buffer | Uint8Array | string) {
|
|
55
65
|
if (resolved) {
|
|
56
66
|
return mockResponse;
|
|
57
67
|
}
|
|
58
68
|
|
|
59
69
|
if (data) {
|
|
60
|
-
|
|
70
|
+
appendBodyChunk(data);
|
|
61
71
|
}
|
|
62
72
|
|
|
63
73
|
// Ensure headers were written (default to 200 if not)
|
|
@@ -70,7 +80,7 @@ export function nodeToWebAdapter(
|
|
|
70
80
|
|
|
71
81
|
// Create Web Response
|
|
72
82
|
resolve(
|
|
73
|
-
new Response(
|
|
83
|
+
new Response(Buffer.concat(bodyChunks), {
|
|
74
84
|
status: statusCode,
|
|
75
85
|
headers: headers as Record<string, string>,
|
|
76
86
|
})
|
|
@@ -85,6 +95,22 @@ export function nodeToWebAdapter(
|
|
|
85
95
|
return mockResponse;
|
|
86
96
|
},
|
|
87
97
|
|
|
98
|
+
off(event: string, listener: (...args: unknown[]) => void) {
|
|
99
|
+
emitter.off(event, listener);
|
|
100
|
+
return mockResponse;
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
removeListener(event: string, listener: (...args: unknown[]) => void) {
|
|
104
|
+
emitter.removeListener(event, listener);
|
|
105
|
+
return mockResponse;
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
destroy(_error?: Error) {
|
|
109
|
+
destroyed = true;
|
|
110
|
+
emitter.emit("close");
|
|
111
|
+
return mockResponse;
|
|
112
|
+
},
|
|
113
|
+
|
|
88
114
|
get statusCode(): number {
|
|
89
115
|
return statusCode;
|
|
90
116
|
},
|
|
@@ -96,6 +122,14 @@ export function nodeToWebAdapter(
|
|
|
96
122
|
get headersSent(): boolean {
|
|
97
123
|
return headersWritten;
|
|
98
124
|
},
|
|
125
|
+
|
|
126
|
+
get destroyed(): boolean {
|
|
127
|
+
return destroyed;
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
get writable(): boolean {
|
|
131
|
+
return !destroyed;
|
|
132
|
+
},
|
|
99
133
|
} as ServerResponse;
|
|
100
134
|
|
|
101
135
|
// Execute handler
|
|
@@ -10,6 +10,25 @@ export interface RequestConversionOptions {
|
|
|
10
10
|
auth?: AuthInfo;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
function toRawHeaders(headers: IncomingHttpHeaders): string[] {
|
|
14
|
+
const rawHeaders: string[] = [];
|
|
15
|
+
|
|
16
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
17
|
+
if (value === undefined) continue;
|
|
18
|
+
|
|
19
|
+
if (Array.isArray(value)) {
|
|
20
|
+
for (const item of value) {
|
|
21
|
+
rawHeaders.push(key, item);
|
|
22
|
+
}
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
rawHeaders.push(key, value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return rawHeaders;
|
|
30
|
+
}
|
|
31
|
+
|
|
13
32
|
/**
|
|
14
33
|
* Creates a Node.js IncomingMessage from Web Request options.
|
|
15
34
|
* This adapter enables the MCP SDK to work with Web Request objects.
|
|
@@ -37,6 +56,7 @@ export function createIncomingMessage(
|
|
|
37
56
|
req.method = method;
|
|
38
57
|
req.url = url;
|
|
39
58
|
req.headers = headers;
|
|
59
|
+
req.rawHeaders = toRawHeaders(headers);
|
|
40
60
|
|
|
41
61
|
// Set auth if available (can be set by middleware)
|
|
42
62
|
if (auth) {
|
|
@@ -37,11 +37,14 @@ export function setupCleanupHandlers(
|
|
|
37
37
|
* Initializes and configures the MCP server with tools, prompts, and resources
|
|
38
38
|
*/
|
|
39
39
|
export async function initializeMcpServer(): Promise<McpServer> {
|
|
40
|
-
const
|
|
41
|
-
const
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
40
|
+
const toolModulesPromise = loadTools();
|
|
41
|
+
const promptModulesPromise = loadPrompts();
|
|
42
|
+
const resourceModulesPromise = loadResources();
|
|
43
|
+
const [toolModules, promptModules, resourceModules] = await Promise.all([
|
|
44
|
+
toolModulesPromise,
|
|
45
|
+
promptModulesPromise,
|
|
46
|
+
resourceModulesPromise,
|
|
47
|
+
]);
|
|
45
48
|
|
|
46
49
|
const server = new McpServer(INJECTED_CONFIG);
|
|
47
50
|
|
|
@@ -10,6 +10,12 @@ import {
|
|
|
10
10
|
} from "./handler/server-lifecycle";
|
|
11
11
|
import { createIncomingMessage } from "./handler/request-converter";
|
|
12
12
|
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
|
|
13
|
+
import { httpRequestContextProvider } from "@/runtime/contexts/http-request-context";
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import {
|
|
16
|
+
setHttpRequestContext,
|
|
17
|
+
} from "@/runtime/contexts/http-request-context";
|
|
18
|
+
import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
|
|
13
19
|
|
|
14
20
|
const BODY_SIZE_LIMIT = "10mb";
|
|
15
21
|
|
|
@@ -23,36 +29,46 @@ export async function xmcpHandler(request: Request): Promise<Response> {
|
|
|
23
29
|
return createMethodNotAllowedResponse();
|
|
24
30
|
}
|
|
25
31
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
32
|
+
const id = randomUUID();
|
|
33
|
+
const requestHeaders = Object.fromEntries(request.headers.entries());
|
|
34
|
+
|
|
35
|
+
return httpRequestContextProvider(
|
|
36
|
+
{ id, headers: requestHeaders, clientInfo: undefined },
|
|
37
|
+
() => {
|
|
38
|
+
return nodeToWebAdapter(request.signal, async (res: ServerResponse) => {
|
|
39
|
+
try {
|
|
40
|
+
// Initialize server and transport
|
|
41
|
+
const lifecycle = await createServerLifecycle(BODY_SIZE_LIMIT);
|
|
30
42
|
|
|
31
|
-
|
|
32
|
-
|
|
43
|
+
// Setup cleanup handlers
|
|
44
|
+
setupCleanupHandlers(res, lifecycle);
|
|
33
45
|
|
|
34
|
-
|
|
35
|
-
|
|
46
|
+
// Parse request body
|
|
47
|
+
const bodyContent = await request.json();
|
|
48
|
+
const clientInfo = extractClientInfoFromMessages(bodyContent);
|
|
49
|
+
setHttpRequestContext({ clientInfo });
|
|
36
50
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
51
|
+
// Convert Web Request to Node.js IncomingMessage
|
|
52
|
+
const incomingRequest = createIncomingMessage({
|
|
53
|
+
method: request.method,
|
|
54
|
+
url: request.url,
|
|
55
|
+
headers: requestHeaders,
|
|
56
|
+
auth: request.auth,
|
|
57
|
+
});
|
|
44
58
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
59
|
+
// Handle request through transport
|
|
60
|
+
await lifecycle.transport.handleRequest(
|
|
61
|
+
incomingRequest,
|
|
62
|
+
res,
|
|
63
|
+
bodyContent
|
|
64
|
+
);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
console.error("[Next.js MCP] Error handling MCP request:", error);
|
|
67
|
+
sendInternalServerError(res);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
54
70
|
}
|
|
55
|
-
|
|
71
|
+
);
|
|
56
72
|
}
|
|
57
73
|
|
|
58
74
|
// Re-export auth types and handlers
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createContext } from "../../utils/context";
|
|
2
|
+
import type { McpClientInfo } from "@/types/client-info";
|
|
2
3
|
|
|
3
4
|
// Headers type compatible with both Node.js IncomingHttpHeaders and Web API headers
|
|
4
5
|
export type HttpHeaders = Record<string, string | string[] | undefined>;
|
|
@@ -6,6 +7,7 @@ export type HttpHeaders = Record<string, string | string[] | undefined>;
|
|
|
6
7
|
export interface HttpRequestContext {
|
|
7
8
|
id: string;
|
|
8
9
|
headers: HttpHeaders;
|
|
10
|
+
clientInfo?: McpClientInfo;
|
|
9
11
|
}
|
|
10
12
|
|
|
11
13
|
export const httpRequestContext = createContext<HttpRequestContext>({
|
package/src/runtime/headers.ts
CHANGED
|
@@ -1,7 +1,42 @@
|
|
|
1
1
|
import { getHttpRequestContext } from "./contexts/http-request-context";
|
|
2
2
|
|
|
3
3
|
export const headers = () => {
|
|
4
|
-
const
|
|
4
|
+
const currentHeaders = getHttpRequestContext().headers;
|
|
5
|
+
const headerLookup = new Map<string, string>();
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
for (const key of Object.keys(currentHeaders)) {
|
|
8
|
+
const normalizedKey = key.toLowerCase();
|
|
9
|
+
|
|
10
|
+
if (!headerLookup.has(normalizedKey)) {
|
|
11
|
+
headerLookup.set(normalizedKey, key);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const resolveHeaderKey = (prop: string): string => {
|
|
16
|
+
return headerLookup.get(prop.toLowerCase()) ?? prop;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
return new Proxy(currentHeaders, {
|
|
20
|
+
get(target, prop, receiver) {
|
|
21
|
+
if (typeof prop !== "string") {
|
|
22
|
+
return Reflect.get(target, prop, receiver);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return Reflect.get(target, resolveHeaderKey(prop), receiver);
|
|
26
|
+
},
|
|
27
|
+
has(target, prop) {
|
|
28
|
+
if (typeof prop !== "string") {
|
|
29
|
+
return Reflect.has(target, prop);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return Reflect.has(target, resolveHeaderKey(prop));
|
|
33
|
+
},
|
|
34
|
+
getOwnPropertyDescriptor(target, prop) {
|
|
35
|
+
if (typeof prop !== "string") {
|
|
36
|
+
return Reflect.getOwnPropertyDescriptor(target, prop);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return Reflect.getOwnPropertyDescriptor(target, resolveHeaderKey(prop));
|
|
40
|
+
},
|
|
41
|
+
});
|
|
7
42
|
};
|
|
@@ -6,7 +6,6 @@ import type { CorsConfig } from "@/compiler/config";
|
|
|
6
6
|
import { buildCorsHeaders } from "@/runtime/transports/http/cors/headers";
|
|
7
7
|
|
|
8
8
|
// CORS config - injected by compiler as combined object
|
|
9
|
-
// @ts-expect-error: injected by compiler
|
|
10
9
|
const corsConfig = HTTP_CORS_CONFIG as CorsConfig;
|
|
11
10
|
|
|
12
11
|
/**
|
|
@@ -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[];
|