( sessionManager: SessionManager, req: IncomingMessage, res: ServerResponse, body: unknown, query: Record<string, unknown>, )
| 22 | * - Session ID not in Redis: 404 → client reinitializes. |
| 23 | */ |
| 24 | export async function handleMcpPost( |
| 25 | sessionManager: SessionManager, |
| 26 | req: IncomingMessage, |
| 27 | res: ServerResponse, |
| 28 | body: unknown, |
| 29 | query: Record<string, unknown>, |
| 30 | ): Promise<void> { |
| 31 | const sessionId = req.headers['mcp-session-id'] as string | undefined; |
| 32 | const message = body as JSONRPCMessage; |
| 33 | |
| 34 | logger.info( |
| 35 | { |
| 36 | sessionId: sessionId ?? 'new', |
| 37 | method: 'method' in message ? message.method : 'unknown', |
| 38 | hasAuth: !!(query['token'] || req.headers.authorization), |
| 39 | }, |
| 40 | 'MCP POST request', |
| 41 | ); |
| 42 | |
| 43 | if (sessionId) { |
| 44 | const context = await sessionManager.getContext(sessionId); |
| 45 | if (!context) { |
| 46 | logger.warn({ sessionId }, 'MCP session not found in Redis'); |
| 47 | res.writeHead(404, { 'Content-Type': 'application/json' }); |
| 48 | res.end(JSON.stringify({ error: 'Session not found — please reconnect' })); |
| 49 | return; |
| 50 | } |
| 51 | |
| 52 | await sessionManager.touchContext(sessionId); |
| 53 | |
| 54 | // Notifications have no `id` and expect no response |
| 55 | if (!('id' in message)) { |
| 56 | res.writeHead(202); |
| 57 | res.end(); |
| 58 | return; |
| 59 | } |
| 60 | |
| 61 | try { |
| 62 | const response = await processRequest(context, message); |
| 63 | res.writeHead(200, { |
| 64 | 'Content-Type': 'application/json', |
| 65 | 'Mcp-Session-Id': sessionId, |
| 66 | }); |
| 67 | res.end(JSON.stringify(response)); |
| 68 | } catch (err) { |
| 69 | logger.error({ err, sessionId }, 'MCP request processing error'); |
| 70 | res.writeHead(500, { 'Content-Type': 'application/json' }); |
| 71 | res.end(JSON.stringify({ error: 'Internal server error' })); |
| 72 | } |
| 73 | return; |
| 74 | } |
| 75 | |
| 76 | // New connection — authenticate and expect `initialize` |
| 77 | const token = extractToken(query, req.headers.authorization); |
| 78 | |
| 79 | try { |
| 80 | const context = await authenticateToken(token); |
| 81 |
no test coverage detected