| 1 | // website/api/v1/mcp/sse.ts |
| 2 | export default async function handler(req: any, res: any) { |
| 3 | res.setHeader("Access-Control-Allow-Origin", "*"); |
| 4 | res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS"); |
| 5 | res.setHeader("Access-Control-Allow-Headers", "Content-Type"); |
| 6 | |
| 7 | if (req.method === "OPTIONS") { |
| 8 | return res.status(200).end(); |
| 9 | } |
| 10 | |
| 11 | if (req.method !== "GET") { |
| 12 | res.setHeader("Allow", "GET"); |
| 13 | return res.status(405).json({ error: `Method ${req.method} not allowed` }); |
| 14 | } |
| 15 | |
| 16 | res.setHeader("Content-Type", "text/event-stream"); |
| 17 | res.setHeader("Cache-Control", "no-cache, no-transform"); |
| 18 | res.setHeader("Connection", "keep-alive"); |
| 19 | |
| 20 | const sessionId = Math.random().toString(36).substring(2, 15); |
| 21 | const host = req.headers.host || "codegraphcontext.vercel.app"; |
| 22 | const protocol = req.headers["x-forwarded-proto"] || "https"; |
| 23 | const messagesUrl = `${protocol}://${host}/api/v1/mcp/messages?sessionId=${sessionId}`; |
| 24 | |
| 25 | res.write(`event: endpoint\ndata: ${messagesUrl}\n\n`); |
| 26 | |
| 27 | const keepAlive = setInterval(() => { |
| 28 | res.write(": keepalive\n\n"); |
| 29 | }, 10000); |
| 30 | |
| 31 | req.on("close", () => { |
| 32 | clearInterval(keepAlive); |
| 33 | res.end(); |
| 34 | }); |
| 35 | } |