This commit is contained in:
bipproduction
2025-10-26 21:12:05 +08:00
parent 8838cc3152
commit 8b30810b38

View File

@@ -1,62 +1,71 @@
import { Elysia } from "elysia";
import { t } from "elysia";
import { Elysia, t } from "elysia";
export const MCPRoute = new Elysia({ prefix: "/mcp-server", tags: ["mcp-server"] })
.all("/mcp", async ({ body, set }) => {
const { id, method, params } = body;
set.headers['Content-Type'] = 'application/json';
set.headers['Transfer-Encoding'] = 'chunked'; // ✅ Streaming-required for n8n
export const MCPRoute = new Elysia({
prefix: "/api/mcp-server", // ✅ Sesuaikan dengan endpoint n8n
tags: ["mcp-server"],
})
.post("/mcp", ({ body, set }) => {
const { id, method, params } = body as any;
set.headers["Content-Type"] = "application/json";
set.headers["Transfer-Encoding"] = "chunked";
set.headers["Connection"] = "keep-alive";
// ---- STREAMING RESPONSE CONSTRUCTION ----
const stream = new ReadableStream({
async start(controller) {
// Jika tools/sayHello → kirim stream
if (method === "tools/sayHello") {
controller.enqueue(JSON.stringify({
jsonrpc: "2.0",
id,
result: { message: "Processing..." }
}) + "\n"); // kirim chunk pertama
await Bun.sleep(500); // contoh delay
controller.enqueue(JSON.stringify({
jsonrpc: "2.0",
id,
result: { message: `Hello ` }
}) + "\n");
// tools.list → kirim daftar tools
if (method === "tools/list") {
controller.enqueue(
JSON.stringify({
jsonrpc: "2.0",
id,
result: [
{
name: "sayHello",
description: "Greets user",
inputSchema: {
type: "object",
properties: { name: { type: "string" } },
},
},
],
}) + "\n"
);
controller.close();
}
// Jika tools/list → kirim langsung tapi tetap stream
else if (method === "tools/list") {
controller.enqueue(JSON.stringify({
jsonrpc: "2.0",
id,
result: [
{
name: "sayHello",
description: "Greets user",
inputSchema: {
type: "object",
properties: { name: { type: "string" } },
}
}
]
}));
// tools.sayHello → streaming bertahap
else if (method === "tools/sayHello") {
controller.enqueue(
JSON.stringify({
jsonrpc: "2.0",
id,
result: { message: "Processing..." },
}) + "\n"
);
await Bun.sleep(500);
controller.enqueue(
JSON.stringify({
jsonrpc: "2.0",
id,
result: { message: `Hello ${params?.name || ""}` },
}) + "\n"
);
controller.close();
}
// Jika tidak ada method
// Method tidak ditemukan
else {
controller.enqueue(JSON.stringify({
jsonrpc: "2.0",
id,
error: { code: -32601, message: `Method ${method} not found` }
}));
controller.enqueue(
JSON.stringify({
jsonrpc: "2.0",
id,
error: { code: -32601, message: `Method ${method} not found` },
}) + "\n"
);
controller.close();
}
}
},
});
return new Response(stream);
@@ -66,7 +75,7 @@ export const MCPRoute = new Elysia({ prefix: "/mcp-server", tags: ["mcp-server"]
method: t.String(),
params: t.Optional(t.Record(t.String(), t.Any())),
id: t.Optional(t.Union([t.String(), t.Number()])),
})
}),
});
export default MCPRoute;