Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"@clack/prompts": "^1.2.0",
"dotenv": "^17.4.2",
"iii-sdk": "0.11.2",
"jsonc-parser": "^3.3.1",
"zod": "^4.0.0"
},
"optionalDependencies": {
Expand Down
97 changes: 85 additions & 12 deletions src/cli/connect/json-mcp-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { existsSync, mkdirSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname } from "node:path";
import * as p from "@clack/prompts";
import { applyEdits, modify, parse } from "jsonc-parser";
import type { ParseError } from "jsonc-parser";
import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js";
import {
AGENTMEMORY_MCP_BLOCK,
backupFile,
logAlreadyWired,
logBackup,
logInstalled,
readJsonSafe,
writeTextAtomic,
writeJsonAtomic,
} from "./util.js";

Expand All @@ -26,13 +28,69 @@ export type JsonMcpAdapterConfig = {
// Wrapper key under which servers live. Default "mcpServers".
// Zed uses "context_servers"; otherwise same shape.
wrapperKey?: string;
// Some hosts, including Zed, store settings as JSONC with comments and
// trailing commas. Preserve those files with textual JSONC edits.
jsonc?: boolean;
// Extra fields merged into the agentmemory entry. Droid requires
// type: "stdio"; other hosts ignore unknown fields.
extraEntryFields?: Record<string, unknown>;
};

type McpEntry = typeof AGENTMEMORY_MCP_BLOCK;
type McpConfig = Record<string, unknown>;
type ReadConfigResult =
| { kind: "missing"; config: McpConfig }
| { kind: "parsed"; config: McpConfig; raw: string }
| { kind: "invalid"; reason: string };

const formattingOptions = {
insertSpaces: true,
tabSize: 2,
eol: "\n",
insertFinalNewline: true,
};

function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}

function readMcpConfig(path: string, jsonc: boolean): ReadConfigResult {
if (!existsSync(path)) return { kind: "missing", config: {} };

const raw = readFileSync(path, "utf-8");
try {
const parsed = jsonc ? parseJsonc(raw) : JSON.parse(raw);
if (parsed === undefined && raw.trim() === "") {
return { kind: "parsed", config: {}, raw };
}
if (!isRecord(parsed)) {
return { kind: "invalid", reason: "top-level config is not an object" };
}
return { kind: "parsed", config: parsed, raw };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { kind: "invalid", reason: message };
}
}

function parseJsonc(raw: string): unknown {
const errors: ParseError[] = [];
const parsed = parse(raw, errors, {
allowTrailingComma: true,
allowEmptyContent: true,
});
if (errors.length > 0) {
const first = errors[0];
throw new Error(
`JSONC parse error ${first.error} at offset ${first.offset}`,
);
}
return parsed;
}

function serverEntries(value: unknown): Record<string, McpEntry> {
return isRecord(value) ? { ...(value as Record<string, McpEntry>) } : {};
}

function entryMatches(entry: unknown): boolean {
if (!entry || typeof entry !== "object") return false;
Expand Down Expand Up @@ -60,11 +118,17 @@ export function createJsonMcpAdapter(
},

async install(opts: ConnectOptions): Promise<ConnectResult> {
const existing = readJsonSafe<McpConfig>(config.configPath);
const next: McpConfig = existing ? { ...existing } : {};
const servers: Record<string, McpEntry> = {
...((next[wrapperKey] as Record<string, McpEntry>) ?? {}),
};
const jsonc = config.jsonc ?? false;
const existing = readMcpConfig(config.configPath, jsonc);
if (existing.kind === "invalid") {
p.log.error(
`${config.displayName}: ${config.configPath} could not be parsed (${existing.reason}); leaving it unchanged.`,
);
return { kind: "skipped", reason: "invalid-config" };
}

const next: McpConfig = { ...existing.config };
const servers = serverEntries(next[wrapperKey]);

const alreadyHas = entryMatches(servers["agentmemory"]);
if (alreadyHas && !opts.force) {
Expand Down Expand Up @@ -92,12 +156,21 @@ export function createJsonMcpAdapter(
...(config.extraEntryFields ?? {}),
};
next[wrapperKey] = servers;
writeJsonAtomic(config.configPath, next);
if (jsonc && existing.kind === "parsed") {
const edits = modify(
existing.raw,
[wrapperKey, "agentmemory"],
servers["agentmemory"],
{ formattingOptions },
);
writeTextAtomic(config.configPath, applyEdits(existing.raw, edits));
} else {
writeJsonAtomic(config.configPath, next);
}

const verify = readJsonSafe<McpConfig>(config.configPath);
const verifyServers = verify?.[wrapperKey] as
| Record<string, McpEntry>
| undefined;
const verify = readMcpConfig(config.configPath, jsonc);
const verifyServers =
verify.kind === "invalid" ? undefined : serverEntries(verify.config[wrapperKey]);
if (!entryMatches(verifyServers?.["agentmemory"])) {
p.log.error(
`Verification failed: ${config.configPath} did not contain ${wrapperKey}.agentmemory after write.`,
Expand Down
7 changes: 6 additions & 1 deletion src/cli/connect/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,14 @@ export function readJsonSafe<T = unknown>(path: string): T | null {
}

export function writeJsonAtomic(path: string, value: unknown): void {
mkdirSync(dirname(path), { recursive: true });
writeTextAtomic(path, `${JSON.stringify(value, null, 2)}\n`);
}

export function writeTextAtomic(path: string, value: string): void {
mkdirSync(dirname(path), { recursive: true });
const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf-8");
writeFileSync(tmp, value, "utf-8");
renameSync(tmp, path);
}

Expand Down
1 change: 1 addition & 0 deletions src/cli/connect/zed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const adapter = createJsonMcpAdapter({
detectDir: zedConfigDir,
configPath: join(zedConfigDir, "settings.json"),
wrapperKey: "context_servers",
jsonc: true,
docs: "https://github.com/rohitg00/agentmemory#other-agents",
protocolNote:
"→ Using MCP via ~/.config/zed/settings.json (key: context_servers).",
Expand Down
40 changes: 39 additions & 1 deletion test/connect-new-agents.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { mkdtempSync, mkdirSync, rmSync, readFileSync, existsSync } from "node:fs";
import {
mkdtempSync,
mkdirSync,
rmSync,
readFileSync,
writeFileSync,
existsSync,
} from "node:fs";
import { tmpdir, platform } from "node:os";
import { join } from "node:path";

Expand Down Expand Up @@ -246,6 +253,37 @@ describe("connect: Zed", () => {
expect(cfg.context_servers.agentmemory.args).toContain("@agentmemory/mcp");
expect(cfg.mcpServers).toBeUndefined();
});

it("preserves existing JSONC Zed settings when adding agentmemory", async () => {
const zedDir = join(home, ".config", "zed");
const settingsPath = join(zedDir, "settings.json");
mkdirSync(zedDir, { recursive: true });
writeFileSync(
settingsPath,
`{
// Keep user's editor preferences.
"vim_mode": true,
"context_servers": {
"existing": {
"command": "node",
"args": ["server.js"],
},
},
}
`,
);

const { adapter } = await import("../src/cli/connect/zed.js");
const result = await adapter.install({ dryRun: false, force: false });
expect(result.kind).toBe("installed");

const updated = readFileSync(settingsPath, "utf-8");
expect(updated).toContain("// Keep user's editor preferences.");
expect(updated).toContain('"vim_mode": true');
expect(updated).toContain('"existing"');
expect(updated).toContain('"agentmemory"');
expect(updated).toContain("@agentmemory/mcp");
});
});

describe("connect: Continue.dev", () => {
Expand Down