|
| 1 | +import type { IncomingMessage, ServerResponse } from "node:http"; |
| 2 | +import { loadConfig } from "../config/config.js"; |
| 3 | +import { resolveMainSessionKey } from "../config/sessions.js"; |
| 4 | +import { normalizeMessageChannel } from "../utils/message-channel.js"; |
| 5 | +import { getHeader } from "./http-utils.js"; |
| 6 | + |
| 7 | +const MAX_MCP_BODY_BYTES = 1_048_576; |
| 8 | + |
| 9 | +export type McpRequestContext = { |
| 10 | + sessionKey: string; |
| 11 | + messageProvider: string | undefined; |
| 12 | + accountId: string | undefined; |
| 13 | +}; |
| 14 | + |
| 15 | +function resolveScopedSessionKey( |
| 16 | + cfg: ReturnType<typeof loadConfig>, |
| 17 | + rawSessionKey: string | undefined, |
| 18 | +): string { |
| 19 | + const trimmed = rawSessionKey?.trim(); |
| 20 | + return !trimmed || trimmed === "main" ? resolveMainSessionKey(cfg) : trimmed; |
| 21 | +} |
| 22 | + |
| 23 | +export function validateMcpLoopbackRequest(params: { |
| 24 | + req: IncomingMessage; |
| 25 | + res: ServerResponse; |
| 26 | + token: string; |
| 27 | +}): boolean { |
| 28 | + let url: URL; |
| 29 | + try { |
| 30 | + url = new URL(params.req.url ?? "/", `http://${params.req.headers.host ?? "localhost"}`); |
| 31 | + } catch { |
| 32 | + params.res.writeHead(400, { "Content-Type": "application/json" }); |
| 33 | + params.res.end(JSON.stringify({ error: "bad_request" })); |
| 34 | + return false; |
| 35 | + } |
| 36 | + |
| 37 | + if (params.req.method === "GET" && url.pathname.startsWith("/.well-known/")) { |
| 38 | + params.res.writeHead(404); |
| 39 | + params.res.end(); |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + if (url.pathname !== "/mcp") { |
| 44 | + params.res.writeHead(404, { "Content-Type": "application/json" }); |
| 45 | + params.res.end(JSON.stringify({ error: "not_found" })); |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + if (params.req.method !== "POST") { |
| 50 | + params.res.writeHead(405, { Allow: "POST" }); |
| 51 | + params.res.end(); |
| 52 | + return false; |
| 53 | + } |
| 54 | + |
| 55 | + const authHeader = getHeader(params.req, "authorization") ?? ""; |
| 56 | + if (authHeader !== `Bearer ${params.token}`) { |
| 57 | + params.res.writeHead(401, { "Content-Type": "application/json" }); |
| 58 | + params.res.end(JSON.stringify({ error: "unauthorized" })); |
| 59 | + return false; |
| 60 | + } |
| 61 | + |
| 62 | + const contentType = getHeader(params.req, "content-type") ?? ""; |
| 63 | + if (!contentType.startsWith("application/json")) { |
| 64 | + params.res.writeHead(415, { "Content-Type": "application/json" }); |
| 65 | + params.res.end(JSON.stringify({ error: "unsupported_media_type" })); |
| 66 | + return false; |
| 67 | + } |
| 68 | + |
| 69 | + return true; |
| 70 | +} |
| 71 | + |
| 72 | +export async function readMcpHttpBody(req: IncomingMessage): Promise<string> { |
| 73 | + return await new Promise((resolve, reject) => { |
| 74 | + const chunks: Buffer[] = []; |
| 75 | + let received = 0; |
| 76 | + req.on("data", (chunk: Buffer) => { |
| 77 | + received += chunk.length; |
| 78 | + if (received > MAX_MCP_BODY_BYTES) { |
| 79 | + req.destroy(); |
| 80 | + reject(new Error(`Request body exceeds ${MAX_MCP_BODY_BYTES} bytes`)); |
| 81 | + return; |
| 82 | + } |
| 83 | + chunks.push(chunk); |
| 84 | + }); |
| 85 | + req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8"))); |
| 86 | + req.on("error", reject); |
| 87 | + }); |
| 88 | +} |
| 89 | + |
| 90 | +export function resolveMcpRequestContext( |
| 91 | + req: IncomingMessage, |
| 92 | + cfg: ReturnType<typeof loadConfig>, |
| 93 | +): McpRequestContext { |
| 94 | + return { |
| 95 | + sessionKey: resolveScopedSessionKey(cfg, getHeader(req, "x-session-key")), |
| 96 | + messageProvider: |
| 97 | + normalizeMessageChannel(getHeader(req, "x-openclaw-message-channel")) ?? undefined, |
| 98 | + accountId: getHeader(req, "x-openclaw-account-id")?.trim() || undefined, |
| 99 | + }; |
| 100 | +} |
0 commit comments