From eb013c5791a01088cf071cb5e72743d78fcc1d92 Mon Sep 17 00:00:00 2001 From: Spaxe <182298766+spaxe-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:28:32 +0530 Subject: [PATCH 1/9] fix: read the launch nonce from chrome globals Marionette's chrome sandbox exposes Services, Cc, and Ci, but cannot load resource:// modules on Zen 1.24b, so the explicit Services import failed before ownership could be proven. Read the environment through the sandbox globals, fall back to nsIEnvironment when Services is hidden, and fail with a clear message when neither is available. Refs #15 --- src/zen/runtime.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/zen/runtime.ts b/src/zen/runtime.ts index 609e2cc..07a8827 100644 --- a/src/zen/runtime.ts +++ b/src/zen/runtime.ts @@ -351,11 +351,25 @@ export class ZenRuntime { try { nonce = await this.marionette.executeChrome( [ - "const { Services } = ChromeUtils.importESModule(", - ' "resource://gre/modules/Services.sys.mjs"', - ");", + // Marionette's chrome sandbox exposes these globals but cannot load + // resource:// modules, so use them directly and fall back to the + // component service when a build hides `Services`. + 'const env = typeof Services !== "undefined" && Services.env', + " ? Services.env", + ' : typeof Cc !== "undefined" && typeof Ci !== "undefined"', + ' ? Cc["@mozilla.org/process/environment;1"].getService(', + " Ci.nsIEnvironment", + " )", + " : null;", + "if (!env) {", + " throw new Error(", + ' "Chrome scope is unavailable, so the launch nonce could not be " +', + ' "read. Zen 138 or newer is required, and the launcher must not " +', + ' "drop MOZ_REMOTE_ALLOW_SYSTEM_ACCESS."', + " );", + "}", // nsIEnvironment returns an empty string for unset variables. - 'return Services.env.get("ZEN_MCP_LAUNCH_NONCE") || null;', + 'return env.get("ZEN_MCP_LAUNCH_NONCE") || null;', ].join("\n"), { timeoutMs: 10_000 } ); From f64b74d65bf4c2ad6d94797eef0ecff1318966d9 Mon Sep 17 00:00:00 2001 From: Spaxe <182298766+spaxe-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:28:34 +0530 Subject: [PATCH 2/9] fix: serialize evidence work per tab Batch verification can paint and record two highlights on the same tab at once. Interleaved steps left an overlay host that clear could not find in the live suite. Evidence and clear now run through a per-tab lock so the paint and record sequence for one quote finishes before the next starts. --- src/bridge/ops.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/bridge/ops.ts b/src/bridge/ops.ts index 590db33..6b00026 100644 --- a/src/bridge/ops.ts +++ b/src/bridge/ops.ts @@ -190,6 +190,22 @@ export function createOps(win: ChromeWindow, windowId: string) { } evidenceMarkers.set(tabId, markers.slice(-20)); }; + /** + * Serializes evidence work per tab. Batch verification can run two quotes + * from the same source at once, and interleaved paint/record steps leave an + * overlay host that clear cannot find. + */ + const tabLocks = new Map>(); + const serializeTab = (tabId: string, work: () => Promise): Promise => { + const previous = tabLocks.get(tabId) ?? Promise.resolve(); + const run = previous.then(work, work); + tabLocks.set(tabId, run); + const release = (): void => { + if (tabLocks.get(tabId) === run) tabLocks.delete(tabId); + }; + void run.then(release, release); + return run; + }; const idForTab = (tab: ChromeTab): string => { let id = tabIds.get(tab); @@ -1290,6 +1306,7 @@ export function createOps(win: ChromeWindow, windowId: string) { ); } + return serializeTab(tabId, async () => { const [tab] = resolveTabs([tabId]); const listedUrl = tabUrl(tab); const listedTitle = tabTitle(tab); @@ -1651,6 +1668,7 @@ export function createOps(win: ChromeWindow, windowId: string) { "once the page settles.", }, } satisfies EvidenceOpResult; + }); }, "tabs.evidenceClear": async ( @@ -1660,6 +1678,7 @@ export function createOps(win: ChromeWindow, windowId: string) { if (!tabId) { throw new OpsError("no_tab", "Provide the tabId whose marks to clear."); } + return serializeTab(tabId, async () => { const [tab] = resolveTabs([tabId]); const markers = markersFor(tabId); if (markers.length === 0) { @@ -1678,6 +1697,7 @@ export function createOps(win: ChromeWindow, windowId: string) { const report = coerceEvidenceClear(raw); rememberMarkers(tabId, []); return { tabId, removed: report.removed } satisfies EvidenceClearResult; + }); }, "folders.list": () => From e442c173ef361004b02c1feea6250d9257da471f Mon Sep 17 00:00:00 2001 From: Spaxe <182298766+spaxe-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:28:37 +0530 Subject: [PATCH 3/9] test: allow live runs in a visible window Set ZEN_MCP_TEST_HEADFUL=1 to drop --headless. Isolation still comes from the launcher's own -no-remote, so the visible run exercises the production launch path instead of a test-only shortcut. --- test/integration/helpers.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/integration/helpers.ts b/test/integration/helpers.ts index 19f8f9c..7f32676 100644 --- a/test/integration/helpers.ts +++ b/test/integration/helpers.ts @@ -18,8 +18,10 @@ export function e2eEnabled(): boolean { /** * Only the headless flag. Isolation from a running user Zen must come from * the launcher's own `-no-remote`, so the tests exercise the production path. + * Set ZEN_MCP_TEST_HEADFUL=1 to watch a run in a real window. */ -const TEST_LAUNCH_ARGS = ["--headless"]; +const TEST_LAUNCH_ARGS = + process.env.ZEN_MCP_TEST_HEADFUL === "1" ? [] : ["--headless"]; let generatedProfile: string | null = null; From e03f126034d572bd5ff9bd638a04fc8749121517 Mon Sep 17 00:00:00 2001 From: Spaxe <182298766+spaxe-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:28:37 +0530 Subject: [PATCH 4/9] test: cover the five fixed browser flows live Add live checks for background tab activation, evidence re-highlighting from Show source, Stop from the progress card, split view cleanup, and essentials keeping their original space. Each check drives the real bridge UI and asserts the user-visible result, not just the tool response. Covers #16, #17, #18, #19, #23 --- test/integration/zen.e2e.test.ts | 202 +++++++++++++++++++++++++++++++ 1 file changed, 202 insertions(+) diff --git a/test/integration/zen.e2e.test.ts b/test/integration/zen.e2e.test.ts index 176edcd..ceb16ae 100644 --- a/test/integration/zen.e2e.test.ts +++ b/test/integration/zen.e2e.test.ts @@ -501,6 +501,208 @@ describe( assert.match(owned.text, /Page-owned lookalike marker/); }); + it("selects a background tab and reports it active", async () => { + const opened = await runtime.hub.openTabs({ + urls: [`${page.url}?select=1`], + space: spaceId, + background: true, + }); + const selectId = opened.tabs[0]?.id ?? ""; + assert.ok(selectId); + + const selected = await runtime.hub.selectTab({ + tabId: selectId, + focusWindow: true, + }); + assert.equal(selected.tab.active, true, "selection report is active"); + assert.equal(selected.tab.id, selectId); + assert.equal(selected.windowFocused, true, "window focus is confirmed"); + + const status = await runtime.status(); + assert.equal(status.activeTab?.id, selectId, "status agrees with selection"); + + await runtime.hub.closeTabs({ tabIds: [selectId] }); + }); + + it("re-highlights evidence when Show source is used", async () => { + await runtime.hub.selectTab({ tabId, focusWindow: true }); + const shown = await runtime.showEvidence({ + url: page.url, + quote: EVIDENCE_QUOTE, + claim: "Show source re-highlight", + highlightMs: 1_000, + }); + assert.equal(shown.ok, true, JSON.stringify(shown.error)); + assert.equal(shown.focused, false); + + const expireDeadline = Date.now() + 8_000; + let expired: { hosts: number } | null = null; + while (Date.now() < expireDeadline) { + expired = await inspectContent(page.url); + if (expired?.hosts === 0) break; + await new Promise((resolve) => setTimeout(resolve, 150)); + } + assert.equal(expired?.hosts, 0, "the original highlight expired"); + + const clicked = await pollUi( + ".card.activity:last-of-type", + `const button = card.querySelector("button.action"); + if (!button) return { ok: false, why: "no action button" }; + if (!/Show source/i.test(button.textContent || "")) { + return { ok: false, why: "label: " + button.textContent }; + } + button.click(); + return { ok: true, label: button.textContent || "" };` + ); + assert.equal(clicked.ok, true, `Show source: ${clicked.why}`); + + const revealDeadline = Date.now() + 10_000; + let revealed: { hosts: number; closed: boolean; scrollY: number } | null = + null; + while (Date.now() < revealDeadline) { + revealed = await inspectContent(page.url); + if (revealed && revealed.hosts > 0 && revealed.scrollY > 0) break; + await new Promise((resolve) => setTimeout(resolve, 150)); + } + assert.ok(revealed, "Show source repaints the mark"); + assert.ok(revealed.hosts > 0, "the repainted overlay exists"); + assert.ok(revealed.closed, "the repainted mark stays in a closed root"); + assert.ok(revealed.scrollY > 0, "Show source scrolls to the passage"); + + const status = await runtime.status(); + assert.equal(status.activeTab?.id, tabId, "Show source selects the tab"); + await runtime.clearEvidence({ tabId }); + }); + + it("delivers a Stop press from the progress card", async () => { + const before = await runtime.events({ waitSeconds: 0 }); + const started = await runtime.progress({ + title: "Stop press check", + step: "Waiting for the user", + stoppable: true, + }); + assert.equal(started.delivered, true); + const progressId = started.progress?.id; + assert.ok(progressId); + + const clicked = await pollUi( + ".card.progress-card", + `const button = card.querySelector(".stop-button"); + if (!button) return { ok: false, why: "no stop button" }; + button.click(); + return { ok: true, label: button.textContent || "" };` + ); + assert.equal(clicked.ok, true, `Stop button: ${clicked.why}`); + assert.match(clicked.label, /Stopping/); + + const after = await runtime.events({ + after: before.cursor, + waitSeconds: 10, + }); + assert.ok( + after.events.some((event) => event.kind === "stop"), + "a stop event is recorded" + ); + assert.equal(after.stopped, true, "the stop request is acknowledged"); + + const cleared = await runtime.progress({ done: true }); + assert.equal(cleared.progress?.id, progressId); + }); + + it("closes a split view without leaving residue", async () => { + const opened = await runtime.hub.openTabs({ + urls: [`${page.url}?split-a=1`, `${page.url}?split-b=1`], + space: spaceId, + background: true, + }); + const splitIds = opened.tabs.map((tab) => tab.id); + assert.equal(splitIds.length, 2); + + const before = await runtime.hub.listTabs({ space: spaceId }); + const split = await runtime.hub.openSplit({ + tabIds: splitIds, + activate: true, + }); + assert.equal(split.split, true); + + const closed = await runtime.hub.closeSplit({ + tabId: split.tabIds[0] ?? splitIds[0], + }); + assert.equal(closed.unsplit, true); + + const after = await runtime.hub.listTabs({ space: spaceId }); + const existing = new Set(before.tabs.map((tab) => tab.id)); + const residue = after.tabs + .filter((tab) => !existing.has(tab.id)) + .map((tab) => tab.url); + assert.deepEqual(residue, [], "no stray or duplicated tabs"); + assert.equal( + after.tabs.filter((tab) => tab.splitView).length, + 0, + "no tab still reports a split view" + ); + + for (const id of splitIds) { + await runtime.hub.closeTabs({ tabIds: [id] }).catch(() => undefined); + } + }); + + it("keeps an essential in its original space", async () => { + const otherSpace = await runtime.hub.createSpace({ + name: "Zen MCP Other Space", + switchTo: false, + }); + const otherSpaceId = otherSpace.space.id; + let essentialId = ""; + try { + const opened = await runtime.hub.openTabs({ + urls: [`${page.url}?essential-space=1`], + space: spaceId, + background: true, + }); + essentialId = opened.tabs[0]?.id ?? ""; + assert.ok(essentialId); + assert.equal(opened.tabs[0].spaceId, spaceId); + + await runtime.hub.switchSpace({ space: otherSpaceId }); + const added = await runtime.hub.addEssentials({ + tabIds: [essentialId], + }); + assert.equal(added.changed, 1); + const removed = await runtime.hub.removeEssentials({ + tabIds: [essentialId], + }); + assert.equal(removed.changed, 1); + + const listed = await runtime.hub.listTabs({}); + const restored = listed.tabs.find((tab) => tab.id === essentialId); + assert.ok(restored); + assert.equal( + restored.spaceId, + spaceId, + "remove returns the tab to its original space" + ); + const status = await runtime.status(); + assert.equal( + status.activeSpaceId, + otherSpaceId, + "neither action switches the user's space" + ); + } finally { + if (essentialId) { + await runtime.hub + .closeTabs({ tabIds: [essentialId] }) + .catch(() => undefined); + } + await runtime.hub + .switchSpace({ space: spaceId }) + .catch(() => undefined); + await runtime.hub + .deleteSpace({ space: otherSpaceId }) + .catch(() => undefined); + } + }); + it("deletes a space and the tabs it holds", async () => { const deleted = await runtime.hub.deleteSpace({ space: spaceId }); assert.equal(deleted.deleted, true); From 2413b0ed5348286263f3d587666d23d6f958b406 Mon Sep 17 00:00:00 2001 From: Spaxe <182298766+spaxe-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:28:44 +0530 Subject: [PATCH 5/9] feat: add MCP client onboarding `zen-mcp onboard` lists the supported MCP clients, preselects the ones found on this machine, and merges only the `zen-mcp` stdio entry into each selected client's configuration. Standard JSON clients get `mcpServers`, VS Code gets `servers` with `type: stdio`, Zed gets `context_servers`, and Codex gets `[mcp_servers.zen-mcp]`. JSON files are merged key by key. JSONC files are spliced in place so comments and trailing commas survive, and TOML tables are replaced without touching other servers. Rerunning updates the existing entry instead of adding a duplicate, and an invalid file is reported without being written. `--clients` skips the picker for scripts and non-TTY shells, `--command` sets the command clients should run, and `--clients other` prints a paste-ready runbook with paths, entry shapes, merge rules, validation, and a completion report. Tests cover detection and paths, JSON and JSONC merges, TOML merges, invalid files, picker movement and toggling, and the runbook. README and configuration docs describe the command. --- CHANGELOG.md | 9 + README.md | 19 +- docs/configuration.md | 14 + src/cli.ts | 177 ++++++++ src/onboard/clients.ts | 873 ++++++++++++++++++++++++++++++++++++++ src/onboard/picker.ts | 240 +++++++++++ src/onboard/theme.ts | 31 ++ test/unit/onboard.test.ts | 501 ++++++++++++++++++++++ 8 files changed, 1863 insertions(+), 1 deletion(-) create mode 100644 src/onboard/clients.ts create mode 100644 src/onboard/picker.ts create mode 100644 src/onboard/theme.ts create mode 100644 test/unit/onboard.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 19a1050..ebee53d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ 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). +## [Unreleased] + +### Added + +- `zen-mcp onboard` lists common MCP clients, preselects the ones found on + this machine, and merges a `zen-mcp` stdio server into each selected + client's configuration. An **Other MCP client** option prints a paste-ready + prompt for clients the picker does not know. + ## [0.3.2] - 2026-11-01 ### Fixed diff --git a/README.md b/README.md index ce0a33d..ac945de 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ The installed command is `zen-mcp`. Nothing is installed into Zen itself; the br ```sh zen-mcp setup # detects Zen, writes a config, prints an MCP snippet +zen-mcp onboard # pick MCP clients and add Zen MCP to their config zen-mcp doctor # config, executable, Marionette, bridge, profile, policy zen-mcp status # config, profile mode, and port state ``` @@ -124,7 +125,23 @@ zen-mcp status # config, profile mode, and port state ### Connect an MCP client -Claude Code: +Run the picker: + +```sh +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. + +For scripts or a shell without a TTY, name the clients: + +```sh +zen-mcp onboard --clients claude-code,cursor +zen-mcp onboard --clients all --command /path/to/zen-mcp +zen-mcp onboard --clients other +``` + +Claude Code by hand: ```sh claude mcp add zen-mcp -- zen-mcp serve diff --git a/docs/configuration.md b/docs/configuration.md index ba26e5c..35e4cc5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -10,6 +10,7 @@ zen-mcp launch Launch Zen once, verify ownership, then quit it zen-mcp status Print config, profile mode, and port state zen-mcp doctor Check config, executable, bridge, profile, port, policy zen-mcp setup Detect Zen, write config, print an MCP snippet +zen-mcp onboard Pick MCP clients and add Zen MCP to their config zen-mcp setup --use-default-profile zen-mcp setup --dedicated-profile zen-mcp config show Print the config path and values @@ -33,6 +34,19 @@ zen-mcp config set `setup` does not install anything into Zen. The bridge is injected at runtime. +## MCP clients + +`onboard` merges Zen MCP into MCP client configurations: + +```text +zen-mcp onboard +zen-mcp onboard --clients claude-code,cursor +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. + ## File locations Config file: diff --git a/src/cli.ts b/src/cli.ts index 6028426..e45b9b3 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -9,6 +9,19 @@ import { type ZenMcpConfig, } from "./config.js"; import { createZenMcpServer } from "./mcp/server.js"; +import { + agentSetupPrompt, + applyClient, + catalog, + clientIds, +} from "./onboard/clients.js"; +import { + buildOptions, + pickClients, + SelectionCancelled, + type PickerResult, +} from "./onboard/picker.js"; +import { createTheme } from "./onboard/theme.js"; import { BRAND, SERVER_VERSION } from "./shared/brand.js"; import { createLogger } from "./utils/logger.js"; import { runDoctor, type DoctorReport } from "./zen/doctor.js"; @@ -102,6 +115,26 @@ program .option("--skip-doctor", "Write the config without running diagnostics.") .action((options) => setup(options)); +program + .command("onboard") + .description( + "Pick MCP clients and add Zen MCP to their configuration." + ) + .option( + "--clients ", + "Comma-separated client ids or 'all'. Skips the interactive picker." + ) + .option( + "--command ", + "Command clients should run. Defaults to `zen-mcp`." + ) + .option("--other", "Also print a setup prompt for any other client.") + .addHelpText( + "after", + `\nClient ids: ${clientIds().join(", ")}, other.` + ) + .action((options) => onboard(options)); + const configCommand = program .command("config") .description("Show or change the saved configuration."); @@ -325,6 +358,150 @@ async function setup(options: { "\nIf Zen MCP is not on your PATH, point command at the absolute path " + "of dist/cli.js and keep args as [\"serve\"]." ); + console.log( + "Run `zen-mcp onboard` to add Zen MCP to a supported MCP client." + ); +} + +async function onboard(options: { + clients?: string; + command?: string; + other?: boolean; +}): Promise { + const context = { command: options.command?.trim() || "zen-mcp" }; + const theme = createTheme(process.stdout); + const rule = theme.unicode ? "─".repeat(56) : "-".repeat(56); + const entries = catalog(context); + const known = new Set(entries.map((entry) => entry.id)); + + let selected: string[]; + let includeOther = Boolean(options.other); + + if (options.clients?.trim()) { + const tokens = options.clients + .split(",") + .map((token) => token.trim()) + .filter(Boolean); + const unknown = tokens.filter( + (token) => token !== "other" && token !== "all" && !known.has(token) + ); + if (unknown.length > 0) { + console.error(`Unknown client(s): ${unknown.join(", ")}.`); + console.error(`Valid clients: ${[...known].join(", ")}, other, all.`); + process.exitCode = 1; + return; + } + selected = tokens.includes("all") + ? entries.map((entry) => entry.id) + : tokens.filter((token) => token !== "other"); + includeOther = includeOther || tokens.includes("other"); + } else { + if (!process.stdin.isTTY || !process.stdout.isTTY) { + console.error("The client picker needs an interactive terminal."); + console.error("Use --clients with a comma-separated list instead:"); + console.error(" zen-mcp onboard --clients claude-code,cursor,other"); + console.error(`Valid clients: ${[...known].join(", ")}, other.`); + process.exitCode = 1; + return; + } + let result: PickerResult; + try { + result = await pickClients(buildOptions(entries)); + } catch (error) { + if (error instanceof SelectionCancelled) { + console.log("Cancelled. No client configuration was changed."); + process.exitCode = 130; + return; + } + throw error; + } + selected = result.selected; + includeOther = includeOther || result.other; + } + + if (selected.length === 0 && !includeOther) { + console.log( + theme.dim(" Nothing selected. No client configuration was changed.") + ); + return; + } + + if (!existsSync(configFilePath())) { + const updates: Partial = {}; + try { + updates.zenPath = findZenExecutable(loadConfig()); + } catch { + // `zen-mcp doctor` explains detection failures. + } + const path = saveConfig(updates); + const mark = theme.unicode ? theme.green("✓") : "[ ok ]"; + console.log(` ${mark} Saved config ${theme.dim(path)}`); + console.log(""); + } + + let failed = 0; + if (selected.length > 0) { + let connected = 0; + console.log(` ${theme.bold("Client configuration")}`); + console.log(` ${theme.dim(rule)}`); + + for (const id of selected) { + const result = applyClient(id, context); + if (result.status === "ok") { + connected += 1; + const mark = theme.unicode ? theme.green("✓") : "[ ok ]"; + console.log( + ` ${mark} ${result.label.padEnd(18)} ${theme.dim(result.message)}` + ); + } else { + failed += 1; + const mark = theme.unicode ? theme.red("✗") : "[FAIL]"; + console.log( + ` ${mark} ${result.label.padEnd(18)} ${theme.red(result.message)}` + ); + } + } + + console.log(""); + console.log( + ` ${ + failed === 0 + ? theme.green( + `${connected} client${connected === 1 ? "" : "s"} connected` + ) + : theme.yellow(`${connected} connected, ${failed} failed`) + }` + ); + } + + if (includeOther) { + console.log(""); + console.log(` ${theme.bold("Other client")}`); + console.log(` ${theme.dim(rule)}`); + console.log(` ${theme.dim("Paste this prompt into your agent.")}`); + console.log(""); + console.log(agentSetupPrompt(context.command)); + } + + console.log(""); + console.log( + theme.dim( + selected.length > 0 + ? " Restart the selected clients so they load the server. On the first " + + "browser tool, approve the card in Zen." + : " Restart the client after your agent updates its configuration. On " + + "the first browser tool, approve the card in Zen." + ) + ); + if (!options.command) { + console.log( + theme.dim( + " If `zen-mcp` is not on your PATH, rerun with " + + "--command ." + ) + ); + } + if (failed > 0) process.exitCode = 1; } function configShow(): void { diff --git a/src/onboard/clients.ts b/src/onboard/clients.ts new file mode 100644 index 0000000..78e8f3a --- /dev/null +++ b/src/onboard/clients.ts @@ -0,0 +1,873 @@ +import { existsSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { atomicWritePrivate, readFileTextBounded } from "../utils/safe-file.js"; + +const MAX_CLIENT_CONFIG_BYTES = 20 * 1024 * 1024; + +/** Name the server is registered under in every client. */ +export const SERVER_ENTRY_NAME = "zen-mcp"; +/** Arguments every client should pass to the server command. */ +export const SERVER_ARGS = ["serve"]; + +export interface ClientContext { + /** Command clients should run. Defaults to `zen-mcp`. */ + command?: string; + home?: string; + platform?: NodeJS.Platform; + env?: NodeJS.ProcessEnv; +} + +interface ResolvedContext { + command: string; + home: string; + platform: NodeJS.Platform; + env: NodeJS.ProcessEnv; + configBase: string; +} + +interface ClientDefinition { + id: string; + label: string; + detail: string; + popular: boolean; + format: "json" | "toml"; + configPaths(ctx: ResolvedContext): string[]; + /** Directories or files whose presence means the client is installed. */ + detectPaths(ctx: ResolvedContext): string[]; + json?: { + key: string; + entry(ctx: ResolvedContext): Record; + }; + toml?: { + section: string; + values(ctx: ResolvedContext): Record; + }; +} + +export interface ClientEntry { + id: string; + label: string; + detail: string; + popular: boolean; + detected: boolean; + /** File that will be created or updated. */ + configPath: string; + format: "json" | "toml"; +} + +export interface ApplyResult { + id: string; + label: string; + path: string; + status: "ok" | "failed"; + message: string; +} + +const CLINE_SETTINGS = join( + "User", + "globalStorage", + "saoudrizwan.claude-dev", + "settings", + "cline_mcp_settings.json" +); + +const DEFINITIONS: ClientDefinition[] = [ + { + id: "claude-code", + label: "Claude Code", + detail: "Anthropic's terminal agent", + popular: true, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".claude.json")], + detectPaths: (ctx) => [ + join(ctx.home, ".claude.json"), + join(ctx.home, ".claude"), + ], + json: { + key: "mcpServers", + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "claude-desktop", + label: "Claude Desktop", + detail: "The Claude desktop app", + popular: true, + format: "json", + configPaths: (ctx) => [ + join(ctx.configBase, "Claude", "claude_desktop_config.json"), + ], + detectPaths: (ctx) => [join(ctx.configBase, "Claude")], + json: { + key: "mcpServers", + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "cursor", + label: "Cursor", + detail: "Cursor editor", + popular: true, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".cursor", "mcp.json")], + detectPaths: (ctx) => [join(ctx.home, ".cursor")], + json: { + key: "mcpServers", + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "vscode", + label: "VS Code", + detail: "GitHub Copilot agent mode", + popular: true, + format: "json", + configPaths: (ctx) => [ + join(ctx.configBase, "Code", "User", "mcp.json"), + join(ctx.configBase, "Code - Insiders", "User", "mcp.json"), + ], + detectPaths: (ctx) => [ + join(ctx.configBase, "Code", "User"), + join(ctx.configBase, "Code - Insiders", "User"), + ], + json: { + key: "servers", + entry: (ctx) => ({ + type: "stdio", + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "codex", + label: "Codex CLI", + detail: "OpenAI Codex terminal agent", + popular: true, + format: "toml", + configPaths: (ctx) => [ + join(ctx.env.CODEX_HOME ?? join(ctx.home, ".codex"), "config.toml"), + ], + detectPaths: (ctx) => [ + ctx.env.CODEX_HOME ?? join(ctx.home, ".codex"), + ], + toml: { + section: "mcp_servers", + values: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "gemini-cli", + label: "Gemini CLI", + detail: "Google's terminal agent", + popular: true, + format: "json", + configPaths: (ctx) => [join(ctx.home, ".gemini", "settings.json")], + detectPaths: (ctx) => [join(ctx.home, ".gemini")], + json: { + key: "mcpServers", + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "windsurf", + label: "Windsurf", + detail: "Windsurf editor", + popular: false, + format: "json", + configPaths: (ctx) => [ + join(ctx.home, ".codeium", "windsurf", "mcp_config.json"), + ], + detectPaths: (ctx) => [join(ctx.home, ".codeium", "windsurf")], + json: { + key: "mcpServers", + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "cline", + label: "Cline", + detail: "Cline extension for VS Code-compatible editors", + popular: false, + format: "json", + configPaths: (ctx) => [ + join(ctx.configBase, "Code", CLINE_SETTINGS), + join(ctx.configBase, "Cursor", CLINE_SETTINGS), + join(ctx.configBase, "Windsurf", CLINE_SETTINGS), + ], + detectPaths: (ctx) => [ + dirname(join(ctx.configBase, "Code", CLINE_SETTINGS)), + dirname(join(ctx.configBase, "Cursor", CLINE_SETTINGS)), + dirname(join(ctx.configBase, "Windsurf", CLINE_SETTINGS)), + ], + json: { + key: "mcpServers", + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, + { + id: "zed", + label: "Zed", + detail: "Zed editor", + popular: false, + format: "json", + configPaths: (ctx) => [ + join(ctx.configBase, ctx.platform === "linux" ? "zed" : "Zed", "settings.json"), + ], + detectPaths: (ctx) => [ + join(ctx.configBase, ctx.platform === "linux" ? "zed" : "Zed"), + ], + json: { + key: "context_servers", + entry: (ctx) => ({ + command: ctx.command, + args: [...SERVER_ARGS], + }), + }, + }, +]; + +/** Lists every supported client id. */ +export function clientIds(): string[] { + return DEFINITIONS.map((definition) => definition.id); +} + +/** Lists every supported client and its resolved config path. */ +export function catalog(ctx: ClientContext = {}): ClientEntry[] { + const resolved = resolveContext(ctx); + return DEFINITIONS.map((definition) => { + const paths = definition.configPaths(resolved); + return { + id: definition.id, + label: definition.label, + detail: definition.detail, + popular: definition.popular, + detected: definition.detectPaths(resolved).some((path) => existsSync(path)), + configPath: paths.find((path) => existsSync(path)) ?? paths[0], + format: definition.format, + }; + }); +} + +/** Adds or replaces the Zen MCP server in one client's configuration. */ +export function applyClient(id: string, ctx: ClientContext = {}): ApplyResult { + const definition = DEFINITIONS.find((entry) => entry.id === id); + if (!definition) { + return { + id, + label: id, + path: "", + status: "failed", + message: "unknown client", + }; + } + + const resolved = resolveContext(ctx); + const paths = definition.configPaths(resolved); + const path = paths.find((candidate) => existsSync(candidate)) ?? paths[0]; + const existed = existsSync(path); + + try { + const existing = existed + ? readFileTextBounded(path, MAX_CLIENT_CONFIG_BYTES) + : undefined; + + if (definition.format === "toml") { + const toml = definition.toml; + if (!toml) throw new Error("TOML settings are missing for this client"); + const next = mergeTomlServer( + existing ?? "", + `${toml.section}.${SERVER_ENTRY_NAME}`, + toml.values(resolved) + ); + atomicWritePrivate(path, next); + } 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)); + atomicWritePrivate(path, next); + } + + return { + id: definition.id, + label: definition.label, + path, + status: "ok", + message: `${existed ? "Updated" : "Created"} ${path}`, + }; + } catch (error) { + return { + id: definition.id, + label: definition.label, + path, + status: "failed", + message: `${path}: ${(error as Error).message}`, + }; + } +} + +/** + * Merges one server entry into a JSON config without touching other keys. + * The target key must be an object (or absent); anything else is an error + * rather than being overwritten. + */ +export function mergeJsonServer( + existing: string | undefined, + key: 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`; + } + + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch (error) { + try { + return mergeJsoncServer(text, key, entry); + } catch { + throw new Error( + `existing file is not valid JSON or JSONC (${(error as Error).message})` + ); + } + } + + 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`); + } + + root[key] = { + ...((current as Record | undefined) ?? {}), + [SERVER_ENTRY_NAME]: entry, + }; + return `${JSON.stringify(root, null, 2)}\n`; +} + +interface JsoncMember { + key: string; + keyStart: number; + valueStart: number; + valueEnd: number; +} + +interface JsoncObject { + open: number; + close: number; + members: JsoncMember[]; +} + +/** + * 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( + text: string, + key: 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`); + } + const serverMap = scanJsoncObject(text, target.valueStart); + if (!serverMap) throw new Error(`"${key}" is not a complete object`); + + const current = serverMap.members.find( + (member) => member.key === SERVER_ENTRY_NAME + ); + if (!current) { + return insertJsoncMember(text, serverMap, SERVER_ENTRY_NAME, entry); + } + + const inline = !text.slice(current.valueStart, current.valueEnd).includes("\n"); + const replacement = inline + ? JSON.stringify(entry) + : indentJson( + JSON.stringify(entry, null, 2), + memberIndent(text, current.keyStart, serverMap) + ); + return ( + text.slice(0, current.valueStart) + + replacement + + text.slice(current.valueEnd) + ); +} + +function insertJsoncMember( + text: string, + object: JsoncObject, + name: string, + entry: Record +): string { + let source = text; + let close = object.close; + const last = object.members[object.members.length - 1]; + + if (last) { + const between = source.slice(last.valueEnd, object.close); + if (!between.includes(",")) { + source = + source.slice(0, last.valueEnd) + "," + source.slice(last.valueEnd); + close += 1; + } + } + + const lineStart = source.lastIndexOf("\n", close - 1) + 1; + const onOwnLine = + lineStart > object.open && source.slice(lineStart, close).trim() === ""; + + if (!onOwnLine) { + const inline = JSON.stringify({ [name]: entry }).slice(1, -1); + return `${source.slice(0, close)} ${inline} ${source.slice(close)}`; + } + + const indent = last + ? memberIndent(source, last.keyStart, object) + : `${closeIndent(source, object)} `; + const entryText = `${JSON.stringify(name)}: ${indentJson( + JSON.stringify(entry, null, 2), + indent + )}`; + return ( + source.slice(0, lineStart) + + `${indent}${entryText}\n` + + source.slice(lineStart) + ); +} + +function scanJsoncObject(text: string, open: number): JsoncObject | null { + const members: JsoncMember[] = []; + let index = open + 1; + let expectingMember = true; + + while (true) { + index = skipJsoncTrivia(text, index); + if (index >= text.length) return null; + + const char = text[index]; + if (char === "}") { + return { open, close: index, members }; + } + if (!expectingMember) { + if (char !== ",") return null; + index += 1; + expectingMember = true; + continue; + } + if (char !== '"') return null; + + const keyStart = index; + const keyEnd = scanJsoncString(text, index); + if (keyEnd < 0) return null; + let key: string; + try { + key = JSON.parse(text.slice(keyStart, keyEnd)) as string; + } catch { + return null; + } + + index = skipJsoncTrivia(text, keyEnd); + if (text[index] !== ":") return null; + index = skipJsoncTrivia(text, index + 1); + + const valueStart = index; + const valueEnd = skipJsoncValue(text, index); + if (valueEnd < 0) return null; + members.push({ key, keyStart, valueStart, valueEnd }); + + index = skipJsoncTrivia(text, valueEnd); + expectingMember = false; + } +} + +function skipJsoncTrivia(text: string, index: number): number { + let cursor = index; + while (cursor < text.length) { + const char = text[cursor]; + if (/\s/.test(char)) { + cursor += 1; + } else if (char === "/" && text[cursor + 1] === "/") { + cursor += 2; + while (cursor < text.length && text[cursor] !== "\n") cursor += 1; + } else if (char === "/" && text[cursor + 1] === "*") { + cursor += 2; + while ( + cursor < text.length && + !(text[cursor] === "*" && text[cursor + 1] === "/") + ) { + cursor += 1; + } + cursor += 2; + } else { + break; + } + } + return Math.min(cursor, text.length); +} + +function scanJsoncString(text: string, index: number): number { + let cursor = index + 1; + while (cursor < text.length) { + if (text[cursor] === "\\") { + cursor += 2; + } else if (text[cursor] === '"') { + return cursor + 1; + } else { + cursor += 1; + } + } + return -1; +} + +function skipJsoncValue(text: string, index: number): number { + const char = text[index]; + if (char === '"') return scanJsoncString(text, index); + if (char === "{" || char === "[") { + let depth = 0; + let cursor = index; + while (cursor < text.length) { + const current = text[cursor]; + if (current === '"') { + const end = scanJsoncString(text, cursor); + if (end < 0) return -1; + cursor = end; + continue; + } + if (current === "/" && (text[cursor + 1] === "/" || text[cursor + 1] === "*")) { + cursor = skipJsoncTrivia(text, cursor); + continue; + } + if (current === "{" || current === "[") depth += 1; + else if (current === "}" || current === "]") { + depth -= 1; + if (depth === 0) return cursor + 1; + } + cursor += 1; + } + return -1; + } + + let cursor = index; + while (cursor < text.length && !/[\s,\]}]/.test(text[cursor])) cursor += 1; + return cursor > index ? cursor : -1; +} + +function memberIndent(text: string, keyStart: number, object: JsoncObject): string { + let start = keyStart; + while (start > object.open && (text[start - 1] === " " || text[start - 1] === "\t")) { + start -= 1; + } + if (start > object.open && text[start - 1] === "\n") { + return text.slice(start, keyStart); + } + const openLine = text.lastIndexOf("\n", object.open - 1) + 1; + return `${" ".repeat(object.open - openLine + 2)}`; +} + +function closeIndent(text: string, object: JsoncObject): string { + const start = text.lastIndexOf("\n", object.close - 1) + 1; + const between = text.slice(start, object.close); + if (/^[ \t]*$/.test(between)) return between; + const openLine = text.lastIndexOf("\n", object.open - 1) + 1; + return " ".repeat(object.open - openLine); +} + +function indentJson(value: string, indent: string): string { + return value.replace(/\n/g, `\n${indent}`); +} + +/** + * Adds or replaces a TOML table for one server. Only that table is touched; + * comments, other tables and unrelated keys keep their place. + */ +export function mergeTomlServer( + existing: string, + table: string, + values: Record +): string { + const lines = existing ? existing.replace(/\r\n/g, "\n").split("\n") : []; + const header = `[${table}]`; + const headerPattern = new RegExp( + `^\\s*\\[\\s*(?:"${escapeRegExp(table)}"|'${escapeRegExp(table)}'|${escapeRegExp( + table + )})\\s*\\]\\s*(?:#.*)?$` + ); + const block = [ + header, + ...Object.entries(values).map( + ([name, value]) => `${name} = ${tomlValue(value)}` + ), + ]; + + const start = lines.findIndex((line) => headerPattern.test(line)); + if (start >= 0) { + let end = start + 1; + while (end < lines.length && !/^\s*\[/.test(lines[end])) end += 1; + lines.splice(start, end - start, ...block); + } else { + while (lines.length > 0 && lines[lines.length - 1].trim() === "") { + lines.pop(); + } + if (lines.length > 0) lines.push(""); + lines.push(...block); + } + + return `${lines.join("\n")}\n`; +} + +/** A paste-ready runbook for any client the picker does not know. */ +export function agentSetupPrompt( + command = "zen-mcp", + ctx: ClientContext = {} +): string { + const resolved = resolveContext({ ...ctx, command }); + const locations = DEFINITIONS.map((definition) => { + const path = placeholderPath(definition.configPaths(resolved)[0], resolved); + const detail = + definition.id === "vscode" + ? " (Insiders uses the same path under `Code - Insiders`)" + : definition.id === "cline" + ? " (same relative path under Cursor or Windsurf)" + : ""; + 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`"; + return `- ${definition.label}: \`${path}\`${detail};${shape}.`; + }).join("\n"); + + return [ + "# Set up Zen MCP in this agent", + "", + "Add a local stdio MCP server named `zen-mcp` to the agent you are running in.", + "Do the work yourself by running commands and editing the client's configuration.", + "Do not ask me to run any of these commands. Only ask me when a step needs a", + "browser approval or when no configuration file can be found.", + "", + "## Server definition", + "", + "- Name: zen-mcp", + "- Transport: stdio, local process (no URL, no OAuth)", + `- Command: ${command}`, + `- Arguments: ${JSON.stringify(SERVER_ARGS)}`, + "- Environment: none", + "", + "If the command is not on PATH, resolve it with `where ` on Windows or", + "`command -v ` on macOS and Linux. Use the absolute path as the command", + "and keep the arguments unchanged.", + "", + "## 1. Prefer the client's own command", + "", + "If the client has a first-class way to add a stdio server, use it instead of", + "editing files. Example for Claude Code:", + "", + ` claude mcp add zen-mcp -- "${command}" serve`, + "", + "Then skip to step 4. An add command that expects a URL is the wrong tool.", + "", + "## 2. Find the configuration file", + "", + "Use the first location that exists for this client:", + "", + locations, + "", + "For any other client, look for a top-level `mcpServers`, `servers` or", + "`context_servers` object in its settings, or follow its official MCP", + "documentation. Ask me only if no configuration file can be found.", + "", + "## 3. Merge the entry", + "", + "- Preserve every existing server, key, comment and trailing comma.", + "- Edit only the `zen-mcp` member. If it already exists, update it instead of", + " adding a duplicate.", + "- Never replace the whole file with a generated object.", + "- For JSONC files (VS Code, Zed), splice the `zen-mcp` member in place so", + " comments and formatting survive.", + "- Do not reorder or reformat unrelated settings.", + "", + "Standard JSON clients use a top-level `mcpServers` object:", + "", + " {", + ' "mcpServers": {', + ' "zen-mcp": {', + ' "command": "",', + ' "args": ["serve"]', + " }", + " }", + " }", + "", + "VS Code uses `servers` and requires the transport type:", + "", + " {", + ' "servers": {', + ' "zen-mcp": {', + ' "type": "stdio",', + ' "command": "",', + ' "args": ["serve"]', + " }", + " }", + " }", + "", + "Zed uses `context_servers` with the same command and args:", + "", + " {", + ' "context_servers": {', + ' "zen-mcp": {', + ' "command": "",', + ' "args": ["serve"]', + " }", + " }", + " }", + "", + "Codex CLI uses TOML:", + "", + " [mcp_servers.zen-mcp]", + ' command = ""', + ' args = ["serve"]', + "", + "## 4. Validate", + "", + "- Parse the file in its own format and confirm there is exactly one `zen-mcp`", + " entry with the command and arguments above.", + "- Confirm no other server was removed, renamed or changed.", + "- If the client has a list command such as `claude mcp list`, run it and confirm", + " `zen-mcp` appears. Do not start the server manually just to test it.", + "", + "## 5. Reload", + "", + "Restart the client or run its reload command so it picks up the new server.", + "Tell me which one you did.", + "", + "## 6. Report", + "", + "Reply with the client name, the file or command you changed, the validation", + "result and the reload instruction. End with:", + "", + " ┌─ Zen MCP setup ──────────────────────────────────────┐", + " │ ✓ Server zen-mcp (stdio) │", + " │ ✓ Config │", + " │ │", + " │ Restart to load the server. │", + " └──────────────────────────────────────────────────────┘", + "", + "## Constraints", + "", + "- Zen MCP runs locally over stdio. Do not add a remote URL, API key or OAuth", + " flow, and do not change the command or arguments.", + "- Do not install or patch anything inside Zen; the bridge is injected at", + " runtime.", + '- Do not launch a browser to test the server. On the first real browser tool', + ' call, Zen shows an approval card. Tell me to click "Allow this session".', + ].join("\n"); +} + +function resolveContext(ctx: ClientContext): ResolvedContext { + const platform = ctx.platform ?? process.platform; + const home = ctx.home ?? homedir(); + const env = ctx.env ?? process.env; + const command = ctx.command?.trim() || "zen-mcp"; + + const configBase = + platform === "win32" + ? env.APPDATA ?? join(home, "AppData", "Roaming") + : platform === "darwin" + ? join(home, "Library", "Application Support") + : env.XDG_CONFIG_HOME ?? join(home, ".config"); + + return { command, home, platform, env, configBase }; +} + +/** Replaces machine-specific roots so prompts never embed a real user name. */ +function placeholderPath(path: string, ctx: ResolvedContext): string { + const windows = ctx.platform === "win32"; + const roots: Array<[string, string]> = []; + const codexHome = ctx.env.CODEX_HOME; + if (codexHome) { + roots.push([codexHome, windows ? "%CODEX_HOME%" : "$CODEX_HOME"]); + } + if (windows) { + roots.push([ctx.configBase, "%APPDATA%"]); + } else if (ctx.env.XDG_CONFIG_HOME) { + roots.push([ctx.configBase, "$XDG_CONFIG_HOME"]); + } + roots.push([ctx.home, windows ? "%USERPROFILE%" : "~"]); + + const normalize = (value: string) => { + const slashed = value.replace(/\\/g, "/"); + return windows ? slashed.toLowerCase() : slashed; + }; + const target = normalize(path); + + for (const [root, label] of roots) { + const prefix = normalize(root); + if (target === prefix) return label; + if (target.startsWith(`${prefix}/`)) { + const rest = path.slice(root.length); + const separator = windows ? "\\" : "/"; + return label + rest.replace(windows ? /\//g : /\\/g, separator); + } + } + return path; +} + +function tomlValue(value: string | string[]): string { + if (Array.isArray(value)) { + return `[${value.map((entry) => JSON.stringify(entry)).join(", ")}]`; + } + return JSON.stringify(value); +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} diff --git a/src/onboard/picker.ts b/src/onboard/picker.ts new file mode 100644 index 0000000..ecf9f3e --- /dev/null +++ b/src/onboard/picker.ts @@ -0,0 +1,240 @@ +import { emitKeypressEvents } from "node:readline"; +import type { Key } from "node:readline"; +import type { ClientEntry } from "./clients.js"; +import { createTheme } from "./theme.js"; + +export interface SelectOption { + id: string; + label: string; + detail: string; + detected: boolean; + popular: boolean; + other?: boolean; + selected: boolean; +} + +export interface PickerResult { + selected: string[]; + other: boolean; +} + +export class SelectionCancelled extends Error {} + +const OTHER_ID = "other"; + +/** + * Builds the picker rows. Only clients found on this machine are preselected; + * when nothing is found, nothing is checked. + */ +export function buildOptions(clients: ClientEntry[]): SelectOption[] { + return [ + ...clients.map((client) => ({ + id: client.id, + label: client.label, + detail: client.detail, + detected: client.detected, + popular: client.popular, + selected: client.detected, + })), + { + id: OTHER_ID, + label: "Other MCP client", + detail: "Print a setup prompt for any agent", + detected: false, + popular: false, + other: true, + selected: false, + }, + ]; +} + +/** Moves the cursor by one row and wraps around the list. */ +export function moveCursor(options: SelectOption[], cursor: number, delta: number): number { + const size = options.length; + return (((cursor + delta) % size) + size) % 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) => + option.other ? option : { ...option, selected } + ); +} + +export function pickerResult(options: SelectOption[]): PickerResult { + return { + selected: options + .filter((option) => !option.other && option.selected) + .map((option) => option.id), + other: options.some((option) => option.other && option.selected), + }; +} + +/** + * Renders a dependency-free multi-select in the terminal. Arrow keys move, + * space toggles, `a` toggles every client, enter confirms and ctrl+c cancels. + */ +export async function pickClients( + options: SelectOption[], + streams: { input?: NodeJS.ReadStream; output?: NodeJS.WriteStream } = {} +): Promise { + const input = streams.input ?? process.stdin; + const output = streams.output ?? process.stdout; + if (!input.isTTY || !output.isTTY) { + throw new Error("the client picker needs an interactive terminal"); + } + + const rows = [...options]; + let cursor = 0; + let painted = 0; + const theme = createTheme(output); + const columns = output.columns ?? 80; + 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 paint = (final = false): void => { + const lines: string[] = []; + const count = rows.filter((row) => !row.other && row.selected).length; + const otherSelected = rows.some((row) => row.other && row.selected); + + lines.push( + ` ${theme.cyan("◆")} ${theme.bold("ZEN MCP")} ${theme.dim("onboard")}` + ); + lines.push(` ${rule}`); + 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 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; + lines.push( + ` ${marker} ${box} ${label} ${tag} ${theme.dim(detail)}`.trimEnd() + ); + }); + + lines.push(""); + if (!rows.some((row) => row.detected)) { + lines.push( + ` ${theme.yellow("No clients detected.")} ${theme.dim( + "Select one below, or choose Other." + )}` + ); + } + const selection = + count > 0 + ? theme.green(`${count} selected${otherSelected ? " + other" : ""}`) + : otherSelected + ? theme.green("other client") + : theme.dim("nothing selected"); + lines.push(` ${selection}`); + lines.push( + final + ? ` ${theme.dim("Selection confirmed.")}` + : ` ${theme.dim( + "↑↓ move · space toggle · a all · enter confirm · esc cancel" + )}` + ); + + if (painted > 0) { + output.write(`\x1b[${painted}A`); + output.write("\x1b[0J"); + } + output.write(`${lines.join("\n")}\n`); + painted = lines.length; + }; + + emitKeypressEvents(input); + input.setRawMode(true); + input.resume(); + output.write("\x1b[?25l"); + paint(); + + return await new Promise((resolve, reject) => { + const cleanup = (): void => { + input.off("keypress", onKey); + input.setRawMode(false); + input.pause(); + output.write("\x1b[?25h"); + }; + + const finish = (result: PickerResult): void => { + cleanup(); + paint(true); + resolve(result); + }; + + const onKey = (_str: string | undefined, key: Key): void => { + if (key.ctrl && key.name === "c") { + cleanup(); + output.write("\n"); + reject(new SelectionCancelled("cancelled")); + return; + } + if (key.name === "escape") { + cleanup(); + output.write("\n"); + reject(new SelectionCancelled("cancelled")); + return; + } + switch (key.name) { + case "up": + cursor = moveCursor(rows, cursor, -1); + break; + case "down": + cursor = moveCursor(rows, cursor, 1); + break; + case "space": + case "spacebar": + rows[cursor] = { ...rows[cursor], selected: !rows[cursor].selected }; + break; + case "a": + if (!key.ctrl && !key.meta) { + const everySelected = rows + .filter((row) => !row.other) + .every((row) => row.selected); + rows.splice(0, rows.length, ...toggleAll(rows, !everySelected)); + } + break; + case "return": + case "enter": + finish(pickerResult(rows)); + return; + default: + break; + } + paint(); + }; + + input.on("keypress", onKey); + }); +} diff --git a/src/onboard/theme.ts b/src/onboard/theme.ts new file mode 100644 index 0000000..82b2534 --- /dev/null +++ b/src/onboard/theme.ts @@ -0,0 +1,31 @@ +export interface Theme { + color: boolean; + unicode: boolean; + bold(text: string): string; + dim(text: string): string; + cyan(text: string): string; + green(text: string): string; + yellow(text: string): string; + red(text: string): string; +} + +/** ANSI styling that turns itself off for pipes, NO_COLOR and dumb terminals. */ +export function createTheme(output: NodeJS.WriteStream): Theme { + const color = + Boolean(output.isTTY) && + !process.env.NO_COLOR && + process.env.TERM !== "dumb"; + const wrap = (code: string) => (text: string) => + color ? `\x1b[${code}m${text}\x1b[0m` : text; + + return { + color, + unicode: Boolean(output.isTTY), + bold: wrap("1"), + dim: wrap("2"), + cyan: wrap("36"), + green: wrap("32"), + yellow: wrap("33"), + red: wrap("31"), + }; +} diff --git a/test/unit/onboard.test.ts b/test/unit/onboard.test.ts new file mode 100644 index 0000000..756fb4c --- /dev/null +++ b/test/unit/onboard.test.ts @@ -0,0 +1,501 @@ +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, describe, it } from "node:test"; +import { + agentSetupPrompt, + applyClient, + catalog, + clientIds, + mergeJsonServer, + mergeTomlServer, +} from "../../src/onboard/clients.js"; +import { + buildOptions, + moveCursor, + pickClients, + pickerResult, + toggleAll, +} from "../../src/onboard/picker.js"; + +const SERVER = { command: "zen-mcp", args: ["serve"] }; + +describe("onboard clients", () => { + it("merges a server into JSON without touching other entries", () => { + const existing = JSON.stringify( + { + theme: "dark", + mcpServers: { other: { command: "other" } }, + }, + null, + 2 + ); + const parsed = JSON.parse(mergeJsonServer(existing, "mcpServers", SERVER)); + + assert.equal(parsed.theme, "dark"); + assert.deepEqual(parsed.mcpServers.other, { command: "other" }); + assert.deepEqual(parsed.mcpServers["zen-mcp"], SERVER); + }); + + it("replaces an existing zen-mcp entry and creates the key when missing", () => { + const replaced = JSON.parse( + mergeJsonServer( + JSON.stringify({ servers: { "zen-mcp": { command: "old" } } }), + "servers", + { type: "stdio", ...SERVER } + ) + ); + assert.deepEqual(replaced.servers["zen-mcp"], { + type: "stdio", + ...SERVER, + }); + + const created = JSON.parse( + mergeJsonServer(undefined, "context_servers", SERVER) + ); + assert.deepEqual(created.context_servers["zen-mcp"], SERVER); + }); + + it("refuses to overwrite a non-object server map or broken JSON", () => { + assert.throws( + () => mergeJsonServer('{"mcpServers": []}', "mcpServers", SERVER), + /"mcpServers" is not a JSON object/ + ); + assert.throws( + () => mergeJsonServer("{ nope", "mcpServers", SERVER), + /not valid JSON/ + ); + }); + + it("preserves comments and trailing commas in JSONC files", () => { + const original = [ + "{", + " // keep this theme comment", + ' "theme": "dark",', + ' "context_servers": {', + ' "other": { "command": "other" }, // keep this server', + " },", + "}", + "", + ].join("\n"); + + const next = mergeJsonServer(original, "context_servers", SERVER); + assert.match(next, /\/\/ keep this theme comment/); + assert.match(next, /\/\/ keep this server/); + assert.match( + next, + /"other": \{ "command": "other" \}, \/\/ keep this server/ + ); + + const parsed = parseLooseJsonc(next); + assert.deepEqual(parsed.context_servers.other, { command: "other" }); + assert.deepEqual(parsed.context_servers["zen-mcp"], SERVER); + }); + + it("adds a missing JSONC key and replaces an inline entry", () => { + const added = mergeJsonServer( + '{\n // servers live here\n "theme": "dark"\n}\n', + "mcpServers", + SERVER + ); + assert.match(added, /\/\/ servers live here/); + assert.deepEqual(parseLooseJsonc(added).mcpServers["zen-mcp"], SERVER); + + const replaced = mergeJsonServer( + '{\n "servers": {\n // server list\n "zen-mcp": { "command": "old" }\n }\n}\n', + "servers", + { type: "stdio", ...SERVER } + ); + assert.match(replaced, /\/\/ server list/); + assert.deepEqual(parseLooseJsonc(replaced).servers["zen-mcp"], { + type: "stdio", + ...SERVER, + }); + + const inline = mergeJsonServer( + '{"context_servers": {}}', + "context_servers", + SERVER + ); + assert.deepEqual(JSON.parse(inline).context_servers["zen-mcp"], SERVER); + }); + + it("appends and replaces a TOML server table only", () => { + const original = [ + "# my codex config", + "", + "[mcp_servers.other]", + 'command = "other"', + "", + "[features]", + "web_search = true", + "", + ].join("\n"); + + const appended = mergeTomlServer( + original, + "mcp_servers.zen-mcp", + SERVER + ); + assert.match(appended, /# my codex config/); + assert.match(appended, /\[mcp_servers\.other\]\ncommand = "other"/); + assert.match( + appended, + /\[mcp_servers\.zen-mcp\]\ncommand = "zen-mcp"\nargs = \["serve"\]/ + ); + assert.match(appended, /\[features\]\nweb_search = true/); + + const replaced = mergeTomlServer( + appended, + "mcp_servers.zen-mcp", + { command: "node", args: ["dist/cli.js"] } + ); + assert.equal( + (replaced.match(/\[mcp_servers\.zen-mcp\]/g) ?? []).length, + 1 + ); + assert.match(replaced, /command = "node"\nargs = \["dist\/cli\.js"\]/); + assert.match(replaced, /\[features\]\nweb_search = true/); + }); + + it("handles quoted TOML table headers", () => { + const replaced = mergeTomlServer( + '[mcp_servers."zen-mcp"]\ncommand = "old"\nargs = []\n\n[features]\nx = true\n', + "mcp_servers.zen-mcp", + SERVER + ); + assert.match(replaced, /command = "zen-mcp"\nargs = \["serve"\]/); + assert.match(replaced, /\[features\]\nx = true/); + }); + + it("lists the supported client ids", () => { + assert.deepEqual(clientIds(), [ + "claude-code", + "claude-desktop", + "cursor", + "vscode", + "codex", + "gemini-cli", + "windsurf", + "cline", + "zed", + ]); + }); + + it("resolves platform-specific config paths", () => { + const home = join(tmpdir(), "zen-mcp-home"); + const win = Object.fromEntries( + catalog({ + home, + platform: "win32", + env: { APPDATA: join(home, "AppData", "Roaming") }, + }).map((entry) => [entry.id, entry]) + ); + assert.equal( + win["claude-desktop"].configPath, + join(home, "AppData", "Roaming", "Claude", "claude_desktop_config.json") + ); + assert.equal( + win["vscode"].configPath, + join(home, "AppData", "Roaming", "Code", "User", "mcp.json") + ); + assert.equal( + win["zed"].configPath, + join(home, "AppData", "Roaming", "Zed", "settings.json") + ); + + const linux = Object.fromEntries( + catalog({ + home, + platform: "linux", + env: { XDG_CONFIG_HOME: join(home, "xdg") }, + }).map((entry) => [entry.id, entry]) + ); + assert.equal( + linux["vscode"].configPath, + join(home, "xdg", "Code", "User", "mcp.json") + ); + assert.equal( + linux["zed"].configPath, + join(home, "xdg", "zed", "settings.json") + ); + + const mac = Object.fromEntries( + catalog({ home, platform: "darwin", env: {} }).map((entry) => [ + entry.id, + entry, + ]) + ); + assert.equal( + mac["claude-desktop"].configPath, + join( + home, + "Library", + "Application Support", + "Claude", + "claude_desktop_config.json" + ) + ); + }); + + it("uses CODEX_HOME when it is set", () => { + const codex = catalog({ + home: join(tmpdir(), "zen-mcp-home"), + platform: "linux", + env: { CODEX_HOME: join(tmpdir(), "custom-codex") }, + }).find((entry) => entry.id === "codex"); + assert.equal( + codex?.configPath, + join(tmpdir(), "custom-codex", "config.toml") + ); + }); + + describe("applyClient", () => { + const temp = mkdtempSync(join(tmpdir(), "zen-mcp-onboard-")); + 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("updates Cursor while keeping other servers", () => { + const path = join(temp, ".cursor", "mcp.json"); + mkdirSync(join(temp, ".cursor"), { recursive: true }); + writeFileSync( + path, + JSON.stringify({ mcpServers: { other: { command: "other" } } }), + "utf8" + ); + + const result = applyClient("cursor", context); + assert.equal(result.status, "ok"); + assert.equal(result.path, path); + + const parsed = JSON.parse(readFileSync(path, "utf8")); + assert.deepEqual(parsed.mcpServers.other, { command: "other" }); + assert.deepEqual(parsed.mcpServers["zen-mcp"], SERVER); + }); + + it("writes the VS Code stdio server shape", () => { + const result = applyClient("vscode", context); + assert.equal(result.status, "ok"); + + const parsed = JSON.parse(readFileSync(result.path, "utf8")); + assert.deepEqual(parsed.servers["zen-mcp"], { + type: "stdio", + ...SERVER, + }); + }); + + it("writes the Zed context server shape", () => { + const result = applyClient("zed", context); + assert.equal(result.status, "ok"); + + const parsed = JSON.parse(readFileSync(result.path, "utf8")); + assert.deepEqual(parsed.context_servers["zen-mcp"], SERVER); + }); + + it("writes a Codex TOML table", () => { + mkdirSync(join(temp, ".codex"), { recursive: true }); + const path = join(temp, ".codex", "config.toml"); + writeFileSync(path, '[features]\nweb_search = true\n', "utf8"); + + const result = applyClient("codex", context); + assert.equal(result.status, "ok"); + + const text = readFileSync(path, "utf8"); + assert.match( + text, + /\[mcp_servers\.zen-mcp\]\ncommand = "zen-mcp"\nargs = \["serve"\]/ + ); + assert.match(text, /\[features\]\nweb_search = true/); + }); + + it("reports unknown clients and leaves a broken file alone", () => { + assert.equal(applyClient("nope", context).status, "failed"); + + const path = join(temp, ".gemini", "settings.json"); + mkdirSync(join(temp, ".gemini"), { recursive: true }); + writeFileSync(path, "{ nope", "utf8"); + const result = applyClient("gemini-cli", context); + assert.equal(result.status, "failed"); + assert.equal(readFileSync(path, "utf8"), "{ nope"); + }); + }); + + it("prints a paste-ready runbook for other clients", () => { + const prompt = agentSetupPrompt("node /opt/zen/dist/cli.js", { + home: "C:\\Users\\test", + platform: "win32", + env: { APPDATA: "C:\\Users\\test\\AppData\\Roaming" }, + }); + assert.match(prompt, /Name: zen-mcp/); + assert.match(prompt, /Command: node \/opt\/zen\/dist\/cli\.js/); + assert.match(prompt, /Arguments: \["serve"\]/); + assert.match(prompt, /Do not ask me to run any of these commands/); + assert.match(prompt, /%USERPROFILE%\\\.claude\.json/); + assert.match(prompt, /%APPDATA%\\Claude\\claude_desktop_config\.json/); + assert.match(prompt, /mcp_servers\.zen-mcp/); + assert.match(prompt, /Preserve every existing server/); + assert.match(prompt, /exactly one `zen-mcp`/); + assert.match(prompt, /Allow this session/); + assert.ok(!prompt.includes("C:\\Users\\test")); + assert.doesNotMatch(prompt, /—/); + }); + + it("uses home-relative placeholders on POSIX", () => { + const prompt = agentSetupPrompt("zen-mcp", { + home: "/home/test", + platform: "linux", + env: {}, + }); + assert.match(prompt, /~\/\.claude\.json/); + assert.match(prompt, /~\/\.config\/Claude\/claude_desktop_config\.json/); + assert.ok(!prompt.includes("/home/test")); + + const xdg = agentSetupPrompt("zen-mcp", { + home: "/home/test", + platform: "linux", + env: { XDG_CONFIG_HOME: "/home/test/xdg" }, + }); + assert.match( + xdg, + /\$XDG_CONFIG_HOME\/Claude\/claude_desktop_config\.json/ + ); + assert.ok(!xdg.includes("/home/test")); + }); +}); + +describe("onboard picker", () => { + const client = ( + id: string, + overrides: { detected?: boolean; popular?: boolean } = {} + ) => ({ + id, + label: id, + detail: "", + popular: overrides.popular ?? false, + detected: overrides.detected ?? false, + configPath: "", + format: "json" as const, + }); + + it("preselects detected clients when any are found", () => { + const options = buildOptions([ + client("a", { detected: true, popular: true }), + client("b", { popular: true }), + client("c", { detected: true }), + ]); + assert.deepEqual( + options.filter((option) => option.selected).map((option) => option.id), + ["a", "c"] + ); + assert.equal(options.at(-1)?.id, "other"); + assert.equal(options.at(-1)?.selected, false); + }); + + it("checks nothing when nothing is detected", () => { + const options = buildOptions([ + client("a", { popular: true }), + client("b"), + ]); + assert.deepEqual( + options.filter((option) => option.selected).map((option) => option.id), + [] + ); + }); + + it("wraps the cursor and toggles every client but not Other", () => { + const options = buildOptions([client("a"), client("b")]); + assert.equal(moveCursor(options, 0, -1), options.length - 1); + assert.equal(moveCursor(options, options.length - 1, 1), 0); + + const all = toggleAll(options, true); + assert.ok(all.filter((option) => !option.other).every((option) => option.selected)); + assert.equal(all.at(-1)?.selected, false); + }); + + it("reports clients and Other separately", () => { + const options = buildOptions([client("a")]).map((option) => + option.id === "a" || option.other ? { ...option, selected: true } : option + ); + assert.deepEqual(pickerResult(options), { selected: ["a"], other: true }); + }); + + it("renders, toggles and confirms from keypress events", async () => { + const input = new FakeInput(); + const output = new FakeOutput(); + const options = buildOptions([ + client("first", { detected: true }), + client("second"), + ]); + + const pending = pickClients(options, { + input: input as unknown as NodeJS.ReadStream, + output: output as unknown as NodeJS.WriteStream, + }); + + input.emit("keypress", undefined, key("down")); + input.emit("keypress", " ", key("space")); + input.emit("keypress", undefined, key("return")); + + const result = await pending; + assert.deepEqual(result, { selected: ["first", "second"], other: false }); + const plain = output.text.replace(/\x1b\[[0-9;]*m/g, ""); + assert.match(plain, /ZEN MCP/); + assert.match(plain, /\[●\] first/); + assert.match(plain, /Selection confirmed/); + assert.equal(input.raw, false); + }); +}); + +class FakeInput extends EventEmitter { + isTTY = true; + raw = true; + + setRawMode(value: boolean): this { + this.raw = value; + return this; + } + + resume(): this { + return this; + } + + pause(): this { + return this; + } +} + +class FakeOutput { + isTTY = true; + text = ""; + + write(chunk: string): boolean { + this.text += chunk; + return true; + } +} + +function key(name: string) { + return { name, ctrl: false, meta: false, shift: false }; +} + +function parseLooseJsonc(text: string): Record { + const stripped = text + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/\/\/[^\n]*/g, "") + .replace(/,\s*([}\]])/g, "$1"); + return JSON.parse(stripped); +} From 7d50927b28d0139cebb08e74d650030ec6d165f5 Mon Sep 17 00:00:00 2001 From: Spaxe <182298766+spaxe-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:32:30 +0530 Subject: [PATCH 6/9] chore: release 0.3.3 Bump the package, lockfile, README tarball example, and advertised server version to 0.3.3. Complete the changelog with the onboarding picker and every fix since 0.3.2: launch ownership and error reporting, POSIX process names, tab focus, evidence repaint, essentials, split cleanup, evidence matching, batch audit, Stop delivery, and per-tab evidence serialization. --- CHANGELOG.md | 38 +++++++++++++++++++++++++++++++++++--- README.md | 2 +- package-lock.json | 4 ++-- package.json | 2 +- src/shared/brand.ts | 2 +- 5 files changed, 40 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ebee53d..237a75d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,14 +4,45 @@ 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). -## [Unreleased] +## [0.3.3] - 2026-11-02 ### Added - `zen-mcp onboard` lists common MCP clients, preselects the ones found on this machine, and merges a `zen-mcp` stdio server into each selected - client's configuration. An **Other MCP client** option prints a paste-ready - prompt for clients the picker does not know. + client's configuration. Existing servers, JSONC comments, trailing commas, + and TOML tables are left alone, and rerunning updates the entry instead of + duplicating it. An **Other MCP client** option prints a paste-ready prompt + for clients the picker does not know. + +### Fixed + +- Launch ownership is read through the chrome sandbox globals with a component + service fallback, so Zen 1.24b can start and an unavailable chrome scope + produces a clear error instead of bare `moz-nullprincipal` frames. (#15) +- POSIX process detection covers the real Zen process names and reports + platform status correctly. (#15) +- Foreground tab selection activates the requested tab and reports the + observed focus state instead of a false success. (#16) +- Show source repaints the evidence overlay and scrolls the quoted passage + back into view after the first highlight expires. (#17) +- Adding and removing an essential restores the tab's original space and + pinned state. (#18) +- Closing a split view verifies the split is gone and closes only clearly + synthetic leftovers. (#19) +- Evidence scoring checks surrounding context before the occurrence cap, so a + repeated word can still be disambiguated. (#20) +- Quotes that are definitely absent return `QUOTE_NOT_FOUND` instead of + `LOW_MATCH_CONFIDENCE`. (#21) +- Batch evidence records the real citation outcomes in the audit log instead + of reporting a partial failure as clean. (#22) +- A Stop press from the progress card produces a stop event, changes the + button to "Stopping...", and is re-sent after a bridge reconnect. (#23) +- Concurrent evidence work on one tab is serialized, so verification and + clearing cannot leave an overlay host behind. +- Consent decline guidance now says to restart the server, and batch evidence + uses the documented 20-second highlight default. +- Sandbox script errors report the error name and message before the stack. ## [0.3.2] - 2026-11-01 @@ -86,6 +117,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.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 [0.3.0]: https://github.com/spaxe-dev/zen-mcp/releases/tag/v0.3.0 diff --git a/README.md b/README.md index ac945de..203994b 100644 --- a/README.md +++ b/README.md @@ -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.2.tgz +npm install -g ./zen-mcp-0.3.3.tgz zen-mcp setup ``` diff --git a/package-lock.json b/package-lock.json index a904f03..6c368b2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@spaxe-dev/zen-mcp", - "version": "0.3.2", + "version": "0.3.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@spaxe-dev/zen-mcp", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", diff --git a/package.json b/package.json index f06a0a5..ec39236 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@spaxe-dev/zen-mcp", - "version": "0.3.2", + "version": "0.3.3", "description": "An agent harness for Zen Browser. Native spaces, background research tabs, and in-browser questions.", "license": "MIT", "repository": { diff --git a/src/shared/brand.ts b/src/shared/brand.ts index 01e8c2e..9ddc19d 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.2"; +export const SERVER_VERSION = "0.3.3"; export const BRIDGE_PROTOCOL_VERSION = 2; export const BRIDGE_HOST_ID = "zen-mcp-host"; export const BRIDGE_SOURCE_NAME = "zen-mcp-bridge.js"; From 3aad2d4492d433c178da33269934a19a355b24e2 Mon Sep 17 00:00:00 2001 From: Spaxe <182298766+spaxe-dev@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:17:19 +0530 Subject: [PATCH 7/9] fix: validate glance previews before loading Resolve the tab's current URL and require http(s) plus the domain allowlist before calling Zen's Glance manager. Pass a content principal for the URL instead of the system principal, and keep the host pre-check for explicit URLs. Adds fake-manager unit coverage and a live regression for allowed and privileged tabs. --- src/bridge/host.ts | 15 +++- src/bridge/ops.ts | 50 +++++++++-- src/shared/protocol.ts | 2 + test/integration/zen.e2e.test.ts | 41 +++++++++ test/unit/glance-policy.test.ts | 141 +++++++++++++++++++++++++++++++ 5 files changed, 240 insertions(+), 9 deletions(-) create mode 100644 test/unit/glance-policy.test.ts diff --git a/src/bridge/host.ts b/src/bridge/host.ts index 8a04503..43591fd 100644 --- a/src/bridge/host.ts +++ b/src/bridge/host.ts @@ -1143,10 +1143,17 @@ export class BridgeHub { params: BridgeMethodMap["glance.open"]["params"], windowId?: string ) { - const result = await this.request("glance.open", params, { - windowId, - timeoutMs: 30_000, - }); + if (params?.url) { + this.#assertUrlAllowed(String(params.url), "Refusing to preview"); + } + const result = await this.request( + "glance.open", + { ...params, allowedDomains: this.#allowedDomains }, + { + windowId, + timeoutMs: 30_000, + } + ); if (result.url) { this.#assertUrlAllowed(result.url, "Refusing to preview"); } diff --git a/src/bridge/ops.ts b/src/bridge/ops.ts index 6b00026..0763c02 100644 --- a/src/bridge/ops.ts +++ b/src/bridge/ops.ts @@ -77,6 +77,7 @@ import { } from "../shared/evidence-script.js"; import { findEvidenceQuote } from "../shared/evidence.js"; import { findLiteralMatches } from "../shared/search.js"; +import { isUrlAllowed, normalizeWebUrl } from "../shared/url-policy.js"; import { activateTab, type TabActivationOutcome } from "./tab-activation.js"; import { captureEssentialsState, @@ -1944,11 +1945,11 @@ export function createOps(win: ChromeWindow, windowId: string) { const sourceTab = params?.tabId ? resolveTabs([String(params.tabId)])[0] : null; - let url: string; + let rawUrl: string; let userContextId: number | undefined; if (sourceTab) { - url = tabUrl(sourceTab); - if (!url) { + rawUrl = tabUrl(sourceTab); + if (!rawUrl) { throw new OpsError( "invalid_url", `The tab "${tabTitle(sourceTab)}" has no URL to preview.` @@ -1957,7 +1958,7 @@ export function createOps(win: ChromeWindow, windowId: string) { const containerId = containerIdOf(sourceTab); userContextId = containerId > 0 ? containerId : undefined; } else { - url = normalizeUrl(String(params?.url ?? "")); + rawUrl = normalizeUrl(String(params?.url ?? "")); if ( params?.container !== undefined && params?.container !== null && @@ -1969,6 +1970,29 @@ export function createOps(win: ChromeWindow, windowId: string) { } } + // Glance hands the URL to a privileged loader, so reject everything that + // is not plain web content before the preview starts. + const preview = normalizeWebUrl(rawUrl); + if (!preview) { + throw new OpsError( + "invalid_url", + `Refusing to preview "${rawUrl}". Glance only opens http(s) URLs.` + ); + } + const url = preview.href; + const allowedDomains = Array.isArray(params?.allowedDomains) + ? params.allowedDomains.filter( + (entry): entry is string => typeof entry === "string" + ) + : []; + if (!isUrlAllowed(url, allowedDomains)) { + throw new OpsError( + "domain_not_allowed", + `Refusing to preview ${preview.hostname}, which is outside the ` + + "configured domain allowlist." + ); + } + const manager = win.gZenGlanceManager; if (!manager || typeof manager.openGlance !== "function") { return { @@ -1980,6 +2004,22 @@ export function createOps(win: ChromeWindow, windowId: string) { } satisfies GlanceResult; } + let triggeringPrincipal: unknown; + try { + triggeringPrincipal = + Services.scriptSecurityManager.createContentPrincipal( + Services.io.newURI(url), + userContextId ? { userContextId } : {} + ); + } catch (error) { + throw new OpsError( + "glance_failed", + `Could not prepare the preview: ${String( + (error as Error)?.message ?? error + )}` + ); + } + const width = clamp(Number(params?.width ?? 960), 240, 4096); const height = clamp(Number(params?.height ?? 720), 240, 4096); let result: unknown = null; @@ -1990,7 +2030,7 @@ export function createOps(win: ChromeWindow, windowId: string) { clientY: 120, width, height, - triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), + triggeringPrincipal, ...(userContextId ? { userContextId } : {}), }); } catch (error) { diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index bfb9ff9..c73572f 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -867,6 +867,8 @@ export interface GlanceParams { container?: string | number; width?: number; height?: number; + /** Host allowlist enforced by the bridge before the preview loads. */ + allowedDomains?: string[]; } export interface GlanceResult { diff --git a/test/integration/zen.e2e.test.ts b/test/integration/zen.e2e.test.ts index ceb16ae..1c5735b 100644 --- a/test/integration/zen.e2e.test.ts +++ b/test/integration/zen.e2e.test.ts @@ -703,6 +703,47 @@ describe( } }); + it("previews an allowed URL and refuses a privileged tab", async () => { + const opened = await runtime.hub.openTabs({ + urls: [`${page.url}?glance=1`], + space: spaceId, + background: true, + }); + const glanceId = opened.tabs[0]?.id ?? ""; + assert.ok(glanceId); + let privilegedId = ""; + try { + const preview = await runtime.hub.openGlance({ tabId: glanceId }); + assert.equal(preview.opened, true, "Zen opens an http(s) glance"); + assert.equal(preview.url, `${page.url}?glance=1`); + + const privileged = await runtime.hub.openTabs({ + urls: ["about:robots"], + space: spaceId, + background: true, + }); + privilegedId = privileged.tabs[0]?.id ?? ""; + assert.ok(privilegedId, "opened an about: tab"); + await assert.rejects( + () => runtime.hub.openGlance({ tabId: privilegedId }), + (error: { code?: string }) => error.code === "invalid_url" + ); + } finally { + await runtime.marionette + .executeChrome(` + const win = Services.wm.getMostRecentWindow("navigator:browser"); + if (win.gZenGlanceManager?.closeGlance) { + win.gZenGlanceManager.closeGlance(); + } + `) + .catch(() => undefined); + const ids = [glanceId, privilegedId].filter(Boolean); + if (ids.length) { + await runtime.hub.closeTabs({ tabIds: ids }).catch(() => undefined); + } + } + }); + it("deletes a space and the tabs it holds", async () => { const deleted = await runtime.hub.deleteSpace({ space: spaceId }); assert.equal(deleted.deleted, true); diff --git a/test/unit/glance-policy.test.ts b/test/unit/glance-policy.test.ts new file mode 100644 index 0000000..1f7c8f9 --- /dev/null +++ b/test/unit/glance-policy.test.ts @@ -0,0 +1,141 @@ +import assert from "node:assert/strict"; +import { after, before, describe, it } from "node:test"; +import { createOps } from "../../src/bridge/ops.js"; + +const originalServices = (globalThis as { Services?: unknown }).Services; + +before(() => { + (globalThis as { Services?: unknown }).Services = { + io: { newURI: (url: string) => ({ spec: url }) }, + scriptSecurityManager: { + createContentPrincipal: (uri: unknown, attrs: unknown) => ({ + kind: "content", + uri, + attrs, + }), + getSystemPrincipal: () => ({ kind: "system" }), + }, + }; +}); + +after(() => { + (globalThis as { Services?: unknown }).Services = originalServices; +}); + +interface GlanceCall { + url: string; + triggeringPrincipal: { kind: string }; + userContextId?: number; +} + +function fakeWindow( + spec: string, + calls: GlanceCall[], + openGlance: (params: GlanceCall) => Promise = async () => true +) { + const tab = { + label: "Preview", + linkedBrowser: { currentURI: { spec } }, + userContextId: 0, + isConnected: true, + closing: false, + selected: true, + pinned: false, + splitView: false, + group: null, + hasAttribute: () => false, + getAttribute: () => null, + }; + return { + document: { querySelectorAll: () => [], hasFocus: () => true }, + gBrowser: { + tabs: [tab], + selectedTab: tab, + removeTab: () => undefined, + }, + gZenWorkspaces: undefined, + gZenGlanceManager: { + openGlance: (params: GlanceCall) => { + calls.push(params); + return openGlance(params); + }, + }, + tab, + }; +} + +async function tabIdFor(ops: ReturnType): Promise { + const listed = (await ops.dispatch("tabs.list", {})) as { + tabs: Array<{ id: string }>; + }; + const id = listed.tabs[0]?.id; + assert.ok(id, "expected the fake tab to be listed"); + return id; +} + +describe("Glance URL policy", () => { + it("refuses an about: tab before calling Glance", async () => { + const calls: GlanceCall[] = []; + const ops = createOps(fakeWindow("about:config", calls) as never, "win"); + const tabId = await tabIdFor(ops); + + await assert.rejects( + async () => ops.dispatch("glance.open", { tabId }), + (error: { code?: string }) => error.code === "invalid_url" + ); + assert.equal(calls.length, 0); + }); + + it("refuses a file: URL before calling Glance", async () => { + const calls: GlanceCall[] = []; + const ops = createOps(fakeWindow("https://allowed.example/", calls) as never, "win"); + + await assert.rejects( + async () => + ops.dispatch("glance.open", { + url: "file:///C:/secret.txt", + allowedDomains: [], + }), + (error: { code?: string }) => error.code === "invalid_url" + ); + assert.equal(calls.length, 0); + }); + + it("refuses a tab outside the allowlist before calling Glance", async () => { + const calls: GlanceCall[] = []; + const ops = createOps( + fakeWindow("https://blocked.example/article", calls) as never, + "win" + ); + const tabId = await tabIdFor(ops); + + await assert.rejects( + async () => + ops.dispatch("glance.open", { + tabId, + allowedDomains: ["allowed.example"], + }), + (error: { code?: string }) => error.code === "domain_not_allowed" + ); + assert.equal(calls.length, 0); + }); + + it("opens an allowed tab with a content principal", async () => { + const calls: GlanceCall[] = []; + const ops = createOps( + fakeWindow("https://allowed.example/article", calls) as never, + "win" + ); + const tabId = await tabIdFor(ops); + + const result = (await ops.dispatch("glance.open", { + tabId, + allowedDomains: ["allowed.example"], + })) as { opened: boolean; url: string }; + + assert.equal(result.opened, true); + assert.equal(result.url, "https://allowed.example/article"); + assert.equal(calls.length, 1); + assert.equal(calls[0]?.triggeringPrincipal.kind, "content"); + }); +}); From 22c8d6fe87386d2c3f88a573e840fff74512afd9 Mon Sep 17 00:00:00 2001 From: Spaxe <182298766+spaxe-dev@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:17:23 +0530 Subject: [PATCH 8/9] fix: close config, read-only, and input-cap audit gaps Reject malformed safety settings and unrecognized safety environment values instead of falling back to a weaker policy. Block the three UI card tools in read-only mode, and cap tab-id arrays at 100 per call. Updates the docs and changelog for 0.3.3. --- CHANGELOG.md | 9 ++++ README.md | 2 +- docs/configuration.md | 12 ++++-- docs/security.md | 4 +- docs/tools.md | 4 +- src/config.ts | 75 ++++++++++++++++++++++++++-------- src/mcp/guard.ts | 9 ++-- src/mcp/server.ts | 22 ++++++++-- test/unit/config.test.ts | 33 +++++++++++---- test/unit/guard.test.ts | 20 +++++++-- test/unit/tools-policy.test.ts | 27 +++++++++--- 11 files changed, 167 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 237a75d..afc4645 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,15 @@ uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixed +- Glance validates the selected tab's current URL as `http(s)`, enforces the + domain allowlist before the preview loads, and uses a content principal for + the URL instead of the system principal. +- Malformed safety settings in the config file or safety environment variables + stop startup with a clear error instead of falling back to a weaker policy. +- Read-only mode also blocks `zen_progress`, `zen_ask`, and `zen_notify`, so an + agent cannot draw or change cards while the server is read-only. +- `zen_tabs_close`, `zen_folder_create`, and `zen_folder_add_tabs` cap their + tab id lists at 100 per call. - Launch ownership is read through the chrome sandbox globals with a component service fallback, so Zen 1.24b can start and an unavailable chrome scope produces a clear error instead of bare `moz-nullprincipal` frames. (#15) diff --git a/README.md b/README.md index 203994b..40298b2 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,7 @@ Do not point `profilePath` at your normal profile unless that is the tradeoff yo | Browser ownership | Always on | Launches its own Zen, proves identity with a nonce and `moz:processID`, then closes the Marionette listener to every other client | A local process can race for the port before lockdown; the race is detected, not eliminated | | Consent | On | Shows one approval card per server process before the first read or change; decline closes the owned browser | After a decline, restart the server to ask again; a timeout leaves the card open | | Pause | Available in the banner | Blocks browser tools with `paused`, hides the progress card, defers questions, and skips watch polls until Resume | A command already running in Zen may finish; its result is discarded. Pause is not persisted, and existing evidence overlays are not removed | -| Read-only mode | Off | Blocks all 27 tools in the mutating set, including `zen_launch` and a read-only server's auto-launch | Reads, lists, questions, events, and the audit log still work; session and template listings still show stored URLs | +| Read-only mode | Off | Blocks all 30 tools in the mutating set, including `zen_launch`, a read-only server's auto-launch, and on-screen progress, question, and notification cards | Reads, lists, events, collected answers, and the audit log still work; session and template listings still show stored URLs | | Domain allowlist | Empty | Matches an exact host or a subdomain on a label boundary before opening, previewing, verifying, watching, restoring a session, or applying a template | It is rechecked immediately after opening, but slow, script, or meta redirects can land elsewhere afterwards; reads recheck the tab URL | | Private windows | Excluded | The bridge is not injected into private windows and an existing bridge is destroyed | This path is not covered by the automated live suite; treat it as a best-effort boundary | | Audit log | On | Appends one JSON line per tool call, including blocked calls, with URLs reduced to scheme, host, and path | Argument summaries are bounded; sensitive values are digested, but a preview of the summarized arguments can remain | diff --git a/docs/configuration.md b/docs/configuration.md index 35e4cc5..b5c2277 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -95,6 +95,8 @@ Session and template files are written atomically with owner-only permissions. T Numeric file values outside their range are clamped when loaded. `config set` rejects them instead, so use it when you want a validation error. +Policy keys are validated by type. `readOnly`, `requireConsent`, `useDefaultProfile`, and `auditLog` must be JSON booleans, and `allowedDomains` must be an array of strings. A malformed value stops the server with a config error instead of falling back to a weaker default. + ### Marionette port Current Zen builds listen on 2828. The launcher passes `-marionette` without a port, so Zen does not follow `marionettePort`; the setting only changes the port the server tries to reach. Leave it at `2828` unless you know your Zen build supports another port. If another process owns 2828, quit that process; changing the setting usually makes the launch fail. @@ -109,18 +111,20 @@ Environment variables override the file for that process. They are never written | `ZEN_MCP_DATA_DIR` | Sessions, templates, audit log, and the default agent profile directory | | `ZEN_MCP_ZEN_PATH` | Zen executable | | `ZEN_MCP_PROFILE` | Custom agent profile directory | -| `ZEN_MCP_USE_DEFAULT_PROFILE` | `1` uses Zen's normal profile instead of the dedicated one | -| `ZEN_MCP_REQUIRE_CONSENT` | `0` skips the one-time approval card | +| `ZEN_MCP_USE_DEFAULT_PROFILE` | `1`, `true`, `yes`, or `on` uses Zen's normal profile instead of the dedicated one | +| `ZEN_MCP_REQUIRE_CONSENT` | `0`, `false`, `no`, or `off` skips the one-time approval card | | `ZEN_MCP_CONSENT_TIMEOUT_SECONDS` | How long a tool waits for approval | | `ZEN_MCP_LAUNCH_ARGS` | Extra Zen arguments, split on whitespace | | `ZEN_MCP_MARIONETTE_PORT` | Port the server connects to (see [Marionette port](#marionette-port)) | -| `ZEN_MCP_READ_ONLY` | `1`, `true`, or `yes` enables read-only mode | +| `ZEN_MCP_READ_ONLY` | `1`, `true`, `yes`, or `on` enables read-only mode | | `ZEN_MCP_ALLOWED_DOMAINS` | Comma-separated domain allowlist | -| `ZEN_MCP_AUDIT_LOG` | `1`, `true`, or `yes` enables the audit log | +| `ZEN_MCP_AUDIT_LOG` | `1`, `true`, `yes`, or `on` enables the audit log | | `ZEN_MCP_WATCH_MIN_INTERVAL_SECONDS` | Lower bound for watch polling | | `ZEN_MCP_LOG` | `debug`, `info`, `warn`, or `error` | | `ZEN_MCP_BRIDGE_SCRIPT` | Override the bundled `bridge.js` path; `doctor` warns when set | +Boolean variables accept `1`/`0`, `true`/`false`, `yes`/`no`, or `on`/`off`, ignoring case and surrounding spaces. Any other value stops the server with an error instead of falling back to the file or default. + Logs always go to **stderr**; stdout belongs to the MCP transport. ## `config set` diff --git a/docs/security.md b/docs/security.md index 6b4f448..fcde0f2 100644 --- a/docs/security.md +++ b/docs/security.md @@ -57,7 +57,7 @@ The banner in Zen has a Pause button. Pausing rejects pending bridge requests, h A command that is already executing in Zen when Pause is pressed may still finish in the browser. The server drops its result and rejects later requests. Pause is held in memory, is not persisted, and does not remove evidence overlays that are already visible. -`readOnly` blocks the complete mutating tool set: `zen_launch` and 26 other tools covering spaces, tabs, folders, pins, essentials, split view, Glance, clipboard writes, watches, sessions, templates, tab grouping, and evidence operations. Reads, lists, status, questions, events, and the audit log keep working. A read-only server also refuses to auto-launch Zen, so it never starts a process or creates a profile. +`readOnly` blocks the complete mutating tool set: `zen_launch` and 29 other tools covering spaces, tabs, folders, pins, essentials, split view, Glance, clipboard writes, watches, sessions, templates, tab grouping, evidence operations, and the on-screen progress, question, and notification cards. Reads, lists, status, events, collected answers, and the audit log keep working. A read-only server also refuses to auto-launch Zen, so it never starts a process or creates a profile. Read-only mode is not a confidentiality boundary. Session and template listings still return stored URLs, and page reads still return page text. Use Pause when the user wants to stop browser access entirely. @@ -65,7 +65,7 @@ Read-only mode is not a confidentiality boundary. Session and template listings One normalizer is shared by the MCP guard, the runtime, and the bridge. Inputs without a scheme are treated as `https`. `zen_tabs_open` accepts `http(s)` and `about:` URLs; Glance previews and both Evidence tools accept only `http(s)`. With an empty allowlist these are all permitted. With a non-empty allowlist, every URL is matched by host, so an `about:` URL is rejected along with any other non-`http(s)` scheme. -The domain allowlist matches a host exactly or as a subdomain on a label boundary, and is checked before tabs open, Glance, evidence, watches, session restores, and template applies. The tab URL is checked again immediately after `zen_tabs_open` returns, and a tab that landed outside the list is closed. A slow script or meta redirect after that check can still move the tab; reads recheck the URL before returning content. An empty list allows every domain; a list whose entries all normalize away denies everything. Sessions and templates are sanitized and capped before use. +The domain allowlist matches a host exactly or as a subdomain on a label boundary, and is checked before tabs open, Glance, evidence, watches, session restores, and template applies. Glance resolves the selected tab's current URL, requires `http(s)`, and checks the allowlist before the preview loads, so a privileged or off-list tab is refused before any load starts. The preview uses a content principal for that URL rather than the system principal. The tab URL is checked again immediately after `zen_tabs_open` returns, and a tab that landed outside the list is closed. A slow script or meta redirect after that check can still move the tab; reads recheck the URL before returning content. An empty list allows every domain; a list whose entries all normalize away denies everything. Sessions and templates are sanitized and capped before use. ### Reads diff --git a/docs/tools.md b/docs/tools.md index d573672..11e0356 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -97,8 +97,8 @@ For read formats and Evidence Mode behavior, see [reading-and-evidence.md](readi The MCP guard applies policy before a tool runs: -- **Read-only mode** blocks the 27 tools that change browser, server, or persisted state: `zen_launch`, space create/switch/delete, tab open/close/select, folder create/add, pin, essentials, Glance, split view/close, clipboard write, watch add/remove, session save/restore/delete, template save/apply/delete, tab grouping, and the three evidence tools. A read-only server also refuses to auto-launch Zen. -- **Read-only mode only blocks the mutating set.** `zen_read_page`, `zen_read_pages`, `zen_find_text`, `zen_search_tabs`, history, bookmarks, status, lists, `zen_ask`, `zen_events`, `zen_answers`, `zen_notify`, `zen_progress`, `zen_config`, and `zen_audit_tail` keep working. Session and template listings can still show stored URLs. +- **Read-only mode** blocks the 30 tools that change browser, server, persisted, or on-screen state: `zen_launch`, space create/switch/delete, tab open/close/select, folder create/add, pin, essentials, Glance, split view/close, clipboard write, watch add/remove, session save/restore/delete, template save/apply/delete, tab grouping, the three evidence tools, and `zen_progress`, `zen_ask`, and `zen_notify`. A read-only server also refuses to auto-launch Zen. +- **Read-only mode only blocks the mutating set.** `zen_read_page`, `zen_read_pages`, `zen_find_text`, `zen_search_tabs`, history, bookmarks, status, lists, `zen_events`, `zen_answers`, `zen_config`, and `zen_audit_tail` keep working. Session and template listings can still show stored URLs. - **The domain allowlist** checks URLs for tools that open, preview, verify, watch, restore, or apply a template. An empty list allows everything. Entries are normalized to a host and match exactly or as a subdomain on a label boundary. URL checks happen before the action and again after `zen_tabs_open` returns; a redirect that happens later, such as a slow script or meta refresh, can still leave the tab on another host. Reads recheck the tab URL before returning content. - **The audit log** records tool calls, including calls blocked by read-only mode or the allowlist, and resource reads under `resource:`. `executed` reports whether the handler returned a result; `ok` reports whether that result succeeded. Evidence batch entries add `citationsVerified`, `citationsFailed`, and `outcome` (`success`, `partial`, or `failed`), so a batch with a failed citation is not logged as full success. diff --git a/src/config.ts b/src/config.ts index 03b7a39..84cc71e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -94,19 +94,21 @@ export function loadConfig(): ZenMcpConfig { const envConsentTimeout = process.env.ZEN_MCP_CONSENT_TIMEOUT_SECONDS; const envLaunchArgs = process.env.ZEN_MCP_LAUNCH_ARGS; - const fileReadOnly = fileBoolean( + const fileReadOnly = fileSafetyBoolean( fileConfig.readOnly, + "readOnly", DEFAULT_CONFIG.readOnly ); - const fileAuditLog = fileBoolean( + const fileAuditLog = fileSafetyBoolean( fileConfig.auditLog, + "auditLog", DEFAULT_CONFIG.auditLog ); - const fileDomains = Array.isArray(fileConfig.allowedDomains) - ? fileConfig.allowedDomains.filter( - (entry): entry is string => typeof entry === "string" - ) - : DEFAULT_CONFIG.allowedDomains; + const fileDomains = fileStringArray( + fileConfig.allowedDomains, + "allowedDomains", + DEFAULT_CONFIG.allowedDomains + ); const domains = envDomains !== undefined ? envDomains @@ -130,15 +132,20 @@ export function loadConfig(): ZenMcpConfig { : undefined), useDefaultProfile: envUseDefault !== undefined - ? parseBoolean(envUseDefault, DEFAULT_CONFIG.useDefaultProfile) - : fileBoolean( + ? envBoolean("ZEN_MCP_USE_DEFAULT_PROFILE", envUseDefault) + : fileSafetyBoolean( fileConfig.useDefaultProfile, + "useDefaultProfile", DEFAULT_CONFIG.useDefaultProfile ), requireConsent: envConsent !== undefined - ? parseBoolean(envConsent, DEFAULT_CONFIG.requireConsent) - : fileBoolean(fileConfig.requireConsent, DEFAULT_CONFIG.requireConsent), + ? envBoolean("ZEN_MCP_REQUIRE_CONSENT", envConsent) + : fileSafetyBoolean( + fileConfig.requireConsent, + "requireConsent", + DEFAULT_CONFIG.requireConsent + ), consentTimeoutSeconds: envConsentTimeout !== undefined && envConsentTimeout.trim() ? boundedInt( @@ -167,14 +174,14 @@ export function loadConfig(): ZenMcpConfig { ), readOnly: envReadOnly !== undefined - ? parseBoolean(envReadOnly, fileReadOnly) + ? envBoolean("ZEN_MCP_READ_ONLY", envReadOnly) : fileReadOnly, allowedDomains: domains.map((domain) => domain.replace(/^\*?\./, "").toLowerCase() ), auditLog: envAuditLog !== undefined - ? parseBoolean(envAuditLog, fileAuditLog) + ? envBoolean("ZEN_MCP_AUDIT_LOG", envAuditLog) : fileAuditLog, watchMinIntervalSeconds: envWatchMin !== undefined && envWatchMin.trim() @@ -228,10 +235,44 @@ function readConfigFile(): Partial { } } -function parseBoolean(value: string, fallback: boolean): boolean { - if (/^(1|true|yes|on)$/i.test(value.trim())) return true; - if (/^(0|false|no|off)$/i.test(value.trim())) return false; - return fallback; +function envBoolean(name: string, value: string): boolean { + const normalized = value.trim().toLowerCase(); + if (/^(1|true|yes|on)$/.test(normalized)) return true; + if (/^(0|false|no|off)$/.test(normalized)) return false; + throw new Error( + `Invalid ${name} value "${value}": use 1/0, true/false, yes/no, or on/off.` + ); +} + +function fileSafetyBoolean( + value: unknown, + field: string, + fallback: boolean +): boolean { + if (value === undefined) return fallback; + if (typeof value === "boolean") return value; + throw new Error( + `Invalid config at ${configFilePath()}: "${field}" must be true or false. ` + + "Fix or delete the file." + ); +} + +function fileStringArray( + value: unknown, + field: string, + fallback: string[] +): string[] { + if (value === undefined) return fallback; + if ( + !Array.isArray(value) || + value.some((entry) => typeof entry !== "string") + ) { + throw new Error( + `Invalid config at ${configFilePath()}: "${field}" must be an array of ` + + "strings. Fix or delete the file." + ); + } + return value; } function fileBoolean(value: unknown, fallback: boolean): boolean { diff --git a/src/mcp/guard.ts b/src/mcp/guard.ts index 6d7c986..efd1474 100644 --- a/src/mcp/guard.ts +++ b/src/mcp/guard.ts @@ -38,9 +38,9 @@ export class ToolGuardError extends Error { } /** - * Tools that change browser, server or persisted state. Everything else - * (status, lists, reads, history, bookmarks, containers, answers, events, - * audit, ask, notify, progress) stays available in read-only mode. + * Tools that change browser, server, persisted or on-screen state. Everything + * else (status, lists, reads, history, bookmarks, containers, answers, events, + * audit) stays available in read-only mode. */ export const MUTATING_TOOLS: ReadonlySet = new Set([ "zen_launch", @@ -70,6 +70,9 @@ export const MUTATING_TOOLS: ReadonlySet = new Set([ "zen_show_evidence", "zen_show_evidence_batch", "zen_clear_evidence", + "zen_progress", + "zen_ask", + "zen_notify", ]); /** Verification outcome of an evidence batch, when the result carries counts. */ diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 30ac763..566c8be 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -77,8 +77,9 @@ function raceWithAbort(work: Promise, signal: AbortSignal): Promise { }); } -const SERVER_INSTRUCTIONS = `${BRAND} drives the user's Zen Browser from outside the page. Zen spaces are workspaces: tabs can live in a space the user is not looking at, and switching is instant for them. +const MAX_TAB_IDS_PER_CALL = 100; +const SERVER_INSTRUCTIONS = `${BRAND} drives the user's Zen Browser from outside the page. Zen spaces are workspaces: tabs can live in a space the user is not looking at, and switching is instant for them. Background research is the default workflow. Never take over the user's screen: 1. Look first with zen_status, zen_spaces_list, and zen_tabs_list. 2. zen_space_create with a short, descriptive name. It does not switch spaces by default. zen_template_apply("research") is faster when a ready-made layout fits. @@ -571,7 +572,11 @@ export function createZenMcpServer( description: "Close one or more tabs by id. Closing tabs is destructive to the user's session; only close tabs the agent opened, or tabs the user explicitly named.", inputSchema: { - tabIds: z.array(z.string().min(1)).min(1).describe("Tab ids from zen_tabs_list."), + tabIds: z + .array(z.string().min(1)) + .min(1) + .max(MAX_TAB_IDS_PER_CALL) + .describe(`Tab ids from zen_tabs_list. At most ${MAX_TAB_IDS_PER_CALL} per call.`), }, annotations: { readOnlyHint: false, destructiveHint: true }, }, @@ -847,8 +852,11 @@ export function createZenMcpServer( label: z.string().min(1).describe("Folder label."), tabIds: z .array(z.string().min(1)) + .max(MAX_TAB_IDS_PER_CALL) .optional() - .describe("Tabs to move into the folder."), + .describe( + `Tabs to move into the folder. At most ${MAX_TAB_IDS_PER_CALL} per call.` + ), space: z .string() .optional() @@ -878,7 +886,13 @@ export function createZenMcpServer( "Move existing tabs into an existing folder. The tabs must be in the folder's space and not already grouped.", inputSchema: { folderId: z.string().min(1).describe("Folder id from zen_folders_list."), - tabIds: z.array(z.string().min(1)).min(1).describe("Tab ids to move."), + tabIds: z + .array(z.string().min(1)) + .min(1) + .max(MAX_TAB_IDS_PER_CALL) + .describe( + `Tab ids to move. At most ${MAX_TAB_IDS_PER_CALL} per call.` + ), }, annotations: { readOnlyHint: false }, }, diff --git a/test/unit/config.test.ts b/test/unit/config.test.ts index 953ecbc..5b05365 100644 --- a/test/unit/config.test.ts +++ b/test/unit/config.test.ts @@ -104,23 +104,42 @@ describe("config", () => { } }); - it("falls back to the file when an environment boolean is unrecognized", () => { + it("rejects an unrecognized safety environment value", () => { writeFileSync(configPath, JSON.stringify({ readOnly: true }), "utf8"); process.env.ZEN_MCP_READ_ONLY = "enabled"; try { - assert.equal(loadConfig().readOnly, true); + assert.throws( + () => loadConfig(), + /Invalid ZEN_MCP_READ_ONLY value "enabled"/ + ); } finally { delete process.env.ZEN_MCP_READ_ONLY; } }); - it("ignores non-boolean file values and bounds numbers", () => { + it("rejects malformed safety settings in the config file", () => { + const cases: Array<[Record, RegExp]> = [ + [{ readOnly: "false" }, /"readOnly" must be true or false/], + [{ requireConsent: "no" }, /"requireConsent" must be true or false/], + [{ auditLog: 0 }, /"auditLog" must be true or false/], + [{ allowedDomains: "example.com" }, /"allowedDomains" must be an array/], + [ + { allowedDomains: ["example.com", 7] }, + /"allowedDomains" must be an array of strings/, + ], + ]; + for (const [value, pattern] of cases) { + writeFileSync(configPath, JSON.stringify(value), "utf8"); + assert.throws(() => loadConfig(), pattern, JSON.stringify(value)); + } + }); + + it("bounds numbers and keeps valid booleans", () => { writeFileSync( configPath, JSON.stringify({ - readOnly: "false", - requireConsent: "no", - watchdog: "nope", + readOnly: true, + requireConsent: true, watchMinIntervalSeconds: 10_000_000, marionettePort: 999_999, consentTimeoutSeconds: "nope", @@ -128,7 +147,7 @@ describe("config", () => { "utf8" ); const config = loadConfig(); - assert.equal(config.readOnly, false); + assert.equal(config.readOnly, true); assert.equal(config.requireConsent, true); assert.equal(config.watchMinIntervalSeconds, 3600); assert.equal(config.marionettePort, 65535); diff --git a/test/unit/guard.test.ts b/test/unit/guard.test.ts index 6b51736..af39530 100644 --- a/test/unit/guard.test.ts +++ b/test/unit/guard.test.ts @@ -127,6 +127,9 @@ describe("MUTATING_TOOLS", () => { "zen_show_evidence", "zen_show_evidence_batch", "zen_clear_evidence", + "zen_progress", + "zen_ask", + "zen_notify", ]; assert.equal(MUTATING_TOOLS.size, expected.length); for (const tool of expected) { @@ -219,7 +222,7 @@ describe("ToolGuard.check", () => { } }); - it("allows reads, status and questions in read-only mode", () => { + it("allows reads, status and answers in read-only mode", () => { const guard = new ToolGuard(options({ readOnly: true, dataDir: tempDir })); for (const tool of [ "zen_status", @@ -232,14 +235,23 @@ describe("ToolGuard.check", () => { "zen_events", "zen_audit", "zen_watch_list", - "zen_ask", - "zen_notify", - "zen_progress", ]) { assert.doesNotThrow(() => guard.check(tool), tool); } }); + it("blocks on-screen cards in read-only mode", () => { + const guard = new ToolGuard(options({ readOnly: true, dataDir: tempDir })); + for (const tool of ["zen_progress", "zen_ask", "zen_notify"]) { + assert.throws( + () => guard.check(tool), + (error: unknown) => + error instanceof ToolGuardError && error.code === "read_only", + tool + ); + } + }); + it("blocks watch changes in read-only mode", () => { const guard = new ToolGuard(options({ readOnly: true, dataDir: tempDir })); for (const tool of ["zen_watch_add", "zen_watch_remove"]) { diff --git a/test/unit/tools-policy.test.ts b/test/unit/tools-policy.test.ts index c9d94c9..710af0f 100644 --- a/test/unit/tools-policy.test.ts +++ b/test/unit/tools-policy.test.ts @@ -26,14 +26,9 @@ const AUTO_LAUNCH_TOOLS = new Set([ "zen_find_text", "zen_search_tabs", "zen_tabs_audit", - "zen_ask", - "zen_notify", ]); -/** Tools that draw transient UI cards without changing browser state. */ -const UI_ONLY_TOOLS = new Set(["zen_ask", "zen_notify", "zen_progress"]); - -const EXEMPT_TOOLS = new Set([...AUTO_LAUNCH_TOOLS, ...UI_ONLY_TOOLS]); +const EXEMPT_TOOLS = new Set(AUTO_LAUNCH_TOOLS); async function registeredTools() { const config = { @@ -97,4 +92,24 @@ describe("tool policy", () => { ); } }); + + it("caps tab id arrays in the tool schemas", async () => { + const tools = await registeredTools(); + const byName = new Map(tools.map((tool) => [tool.name, tool])); + + for (const name of [ + "zen_tabs_close", + "zen_folder_create", + "zen_folder_add_tabs", + ]) { + const schema = byName.get(name)?.inputSchema as + | { properties?: { tabIds?: { maxItems?: number } } } + | undefined; + assert.equal( + schema?.properties?.tabIds?.maxItems, + 100, + `${name} must cap tabIds at 100` + ); + } + }); }); From 1ee90f61577783019ea5d6c8b8f71da849ed6933 Mon Sep 17 00:00:00 2001 From: Spaxe <182298766+spaxe-dev@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:36:12 +0530 Subject: [PATCH 9/9] fix: verify the loaded glance URL and tighten launch config The host re-checked the URL it requested, so a redirect could leave the allowlist after Glance opened. Read the committed glance URL, close the preview when it is outside the list, and keep watching location changes for a later redirect. Malformed autoLaunch and autoAttachWindows values now stop startup instead of falling back to true. --- CHANGELOG.md | 6 +- docs/configuration.md | 2 +- docs/security.md | 2 +- src/bridge/ops.ts | 139 +++++++++++++++++++++++++++++++- src/config.ts | 13 +-- test/unit/config.test.ts | 5 ++ test/unit/glance-policy.test.ts | 114 +++++++++++++++++++++++++- 7 files changed, 267 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index afc4645..caa6f58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,9 +19,13 @@ uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - Glance validates the selected tab's current URL as `http(s)`, enforces the domain allowlist before the preview loads, and uses a content principal for - the URL instead of the system principal. + the URL instead of the system principal. It also checks the URL the preview + actually committed and closes the preview when a redirect leaves the + allowlist. - Malformed safety settings in the config file or safety environment variables stop startup with a clear error instead of falling back to a weaker policy. + That includes `autoLaunch` and `autoAttachWindows`, which no longer fall back + to `true` when the value is malformed. - Read-only mode also blocks `zen_progress`, `zen_ask`, and `zen_notify`, so an agent cannot draw or change cards while the server is read-only. - `zen_tabs_close`, `zen_folder_create`, and `zen_folder_add_tabs` cap their diff --git a/docs/configuration.md b/docs/configuration.md index b5c2277..f5032de 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -95,7 +95,7 @@ Session and template files are written atomically with owner-only permissions. T Numeric file values outside their range are clamped when loaded. `config set` rejects them instead, so use it when you want a validation error. -Policy keys are validated by type. `readOnly`, `requireConsent`, `useDefaultProfile`, and `auditLog` must be JSON booleans, and `allowedDomains` must be an array of strings. A malformed value stops the server with a config error instead of falling back to a weaker default. +Policy keys are validated by type. `readOnly`, `requireConsent`, `useDefaultProfile`, `auditLog`, `autoLaunch`, and `autoAttachWindows` must be JSON booleans, and `allowedDomains` must be an array of strings. A malformed value stops the server with a config error instead of falling back to a weaker default. ### Marionette port diff --git a/docs/security.md b/docs/security.md index fcde0f2..668cd80 100644 --- a/docs/security.md +++ b/docs/security.md @@ -65,7 +65,7 @@ Read-only mode is not a confidentiality boundary. Session and template listings One normalizer is shared by the MCP guard, the runtime, and the bridge. Inputs without a scheme are treated as `https`. `zen_tabs_open` accepts `http(s)` and `about:` URLs; Glance previews and both Evidence tools accept only `http(s)`. With an empty allowlist these are all permitted. With a non-empty allowlist, every URL is matched by host, so an `about:` URL is rejected along with any other non-`http(s)` scheme. -The domain allowlist matches a host exactly or as a subdomain on a label boundary, and is checked before tabs open, Glance, evidence, watches, session restores, and template applies. Glance resolves the selected tab's current URL, requires `http(s)`, and checks the allowlist before the preview loads, so a privileged or off-list tab is refused before any load starts. The preview uses a content principal for that URL rather than the system principal. The tab URL is checked again immediately after `zen_tabs_open` returns, and a tab that landed outside the list is closed. A slow script or meta redirect after that check can still move the tab; reads recheck the URL before returning content. An empty list allows every domain; a list whose entries all normalize away denies everything. Sessions and templates are sanitized and capped before use. +The domain allowlist matches a host exactly or as a subdomain on a label boundary, and is checked before tabs open, Glance, evidence, watches, session restores, and template applies. Glance resolves the selected tab's current URL, requires `http(s)`, and checks the allowlist before the preview loads, so a privileged or off-list tab is refused before any load starts. The preview uses a content principal for that URL rather than the system principal. After it opens, the bridge reads the URL the preview actually committed; a redirect that lands outside the allowlist closes the preview and fails the call. A later location change on the glance is watched too, and a preview that leaves the allowlist is closed. The tab URL is checked again immediately after `zen_tabs_open` returns, and a tab that landed outside the list is closed. A slow script or meta redirect after that check can still move the tab; reads recheck the URL before returning content. An empty list allows every domain; a list whose entries all normalize away denies everything. Sessions and templates are sanitized and capped before use. ### Reads diff --git a/src/bridge/ops.ts b/src/bridge/ops.ts index 0763c02..3ae61ae 100644 --- a/src/bridge/ops.ts +++ b/src/bridge/ops.ts @@ -141,6 +141,92 @@ function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } +const GLANCE_SETTLE_MS = 10_000; +const GLANCE_POLL_MS = 50; + +/** Zen resolves a normal glance with its Tab; anything else cannot be checked. */ +function isGlanceTab(result: unknown): boolean { + return ( + typeof result === "object" && + result !== null && + "linkedBrowser" in (result as Record) + ); +} + +/** The URL a glance tab has actually committed, once it leaves about:blank. */ +function glanceUrlOf(result: unknown): string | undefined { + const browser = ( + result as { linkedBrowser?: { currentURI?: { spec?: unknown } } } | null + )?.linkedBrowser; + const spec = browser?.currentURI?.spec; + if (typeof spec !== "string" || !spec || spec === "about:blank") { + return undefined; + } + return spec; +} + +async function waitForGlanceUrl( + result: unknown +): Promise { + const deadline = Date.now() + GLANCE_SETTLE_MS; + let observed = glanceUrlOf(result); + while (!observed && Date.now() < deadline) { + await sleep(GLANCE_POLL_MS); + observed = glanceUrlOf(result); + } + return observed; +} + +/** + * Glance can follow a redirect after opening, so keep watching the committed + * URL and close the preview if it leaves the allowlist. + */ +function watchGlanceRedirects( + result: unknown, + manager: { closeGlance?: (options?: Record) => unknown }, + allowedDomains: string[] +): void { + const tab = result as { + linkedBrowser?: { + addEventListener?: (...args: unknown[]) => void; + removeEventListener?: (...args: unknown[]) => void; + }; + addEventListener?: (...args: unknown[]) => void; + removeEventListener?: (...args: unknown[]) => void; + } | null; + const browser = tab?.linkedBrowser; + if (typeof browser?.addEventListener !== "function") return; + + function stop() { + try { + browser?.removeEventListener?.("locationchange", check, true); + tab?.removeEventListener?.("GlanceClose", stop, true); + } catch { + // The tab is already gone. + } + } + + function check() { + const current = glanceUrlOf(result); + if (!current) return; + const target = normalizeWebUrl(current); + if (target && isUrlAllowed(target.href, allowedDomains)) return; + stop(); + try { + manager.closeGlance?.({ noAnimation: true, skipPermitUnload: true }); + } catch { + // Closing is best effort; the host also checks the returned URL. + } + } + + try { + browser.addEventListener("locationchange", check, true); + tab?.addEventListener?.("GlanceClose", stop, true); + } catch { + // Without a listener the final-URL check at open time still applies. + } +} + class OpsError extends Error { readonly code: string; constructor(code: string, message: string) { @@ -2041,11 +2127,56 @@ export function createOps(win: ChromeWindow, windowId: string) { )}` ); } + if (!result) { + return { + opened: false, + url, + mode: "none", + message: "Zen declined to open the glance view.", + } satisfies GlanceResult; + } + + const closePreview = () => { + try { + manager.closeGlance?.({ noAnimation: true, skipPermitUnload: true }); + } catch { + // Closing is best effort; the policy violation is reported below. + } + }; + + // The requested URL is not necessarily the URL that loads: a redirect + // can leave the allowlist. Verify what the preview committed. + const loadedUrl = isGlanceTab(result) + ? await waitForGlanceUrl(result) + : undefined; + if (!loadedUrl) { + closePreview(); + throw new OpsError( + "glance_failed", + "The preview opened but its URL could not be verified, so it was closed." + ); + } + const loaded = normalizeWebUrl(loadedUrl); + if (!loaded) { + closePreview(); + throw new OpsError( + "invalid_url", + `The preview loaded "${loadedUrl}", which is not an http(s) URL.` + ); + } + if (!isUrlAllowed(loaded.href, allowedDomains)) { + closePreview(); + throw new OpsError( + "domain_not_allowed", + `The preview redirected to ${loaded.hostname}, which is outside the ` + + "configured domain allowlist, so it was closed." + ); + } + watchGlanceRedirects(result, manager, allowedDomains); return { - opened: !!result, - url, - mode: result ? "glance" : "none", - message: result ? undefined : "Zen declined to open the glance view.", + opened: true, + url: loaded.href, + mode: "glance", } satisfies GlanceResult; }, diff --git a/src/config.ts b/src/config.ts index 84cc71e..ad3efd4 100644 --- a/src/config.ts +++ b/src/config.ts @@ -209,9 +209,14 @@ export function loadConfig(): ZenMcpConfig { 3_600, DEFAULT_CONFIG.askTimeoutSeconds ), - autoLaunch: fileBoolean(fileConfig.autoLaunch, DEFAULT_CONFIG.autoLaunch), - autoAttachWindows: fileBoolean( + autoLaunch: fileSafetyBoolean( + fileConfig.autoLaunch, + "autoLaunch", + DEFAULT_CONFIG.autoLaunch + ), + autoAttachWindows: fileSafetyBoolean( fileConfig.autoAttachWindows, + "autoAttachWindows", DEFAULT_CONFIG.autoAttachWindows ), }; @@ -275,10 +280,6 @@ function fileStringArray( return value; } -function fileBoolean(value: unknown, fallback: boolean): boolean { - return typeof value === "boolean" ? value : fallback; -} - function boundedInt( value: unknown, min: number, diff --git a/test/unit/config.test.ts b/test/unit/config.test.ts index 5b05365..0c40595 100644 --- a/test/unit/config.test.ts +++ b/test/unit/config.test.ts @@ -122,6 +122,11 @@ describe("config", () => { [{ readOnly: "false" }, /"readOnly" must be true or false/], [{ requireConsent: "no" }, /"requireConsent" must be true or false/], [{ auditLog: 0 }, /"auditLog" must be true or false/], + [{ autoLaunch: "yes" }, /"autoLaunch" must be true or false/], + [ + { autoAttachWindows: 1 }, + /"autoAttachWindows" must be true or false/, + ], [{ allowedDomains: "example.com" }, /"allowedDomains" must be an array/], [ { allowedDomains: ["example.com", 7] }, diff --git a/test/unit/glance-policy.test.ts b/test/unit/glance-policy.test.ts index 1f7c8f9..485c720 100644 --- a/test/unit/glance-policy.test.ts +++ b/test/unit/glance-policy.test.ts @@ -28,10 +28,16 @@ interface GlanceCall { userContextId?: number; } +function glanceTab(url: string) { + return { linkedBrowser: { currentURI: { spec: url } } }; +} + function fakeWindow( spec: string, calls: GlanceCall[], - openGlance: (params: GlanceCall) => Promise = async () => true + openGlance: (params: GlanceCall) => Promise = async (params) => + glanceTab(params.url), + closes: unknown[] = [] ) { const tab = { label: "Preview", @@ -59,6 +65,9 @@ function fakeWindow( calls.push(params); return openGlance(params); }, + closeGlance: (options: unknown) => { + closes.push(options); + }, }, tab, }; @@ -138,4 +147,107 @@ describe("Glance URL policy", () => { assert.equal(calls.length, 1); assert.equal(calls[0]?.triggeringPrincipal.kind, "content"); }); + + it("refuses data: and javascript: URLs before calling Glance", async () => { + for (const url of ["data:text/html,

