mcp-server-kubernetes
Version:
MCP server for interacting with Kubernetes clusters via kubectl
128 lines (127 loc) • 6.04 kB
JavaScript
import express from "express";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { createAuthMiddleware, isAuthEnabled } from "./auth.js";
import { buildDefaultAllowedHosts, isAllInterfacesHost, } from "./allowed-hosts.js";
export function startStreamableHTTPServer(server) {
const app = express();
app.use(express.json());
// 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.");
}
app.post("/mcp", authMiddleware, async (req, res) => {
// In stateless mode, create a new instance of transport and server for each request
// to ensure complete isolation. A single instance would cause request ID collisions
// when multiple clients connect concurrently.
try {
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableDnsRebindingProtection,
allowedHosts,
});
res.on("close", () => {
transport.close();
// Note: server.close() should NOT be called here as server is shared
// across all requests. Calling it would close the global MCP Server
// instance and cause the Node.js process to exit. Only the transport
// instance needs to be closed when the HTTP connection ends.
});
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
}
catch (error) {
console.error("Error handling MCP request:", error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: "2.0",
error: {
code: -32603,
message: "Internal server error",
},
id: null,
});
}
}
});
// SSE notifications not supported in stateless mode
app.get("/mcp", authMiddleware, async (req, res) => {
console.log("Received GET MCP request");
res.writeHead(405).end(JSON.stringify({
jsonrpc: "2.0",
error: {
code: -32000,
message: "Method not allowed.",
},
id: null,
}));
});
// Session termination not needed in stateless mode
app.delete("/mcp", authMiddleware, async (req, res) => {
console.log("Received DELETE MCP request");
res.writeHead(405).end(JSON.stringify({
jsonrpc: "2.0",
error: {
code: -32000,
message: "Method not allowed.",
},
id: null,
}));
});
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;
const httpServer = 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}/mcp`);
if (isAuthEnabled()) {
console.log("Authentication enabled: X-MCP-AUTH header required for all MCP requests");
}
});
return httpServer;
}