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
|
@@ -33,7 +33,7 @@ export function generateToolsExportCode(): string {
|
|
|
33
33
|
|
|
34
34
|
${importStatements}
|
|
35
35
|
|
|
36
|
-
/**
|
|
36
|
+
/**
|
|
37
37
|
* Runtime-accessible tools function that works from any context.
|
|
38
38
|
* Generated at build time - always up to date with discovered tools.
|
|
39
39
|
* @returns {Promise<ToolRegistry>}
|
|
@@ -65,7 +65,7 @@ export async function getTools() {
|
|
|
65
65
|
if (!("parse" in val) || typeof val.parse !== "function") return false;
|
|
66
66
|
return true;
|
|
67
67
|
});
|
|
68
|
-
|
|
68
|
+
|
|
69
69
|
if (isValidSchema) {
|
|
70
70
|
toolSchema = schema;
|
|
71
71
|
} else {
|
|
@@ -89,10 +89,8 @@ export async function getTools() {
|
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
// Make sure tools has annotations with a title
|
|
93
|
-
|
|
94
|
-
toolConfig.annotations = {};
|
|
95
|
-
}
|
|
92
|
+
// Make sure tools has annotations with a title — shallow copy to avoid mutating shared objects
|
|
93
|
+
toolConfig.annotations = { ...(toolConfig.annotations ?? {}) };
|
|
96
94
|
if (toolConfig.annotations.title === undefined) {
|
|
97
95
|
toolConfig.annotations.title = toolConfig.name;
|
|
98
96
|
}
|
package/src/compiler/index.ts
CHANGED
|
@@ -130,13 +130,18 @@ export async function compile({ onBuild }: CompileOptions = {}) {
|
|
|
130
130
|
onAdd: async (filePath) => {
|
|
131
131
|
addWatchedPath(promptPaths, filePath);
|
|
132
132
|
if (compilerStarted) {
|
|
133
|
-
await generateCode();
|
|
133
|
+
await generateCode({ rebuildClientBundles: false });
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
onChange: async () => {
|
|
137
|
+
if (compilerStarted) {
|
|
138
|
+
await generateCode({ rebuildClientBundles: false });
|
|
134
139
|
}
|
|
135
140
|
},
|
|
136
141
|
onUnlink: async (filePath) => {
|
|
137
142
|
removeWatchedPath(promptPaths, filePath);
|
|
138
143
|
if (compilerStarted) {
|
|
139
|
-
await generateCode();
|
|
144
|
+
await generateCode({ rebuildClientBundles: false });
|
|
140
145
|
}
|
|
141
146
|
},
|
|
142
147
|
});
|
|
@@ -154,13 +159,18 @@ export async function compile({ onBuild }: CompileOptions = {}) {
|
|
|
154
159
|
onAdd: async (filePath) => {
|
|
155
160
|
addWatchedPath(resourcePaths, filePath);
|
|
156
161
|
if (compilerStarted) {
|
|
157
|
-
await generateCode();
|
|
162
|
+
await generateCode({ rebuildClientBundles: false });
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
onChange: async () => {
|
|
166
|
+
if (compilerStarted) {
|
|
167
|
+
await generateCode({ rebuildClientBundles: false });
|
|
158
168
|
}
|
|
159
169
|
},
|
|
160
170
|
onUnlink: async (filePath) => {
|
|
161
171
|
removeWatchedPath(resourcePaths, filePath);
|
|
162
172
|
if (compilerStarted) {
|
|
163
|
-
await generateCode();
|
|
173
|
+
await generateCode({ rebuildClientBundles: false });
|
|
164
174
|
}
|
|
165
175
|
},
|
|
166
176
|
});
|
|
@@ -430,9 +440,16 @@ async function buildClientBundles(): Promise<Map<string, string> | undefined> {
|
|
|
430
440
|
* Generates all runtime code and builds client bundles if needed
|
|
431
441
|
* This centralizes all code generation logic including client bundle building
|
|
432
442
|
*/
|
|
433
|
-
async function generateCode(
|
|
434
|
-
|
|
435
|
-
|
|
443
|
+
async function generateCode({
|
|
444
|
+
rebuildClientBundles = true,
|
|
445
|
+
}: {
|
|
446
|
+
rebuildClientBundles?: boolean;
|
|
447
|
+
} = {}) {
|
|
448
|
+
const { clientBundles: currentClientBundles } = compilerContext.getContext();
|
|
449
|
+
const clientBundles =
|
|
450
|
+
rebuildClientBundles || currentClientBundles === undefined
|
|
451
|
+
? await buildClientBundles()
|
|
452
|
+
: currentClientBundles;
|
|
436
453
|
|
|
437
454
|
// Store in context for import map generation
|
|
438
455
|
compilerContext.setContext({ clientBundles });
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import dotenv from "dotenv";
|
|
2
|
-
export type {
|
|
2
|
+
export type {
|
|
3
|
+
Middleware,
|
|
4
|
+
WebMiddleware,
|
|
5
|
+
WebMiddlewareContext,
|
|
6
|
+
} from "./types/middleware";
|
|
3
7
|
dotenv.config();
|
|
4
8
|
|
|
5
9
|
export type {
|
|
@@ -8,7 +12,9 @@ export type {
|
|
|
8
12
|
ToolOutputSchema,
|
|
9
13
|
ToolExtraArguments,
|
|
10
14
|
InferSchema,
|
|
15
|
+
ElicitResult,
|
|
11
16
|
} from "./types/tool";
|
|
17
|
+
export type { McpClientInfo } from "./types/client-info";
|
|
12
18
|
export type { PromptMetadata } from "./types/prompt";
|
|
13
19
|
export type { ResourceMetadata } from "./types/resource";
|
|
14
20
|
export type { UIMetadata } from "./types/ui-meta";
|
|
@@ -21,6 +27,7 @@ export { jwtAuthMiddleware } from "./auth/jwt";
|
|
|
21
27
|
export { createContext } from "./utils/context";
|
|
22
28
|
|
|
23
29
|
export { completable } from "@modelcontextprotocol/sdk/server/completable";
|
|
30
|
+
export { UrlElicitationRequiredError } from "@modelcontextprotocol/sdk/types";
|
|
24
31
|
|
|
25
32
|
export {
|
|
26
33
|
createHTTPClient,
|
|
@@ -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
|
/**
|