-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathmcp-api-handler.ts
More file actions
697 lines (634 loc) · 20 KB
/
mcp-api-handler.ts
File metadata and controls
697 lines (634 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import {
type IncomingHttpHeaders,
IncomingMessage,
type ServerResponse,
} from "node:http";
import { createClient } from "redis";
import { Socket } from "node:net";
import { Readable } from "node:stream";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import type { BodyType } from "./server-response-adapter";
import assert from "node:assert";
import type {
McpEvent,
McpErrorEvent,
McpSessionEvent,
McpRequestEvent,
} from "../lib/log-helper";
import { createEvent } from "../lib/log-helper";
import { EventEmittingResponse } from "../lib/event-emitter.js";
import { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
import { getAuthContext } from "../auth/auth-context";
import { ServerOptions } from ".";
import { Logger, LogLevel, createDefaultLogger } from "../types/logger";
interface SerializedRequest {
requestId: string;
url: string;
method: string;
body: BodyType;
headers: IncomingHttpHeaders;
}
/**
* Configuration for the MCP handler.
* @property redisUrl - The URL of the Redis instance to use for the MCP handler.
* @property streamableHttpEndpoint - The endpoint to use for the streamable HTTP transport.
* @property sseEndpoint - The endpoint to use for the SSE transport.
* @property verboseLogs - If true, enables console logging.
* @property logger - Custom logger implementation. If provided, takes precedence over verboseLogs.
*/
export type Config = {
/**
* The URL of the Redis instance to use for the MCP handler.
* @default process.env.REDIS_URL || process.env.KV_URL
*/
redisUrl?: string;
/**
* The endpoint to use for the streamable HTTP transport.
* @deprecated Use `set basePath` instead.
* @default "/mcp"
*/
streamableHttpEndpoint?: string;
/**
* The endpoint to use for the SSE transport.
* @deprecated Use `set basePath` instead.
* @default "/sse"
*/
sseEndpoint?: string;
/**
* The endpoint to use for the SSE messages transport.
* @deprecated Use `set basePath` instead.
* @default "/message"
*/
sseMessageEndpoint?: string;
/**
* The maximum duration of an MCP request in seconds.
* @default 60
*/
maxDuration?: number;
/**
* If true, enables console logging.
* @default false
*/
verboseLogs?: boolean;
/**
* The base path to use for deriving endpoints.
* If provided, endpoints will be derived from this path.
* For example, if basePath is "/", that means your routing is:
* /app/[transport]/route.ts and then:
* - streamableHttpEndpoint will be "/mcp"
* - sseEndpoint will be "/sse"
* - sseMessageEndpoint will be "/message"
* @default ""
*/
basePath?: string;
/**
* Callback function that receives MCP events.
* This can be used to track analytics, debug issues, or implement custom behaviors.
*/
onEvent?: (event: McpEvent) => void;
/**
* If true, disables the SSE endpoint.
* As of 2025-03-26, SSE is not supported by the MCP spec.
* https://modelcontextprotocol.io/specification/2025-03-26/basic/transports
* @default false
*/
disableSse?: boolean;
/**
* Custom logger implementation.
* If provided, this logger will be used instead of the default console logger.
* Takes precedence over the verboseLogs option.
*/
logger?: Logger;
};
/**
* Derives MCP endpoints from a base path.
* @param basePath - The base path to derive endpoints from
* @returns An object containing the derived endpoints
*/
function deriveEndpointsFromBasePath(basePath: string): {
streamableHttpEndpoint: string;
sseEndpoint: string;
sseMessageEndpoint: string;
} {
// Remove trailing slash if present
const normalizedBasePath = basePath.replace(/\/$/, "");
return {
streamableHttpEndpoint: `${normalizedBasePath}/mcp`,
sseEndpoint: `${normalizedBasePath}/sse`,
sseMessageEndpoint: `${normalizedBasePath}/message`,
};
}
/**
* Calculates the endpoints for the MCP handler.
* @param config - The configuration for the MCP handler.
* @returns An object containing the endpoints for the MCP handler.
*/
export function calculateEndpoints({
basePath,
streamableHttpEndpoint = "/mcp",
sseEndpoint = "/sse",
sseMessageEndpoint = "/message",
}: Config) {
const {
streamableHttpEndpoint: fullStreamableHttpEndpoint,
sseEndpoint: fullSseEndpoint,
sseMessageEndpoint: fullSseMessageEndpoint,
} = basePath != null
? deriveEndpointsFromBasePath(basePath)
: {
streamableHttpEndpoint,
sseEndpoint,
sseMessageEndpoint,
};
return {
streamableHttpEndpoint: fullStreamableHttpEndpoint,
sseEndpoint: fullSseEndpoint,
sseMessageEndpoint: fullSseMessageEndpoint,
};
}
let redisPublisher: ReturnType<typeof createClient>;
let redis: ReturnType<typeof createClient>;
async function initializeRedis({
redisUrl,
logger,
}: {
redisUrl?: string;
logger: Logger;
}) {
if (redis && redisPublisher) {
return { redis, redisPublisher };
}
if (!redisUrl) {
throw new Error("redisUrl is required");
}
redis = createClient({
url: redisUrl,
});
redisPublisher = createClient({
url: redisUrl,
});
redis.on("error", (err) => {
logger.error("Redis error", err);
});
redisPublisher.on("error", (err) => {
logger.error("Redis error", err);
});
await Promise.all([redis.connect(), redisPublisher.connect()]);
return { redis, redisPublisher };
}
export function initializeMcpApiHandler(
initializeServer:
| ((server: McpServer) => Promise<void>)
| ((server: McpServer) => void),
serverOptions: ServerOptions = {},
config: Config = {
redisUrl: process.env.REDIS_URL || process.env.KV_URL,
streamableHttpEndpoint: "/mcp",
sseEndpoint: "/sse",
sseMessageEndpoint: "/message",
basePath: "",
maxDuration: 60,
verboseLogs: false,
disableSse: false,
}
) {
const {
redisUrl,
basePath,
streamableHttpEndpoint: explicitStreamableHttpEndpoint,
sseEndpoint: explicitSseEndpoint,
sseMessageEndpoint: explicitSseMessageEndpoint,
maxDuration,
verboseLogs,
disableSse,
} = config;
const {
serverInfo = {
name: "mcp-typescript server on vercel",
version: "0.1.0",
},
...mcpServerOptions
} = serverOptions;
// If basePath is provided, derive endpoints from it
const { streamableHttpEndpoint, sseEndpoint, sseMessageEndpoint } =
calculateEndpoints({
basePath,
streamableHttpEndpoint: explicitStreamableHttpEndpoint,
sseEndpoint: explicitSseEndpoint,
sseMessageEndpoint: explicitSseMessageEndpoint,
});
const logger = config.logger || createDefaultLogger({ verboseLogs });
let servers: McpServer[] = [];
let statelessServer: McpServer;
const statelessTransport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
});
return async function mcpApiHandler(req: Request, res: ServerResponse) {
const url = new URL(req.url || "", "https://example.com");
if (url.pathname === streamableHttpEndpoint) {
if (req.method === "GET") {
logger.log("Received GET MCP request");
res.writeHead(405).end(
JSON.stringify({
jsonrpc: "2.0",
error: {
code: -32000,
message: "Method not allowed.",
},
id: null,
})
);
return;
}
if (req.method === "DELETE") {
logger.log("Received DELETE MCP request");
res.writeHead(405).end(
JSON.stringify({
jsonrpc: "2.0",
error: {
code: -32000,
message: "Method not allowed.",
},
id: null,
})
);
return;
}
if (req.method === "POST") {
const eventRes = new EventEmittingResponse(
createFakeIncomingMessage(),
config.onEvent
);
if (!statelessServer) {
statelessServer = new McpServer(serverInfo, mcpServerOptions);
await initializeServer(statelessServer);
await statelessServer.connect(statelessTransport);
}
// Parse the request body
let bodyContent: BodyType;
const contentType = req.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
bodyContent = await req.json();
} else {
bodyContent = await req.text();
}
const incomingRequest = createFakeIncomingMessage({
method: req.method,
url: req.url,
headers: Object.fromEntries(req.headers),
body: bodyContent,
auth: req.auth, // Use the auth info that should already be set by withMcpAuth
});
// Create a response that will emit events
const wrappedRes = new EventEmittingResponse(
incomingRequest,
config.onEvent
);
Object.assign(wrappedRes, res);
try {
await statelessTransport.handleRequest(incomingRequest, wrappedRes);
if (
typeof bodyContent === "object" &&
bodyContent &&
"method" in bodyContent
) {
eventRes.requestCompleted(
bodyContent.method as string,
bodyContent
);
}
} catch (error) {
if (
typeof bodyContent === "object" &&
bodyContent &&
"method" in bodyContent
) {
eventRes.requestCompleted(
bodyContent.method as string,
undefined,
error instanceof Error ? error : String(error)
);
}
throw error;
}
}
} else if (url.pathname === sseEndpoint) {
if (disableSse) {
res.statusCode = 404;
res.end("Not found");
return;
}
// Check HTTP method - only allow GET for SSE connections
if (req.method !== "GET") {
logger.log(`Rejected SSE connection with method ${req.method}`);
res
.writeHead(405, { "Content-Type": "text/plain" })
.end("Method Not Allowed");
return;
}
// Check that Accept header supports event-stream
const acceptHeader =
req.headers.get("accept") || req.headers.get("Accept");
if (
acceptHeader &&
!acceptHeader.includes("text/event-stream") &&
!acceptHeader.includes("*/*") &&
!acceptHeader.includes("text/*")
) {
logger.log(
`Rejected SSE connection with incompatible Accept header: ${acceptHeader}`
);
res
.writeHead(406, { "Content-Type": "text/plain" })
.end("Not Acceptable");
return;
}
const { redis, redisPublisher } = await initializeRedis({
redisUrl,
logger,
});
logger.log("Got new SSE connection");
assert(sseMessageEndpoint, "sseMessageEndpoint is required");
const transport = new SSEServerTransport(sseMessageEndpoint, res);
const sessionId = transport.sessionId;
const eventRes = new EventEmittingResponse(
createFakeIncomingMessage(),
config.onEvent,
sessionId
);
eventRes.startSession("SSE", {
userAgent: req.headers.get("user-agent") ?? undefined,
ip:
req.headers.get("x-forwarded-for") ??
req.headers.get("x-real-ip") ??
undefined,
});
const server = new McpServer(serverInfo, serverOptions);
await initializeServer(server);
servers.push(server);
server.server.onclose = () => {
logger.log("SSE connection closed");
eventRes.endSession("SSE");
servers = servers.filter((s) => s !== server);
};
let logs: {
type: LogLevel;
messages: string[];
}[] = [];
// eslint-disable-next-line no-inner-declarations
function logInContext(severity: LogLevel, ...messages: string[]) {
logs.push({
type: severity,
messages,
});
}
// Handles messages originally received via /message
const handleMessage = async (message: string) => {
logger.log("Received message from Redis", message);
logInContext("log", "Received message from Redis", message);
const request = JSON.parse(message) as SerializedRequest;
// Make in IncomingMessage object because that is what the SDK expects.
const req = createFakeIncomingMessage({
method: request.method,
url: request.url,
headers: request.headers,
body: request.body,
});
const syntheticRes = new EventEmittingResponse(
req,
config.onEvent,
sessionId
);
let status = 100;
let body = "";
syntheticRes.writeHead = (statusCode: number) => {
status = statusCode;
return syntheticRes;
};
syntheticRes.end = (b: unknown) => {
body = b as string;
return syntheticRes;
};
try {
await transport.handlePostMessage(req, syntheticRes);
// If it was a function call, complete it
if (
typeof request.body === "object" &&
request.body &&
"method" in request.body
) {
try {
const result = JSON.parse(body);
eventRes.requestCompleted(request.body.method as string, result);
} catch {
eventRes.requestCompleted(request.body.method as string, body);
}
}
} catch (error) {
eventRes.error(
error instanceof Error ? error : String(error),
"Error handling SSE message",
"session"
);
throw error;
}
await redisPublisher.publish(
`responses:${sessionId}:${request.requestId}`,
JSON.stringify({
status,
body,
})
);
if (status >= 200 && status < 300) {
logInContext(
"log",
`Request ${sessionId}:${request.requestId} succeeded: ${body}`
);
} else {
logInContext(
"error",
`Message for ${sessionId}:${request.requestId} failed with status ${status}: ${body}`
);
eventRes.error(
`Request failed with status ${status}`,
body,
"session"
);
}
};
const interval = setInterval(() => {
for (const log of logs) {
logger[log.type](...log.messages);
}
logs = [];
}, 100);
await redis.subscribe(`requests:${sessionId}`, handleMessage);
logger.log(`Subscribed to requests:${sessionId}`);
let timeout: NodeJS.Timeout;
let resolveTimeout: (value: unknown) => void;
const waitPromise = new Promise((resolve) => {
resolveTimeout = resolve;
timeout = setTimeout(() => {
resolve("max duration reached");
}, (maxDuration ?? 60) * 1000);
});
// eslint-disable-next-line no-inner-declarations
async function cleanup() {
clearTimeout(timeout);
clearInterval(interval);
await redis.unsubscribe(`requests:${sessionId}`, handleMessage);
logger.log("Done");
res.statusCode = 200;
res.end();
}
req.signal.addEventListener("abort", () =>
resolveTimeout("client hang up")
);
await server.connect(transport);
const closeReason = await waitPromise;
logger.log(closeReason);
await cleanup();
} else if (url.pathname === sseMessageEndpoint) {
if (disableSse) {
res.statusCode = 404;
res.end("Not found");
return;
}
const { redis, redisPublisher } = await initializeRedis({
redisUrl,
logger,
});
logger.log("Received message");
const body = await req.text();
let parsedBody: BodyType;
try {
parsedBody = JSON.parse(body);
} catch (e) {
parsedBody = body;
}
const sessionId = url.searchParams.get("sessionId") || "";
if (!sessionId) {
res.statusCode = 400;
res.end("No sessionId provided");
return;
}
const requestId = crypto.randomUUID();
const serializedRequest: SerializedRequest = {
requestId,
url: req.url || "",
method: req.method || "",
body: parsedBody,
headers: Object.fromEntries(req.headers.entries()),
};
// Declare timeout and response handling state before subscription
let timeout: NodeJS.Timeout;
let hasResponded = false;
// Safe response handler to prevent double res.end()
const sendResponse = (status: number, body: string) => {
if (!hasResponded) {
hasResponded = true;
clearTimeout(timeout);
res.statusCode = status;
res.end(body);
}
};
// Handles responses from the /sse endpoint.
await redis.subscribe(
`responses:${sessionId}:${requestId}`,
(message) => {
try {
const response = JSON.parse(message) as {
status: number;
body: string;
};
sendResponse(response.status, response.body);
} catch (error) {
logger.error("Failed to parse response message:", error);
sendResponse(500, "Internal server error");
}
}
);
// Queue the request in Redis so that a subscriber can pick it up.
// One queue per session.
await redisPublisher.publish(
`requests:${sessionId}`,
JSON.stringify(serializedRequest)
);
logger.log(`Published requests:${sessionId}`, serializedRequest);
// Set timeout after subscription is established
timeout = setTimeout(async () => {
await redis.unsubscribe(`responses:${sessionId}:${requestId}`);
sendResponse(408, "Request timed out");
}, 10 * 1000);
res.on("close", async () => {
hasResponded = true;
clearTimeout(timeout);
await redis.unsubscribe(`responses:${sessionId}:${requestId}`);
});
} else {
res.statusCode = 404;
res.end("Not found");
}
};
}
// Define the options interface
interface FakeIncomingMessageOptions {
method?: string;
url?: string;
headers?: IncomingHttpHeaders;
body?: BodyType;
socket?: Socket;
auth?: AuthInfo;
}
// Create a fake IncomingMessage
function createFakeIncomingMessage(
options: FakeIncomingMessageOptions = {}
): IncomingMessage & { auth?: AuthInfo } {
const {
method = "GET",
url = "/",
headers = {},
body = null,
socket = new Socket(),
} = options;
// Create a readable stream that will be used as the base for IncomingMessage
const readable = new Readable();
readable._read = (): void => {}; // Required implementation
// Add the body content if provided
if (body) {
if (typeof body === "string") {
readable.push(body);
} else if (Buffer.isBuffer(body)) {
readable.push(body);
} else {
// Ensure proper JSON-RPC format
const bodyString = JSON.stringify(body);
readable.push(bodyString);
}
readable.push(null); // Signal the end of the stream
} else {
readable.push(null); // Always end the stream even if no body
}
// Create the IncomingMessage instance
const req = new IncomingMessage(socket) as IncomingMessage & {
auth?: AuthInfo;
};
// Set the properties
req.method = method;
req.url = url;
req.headers = headers;
const auth = options.auth || getAuthContext();
if (auth) {
// See https://github.com/modelcontextprotocol/typescript-sdk/blob/590d4841373fc4eb86ecc9079834353a98cb84a3/src/server/auth/middleware/bearerAuth.ts#L71 for more info.
(req as { auth?: AuthInfo }).auth = auth;
}
// Copy over the stream methods
req.push = readable.push.bind(readable);
req.read = readable.read.bind(readable);
// @ts-expect-error
req.on = readable.on.bind(readable);
req.pipe = readable.pipe.bind(readable);
return req;
}