mcp-server-kubernetes
Version:
MCP server for interacting with Kubernetes clusters via kubectl
105 lines (104 loc) • 4.51 kB
JavaScript
import express from "express";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { createAuthMiddleware, isAuthEnabled } from "./auth.js";
/**
* Build the default allowedHosts list for DNS rebinding protection.
* Includes localhost variants with and without port.
*/
function buildDefaultAllowedHosts(host, port) {
// Always allow the bare host and host:port for common localhost addresses
const localhostAliases = ["127.0.0.1", "localhost", "::1"];
const hosts = [];
for (const alias of localhostAliases) {
hosts.push(alias);
// HTTP Host header uses bracket notation for IPv6: [::1]:3000
if (alias.includes(":")) {
hosts.push(`[${alias}]`);
hosts.push(`[${alias}]:${port}`);
}
else {
hosts.push(`${alias}:${port}`);
}
}
// Also add the configured host if it's not already covered
if (!localhostAliases.includes(host)) {
hosts.push(host);
if (host.includes(":") && !host.startsWith("[")) {
hosts.push(`[${host}]`);
hosts.push(`[${host}]:${port}`);
}
else {
hosts.push(`${host}:${port}`);
}
}
return hosts;
}
export function startSSEServer(server) {
const app = express();
// Create auth middleware - when MCP_AUTH_TOKEN is set, requires X-MCP-AUTH header
const authMiddleware = createAuthMiddleware();
// DNS rebinding protection is enabled by default. Set DNS_REBINDING_PROTECTION=false to disable.
const enableDnsRebindingProtection = process.env.DNS_REBINDING_PROTECTION !== "false";
const host = process.env.HOST || "localhost";
const parsed = parseInt(process.env.PORT || "3000", 10);
const port = Number.isNaN(parsed) ? 3000 : parsed;
const allowedHosts = process.env.DNS_REBINDING_ALLOWED_HOST
? [process.env.DNS_REBINDING_ALLOWED_HOST]
: buildDefaultAllowedHosts(host, port);
// Warn when binding to all interfaces with DNS rebinding protection disabled
if (!enableDnsRebindingProtection && (host === "0.0.0.0" || host === "::")) {
console.warn("WARNING: DNS rebinding protection is disabled while HOST is set to " +
`'${host}'. This exposes the MCP server to DNS rebinding attacks ` +
"from any browser on the network. Set DNS_REBINDING_PROTECTION=true " +
"(the default) or restrict HOST to 'localhost' / '127.0.0.1'.");
}
// Currently just copying from docs & allowing for multiple transport connections: https://modelcontextprotocol.io/docs/concepts/transports#server-sent-events-sse
// Note: When MCP_AUTH_TOKEN is set, requests require X-MCP-AUTH header for authentication
let transports = [];
app.get("/sse", authMiddleware, async (req, res) => {
const transport = new SSEServerTransport("/messages", res, {
enableDnsRebindingProtection,
allowedHosts,
});
transports.push(transport);
await server.connect(transport);
});
app.post("/messages", authMiddleware, (req, res) => {
const transport = transports.find((t) => t.sessionId === req.query.sessionId);
if (transport) {
transport.handlePostMessage(req, res);
}
else {
res
.status(404)
.send("Not found. Must pass valid sessionId as query param.");
}
});
app.get("/health", async (req, res) => {
res.json({ status: "ok" });
});
app.get("/ready", async (req, res) => {
try {
// We can add more checks if required
// For now, we'll consider the server ready if it can respond to this request
res.json({
status: "ready",
timestamp: new Date().toISOString(),
});
}
catch (error) {
console.error("Readiness check failed:", error);
res.status(503).json({
status: "not ready",
reason: "Server initialization incomplete",
timestamp: new Date().toISOString()
});
}
});
app.listen(port, host, () => {
console.log(`mcp-kubernetes-server is listening on port ${port}\nUse the following url to connect to the server:\nhttp://${host}:${port}/sse`);
if (isAuthEnabled()) {
console.log("Authentication enabled: X-MCP-AUTH header required for all MCP requests");
}
});
}