* Handle an incoming HTTP request * @param {http.IncomingMessage} req - HTTP request * @param {http.ServerResponse} res - HTTP response * @param {Object} [parsedBody] - Pre-parsed request body
(req, res, parsedBody)
| 155 | * @param {Object} [parsedBody] - Pre-parsed request body |
| 156 | */ |
| 157 | async handleRequest(req, res, parsedBody) { |
| 158 | // Set CORS headers |
| 159 | res.setHeader("Access-Control-Allow-Origin", "*"); |
| 160 | res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); |
| 161 | res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Mcp-Session-Id"); |
| 162 | |
| 163 | // Handle OPTIONS preflight |
| 164 | if (req.method === "OPTIONS") { |
| 165 | res.writeHead(200); |
| 166 | res.end(); |
| 167 | return; |
| 168 | } |
| 169 | |
| 170 | // Only handle POST requests for MCP protocol |
| 171 | if (req.method !== "POST") { |
| 172 | res.writeHead(405, { "Content-Type": "application/json" }); |
| 173 | res.end(JSON.stringify({ error: "Method not allowed" })); |
| 174 | return; |
| 175 | } |
| 176 | |
| 177 | try { |
| 178 | // Parse request body if not already parsed |
| 179 | let body = parsedBody; |
| 180 | if (!body) { |
| 181 | const chunks = []; |
| 182 | for await (const chunk of req) { |
| 183 | chunks.push(chunk); |
| 184 | } |
| 185 | const bodyStr = Buffer.concat(chunks).toString(); |
| 186 | try { |
| 187 | body = bodyStr ? JSON.parse(bodyStr) : null; |
| 188 | } catch (parseError) { |
| 189 | res.writeHead(400, { "Content-Type": "application/json" }); |
| 190 | res.end( |
| 191 | JSON.stringify({ |
| 192 | jsonrpc: "2.0", |
| 193 | error: { |
| 194 | code: -32700, |
| 195 | message: "Parse error: Invalid JSON in request body", |
| 196 | }, |
| 197 | id: null, |
| 198 | }) |
| 199 | ); |
| 200 | return; |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | if (!body) { |
| 205 | res.writeHead(400, { "Content-Type": "application/json" }); |
| 206 | res.end( |
| 207 | JSON.stringify({ |
| 208 | jsonrpc: "2.0", |
| 209 | error: { |
| 210 | code: -32600, |
| 211 | message: "Invalid Request: Empty request body", |
| 212 | }, |
| 213 | id: null, |
| 214 | }) |
nothing calls this directly
no test coverage detected