Skip to content

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

fix(cli): preserve OpenCode configuration comments and trailing commas (#3201)

Matthew Skovranek323bda95a613
diff --git a/.changeset/opencode-keep-comments.md b/.changeset/opencode-keep-comments.md
new file mode 100644
index 00000000..6d53aada
--- /dev/null
+++ b/.changeset/opencode-keep-comments.md
@@ -0,0 +1,5 @@
+---
+"ctx7": patch
+---
+
+Keep the comments and trailing commas in an OpenCode config file when `ctx7 setup` or `ctx7 remove` edits it.
diff --git a/packages/cli/src/__tests__/opencode-editor.test.ts b/packages/cli/src/__tests__/opencode-editor.test.ts
new file mode 100644
index 00000000..df475ed2
--- /dev/null
+++ b/packages/cli/src/__tests__/opencode-editor.test.ts
@@ -0,0 +1,93 @@
+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 { editOpenCodeServer } from "../setup/opencode-editor.js";
+import { readJsonConfig } from "../setup/mcp-writer.js";
+
+let path: string;
+
+beforeEach(async () => {
+ path = join(await mkdtemp(join(tmpdir(), "ctx7-opencode-")), "opencode.jsonc");
+});
+
+afterEach(async () => {
+ await rm(join(path, ".."), { recursive: true, force: true });
+});
+
+const entry = { type: "remote", url: "https://mcp.context7.com/mcp", enabled: true };
+
+describe("editOpenCodeServer", () => {
+ test("replaces the entry and keeps comments and trailing commas outside it", async () => {
+ await writeFile(
+ path,
+ `// personal configuration
+{
+ "theme": "night", // dark
+ "mcp": {
+ // work server
+ "other": { "type": "remote", "url": "https://other.example", },
+ "context7": { "type": "local", "command": ["npx", "old"], },
+ },
+}
+`
+ );
+
+ await editOpenCodeServer(path, entry);
+
+ const updated = await readFile(path, "utf-8");
+ expect(updated).toContain("// personal configuration");
+ expect(updated).toContain("// dark");
+ expect(updated).toContain("// work server");
+ expect(updated).toContain('"other": { "type": "remote", "url": "https://other.example", },');
+ expect(await readJsonConfig(path)).toEqual({
+ theme: "night",
+ mcp: { other: { type: "remote", url: "https://other.example" }, context7: entry },
+ });
+ });
+
+ test("adds an indented entry to a file without an mcp section", async () => {
+ await writeFile(path, '{\n // keep\n "theme": "night",\n}\n');
+
+ await editOpenCodeServer(path, entry);
+
+ const updated = await readFile(path, "utf-8");
+ expect(updated).toContain("// keep");
+ expect(updated).toContain('\n "mcp": {\n "context7": {\n "type": "remote",\n');
+ expect(await readJsonConfig(path)).toEqual({ theme: "night", mcp: { context7: entry } });
+ });
+
+ test.each([
+ ["a missing file", undefined],
+ ["an empty file", ""],
+ ["a file with only a byte order mark", "\uFEFF\r\n"],
+ ])("writes a new formatted config to %s", async (_name, source) => {
+ if (source !== undefined) await writeFile(path, source);
+
+ await editOpenCodeServer(path, entry);
+
+ expect(await readFile(path, "utf-8")).toBe(
+ JSON.stringify({ mcp: { context7: entry } }, null, 2) + "\n"
+ );
+ });
+
+ test("edits a file that starts with a byte order mark", async () => {
+ await writeFile(path, '\uFEFF{\n "theme": "night",\n}\n');
+
+ await editOpenCodeServer(path, entry);
+
+ expect(await readJsonConfig(path)).toEqual({ theme: "night", mcp: { context7: entry } });
+ });
+
+ test("removes the only entry before a trailing comma and leaves valid JSONC", async () => {
+ await writeFile(
+ path,
+ '{\n // keep\n "mcp": {\n "context7": { "enabled": true },\n },\n}\n'
+ );
+
+ await editOpenCodeServer(path);
+
+ expect(await readFile(path, "utf-8")).toContain("// keep");
+ expect(await readJsonConfig(path)).toEqual({ mcp: {} });
+ });
+});
diff --git a/packages/cli/src/__tests__/remove.test.ts b/packages/cli/src/__tests__/remove.test.ts
index 9d256e0f..1d86c412 100644
--- a/packages/cli/src/__tests__/remove.test.ts
+++ b/packages/cli/src/__tests__/remove.test.ts
@@ -3,6 +3,7 @@ import { Command } from "commander";
import { mkdir, readFile, writeFile, rm, access } from "fs/promises";
import { join } from "path";
import { tmpdir } from "os";
+import { readJsonConfig } from "../setup/mcp-writer.js";
const trackEvent = vi.fn();
const mockCheckboxWithHover = vi.fn();
@@ -413,9 +414,10 @@ describe("remove command", () => {
// keep this file functional after removing Context7
"theme": "night",
"mcp": {
+ // first server
"alpha": { "type": "remote", "url": "https://alpha.com", "enabled": true },
"context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "enabled": true },
- "omega": { "type": "remote", "url": "https://omega.com", "enabled": false }
+ "omega": { "type": "remote", "url": "https://omega.com", "enabled": false },
},
"telemetry": { "enabled": true }
}
@@ -425,7 +427,13 @@ describe("remove command", () => {
await runCommand("remove", "--opencode", "--mcp", "--project");
- expect(JSON.parse(await readFile(configPath, "utf-8"))).toEqual({
+ const updated = await readFile(configPath, "utf-8");
+ expect(updated).toContain("// keep this file functional after removing Context7");
+ expect(updated).toContain("// first server");
+ expect(updated).toContain(
+ '"omega": { "type": "remote", "url": "https://omega.com", "enabled": false },'
+ );
+ expect(await readJsonConfig(configPath)).toEqual({
theme: "night",
mcp: {
alpha: { type: "remote", url: "https://alpha.com", enabled: true },
diff --git a/packages/cli/src/commands/remove.ts b/packages/cli/src/commands/remove.ts
index 02bc8433..899cba4f 100644
--- a/packages/cli/src/commands/remove.ts
+++ b/packages/cli/src/commands/remove.ts
@@ -13,6 +13,7 @@ import {
resolveMcpPath,
removeTomlServer,
} from "../setup/mcp-writer.js";
+import { editOpenCodeServer } from "../setup/opencode-editor.js";
import { join } from "path";
import { access, readFile, rm, writeFile } from "fs/promises";
@@ -331,7 +332,8 @@ async function uninstallMcp(agentName: SetupAgent, scope: Scope): Promise<Cleanu
const existing = await readJsonConfig(mcpPath);
const { config, removed } = removeServerEntry(existing, agent.mcp.configKey, "context7");
if (removed) {
- await writeJsonConfig(mcpPath, config);
+ if (agentName === "opencode") await editOpenCodeServer(mcpPath);
+ else await writeJsonConfig(mcpPath, config);
}
return { status: removed ? "removed" : "not found", path: mcpPath };
} catch (err) {
diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.ts
index 42ba06b5..4f9c5b76 100644
--- a/packages/cli/src/commands/setup.ts
+++ b/packages/cli/src/commands/setup.ts
@@ -48,6 +48,7 @@ import {
patchStdioApiKey,
getJsonServerEntry,
} from "../setup/mcp-writer.js";
+import { editOpenCodeServer } from "../setup/opencode-editor.js";
type Scope = "global" | "project";
type SetupMode = "mcp" | "cli";
@@ -400,7 +401,8 @@ async function setupAgent(
mcpStatus = alreadyExists
? `reconfigured with ${AUTH_MODE_LABELS[auth.mode]}`
: `configured with ${AUTH_MODE_LABELS[auth.mode]}`;
- await writeJsonConfig(mcpPath, config);
+ if (agentName === "opencode") await editOpenCodeServer(mcpPath, entry);
+ else await writeJsonConfig(mcpPath, config);
}
} catch (err) {
mcpStatus = `failed: ${err instanceof Error ? err.message : String(err)}`;
diff --git a/packages/cli/src/setup/opencode-editor.ts b/packages/cli/src/setup/opencode-editor.ts
new file mode 100644
index 00000000..6c313bf4
--- /dev/null
+++ b/packages/cli/src/setup/opencode-editor.ts
@@ -0,0 +1,27 @@
+import { mkdir, readFile, writeFile } from "fs/promises";
+import { dirname } from "path";
+import { applyEdits, modify } from "jsonc-parser";
+import { readJsonConfig } from "./mcp-writer.js";
+
+const options = { formattingOptions: { tabSize: 2, insertSpaces: true } };
+
+/**
+ * Sets `mcp.context7` to `entry`, or removes it when `entry` is omitted. Edits the
+ * file text in place, so comments and trailing commas outside the entry survive.
+ */
+export async function editOpenCodeServer(
+ filePath: string,
+ entry?: Record<string, unknown>
+): Promise<void> {
+ const servers = Object.keys(((await readJsonConfig(filePath)).mcp ?? {}) as object);
+ const raw = await readFile(filePath, "utf-8").catch(() => "");
+ const source = raw.trim() ? raw : "{}\n";
+ // modify() leaves `{ , }` when it deletes the only property of an object that
+ // has a trailing comma, so empty the `mcp` object instead.
+ const edits =
+ !entry && servers.join() === "context7"
+ ? modify(source, ["mcp"], {}, options)
+ : modify(source, ["mcp", "context7"], entry, options);
+ await mkdir(dirname(filePath), { recursive: true });
+ await writeFile(filePath, applyEdits(source, edits), "utf-8");
+}