|
| 1 | +/** |
| 2 | + * Shared utilities for running MCP servers with Streamable HTTP transport. |
| 3 | + */ |
| 4 | + |
| 5 | +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; |
| 6 | +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; |
| 7 | +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; |
| 8 | +import cors from "cors"; |
| 9 | +import type { Request, Response } from "express"; |
| 10 | + |
| 11 | +export interface ServerOptions { |
| 12 | + port: number; |
| 13 | + name?: string; |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * Starts an MCP server with Streamable HTTP transport in stateless mode. |
| 18 | + * |
| 19 | + * @param createServer - Factory function that creates a new McpServer instance per request. |
| 20 | + * @param options - Server configuration options. |
| 21 | + */ |
| 22 | +export async function startServer( |
| 23 | + createServer: () => McpServer, |
| 24 | + options: ServerOptions, |
| 25 | +): Promise<void> { |
| 26 | + const { port, name = "MCP Server" } = options; |
| 27 | + |
| 28 | + const app = createMcpExpressApp({ host: "0.0.0.0" }); |
| 29 | + app.use(cors()); |
| 30 | + |
| 31 | + app.all("/mcp", async (req: Request, res: Response) => { |
| 32 | + const server = createServer(); |
| 33 | + const transport = new StreamableHTTPServerTransport({ |
| 34 | + sessionIdGenerator: undefined, |
| 35 | + }); |
| 36 | + |
| 37 | + res.on("close", () => { |
| 38 | + transport.close().catch(() => {}); |
| 39 | + server.close().catch(() => {}); |
| 40 | + }); |
| 41 | + |
| 42 | + try { |
| 43 | + await server.connect(transport); |
| 44 | + await transport.handleRequest(req, res, req.body); |
| 45 | + } catch (error) { |
| 46 | + console.error("MCP error:", error); |
| 47 | + if (!res.headersSent) { |
| 48 | + res.status(500).json({ |
| 49 | + jsonrpc: "2.0", |
| 50 | + error: { code: -32603, message: "Internal server error" }, |
| 51 | + id: null, |
| 52 | + }); |
| 53 | + } |
| 54 | + } |
| 55 | + }); |
| 56 | + |
| 57 | + const httpServer = app.listen(port, () => { |
| 58 | + console.log(`${name} listening on http://localhost:${port}/mcp`); |
| 59 | + }); |
| 60 | + |
| 61 | + const shutdown = () => { |
| 62 | + console.log("\nShutting down..."); |
| 63 | + httpServer.close(() => process.exit(0)); |
| 64 | + }; |
| 65 | + |
| 66 | + process.on("SIGINT", shutdown); |
| 67 | + process.on("SIGTERM", shutdown); |
| 68 | +} |
0 commit comments