mcp-server-kubernetes
Version:
MCP server for interacting with Kubernetes clusters via kubectl
90 lines (89 loc) • 4.61 kB
JavaScript
import express from "express";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { createAuthMiddleware, isAuthEnabled } from "./auth.js";
import { buildDefaultAllowedHosts, isAllInterfacesHost, } from "./allowed-hosts.js";
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 && isAllInterfacesHost(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'.");
}
// Binding to all interfaces makes the server reachable off-host, but the
// default allowlist only covers localhost: a client reaching it under any
// other name gets a 403 until the operator names that hostname explicitly.
if (enableDnsRebindingProtection &&
isAllInterfacesHost(host) &&
!process.env.DNS_REBINDING_ALLOWED_HOST) {
console.warn(`NOTE: HOST is set to '${host}' (all interfaces) and DNS rebinding ` +
"protection is enabled, so only requests with a localhost Host header " +
"are accepted. Clients reaching this server under another hostname " +
"(a Kubernetes Service name, an ingress host) must be allowed by " +
"setting DNS_REBINDING_ALLOWED_HOST to that hostname.");
}
// 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()
});
}
});
// An all-interfaces bind is not a hostname a client can use: with DNS
// rebinding protection on it is not in the allowlist either, so advertise a
// localhost URL that actually works rather than 'http://0.0.0.0:<port>'.
const advertisedHost = isAllInterfacesHost(host) ? "localhost" : host;
app.listen(port, host, () => {
console.log(`mcp-kubernetes-server is listening on port ${port}\nUse the following url to connect to the server:\nhttp://${advertisedHost}:${port}/sse`);
if (isAuthEnabled()) {
console.log("Authentication enabled: X-MCP-AUTH header required for all MCP requests");
}
});
}