import type { IncomingMessage, ServerResponse } from "node:http"; import { getTrustedProxyClientIp } from "@hivegrid/foundation/trusted-client-ip"; import { McpHttpError } from "./errors.js"; export const MCP_MAX_BODY_BYTES = 1_000_000; export async function readJsonBody(req: IncomingMessage): Promise { const contentLength = parseContentLength(req.headers["content-length"]); if (contentLength !== null && contentLength > MCP_MAX_BODY_BYTES) { throw new McpHttpError(413, "payload_too_large", "MCP request body is too large."); } 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 > MCP_MAX_BODY_BYTES) { 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."); } } function parseContentLength(value: string | undefined): number | null { if (!value || !/^\d+$/.test(value.trim())) return null; const parsed = Number(value); return Number.isSafeInteger(parsed) ? parsed : null; } 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)); } export function getClientIp(req: IncomingMessage): string { return ( getTrustedProxyClientIp((name) => { const value = req.headers[name]; return Array.isArray(value) ? value.at(-1) : value; }, 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; }