// Node's standard library only: the TOML parser is a parameter, so importing this never throws. import { isDeepStrictEqual } from "node:util"; const BEGIN = "# BEGIN karajan-mcp"; const END = "# END karajan-mcp"; const MENTION = /karajan-mcp/; /** The block between its marker lines, also what the user pastes by hand. */ export const markedCodexBlock = (block) => `${BEGIN}\n${block}\n${END}`; const indexesOf = (lines, marker) => lines.flatMap((line, i) => (line.trim() === marker ? [i] : [])); // Plain text between the two marker lines. Null when karajan-mcp shows up in any other shape: // kj only manages its own block, and over-detecting is fine. function placeBlock(toml, marked) { if (!MENTION.test(toml)) return [toml.trimEnd(), `${marked}\n`].filter(Boolean).join("\n\n"); const lines = toml.split("\n"); const [begins, ends] = [indexesOf(lines, BEGIN), indexesOf(lines, END)]; if (begins.length !== 1 || ends.length !== 1 || ends[0] < begins[0]) return null; const before = lines.slice(0, begins[0]); const after = lines.slice(ends[0] + 1); if ([...before, ...after].some((line) => MENTION.test(line))) return null; if (marked !== null) return [...before, marked, ...after].join("\n"); // Taking the block out takes the blank line kj put before it. return [...(before.at(-1) === "" ? before.slice(0, -1) : before), ...after].join("\n"); } /** The config without kj's marked block, or null when that would not take out kj's entry alone. */ export function removeCodexMcpBlock(toml, parse) { if (!MENTION.test(toml)) return toml; const updated = placeBlock(toml, null); return updated !== null && onlyChangesTheEntry(toml, updated, "", parse) ? updated : null; } function parseToml(text, parse) { try { return parse(text); } catch { return null; } } // Takes kj's entry out of a parsed config (mutating it) and returns it. A table left empty // goes too: a config that only held kj's entry equals one without any. function takeEntry(config) { const servers = config.mcp_servers; const entry = servers?.["karajan-mcp"]; if (entry !== undefined) { delete servers["karajan-mcp"]; if (Object.keys(servers).length === 0) delete config.mcp_servers; } return entry; } // What the text MEANS, whatever its lines look like: kj's entry is exactly the block, and // nothing else of the user's changed. function onlyChangesTheEntry(original, updated, block, parse) { const [before, after, wanted] = [original, updated, block].map((text) => parseToml(text, parse)); if (!before || !after) return false; takeEntry(before); return isDeepStrictEqual(takeEntry(after), takeEntry(wanted)) && isDeepStrictEqual(before, after); } /** The config with kj's marked block replaced or appended, or null when it must not be written. */ export function upsertCodexMcpBlock(toml, block, parse) { const updated = placeBlock(toml, markedCodexBlock(block)); return updated !== null && onlyChangesTheEntry(toml, updated, block, parse) ? updated : null; }