/**
* MCSManager MCP Server - HTTP/SSE Transport
* Provides Model Context Protocol access via HTTP Server-Sent Events
*/
import express from "express";
import cors from "cors";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
InitializeRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { MCPClient as MCSManagerClient } from "./api-client.js";
import { handleToolCall, TOOL_DEFINITIONS } from "./tools.js";
const PORT = parseInt(process.env.PORT || "3010", 10);
// Create Express app
const app = express();
app.use(cors({
origin: "*",
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: [
"Content-Type",
"Authorization",
"Accept",
"Cache-Control",
"mcsm-api-key",
"mcsm_api_key",
"mcsm-api-url",
"mcsm_api_url",
"X-Requested-With",
],
exposedHeaders: ["Content-Type"],
credentials: false,
}));
app.use(express.json({ limit: "10mb" }));
// MCP specific response headers
app.use((req, res, next) => {
res.setHeader("X-Powered-By", "@mcsmanager/mcp-server");
res.setHeader("X-MCP-Version", "2024-11-05");
if (req.method === "OPTIONS") {
res.status(200).end();
return;
}
next();
});
// Health check endpoint
app.get("/health", (req, res) => {
res.json({ status: "ok", service: "mcsmanager-mcp-server" });
});
// MCP endpoint – supports query parameters for apiKey and apiUrl
app.all(["/mcp/:apiKey", "/mcp"], async (req, res) => {
const reqIp = req.ip || req.connection?.remoteAddress || "unknown";
console.log(`\n[MCP] Incoming ${req.method} request from ${reqIp}`);
console.log(`[MCP] Request Headers:`, req.headers);
const query = req.query || {};
const getString = (val: any): string | undefined => {
if (typeof val === "string") return val;
if (Array.isArray(val) && val.length > 0 && typeof val[0] === "string") return val[0];
return undefined;
};
// Extract API key
let apiKeyValue = getString(query["mcsm-api-key"]) || getString(query["mcsm_api_key"]);
if (!apiKeyValue) {
apiKeyValue =
getString(req.params?.apiKey) ||
getString(req.headers["mcsm-api-key"]) ||
getString(req.headers["mcsm_api_key"]) ||
getString(req.headers["authorization"]);
}
const isLocal = reqIp === "::1" || reqIp === "127.0.0.1" || reqIp === "::ffff:127.0.0.1";
if (!apiKeyValue && isLocal) {
apiKeyValue = "YOUR_TEST_KEY_HERE";
}
// Extract API URL and normalize to panel port (23333)
let apiUrl = getString(query["mcsm-api-url"]) || getString(query["mcsm_api_url"]);
if (!apiUrl) {
apiUrl = getString(req.params?.apiUrl) || process.env.MCSM_API_URL || "http://localhost:23333";
}
if (apiUrl) {
apiUrl = apiUrl.replace(/^["']|["']$/g, "");
if (!apiUrl.match(/^https?:\/\//i)) {
apiUrl = `http://${apiUrl}`;
}
}
console.log(`[MCP] Extracted API Key: ${apiKeyValue ? `${apiKeyValue.substring(0, 8)}***` : "none"}`);
console.log(`[MCP] Extracted API URL: ${apiUrl}`);
// Initialize client
const mcsmClient = new MCSManagerClient({ apiUrl, apiKey: apiKeyValue });
// MCP server
const server = new Server(
{ name: "@mcsmanager/mcp-server", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOL_DEFINITIONS }));
server.setRequestHandler(CallToolRequestSchema, async (request) => handleToolCall(request, mcsmClient));
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: false,
enableDnsRebindingProtection: false,
});
try {
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
} catch (error) {
console.error(`[MCP] Error handling request:`, error);
if (!res.headersSent) {
res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" } });
}
}
});
// Start server
app.listen(PORT, "0.0.0.0", () => {
console.log(`MCSManager MCP Server (HTTP/SSE) listening on port ${PORT}`);
console.log(`Local endpoint: http://localhost:${PORT}/mcp`);
console.log(`Network endpoint: http://0.0.0.0:${PORT}/mcp`);
console.log(`Health check: http://localhost:${PORT}/health`);
});