diff --git a/CHANGELOG.md b/CHANGELOG.md index caa6f58..c39d7d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ All notable changes to Zen MCP are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.4.0] - 2026-11-08 + +### Added + +- `zen-mcp onboard` now covers 28 MCP clients. Alongside the original nine it + knows OpenCode, oh-my-pi (OMP), DeepSeek Harness (DSH), ZCode (Z.ai), Roo + Code, Kilo Code, Continue, Amp, Crush, Qwen Code, Kiro, Warp, Copilot CLI, + Factory Droid, Amazon Q, Goose, LM Studio, Junie and Pi. +- The client list scrolls inside a fixed pane, with `up N more` and + `down N more` markers and Page Up, Page Down, Home and End keys. The header + and the selection footer stay in place while the rows move. +- Writers for the formats those clients use: nested JSON keys such as + `mcp.servers` and `amp.mcpServers`, JSONC with comments and trailing commas, + TOML tables, YAML (the DSH patch file, Continue's list and Goose's + `extensions` mapping) and shell rc files (Crush). Each writer creates or + replaces only the `zen-mcp` entry and leaves every other entry alone. +- The Other client runbook describes each of these config paths and entry + shapes. + ## [0.3.3] - 2026-11-02 ### Added @@ -130,6 +149,7 @@ uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Changes for 0.1.0 and 0.2.0 are not recorded here. See the release notes on GitHub. +[0.4.0]: https://github.com/spaxe-dev/zen-mcp/releases/tag/v0.4.0 [0.3.3]: https://github.com/spaxe-dev/zen-mcp/releases/tag/v0.3.3 [0.3.2]: https://github.com/spaxe-dev/zen-mcp/releases/tag/v0.3.2 [0.3.1]: https://github.com/spaxe-dev/zen-mcp/releases/tag/v0.3.1 diff --git a/README.md b/README.md index 40298b2..2c5c018 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Zen MCP is an MCP server that lets an AI agent work inside [Zen Browser](https://zen-browser.app) using Zen's own spaces, folders, and tabs. The agent can research in background tabs, read and search pages without switching what you are looking at, ask you a question in a small in-browser card, and show the evidence behind an answer. -Status: **0.3.x, pre-1.0.** Windows is the only platform with a live-tested Zen launch. The public API, tools, and configuration keys can still change. See [Current maturity](#current-maturity-and-platform-support) and [Known limitations](https://github.com/spaxe-dev/zen-mcp/blob/main/docs/troubleshooting.md#known-limitations). +Status: **0.4.x, pre-1.0.** Windows is the only platform with a live-tested Zen launch. The public API, tools, and configuration keys can still change. See [Current maturity](#current-maturity-and-platform-support) and [Known limitations](https://github.com/spaxe-dev/zen-mcp/blob/main/docs/troubleshooting.md#known-limitations). ## What it does @@ -96,7 +96,7 @@ npx @spaxe-dev/zen-mcp setup Each GitHub release also attaches a package tarball and `SHA256SUMS`: ```sh -npm install -g ./zen-mcp-0.3.3.tgz +npm install -g ./zen-mcp-0.4.0.tgz zen-mcp setup ``` @@ -131,7 +131,7 @@ Run the picker: zen-mcp onboard ``` -It lists Claude Code, Claude Desktop, Cursor, VS Code, Codex CLI, Gemini CLI, Windsurf, Cline, and Zed. Clients found on this machine are preselected. Use the arrow keys to move, space to toggle, and enter to confirm. Zen MCP merges a `zen-mcp` entry into each selected client's own configuration file and leaves other servers alone. Choose **Other MCP client** to print a step-by-step runbook for any agent: known config paths, the right entry shape for JSON, VS Code, Zed and TOML clients, merge rules, a validation checklist, and a completion report. +It lists Claude Code, Claude Desktop, Cursor, VS Code, Codex CLI, Gemini CLI, OpenCode, oh-my-pi, DeepSeek Harness, ZCode, Windsurf, Cline, Zed, Roo Code, Kilo Code, Continue, Amp, Crush, Qwen Code, Kiro, Warp, Copilot CLI, Factory Droid, Amazon Q, Goose, LM Studio, Junie, and Pi. The list scrolls inside the picker, and clients found on this machine are preselected. Use the arrow keys, Page Up, Page Down, Home and End to move, space to toggle, and enter to confirm. Zen MCP merges a `zen-mcp` entry into each selected client's own configuration file and leaves other servers alone. Choose **Other MCP client** to print a step-by-step runbook for any agent: known config paths, the right entry shape for JSON, nested JSON, VS Code, Zed, TOML, YAML and shell clients, merge rules, a validation checklist, and a completion report. For scripts or a shell without a TTY, name the clients: diff --git a/docs/configuration.md b/docs/configuration.md index f5032de..b2a5e13 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -45,7 +45,7 @@ zen-mcp onboard --clients all zen-mcp onboard --clients other ``` -The picker knows Claude Code, Claude Desktop, Cursor, VS Code, Codex CLI, Gemini CLI, Windsurf, Cline, and Zed. It preselects clients found on this machine. Only the `zen-mcp` entry is created or replaced; other servers stay, and JSONC files keep their comments and trailing commas. `other` prints a step-by-step runbook with config paths, entry shapes, merge rules, a validation checklist and a completion report. `--command` changes the command clients should run. +The picker knows Claude Code, Claude Desktop, Cursor, VS Code, Codex CLI, Gemini CLI, OpenCode, oh-my-pi, DeepSeek Harness, ZCode, Windsurf, Cline, Zed, Roo Code, Kilo Code, Continue, Amp, Crush, Qwen Code, Kiro, Warp, Copilot CLI, Factory Droid, Amazon Q, Goose, LM Studio, Junie, and Pi. The list scrolls inside the pane, and clients found on this machine are preselected. Only the `zen-mcp` entry is created or replaced; other servers stay, and JSONC files keep their comments and trailing commas. `other` prints a step-by-step runbook with config paths, entry shapes, merge rules, a validation checklist and a completion report. `--command` changes the command clients should run. ## File locations diff --git a/package-lock.json b/package-lock.json index 6c368b2..e5d29a9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@spaxe-dev/zen-mcp", - "version": "0.3.3", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@spaxe-dev/zen-mcp", - "version": "0.3.3", + "version": "0.4.0", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", diff --git a/package.json b/package.json index ec39236..1134482 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@spaxe-dev/zen-mcp", - "version": "0.3.3", + "version": "0.4.0", "description": "An agent harness for Zen Browser. Native spaces, background research tabs, and in-browser questions.", "license": "MIT", "repository": { diff --git a/src/onboard/clients.ts b/src/onboard/clients.ts index 78e8f3a..71d7463 100644 --- a/src/onboard/clients.ts +++ b/src/onboard/clients.ts @@ -31,18 +31,21 @@ interface ClientDefinition { label: string; detail: string; popular: boolean; - format: "json" | "toml"; + format: "json" | "toml" | "yaml" | "bash"; configPaths(ctx: ResolvedContext): string[]; /** Directories or files whose presence means the client is installed. */ detectPaths(ctx: ResolvedContext): string[]; json?: { - key: string; + /** Nested key path to the server map, for example ["mcp", "servers"]. */ + path: string[]; entry(ctx: ResolvedContext): Record; }; toml?: { section: string; values(ctx: ResolvedContext): Record; }; + /** Text formats that cannot be parsed generically (YAML, shell files). */ + text?: (existing: string | undefined, ctx: ResolvedContext) => string; } export interface ClientEntry { @@ -53,7 +56,7 @@ export interface ClientEntry { detected: boolean; /** File that will be created or updated. */ configPath: string; - format: "json" | "toml"; + format: "json" | "toml" | "yaml" | "bash"; } export interface ApplyResult { @@ -72,6 +75,15 @@ const CLINE_SETTINGS = join( "cline_mcp_settings.json" ); +/** Cross-platform tools keep their config under `~/.config` on every OS. */ +const xdgConfig = (ctx: ResolvedContext): string => + ctx.env.XDG_CONFIG_HOME ?? join(ctx.home, ".config"); + +const mcpServers = (ctx: ResolvedContext): Record => ({ + command: ctx.command, + args: [...SERVER_ARGS], +}); + const DEFINITIONS: ClientDefinition[] = [ { id: "claude-code", @@ -85,7 +97,7 @@ const DEFINITIONS: ClientDefinition[] = [ join(ctx.home, ".claude"), ], json: { - key: "mcpServers", + path: ["mcpServers"], entry: (ctx) => ({ command: ctx.command, args: [...SERVER_ARGS], @@ -103,7 +115,7 @@ const DEFINITIONS: ClientDefinition[] = [ ], detectPaths: (ctx) => [join(ctx.configBase, "Claude")], json: { - key: "mcpServers", + path: ["mcpServers"], entry: (ctx) => ({ command: ctx.command, args: [...SERVER_ARGS], @@ -119,7 +131,7 @@ const DEFINITIONS: ClientDefinition[] = [ configPaths: (ctx) => [join(ctx.home, ".cursor", "mcp.json")], detectPaths: (ctx) => [join(ctx.home, ".cursor")], json: { - key: "mcpServers", + path: ["mcpServers"], entry: (ctx) => ({ command: ctx.command, args: [...SERVER_ARGS], @@ -141,7 +153,7 @@ const DEFINITIONS: ClientDefinition[] = [ join(ctx.configBase, "Code - Insiders", "User"), ], json: { - key: "servers", + path: ["servers"], entry: (ctx) => ({ type: "stdio", command: ctx.command, @@ -178,7 +190,7 @@ const DEFINITIONS: ClientDefinition[] = [ configPaths: (ctx) => [join(ctx.home, ".gemini", "settings.json")], detectPaths: (ctx) => [join(ctx.home, ".gemini")], json: { - key: "mcpServers", + path: ["mcpServers"], entry: (ctx) => ({ command: ctx.command, args: [...SERVER_ARGS], @@ -196,7 +208,7 @@ const DEFINITIONS: ClientDefinition[] = [ ], detectPaths: (ctx) => [join(ctx.home, ".codeium", "windsurf")], json: { - key: "mcpServers", + path: ["mcpServers"], entry: (ctx) => ({ command: ctx.command, args: [...SERVER_ARGS], @@ -220,7 +232,7 @@ const DEFINITIONS: ClientDefinition[] = [ dirname(join(ctx.configBase, "Windsurf", CLINE_SETTINGS)), ], json: { - key: "mcpServers", + path: ["mcpServers"], entry: (ctx) => ({ command: ctx.command, args: [...SERVER_ARGS], @@ -240,13 +252,352 @@ const DEFINITIONS: ClientDefinition[] = [ join(ctx.configBase, ctx.platform === "linux" ? "zed" : "Zed"), ], json: { - key: "context_servers", + path: ["context_servers"], + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "opencode", + label: "OpenCode", + detail: "sst terminal agent", + popular: true, + format: "json", + configPaths: (ctx) => [ + join(xdgConfig(ctx), "opencode", "opencode.json"), + join(xdgConfig(ctx), "opencode", "opencode.jsonc"), + ], + detectPaths: (ctx) => [join(xdgConfig(ctx), "opencode")], + json: { + path: ["mcp", "servers"], + entry: (ctx) => ({ + type: "local", + command: [ctx.command, ...SERVER_ARGS], + }), + }, + }, + { + id: "omp", + label: "oh-my-pi (omp)", + detail: "can1357's terminal agent", + popular: true, + format: "json", + configPaths: (ctx) => [ + join( + ctx.env.PI_CONFIG_DIR ?? join(ctx.home, ".omp"), + "agent", + "mcp.json" + ), + ], + detectPaths: (ctx) => [ + ctx.env.PI_CONFIG_DIR ?? join(ctx.home, ".omp"), + ], + json: { + path: ["mcpServers"], + entry: (ctx) => ({ + type: "stdio", + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "dsh", + label: "DeepSeek Harness", + detail: "dsh agent framework", + popular: true, + format: "yaml", + configPaths: (ctx) => [ + join(ctx.env.DSH_HOME ?? join(ctx.home, ".dsh"), "cordis.patch.yml"), + ], + detectPaths: (ctx) => [ctx.env.DSH_HOME ?? join(ctx.home, ".dsh")], + text: (existing, ctx) => mergeDshPatch(existing, ctx), + }, + { + id: "zcode", + label: "ZCode (Z.ai)", + detail: "Z.ai coding agent", + popular: true, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".zcode", "cli", "config.json")], + detectPaths: (ctx) => [join(ctx.home, ".zcode")], + json: { + path: ["mcp", "servers"], + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + env: {}, + }), + }, + }, + { + id: "roo-code", + label: "Roo Code", + detail: "VS Code extension", + popular: false, + format: "json", + configPaths: (ctx) => [ + join( + ctx.configBase, + "Code", + "User", + "globalStorage", + "rooveterinaryinc.roo-cline", + "settings", + "mcp_settings.json" + ), + ], + detectPaths: (ctx) => [ + join( + ctx.configBase, + "Code", + "User", + "globalStorage", + "rooveterinaryinc.roo-cline" + ), + ], + json: { + path: ["mcpServers"], + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + disabled: false, + alwaysAllow: [], + }), + }, + }, + { + id: "kilo-code", + label: "Kilo Code", + detail: "Kilo editor extension", + popular: false, + format: "json", + configPaths: (ctx) => [join(xdgConfig(ctx), "kilo", "kilo.jsonc")], + detectPaths: (ctx) => [join(xdgConfig(ctx), "kilo")], + json: { + path: ["mcp"], + entry: (ctx) => ({ + type: "local", + command: [ctx.command, ...SERVER_ARGS], + enabled: true, + timeout: 10000, + }), + }, + }, + { + id: "continue", + label: "Continue", + detail: "VS Code and JetBrains extension", + popular: false, + format: "yaml", + configPaths: (ctx) => [join(ctx.home, ".continue", "config.yaml")], + detectPaths: (ctx) => [join(ctx.home, ".continue")], + text: (existing, ctx) => + mergeYamlListSection(existing, "mcpServers", SERVER_ENTRY_NAME, [ + `name: ${SERVER_ENTRY_NAME}`, + "type: stdio", + `command: ${yamlScalar(ctx.command)}`, + `args: ${yamlFlowArray(SERVER_ARGS)}`, + ]), + }, + { + id: "amp", + label: "Amp", + detail: "Sourcegraph terminal agent", + popular: false, + format: "json", + configPaths: (ctx) => [ + ctx.platform === "win32" + ? join(ctx.configBase, "amp", "settings.json") + : join(xdgConfig(ctx), "amp", "settings.json"), + ], + detectPaths: (ctx) => [ + ctx.platform === "win32" + ? join(ctx.configBase, "amp") + : join(xdgConfig(ctx), "amp"), + ], + json: { + path: ["amp.mcpServers"], + entry: (ctx) => mcpServers(ctx), + }, + }, + { + id: "crush", + label: "Crush", + detail: "Charmbracelet terminal agent", + popular: false, + format: "bash", + configPaths: (ctx) => [ + ctx.env.CRUSH_GLOBAL_CONFIG ?? join(xdgConfig(ctx), "crush", "crushrc"), + ], + detectPaths: (ctx) => [join(xdgConfig(ctx), "crush")], + text: (existing, ctx) => mergeCrushrc(existing, ctx), + }, + { + id: "qwen-code", + label: "Qwen Code", + detail: "Alibaba terminal agent", + popular: false, + format: "json", + configPaths: (ctx) => [ + join(ctx.env.QWEN_HOME ?? join(ctx.home, ".qwen"), "settings.json"), + ], + detectPaths: (ctx) => [ctx.env.QWEN_HOME ?? join(ctx.home, ".qwen")], + json: { + path: ["mcpServers"], + entry: (ctx) => mcpServers(ctx), + }, + }, + { + id: "kiro", + label: "Kiro", + detail: "AWS agentic IDE and CLI", + popular: false, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".kiro", "settings", "mcp.json")], + detectPaths: (ctx) => [join(ctx.home, ".kiro")], + json: { + path: ["mcpServers"], entry: (ctx) => ({ command: ctx.command, args: [...SERVER_ARGS], + disabled: false, + autoApprove: [], }), }, }, + { + id: "warp", + label: "Warp", + detail: "Warp terminal agent", + popular: false, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".warp", ".mcp.json")], + detectPaths: (ctx) => [join(ctx.home, ".warp")], + json: { + path: ["mcpServers"], + entry: (ctx) => mcpServers(ctx), + }, + }, + { + id: "copilot-cli", + label: "Copilot CLI", + detail: "GitHub Copilot terminal agent", + popular: false, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".copilot", "mcp-config.json")], + detectPaths: (ctx) => [join(ctx.home, ".copilot")], + json: { + path: ["mcpServers"], + entry: (ctx) => ({ + type: "local", + command: ctx.command, + args: [...SERVER_ARGS], + tools: ["*"], + }), + }, + }, + { + id: "droid", + label: "Factory Droid", + detail: "Factory terminal agent", + popular: false, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".factory", "mcp.json")], + detectPaths: (ctx) => [join(ctx.home, ".factory")], + json: { + path: ["mcpServers"], + entry: (ctx) => ({ + type: "stdio", + command: ctx.command, + args: [...SERVER_ARGS], + disabled: false, + }), + }, + }, + { + id: "amazon-q", + label: "Amazon Q", + detail: "Amazon Q Developer CLI", + popular: false, + format: "json", + configPaths: (ctx) => [ + join(ctx.home, ".aws", "amazonq", "mcp.json"), + ], + detectPaths: (ctx) => [join(ctx.home, ".aws", "amazonq")], + json: { + path: ["mcpServers"], + entry: (ctx) => mcpServers(ctx), + }, + }, + { + id: "goose", + label: "Goose", + detail: "Block's terminal agent", + popular: false, + format: "yaml", + configPaths: (ctx) => [ + ctx.platform === "win32" + ? join(ctx.configBase, "Block", "goose", "config", "config.yaml") + : join(xdgConfig(ctx), "goose", "config.yaml"), + ], + detectPaths: (ctx) => [ + ctx.platform === "win32" + ? join(ctx.configBase, "Block", "goose") + : join(xdgConfig(ctx), "goose"), + ], + text: (existing, ctx) => + mergeYamlMappingSection(existing, "extensions", SERVER_ENTRY_NAME, [ + "type: stdio", + `name: ${SERVER_ENTRY_NAME}`, + "enabled: true", + `cmd: ${yamlScalar(ctx.command)}`, + `args: ${yamlFlowArray(SERVER_ARGS)}`, + "envs: {}", + "timeout: 300", + ]), + }, + { + id: "lm-studio", + label: "LM Studio", + detail: "LM Studio desktop app", + popular: false, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".lmstudio", "mcp.json")], + detectPaths: (ctx) => [join(ctx.home, ".lmstudio")], + json: { + path: ["mcpServers"], + entry: (ctx) => mcpServers(ctx), + }, + }, + { + id: "junie", + label: "Junie", + detail: "JetBrains Junie CLI", + popular: false, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".junie", "mcp", "mcp.json")], + detectPaths: (ctx) => [join(ctx.home, ".junie")], + json: { + path: ["mcpServers"], + entry: (ctx) => mcpServers(ctx), + }, + }, + { + id: "pi", + label: "Pi", + detail: "pi.dev terminal agent", + popular: false, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".pi", "agent", "mcp.json")], + detectPaths: (ctx) => [join(ctx.home, ".pi")], + json: { + path: ["mcpServers"], + entry: (ctx) => mcpServers(ctx), + }, + }, ]; /** Lists every supported client id. */ @@ -257,7 +608,7 @@ export function clientIds(): string[] { /** Lists every supported client and its resolved config path. */ export function catalog(ctx: ClientContext = {}): ClientEntry[] { const resolved = resolveContext(ctx); - return DEFINITIONS.map((definition) => { + const entries = DEFINITIONS.map((definition) => { const paths = definition.configPaths(resolved); return { id: definition.id, @@ -269,6 +620,11 @@ export function catalog(ctx: ClientContext = {}): ClientEntry[] { format: definition.format, }; }); + // The picker draws one POPULAR section, so popular entries must be adjacent. + return [ + ...entries.filter((entry) => entry.popular), + ...entries.filter((entry) => !entry.popular), + ]; } /** Adds or replaces the Zen MCP server in one client's configuration. */ @@ -294,7 +650,9 @@ export function applyClient(id: string, ctx: ClientContext = {}): ApplyResult { ? readFileTextBounded(path, MAX_CLIENT_CONFIG_BYTES) : undefined; - if (definition.format === "toml") { + if (definition.text) { + atomicWritePrivate(path, definition.text(existing, resolved)); + } else if (definition.format === "toml") { const toml = definition.toml; if (!toml) throw new Error("TOML settings are missing for this client"); const next = mergeTomlServer( @@ -306,7 +664,11 @@ export function applyClient(id: string, ctx: ClientContext = {}): ApplyResult { } else { const json = definition.json; if (!json) throw new Error("JSON settings are missing for this client"); - const next = mergeJsonServer(existing, json.key, json.entry(resolved)); + const next = mergeJsonServerPath( + existing, + json.path, + json.entry(resolved) + ); atomicWritePrivate(path, next); } @@ -337,12 +699,23 @@ export function mergeJsonServer( existing: string | undefined, key: string, entry: Record +): string { + return mergeJsonServerPath(existing, [key], entry); +} + +/** Merges into a nested key path, creating missing objects along the way. */ +export function mergeJsonServerPath( + existing: string | undefined, + path: string[], + entry: Record ): string { let text = existing; if (text && text.charCodeAt(0) === 0xfeff) text = text.slice(1); if (!text || !text.trim()) { - return `${JSON.stringify({ [key]: { [SERVER_ENTRY_NAME]: entry } }, null, 2)}\n`; + const root: Record = {}; + placeJsonServer(root, path, entry); + return `${JSON.stringify(root, null, 2)}\n`; } let parsed: unknown; @@ -350,7 +723,7 @@ export function mergeJsonServer( parsed = JSON.parse(text); } catch (error) { try { - return mergeJsoncServer(text, key, entry); + return mergeJsoncServerPath(text, path, entry); } catch { throw new Error( `existing file is not valid JSON or JSONC (${(error as Error).message})` @@ -361,21 +734,34 @@ export function mergeJsonServer( if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { throw new Error("existing file is not a JSON object"); } - const root = parsed as Record; - - const current = root[key]; - if ( - current !== undefined && - (current === null || typeof current !== "object" || Array.isArray(current)) - ) { - throw new Error(`"${key}" is not a JSON object`); - } + placeJsonServer(parsed as Record, path, entry); + return `${JSON.stringify(parsed, null, 2)}\n`; +} - root[key] = { - ...((current as Record | undefined) ?? {}), - [SERVER_ENTRY_NAME]: entry, - }; - return `${JSON.stringify(root, null, 2)}\n`; +function placeJsonServer( + root: Record, + path: string[], + entry: Record +): void { + let node = root; + for (const key of path) { + const current = node[key]; + if (current === undefined) { + const created: Record = {}; + node[key] = created; + node = created; + continue; + } + if ( + current === null || + typeof current !== "object" || + Array.isArray(current) + ) { + throw new Error(`"${key}" is not a JSON object`); + } + node = current as Record; + } + node[SERVER_ENTRY_NAME] = entry; } interface JsoncMember { @@ -395,30 +781,57 @@ interface JsoncObject { * Merges into a JSONC document without reserializing it, so comments and * trailing commas survive. Only the `zen-mcp` entry is replaced or added. */ -function mergeJsoncServer( +function mergeJsoncServerPath( text: string, - key: string, + path: string[], entry: Record ): string { const rootStart = skipJsoncTrivia(text, 0); if (text[rootStart] !== "{") { throw new Error("the top level is not a JSON object"); } - const root = scanJsoncObject(text, rootStart); - if (!root) throw new Error("the file has an unterminated object"); - - const target = root.members.find((member) => member.key === key); - if (!target) { - return insertJsoncMember(text, root, key, { - [SERVER_ENTRY_NAME]: entry, - }); - } - if (text[target.valueStart] !== "{") { - throw new Error(`"${key}" is not a JSON object`); + let object = scanJsoncObject(text, rootStart); + if (!object) throw new Error("the file has an unterminated object"); + + for (let index = 0; index < path.length; index += 1) { + const key = path[index]; + const member = object.members.find((item) => item.key === key); + if (!member) { + return insertJsoncMember( + text, + object, + key, + nestedJsonValue(path.slice(index + 1), entry) + ); + } + if (text[member.valueStart] !== "{") { + throw new Error(`"${key}" is not a JSON object`); + } + const child = scanJsoncObject(text, member.valueStart); + if (!child) throw new Error(`"${key}" is not a complete object`); + if (index === path.length - 1) { + return upsertJsoncServer(text, child, entry); + } + object = child; } - const serverMap = scanJsoncObject(text, target.valueStart); - if (!serverMap) throw new Error(`"${key}" is not a complete object`); + throw new Error("the server path is empty"); +} + +function nestedJsonValue( + keys: string[], + entry: Record +): Record { + return keys.reduceRight>( + (value, key) => ({ [key]: value }), + { [SERVER_ENTRY_NAME]: entry } + ); +} +function upsertJsoncServer( + text: string, + serverMap: JsoncObject, + entry: Record +): string { const current = serverMap.members.find( (member) => member.key === SERVER_ENTRY_NAME ); @@ -662,6 +1075,257 @@ export function mergeTomlServer( return `${lines.join("\n")}\n`; } +function yamlScalar(value: string): string { + return JSON.stringify(value); +} + +function yamlFlowArray(values: string[]): string { + return `[${values.map(yamlScalar).join(", ")}]`; +} + +interface YamlSection { + start: number; + end: number; + indent: string; +} + +/** Finds a top-level YAML key and the lines that belong to it. */ +function findYamlSection(lines: string[], section: string): YamlSection | null { + const header = new RegExp(`^${escapeRegExp(section)}:\\s*(?:#.*)?$`); + const start = lines.findIndex((line) => header.test(line)); + if (start < 0) return null; + + let end = start + 1; + while (end < lines.length) { + const line = lines[end]; + if ( + line.trim() === "" || + /^[ \t]/.test(line) || + line.trimStart().startsWith("#") + ) { + end += 1; + } else { + break; + } + } + const child = lines + .slice(start + 1, end) + .find((line) => /^[ \t]+\S/.test(line)); + return { start, end, indent: child?.match(/^[ \t]+/)?.[0] ?? " " }; +} + +function splitYamlLines(existing: string | undefined): string[] { + const lines = (existing ?? "").replace(/\r\n/g, "\n").split("\n"); + while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop(); + return lines; +} + +/** + * Adds or replaces one key under a top-level YAML mapping. The block is + * spliced into the text so comments and unrelated keys keep their place. + */ +function mergeYamlMappingSection( + existing: string | undefined, + section: string, + key: string, + block: string[] +): string { + const lines = splitYamlLines(existing); + const found = findYamlSection(lines, section); + + if (!found) { + if (lines.length > 0) lines.push(""); + lines.push( + `${section}:`, + `${key}:`, + ...block.map((line) => ` ${line}`) + ); + return `${lines.join("\n")}\n`; + } + + const indent = found.indent; + const keyLine = `${indent}${key}:`; + const keyPattern = new RegExp( + `^${escapeRegExp(indent)}${escapeRegExp(key)}:\\s*(?:#.*)?$` + ); + const index = lines.findIndex( + (line, position) => + position > found.start && position < found.end && keyPattern.test(line) + ); + + if (index >= 0) { + let end = index + 1; + while (end < found.end) { + const line = lines[end]; + if (line.trim() === "") { + end += 1; + continue; + } + const lineIndent = line.match(/^[ \t]*/)?.[0].length ?? 0; + if (lineIndent <= indent.length) break; + end += 1; + } + lines.splice( + index, + end - index, + keyLine, + ...block.map((line) => ` ${indent}${line}`) + ); + } else { + lines.splice( + found.end, + 0, + keyLine, + ...block.map((line) => ` ${indent}${line}`) + ); + } + return `${lines.join("\n")}\n`; +} + +/** Adds or replaces one `- name:` item under a top-level YAML list. */ +function mergeYamlListSection( + existing: string | undefined, + section: string, + name: string, + block: string[] +): string { + const lines = splitYamlLines(existing); + const found = findYamlSection(lines, section); + const item = [`- name: ${name}`, ...block.slice(1)]; + + if (!found) { + if (lines.length > 0) lines.push(""); + lines.push(`${section}:`, ...item.map((line) => ` ${line}`)); + return `${lines.join("\n")}\n`; + } + + const itemIndent = + lines + .slice(found.start + 1, found.end) + .find((line) => /^[ \t]*-[ \t]+\S/.test(line)) + ?.match(/^[ \t]*/)?.[0] ?? " "; + const namePattern = new RegExp( + `^${escapeRegExp(itemIndent)}-[ \\t]+name:\\s*['"]?${escapeRegExp( + name + )}['"]?\\s*(?:#.*)?$` + ); + const index = lines.findIndex( + (line, position) => + position > found.start && position < found.end && namePattern.test(line) + ); + + if (index >= 0) { + let end = index + 1; + while (end < found.end) { + const line = lines[end]; + if (line.trim() === "") { + end += 1; + continue; + } + if (new RegExp(`^${escapeRegExp(itemIndent)}-[ \\t]`).test(line)) break; + if ((line.match(/^[ \t]*/)?.[0].length ?? 0) < itemIndent.length) break; + end += 1; + } + lines.splice( + index, + end - index, + `${itemIndent}${item[0]}`, + ...item.slice(1).map((line) => `${itemIndent} ${line}`) + ); + } else { + lines.splice( + found.end, + 0, + `${itemIndent}${item[0]}`, + ...item.slice(1).map((line) => `${itemIndent} ${line}`) + ); + } + return `${lines.join("\n")}\n`; +} + +/** DSH stores MCP clients as plugin entries in a Cordis patch overlay. */ +function mergeDshPatch( + existing: string | undefined, + ctx: ResolvedContext +): string { + const lines = splitYamlLines(existing); + const item = [ + "- id: zen-mcp", + " name: '@deepseek-ai/dsh-mcp-client'", + " config:", + " serverName: zen_mcp", + " transport: stdio", + ` command: ${yamlScalar(ctx.command)}`, + ` args: ${yamlFlowArray(SERVER_ARGS)}`, + ]; + const idPattern = /^([ \t]*)-[ \t]*id:\s*['"]?zen-mcp['"]?\s*$/; + const index = lines.findIndex((line) => idPattern.test(line)); + + if (index < 0) { + if (lines.length > 0) lines.push(""); + lines.push("- insert:", ...item.map((line) => ` ${line}`)); + return `${lines.join("\n")}\n`; + } + + const indent = lines[index].match(idPattern)?.[1] ?? " "; + let start = index; + while (start > 0) { + const previous = lines[start - 1]; + const previousIndent = previous.match(/^[ \t]*/)?.[0].length ?? 0; + if (previousIndent < indent.length) break; + if ( + previousIndent === indent.length && + /^[ \t]*-[ \t]/.test(previous) + ) { + break; + } + start -= 1; + } + + let end = index + 1; + while (end < lines.length) { + const line = lines[end]; + const lineIndent = line.match(/^[ \t]*/)?.[0].length ?? 0; + if (line.trim() !== "" && lineIndent < indent.length) break; + if (lineIndent === indent.length && /^[ \t]*-[ \t]/.test(line)) break; + end += 1; + } + + lines.splice( + start, + end - start, + ...item.map((line) => `${indent}${line}`) + ); + return `${lines.join("\n")}\n`; +} + +/** Crush reads a shell rc file, so the entry is an `mcp add` command. */ +function mergeCrushrc( + existing: string | undefined, + ctx: ResolvedContext +): string { + const lines = splitYamlLines(existing); + const command = `mcp add zen-mcp --command ${shellQuote( + ctx.command + )} --args ${SERVER_ARGS.map(shellQuote).join(" ")}`; + const index = lines.findIndex((line) => + /^\s*mcp\s+add\s+zen-mcp(?:\s|$)/.test(line) + ); + if (index >= 0) { + lines[index] = command; + } else { + if (lines.length > 0) lines.push(""); + lines.push(command); + } + return `${lines.join("\n")}\n`; +} + +function shellQuote(value: string): string { + return /^[A-Za-z0-9_./:-]+$/.test(value) + ? value + : `'${value.replace(/'/g, `'\\''`)}'`; +} + /** A paste-ready runbook for any client the picker does not know. */ export function agentSetupPrompt( command = "zen-mcp", @@ -676,14 +1340,21 @@ export function agentSetupPrompt( : definition.id === "cline" ? " (same relative path under Cursor or Windsurf)" : ""; + const jsonPath = definition.json?.path; const shape = - definition.id === "vscode" - ? ' top-level `servers`, entry needs `"type": "stdio"`' - : definition.id === "zed" - ? " top-level `context_servers`" - : definition.id === "codex" - ? " TOML table `[mcp_servers.zen-mcp]`" - : " top-level `mcpServers`"; + definition.format === "toml" + ? " TOML table `[mcp_servers.zen-mcp]`" + : definition.format === "yaml" + ? " YAML configuration, keep existing entries" + : definition.format === "bash" + ? " shell rc file, add it with `mcp add`" + : definition.id === "vscode" + ? ' top-level `servers`, entry needs `"type": "stdio"`' + : jsonPath && jsonPath.length > 1 + ? ` nested \`${jsonPath.join(".")}\` object` + : jsonPath?.[0] === "context_servers" + ? " top-level `context_servers`" + : " top-level `mcpServers`"; return `- ${definition.label}: \`${path}\`${detail};${shape}.`; }).join("\n"); diff --git a/src/onboard/picker.ts b/src/onboard/picker.ts index ecf9f3e..0743ea0 100644 --- a/src/onboard/picker.ts +++ b/src/onboard/picker.ts @@ -54,6 +54,25 @@ export function moveCursor(options: SelectOption[], cursor: number, delta: numbe return (((cursor + delta) % size) + size) % size; } +/** + * Returns the slice of `total` lines to draw. The window only moves when the + * cursor would leave it, so short moves do not make the list jump around. + */ +export function scrollWindow( + total: number, + cursor: number, + height: number, + start = 0 +): { start: number; end: number } { + const size = Math.max(1, Math.min(height, total)); + const limit = Math.max(0, total - size); + let next = Math.max(0, Math.min(start, limit)); + if (cursor < next) next = cursor; + if (cursor >= next + size) next = cursor - size + 1; + next = Math.max(0, Math.min(next, limit)); + return { start: next, end: Math.min(total, next + size) }; +} + /** Selects or clears every client row; the Other row keeps its state. */ export function toggleAll(options: SelectOption[], selected: boolean): SelectOption[] { return options.map((option) => @@ -70,6 +89,29 @@ export function pickerResult(options: SelectOption[]): PickerResult { }; } +type BodyEntry = + | { kind: "header"; text: string } + | { kind: "blank" } + | { kind: "option"; rowIndex: number }; + +/** Section labels scroll with the rows so the pane itself never moves. */ +function buildBodyEntries(rows: SelectOption[]): BodyEntry[] { + const entries: BodyEntry[] = []; + rows.forEach((row, index) => { + if (index === 0) { + entries.push({ kind: "header", text: "POPULAR" }); + } else if (row.other) { + entries.push({ kind: "blank" }); + entries.push({ kind: "header", text: "OTHER" }); + } else if (rows[index - 1]?.popular && !row.popular) { + entries.push({ kind: "blank" }); + entries.push({ kind: "header", text: "MORE CLIENTS" }); + } + entries.push({ kind: "option", rowIndex: index }); + }); + return entries; +} + /** * Renders a dependency-free multi-select in the terminal. Arrow keys move, * space toggles, `a` toggles every client, enter confirms and ctrl+c cancels. @@ -89,10 +131,40 @@ export async function pickClients( let painted = 0; const theme = createTheme(output); const columns = output.columns ?? 80; + const terminalRows = output.rows ?? 24; const width = Math.max(44, Math.min(columns - 4, 64)); const showDetail = columns >= 72; const detailLimit = Math.max(18, columns - 40); const rule = theme.dim("─".repeat(width)); + const headerHeight = 4; + const footerHeight = rows.some((row) => row.detected) ? 3 : 4; + const bodyHeight = Math.max(3, terminalRows - headerHeight - footerHeight); + const body = buildBodyEntries(rows); + let scrollStart = 0; + let pageSize = bodyHeight; + + const paintRow = ( + row: SelectOption, + index: number, + final: boolean + ): string => { + const marker = final ? " " : index === cursor ? theme.cyan("❯") : " "; + const box = row.selected ? theme.green("[●]") : theme.dim("[ ]"); + const padding = row.label.padEnd(20); + const label = index === cursor && !final ? theme.bold(padding) : padding; + const tagName = row.detected ? "detected" : row.popular ? "popular" : ""; + const tag = tagName + ? row.detected + ? theme.green(tagName.padEnd(10)) + : theme.dim(tagName.padEnd(10)) + : " ".repeat(10); + const detail = !showDetail + ? "" + : row.detail.length > detailLimit + ? `${row.detail.slice(0, detailLimit - 1).trimEnd()}…` + : row.detail; + return ` ${marker} ${box} ${label} ${tag} ${theme.dim(detail)}`.trimEnd(); + }; const paint = (final = false): void => { const lines: string[] = []; @@ -106,41 +178,34 @@ export async function pickClients( lines.push(` ${theme.dim("Connect Zen to the agents you use.")}`); lines.push(""); - rows.forEach((row, index) => { - const previous = rows[index - 1]; - if (index === 0) { - lines.push(` ${theme.dim("POPULAR")}`); - } else if (row.other) { - lines.push(""); - lines.push(` ${theme.dim("OTHER")}`); - } else if (previous?.popular && !row.popular) { - lines.push(""); - lines.push(` ${theme.dim("MORE CLIENTS")}`); - } + const scrolling = body.length > bodyHeight; + const visible = scrolling ? Math.max(1, bodyHeight - 2) : bodyHeight; + pageSize = visible; + const cursorLine = body.findIndex( + (entry) => entry.kind === "option" && entry.rowIndex === cursor + ); + const window = scrollWindow(body.length, cursorLine, visible, scrollStart); + scrollStart = window.start; - const marker = final ? " " : index === cursor ? theme.cyan("❯") : " "; - const box = row.selected ? theme.green("[●]") : theme.dim("[ ]"); - const padding = row.label.padEnd(20); - const label = index === cursor && !final ? theme.bold(padding) : padding; - const tagName = row.detected - ? "detected" - : row.popular - ? "popular" - : ""; - const tag = tagName - ? row.detected - ? theme.green(tagName.padEnd(10)) - : theme.dim(tagName.padEnd(10)) - : " ".repeat(10); - const detail = !showDetail - ? "" - : row.detail.length > detailLimit - ? `${row.detail.slice(0, detailLimit - 1).trimEnd()}…` - : row.detail; + if (scrolling) { lines.push( - ` ${marker} ${box} ${label} ${tag} ${theme.dim(detail)}`.trimEnd() + window.start > 0 ? ` ${theme.dim(`↑ ${window.start} more`)}` : "" ); - }); + } + for (let index = window.start; index < window.end; index += 1) { + const entry = body[index]; + if (entry.kind === "option") { + lines.push(paintRow(rows[entry.rowIndex], entry.rowIndex, final)); + } else if (entry.kind === "header") { + lines.push(` ${theme.dim(entry.text)}`); + } else { + lines.push(""); + } + } + if (scrolling) { + const below = body.length - window.end; + lines.push(below > 0 ? ` ${theme.dim(`↓ ${below} more`)}` : ""); + } lines.push(""); if (!rows.some((row) => row.detected)) { @@ -213,6 +278,18 @@ export async function pickClients( case "down": cursor = moveCursor(rows, cursor, 1); break; + case "pageup": + cursor = moveCursor(rows, cursor, -pageSize); + break; + case "pagedown": + cursor = moveCursor(rows, cursor, pageSize); + break; + case "home": + cursor = 0; + break; + case "end": + cursor = rows.length - 1; + break; case "space": case "spacebar": rows[cursor] = { ...rows[cursor], selected: !rows[cursor].selected }; diff --git a/src/shared/brand.ts b/src/shared/brand.ts index 9ddc19d..cfce51a 100644 --- a/src/shared/brand.ts +++ b/src/shared/brand.ts @@ -1,6 +1,6 @@ export const BRAND = "Zen MCP"; export const SERVER_NAME = "zen-mcp"; -export const SERVER_VERSION = "0.3.3"; +export const SERVER_VERSION = "0.4.0"; export const BRIDGE_PROTOCOL_VERSION = 2; export const BRIDGE_HOST_ID = "zen-mcp-host"; export const BRIDGE_SOURCE_NAME = "zen-mcp-bridge.js"; diff --git a/test/unit/onboard.test.ts b/test/unit/onboard.test.ts index 756fb4c..33a1939 100644 --- a/test/unit/onboard.test.ts +++ b/test/unit/onboard.test.ts @@ -8,7 +8,7 @@ import { writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { after, describe, it } from "node:test"; import { agentSetupPrompt, @@ -23,6 +23,7 @@ import { moveCursor, pickClients, pickerResult, + scrollWindow, toggleAll, } from "../../src/onboard/picker.js"; @@ -187,6 +188,25 @@ describe("onboard clients", () => { "windsurf", "cline", "zed", + "opencode", + "omp", + "dsh", + "zcode", + "roo-code", + "kilo-code", + "continue", + "amp", + "crush", + "qwen-code", + "kiro", + "warp", + "copilot-cli", + "droid", + "amazon-q", + "goose", + "lm-studio", + "junie", + "pi", ]); }); @@ -258,6 +278,106 @@ describe("onboard clients", () => { ); }); + describe("additional clients", () => { + const temp = mkdtempSync(join(tmpdir(), "zen-mcp-onboard-more-")); + const context = { + home: temp, + platform: "linux" as const, + env: { XDG_CONFIG_HOME: join(temp, "config") }, + command: "zen-mcp", + }; + + after(() => rmSync(temp, { recursive: true, force: true })); + + it("creates OpenCode's nested mcp.servers object", () => { + const result = applyClient("opencode", context); + assert.equal(result.status, "ok"); + + const parsed = JSON.parse(readFileSync(result.path, "utf8")); + assert.deepEqual(parsed.mcp.servers["zen-mcp"], { + type: "local", + command: ["zen-mcp", "serve"], + }); + }); + + it("merges into an existing nested JSON object", () => { + const path = join(temp, ".zcode", "cli", "config.json"); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync( + path, + JSON.stringify({ + mcp: { servers: { other: { command: "other" } } }, + }), + "utf8" + ); + + const result = applyClient("zcode", context); + assert.equal(result.path, path); + + const parsed = JSON.parse(readFileSync(path, "utf8")); + assert.deepEqual(parsed.mcp.servers.other, { command: "other" }); + assert.deepEqual(parsed.mcp.servers["zen-mcp"], { + command: "zen-mcp", + args: ["serve"], + env: {}, + }); + }); + + it("writes and updates the DSH plugin patch once", () => { + const result = applyClient("dsh", context); + let text = readFileSync(result.path, "utf8"); + assert.match(text, /- insert:/); + assert.match(text, /id: zen-mcp/); + assert.match(text, /@deepseek-ai\/dsh-mcp-client/); + assert.match(text, /transport: stdio/); + + applyClient("dsh", context); + text = readFileSync(result.path, "utf8"); + assert.equal((text.match(/id: zen-mcp/g) ?? []).length, 1); + }); + + it("adds one Continue list item", () => { + applyClient("continue", context); + applyClient("continue", context); + + const text = readFileSync( + join(temp, ".continue", "config.yaml"), + "utf8" + ); + assert.equal((text.match(/- name: zen-mcp/g) ?? []).length, 1); + assert.match(text, /mcpServers:\n {2}- name: zen-mcp\n {4}type: stdio/); + }); + + it("keeps other Goose extensions when adding Zen", () => { + const path = join(temp, "config", "goose", "config.yaml"); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync( + path, + "extensions:\n other:\n type: stdio\n\ntheme: dark\n", + "utf8" + ); + + applyClient("goose", context); + + const text = readFileSync(path, "utf8"); + assert.match(text, /other:\n {4}type: stdio/); + assert.match(text, / {2}zen-mcp:\n {4}type: stdio/); + assert.match(text, /theme: dark/); + }); + + it("adds one Crush command", () => { + applyClient("crush", context); + applyClient("crush", context); + + const text = readFileSync( + join(temp, "config", "crush", "crushrc"), + "utf8" + ); + assert.equal((text.match(/^mcp add zen-mcp/mg) ?? []).length, 1); + assert.match(text, /--command zen-mcp --args serve/); + }); + }); + describe("applyClient", () => { const temp = mkdtempSync(join(tmpdir(), "zen-mcp-onboard-")); const context = { @@ -433,6 +553,43 @@ describe("onboard picker", () => { assert.deepEqual(pickerResult(options), { selected: ["a"], other: true }); }); + it("scrolls only when the cursor leaves the window", () => { + assert.deepEqual(scrollWindow(30, 0, 5), { start: 0, end: 5 }); + assert.deepEqual(scrollWindow(30, 4, 5), { start: 0, end: 5 }); + assert.deepEqual(scrollWindow(30, 5, 5), { start: 1, end: 6 }); + assert.deepEqual(scrollWindow(30, 29, 5), { start: 25, end: 30 }); + assert.deepEqual(scrollWindow(30, 6, 5, 0), { start: 2, end: 7 }); + assert.deepEqual(scrollWindow(3, 2, 5), { start: 0, end: 3 }); + }); + + it("keeps the pane fixed while the list scrolls", async () => { + const input = new FakeInput(); + const output = new FakeOutput(); + output.rows = 14; + output.columns = 100; + const options = buildOptions( + Array.from({ length: 20 }, (_, index) => client(`c${index}`)) + ); + + const pending = pickClients(options, { + input: input as unknown as NodeJS.ReadStream, + output: output as unknown as NodeJS.WriteStream, + }); + + for (let index = 0; index < 15; index += 1) { + input.emit("keypress", undefined, key("down")); + } + input.emit("keypress", " ", key("space")); + input.emit("keypress", undefined, key("return")); + + assert.deepEqual(await pending, { selected: ["c15"], other: false }); + const plain = output.text.replace(/\x1b\[[0-9;]*m/g, ""); + assert.match(plain, /↑ \d+ more/); + assert.match(plain, /↓ \d+ more/); + assert.match(plain, /ZEN MCP/); + assert.match(plain, /Selection confirmed/); + }); + it("renders, toggles and confirms from keypress events", async () => { const input = new FakeInput(); const output = new FakeOutput(); @@ -480,6 +637,8 @@ class FakeInput extends EventEmitter { class FakeOutput { isTTY = true; + columns = 80; + rows: number | undefined; text = ""; write(chunk: string): boolean {