|
| 1 | +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; |
| 2 | +import { InMemoryEventStore } from '@modelcontextprotocol/sdk/examples/shared/inMemoryEventStore.js'; |
| 3 | +import express, { Request, Response } from "express"; |
| 4 | +import { createServer } from "./everything.js"; |
| 5 | +import { randomUUID } from 'node:crypto'; |
| 6 | + |
| 7 | +console.error('Starting Streamable HTTP server...'); |
| 8 | + |
| 9 | +const app = express(); |
| 10 | + |
| 11 | +const { server, cleanup } = createServer(); |
| 12 | + |
| 13 | +const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}; |
| 14 | + |
| 15 | +app.post('/mcp', async (req: Request, res: Response) => { |
| 16 | + console.log('Received MCP POST request'); |
| 17 | + try { |
| 18 | + // Check for existing session ID |
| 19 | + const sessionId = req.headers['mcp-session-id'] as string | undefined; |
| 20 | + let transport: StreamableHTTPServerTransport; |
| 21 | + |
| 22 | + if (sessionId && transports[sessionId]) { |
| 23 | + // Reuse existing transport |
| 24 | + transport = transports[sessionId]; |
| 25 | + } else if (!sessionId) { |
| 26 | + // New initialization request |
| 27 | + const eventStore = new InMemoryEventStore(); |
| 28 | + transport = new StreamableHTTPServerTransport({ |
| 29 | + sessionIdGenerator: () => randomUUID(), |
| 30 | + eventStore, // Enable resumability |
| 31 | + onsessioninitialized: (sessionId) => { |
| 32 | + // Store the transport by session ID when session is initialized |
| 33 | + // This avoids race conditions where requests might come in before the session is stored |
| 34 | + console.log(`Session initialized with ID: ${sessionId}`); |
| 35 | + transports[sessionId] = transport; |
| 36 | + } |
| 37 | + }); |
| 38 | + |
| 39 | + // Set up onclose handler to clean up transport when closed |
| 40 | + transport.onclose = () => { |
| 41 | + const sid = transport.sessionId; |
| 42 | + if (sid && transports[sid]) { |
| 43 | + console.log(`Transport closed for session ${sid}, removing from transports map`); |
| 44 | + delete transports[sid]; |
| 45 | + } |
| 46 | + }; |
| 47 | + |
| 48 | + // Connect the transport to the MCP server BEFORE handling the request |
| 49 | + // so responses can flow back through the same transport |
| 50 | + await server.connect(transport); |
| 51 | + |
| 52 | + await transport.handleRequest(req, res); |
| 53 | + return; // Already handled |
| 54 | + } else { |
| 55 | + // Invalid request - no session ID or not initialization request |
| 56 | + res.status(400).json({ |
| 57 | + jsonrpc: '2.0', |
| 58 | + error: { |
| 59 | + code: -32000, |
| 60 | + message: 'Bad Request: No valid session ID provided', |
| 61 | + }, |
| 62 | + id: req?.body?.id, |
| 63 | + }); |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + // Handle the request with existing transport - no need to reconnect |
| 68 | + // The existing transport is already connected to the server |
| 69 | + await transport.handleRequest(req, res); |
| 70 | + } catch (error) { |
| 71 | + console.error('Error handling MCP request:', error); |
| 72 | + if (!res.headersSent) { |
| 73 | + res.status(500).json({ |
| 74 | + jsonrpc: '2.0', |
| 75 | + error: { |
| 76 | + code: -32603, |
| 77 | + message: 'Internal server error', |
| 78 | + }, |
| 79 | + id: req?.body?.id, |
| 80 | + }); |
| 81 | + return; |
| 82 | + } |
| 83 | + } |
| 84 | +}); |
| 85 | + |
| 86 | +// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) |
| 87 | +app.get('/mcp', async (req: Request, res: Response) => { |
| 88 | + console.log('Received MCP GET request'); |
| 89 | + const sessionId = req.headers['mcp-session-id'] as string | undefined; |
| 90 | + if (!sessionId || !transports[sessionId]) { |
| 91 | + res.status(400).json({ |
| 92 | + jsonrpc: '2.0', |
| 93 | + error: { |
| 94 | + code: -32000, |
| 95 | + message: 'Bad Request: No valid session ID provided', |
| 96 | + }, |
| 97 | + id: req?.body?.id, |
| 98 | + }); |
| 99 | + return; |
| 100 | + } |
| 101 | + |
| 102 | + // Check for Last-Event-ID header for resumability |
| 103 | + const lastEventId = req.headers['last-event-id'] as string | undefined; |
| 104 | + if (lastEventId) { |
| 105 | + console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); |
| 106 | + } else { |
| 107 | + console.log(`Establishing new SSE stream for session ${sessionId}`); |
| 108 | + } |
| 109 | + |
| 110 | + const transport = transports[sessionId]; |
| 111 | + await transport.handleRequest(req, res); |
| 112 | +}); |
| 113 | + |
| 114 | +// Handle DELETE requests for session termination (according to MCP spec) |
| 115 | +app.delete('/mcp', async (req: Request, res: Response) => { |
| 116 | + const sessionId = req.headers['mcp-session-id'] as string | undefined; |
| 117 | + if (!sessionId || !transports[sessionId]) { |
| 118 | + res.status(400).json({ |
| 119 | + jsonrpc: '2.0', |
| 120 | + error: { |
| 121 | + code: -32000, |
| 122 | + message: 'Bad Request: No valid session ID provided', |
| 123 | + }, |
| 124 | + id: req?.body?.id, |
| 125 | + }); |
| 126 | + return; |
| 127 | + } |
| 128 | + |
| 129 | + console.log(`Received session termination request for session ${sessionId}`); |
| 130 | + |
| 131 | + try { |
| 132 | + const transport = transports[sessionId]; |
| 133 | + await transport.handleRequest(req, res); |
| 134 | + } catch (error) { |
| 135 | + console.error('Error handling session termination:', error); |
| 136 | + if (!res.headersSent) { |
| 137 | + res.status(500).json({ |
| 138 | + jsonrpc: '2.0', |
| 139 | + error: { |
| 140 | + code: -32603, |
| 141 | + message: 'Error handling session termination', |
| 142 | + }, |
| 143 | + id: req?.body?.id, |
| 144 | + }); |
| 145 | + return; |
| 146 | + } |
| 147 | + } |
| 148 | +}); |
| 149 | + |
| 150 | +// Start the server |
| 151 | +const PORT = process.env.PORT || 3001; |
| 152 | +app.listen(PORT, () => { |
| 153 | + console.log(`MCP Streamable HTTP Server listening on port ${PORT}`); |
| 154 | +}); |
| 155 | + |
| 156 | +// Handle server shutdown |
| 157 | +process.on('SIGINT', async () => { |
| 158 | + console.log('Shutting down server...'); |
| 159 | + |
| 160 | + // Close all active transports to properly clean up resources |
| 161 | + for (const sessionId in transports) { |
| 162 | + try { |
| 163 | + console.log(`Closing transport for session ${sessionId}`); |
| 164 | + await transports[sessionId].close(); |
| 165 | + delete transports[sessionId]; |
| 166 | + } catch (error) { |
| 167 | + console.error(`Error closing transport for session ${sessionId}:`, error); |
| 168 | + } |
| 169 | + } |
| 170 | + await cleanup(); |
| 171 | + await server.close(); |
| 172 | + console.log('Server shutdown complete'); |
| 173 | + process.exit(0); |
| 174 | +}); |
0 commit comments