Skip to content

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

fix(setup): remove already configured state from ctx7 setup (#2344)

Fahreddin Özcan6961bdd4fb41
diff --git a/.changeset/remove-already-configured-state.md b/.changeset/remove-already-configured-state.md
new file mode 100644
index 00000000..5dc9b47d
--- /dev/null
+++ b/.changeset/remove-already-configured-state.md
@@ -0,0 +1,5 @@
+---
+"ctx7": patch
+---
+
+Allow re-selecting already configured agents in ctx7 setup and overwrite existing MCP config entries instead of skipping them. Fix TOML replacement to correctly handle sub-sections and prevent whitespace drift on repeated runs.
diff --git a/packages/cli/src/__tests__/setup.test.ts b/packages/cli/src/__tests__/setup.test.ts
index 22de5fd6..8620d4c6 100644
--- a/packages/cli/src/__tests__/setup.test.ts
+++ b/packages/cli/src/__tests__/setup.test.ts
@@ -29,6 +29,7 @@ import {
appendTomlServer,
resolveMcpPath,
} from "../setup/mcp-writer.js";
+import { getAgent, ALL_AGENT_NAMES, type AuthOptions } from "../setup/agents.js";
describe("getRuleContent", () => {
test("returns correct content per mode", async () => {
@@ -92,13 +93,50 @@ describe("mergeServerEntry", () => {
expect(servers.other).toEqual({ url: "https://other.com" });
});
- test("does not overwrite existing server", () => {
+ test("overwrites existing server and flags alreadyExists", () => {
const existing = { mcpServers: { context7: { url: "https://old.com" } } };
const { config, alreadyExists } = mergeServerEntry(existing, "mcpServers", "context7", {
url: "https://new.com",
});
expect(alreadyExists).toBe(true);
- expect(config).toBe(existing);
+ expect((config.mcpServers as Record<string, unknown>).context7).toEqual({
+ url: "https://new.com",
+ });
+ });
+
+ test("overwrites existing server entry with new url", () => {
+ const existing = {
+ mcpServers: {
+ context7: { url: "https://old.com", headers: { key: "old-key" } },
+ other: { url: "https://other.com" },
+ },
+ };
+ const { config, alreadyExists } = mergeServerEntry(existing, "mcpServers", "context7", {
+ url: "https://mcp.context7.com/mcp",
+ headers: { key: "new-key" },
+ });
+ expect(alreadyExists).toBe(true);
+ const servers = config.mcpServers as Record<string, unknown>;
+ expect(servers.context7).toEqual({
+ url: "https://mcp.context7.com/mcp",
+ headers: { key: "new-key" },
+ });
+ expect(servers.other).toEqual({ url: "https://other.com" });
+ });
+
+ test("overwrites existing server entry with different auth mode", () => {
+ const existing = {
+ mcpServers: {
+ context7: { url: "https://mcp.context7.com/mcp", headers: { "x-api-key": "old" } },
+ },
+ };
+ const { config, alreadyExists } = mergeServerEntry(existing, "mcpServers", "context7", {
+ url: "https://mcp.context7.com/mcp",
+ });
+ expect(alreadyExists).toBe(true);
+ expect((config.mcpServers as Record<string, unknown>).context7).toEqual({
+ url: "https://mcp.context7.com/mcp",
+ });
});
test("works with opencode configKey 'mcp'", () => {
@@ -273,6 +311,85 @@ describe("TOML config", () => {
const content = await readFile(path, "utf-8");
expect(content.match(/\[mcp_servers\.context7\]/g)?.length).toBe(1);
});
+
+ test("appendTomlServer overwrites existing server with new url", async () => {
+ const path = join(tempDir, "config.toml");
+ await appendTomlServer(path, "context7", { url: "https://old.com" });
+ const { alreadyExists } = await appendTomlServer(path, "context7", {
+ url: "https://mcp.context7.com/mcp",
+ });
+ expect(alreadyExists).toBe(true);
+ const content = await readFile(path, "utf-8");
+ expect(content.match(/\[mcp_servers\.context7\]/g)?.length).toBe(1);
+ expect(content).toContain('url = "https://mcp.context7.com/mcp"');
+ expect(content).not.toContain("https://old.com");
+ });
+
+ test("appendTomlServer overwrites server without affecting other servers", async () => {
+ const path = join(tempDir, "config.toml");
+ await writeFile(
+ path,
+ '[mcp_servers.context7]\nurl = "https://old.com"\n\n[mcp_servers.other]\nurl = "https://other.com"\n'
+ );
+ await appendTomlServer(path, "context7", { url: "https://mcp.context7.com/mcp" });
+ const content = await readFile(path, "utf-8");
+ expect(content).toContain('url = "https://mcp.context7.com/mcp"');
+ expect(content).not.toContain("https://old.com");
+ expect(content).toContain("[mcp_servers.other]");
+ expect(content).toContain('url = "https://other.com"');
+ });
+
+ test("appendTomlServer overwrites server that appears before non-mcp sections", async () => {
+ const path = join(tempDir, "config.toml");
+ await writeFile(
+ path,
+ 'model = "gpt-5"\n\n[mcp_servers.context7]\nurl = "https://old.com"\n\n[some_other_section]\nkey = "value"\n'
+ );
+ await appendTomlServer(path, "context7", {
+ url: "https://mcp.context7.com/mcp",
+ headers: { "x-api-key": "sk-new" },
+ });
+ const content = await readFile(path, "utf-8");
+ expect(content).toContain('model = "gpt-5"');
+ expect(content).toContain('url = "https://mcp.context7.com/mcp"');
+ expect(content).toContain("[mcp_servers.context7.http_headers]");
+ expect(content).toContain('x-api-key = "sk-new"');
+ expect(content).not.toContain("https://old.com");
+ expect(content).toContain("[some_other_section]");
+ expect(content).toContain('key = "value"');
+ });
+
+ test("appendTomlServer overwrites server at end of file", async () => {
+ const path = join(tempDir, "config.toml");
+ await writeFile(
+ path,
+ '[mcp_servers.other]\nurl = "https://other.com"\n\n[mcp_servers.context7]\nurl = "https://old.com"\n'
+ );
+ await appendTomlServer(path, "context7", { url: "https://new.com" });
+ const content = await readFile(path, "utf-8");
+ expect(content).toContain("[mcp_servers.other]");
+ expect(content).toContain('url = "https://new.com"');
+ expect(content).not.toContain("https://old.com");
+ expect(content.match(/\[mcp_servers\.context7\]/g)?.length).toBe(1);
+ });
+
+ test("appendTomlServer does not accumulate blank lines on repeated overwrites", async () => {
+ const path = join(tempDir, "config.toml");
+ await writeFile(
+ path,
+ 'model = "o3"\n\n[mcp_servers.context7]\nurl = "https://old.com"\n\n[mcp_servers.other]\nurl = "https://other.com"\n'
+ );
+
+ for (let i = 1; i <= 3; i++) {
+ await appendTomlServer(path, "context7", { url: `https://v${i}.com` });
+ }
+
+ const content = await readFile(path, "utf-8");
+ expect(content.match(/\[mcp_servers\.context7\]/g)?.length).toBe(1);
+ expect(content).toContain('url = "https://v3.com"');
+ expect(content).toContain("[mcp_servers.other]");
+ expect(content).not.toContain("\n\n\n");
+ });
});
describe("AGENTS.md append", () => {
@@ -301,9 +418,7 @@ describe("AGENTS.md append", () => {
let content = "";
try {
content = await readFile(filePath, "utf-8");
- } catch {
- // doesn't exist
- }
+ } catch {}
if (content.includes(marker)) {
const regex = new RegExp(`${escapedMarker}\\n[\\s\\S]*?${escapedMarker}`);
@@ -351,3 +466,356 @@ describe("AGENTS.md append", () => {
expect(result).toContain(ruleContent);
});
});
+
+describe("agent config integration", () => {
+ let tempDir: string;
+
+ beforeEach(async () => {
+ tempDir = join(tmpdir(), `ctx7-agent-cfg-${Date.now()}`);
+ await mkdir(tempDir, { recursive: true });
+ });
+
+ afterEach(async () => {
+ await rm(tempDir, { recursive: true, force: true });
+ });
+
+ const apiKeyAuth: AuthOptions = { mode: "api-key", apiKey: "sk-test-123" };
+ const oauthAuth: AuthOptions = { mode: "oauth" };
+
+ describe("claude", () => {
+ const agent = getAgent("claude");
+
+ test("buildEntry with api-key produces correct shape", () => {
+ const entry = agent.mcp.buildEntry(apiKeyAuth);
+ expect(entry).toEqual({
+ type: "http",
+ url: "https://mcp.context7.com/mcp",
+ headers: { CONTEXT7_API_KEY: "sk-test-123" },
+ });
+ });
+
+ test("buildEntry with oauth produces correct shape", () => {
+ const entry = agent.mcp.buildEntry(oauthAuth);
+ expect(entry).toEqual({
+ type: "http",
+ url: "https://mcp.context7.com/mcp/oauth",
+ });
+ });
+
+ test("merges into JSON config with configKey mcpServers", async () => {
+ const path = join(tempDir, ".claude.json");
+ const existing = await readJsonConfig(path);
+ const { config } = mergeServerEntry(
+ existing,
+ agent.mcp.configKey,
+ "context7",
+ agent.mcp.buildEntry(apiKeyAuth)
+ );
+ await writeJsonConfig(path, config);
+
+ const result = await readJsonConfig(path);
+ const servers = result.mcpServers as Record<string, unknown>;
+ expect(servers.context7).toEqual({
+ type: "http",
+ url: "https://mcp.context7.com/mcp",
+ headers: { CONTEXT7_API_KEY: "sk-test-123" },
+ });
+ });
+
+ test("overwrites existing config in JSON", async () => {
+ const path = join(tempDir, ".claude.json");
+ await writeJsonConfig(path, {
+ mcpServers: { context7: { type: "http", url: "https://old.com" } },
+ });
+
+ const existing = await readJsonConfig(path);
+ const { config, alreadyExists } = mergeServerEntry(
+ existing,
+ agent.mcp.configKey,
+ "context7",
+ agent.mcp.buildEntry(apiKeyAuth)
+ );
+ expect(alreadyExists).toBe(true);
+ await writeJsonConfig(path, config);
+
+ const result = await readJsonConfig(path);
+ expect((result.mcpServers as Record<string, unknown>).context7).toEqual({
+ type: "http",
+ url: "https://mcp.context7.com/mcp",
+ headers: { CONTEXT7_API_KEY: "sk-test-123" },
+ });
+ });
+ });
+
+ describe("cursor", () => {
+ const agent = getAgent("cursor");
+
+ test("buildEntry with api-key produces correct shape (no type field)", () => {
+ const entry = agent.mcp.buildEntry(apiKeyAuth);
+ expect(entry).toEqual({
+ url: "https://mcp.context7.com/mcp",
+ headers: { CONTEXT7_API_KEY: "sk-test-123" },
+ });
+ expect(entry).not.toHaveProperty("type");
+ });
+
+ test("buildEntry with oauth produces correct shape", () => {
+ const entry = agent.mcp.buildEntry(oauthAuth);
+ expect(entry).toEqual({
+ url: "https://mcp.context7.com/mcp/oauth",
+ });
+ });
+
+ test("merges into JSON config with configKey mcpServers", async () => {
+ const path = join(tempDir, "mcp.json");
+ const existing = await readJsonConfig(path);
+ const { config } = mergeServerEntry(
+ existing,
+ agent.mcp.configKey,
+ "context7",
+ agent.mcp.buildEntry(oauthAuth)
+ );
+ await writeJsonConfig(path, config);
+
+ const result = await readJsonConfig(path);
+ expect((result.mcpServers as Record<string, unknown>).context7).toEqual({
+ url: "https://mcp.context7.com/mcp/oauth",
+ });
+ });
+
+ test("overwrites existing config in JSON", async () => {
+ const path = join(tempDir, "mcp.json");
+ await writeJsonConfig(path, {
+ mcpServers: { context7: { url: "https://old.com" }, other: { url: "https://other.com" } },
+ });
+
+ const existing = await readJsonConfig(path);
+ const { config, alreadyExists } = mergeServerEntry(
+ existing,
+ agent.mcp.configKey,
+ "context7",
+ agent.mcp.buildEntry(apiKeyAuth)
+ );
+ expect(alreadyExists).toBe(true);
+ await writeJsonConfig(path, config);
+
+ const result = await readJsonConfig(path);
+ const servers = result.mcpServers as Record<string, unknown>;
+ expect(servers.context7).toEqual({
+ url: "https://mcp.context7.com/mcp",
+ headers: { CONTEXT7_API_KEY: "sk-test-123" },
+ });
+ expect(servers.other).toEqual({ url: "https://other.com" });
+ });
+ });
+
+ describe("opencode", () => {
+ const agent = getAgent("opencode");
+
+ test("buildEntry with api-key includes type, url, enabled, and headers", () => {
+ const entry = agent.mcp.buildEntry(apiKeyAuth);
+ expect(entry).toEqual({
+ type: "remote",
+ url: "https://mcp.context7.com/mcp",
+ enabled: true,
+ headers: { CONTEXT7_API_KEY: "sk-test-123" },
+ });
+ });
+
+ test("buildEntry with oauth includes type, url, enabled without headers", () => {
+ const entry = agent.mcp.buildEntry(oauthAuth);
+ expect(entry).toEqual({
+ type: "remote",
+ url: "https://mcp.context7.com/mcp/oauth",
+ enabled: true,
+ });
+ });
+
+ test("uses configKey 'mcp' instead of 'mcpServers'", () => {
+ expect(agent.mcp.configKey).toBe("mcp");
+ });
+
+ test("merges into JSON config with configKey mcp", async () => {
+ const path = join(tempDir, "opencode.json");
+ await writeJsonConfig(path, { $schema: "https://opencode.ai/config.json" });
+
+ const existing = await readJsonConfig(path);
+ const { config } = mergeServerEntry(
+ existing,
+ agent.mcp.configKey,
+ "context7",
+ agent.mcp.buildEntry(apiKeyAuth)
+ );
+ await writeJsonConfig(path, config);
+
+ const result = await readJsonConfig(path);
+ expect(result.$schema).toBe("https://opencode.ai/config.json");
+ expect((result.mcp as Record<string, unknown>).context7).toEqual({
+ type: "remote",
+ url: "https://mcp.context7.com/mcp",
+ enabled: true,
+ headers: { CONTEXT7_API_KEY: "sk-test-123" },
+ });
+ });
+
+ test("overwrites existing config in JSON", async () => {
+ const path = join(tempDir, "opencode.json");
+ await writeJsonConfig(path, {
+ mcp: { context7: { type: "remote", url: "https://old.com", enabled: true } },
+ });
+
+ const existing = await readJsonConfig(path);
+ const { config, alreadyExists } = mergeServerEntry(
+ existing,
+ agent.mcp.configKey,
+ "context7",
+ agent.mcp.buildEntry(oauthAuth)
+ );
+ expect(alreadyExists).toBe(true);
+ await writeJsonConfig(path, config);
+
+ const result = await readJsonConfig(path);
+ expect((result.mcp as Record<string, unknown>).context7).toEqual({
+ type: "remote",
+ url: "https://mcp.context7.com/mcp/oauth",
+ enabled: true,
+ });
+ });
+
+ test("works with JSONC files containing comments", async () => {
+ const path = join(tempDir, "opencode.jsonc");
+ await writeFile(
+ path,
+ `{
+ // OpenCode config
+ "$schema": "https://opencode.ai/config.json",
+ "mcp": {}
+}`,
+ "utf-8"
+ );
+
+ const existing = await readJsonConfig(path);
+ const { config } = mergeServerEntry(
+ existing,
+ agent.mcp.configKey,
+ "context7",
+ agent.mcp.buildEntry(apiKeyAuth)
+ );
+ await writeJsonConfig(path, config);
+
+ const result = await readJsonConfig(path);
+ expect(result.$schema).toBe("https://opencode.ai/config.json");
+ expect((result.mcp as Record<string, unknown>).context7).toBeTruthy();
+ });
+ });
+
+ describe("codex", () => {
+ const agent = getAgent("codex");
+
+ test("buildEntry with api-key produces correct shape", () => {
+ const entry = agent.mcp.buildEntry(apiKeyAuth);
+ expect(entry).toEqual({
+ type: "http",
+ url: "https://mcp.context7.com/mcp",
+ headers: { CONTEXT7_API_KEY: "sk-test-123" },
+ });
+ });
+
+ test("buildEntry with oauth produces correct shape", () => {
+ const entry = agent.mcp.buildEntry(oauthAuth);
+ expect(entry).toEqual({
+ type: "http",
+ url: "https://mcp.context7.com/mcp/oauth",
+ });
+ });
+
+ test("appends to TOML config", async () => {
+ const path = join(tempDir, "config.toml");
+ const { alreadyExists } = await appendTomlServer(
+ path,
+ "context7",
+ agent.mcp.buildEntry(apiKeyAuth)
+ );
+ expect(alreadyExists).toBe(false);
+
+ const content = await readFile(path, "utf-8");
+ expect(content).toContain("[mcp_servers.context7]");
+ expect(content).toContain('type = "http"');
+ expect(content).toContain('url = "https://mcp.context7.com/mcp"');
+ expect(content).toContain("[mcp_servers.context7.http_headers]");
+ expect(content).toContain('CONTEXT7_API_KEY = "sk-test-123"');
+ });
+
+ test("appends oauth entry to TOML without headers", async () => {
+ const path = join(tempDir, "config.toml");
+ await appendTomlServer(path, "context7", agent.mcp.buildEntry(oauthAuth));
+
+ const content = await readFile(path, "utf-8");
+ expect(content).toContain("[mcp_servers.context7]");
+ expect(content).toContain('url = "https://mcp.context7.com/mcp/oauth"');
+ expect(content).not.toContain("http_headers");
+ });
+
+ test("overwrites existing TOML config", async () => {
+ const path = join(tempDir, "config.toml");
+ await appendTomlServer(path, "context7", agent.mcp.buildEntry(oauthAuth));
+ const { alreadyExists } = await appendTomlServer(
+ path,
+ "context7",
+ agent.mcp.buildEntry(apiKeyAuth)
+ );
+
+ expect(alreadyExists).toBe(true);
+ const content = await readFile(path, "utf-8");
+ expect(content.match(/\[mcp_servers\.context7\]/g)?.length).toBe(1);
+ expect(content).toContain('url = "https://mcp.context7.com/mcp"');
+ expect(content).not.toContain("mcp/oauth");
+ expect(content).toContain('CONTEXT7_API_KEY = "sk-test-123"');
+ });
+
+ test("overwrites TOML config preserving other servers", async () => {
+ const path = join(tempDir, "config.toml");
+ await writeFile(
+ path,
+ '[mcp_servers.other]\nurl = "https://other.com"\n\n[mcp_servers.context7]\ntype = "http"\nurl = "https://old.com"\n'
+ );
+ await appendTomlServer(path, "context7", agent.mcp.buildEntry(apiKeyAuth));
+
+ const content = await readFile(path, "utf-8");
+ expect(content).toContain("[mcp_servers.other]");
+ expect(content).toContain('url = "https://other.com"');
+ expect(content).toContain('url = "https://mcp.context7.com/mcp"');
+ expect(content).not.toContain("https://old.com");
+ });
+ });
+
+ describe("all agents have consistent config", () => {
+ test("all agents are covered", () => {
+ expect(ALL_AGENT_NAMES).toEqual(["claude", "cursor", "opencode", "codex"]);
+ });
+
+ test.each(ALL_AGENT_NAMES)("%s buildEntry returns url for both auth modes", (name) => {
+ const agent = getAgent(name);
+ const apiEntry = agent.mcp.buildEntry(apiKeyAuth);
+ const oauthEntry = agent.mcp.buildEntry(oauthAuth);
+
+ expect(apiEntry.url).toBe("https://mcp.context7.com/mcp");
+ expect(oauthEntry.url).toBe("https://mcp.context7.com/mcp/oauth");
+ });
+
+ test.each(ALL_AGENT_NAMES)("%s buildEntry includes headers only for api-key auth", (name) => {
+ const agent = getAgent(name);
+ const apiEntry = agent.mcp.buildEntry(apiKeyAuth);
+ const oauthEntry = agent.mcp.buildEntry(oauthAuth);
+
+ expect(apiEntry.headers).toEqual({ CONTEXT7_API_KEY: "sk-test-123" });
+ expect(oauthEntry).not.toHaveProperty("headers");
+ });
+
+ test.each(ALL_AGENT_NAMES)("%s buildEntry without apiKey omits headers", (name) => {
+ const agent = getAgent(name);
+ const entry = agent.mcp.buildEntry({ mode: "api-key" });
+ expect(entry).not.toHaveProperty("headers");
+ });
+ });
+});
diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.ts
index 3f15b7b3..dcaeffab 100644
--- a/packages/cli/src/commands/setup.ts
+++ b/packages/cli/src/commands/setup.ts
@@ -172,42 +172,11 @@ async function resolveCliAuth(apiKey?: string): Promise<void> {
await performLogin();
}
-async function isAlreadyConfigured(agentName: SetupAgent, scope: Scope): Promise<boolean> {
- const agent = getAgent(agentName);
- const mcpCandidates =
- scope === "global"
- ? agent.mcp.globalPaths
- : agent.mcp.projectPaths.map((p) => join(process.cwd(), p));
- const mcpPath = await resolveMcpPath(mcpCandidates);
- try {
- if (mcpPath.endsWith(".toml")) {
- const { readTomlServerExists } = await import("../setup/mcp-writer.js");
- return readTomlServerExists(mcpPath, "context7");
- }
- const existing = await readJsonConfig(mcpPath);
- const section = (existing[agent.mcp.configKey] as Record<string, unknown> | undefined) ?? {};
- return "context7" in section;
- } catch {
- return false;
- }
-}
-
-async function promptAgents(scope: Scope, mode: SetupMode): Promise<SetupAgent[] | null> {
- const choices = await Promise.all(
- ALL_AGENT_NAMES.map(async (name) => {
- const configured = mode === "mcp" ? await isAlreadyConfigured(name, scope) : false;
- return {
- name: SETUP_AGENT_NAMES[name],
- value: name,
- disabled: configured ? "(already configured)" : false,
- };
- })
- );
-
- if (choices.every((c) => c.disabled)) {
- log.info("Context7 is already configured for all detected agents.");
- return null;
- }
+async function promptAgents(): Promise<SetupAgent[] | null> {
+ const choices = ALL_AGENT_NAMES.map((name) => ({
+ name: SETUP_AGENT_NAMES[name],
+ value: name,
+ }));
const message = "Which agents do you want to set up?";
@@ -226,11 +195,7 @@ async function promptAgents(scope: Scope, mode: SetupMode): Promise<SetupAgent[]
}
}
-async function resolveAgents(
- options: SetupOptions,
- scope: Scope,
- mode: SetupMode = "mcp"
-): Promise<SetupAgent[]> {
+async function resolveAgents(options: SetupOptions, scope: Scope): Promise<SetupAgent[]> {
const explicit = getSelectedAgents(options);
if (explicit.length > 0) return explicit;
@@ -239,7 +204,7 @@ async function resolveAgents(
if (detected.length > 0 && options.yes) return detected;
log.blank();
- const selected = await promptAgents(scope, mode);
+ const selected = await promptAgents();
if (!selected) {
log.warn("Setup cancelled");
return [];
@@ -322,7 +287,7 @@ async function setupAgent(
agent.mcp.buildEntry(auth)
);
mcpStatus = alreadyExists
- ? "already configured"
+ ? `reconfigured with ${AUTH_MODE_LABELS[auth.mode]}`
: `configured with ${AUTH_MODE_LABELS[auth.mode]}`;
} else {
const existing = await readJsonConfig(mcpPath);
@@ -332,14 +297,10 @@ async function setupAgent(
"context7",
agent.mcp.buildEntry(auth)
);
- if (alreadyExists) {
- mcpStatus = "already configured";
- } else {
- mcpStatus = `configured with ${AUTH_MODE_LABELS[auth.mode]}`;
- }
- if (config !== existing) {
- await writeJsonConfig(mcpPath, config);
- }
+ mcpStatus = alreadyExists
+ ? `reconfigured with ${AUTH_MODE_LABELS[auth.mode]}`
+ : `configured with ${AUTH_MODE_LABELS[auth.mode]}`;
+ await writeJsonConfig(mcpPath, config);
}
} catch (err) {
mcpStatus = `failed: ${err instanceof Error ? err.message : String(err)}`;
@@ -406,7 +367,10 @@ async function setupMcp(agents: SetupAgent[], options: SetupOptions, scope: Scop
log.blank();
for (const r of results) {
log.plain(` ${pc.bold(r.agent)}`);
- const mcpIcon = r.mcpStatus.startsWith("configured") ? pc.green("+") : pc.dim("~");
+ const mcpIcon =
+ r.mcpStatus.startsWith("configured") || r.mcpStatus.startsWith("reconfigured")
+ ? pc.green("+")
+ : pc.dim("~");
log.plain(` ${mcpIcon} MCP server ${r.mcpStatus}`);
log.plain(` ${pc.dim(r.mcpPath)}`);
const ruleIcon = r.ruleStatus === "installed" ? pc.green("+") : pc.dim("~");
@@ -460,7 +424,7 @@ async function setupCli(options: SetupOptions): Promise<void> {
await resolveCliAuth(options.apiKey);
const scope: Scope = options.project ? "project" : "global";
- const agents = await resolveAgents(options, scope, "cli");
+ const agents = await resolveAgents(options, scope);
if (agents.length === 0) return;
log.blank();
@@ -515,7 +479,7 @@ async function setupCommand(options: SetupOptions): Promise<void> {
const mode = await resolveMode(options);
if (mode === "mcp") {
const scope: Scope = options.project ? "project" : "global";
- const agents = await resolveAgents(options, scope, mode);
+ const agents = await resolveAgents(options, scope);
if (agents.length === 0) return;
await setupMcp(agents, options, scope);
} else {
diff --git a/packages/cli/src/setup/mcp-writer.ts b/packages/cli/src/setup/mcp-writer.ts
index ce65ec28..517f89f2 100644
--- a/packages/cli/src/setup/mcp-writer.ts
+++ b/packages/cli/src/setup/mcp-writer.ts
@@ -47,10 +47,7 @@ export function mergeServerEntry(
entry: Record<string, unknown>
): { config: Record<string, unknown>; alreadyExists: boolean } {
const section = (existing[configKey] as Record<string, unknown> | undefined) ?? {};
-
- if (serverName in section) {
- return { config: existing, alreadyExists: true };
- }
+ const alreadyExists = serverName in section;
return {
config: {
@@ -60,7 +57,7 @@ export function mergeServerEntry(
[serverName]: entry,
},
},
- alreadyExists: false,
+ alreadyExists,
};
}
@@ -69,9 +66,7 @@ export async function resolveMcpPath(candidates: string[]): Promise<string> {
try {
await access(candidate);
return candidate;
- } catch {
- // continue
- }
+ } catch {}
}
return candidates[0];
}
@@ -118,22 +113,48 @@ export async function appendTomlServer(
serverName: string,
entry: Record<string, unknown>
): Promise<{ alreadyExists: boolean }> {
- if (await readTomlServerExists(filePath, serverName)) {
- return { alreadyExists: true };
- }
-
const block = buildTomlServerBlock(serverName, entry);
let existing = "";
try {
existing = await readFile(filePath, "utf-8");
- } catch {
- // File doesn't exist
+ } catch {}
+
+ const sectionHeader = `[mcp_servers.${serverName}]`;
+ const alreadyExists = existing.includes(sectionHeader);
+
+ if (alreadyExists) {
+ const subPrefix = `[mcp_servers.${serverName}.`;
+ const startIdx = existing.indexOf(sectionHeader);
+ const rest = existing.slice(startIdx + sectionHeader.length);
+
+ let endOffset = rest.length;
+ const re = /^\[/gm;
+ let m;
+ while ((m = re.exec(rest)) !== null) {
+ const lineEnd = rest.indexOf("\n", m.index);
+ const line = rest.slice(m.index, lineEnd === -1 ? undefined : lineEnd);
+ if (!line.startsWith(subPrefix)) {
+ endOffset = m.index;
+ break;
+ }
+ }
+
+ const rawBefore = existing.slice(0, startIdx).replace(/\n+$/, "");
+ const rawAfter = existing
+ .slice(startIdx + sectionHeader.length + endOffset)
+ .replace(/^\n+/, "");
+ const before = rawBefore.length > 0 ? rawBefore + "\n\n" : "";
+ const after = rawAfter.length > 0 ? "\n" + rawAfter : "";
+ const content = before + block + after;
+ await mkdir(dirname(filePath), { recursive: true });
+ await writeFile(filePath, content, "utf-8");
+ } else {
+ const separator =
+ existing.length > 0 && !existing.endsWith("\n") ? "\n\n" : existing.length > 0 ? "\n" : "";
+ await mkdir(dirname(filePath), { recursive: true });
+ await writeFile(filePath, existing + separator + block, "utf-8");
}
- const separator =
- existing.length > 0 && !existing.endsWith("\n") ? "\n\n" : existing.length > 0 ? "\n" : "";
- await mkdir(dirname(filePath), { recursive: true });
- await writeFile(filePath, existing + separator + block, "utf-8");
- return { alreadyExists: false };
+ return { alreadyExists };
}