forked from hustcc/mcp-mermaid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsse.ts
More file actions
51 lines (44 loc) · 1.61 KB
/
Copy pathsse.ts
File metadata and controls
51 lines (44 loc) · 1.61 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
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import type { Request, Response } from "express";
import express from "express";
export const startSSEMcpServer = async (
server: McpServer,
endpoint = "/sse",
port = 3033,
host?: string,
): Promise<void> => {
const app = express();
app.use(express.json());
const transports: Record<string, SSEServerTransport> = {};
app.get(endpoint, async (req: Request, res: Response) => {
try {
const transport = new SSEServerTransport("/messages", res);
transports[transport.sessionId] = transport;
transport.onclose = () => delete transports[transport.sessionId];
await server.connect(transport);
} catch (error) {
if (!res.headersSent)
res.status(500).send("Error establishing SSE stream");
}
});
app.post("/messages", async (req: Request, res: Response) => {
const sessionId = req.query.sessionId as string;
if (!sessionId) return res.status(400).send("Missing sessionId parameter");
const transport = transports[sessionId];
if (!transport) return res.status(404).send("Session not found");
try {
await transport.handlePostMessage(req, res, req.body);
} catch (error) {
if (!res.headersSent) res.status(500).send("Error handling request");
}
});
const cb = () => {
const shownHost = host || "localhost";
console.log(
`SSE Server listening on http://${shownHost}:${port}${endpoint}`,
);
};
if (host) app.listen(port, host, cb);
else app.listen(port, cb);
};