tambahan
This commit is contained in:
@@ -1,262 +1,190 @@
|
|||||||
|
// src/routes/mcp_route.ts
|
||||||
import { Elysia, t } from "elysia";
|
import { Elysia, t } from "elysia";
|
||||||
import { cors } from '@elysiajs/cors';
|
|
||||||
|
|
||||||
export const MCPRoute = new Elysia({
|
export const MCPRoute = new Elysia({
|
||||||
prefix: "/mcp-server",
|
prefix: "/mcp",
|
||||||
tags: ["mcp-server"],
|
|
||||||
})
|
})
|
||||||
.use(cors())
|
.get("/", ({ set, query }) => {
|
||||||
|
const id = query.id ?? 1;
|
||||||
|
const method = query.method as string;
|
||||||
|
const params = query;
|
||||||
|
|
||||||
// ✅ Health check endpoint
|
// Header untuk SSE / Streaming agar diterima oleh n8n
|
||||||
.get("/", () => ({
|
set.headers["Content-Type"] = "application/json; charset=utf-8";
|
||||||
status: "ok",
|
set.headers["Cache-Control"] = "no-cache, no-transform";
|
||||||
message: "MCP Server is running",
|
set.headers["Connection"] = "keep-alive";
|
||||||
protocol: "2024-11-05",
|
set.headers["Transfer-Encoding"] = "chunked";
|
||||||
transport: "sse",
|
set.headers["X-Accel-Buffering"] = "no"; // Matikan buffering (nginx/cloudflare)
|
||||||
endpoints: {
|
|
||||||
sse: "/mcp-server/sse",
|
|
||||||
message: "/mcp-server/message"
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
|
|
||||||
// ✅ SSE endpoint - Server-Sent Events untuk n8n
|
|
||||||
.get("/sse", ({ set }) => {
|
|
||||||
set.headers = {
|
|
||||||
"Content-Type": "text/event-stream",
|
|
||||||
"Cache-Control": "no-cache, no-transform",
|
|
||||||
"Connection": "keep-alive",
|
|
||||||
"X-Accel-Buffering": "no"
|
|
||||||
};
|
|
||||||
|
|
||||||
const encoder = new TextEncoder();
|
|
||||||
let isClosed = false;
|
|
||||||
|
|
||||||
const stream = new ReadableStream({
|
const stream = new ReadableStream({
|
||||||
start(controller) {
|
async start(controller) {
|
||||||
// Send endpoint info immediately
|
// ✅ Heartbeat agar tidak time-out di Cloudflare / n8n
|
||||||
const endpointMsg = {
|
controller.enqueue(":\n\n");
|
||||||
type: "endpoint",
|
|
||||||
endpoint: "/mcp-server/message"
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
// 1. Handshake MCP Version
|
||||||
|
if (method === "mcp/version") {
|
||||||
controller.enqueue(
|
controller.enqueue(
|
||||||
encoder.encode(`data: ${JSON.stringify(endpointMsg)}\n\n`)
|
JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id,
|
||||||
|
result: {
|
||||||
|
protocol: "2024-11-05",
|
||||||
|
capabilities: {
|
||||||
|
"tools/list": true,
|
||||||
|
"tools/call": true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}) + "\n"
|
||||||
);
|
);
|
||||||
} catch (e) {
|
return; // ❗ biarkan stream tetap terbuka
|
||||||
console.error("Failed to send endpoint message:", e);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keep connection alive with heartbeat
|
// 2. tools/list → Informasi tools ke n8n
|
||||||
const heartbeat = setInterval(() => {
|
if (method === "tools/list") {
|
||||||
if (isClosed) {
|
controller.enqueue(
|
||||||
clearInterval(heartbeat);
|
JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id,
|
||||||
|
result: [
|
||||||
|
{
|
||||||
|
name: "sayHello",
|
||||||
|
description: "Greets a user",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
name: { type: "string", description: "Your name" },
|
||||||
|
},
|
||||||
|
required: ["name"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}) + "\n"
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
// 3. tools/sayHello → kirim progres lalu hasil
|
||||||
controller.enqueue(encoder.encode(`: heartbeat\n\n`));
|
if (method === "tools/sayHello") {
|
||||||
} catch (e) {
|
controller.enqueue(
|
||||||
console.error("Heartbeat failed:", e);
|
JSON.stringify({
|
||||||
clearInterval(heartbeat);
|
|
||||||
isClosed = true;
|
|
||||||
try {
|
|
||||||
controller.close();
|
|
||||||
} catch (closeErr) {
|
|
||||||
// Already closed
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, 15000); // Every 15 seconds
|
|
||||||
|
|
||||||
// Cleanup on connection close
|
|
||||||
return () => {
|
|
||||||
isClosed = true;
|
|
||||||
clearInterval(heartbeat);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(stream);
|
|
||||||
})
|
|
||||||
|
|
||||||
// ✅ Message endpoint - untuk JSON-RPC messages
|
|
||||||
.post("/message", async ({ body, set }) => {
|
|
||||||
set.headers["Content-Type"] = "application/json";
|
|
||||||
|
|
||||||
const { jsonrpc, id, method, params } = body as any;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Initialize
|
|
||||||
if (method === "initialize") {
|
|
||||||
return {
|
|
||||||
jsonrpc: "2.0",
|
jsonrpc: "2.0",
|
||||||
id,
|
id,
|
||||||
result: {
|
result: { status: "Processing..." },
|
||||||
protocolVersion: "2024-11-05",
|
}) + "\n"
|
||||||
capabilities: {
|
);
|
||||||
tools: {}
|
await Bun.sleep(500);
|
||||||
},
|
|
||||||
serverInfo: {
|
|
||||||
name: "tentang-darmasaba-mcp",
|
|
||||||
version: "1.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ping
|
controller.enqueue(
|
||||||
if (method === "ping") {
|
JSON.stringify({
|
||||||
return {
|
|
||||||
jsonrpc: "2.0",
|
jsonrpc: "2.0",
|
||||||
id,
|
id,
|
||||||
result: {}
|
result: { message: `Hello ${params?.name || "User"}` },
|
||||||
};
|
}) + "\n"
|
||||||
|
);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// List tools
|
// 4. Unknown method
|
||||||
if (method === "tools/list") {
|
controller.enqueue(
|
||||||
return {
|
JSON.stringify({
|
||||||
jsonrpc: "2.0",
|
|
||||||
id,
|
|
||||||
result: {
|
|
||||||
tools: [
|
|
||||||
{
|
|
||||||
name: "sayHello",
|
|
||||||
description: "Greets user with a personalized message",
|
|
||||||
inputSchema: {
|
|
||||||
type: "object",
|
|
||||||
properties: {
|
|
||||||
name: {
|
|
||||||
type: "string",
|
|
||||||
description: "Name of the person to greet"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
required: ["name"]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "getCurrentTime",
|
|
||||||
description: "Returns current server time",
|
|
||||||
inputSchema: {
|
|
||||||
type: "object",
|
|
||||||
properties: {}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "getTentangDarmasaba",
|
|
||||||
description: "Get information about Tentang Darmasaba platform",
|
|
||||||
inputSchema: {
|
|
||||||
type: "object",
|
|
||||||
properties: {
|
|
||||||
section: {
|
|
||||||
type: "string",
|
|
||||||
description: "Specific section to get info about",
|
|
||||||
enum: ["about", "features", "contact"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Call tool
|
|
||||||
if (method === "tools/call") {
|
|
||||||
const toolName = params?.name;
|
|
||||||
const args = params?.arguments || {};
|
|
||||||
|
|
||||||
if (toolName === "sayHello") {
|
|
||||||
return {
|
|
||||||
jsonrpc: "2.0",
|
|
||||||
id,
|
|
||||||
result: {
|
|
||||||
content: [
|
|
||||||
{
|
|
||||||
type: "text",
|
|
||||||
text: `Hello ${args.name || "there"}! 👋 Welcome to Tentang Darmasaba MCP Server!`
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (toolName === "getCurrentTime") {
|
|
||||||
return {
|
|
||||||
jsonrpc: "2.0",
|
|
||||||
id,
|
|
||||||
result: {
|
|
||||||
content: [
|
|
||||||
{
|
|
||||||
type: "text",
|
|
||||||
text: `Current server time: ${new Date().toISOString()}`
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (toolName === "getTentangDarmasaba") {
|
|
||||||
const section = args.section || "about";
|
|
||||||
const info: Record<string, string> = {
|
|
||||||
about: "Tentang Darmasaba adalah platform pembelajaran dan kolaborasi.",
|
|
||||||
features: "Fitur: MCP Server integration, Real-time collaboration, API tools",
|
|
||||||
contact: "Contact: support@tentangdarmasaba.com"
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
jsonrpc: "2.0",
|
|
||||||
id,
|
|
||||||
result: {
|
|
||||||
content: [
|
|
||||||
{
|
|
||||||
type: "text",
|
|
||||||
text: info[section] || info.about
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tool not found
|
|
||||||
return {
|
|
||||||
jsonrpc: "2.0",
|
|
||||||
id,
|
|
||||||
error: {
|
|
||||||
code: -32602,
|
|
||||||
message: `Unknown tool: ${toolName}`
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Method not found
|
|
||||||
return {
|
|
||||||
jsonrpc: "2.0",
|
jsonrpc: "2.0",
|
||||||
id,
|
id,
|
||||||
error: {
|
error: {
|
||||||
code: -32601,
|
code: -32601,
|
||||||
message: `Unknown method: ${method}`
|
message: `Method "${method}" not found`,
|
||||||
}
|
},
|
||||||
};
|
}) + "\n"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
cancel() {
|
||||||
|
console.log("🔴 Stream closed by client");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
} catch (error: any) {
|
return new Response(stream);
|
||||||
console.error("MCP Error:", error);
|
})
|
||||||
return {
|
// Optional: juga izinkan MCP pakai POST request JSON-RPC
|
||||||
|
.post("/", async ({ body, set }) => {
|
||||||
|
const { id, method, params } = body as any;
|
||||||
|
|
||||||
|
set.headers["Content-Type"] = "application/json; charset=utf-8";
|
||||||
|
set.headers["Connection"] = "keep-alive";
|
||||||
|
set.headers["Transfer-Encoding"] = "chunked";
|
||||||
|
set.headers["X-Accel-Buffering"] = "no";
|
||||||
|
|
||||||
|
const stream = new ReadableStream({
|
||||||
|
async start(controller) {
|
||||||
|
controller.enqueue(":\n\n");
|
||||||
|
|
||||||
|
if (method === "mcp/version") {
|
||||||
|
controller.enqueue(
|
||||||
|
JSON.stringify({
|
||||||
jsonrpc: "2.0",
|
jsonrpc: "2.0",
|
||||||
id,
|
id,
|
||||||
error: {
|
result: {
|
||||||
code: -32603,
|
protocol: "2024-11-05",
|
||||||
message: `Internal error: ${error.message}`
|
capabilities: {
|
||||||
|
"tools/list": true,
|
||||||
|
"tools/call": true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}) + "\n"
|
||||||
|
);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
if (method === "tools/list") {
|
||||||
|
controller.enqueue(
|
||||||
|
JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id,
|
||||||
|
result: [
|
||||||
|
{
|
||||||
|
name: "sayHello",
|
||||||
|
description: "Greets a user",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
name: { type: "string" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}) + "\n"
|
||||||
|
);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}, {
|
|
||||||
|
if (method === "tools/sayHello") {
|
||||||
|
controller.enqueue(
|
||||||
|
JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id,
|
||||||
|
result: { status: "Processing..." },
|
||||||
|
}) + "\n"
|
||||||
|
);
|
||||||
|
await Bun.sleep(500);
|
||||||
|
|
||||||
|
controller.enqueue(
|
||||||
|
JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id,
|
||||||
|
result: { message: `Hello ${params?.name || ""}` },
|
||||||
|
}) + "\n"
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Response(stream);
|
||||||
|
}, {
|
||||||
body: t.Object({
|
body: t.Object({
|
||||||
jsonrpc: t.String(),
|
jsonrpc: t.Optional(t.String()),
|
||||||
method: t.String(),
|
method: t.String(),
|
||||||
params: t.Optional(t.Any()),
|
params: t.Optional(t.Record(t.String(), t.Any())),
|
||||||
id: t.Union([t.String(), t.Number()]),
|
id: t.Optional(t.Union([t.String(), t.Number()])),
|
||||||
})
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
export default MCPRoute;
|
export default MCPRoute;
|
||||||
Reference in New Issue
Block a user