hi

", "javascript:alert(1)"]) { + const calls: GlanceCall[] = []; + const ops = createOps( + fakeWindow("https://allowed.example/", calls) as never, + "win" + ); + + await assert.rejects( + async () => ops.dispatch("glance.open", { url, allowedDomains: [] }), + (error: { code?: string }) => error.code === "invalid_url", + url + ); + assert.equal(calls.length, 0, url); + } + }); + + it("allows an allowed subdomain and refuses a lookalike host", async () => { + const allowedCalls: GlanceCall[] = []; + const allowedOps = createOps( + fakeWindow("https://deep.sub.allowed.example/a", allowedCalls) as never, + "win" + ); + const allowedId = await tabIdFor(allowedOps); + + const allowed = (await allowedOps.dispatch("glance.open", { + tabId: allowedId, + allowedDomains: ["allowed.example"], + })) as { opened: boolean; url: string }; + assert.equal(allowed.opened, true); + assert.equal(allowed.url, "https://deep.sub.allowed.example/a"); + + const blockedCalls: GlanceCall[] = []; + const blockedOps = createOps( + fakeWindow( + "https://allowed.example.attacker.test/a", + blockedCalls + ) as never, + "win" + ); + const blockedId = await tabIdFor(blockedOps); + + await assert.rejects( + async () => + blockedOps.dispatch("glance.open", { + tabId: blockedId, + allowedDomains: ["allowed.example"], + }), + (error: { code?: string }) => error.code === "domain_not_allowed" + ); + assert.equal(blockedCalls.length, 0); + }); + + it("closes a preview that redirects outside the allowlist", async () => { + const calls: GlanceCall[] = []; + const closes: unknown[] = []; + const ops = createOps( + fakeWindow( + "https://allowed.example/start", + calls, + async () => glanceTab("https://blocked.example/landing"), + closes + ) as never, + "win" + ); + + await assert.rejects( + async () => + ops.dispatch("glance.open", { + url: "https://allowed.example/start", + allowedDomains: ["allowed.example"], + }), + (error: { code?: string }) => error.code === "domain_not_allowed" + ); + assert.equal(calls.length, 1); + assert.equal(closes.length, 1); + }); + + it("fails closed when the preview result cannot be inspected", async () => { + const calls: GlanceCall[] = []; + const closes: unknown[] = []; + const ops = createOps( + fakeWindow( + "https://allowed.example/", + calls, + async () => true, + closes + ) as never, + "win" + ); + + await assert.rejects( + async () => + ops.dispatch("glance.open", { + url: "https://allowed.example/", + allowedDomains: ["allowed.example"], + }), + (error: { code?: string }) => error.code === "glance_failed" + ); + assert.equal(calls.length, 1); + assert.equal(closes.length, 1); + }); });