This commit is contained in:
bipproduction
2025-10-27 02:57:45 +08:00
parent 174a98fb18
commit 385d6493cb

View File

@@ -1,23 +1,15 @@
import { Elysia } from "elysia";
export const MCPRoute = new Elysia()
.get("/mcp/:sessionId", async ({ params, set }) => {
// Atur header SSE
set.headers = {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"Access-Control-Allow-Origin": "*",
};
.get("/mcp/:sessionId", ({ params }) => {
const encoder = new TextEncoder();
let interval: NodeJS.Timeout;
let interval: Timer | null = null;
const stream = new ReadableStream({
start(controller) {
// kirim handshake awal
const initial = {
// kirim event awal (flush langsung)
const init = {
jsonrpc: "2.0",
id: null,
result: {
@@ -30,24 +22,30 @@ export const MCPRoute = new Elysia()
},
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(initial)}\n\n`));
controller.enqueue(
encoder.encode(`data: ${JSON.stringify(init)}\n\n`)
);
// jaga stream tetap hidup
// SSE heartbeat
interval = setInterval(() => {
controller.enqueue(encoder.encode(`: ping ${Date.now()}\n\n`));
}, 10000);
// kirim ready event
controller.enqueue(encoder.encode(`event: ready\ndata: "stream ready"\n\n`));
},
cancel() {
clearInterval(interval);
console.log(`SSE connection ${params.sessionId} closed by client`);
if (interval) clearInterval(interval);
console.log(`[SSE] koneksi session ${params.sessionId} ditutup`);
},
});
return stream;
// gunakan Response manual agar Bun flush data pertama
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"Access-Control-Allow-Origin": "*",
},
});
})
.post("/mcp", async ({ body, set }) => {