import type { IncomingMessage, ServerResponse } from "node:http"; import { McpHttpError } from "./errors.js"; export async function readJsonBody(req: IncomingMessage): Promise { const chunks: Buffer[] = []; let size = 0; for await (const chunk of req) { const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)); size += buffer.byteLength; if (size > 1_000_000) { throw new McpHttpError(413, "payload_too_large", "MCP request body is too large."); } chunks.push(buffer); } if (chunks.length === 0) { return undefined; } try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { throw new McpHttpError(400, "invalid_json", "MCP request body must be valid JSON."); } } export function writeJson(res: ServerResponse, status: number, payload: unknown, headers: Record = {}): void { if (res.headersSent) { return; } res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", ...headers, }); res.end(JSON.stringify(payload)); } // Trusted, proxy-set headers only. The leftmost X-Forwarded-For value is // client-controlled, so keying a rate limit on it would let an attacker rotate // their apparent IP. In this estate the MCP host sits behind Cloudflare, which // sets CF-Connecting-IP and overwrites any client-supplied value. const TRUSTED_IP_HEADERS = ["cf-connecting-ip", "true-client-ip", "x-real-ip"] as const; export function getClientIp(req: IncomingMessage): string { for (const headerName of TRUSTED_IP_HEADERS) { const value = req.headers[headerName]; const candidate = (Array.isArray(value) ? value[0] : value)?.trim(); if (candidate) { return candidate; } } return req.socket.remoteAddress ?? "unknown"; } export function getHeader(req: IncomingMessage, name: string): string | undefined { const value = req.headers[name.toLowerCase()]; if (Array.isArray(value)) { return value.at(-1); } return value; }