Skip to content

Context7 Platform -- Up-to-date docs for AI agents

fix(cli): safely patch Codex TOML stdio args (#3075)

Fahreddin Özcan118c8528e4cf
diff --git a/.changeset/safe-codex-toml.md b/.changeset/safe-codex-toml.md
new file mode 100644
index 00000000..00d23e05
--- /dev/null
+++ b/.changeset/safe-codex-toml.md
@@ -0,0 +1,5 @@
+---
+"ctx7": patch
+---
+
+Preserve existing Codex TOML settings when rotating stdio API keys.
diff --git a/packages/cli/src/__tests__/setup.test.ts b/packages/cli/src/__tests__/setup.test.ts
index 2889cf5e..19c56047 100644
--- a/packages/cli/src/__tests__/setup.test.ts
+++ b/packages/cli/src/__tests__/setup.test.ts
@@ -26,7 +26,6 @@ import {
readJsonConfig,
writeJsonConfig,
readTomlServerExists,
- readTomlServerEntry,
buildTomlServerBlock,
appendTomlServer,
removeTomlServer,
@@ -1244,70 +1243,4 @@ describe("agent config integration", () => {
expect(patched.cwd).toBe("/custom");
});
});
-
- describe("readTomlServerEntry", () => {
- let tempDir: string;
-
- beforeEach(async () => {
- tempDir = join(tmpdir(), `ctx7-test-${Date.now()}`);
- await mkdir(tempDir, { recursive: true });
- });
-
- afterEach(async () => {
- await rm(tempDir, { recursive: true, force: true });
- });
-
- test("returns undefined for missing file", async () => {
- expect(await readTomlServerEntry(join(tempDir, "nope.toml"), "context7")).toBeUndefined();
- });
-
- test("returns undefined for missing section", async () => {
- const path = join(tempDir, "config.toml");
- await writeFile(path, '[mcp_servers.other]\nurl = "https://other.com"\n', "utf-8");
- expect(await readTomlServerEntry(path, "context7")).toBeUndefined();
- });
-
- test("parses string and array values from a stdio block", async () => {
- const path = join(tempDir, "config.toml");
- await writeFile(
- path,
- '[mcp_servers.context7]\ncommand = "npx"\nargs = ["-y", "@upstash/context7-mcp@latest", "--api-key", "OLD"]\n',
- "utf-8"
- );
- const entry = await readTomlServerEntry(path, "context7");
- expect(entry).toEqual({
- command: "npx",
- args: ["-y", "@upstash/context7-mcp@latest", "--api-key", "OLD"],
- });
- });
-
- test("ignores http_headers sub-table", async () => {
- const path = join(tempDir, "config.toml");
- await writeFile(
- path,
- '[mcp_servers.context7]\ntype = "http"\nurl = "https://mcp.context7.com/mcp"\n\n[mcp_servers.context7.http_headers]\nCONTEXT7_API_KEY = "k"\n',
- "utf-8"
- );
- const entry = await readTomlServerEntry(path, "context7");
- expect(entry).toEqual({ type: "http", url: "https://mcp.context7.com/mcp" });
- });
-
- test("round-trips through patchStdioApiKey + appendTomlServer", async () => {
- const path = join(tempDir, "config.toml");
- await writeFile(
- path,
- '[mcp_servers.context7]\ncommand = "npx"\nargs = ["-y", "@upstash/context7-mcp@latest", "--api-key", "OLD"]\n',
- "utf-8"
- );
- const existing = await readTomlServerEntry(path, "context7");
- expect(existing).toBeDefined();
- expect(isStdioContext7Entry(existing)).toBe(true);
- const patched = patchStdioApiKey(existing!, "NEW");
- await appendTomlServer(path, "context7", patched);
- const content = await readFile(path, "utf-8");
- expect(content).toContain("@upstash/context7-mcp@latest");
- expect(content).toContain('"--api-key","NEW"');
- expect(content).not.toContain('"OLD"');
- });
- });
});
diff --git a/packages/cli/src/__tests__/toml-editor.test.ts b/packages/cli/src/__tests__/toml-editor.test.ts
new file mode 100644
index 00000000..74d729c3
--- /dev/null
+++ b/packages/cli/src/__tests__/toml-editor.test.ts
@@ -0,0 +1,349 @@
+import { afterEach, beforeEach, describe, expect, test } from "vitest";
+import { mkdtemp, readFile, rm, writeFile } from "fs/promises";
+import { join } from "path";
+import { tmpdir } from "os";
+import { patchTomlStdioApiKey } from "../setup/toml-editor.js";
+
+const PACKAGE = "@upstash/context7-mcp";
+
+interface RotationCase {
+ name: string;
+ source: string;
+ oldToken: string;
+}
+
+const rotation = (name: string, source: string, oldToken = '"OLD"'): RotationCase => ({
+ name,
+ source,
+ oldToken,
+});
+
+const rotations: RotationCase[] = [
+ rotation(
+ "single-line array",
+ `[mcp_servers.context7]\ncommand = "npx"\nargs = ["-y", "${PACKAGE}@latest", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "multiline array with trailing comma",
+ `[mcp_servers.context7]\nargs = [\n "-y",\n "${PACKAGE}@latest",\n "--api-key",\n "OLD",\n]\n`
+ ),
+ rotation(
+ "multiline array without trailing comma",
+ `[mcp_servers.context7]\nargs = [\n "${PACKAGE}",\n "--api-key",\n "OLD"\n]\n`
+ ),
+ rotation("CRLF input", `[mcp_servers.context7]\r\nargs = ["${PACKAGE}", "--api-key", "OLD"]\r\n`),
+ rotation(
+ "literal API key",
+ `[mcp_servers.context7]\nargs = ["${PACKAGE}", "--api-key", 'OLD']\n`,
+ "'OLD'"
+ ),
+ rotation(
+ "quoted server key",
+ `[mcp_servers."context7"]\nargs = ["${PACKAGE}", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "fully quoted table path",
+ `["mcp_servers"."context7"]\nargs = ["${PACKAGE}", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "spaced dotted table path",
+ `[ mcp_servers . context7 ]\nargs = ["${PACKAGE}", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "UTF-8 BOM",
+ `\uFEFF[mcp_servers.context7]\nargs = ["${PACKAGE}", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "quoted args key",
+ `[mcp_servers.context7]\n"args" = ["${PACKAGE}", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "literal args key",
+ `[mcp_servers.context7]\n'args' = ["${PACKAGE}", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "table header trailing comment",
+ `[mcp_servers.context7] # docs\nargs = ["${PACKAGE}", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "tab indentation",
+ `[mcp_servers.context7]\nargs\t=\t[\n\t"${PACKAGE}",\n\t"--api-key",\n\t"OLD"\n]\n`
+ ),
+ rotation(
+ "pinned package version",
+ `[mcp_servers.context7]\nargs = ["${PACKAGE}@0.6.0", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "unversioned package",
+ `[mcp_servers.context7]\nargs = ["${PACKAGE}", "--api-key", "OLD"]\n`
+ ),
+ rotation(
+ "flags around API key",
+ `[mcp_servers.context7]\nargs = ["-y", "${PACKAGE}", "--transport", "stdio", "--api-key", "OLD", "--debug"]\n`
+ ),
+ rotation(
+ "comments between every item",
+ `[mcp_servers.context7]\nargs = [\n "${PACKAGE}", # package\n "--api-key", # flag\n "OLD", # value\n]\n`
+ ),
+ rotation(
+ "Unicode escape in old key",
+ `[mcp_servers.context7]\nargs = ["${PACKAGE}", "--api-key", "OLD\\u0021"]\n`,
+ '"OLD\\u0021"'
+ ),
+ rotation(
+ "escaped backslash in old key",
+ `[mcp_servers.context7]\nargs = ["${PACKAGE}", "--api-key", "OLD\\\\KEY"]\n`,
+ '"OLD\\\\KEY"'
+ ),
+ rotation(
+ "Unicode package escape",
+ `[mcp_servers.context7]\nargs = ["@upstash/context7-mcp\\u0040latest", "--api-key", "OLD"]\n`
+ ),
+];
+
+interface MutationCase {
+ name: string;
+ args: string;
+ apiKey: string | undefined;
+ expectedArgs: string;
+}
+
+const mutations: MutationCase[] = [
+ {
+ name: "adds a key",
+ args: `["${PACKAGE}"]`,
+ apiKey: "NEW",
+ expectedArgs: `["${PACKAGE}","--api-key","NEW"]`,
+ },
+ {
+ name: "adds a key to multiline args",
+ args: `[\n "-y",\n "${PACKAGE}@latest",\n]`,
+ apiKey: "NEW",
+ expectedArgs: `["-y","${PACKAGE}@latest","--api-key","NEW"]`,
+ },
+ {
+ name: "removes a key",
+ args: `["${PACKAGE}", "--api-key", "OLD"]`,
+ apiKey: undefined,
+ expectedArgs: `["${PACKAGE}"]`,
+ },
+ {
+ name: "removes a literal key",
+ args: `['${PACKAGE}', '--api-key', 'OLD']`,
+ apiKey: undefined,
+ expectedArgs: `["${PACKAGE}"]`,
+ },
+ {
+ name: "normalizes duplicate keys",
+ args: `["${PACKAGE}", "--api-key", "A", "--api-key", "B"]`,
+ apiKey: "NEW",
+ expectedArgs: `["${PACKAGE}","--api-key","NEW"]`,
+ },
+ {
+ name: "removes duplicate keys",
+ args: `["${PACKAGE}", "--api-key", "A", "--api-key", "B"]`,
+ apiKey: undefined,
+ expectedArgs: `["${PACKAGE}"]`,
+ },
+ {
+ name: "repairs a dangling key",
+ args: `["${PACKAGE}", "--api-key"]`,
+ apiKey: "NEW",
+ expectedArgs: `["${PACKAGE}","--api-key","NEW"]`,
+ },
+ {
+ name: "removes a dangling key",
+ args: `["${PACKAGE}", "--api-key"]`,
+ apiKey: undefined,
+ expectedArgs: `["${PACKAGE}"]`,
+ },
+ {
+ name: "preserves an already-current key",
+ args: `["${PACKAGE}", "--api-key", "NEW"]`,
+ apiKey: "NEW",
+ expectedArgs: `["${PACKAGE}", "--api-key", "NEW"]`,
+ },
+ {
+ name: "preserves flags while adding a key",
+ args: `["-y", "${PACKAGE}", "--debug"]`,
+ apiKey: "NEW",
+ expectedArgs: `["-y","${PACKAGE}","--debug","--api-key","NEW"]`,
+ },
+];
+
+const preservationVariants = [
+ { name: "working directory", suffix: `cwd = "/custom"\n` },
+ { name: "inline environment", suffix: `env = { FOO = "bar" }\n` },
+ { name: "environment subtable", suffix: `[mcp_servers.context7.env]\nFOO = "bar"\n` },
+ {
+ name: "HTTP headers subtable",
+ suffix: `[mcp_servers.context7.http_headers]\nX_TRACE = "enabled"\n`,
+ },
+ {
+ name: "following MCP server",
+ suffix: `[mcp_servers.filesystem]\ncommand = "uvx"\nargs = ["server-filesystem", "/tmp"]\n`,
+ },
+ { name: "following unrelated table", suffix: `[profiles.work]\nmodel = "gpt-5"\n` },
+ { name: "comments and blank lines", suffix: `# retain this comment\n\n` },
+ { name: "server options", suffix: `enabled = true\nstartup_timeout_sec = 30\n` },
+ { name: "TOML-looking string content", suffix: `env = { LABEL = "[global],#literal" }\n` },
+ {
+ name: "CRLF following server",
+ suffix: `\r\n[mcp_servers.other]\r\nurl = "https://example.com"\r\n`,
+ },
+] as const;
+
+interface OptionalSourceCase {
+ name: string;
+ source?: string;
+}
+
+interface SourceCase {
+ name: string;
+ source: string;
+}
+
+const absentTargets: OptionalSourceCase[] = [
+ { name: "missing file" },
+ { name: "empty file", source: "" },
+ { name: "different server", source: `[mcp_servers.other]\nargs = ["${PACKAGE}"]\n` },
+ {
+ name: "similar server name",
+ source: `[mcp_servers.context70]\nargs = ["${PACKAGE}", "--api-key", "OLD"]\n`,
+ },
+];
+
+const unsafeTargets: SourceCase[] = [
+ { name: "HTTP server", source: `[mcp_servers.context7]\nurl = "https://mcp.context7.com/mcp"\n` },
+ {
+ name: "quoted HTTP server",
+ source: `[mcp_servers."context7"]\nurl = "https://mcp.context7.com/mcp"\n`,
+ },
+ {
+ name: "different package",
+ source: `[mcp_servers.context7]\nargs = ["other-package", "--api-key", "OLD"]\n`,
+ },
+ {
+ name: "package only in comment",
+ source: `[mcp_servers.context7]\nargs = ["other-package"] # ${PACKAGE}\n`,
+ },
+ {
+ name: "package name with suffix",
+ source: `[mcp_servers.context7]\nargs = ["${PACKAGE}-lookalike", "--api-key", "OLD"]\n`,
+ },
+ {
+ name: "package name with prefix",
+ source: `[mcp_servers.context7]\nargs = ["evil-${PACKAGE}", "--api-key", "OLD"]\n`,
+ },
+ {
+ name: "package belongs to another server",
+ source: `[mcp_servers.context7]\nargs = ["other-package"]\n\n[mcp_servers.other]\nargs = ["${PACKAGE}"]\n`,
+ },
+ {
+ name: "target table and args inside a multiline string",
+ source: `description = """
+[mcp_servers.context7]
+args = ["${PACKAGE}", "--api-key", "DECOY"]
+[not-a-real-table]
+"""
+[mcp_servers.context7]
+args = ["${PACKAGE}", "--api-key", "REAL"]
+`,
+ },
+];
+
+const invalidArgs = [
+ { name: "number", value: `["${PACKAGE}", 42]` },
+ { name: "boolean", value: `["${PACKAGE}", true]` },
+ { name: "inline table", value: `["${PACKAGE}", { key = "value" }]` },
+ { name: "nested array", value: `["${PACKAGE}", ["nested"]]` },
+ { name: "unterminated array", value: `["${PACKAGE}"` },
+ { name: "unterminated basic string", value: `["${PACKAGE}", "broken]` },
+ { name: "unsupported escape", value: `["${PACKAGE}", "bad\\x"]` },
+ { name: "invalid Unicode escape", value: `["${PACKAGE}", "bad\\u12ZZ"]` },
+ { name: "multiline basic string", value: `["${PACKAGE}", "line\nbreak"]` },
+ { name: "missing args", value: null },
+] as const;
+
+const CONFIG_COUNT =
+ rotations.length +
+ mutations.length +
+ preservationVariants.length +
+ absentTargets.length +
+ unsafeTargets.length +
+ invalidArgs.length;
+if (CONFIG_COUNT !== 62) throw new Error(`Expected 62 TOML fixtures, received ${CONFIG_COUNT}`);
+
+describe("patchTomlStdioApiKey 62-config compatibility matrix", () => {
+ let tempDir: string;
+ let configPath: string;
+
+ beforeEach(async () => {
+ tempDir = await mkdtemp(join(tmpdir(), "ctx7-toml-editor-"));
+ configPath = join(tempDir, "config.toml");
+ });
+
+ afterEach(async () => {
+ await rm(tempDir, { recursive: true, force: true });
+ });
+
+ test.each(rotations)("rotates API key: $name", async ({ source, oldToken }) => {
+ await writeFile(configPath, source, "utf-8");
+
+ expect(await patchTomlStdioApiKey(configPath, "context7", "NEW")).toBe(true);
+ expect(await readFile(configPath, "utf-8")).toBe(source.replace(oldToken, '"NEW"'));
+ });
+
+ test.each(mutations)("changes API key shape: $name", async ({ args, apiKey, expectedArgs }) => {
+ const source = `[mcp_servers.context7]\ncommand = "npx"\nargs = ${args}\ncwd = "/keep"\n`;
+ await writeFile(configPath, source, "utf-8");
+
+ expect(await patchTomlStdioApiKey(configPath, "context7", apiKey)).toBe(true);
+ expect(await readFile(configPath, "utf-8")).toBe(
+ `[mcp_servers.context7]\ncommand = "npx"\nargs = ${expectedArgs}\ncwd = "/keep"\n`
+ );
+ });
+
+ test.each(preservationVariants)(
+ "preserves surrounding TOML byte-for-byte: $name",
+ async ({ suffix }) => {
+ const lineEnding = suffix.includes("\r\n") ? "\r\n" : "\n";
+ const source = `model = "gpt-5"${lineEnding}[mcp_servers.context7]${lineEnding}args = ["${PACKAGE}", "--api-key", "OLD"]${lineEnding}${suffix}`;
+ await writeFile(configPath, source, "utf-8");
+
+ expect(await patchTomlStdioApiKey(configPath, "context7", "NEW")).toBe(true);
+ expect(await readFile(configPath, "utf-8")).toBe(source.replace('"OLD"', '"NEW"'));
+ }
+ );
+
+ test.each(absentTargets)(
+ "leaves configs without the target unchanged: $name",
+ async ({ source }) => {
+ if (source !== undefined) await writeFile(configPath, source, "utf-8");
+
+ expect(await patchTomlStdioApiKey(configPath, "context7", "NEW")).toBe(false);
+ if (source !== undefined) expect(await readFile(configPath, "utf-8")).toBe(source);
+ }
+ );
+
+ test.each(unsafeTargets)(
+ "fails closed for an unsafe existing target: $name",
+ async ({ source }) => {
+ await writeFile(configPath, source, "utf-8");
+
+ await expect(patchTomlStdioApiKey(configPath, "context7", "NEW")).rejects.toThrow();
+ expect(await readFile(configPath, "utf-8")).toBe(source);
+ }
+ );
+
+ test.each(invalidArgs)("fails closed: $name", async ({ value }) => {
+ const source =
+ value === null
+ ? `[mcp_servers.context7]\ncommand = "custom-wrapper"\n`
+ : `[mcp_servers.context7]\ncommand = "npx"\nargs = ${value}\n`;
+ await writeFile(configPath, source, "utf-8");
+
+ await expect(patchTomlStdioApiKey(configPath, "context7", "NEW")).rejects.toThrow();
+ expect(await readFile(configPath, "utf-8")).toBe(source);
+ });
+});
diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.ts
index c5b8a3f7..c2aab8c2 100644
--- a/packages/cli/src/commands/setup.ts
+++ b/packages/cli/src/commands/setup.ts
@@ -30,7 +30,7 @@ import {
writeJsonConfig,
resolveMcpPath,
appendTomlServer,
- readTomlServerEntry,
+ patchTomlStdioApiKey,
isStdioContext7Entry,
patchStdioApiKey,
getJsonServerEntry,
@@ -315,10 +315,16 @@ async function setupAgent(
let mcpStatus: string;
try {
if (mcpPath.endsWith(".toml")) {
- const existingTomlEntry =
- transport === "stdio" ? await readTomlServerEntry(mcpPath, "context7") : undefined;
- const entry = resolveEntryToWrite(agent, auth, transport, existingTomlEntry);
- const { alreadyExists } = await appendTomlServer(mcpPath, "context7", entry);
+ const apiKey = auth.mode === "api-key" ? auth.apiKey : undefined;
+ const patched =
+ transport === "stdio" ? await patchTomlStdioApiKey(mcpPath, "context7", apiKey) : false;
+ const { alreadyExists } = patched
+ ? { alreadyExists: true }
+ : await appendTomlServer(
+ mcpPath,
+ "context7",
+ resolveEntryToWrite(agent, auth, transport, undefined)
+ );
mcpStatus = alreadyExists
? `reconfigured with ${AUTH_MODE_LABELS[auth.mode]}`
: `configured with ${AUTH_MODE_LABELS[auth.mode]}`;
diff --git a/packages/cli/src/setup/mcp-writer.ts b/packages/cli/src/setup/mcp-writer.ts
index 1c9ddf16..129b9c85 100644
--- a/packages/cli/src/setup/mcp-writer.ts
+++ b/packages/cli/src/setup/mcp-writer.ts
@@ -2,6 +2,8 @@ import { access, readFile, writeFile, mkdir } from "fs/promises";
import { dirname } from "path";
import { STDIO_PACKAGE } from "./agents.js";
+export { patchTomlStdioApiKey } from "./toml-editor.js";
+
function stripJsonComments(text: string): string {
let result = "";
let i = 0;
@@ -116,50 +118,6 @@ export async function readTomlServerExists(filePath: string, serverName: string)
}
}
-/**
- * Reads the top-level `[mcp_servers.<serverName>]` block from a TOML config
- * file and parses its key-value lines into a JS object. Handles string and
- * array values (TOML array syntax is JSON-compatible). Sub-tables like
- * `[mcp_servers.<serverName>.http_headers]` are ignored. Returns undefined
- * if the file or section is missing.
- */
-export async function readTomlServerEntry(
- filePath: string,
- serverName: string
-): Promise<Record<string, unknown> | undefined> {
- let raw: string;
- try {
- raw = await readFile(filePath, "utf-8");
- } catch {
- return undefined;
- }
-
- const sectionHeader = `[mcp_servers.${serverName}]`;
- const startIdx = raw.indexOf(sectionHeader);
- if (startIdx === -1) return undefined;
-
- // The top-level table's values live between its header and the next `[...]`
- // header (whether that's a sub-table like `[mcp_servers.foo.http_headers]`
- // or an unrelated section). Sub-table values belong to the sub-table, not
- // here, so excluding them is correct.
- const rest = raw.slice(startIdx + sectionHeader.length);
- const nextHeader = /^\[/m.exec(rest);
- const block = nextHeader ? rest.slice(0, nextHeader.index) : rest;
-
- const entry: Record<string, unknown> = {};
- const lineRe = /^([A-Za-z_][\w-]*)\s*=\s*(.+?)\s*$/gm;
- let lineMatch: RegExpExecArray | null;
- while ((lineMatch = lineRe.exec(block)) !== null) {
- const [, key, valueText] = lineMatch;
- try {
- entry[key] = JSON.parse(valueText);
- } catch {
- // Skip values we can't parse as JSON (e.g., bare TOML numbers like 20)
- }
- }
- return Object.keys(entry).length > 0 ? entry : undefined;
-}
-
/**
* True when `entry` looks like a stdio invocation of `@upstash/context7-mcp`
* (either `command: "npx", args: [..., "@upstash/context7-mcp", ...]` or
diff --git a/packages/cli/src/setup/toml-editor.ts b/packages/cli/src/setup/toml-editor.ts
new file mode 100644
index 00000000..e2065a42
--- /dev/null
+++ b/packages/cli/src/setup/toml-editor.ts
@@ -0,0 +1,213 @@
+import { mkdir, readFile, writeFile } from "fs/promises";
+import { dirname } from "path";
+import { STDIO_PACKAGE } from "./agents.js";
+
+interface TomlStringToken {
+ value: string;
+ start: number;
+ end: number;
+}
+
+const TOML_BASIC_ESCAPES: Readonly<Record<string, string>> = {
+ b: "\b",
+ t: "\t",
+ n: "\n",
+ f: "\f",
+ r: "\r",
+ '"': '"',
+ "\\": "\\",
+};
+
+function skipTomlArrayTrivia(source: string, start: number): number {
+ let index = start;
+ while (index < source.length) {
+ if (/\s/.test(source[index])) {
+ index++;
+ continue;
+ }
+ if (source[index] !== "#") break;
+ while (index < source.length && source[index] !== "\n") index++;
+ }
+ return index;
+}
+
+function parseTomlBasicString(source: string, start: number): TomlStringToken {
+ let value = "";
+ let index = start + 1;
+ while (index < source.length) {
+ const char = source[index++];
+ if (char === '"') return { value, start, end: index };
+ if (char === "\n" || char === "\r") {
+ throw new Error("Multiline strings are not supported in MCP args");
+ }
+ if (char !== "\\") {
+ value += char;
+ continue;
+ }
+
+ const escape = source[index++];
+ if (Object.hasOwn(TOML_BASIC_ESCAPES, escape)) {
+ value += TOML_BASIC_ESCAPES[escape];
+ continue;
+ }
+ if (escape !== "u" && escape !== "U") {
+ throw new Error(`Unsupported TOML escape \\${escape}`);
+ }
+
+ const width = escape === "u" ? 4 : 8;
+ const hex = source.slice(index, index + width);
+ if (!new RegExp(`^[0-9A-Fa-f]{${width}}$`).test(hex)) {
+ throw new Error(`Invalid TOML Unicode escape \\${escape}${hex}`);
+ }
+ const codePoint = Number.parseInt(hex, 16);
+ if (codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) {
+ throw new Error(`Invalid TOML Unicode code point U+${hex}`);
+ }
+ value += String.fromCodePoint(codePoint);
+ index += width;
+ }
+ throw new Error("Unterminated TOML basic string in MCP args");
+}
+
+function parseTomlLiteralString(source: string, start: number): TomlStringToken {
+ const endQuote = source.indexOf("'", start + 1);
+ if (endQuote === -1) throw new Error("Unterminated TOML literal string in MCP args");
+ const value = source.slice(start + 1, endQuote);
+ if (value.includes("\n") || value.includes("\r")) {
+ throw new Error("Multiline strings are not supported in MCP args");
+ }
+ return { value, start, end: endQuote + 1 };
+}
+
+function parseTomlStringArray(
+ source: string,
+ start: number
+): { tokens: TomlStringToken[]; end: number } {
+ if (source[start] !== "[") throw new Error("Expected a TOML array for MCP args");
+
+ const tokens: TomlStringToken[] = [];
+ let index = start + 1;
+ while (index < source.length) {
+ index = skipTomlArrayTrivia(source, index);
+ if (source[index] === "]") return { tokens, end: index + 1 };
+
+ const quote = source[index];
+ if (quote !== '"' && quote !== "'") {
+ throw new Error("MCP args must be a TOML array containing only strings");
+ }
+ if (source.slice(index, index + 3) === quote.repeat(3)) {
+ throw new Error("Multiline strings are not supported in MCP args");
+ }
+
+ const token =
+ quote === '"' ? parseTomlBasicString(source, index) : parseTomlLiteralString(source, index);
+ tokens.push(token);
+ index = skipTomlArrayTrivia(source, token.end);
+
+ if (source[index] === ",") {
+ index++;
+ continue;
+ }
+ if (source[index] !== "]") {
+ throw new Error("Expected a comma or closing bracket in MCP args");
+ }
+ }
+ throw new Error("Unterminated TOML array in MCP args");
+}
+
+function findTomlServerArgs(
+ raw: string,
+ serverName: string
+): { start: number; end: number; tokens: TomlStringToken[] } | null {
+ const escapedName = serverName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const tableKey = `(?:mcp_servers|"mcp_servers"|'mcp_servers')`;
+ const serverKey = `(?:${escapedName}|"${escapedName}"|'${escapedName}')`;
+ const headerRe = new RegExp(
+ `^[\\uFEFF\\t ]*\\[[\\t ]*${tableKey}[\\t ]*\\.[\\t ]*${serverKey}[\\t ]*\\][\\t ]*(?:#.*)?\\r?$`,
+ "m"
+ );
+ const header = headerRe.exec(raw);
+ if (!header) return null;
+
+ const bodyStart = raw.indexOf("\n", header.index + header[0].length) + 1;
+ const effectiveBodyStart = bodyStart === 0 ? raw.length : bodyStart;
+ const nextHeaderRe = /^[\t ]*\[[^\r\n]+\][\t ]*(?:#.*)?\r?$/gm;
+ nextHeaderRe.lastIndex = effectiveBodyStart;
+ const nextHeader = nextHeaderRe.exec(raw);
+ const bodyEnd = nextHeader?.index ?? raw.length;
+
+ const body = raw.slice(effectiveBodyStart, bodyEnd);
+ const argsRe = /^[\t ]*(?:args|"args"|'args')[\t ]*=[\t ]*/gm;
+ const args = argsRe.exec(body);
+ if (!args) {
+ throw new Error("Existing MCP server has no safely editable args array");
+ }
+
+ const start = effectiveBodyStart + args.index + args[0].length;
+ const parsed = parseTomlStringArray(raw, start);
+ return { start, end: parsed.end, tokens: parsed.tokens };
+}
+
+function withoutApiKey(args: string[]): string[] {
+ const result: string[] = [];
+ for (let index = 0; index < args.length; index++) {
+ if (args[index] === "--api-key") {
+ index++;
+ continue;
+ }
+ result.push(args[index]);
+ }
+ return result;
+}
+
+function isContext7Package(arg: string): boolean {
+ return arg === STDIO_PACKAGE || arg.startsWith(`${STDIO_PACKAGE}@`);
+}
+
+/**
+ * Updates only the `args` value of an existing Context7 stdio TOML entry.
+ * Every other byte in the config is preserved. Unsupported `args` syntax
+ * throws instead of allowing setup to replace a configuration it cannot read.
+ * Returns false only when the requested server table is absent.
+ */
+export async function patchTomlStdioApiKey(
+ filePath: string,
+ serverName: string,
+ apiKey: string | undefined
+): Promise<boolean> {
+ let raw: string;
+ try {
+ raw = await readFile(filePath, "utf-8");
+ } catch {
+ return false;
+ }
+
+ if (raw.includes('"""') || raw.includes("'''")) {
+ throw new Error("TOML files containing multiline strings are not safely editable");
+ }
+
+ const range = findTomlServerArgs(raw, serverName);
+ if (!range) return false;
+
+ const args = range.tokens.map((token) => token.value);
+ if (!args.some(isContext7Package)) {
+ throw new Error(`Existing MCP args do not invoke ${STDIO_PACKAGE}`);
+ }
+
+ const apiKeyIndexes = args.flatMap((arg, index) => (arg === "--api-key" ? [index] : []));
+ let content: string;
+ if (apiKey && apiKeyIndexes.length === 1 && apiKeyIndexes[0] + 1 < range.tokens.length) {
+ const valueToken = range.tokens[apiKeyIndexes[0] + 1];
+ content = raw.slice(0, valueToken.start) + JSON.stringify(apiKey) + raw.slice(valueToken.end);
+ } else {
+ const patched = withoutApiKey(args);
+ if (apiKey) patched.push("--api-key", apiKey);
+ content = raw.slice(0, range.start) + JSON.stringify(patched) + raw.slice(range.end);
+ }
+
+ if (content !== raw) {
+ await mkdir(dirname(filePath), { recursive: true });
+ await writeFile(filePath, content, "utf-8");
+ }
+ return true;
+}