@spaxe-dev/zen-mcp 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import { existsSync as existsSync9 } from "node:fs";
4
+ import { existsSync as existsSync10 } from "node:fs";
5
5
  import { Command, InvalidArgumentError } from "commander";
6
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
7
 
@@ -133,17 +133,21 @@ function loadConfig() {
133
133
  const envConsent = process.env.ZEN_MCP_REQUIRE_CONSENT;
134
134
  const envConsentTimeout = process.env.ZEN_MCP_CONSENT_TIMEOUT_SECONDS;
135
135
  const envLaunchArgs = process.env.ZEN_MCP_LAUNCH_ARGS;
136
- const fileReadOnly = fileBoolean(
136
+ const fileReadOnly = fileSafetyBoolean(
137
137
  fileConfig.readOnly,
138
+ "readOnly",
138
139
  DEFAULT_CONFIG.readOnly
139
140
  );
140
- const fileAuditLog = fileBoolean(
141
+ const fileAuditLog = fileSafetyBoolean(
141
142
  fileConfig.auditLog,
143
+ "auditLog",
142
144
  DEFAULT_CONFIG.auditLog
143
145
  );
144
- const fileDomains = Array.isArray(fileConfig.allowedDomains) ? fileConfig.allowedDomains.filter(
145
- (entry) => typeof entry === "string"
146
- ) : DEFAULT_CONFIG.allowedDomains;
146
+ const fileDomains = fileStringArray(
147
+ fileConfig.allowedDomains,
148
+ "allowedDomains",
149
+ DEFAULT_CONFIG.allowedDomains
150
+ );
147
151
  const domains = envDomains !== void 0 ? envDomains.split(",").map((entry) => entry.trim().toLowerCase()).filter(Boolean) : fileDomains;
148
152
  const launchArgs = Array.isArray(fileConfig.launchArgs) ? fileConfig.launchArgs.map(String).filter(Boolean) : DEFAULT_CONFIG.launchArgs;
149
153
  return {
@@ -151,11 +155,16 @@ function loadConfig() {
151
155
  ...fileConfig,
152
156
  zenPath: process.env.ZEN_MCP_ZEN_PATH || (typeof fileConfig.zenPath === "string" ? fileConfig.zenPath : void 0),
153
157
  profilePath: process.env.ZEN_MCP_PROFILE || (typeof fileConfig.profilePath === "string" ? fileConfig.profilePath : void 0),
154
- useDefaultProfile: envUseDefault !== void 0 ? parseBoolean(envUseDefault, DEFAULT_CONFIG.useDefaultProfile) : fileBoolean(
158
+ useDefaultProfile: envUseDefault !== void 0 ? envBoolean("ZEN_MCP_USE_DEFAULT_PROFILE", envUseDefault) : fileSafetyBoolean(
155
159
  fileConfig.useDefaultProfile,
160
+ "useDefaultProfile",
156
161
  DEFAULT_CONFIG.useDefaultProfile
157
162
  ),
158
- requireConsent: envConsent !== void 0 ? parseBoolean(envConsent, DEFAULT_CONFIG.requireConsent) : fileBoolean(fileConfig.requireConsent, DEFAULT_CONFIG.requireConsent),
163
+ requireConsent: envConsent !== void 0 ? envBoolean("ZEN_MCP_REQUIRE_CONSENT", envConsent) : fileSafetyBoolean(
164
+ fileConfig.requireConsent,
165
+ "requireConsent",
166
+ DEFAULT_CONFIG.requireConsent
167
+ ),
159
168
  consentTimeoutSeconds: envConsentTimeout !== void 0 && envConsentTimeout.trim() ? boundedInt(
160
169
  envConsentTimeout,
161
170
  1,
@@ -174,11 +183,11 @@ function loadConfig() {
174
183
  65535,
175
184
  DEFAULT_CONFIG.marionettePort
176
185
  ),
177
- readOnly: envReadOnly !== void 0 ? parseBoolean(envReadOnly, fileReadOnly) : fileReadOnly,
186
+ readOnly: envReadOnly !== void 0 ? envBoolean("ZEN_MCP_READ_ONLY", envReadOnly) : fileReadOnly,
178
187
  allowedDomains: domains.map(
179
188
  (domain) => domain.replace(/^\*?\./, "").toLowerCase()
180
189
  ),
181
- auditLog: envAuditLog !== void 0 ? parseBoolean(envAuditLog, fileAuditLog) : fileAuditLog,
190
+ auditLog: envAuditLog !== void 0 ? envBoolean("ZEN_MCP_AUDIT_LOG", envAuditLog) : fileAuditLog,
182
191
  watchMinIntervalSeconds: envWatchMin !== void 0 && envWatchMin.trim() ? boundedInt(
183
192
  envWatchMin,
184
193
  1,
@@ -202,9 +211,14 @@ function loadConfig() {
202
211
  3600,
203
212
  DEFAULT_CONFIG.askTimeoutSeconds
204
213
  ),
205
- autoLaunch: fileBoolean(fileConfig.autoLaunch, DEFAULT_CONFIG.autoLaunch),
206
- autoAttachWindows: fileBoolean(
214
+ autoLaunch: fileSafetyBoolean(
215
+ fileConfig.autoLaunch,
216
+ "autoLaunch",
217
+ DEFAULT_CONFIG.autoLaunch
218
+ ),
219
+ autoAttachWindows: fileSafetyBoolean(
207
220
  fileConfig.autoAttachWindows,
221
+ "autoAttachWindows",
208
222
  DEFAULT_CONFIG.autoAttachWindows
209
223
  )
210
224
  };
@@ -226,13 +240,29 @@ function readConfigFile() {
226
240
  );
227
241
  }
228
242
  }
229
- function parseBoolean(value, fallback) {
230
- if (/^(1|true|yes|on)$/i.test(value.trim())) return true;
231
- if (/^(0|false|no|off)$/i.test(value.trim())) return false;
232
- return fallback;
243
+ function envBoolean(name, value) {
244
+ const normalized = value.trim().toLowerCase();
245
+ if (/^(1|true|yes|on)$/.test(normalized)) return true;
246
+ if (/^(0|false|no|off)$/.test(normalized)) return false;
247
+ throw new Error(
248
+ `Invalid ${name} value "${value}": use 1/0, true/false, yes/no, or on/off.`
249
+ );
233
250
  }
234
- function fileBoolean(value, fallback) {
235
- return typeof value === "boolean" ? value : fallback;
251
+ function fileSafetyBoolean(value, field, fallback) {
252
+ if (value === void 0) return fallback;
253
+ if (typeof value === "boolean") return value;
254
+ throw new Error(
255
+ `Invalid config at ${configFilePath()}: "${field}" must be true or false. Fix or delete the file.`
256
+ );
257
+ }
258
+ function fileStringArray(value, field, fallback) {
259
+ if (value === void 0) return fallback;
260
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
261
+ throw new Error(
262
+ `Invalid config at ${configFilePath()}: "${field}" must be an array of strings. Fix or delete the file.`
263
+ );
264
+ }
265
+ return value;
236
266
  }
237
267
  function boundedInt(value, min, max, fallback) {
238
268
  const parsed = typeof value === "number" ? value : Number(value);
@@ -261,7 +291,7 @@ import { WebSocketServer } from "ws";
261
291
  // src/shared/brand.ts
262
292
  var BRAND = "Zen MCP";
263
293
  var SERVER_NAME = "zen-mcp";
264
- var SERVER_VERSION = "0.3.2";
294
+ var SERVER_VERSION = "0.4.0";
265
295
  var BRIDGE_PROTOCOL_VERSION = 2;
266
296
 
267
297
  // src/shared/bridge-auth.ts
@@ -1144,10 +1174,17 @@ var BridgeHub = class {
1144
1174
  return this.request("containers.list", void 0, { windowId });
1145
1175
  }
1146
1176
  async openGlance(params, windowId) {
1147
- const result = await this.request("glance.open", params, {
1148
- windowId,
1149
- timeoutMs: 3e4
1150
- });
1177
+ if (params?.url) {
1178
+ this.#assertUrlAllowed(String(params.url), "Refusing to preview");
1179
+ }
1180
+ const result = await this.request(
1181
+ "glance.open",
1182
+ { ...params, allowedDomains: this.#allowedDomains },
1183
+ {
1184
+ windowId,
1185
+ timeoutMs: 3e4
1186
+ }
1187
+ );
1151
1188
  if (result.url) {
1152
1189
  this.#assertUrlAllowed(result.url, "Refusing to preview");
1153
1190
  }
@@ -1903,8 +1940,33 @@ var MUTATING_TOOLS = /* @__PURE__ */ new Set([
1903
1940
  "zen_tabs_group",
1904
1941
  "zen_show_evidence",
1905
1942
  "zen_show_evidence_batch",
1906
- "zen_clear_evidence"
1943
+ "zen_clear_evidence",
1944
+ "zen_progress",
1945
+ "zen_ask",
1946
+ "zen_notify"
1907
1947
  ]);
1948
+ function auditOutcomeForResult(tool, value) {
1949
+ const result = value !== null && typeof value === "object" ? value : void 0;
1950
+ const structuredOk = result && typeof result.ok === "boolean" ? result.ok : void 0;
1951
+ const fields = {
1952
+ ok: structuredOk ?? true,
1953
+ executed: true
1954
+ };
1955
+ if (!result) {
1956
+ return fields;
1957
+ }
1958
+ const total = result.total;
1959
+ const verified = result.verified;
1960
+ const failed = result.failed;
1961
+ const batchShaped = tool === "zen_show_evidence_batch" || total !== void 0 || verified !== void 0 || failed !== void 0;
1962
+ if (!batchShaped || typeof total !== "number" || !Number.isFinite(total) || typeof verified !== "number" || !Number.isFinite(verified) || typeof failed !== "number" || !Number.isFinite(failed)) {
1963
+ return fields;
1964
+ }
1965
+ fields.citationsVerified = verified;
1966
+ fields.citationsFailed = failed;
1967
+ fields.outcome = fields.ok && failed === 0 ? "success" : verified > 0 ? "partial" : "failed";
1968
+ return fields;
1969
+ }
1908
1970
  var MAX_STRING_CHARS = 500;
1909
1971
  var MAX_ARRAY_ENTRIES = 20;
1910
1972
  var MAX_DEPTH = 3;
@@ -2167,7 +2229,11 @@ var ToolGuard = class {
2167
2229
  at: next.at,
2168
2230
  tool: next.tool,
2169
2231
  ok: next.ok,
2232
+ executed: next.executed,
2170
2233
  durationMs: next.durationMs,
2234
+ ...next.citationsVerified !== void 0 ? { citationsVerified: next.citationsVerified } : {},
2235
+ ...next.citationsFailed !== void 0 ? { citationsFailed: next.citationsFailed } : {},
2236
+ ...next.outcome !== void 0 ? { outcome: next.outcome } : {},
2171
2237
  urls: next.urls,
2172
2238
  args: { truncated: true },
2173
2239
  ...next.error ? { error: next.error } : {}
@@ -2612,7 +2678,8 @@ var TOOL_OUTPUT_SCHEMAS = {
2612
2678
  },
2613
2679
  zen_tab_select: {
2614
2680
  tab: tabSchema,
2615
- activeSpaceId: z.string().nullable()
2681
+ activeSpaceId: z.string().nullable(),
2682
+ windowFocused: z.boolean().optional()
2616
2683
  },
2617
2684
  zen_glance: {
2618
2685
  opened: z.boolean(),
@@ -2627,7 +2694,9 @@ var TOOL_OUTPUT_SCHEMAS = {
2627
2694
  },
2628
2695
  zen_split_close: {
2629
2696
  unsplit: z.boolean(),
2630
- tabIds: z.array(z.string())
2697
+ tabIds: z.array(z.string()),
2698
+ closedResidue: z.number().optional(),
2699
+ limitation: z.string().optional()
2631
2700
  },
2632
2701
  zen_pin_tabs: {
2633
2702
  tabIds: z.array(z.string()),
@@ -2635,7 +2704,9 @@ var TOOL_OUTPUT_SCHEMAS = {
2635
2704
  },
2636
2705
  zen_essentials: {
2637
2706
  tabIds: z.array(z.string()),
2638
- changed: z.number()
2707
+ changed: z.number(),
2708
+ restored: z.number().optional(),
2709
+ limitation: z.string().optional()
2639
2710
  },
2640
2711
  zen_containers_list: {
2641
2712
  containers: z.array(containerInfoSchema)
@@ -2863,7 +2934,11 @@ var TOOL_OUTPUT_SCHEMAS = {
2863
2934
  at: z.string(),
2864
2935
  tool: z.string(),
2865
2936
  ok: z.boolean().optional(),
2937
+ executed: z.boolean().optional(),
2866
2938
  durationMs: z.number().optional(),
2939
+ citationsVerified: z.number().optional(),
2940
+ citationsFailed: z.number().optional(),
2941
+ outcome: z.enum(["success", "partial", "failed"]).optional(),
2867
2942
  args: z.unknown().optional(),
2868
2943
  error: z.looseObject({
2869
2944
  code: z.string().optional(),
@@ -4263,8 +4338,8 @@ function raceWithAbort(work, signal) {
4263
4338
  );
4264
4339
  });
4265
4340
  }
4341
+ var MAX_TAB_IDS_PER_CALL = 100;
4266
4342
  var 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.
4267
-
4268
4343
  Background research is the default workflow. Never take over the user's screen:
4269
4344
  1. Look first with zen_status, zen_spaces_list, and zen_tabs_list.
4270
4345
  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.
@@ -4357,7 +4432,9 @@ function createZenMcpServer(runtime, config) {
4357
4432
  let urls = [];
4358
4433
  if (signal.aborted) {
4359
4434
  const error = new BridgeRequestError("cancelled", CANCELLED_MESSAGE2);
4360
- guard.audit(auditRecord(tool, started, args, urls, false, error));
4435
+ guard.audit(
4436
+ auditRecord(tool, started, args, urls, { ok: false, executed: false }, error)
4437
+ );
4361
4438
  logToolEvent("warning", tool, "cancelled", error.message);
4362
4439
  return errorResult(error);
4363
4440
  }
@@ -4366,7 +4443,9 @@ function createZenMcpServer(runtime, config) {
4366
4443
  "paused",
4367
4444
  "The user paused Zen MCP in the browser. No reads or changes are allowed until they press Resume. zen_events shows when access is restored."
4368
4445
  );
4369
- guard.audit(auditRecord(tool, started, args, urls, false, error));
4446
+ guard.audit(
4447
+ auditRecord(tool, started, args, urls, { ok: false, executed: false }, error)
4448
+ );
4370
4449
  logToolEvent("warning", tool, "paused", error.message);
4371
4450
  return errorResult(error);
4372
4451
  }
@@ -4376,7 +4455,14 @@ function createZenMcpServer(runtime, config) {
4376
4455
  guard.check(tool, args, urls);
4377
4456
  } catch (error) {
4378
4457
  guard.audit(
4379
- auditRecord(tool, started, args, urls, false, error)
4458
+ auditRecord(
4459
+ tool,
4460
+ started,
4461
+ args,
4462
+ urls,
4463
+ { ok: false, executed: false },
4464
+ error
4465
+ )
4380
4466
  );
4381
4467
  logToolEvent("warning", tool, errorCode(error), describeError2(error));
4382
4468
  return errorResult(error);
@@ -4389,7 +4475,9 @@ function createZenMcpServer(runtime, config) {
4389
4475
  if (signal.aborted) {
4390
4476
  throw new BridgeRequestError("cancelled", CANCELLED_MESSAGE2);
4391
4477
  }
4392
- guard.audit(auditRecord(tool, started, args, urls, true));
4478
+ guard.audit(
4479
+ auditRecord(tool, started, args, urls, auditOutcomeForResult(tool, value))
4480
+ );
4393
4481
  if (RESOURCE_CHANGING_TOOLS.has(tool)) {
4394
4482
  try {
4395
4483
  server.sendResourceListChanged();
@@ -4403,7 +4491,14 @@ function createZenMcpServer(runtime, config) {
4403
4491
  } catch (error) {
4404
4492
  const failure = signal.aborted ? new BridgeRequestError("cancelled", CANCELLED_MESSAGE2) : error;
4405
4493
  guard.audit(
4406
- auditRecord(tool, started, args, urls, false, failure)
4494
+ auditRecord(
4495
+ tool,
4496
+ started,
4497
+ args,
4498
+ urls,
4499
+ { ok: false, executed: false },
4500
+ failure
4501
+ )
4407
4502
  );
4408
4503
  const code = errorCode(failure);
4409
4504
  logToolEvent(
@@ -4618,7 +4713,7 @@ function createZenMcpServer(runtime, config) {
4618
4713
  title: "Close tabs",
4619
4714
  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.",
4620
4715
  inputSchema: {
4621
- tabIds: z2.array(z2.string().min(1)).min(1).describe("Tab ids from zen_tabs_list.")
4716
+ tabIds: z2.array(z2.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.`)
4622
4717
  },
4623
4718
  annotations: { readOnlyHint: false, destructiveHint: true }
4624
4719
  },
@@ -4834,7 +4929,9 @@ function createZenMcpServer(runtime, config) {
4834
4929
  description: "Create a Zen folder around existing tabs, optionally collapsed. Useful for grouping a batch of research tabs inside a space. Tabs must be in one space and cannot already belong to a folder or split view.",
4835
4930
  inputSchema: {
4836
4931
  label: z2.string().min(1).describe("Folder label."),
4837
- tabIds: z2.array(z2.string().min(1)).optional().describe("Tabs to move into the folder."),
4932
+ tabIds: z2.array(z2.string().min(1)).max(MAX_TAB_IDS_PER_CALL).optional().describe(
4933
+ `Tabs to move into the folder. At most ${MAX_TAB_IDS_PER_CALL} per call.`
4934
+ ),
4838
4935
  space: z2.string().optional().describe("Space id or name. Defaults to the tabs' space or the active space."),
4839
4936
  collapsed: z2.boolean().optional().describe("Create the folder collapsed.")
4840
4937
  },
@@ -4858,7 +4955,9 @@ function createZenMcpServer(runtime, config) {
4858
4955
  description: "Move existing tabs into an existing folder. The tabs must be in the folder's space and not already grouped.",
4859
4956
  inputSchema: {
4860
4957
  folderId: z2.string().min(1).describe("Folder id from zen_folders_list."),
4861
- tabIds: z2.array(z2.string().min(1)).min(1).describe("Tab ids to move.")
4958
+ tabIds: z2.array(z2.string().min(1)).min(1).max(MAX_TAB_IDS_PER_CALL).describe(
4959
+ `Tab ids to move. At most ${MAX_TAB_IDS_PER_CALL} per call.`
4960
+ )
4862
4961
  },
4863
4962
  annotations: { readOnlyHint: false }
4864
4963
  },
@@ -5865,11 +5964,23 @@ function createZenMcpServer(runtime, config) {
5865
5964
  value = await read();
5866
5965
  } catch (error) {
5867
5966
  guard.audit(
5868
- auditRecord(`resource:${uri}`, started, void 0, [], false, error)
5967
+ auditRecord(
5968
+ `resource:${uri}`,
5969
+ started,
5970
+ void 0,
5971
+ [],
5972
+ { ok: false, executed: false },
5973
+ error
5974
+ )
5869
5975
  );
5870
5976
  throw error;
5871
5977
  }
5872
- guard.audit(auditRecord(`resource:${uri}`, started, void 0, [], true));
5978
+ guard.audit(
5979
+ auditRecord(`resource:${uri}`, started, void 0, [], {
5980
+ ok: true,
5981
+ executed: true
5982
+ })
5983
+ );
5873
5984
  return value;
5874
5985
  });
5875
5986
  jsonResource("zen://status", "Zen status", () => runtime.status());
@@ -6009,12 +6120,16 @@ function registerJsonResource(server, uri, title, read) {
6009
6120
  }
6010
6121
  );
6011
6122
  }
6012
- function auditRecord(tool, started, args, urls, ok, error) {
6123
+ function auditRecord(tool, started, args, urls, fields, error) {
6013
6124
  return {
6014
6125
  at: (/* @__PURE__ */ new Date()).toISOString(),
6015
6126
  tool,
6016
- ok,
6127
+ ok: fields.ok,
6128
+ executed: fields.executed,
6017
6129
  durationMs: Date.now() - started,
6130
+ ...fields.citationsVerified !== void 0 ? { citationsVerified: fields.citationsVerified } : {},
6131
+ ...fields.citationsFailed !== void 0 ? { citationsFailed: fields.citationsFailed } : {},
6132
+ ...fields.outcome !== void 0 ? { outcome: fields.outcome } : {},
6018
6133
  ...args !== void 0 ? { args } : {},
6019
6134
  ...urls.length > 0 ? { urls: [...new Set(urls)].slice(0, 30) } : {},
6020
6135
  ...error !== void 0 ? { error: { code: errorCode(error), message: describeError2(error) } } : {}
@@ -6043,23 +6158,1517 @@ function describeError2(error) {
6043
6158
  return name && name !== "Error" ? `${name}: ${message}` : message;
6044
6159
  }
6045
6160
 
6161
+ // src/onboard/clients.ts
6162
+ import { existsSync as existsSync7 } from "node:fs";
6163
+ import { homedir as homedir2 } from "node:os";
6164
+ import { dirname as dirname5, join as join7 } from "node:path";
6165
+ var MAX_CLIENT_CONFIG_BYTES = 20 * 1024 * 1024;
6166
+ var SERVER_ENTRY_NAME = "zen-mcp";
6167
+ var SERVER_ARGS = ["serve"];
6168
+ var CLINE_SETTINGS = join7(
6169
+ "User",
6170
+ "globalStorage",
6171
+ "saoudrizwan.claude-dev",
6172
+ "settings",
6173
+ "cline_mcp_settings.json"
6174
+ );
6175
+ var xdgConfig = (ctx) => ctx.env.XDG_CONFIG_HOME ?? join7(ctx.home, ".config");
6176
+ var mcpServers = (ctx) => ({
6177
+ command: ctx.command,
6178
+ args: [...SERVER_ARGS]
6179
+ });
6180
+ var DEFINITIONS = [
6181
+ {
6182
+ id: "claude-code",
6183
+ label: "Claude Code",
6184
+ detail: "Anthropic's terminal agent",
6185
+ popular: true,
6186
+ format: "json",
6187
+ configPaths: (ctx) => [join7(ctx.home, ".claude.json")],
6188
+ detectPaths: (ctx) => [
6189
+ join7(ctx.home, ".claude.json"),
6190
+ join7(ctx.home, ".claude")
6191
+ ],
6192
+ json: {
6193
+ path: ["mcpServers"],
6194
+ entry: (ctx) => ({
6195
+ command: ctx.command,
6196
+ args: [...SERVER_ARGS]
6197
+ })
6198
+ }
6199
+ },
6200
+ {
6201
+ id: "claude-desktop",
6202
+ label: "Claude Desktop",
6203
+ detail: "The Claude desktop app",
6204
+ popular: true,
6205
+ format: "json",
6206
+ configPaths: (ctx) => [
6207
+ join7(ctx.configBase, "Claude", "claude_desktop_config.json")
6208
+ ],
6209
+ detectPaths: (ctx) => [join7(ctx.configBase, "Claude")],
6210
+ json: {
6211
+ path: ["mcpServers"],
6212
+ entry: (ctx) => ({
6213
+ command: ctx.command,
6214
+ args: [...SERVER_ARGS]
6215
+ })
6216
+ }
6217
+ },
6218
+ {
6219
+ id: "cursor",
6220
+ label: "Cursor",
6221
+ detail: "Cursor editor",
6222
+ popular: true,
6223
+ format: "json",
6224
+ configPaths: (ctx) => [join7(ctx.home, ".cursor", "mcp.json")],
6225
+ detectPaths: (ctx) => [join7(ctx.home, ".cursor")],
6226
+ json: {
6227
+ path: ["mcpServers"],
6228
+ entry: (ctx) => ({
6229
+ command: ctx.command,
6230
+ args: [...SERVER_ARGS]
6231
+ })
6232
+ }
6233
+ },
6234
+ {
6235
+ id: "vscode",
6236
+ label: "VS Code",
6237
+ detail: "GitHub Copilot agent mode",
6238
+ popular: true,
6239
+ format: "json",
6240
+ configPaths: (ctx) => [
6241
+ join7(ctx.configBase, "Code", "User", "mcp.json"),
6242
+ join7(ctx.configBase, "Code - Insiders", "User", "mcp.json")
6243
+ ],
6244
+ detectPaths: (ctx) => [
6245
+ join7(ctx.configBase, "Code", "User"),
6246
+ join7(ctx.configBase, "Code - Insiders", "User")
6247
+ ],
6248
+ json: {
6249
+ path: ["servers"],
6250
+ entry: (ctx) => ({
6251
+ type: "stdio",
6252
+ command: ctx.command,
6253
+ args: [...SERVER_ARGS]
6254
+ })
6255
+ }
6256
+ },
6257
+ {
6258
+ id: "codex",
6259
+ label: "Codex CLI",
6260
+ detail: "OpenAI Codex terminal agent",
6261
+ popular: true,
6262
+ format: "toml",
6263
+ configPaths: (ctx) => [
6264
+ join7(ctx.env.CODEX_HOME ?? join7(ctx.home, ".codex"), "config.toml")
6265
+ ],
6266
+ detectPaths: (ctx) => [
6267
+ ctx.env.CODEX_HOME ?? join7(ctx.home, ".codex")
6268
+ ],
6269
+ toml: {
6270
+ section: "mcp_servers",
6271
+ values: (ctx) => ({
6272
+ command: ctx.command,
6273
+ args: [...SERVER_ARGS]
6274
+ })
6275
+ }
6276
+ },
6277
+ {
6278
+ id: "gemini-cli",
6279
+ label: "Gemini CLI",
6280
+ detail: "Google's terminal agent",
6281
+ popular: true,
6282
+ format: "json",
6283
+ configPaths: (ctx) => [join7(ctx.home, ".gemini", "settings.json")],
6284
+ detectPaths: (ctx) => [join7(ctx.home, ".gemini")],
6285
+ json: {
6286
+ path: ["mcpServers"],
6287
+ entry: (ctx) => ({
6288
+ command: ctx.command,
6289
+ args: [...SERVER_ARGS]
6290
+ })
6291
+ }
6292
+ },
6293
+ {
6294
+ id: "windsurf",
6295
+ label: "Windsurf",
6296
+ detail: "Windsurf editor",
6297
+ popular: false,
6298
+ format: "json",
6299
+ configPaths: (ctx) => [
6300
+ join7(ctx.home, ".codeium", "windsurf", "mcp_config.json")
6301
+ ],
6302
+ detectPaths: (ctx) => [join7(ctx.home, ".codeium", "windsurf")],
6303
+ json: {
6304
+ path: ["mcpServers"],
6305
+ entry: (ctx) => ({
6306
+ command: ctx.command,
6307
+ args: [...SERVER_ARGS]
6308
+ })
6309
+ }
6310
+ },
6311
+ {
6312
+ id: "cline",
6313
+ label: "Cline",
6314
+ detail: "Cline extension for VS Code-compatible editors",
6315
+ popular: false,
6316
+ format: "json",
6317
+ configPaths: (ctx) => [
6318
+ join7(ctx.configBase, "Code", CLINE_SETTINGS),
6319
+ join7(ctx.configBase, "Cursor", CLINE_SETTINGS),
6320
+ join7(ctx.configBase, "Windsurf", CLINE_SETTINGS)
6321
+ ],
6322
+ detectPaths: (ctx) => [
6323
+ dirname5(join7(ctx.configBase, "Code", CLINE_SETTINGS)),
6324
+ dirname5(join7(ctx.configBase, "Cursor", CLINE_SETTINGS)),
6325
+ dirname5(join7(ctx.configBase, "Windsurf", CLINE_SETTINGS))
6326
+ ],
6327
+ json: {
6328
+ path: ["mcpServers"],
6329
+ entry: (ctx) => ({
6330
+ command: ctx.command,
6331
+ args: [...SERVER_ARGS]
6332
+ })
6333
+ }
6334
+ },
6335
+ {
6336
+ id: "zed",
6337
+ label: "Zed",
6338
+ detail: "Zed editor",
6339
+ popular: false,
6340
+ format: "json",
6341
+ configPaths: (ctx) => [
6342
+ join7(ctx.configBase, ctx.platform === "linux" ? "zed" : "Zed", "settings.json")
6343
+ ],
6344
+ detectPaths: (ctx) => [
6345
+ join7(ctx.configBase, ctx.platform === "linux" ? "zed" : "Zed")
6346
+ ],
6347
+ json: {
6348
+ path: ["context_servers"],
6349
+ entry: (ctx) => ({
6350
+ command: ctx.command,
6351
+ args: [...SERVER_ARGS]
6352
+ })
6353
+ }
6354
+ },
6355
+ {
6356
+ id: "opencode",
6357
+ label: "OpenCode",
6358
+ detail: "sst terminal agent",
6359
+ popular: true,
6360
+ format: "json",
6361
+ configPaths: (ctx) => [
6362
+ join7(xdgConfig(ctx), "opencode", "opencode.json"),
6363
+ join7(xdgConfig(ctx), "opencode", "opencode.jsonc")
6364
+ ],
6365
+ detectPaths: (ctx) => [join7(xdgConfig(ctx), "opencode")],
6366
+ json: {
6367
+ path: ["mcp", "servers"],
6368
+ entry: (ctx) => ({
6369
+ type: "local",
6370
+ command: [ctx.command, ...SERVER_ARGS]
6371
+ })
6372
+ }
6373
+ },
6374
+ {
6375
+ id: "omp",
6376
+ label: "oh-my-pi (omp)",
6377
+ detail: "can1357's terminal agent",
6378
+ popular: true,
6379
+ format: "json",
6380
+ configPaths: (ctx) => [
6381
+ join7(
6382
+ ctx.env.PI_CONFIG_DIR ?? join7(ctx.home, ".omp"),
6383
+ "agent",
6384
+ "mcp.json"
6385
+ )
6386
+ ],
6387
+ detectPaths: (ctx) => [
6388
+ ctx.env.PI_CONFIG_DIR ?? join7(ctx.home, ".omp")
6389
+ ],
6390
+ json: {
6391
+ path: ["mcpServers"],
6392
+ entry: (ctx) => ({
6393
+ type: "stdio",
6394
+ command: ctx.command,
6395
+ args: [...SERVER_ARGS]
6396
+ })
6397
+ }
6398
+ },
6399
+ {
6400
+ id: "dsh",
6401
+ label: "DeepSeek Harness",
6402
+ detail: "dsh agent framework",
6403
+ popular: true,
6404
+ format: "yaml",
6405
+ configPaths: (ctx) => [
6406
+ join7(ctx.env.DSH_HOME ?? join7(ctx.home, ".dsh"), "cordis.patch.yml")
6407
+ ],
6408
+ detectPaths: (ctx) => [ctx.env.DSH_HOME ?? join7(ctx.home, ".dsh")],
6409
+ text: (existing, ctx) => mergeDshPatch(existing, ctx)
6410
+ },
6411
+ {
6412
+ id: "zcode",
6413
+ label: "ZCode (Z.ai)",
6414
+ detail: "Z.ai coding agent",
6415
+ popular: true,
6416
+ format: "json",
6417
+ configPaths: (ctx) => [join7(ctx.home, ".zcode", "cli", "config.json")],
6418
+ detectPaths: (ctx) => [join7(ctx.home, ".zcode")],
6419
+ json: {
6420
+ path: ["mcp", "servers"],
6421
+ entry: (ctx) => ({
6422
+ command: ctx.command,
6423
+ args: [...SERVER_ARGS],
6424
+ env: {}
6425
+ })
6426
+ }
6427
+ },
6428
+ {
6429
+ id: "roo-code",
6430
+ label: "Roo Code",
6431
+ detail: "VS Code extension",
6432
+ popular: false,
6433
+ format: "json",
6434
+ configPaths: (ctx) => [
6435
+ join7(
6436
+ ctx.configBase,
6437
+ "Code",
6438
+ "User",
6439
+ "globalStorage",
6440
+ "rooveterinaryinc.roo-cline",
6441
+ "settings",
6442
+ "mcp_settings.json"
6443
+ )
6444
+ ],
6445
+ detectPaths: (ctx) => [
6446
+ join7(
6447
+ ctx.configBase,
6448
+ "Code",
6449
+ "User",
6450
+ "globalStorage",
6451
+ "rooveterinaryinc.roo-cline"
6452
+ )
6453
+ ],
6454
+ json: {
6455
+ path: ["mcpServers"],
6456
+ entry: (ctx) => ({
6457
+ command: ctx.command,
6458
+ args: [...SERVER_ARGS],
6459
+ disabled: false,
6460
+ alwaysAllow: []
6461
+ })
6462
+ }
6463
+ },
6464
+ {
6465
+ id: "kilo-code",
6466
+ label: "Kilo Code",
6467
+ detail: "Kilo editor extension",
6468
+ popular: false,
6469
+ format: "json",
6470
+ configPaths: (ctx) => [join7(xdgConfig(ctx), "kilo", "kilo.jsonc")],
6471
+ detectPaths: (ctx) => [join7(xdgConfig(ctx), "kilo")],
6472
+ json: {
6473
+ path: ["mcp"],
6474
+ entry: (ctx) => ({
6475
+ type: "local",
6476
+ command: [ctx.command, ...SERVER_ARGS],
6477
+ enabled: true,
6478
+ timeout: 1e4
6479
+ })
6480
+ }
6481
+ },
6482
+ {
6483
+ id: "continue",
6484
+ label: "Continue",
6485
+ detail: "VS Code and JetBrains extension",
6486
+ popular: false,
6487
+ format: "yaml",
6488
+ configPaths: (ctx) => [join7(ctx.home, ".continue", "config.yaml")],
6489
+ detectPaths: (ctx) => [join7(ctx.home, ".continue")],
6490
+ text: (existing, ctx) => mergeYamlListSection(existing, "mcpServers", SERVER_ENTRY_NAME, [
6491
+ `name: ${SERVER_ENTRY_NAME}`,
6492
+ "type: stdio",
6493
+ `command: ${yamlScalar(ctx.command)}`,
6494
+ `args: ${yamlFlowArray(SERVER_ARGS)}`
6495
+ ])
6496
+ },
6497
+ {
6498
+ id: "amp",
6499
+ label: "Amp",
6500
+ detail: "Sourcegraph terminal agent",
6501
+ popular: false,
6502
+ format: "json",
6503
+ configPaths: (ctx) => [
6504
+ ctx.platform === "win32" ? join7(ctx.configBase, "amp", "settings.json") : join7(xdgConfig(ctx), "amp", "settings.json")
6505
+ ],
6506
+ detectPaths: (ctx) => [
6507
+ ctx.platform === "win32" ? join7(ctx.configBase, "amp") : join7(xdgConfig(ctx), "amp")
6508
+ ],
6509
+ json: {
6510
+ path: ["amp.mcpServers"],
6511
+ entry: (ctx) => mcpServers(ctx)
6512
+ }
6513
+ },
6514
+ {
6515
+ id: "crush",
6516
+ label: "Crush",
6517
+ detail: "Charmbracelet terminal agent",
6518
+ popular: false,
6519
+ format: "bash",
6520
+ configPaths: (ctx) => [
6521
+ ctx.env.CRUSH_GLOBAL_CONFIG ?? join7(xdgConfig(ctx), "crush", "crushrc")
6522
+ ],
6523
+ detectPaths: (ctx) => [join7(xdgConfig(ctx), "crush")],
6524
+ text: (existing, ctx) => mergeCrushrc(existing, ctx)
6525
+ },
6526
+ {
6527
+ id: "qwen-code",
6528
+ label: "Qwen Code",
6529
+ detail: "Alibaba terminal agent",
6530
+ popular: false,
6531
+ format: "json",
6532
+ configPaths: (ctx) => [
6533
+ join7(ctx.env.QWEN_HOME ?? join7(ctx.home, ".qwen"), "settings.json")
6534
+ ],
6535
+ detectPaths: (ctx) => [ctx.env.QWEN_HOME ?? join7(ctx.home, ".qwen")],
6536
+ json: {
6537
+ path: ["mcpServers"],
6538
+ entry: (ctx) => mcpServers(ctx)
6539
+ }
6540
+ },
6541
+ {
6542
+ id: "kiro",
6543
+ label: "Kiro",
6544
+ detail: "AWS agentic IDE and CLI",
6545
+ popular: false,
6546
+ format: "json",
6547
+ configPaths: (ctx) => [join7(ctx.home, ".kiro", "settings", "mcp.json")],
6548
+ detectPaths: (ctx) => [join7(ctx.home, ".kiro")],
6549
+ json: {
6550
+ path: ["mcpServers"],
6551
+ entry: (ctx) => ({
6552
+ command: ctx.command,
6553
+ args: [...SERVER_ARGS],
6554
+ disabled: false,
6555
+ autoApprove: []
6556
+ })
6557
+ }
6558
+ },
6559
+ {
6560
+ id: "warp",
6561
+ label: "Warp",
6562
+ detail: "Warp terminal agent",
6563
+ popular: false,
6564
+ format: "json",
6565
+ configPaths: (ctx) => [join7(ctx.home, ".warp", ".mcp.json")],
6566
+ detectPaths: (ctx) => [join7(ctx.home, ".warp")],
6567
+ json: {
6568
+ path: ["mcpServers"],
6569
+ entry: (ctx) => mcpServers(ctx)
6570
+ }
6571
+ },
6572
+ {
6573
+ id: "copilot-cli",
6574
+ label: "Copilot CLI",
6575
+ detail: "GitHub Copilot terminal agent",
6576
+ popular: false,
6577
+ format: "json",
6578
+ configPaths: (ctx) => [join7(ctx.home, ".copilot", "mcp-config.json")],
6579
+ detectPaths: (ctx) => [join7(ctx.home, ".copilot")],
6580
+ json: {
6581
+ path: ["mcpServers"],
6582
+ entry: (ctx) => ({
6583
+ type: "local",
6584
+ command: ctx.command,
6585
+ args: [...SERVER_ARGS],
6586
+ tools: ["*"]
6587
+ })
6588
+ }
6589
+ },
6590
+ {
6591
+ id: "droid",
6592
+ label: "Factory Droid",
6593
+ detail: "Factory terminal agent",
6594
+ popular: false,
6595
+ format: "json",
6596
+ configPaths: (ctx) => [join7(ctx.home, ".factory", "mcp.json")],
6597
+ detectPaths: (ctx) => [join7(ctx.home, ".factory")],
6598
+ json: {
6599
+ path: ["mcpServers"],
6600
+ entry: (ctx) => ({
6601
+ type: "stdio",
6602
+ command: ctx.command,
6603
+ args: [...SERVER_ARGS],
6604
+ disabled: false
6605
+ })
6606
+ }
6607
+ },
6608
+ {
6609
+ id: "amazon-q",
6610
+ label: "Amazon Q",
6611
+ detail: "Amazon Q Developer CLI",
6612
+ popular: false,
6613
+ format: "json",
6614
+ configPaths: (ctx) => [
6615
+ join7(ctx.home, ".aws", "amazonq", "mcp.json")
6616
+ ],
6617
+ detectPaths: (ctx) => [join7(ctx.home, ".aws", "amazonq")],
6618
+ json: {
6619
+ path: ["mcpServers"],
6620
+ entry: (ctx) => mcpServers(ctx)
6621
+ }
6622
+ },
6623
+ {
6624
+ id: "goose",
6625
+ label: "Goose",
6626
+ detail: "Block's terminal agent",
6627
+ popular: false,
6628
+ format: "yaml",
6629
+ configPaths: (ctx) => [
6630
+ ctx.platform === "win32" ? join7(ctx.configBase, "Block", "goose", "config", "config.yaml") : join7(xdgConfig(ctx), "goose", "config.yaml")
6631
+ ],
6632
+ detectPaths: (ctx) => [
6633
+ ctx.platform === "win32" ? join7(ctx.configBase, "Block", "goose") : join7(xdgConfig(ctx), "goose")
6634
+ ],
6635
+ text: (existing, ctx) => mergeYamlMappingSection(existing, "extensions", SERVER_ENTRY_NAME, [
6636
+ "type: stdio",
6637
+ `name: ${SERVER_ENTRY_NAME}`,
6638
+ "enabled: true",
6639
+ `cmd: ${yamlScalar(ctx.command)}`,
6640
+ `args: ${yamlFlowArray(SERVER_ARGS)}`,
6641
+ "envs: {}",
6642
+ "timeout: 300"
6643
+ ])
6644
+ },
6645
+ {
6646
+ id: "lm-studio",
6647
+ label: "LM Studio",
6648
+ detail: "LM Studio desktop app",
6649
+ popular: false,
6650
+ format: "json",
6651
+ configPaths: (ctx) => [join7(ctx.home, ".lmstudio", "mcp.json")],
6652
+ detectPaths: (ctx) => [join7(ctx.home, ".lmstudio")],
6653
+ json: {
6654
+ path: ["mcpServers"],
6655
+ entry: (ctx) => mcpServers(ctx)
6656
+ }
6657
+ },
6658
+ {
6659
+ id: "junie",
6660
+ label: "Junie",
6661
+ detail: "JetBrains Junie CLI",
6662
+ popular: false,
6663
+ format: "json",
6664
+ configPaths: (ctx) => [join7(ctx.home, ".junie", "mcp", "mcp.json")],
6665
+ detectPaths: (ctx) => [join7(ctx.home, ".junie")],
6666
+ json: {
6667
+ path: ["mcpServers"],
6668
+ entry: (ctx) => mcpServers(ctx)
6669
+ }
6670
+ },
6671
+ {
6672
+ id: "pi",
6673
+ label: "Pi",
6674
+ detail: "pi.dev terminal agent",
6675
+ popular: false,
6676
+ format: "json",
6677
+ configPaths: (ctx) => [join7(ctx.home, ".pi", "agent", "mcp.json")],
6678
+ detectPaths: (ctx) => [join7(ctx.home, ".pi")],
6679
+ json: {
6680
+ path: ["mcpServers"],
6681
+ entry: (ctx) => mcpServers(ctx)
6682
+ }
6683
+ }
6684
+ ];
6685
+ function clientIds() {
6686
+ return DEFINITIONS.map((definition) => definition.id);
6687
+ }
6688
+ function catalog(ctx = {}) {
6689
+ const resolved = resolveContext(ctx);
6690
+ const entries = DEFINITIONS.map((definition) => {
6691
+ const paths = definition.configPaths(resolved);
6692
+ return {
6693
+ id: definition.id,
6694
+ label: definition.label,
6695
+ detail: definition.detail,
6696
+ popular: definition.popular,
6697
+ detected: definition.detectPaths(resolved).some((path) => existsSync7(path)),
6698
+ configPath: paths.find((path) => existsSync7(path)) ?? paths[0],
6699
+ format: definition.format
6700
+ };
6701
+ });
6702
+ return [
6703
+ ...entries.filter((entry) => entry.popular),
6704
+ ...entries.filter((entry) => !entry.popular)
6705
+ ];
6706
+ }
6707
+ function applyClient(id, ctx = {}) {
6708
+ const definition = DEFINITIONS.find((entry) => entry.id === id);
6709
+ if (!definition) {
6710
+ return {
6711
+ id,
6712
+ label: id,
6713
+ path: "",
6714
+ status: "failed",
6715
+ message: "unknown client"
6716
+ };
6717
+ }
6718
+ const resolved = resolveContext(ctx);
6719
+ const paths = definition.configPaths(resolved);
6720
+ const path = paths.find((candidate) => existsSync7(candidate)) ?? paths[0];
6721
+ const existed = existsSync7(path);
6722
+ try {
6723
+ const existing = existed ? readFileTextBounded(path, MAX_CLIENT_CONFIG_BYTES) : void 0;
6724
+ if (definition.text) {
6725
+ atomicWritePrivate(path, definition.text(existing, resolved));
6726
+ } else if (definition.format === "toml") {
6727
+ const toml = definition.toml;
6728
+ if (!toml) throw new Error("TOML settings are missing for this client");
6729
+ const next = mergeTomlServer(
6730
+ existing ?? "",
6731
+ `${toml.section}.${SERVER_ENTRY_NAME}`,
6732
+ toml.values(resolved)
6733
+ );
6734
+ atomicWritePrivate(path, next);
6735
+ } else {
6736
+ const json = definition.json;
6737
+ if (!json) throw new Error("JSON settings are missing for this client");
6738
+ const next = mergeJsonServerPath(
6739
+ existing,
6740
+ json.path,
6741
+ json.entry(resolved)
6742
+ );
6743
+ atomicWritePrivate(path, next);
6744
+ }
6745
+ return {
6746
+ id: definition.id,
6747
+ label: definition.label,
6748
+ path,
6749
+ status: "ok",
6750
+ message: `${existed ? "Updated" : "Created"} ${path}`
6751
+ };
6752
+ } catch (error) {
6753
+ return {
6754
+ id: definition.id,
6755
+ label: definition.label,
6756
+ path,
6757
+ status: "failed",
6758
+ message: `${path}: ${error.message}`
6759
+ };
6760
+ }
6761
+ }
6762
+ function mergeJsonServerPath(existing, path, entry) {
6763
+ let text = existing;
6764
+ if (text && text.charCodeAt(0) === 65279) text = text.slice(1);
6765
+ if (!text || !text.trim()) {
6766
+ const root = {};
6767
+ placeJsonServer(root, path, entry);
6768
+ return `${JSON.stringify(root, null, 2)}
6769
+ `;
6770
+ }
6771
+ let parsed;
6772
+ try {
6773
+ parsed = JSON.parse(text);
6774
+ } catch (error) {
6775
+ try {
6776
+ return mergeJsoncServerPath(text, path, entry);
6777
+ } catch {
6778
+ throw new Error(
6779
+ `existing file is not valid JSON or JSONC (${error.message})`
6780
+ );
6781
+ }
6782
+ }
6783
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
6784
+ throw new Error("existing file is not a JSON object");
6785
+ }
6786
+ placeJsonServer(parsed, path, entry);
6787
+ return `${JSON.stringify(parsed, null, 2)}
6788
+ `;
6789
+ }
6790
+ function placeJsonServer(root, path, entry) {
6791
+ let node = root;
6792
+ for (const key of path) {
6793
+ const current = node[key];
6794
+ if (current === void 0) {
6795
+ const created = {};
6796
+ node[key] = created;
6797
+ node = created;
6798
+ continue;
6799
+ }
6800
+ if (current === null || typeof current !== "object" || Array.isArray(current)) {
6801
+ throw new Error(`"${key}" is not a JSON object`);
6802
+ }
6803
+ node = current;
6804
+ }
6805
+ node[SERVER_ENTRY_NAME] = entry;
6806
+ }
6807
+ function mergeJsoncServerPath(text, path, entry) {
6808
+ const rootStart = skipJsoncTrivia(text, 0);
6809
+ if (text[rootStart] !== "{") {
6810
+ throw new Error("the top level is not a JSON object");
6811
+ }
6812
+ let object = scanJsoncObject(text, rootStart);
6813
+ if (!object) throw new Error("the file has an unterminated object");
6814
+ for (let index = 0; index < path.length; index += 1) {
6815
+ const key = path[index];
6816
+ const member = object.members.find((item) => item.key === key);
6817
+ if (!member) {
6818
+ return insertJsoncMember(
6819
+ text,
6820
+ object,
6821
+ key,
6822
+ nestedJsonValue(path.slice(index + 1), entry)
6823
+ );
6824
+ }
6825
+ if (text[member.valueStart] !== "{") {
6826
+ throw new Error(`"${key}" is not a JSON object`);
6827
+ }
6828
+ const child = scanJsoncObject(text, member.valueStart);
6829
+ if (!child) throw new Error(`"${key}" is not a complete object`);
6830
+ if (index === path.length - 1) {
6831
+ return upsertJsoncServer(text, child, entry);
6832
+ }
6833
+ object = child;
6834
+ }
6835
+ throw new Error("the server path is empty");
6836
+ }
6837
+ function nestedJsonValue(keys, entry) {
6838
+ return keys.reduceRight(
6839
+ (value, key) => ({ [key]: value }),
6840
+ { [SERVER_ENTRY_NAME]: entry }
6841
+ );
6842
+ }
6843
+ function upsertJsoncServer(text, serverMap, entry) {
6844
+ const current = serverMap.members.find(
6845
+ (member) => member.key === SERVER_ENTRY_NAME
6846
+ );
6847
+ if (!current) {
6848
+ return insertJsoncMember(text, serverMap, SERVER_ENTRY_NAME, entry);
6849
+ }
6850
+ const inline = !text.slice(current.valueStart, current.valueEnd).includes("\n");
6851
+ const replacement = inline ? JSON.stringify(entry) : indentJson(
6852
+ JSON.stringify(entry, null, 2),
6853
+ memberIndent(text, current.keyStart, serverMap)
6854
+ );
6855
+ return text.slice(0, current.valueStart) + replacement + text.slice(current.valueEnd);
6856
+ }
6857
+ function insertJsoncMember(text, object, name, entry) {
6858
+ let source = text;
6859
+ let close = object.close;
6860
+ const last = object.members[object.members.length - 1];
6861
+ if (last) {
6862
+ const between = source.slice(last.valueEnd, object.close);
6863
+ if (!between.includes(",")) {
6864
+ source = source.slice(0, last.valueEnd) + "," + source.slice(last.valueEnd);
6865
+ close += 1;
6866
+ }
6867
+ }
6868
+ const lineStart = source.lastIndexOf("\n", close - 1) + 1;
6869
+ const onOwnLine = lineStart > object.open && source.slice(lineStart, close).trim() === "";
6870
+ if (!onOwnLine) {
6871
+ const inline = JSON.stringify({ [name]: entry }).slice(1, -1);
6872
+ return `${source.slice(0, close)} ${inline} ${source.slice(close)}`;
6873
+ }
6874
+ const indent = last ? memberIndent(source, last.keyStart, object) : `${closeIndent(source, object)} `;
6875
+ const entryText = `${JSON.stringify(name)}: ${indentJson(
6876
+ JSON.stringify(entry, null, 2),
6877
+ indent
6878
+ )}`;
6879
+ return source.slice(0, lineStart) + `${indent}${entryText}
6880
+ ` + source.slice(lineStart);
6881
+ }
6882
+ function scanJsoncObject(text, open) {
6883
+ const members = [];
6884
+ let index = open + 1;
6885
+ let expectingMember = true;
6886
+ while (true) {
6887
+ index = skipJsoncTrivia(text, index);
6888
+ if (index >= text.length) return null;
6889
+ const char = text[index];
6890
+ if (char === "}") {
6891
+ return { open, close: index, members };
6892
+ }
6893
+ if (!expectingMember) {
6894
+ if (char !== ",") return null;
6895
+ index += 1;
6896
+ expectingMember = true;
6897
+ continue;
6898
+ }
6899
+ if (char !== '"') return null;
6900
+ const keyStart = index;
6901
+ const keyEnd = scanJsoncString(text, index);
6902
+ if (keyEnd < 0) return null;
6903
+ let key;
6904
+ try {
6905
+ key = JSON.parse(text.slice(keyStart, keyEnd));
6906
+ } catch {
6907
+ return null;
6908
+ }
6909
+ index = skipJsoncTrivia(text, keyEnd);
6910
+ if (text[index] !== ":") return null;
6911
+ index = skipJsoncTrivia(text, index + 1);
6912
+ const valueStart = index;
6913
+ const valueEnd = skipJsoncValue(text, index);
6914
+ if (valueEnd < 0) return null;
6915
+ members.push({ key, keyStart, valueStart, valueEnd });
6916
+ index = skipJsoncTrivia(text, valueEnd);
6917
+ expectingMember = false;
6918
+ }
6919
+ }
6920
+ function skipJsoncTrivia(text, index) {
6921
+ let cursor = index;
6922
+ while (cursor < text.length) {
6923
+ const char = text[cursor];
6924
+ if (/\s/.test(char)) {
6925
+ cursor += 1;
6926
+ } else if (char === "/" && text[cursor + 1] === "/") {
6927
+ cursor += 2;
6928
+ while (cursor < text.length && text[cursor] !== "\n") cursor += 1;
6929
+ } else if (char === "/" && text[cursor + 1] === "*") {
6930
+ cursor += 2;
6931
+ while (cursor < text.length && !(text[cursor] === "*" && text[cursor + 1] === "/")) {
6932
+ cursor += 1;
6933
+ }
6934
+ cursor += 2;
6935
+ } else {
6936
+ break;
6937
+ }
6938
+ }
6939
+ return Math.min(cursor, text.length);
6940
+ }
6941
+ function scanJsoncString(text, index) {
6942
+ let cursor = index + 1;
6943
+ while (cursor < text.length) {
6944
+ if (text[cursor] === "\\") {
6945
+ cursor += 2;
6946
+ } else if (text[cursor] === '"') {
6947
+ return cursor + 1;
6948
+ } else {
6949
+ cursor += 1;
6950
+ }
6951
+ }
6952
+ return -1;
6953
+ }
6954
+ function skipJsoncValue(text, index) {
6955
+ const char = text[index];
6956
+ if (char === '"') return scanJsoncString(text, index);
6957
+ if (char === "{" || char === "[") {
6958
+ let depth = 0;
6959
+ let cursor2 = index;
6960
+ while (cursor2 < text.length) {
6961
+ const current = text[cursor2];
6962
+ if (current === '"') {
6963
+ const end = scanJsoncString(text, cursor2);
6964
+ if (end < 0) return -1;
6965
+ cursor2 = end;
6966
+ continue;
6967
+ }
6968
+ if (current === "/" && (text[cursor2 + 1] === "/" || text[cursor2 + 1] === "*")) {
6969
+ cursor2 = skipJsoncTrivia(text, cursor2);
6970
+ continue;
6971
+ }
6972
+ if (current === "{" || current === "[") depth += 1;
6973
+ else if (current === "}" || current === "]") {
6974
+ depth -= 1;
6975
+ if (depth === 0) return cursor2 + 1;
6976
+ }
6977
+ cursor2 += 1;
6978
+ }
6979
+ return -1;
6980
+ }
6981
+ let cursor = index;
6982
+ while (cursor < text.length && !/[\s,\]}]/.test(text[cursor])) cursor += 1;
6983
+ return cursor > index ? cursor : -1;
6984
+ }
6985
+ function memberIndent(text, keyStart, object) {
6986
+ let start = keyStart;
6987
+ while (start > object.open && (text[start - 1] === " " || text[start - 1] === " ")) {
6988
+ start -= 1;
6989
+ }
6990
+ if (start > object.open && text[start - 1] === "\n") {
6991
+ return text.slice(start, keyStart);
6992
+ }
6993
+ const openLine = text.lastIndexOf("\n", object.open - 1) + 1;
6994
+ return `${" ".repeat(object.open - openLine + 2)}`;
6995
+ }
6996
+ function closeIndent(text, object) {
6997
+ const start = text.lastIndexOf("\n", object.close - 1) + 1;
6998
+ const between = text.slice(start, object.close);
6999
+ if (/^[ \t]*$/.test(between)) return between;
7000
+ const openLine = text.lastIndexOf("\n", object.open - 1) + 1;
7001
+ return " ".repeat(object.open - openLine);
7002
+ }
7003
+ function indentJson(value, indent) {
7004
+ return value.replace(/\n/g, `
7005
+ ${indent}`);
7006
+ }
7007
+ function mergeTomlServer(existing, table, values) {
7008
+ const lines = existing ? existing.replace(/\r\n/g, "\n").split("\n") : [];
7009
+ const header = `[${table}]`;
7010
+ const headerPattern = new RegExp(
7011
+ `^\\s*\\[\\s*(?:"${escapeRegExp(table)}"|'${escapeRegExp(table)}'|${escapeRegExp(
7012
+ table
7013
+ )})\\s*\\]\\s*(?:#.*)?$`
7014
+ );
7015
+ const block = [
7016
+ header,
7017
+ ...Object.entries(values).map(
7018
+ ([name, value]) => `${name} = ${tomlValue(value)}`
7019
+ )
7020
+ ];
7021
+ const start = lines.findIndex((line) => headerPattern.test(line));
7022
+ if (start >= 0) {
7023
+ let end = start + 1;
7024
+ while (end < lines.length && !/^\s*\[/.test(lines[end])) end += 1;
7025
+ lines.splice(start, end - start, ...block);
7026
+ } else {
7027
+ while (lines.length > 0 && lines[lines.length - 1].trim() === "") {
7028
+ lines.pop();
7029
+ }
7030
+ if (lines.length > 0) lines.push("");
7031
+ lines.push(...block);
7032
+ }
7033
+ return `${lines.join("\n")}
7034
+ `;
7035
+ }
7036
+ function yamlScalar(value) {
7037
+ return JSON.stringify(value);
7038
+ }
7039
+ function yamlFlowArray(values) {
7040
+ return `[${values.map(yamlScalar).join(", ")}]`;
7041
+ }
7042
+ function findYamlSection(lines, section) {
7043
+ const header = new RegExp(`^${escapeRegExp(section)}:\\s*(?:#.*)?$`);
7044
+ const start = lines.findIndex((line) => header.test(line));
7045
+ if (start < 0) return null;
7046
+ let end = start + 1;
7047
+ while (end < lines.length) {
7048
+ const line = lines[end];
7049
+ if (line.trim() === "" || /^[ \t]/.test(line) || line.trimStart().startsWith("#")) {
7050
+ end += 1;
7051
+ } else {
7052
+ break;
7053
+ }
7054
+ }
7055
+ const child = lines.slice(start + 1, end).find((line) => /^[ \t]+\S/.test(line));
7056
+ return { start, end, indent: child?.match(/^[ \t]+/)?.[0] ?? " " };
7057
+ }
7058
+ function splitYamlLines(existing) {
7059
+ const lines = (existing ?? "").replace(/\r\n/g, "\n").split("\n");
7060
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
7061
+ return lines;
7062
+ }
7063
+ function mergeYamlMappingSection(existing, section, key, block) {
7064
+ const lines = splitYamlLines(existing);
7065
+ const found = findYamlSection(lines, section);
7066
+ if (!found) {
7067
+ if (lines.length > 0) lines.push("");
7068
+ lines.push(
7069
+ `${section}:`,
7070
+ `${key}:`,
7071
+ ...block.map((line) => ` ${line}`)
7072
+ );
7073
+ return `${lines.join("\n")}
7074
+ `;
7075
+ }
7076
+ const indent = found.indent;
7077
+ const keyLine = `${indent}${key}:`;
7078
+ const keyPattern = new RegExp(
7079
+ `^${escapeRegExp(indent)}${escapeRegExp(key)}:\\s*(?:#.*)?$`
7080
+ );
7081
+ const index = lines.findIndex(
7082
+ (line, position) => position > found.start && position < found.end && keyPattern.test(line)
7083
+ );
7084
+ if (index >= 0) {
7085
+ let end = index + 1;
7086
+ while (end < found.end) {
7087
+ const line = lines[end];
7088
+ if (line.trim() === "") {
7089
+ end += 1;
7090
+ continue;
7091
+ }
7092
+ const lineIndent = line.match(/^[ \t]*/)?.[0].length ?? 0;
7093
+ if (lineIndent <= indent.length) break;
7094
+ end += 1;
7095
+ }
7096
+ lines.splice(
7097
+ index,
7098
+ end - index,
7099
+ keyLine,
7100
+ ...block.map((line) => ` ${indent}${line}`)
7101
+ );
7102
+ } else {
7103
+ lines.splice(
7104
+ found.end,
7105
+ 0,
7106
+ keyLine,
7107
+ ...block.map((line) => ` ${indent}${line}`)
7108
+ );
7109
+ }
7110
+ return `${lines.join("\n")}
7111
+ `;
7112
+ }
7113
+ function mergeYamlListSection(existing, section, name, block) {
7114
+ const lines = splitYamlLines(existing);
7115
+ const found = findYamlSection(lines, section);
7116
+ const item = [`- name: ${name}`, ...block.slice(1)];
7117
+ if (!found) {
7118
+ if (lines.length > 0) lines.push("");
7119
+ lines.push(`${section}:`, ...item.map((line) => ` ${line}`));
7120
+ return `${lines.join("\n")}
7121
+ `;
7122
+ }
7123
+ const itemIndent = lines.slice(found.start + 1, found.end).find((line) => /^[ \t]*-[ \t]+\S/.test(line))?.match(/^[ \t]*/)?.[0] ?? " ";
7124
+ const namePattern = new RegExp(
7125
+ `^${escapeRegExp(itemIndent)}-[ \\t]+name:\\s*['"]?${escapeRegExp(
7126
+ name
7127
+ )}['"]?\\s*(?:#.*)?$`
7128
+ );
7129
+ const index = lines.findIndex(
7130
+ (line, position) => position > found.start && position < found.end && namePattern.test(line)
7131
+ );
7132
+ if (index >= 0) {
7133
+ let end = index + 1;
7134
+ while (end < found.end) {
7135
+ const line = lines[end];
7136
+ if (line.trim() === "") {
7137
+ end += 1;
7138
+ continue;
7139
+ }
7140
+ if (new RegExp(`^${escapeRegExp(itemIndent)}-[ \\t]`).test(line)) break;
7141
+ if ((line.match(/^[ \t]*/)?.[0].length ?? 0) < itemIndent.length) break;
7142
+ end += 1;
7143
+ }
7144
+ lines.splice(
7145
+ index,
7146
+ end - index,
7147
+ `${itemIndent}${item[0]}`,
7148
+ ...item.slice(1).map((line) => `${itemIndent} ${line}`)
7149
+ );
7150
+ } else {
7151
+ lines.splice(
7152
+ found.end,
7153
+ 0,
7154
+ `${itemIndent}${item[0]}`,
7155
+ ...item.slice(1).map((line) => `${itemIndent} ${line}`)
7156
+ );
7157
+ }
7158
+ return `${lines.join("\n")}
7159
+ `;
7160
+ }
7161
+ function mergeDshPatch(existing, ctx) {
7162
+ const lines = splitYamlLines(existing);
7163
+ const item = [
7164
+ "- id: zen-mcp",
7165
+ " name: '@deepseek-ai/dsh-mcp-client'",
7166
+ " config:",
7167
+ " serverName: zen_mcp",
7168
+ " transport: stdio",
7169
+ ` command: ${yamlScalar(ctx.command)}`,
7170
+ ` args: ${yamlFlowArray(SERVER_ARGS)}`
7171
+ ];
7172
+ const idPattern = /^([ \t]*)-[ \t]*id:\s*['"]?zen-mcp['"]?\s*$/;
7173
+ const index = lines.findIndex((line) => idPattern.test(line));
7174
+ if (index < 0) {
7175
+ if (lines.length > 0) lines.push("");
7176
+ lines.push("- insert:", ...item.map((line) => ` ${line}`));
7177
+ return `${lines.join("\n")}
7178
+ `;
7179
+ }
7180
+ const indent = lines[index].match(idPattern)?.[1] ?? " ";
7181
+ let start = index;
7182
+ while (start > 0) {
7183
+ const previous = lines[start - 1];
7184
+ const previousIndent = previous.match(/^[ \t]*/)?.[0].length ?? 0;
7185
+ if (previousIndent < indent.length) break;
7186
+ if (previousIndent === indent.length && /^[ \t]*-[ \t]/.test(previous)) {
7187
+ break;
7188
+ }
7189
+ start -= 1;
7190
+ }
7191
+ let end = index + 1;
7192
+ while (end < lines.length) {
7193
+ const line = lines[end];
7194
+ const lineIndent = line.match(/^[ \t]*/)?.[0].length ?? 0;
7195
+ if (line.trim() !== "" && lineIndent < indent.length) break;
7196
+ if (lineIndent === indent.length && /^[ \t]*-[ \t]/.test(line)) break;
7197
+ end += 1;
7198
+ }
7199
+ lines.splice(
7200
+ start,
7201
+ end - start,
7202
+ ...item.map((line) => `${indent}${line}`)
7203
+ );
7204
+ return `${lines.join("\n")}
7205
+ `;
7206
+ }
7207
+ function mergeCrushrc(existing, ctx) {
7208
+ const lines = splitYamlLines(existing);
7209
+ const command = `mcp add zen-mcp --command ${shellQuote(
7210
+ ctx.command
7211
+ )} --args ${SERVER_ARGS.map(shellQuote).join(" ")}`;
7212
+ const index = lines.findIndex(
7213
+ (line) => /^\s*mcp\s+add\s+zen-mcp(?:\s|$)/.test(line)
7214
+ );
7215
+ if (index >= 0) {
7216
+ lines[index] = command;
7217
+ } else {
7218
+ if (lines.length > 0) lines.push("");
7219
+ lines.push(command);
7220
+ }
7221
+ return `${lines.join("\n")}
7222
+ `;
7223
+ }
7224
+ function shellQuote(value) {
7225
+ return /^[A-Za-z0-9_./:-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
7226
+ }
7227
+ function agentSetupPrompt(command = "zen-mcp", ctx = {}) {
7228
+ const resolved = resolveContext({ ...ctx, command });
7229
+ const locations = DEFINITIONS.map((definition) => {
7230
+ const path = placeholderPath(definition.configPaths(resolved)[0], resolved);
7231
+ const detail = definition.id === "vscode" ? " (Insiders uses the same path under `Code - Insiders`)" : definition.id === "cline" ? " (same relative path under Cursor or Windsurf)" : "";
7232
+ const jsonPath = definition.json?.path;
7233
+ const shape = definition.format === "toml" ? " TOML table `[mcp_servers.zen-mcp]`" : definition.format === "yaml" ? " YAML configuration, keep existing entries" : definition.format === "bash" ? " shell rc file, add it with `mcp add`" : definition.id === "vscode" ? ' top-level `servers`, entry needs `"type": "stdio"`' : jsonPath && jsonPath.length > 1 ? ` nested \`${jsonPath.join(".")}\` object` : jsonPath?.[0] === "context_servers" ? " top-level `context_servers`" : " top-level `mcpServers`";
7234
+ return `- ${definition.label}: \`${path}\`${detail};${shape}.`;
7235
+ }).join("\n");
7236
+ return [
7237
+ "# Set up Zen MCP in this agent",
7238
+ "",
7239
+ "Add a local stdio MCP server named `zen-mcp` to the agent you are running in.",
7240
+ "Do the work yourself by running commands and editing the client's configuration.",
7241
+ "Do not ask me to run any of these commands. Only ask me when a step needs a",
7242
+ "browser approval or when no configuration file can be found.",
7243
+ "",
7244
+ "## Server definition",
7245
+ "",
7246
+ "- Name: zen-mcp",
7247
+ "- Transport: stdio, local process (no URL, no OAuth)",
7248
+ `- Command: ${command}`,
7249
+ `- Arguments: ${JSON.stringify(SERVER_ARGS)}`,
7250
+ "- Environment: none",
7251
+ "",
7252
+ "If the command is not on PATH, resolve it with `where <command>` on Windows or",
7253
+ "`command -v <command>` on macOS and Linux. Use the absolute path as the command",
7254
+ "and keep the arguments unchanged.",
7255
+ "",
7256
+ "## 1. Prefer the client's own command",
7257
+ "",
7258
+ "If the client has a first-class way to add a stdio server, use it instead of",
7259
+ "editing files. Example for Claude Code:",
7260
+ "",
7261
+ ` claude mcp add zen-mcp -- "${command}" serve`,
7262
+ "",
7263
+ "Then skip to step 4. An add command that expects a URL is the wrong tool.",
7264
+ "",
7265
+ "## 2. Find the configuration file",
7266
+ "",
7267
+ "Use the first location that exists for this client:",
7268
+ "",
7269
+ locations,
7270
+ "",
7271
+ "For any other client, look for a top-level `mcpServers`, `servers` or",
7272
+ "`context_servers` object in its settings, or follow its official MCP",
7273
+ "documentation. Ask me only if no configuration file can be found.",
7274
+ "",
7275
+ "## 3. Merge the entry",
7276
+ "",
7277
+ "- Preserve every existing server, key, comment and trailing comma.",
7278
+ "- Edit only the `zen-mcp` member. If it already exists, update it instead of",
7279
+ " adding a duplicate.",
7280
+ "- Never replace the whole file with a generated object.",
7281
+ "- For JSONC files (VS Code, Zed), splice the `zen-mcp` member in place so",
7282
+ " comments and formatting survive.",
7283
+ "- Do not reorder or reformat unrelated settings.",
7284
+ "",
7285
+ "Standard JSON clients use a top-level `mcpServers` object:",
7286
+ "",
7287
+ " {",
7288
+ ' "mcpServers": {',
7289
+ ' "zen-mcp": {',
7290
+ ' "command": "<command>",',
7291
+ ' "args": ["serve"]',
7292
+ " }",
7293
+ " }",
7294
+ " }",
7295
+ "",
7296
+ "VS Code uses `servers` and requires the transport type:",
7297
+ "",
7298
+ " {",
7299
+ ' "servers": {',
7300
+ ' "zen-mcp": {',
7301
+ ' "type": "stdio",',
7302
+ ' "command": "<command>",',
7303
+ ' "args": ["serve"]',
7304
+ " }",
7305
+ " }",
7306
+ " }",
7307
+ "",
7308
+ "Zed uses `context_servers` with the same command and args:",
7309
+ "",
7310
+ " {",
7311
+ ' "context_servers": {',
7312
+ ' "zen-mcp": {',
7313
+ ' "command": "<command>",',
7314
+ ' "args": ["serve"]',
7315
+ " }",
7316
+ " }",
7317
+ " }",
7318
+ "",
7319
+ "Codex CLI uses TOML:",
7320
+ "",
7321
+ " [mcp_servers.zen-mcp]",
7322
+ ' command = "<command>"',
7323
+ ' args = ["serve"]',
7324
+ "",
7325
+ "## 4. Validate",
7326
+ "",
7327
+ "- Parse the file in its own format and confirm there is exactly one `zen-mcp`",
7328
+ " entry with the command and arguments above.",
7329
+ "- Confirm no other server was removed, renamed or changed.",
7330
+ "- If the client has a list command such as `claude mcp list`, run it and confirm",
7331
+ " `zen-mcp` appears. Do not start the server manually just to test it.",
7332
+ "",
7333
+ "## 5. Reload",
7334
+ "",
7335
+ "Restart the client or run its reload command so it picks up the new server.",
7336
+ "Tell me which one you did.",
7337
+ "",
7338
+ "## 6. Report",
7339
+ "",
7340
+ "Reply with the client name, the file or command you changed, the validation",
7341
+ "result and the reload instruction. End with:",
7342
+ "",
7343
+ " \u250C\u2500 Zen MCP setup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510",
7344
+ " \u2502 \u2713 Server zen-mcp (stdio) \u2502",
7345
+ " \u2502 \u2713 Config <file or command> \u2502",
7346
+ " \u2502 \u2502",
7347
+ " \u2502 Restart <client> to load the server. \u2502",
7348
+ " \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",
7349
+ "",
7350
+ "## Constraints",
7351
+ "",
7352
+ "- Zen MCP runs locally over stdio. Do not add a remote URL, API key or OAuth",
7353
+ " flow, and do not change the command or arguments.",
7354
+ "- Do not install or patch anything inside Zen; the bridge is injected at",
7355
+ " runtime.",
7356
+ "- Do not launch a browser to test the server. On the first real browser tool",
7357
+ ' call, Zen shows an approval card. Tell me to click "Allow this session".'
7358
+ ].join("\n");
7359
+ }
7360
+ function resolveContext(ctx) {
7361
+ const platform = ctx.platform ?? process.platform;
7362
+ const home = ctx.home ?? homedir2();
7363
+ const env = ctx.env ?? process.env;
7364
+ const command = ctx.command?.trim() || "zen-mcp";
7365
+ const configBase = platform === "win32" ? env.APPDATA ?? join7(home, "AppData", "Roaming") : platform === "darwin" ? join7(home, "Library", "Application Support") : env.XDG_CONFIG_HOME ?? join7(home, ".config");
7366
+ return { command, home, platform, env, configBase };
7367
+ }
7368
+ function placeholderPath(path, ctx) {
7369
+ const windows = ctx.platform === "win32";
7370
+ const roots = [];
7371
+ const codexHome = ctx.env.CODEX_HOME;
7372
+ if (codexHome) {
7373
+ roots.push([codexHome, windows ? "%CODEX_HOME%" : "$CODEX_HOME"]);
7374
+ }
7375
+ if (windows) {
7376
+ roots.push([ctx.configBase, "%APPDATA%"]);
7377
+ } else if (ctx.env.XDG_CONFIG_HOME) {
7378
+ roots.push([ctx.configBase, "$XDG_CONFIG_HOME"]);
7379
+ }
7380
+ roots.push([ctx.home, windows ? "%USERPROFILE%" : "~"]);
7381
+ const normalize = (value) => {
7382
+ const slashed = value.replace(/\\/g, "/");
7383
+ return windows ? slashed.toLowerCase() : slashed;
7384
+ };
7385
+ const target = normalize(path);
7386
+ for (const [root, label] of roots) {
7387
+ const prefix = normalize(root);
7388
+ if (target === prefix) return label;
7389
+ if (target.startsWith(`${prefix}/`)) {
7390
+ const rest = path.slice(root.length);
7391
+ const separator = windows ? "\\" : "/";
7392
+ return label + rest.replace(windows ? /\//g : /\\/g, separator);
7393
+ }
7394
+ }
7395
+ return path;
7396
+ }
7397
+ function tomlValue(value) {
7398
+ if (Array.isArray(value)) {
7399
+ return `[${value.map((entry) => JSON.stringify(entry)).join(", ")}]`;
7400
+ }
7401
+ return JSON.stringify(value);
7402
+ }
7403
+ function escapeRegExp(value) {
7404
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7405
+ }
7406
+
7407
+ // src/onboard/picker.ts
7408
+ import { emitKeypressEvents } from "node:readline";
7409
+
7410
+ // src/onboard/theme.ts
7411
+ function createTheme(output) {
7412
+ const color = Boolean(output.isTTY) && !process.env.NO_COLOR && process.env.TERM !== "dumb";
7413
+ const wrap = (code) => (text) => color ? `\x1B[${code}m${text}\x1B[0m` : text;
7414
+ return {
7415
+ color,
7416
+ unicode: Boolean(output.isTTY),
7417
+ bold: wrap("1"),
7418
+ dim: wrap("2"),
7419
+ cyan: wrap("36"),
7420
+ green: wrap("32"),
7421
+ yellow: wrap("33"),
7422
+ red: wrap("31")
7423
+ };
7424
+ }
7425
+
7426
+ // src/onboard/picker.ts
7427
+ var SelectionCancelled = class extends Error {
7428
+ };
7429
+ var OTHER_ID = "other";
7430
+ function buildOptions(clients) {
7431
+ return [
7432
+ ...clients.map((client) => ({
7433
+ id: client.id,
7434
+ label: client.label,
7435
+ detail: client.detail,
7436
+ detected: client.detected,
7437
+ popular: client.popular,
7438
+ selected: client.detected
7439
+ })),
7440
+ {
7441
+ id: OTHER_ID,
7442
+ label: "Other MCP client",
7443
+ detail: "Print a setup prompt for any agent",
7444
+ detected: false,
7445
+ popular: false,
7446
+ other: true,
7447
+ selected: false
7448
+ }
7449
+ ];
7450
+ }
7451
+ function moveCursor(options, cursor, delta) {
7452
+ const size = options.length;
7453
+ return ((cursor + delta) % size + size) % size;
7454
+ }
7455
+ function scrollWindow(total, cursor, height, start = 0) {
7456
+ const size = Math.max(1, Math.min(height, total));
7457
+ const limit = Math.max(0, total - size);
7458
+ let next = Math.max(0, Math.min(start, limit));
7459
+ if (cursor < next) next = cursor;
7460
+ if (cursor >= next + size) next = cursor - size + 1;
7461
+ next = Math.max(0, Math.min(next, limit));
7462
+ return { start: next, end: Math.min(total, next + size) };
7463
+ }
7464
+ function toggleAll(options, selected) {
7465
+ return options.map(
7466
+ (option) => option.other ? option : { ...option, selected }
7467
+ );
7468
+ }
7469
+ function pickerResult(options) {
7470
+ return {
7471
+ selected: options.filter((option) => !option.other && option.selected).map((option) => option.id),
7472
+ other: options.some((option) => option.other && option.selected)
7473
+ };
7474
+ }
7475
+ function buildBodyEntries(rows) {
7476
+ const entries = [];
7477
+ rows.forEach((row, index) => {
7478
+ if (index === 0) {
7479
+ entries.push({ kind: "header", text: "POPULAR" });
7480
+ } else if (row.other) {
7481
+ entries.push({ kind: "blank" });
7482
+ entries.push({ kind: "header", text: "OTHER" });
7483
+ } else if (rows[index - 1]?.popular && !row.popular) {
7484
+ entries.push({ kind: "blank" });
7485
+ entries.push({ kind: "header", text: "MORE CLIENTS" });
7486
+ }
7487
+ entries.push({ kind: "option", rowIndex: index });
7488
+ });
7489
+ return entries;
7490
+ }
7491
+ async function pickClients(options, streams = {}) {
7492
+ const input = streams.input ?? process.stdin;
7493
+ const output = streams.output ?? process.stdout;
7494
+ if (!input.isTTY || !output.isTTY) {
7495
+ throw new Error("the client picker needs an interactive terminal");
7496
+ }
7497
+ const rows = [...options];
7498
+ let cursor = 0;
7499
+ let painted = 0;
7500
+ const theme = createTheme(output);
7501
+ const columns = output.columns ?? 80;
7502
+ const terminalRows = output.rows ?? 24;
7503
+ const width = Math.max(44, Math.min(columns - 4, 64));
7504
+ const showDetail = columns >= 72;
7505
+ const detailLimit = Math.max(18, columns - 40);
7506
+ const rule = theme.dim("\u2500".repeat(width));
7507
+ const headerHeight = 4;
7508
+ const footerHeight = rows.some((row) => row.detected) ? 3 : 4;
7509
+ const bodyHeight = Math.max(3, terminalRows - headerHeight - footerHeight);
7510
+ const body = buildBodyEntries(rows);
7511
+ let scrollStart = 0;
7512
+ let pageSize = bodyHeight;
7513
+ const paintRow = (row, index, final) => {
7514
+ const marker = final ? " " : index === cursor ? theme.cyan("\u276F") : " ";
7515
+ const box = row.selected ? theme.green("[\u25CF]") : theme.dim("[ ]");
7516
+ const padding = row.label.padEnd(20);
7517
+ const label = index === cursor && !final ? theme.bold(padding) : padding;
7518
+ const tagName = row.detected ? "detected" : row.popular ? "popular" : "";
7519
+ const tag = tagName ? row.detected ? theme.green(tagName.padEnd(10)) : theme.dim(tagName.padEnd(10)) : " ".repeat(10);
7520
+ const detail = !showDetail ? "" : row.detail.length > detailLimit ? `${row.detail.slice(0, detailLimit - 1).trimEnd()}\u2026` : row.detail;
7521
+ return ` ${marker} ${box} ${label} ${tag} ${theme.dim(detail)}`.trimEnd();
7522
+ };
7523
+ const paint = (final = false) => {
7524
+ const lines = [];
7525
+ const count = rows.filter((row) => !row.other && row.selected).length;
7526
+ const otherSelected = rows.some((row) => row.other && row.selected);
7527
+ lines.push(
7528
+ ` ${theme.cyan("\u25C6")} ${theme.bold("ZEN MCP")} ${theme.dim("onboard")}`
7529
+ );
7530
+ lines.push(` ${rule}`);
7531
+ lines.push(` ${theme.dim("Connect Zen to the agents you use.")}`);
7532
+ lines.push("");
7533
+ const scrolling = body.length > bodyHeight;
7534
+ const visible = scrolling ? Math.max(1, bodyHeight - 2) : bodyHeight;
7535
+ pageSize = visible;
7536
+ const cursorLine = body.findIndex(
7537
+ (entry) => entry.kind === "option" && entry.rowIndex === cursor
7538
+ );
7539
+ const window = scrollWindow(body.length, cursorLine, visible, scrollStart);
7540
+ scrollStart = window.start;
7541
+ if (scrolling) {
7542
+ lines.push(
7543
+ window.start > 0 ? ` ${theme.dim(`\u2191 ${window.start} more`)}` : ""
7544
+ );
7545
+ }
7546
+ for (let index = window.start; index < window.end; index += 1) {
7547
+ const entry = body[index];
7548
+ if (entry.kind === "option") {
7549
+ lines.push(paintRow(rows[entry.rowIndex], entry.rowIndex, final));
7550
+ } else if (entry.kind === "header") {
7551
+ lines.push(` ${theme.dim(entry.text)}`);
7552
+ } else {
7553
+ lines.push("");
7554
+ }
7555
+ }
7556
+ if (scrolling) {
7557
+ const below = body.length - window.end;
7558
+ lines.push(below > 0 ? ` ${theme.dim(`\u2193 ${below} more`)}` : "");
7559
+ }
7560
+ lines.push("");
7561
+ if (!rows.some((row) => row.detected)) {
7562
+ lines.push(
7563
+ ` ${theme.yellow("No clients detected.")} ${theme.dim(
7564
+ "Select one below, or choose Other."
7565
+ )}`
7566
+ );
7567
+ }
7568
+ const selection = count > 0 ? theme.green(`${count} selected${otherSelected ? " + other" : ""}`) : otherSelected ? theme.green("other client") : theme.dim("nothing selected");
7569
+ lines.push(` ${selection}`);
7570
+ lines.push(
7571
+ final ? ` ${theme.dim("Selection confirmed.")}` : ` ${theme.dim(
7572
+ "\u2191\u2193 move \xB7 space toggle \xB7 a all \xB7 enter confirm \xB7 esc cancel"
7573
+ )}`
7574
+ );
7575
+ if (painted > 0) {
7576
+ output.write(`\x1B[${painted}A`);
7577
+ output.write("\x1B[0J");
7578
+ }
7579
+ output.write(`${lines.join("\n")}
7580
+ `);
7581
+ painted = lines.length;
7582
+ };
7583
+ emitKeypressEvents(input);
7584
+ input.setRawMode(true);
7585
+ input.resume();
7586
+ output.write("\x1B[?25l");
7587
+ paint();
7588
+ return await new Promise((resolve3, reject) => {
7589
+ const cleanup = () => {
7590
+ input.off("keypress", onKey);
7591
+ input.setRawMode(false);
7592
+ input.pause();
7593
+ output.write("\x1B[?25h");
7594
+ };
7595
+ const finish = (result) => {
7596
+ cleanup();
7597
+ paint(true);
7598
+ resolve3(result);
7599
+ };
7600
+ const onKey = (_str, key) => {
7601
+ if (key.ctrl && key.name === "c") {
7602
+ cleanup();
7603
+ output.write("\n");
7604
+ reject(new SelectionCancelled("cancelled"));
7605
+ return;
7606
+ }
7607
+ if (key.name === "escape") {
7608
+ cleanup();
7609
+ output.write("\n");
7610
+ reject(new SelectionCancelled("cancelled"));
7611
+ return;
7612
+ }
7613
+ switch (key.name) {
7614
+ case "up":
7615
+ cursor = moveCursor(rows, cursor, -1);
7616
+ break;
7617
+ case "down":
7618
+ cursor = moveCursor(rows, cursor, 1);
7619
+ break;
7620
+ case "pageup":
7621
+ cursor = moveCursor(rows, cursor, -pageSize);
7622
+ break;
7623
+ case "pagedown":
7624
+ cursor = moveCursor(rows, cursor, pageSize);
7625
+ break;
7626
+ case "home":
7627
+ cursor = 0;
7628
+ break;
7629
+ case "end":
7630
+ cursor = rows.length - 1;
7631
+ break;
7632
+ case "space":
7633
+ case "spacebar":
7634
+ rows[cursor] = { ...rows[cursor], selected: !rows[cursor].selected };
7635
+ break;
7636
+ case "a":
7637
+ if (!key.ctrl && !key.meta) {
7638
+ const everySelected = rows.filter((row) => !row.other).every((row) => row.selected);
7639
+ rows.splice(0, rows.length, ...toggleAll(rows, !everySelected));
7640
+ }
7641
+ break;
7642
+ case "return":
7643
+ case "enter":
7644
+ finish(pickerResult(rows));
7645
+ return;
7646
+ default:
7647
+ break;
7648
+ }
7649
+ paint();
7650
+ };
7651
+ input.on("keypress", onKey);
7652
+ });
7653
+ }
7654
+
6046
7655
  // src/zen/doctor.ts
6047
- import { existsSync as existsSync8 } from "node:fs";
7656
+ import { existsSync as existsSync9 } from "node:fs";
6048
7657
 
6049
7658
  // src/zen/launcher.ts
6050
7659
  import { randomUUID as randomUUID2 } from "node:crypto";
6051
7660
  import { execFileSync, spawn } from "node:child_process";
6052
7661
  import {
6053
7662
  closeSync as closeSync3,
6054
- existsSync as existsSync7,
7663
+ existsSync as existsSync8,
6055
7664
  mkdirSync as mkdirSync2,
6056
7665
  openSync as openSync3,
6057
7666
  readlinkSync,
6058
7667
  statSync as statSync3
6059
7668
  } from "node:fs";
6060
7669
  import net from "node:net";
6061
- import { homedir as homedir2 } from "node:os";
6062
- import { join as join7, resolve as resolve2 } from "node:path";
7670
+ import { homedir as homedir3 } from "node:os";
7671
+ import { join as join8, resolve as resolve2 } from "node:path";
6063
7672
  var logger = createLogger("launcher");
6064
7673
  var ZenLaunchError = class extends Error {
6065
7674
  name = "ZenLaunchError";
@@ -6067,7 +7676,7 @@ var ZenLaunchError = class extends Error {
6067
7676
  function resolvedProfilePath(config) {
6068
7677
  if (config.profilePath) return resolve2(config.profilePath);
6069
7678
  if (config.useDefaultProfile) return null;
6070
- return join7(config.dataDir ?? dataDirPath(), "agent-profile");
7679
+ return join8(config.dataDir ?? dataDirPath(), "agent-profile");
6071
7680
  }
6072
7681
  function buildLaunchArgs(config, extraArgs = []) {
6073
7682
  const profile = resolvedProfilePath(config);
@@ -6078,7 +7687,7 @@ function buildLaunchArgs(config, extraArgs = []) {
6078
7687
  }
6079
7688
  function findZenExecutable(config) {
6080
7689
  if (config.zenPath) {
6081
- if (!existsSync7(config.zenPath)) {
7690
+ if (!existsSync8(config.zenPath)) {
6082
7691
  throw new ZenLaunchError(
6083
7692
  `Configured Zen executable does not exist: ${config.zenPath}`
6084
7693
  );
@@ -6086,7 +7695,7 @@ function findZenExecutable(config) {
6086
7695
  return config.zenPath;
6087
7696
  }
6088
7697
  for (const candidate of zenCandidates()) {
6089
- if (!candidate || !existsSync7(candidate)) continue;
7698
+ if (!candidate || !existsSync8(candidate)) continue;
6090
7699
  try {
6091
7700
  if (!statSync3(candidate).isFile()) continue;
6092
7701
  } catch {
@@ -6102,20 +7711,20 @@ function zenCandidates() {
6102
7711
  switch (process.platform) {
6103
7712
  case "win32":
6104
7713
  return [
6105
- join7(process.env.ProgramFiles ?? "C:\\Program Files", "Zen Browser", "zen.exe"),
6106
- join7(
7714
+ join8(process.env.ProgramFiles ?? "C:\\Program Files", "Zen Browser", "zen.exe"),
7715
+ join8(
6107
7716
  process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)",
6108
7717
  "Zen Browser",
6109
7718
  "zen.exe"
6110
7719
  ),
6111
- join7(
6112
- process.env.LOCALAPPDATA ?? join7(homedir2(), "AppData", "Local"),
7720
+ join8(
7721
+ process.env.LOCALAPPDATA ?? join8(homedir3(), "AppData", "Local"),
6113
7722
  "Programs",
6114
7723
  "Zen Browser",
6115
7724
  "zen.exe"
6116
7725
  ),
6117
- join7(
6118
- process.env.LOCALAPPDATA ?? join7(homedir2(), "AppData", "Local"),
7726
+ join8(
7727
+ process.env.LOCALAPPDATA ?? join8(homedir3(), "AppData", "Local"),
6119
7728
  "Zen Browser",
6120
7729
  "zen.exe"
6121
7730
  )
@@ -6123,7 +7732,7 @@ function zenCandidates() {
6123
7732
  case "darwin":
6124
7733
  return [
6125
7734
  "/Applications/Zen Browser.app/Contents/MacOS/zen",
6126
- join7(homedir2(), "Applications", "Zen Browser.app", "Contents", "MacOS", "zen")
7735
+ join8(homedir3(), "Applications", "Zen Browser.app", "Contents", "MacOS", "zen")
6127
7736
  ];
6128
7737
  default:
6129
7738
  return [
@@ -6132,8 +7741,8 @@ function zenCandidates() {
6132
7741
  "/opt/zen/zen",
6133
7742
  "/usr/lib/zen/zen",
6134
7743
  "/var/lib/flatpak/exports/bin/app.zen_browser.zen",
6135
- join7(
6136
- homedir2(),
7744
+ join8(
7745
+ homedir3(),
6137
7746
  ".local/share/flatpak/exports/bin/app.zen_browser.zen"
6138
7747
  ),
6139
7748
  "/snap/bin/zen-browser"
@@ -6276,8 +7885,8 @@ function assertProfileAvailable(profilePath) {
6276
7885
  }
6277
7886
  function isProfileLocked(profilePath) {
6278
7887
  if (process.platform === "win32") {
6279
- const lock = join7(profilePath, "parent.lock");
6280
- if (!existsSync7(lock)) return false;
7888
+ const lock = join8(profilePath, "parent.lock");
7889
+ if (!existsSync8(lock)) return false;
6281
7890
  try {
6282
7891
  closeSync3(openSync3(lock, "r+"));
6283
7892
  return false;
@@ -6288,7 +7897,7 @@ function isProfileLocked(profilePath) {
6288
7897
  for (const name of [".parentlock", "lock", "parent.lock"]) {
6289
7898
  let target;
6290
7899
  try {
6291
- target = readlinkSync(join7(profilePath, name));
7900
+ target = readlinkSync(join8(profilePath, name));
6292
7901
  } catch {
6293
7902
  continue;
6294
7903
  }
@@ -6324,9 +7933,9 @@ async function runDoctor(config, options = {}) {
6324
7933
  const path = configFilePath();
6325
7934
  checks.push({
6326
7935
  name: "Config",
6327
- status: existsSync8(path) ? "ok" : "warn",
6328
- detail: existsSync8(path) ? `Loaded ${path}` : "No config file yet; built-in defaults are in use.",
6329
- hint: existsSync8(path) ? void 0 : "Run `zen-mcp setup` to detect Zen and write a config file."
7936
+ status: existsSync9(path) ? "ok" : "warn",
7937
+ detail: existsSync9(path) ? `Loaded ${path}` : "No config file yet; built-in defaults are in use.",
7938
+ hint: existsSync9(path) ? void 0 : "Run `zen-mcp setup` to detect Zen and write a config file."
6330
7939
  });
6331
7940
  try {
6332
7941
  checks.push({
@@ -6343,7 +7952,7 @@ async function runDoctor(config, options = {}) {
6343
7952
  });
6344
7953
  }
6345
7954
  const bridgeBundle = options.bridgeScriptPath ?? resolveBridgeScriptPath();
6346
- const bundleExists = existsSync8(bridgeBundle);
7955
+ const bundleExists = existsSync9(bridgeBundle);
6347
7956
  checks.push({
6348
7957
  name: "Bridge bundle",
6349
7958
  status: bundleExists ? "ok" : "fail",
@@ -6941,13 +8550,27 @@ var MarionetteClient = class {
6941
8550
  function wrapScript(body) {
6942
8551
  return [
6943
8552
  "const __zenMcpDone = arguments[arguments.length - 1];",
8553
+ // Gecko's Error.stack contains frames only, with no name or message line,
8554
+ // so report all three. Otherwise a sandbox failure arrives as line numbers
8555
+ // with no explanation.
8556
+ "const __zenMcpDescribe = (error) => {",
8557
+ " try {",
8558
+ " if (!error || typeof error !== 'object') return String(error);",
8559
+ " const name = error.name ? String(error.name) : 'Error';",
8560
+ " const message = error.message ? String(error.message) : String(error);",
8561
+ " const stack = error.stack ? String(error.stack) : '';",
8562
+ " return stack ? name + ': ' + message + '\\n' + stack : name + ': ' + message;",
8563
+ " } catch (describeError) {",
8564
+ " return 'Script threw an error that could not be described';",
8565
+ " }",
8566
+ "};",
6944
8567
  "(async () => {",
6945
8568
  body,
6946
8569
  "})().then(",
6947
8570
  " (value) => __zenMcpDone({ __zenMcpOk: true, value }),",
6948
8571
  " (error) => __zenMcpDone({",
6949
8572
  " __zenMcpOk: false,",
6950
- " error: String((error && (error.stack || error.message)) || error),",
8573
+ " error: __zenMcpDescribe(error),",
6951
8574
  " })",
6952
8575
  ");"
6953
8576
  ].join("\n");
@@ -7169,7 +8792,27 @@ var ZenRuntime = class {
7169
8792
  let nonce = null;
7170
8793
  try {
7171
8794
  nonce = await this.marionette.executeChrome(
7172
- 'return Services.env.get("ZEN_MCP_LAUNCH_NONCE") ?? null;',
8795
+ [
8796
+ // Marionette's chrome sandbox exposes these globals but cannot load
8797
+ // resource:// modules, so use them directly and fall back to the
8798
+ // component service when a build hides `Services`.
8799
+ 'const env = typeof Services !== "undefined" && Services.env',
8800
+ " ? Services.env",
8801
+ ' : typeof Cc !== "undefined" && typeof Ci !== "undefined"',
8802
+ ' ? Cc["@mozilla.org/process/environment;1"].getService(',
8803
+ " Ci.nsIEnvironment",
8804
+ " )",
8805
+ " : null;",
8806
+ "if (!env) {",
8807
+ " throw new Error(",
8808
+ ' "Chrome scope is unavailable, so the launch nonce could not be " +',
8809
+ ' "read. Zen 138 or newer is required, and the launcher must not " +',
8810
+ ' "drop MOZ_REMOTE_ALLOW_SYSTEM_ACCESS."',
8811
+ " );",
8812
+ "}",
8813
+ // nsIEnvironment returns an empty string for unset variables.
8814
+ 'return env.get("ZEN_MCP_LAUNCH_NONCE") || null;'
8815
+ ].join("\n"),
7173
8816
  { timeoutMs: 1e4 }
7174
8817
  );
7175
8818
  } catch (error) {
@@ -7233,7 +8876,7 @@ var ZenRuntime = class {
7233
8876
  if (outcome === "denied") {
7234
8877
  await this.#closeOwnedBrowser("access was declined in the browser");
7235
8878
  throw new ZenAccessError(
7236
- "Browser access was declined in Zen. The browser Zen MCP started was closed. Call zen_launch to ask again."
8879
+ "Browser access was declined in Zen. The browser Zen MCP started was closed. Restart the MCP server to ask again."
7237
8880
  );
7238
8881
  }
7239
8882
  throw new ZenAccessError(
@@ -7703,8 +9346,15 @@ var ZenRuntime = class {
7703
9346
  }
7704
9347
  };
7705
9348
  }
9349
+ let focused = false;
9350
+ let focusLimitation;
7706
9351
  if (focus) {
7707
- await this.hub.selectTab({ tabId: target.tab.id, focusWindow: true }, target.windowId).catch(() => void 0);
9352
+ const brought = await this.#bringTabForward(
9353
+ target.tab.id,
9354
+ target.windowId
9355
+ );
9356
+ focused = brought.focused;
9357
+ focusLimitation = brought.limitation;
7708
9358
  }
7709
9359
  this.#rememberEvidence(target.tab.id, target.windowId);
7710
9360
  let op;
@@ -7735,10 +9385,13 @@ var ZenRuntime = class {
7735
9385
  url: op.url || target.tab.url,
7736
9386
  title: op.title || target.tab.title || options.sourceTitle?.trim() || "",
7737
9387
  tabReused: target.reused,
7738
- focused: focus,
9388
+ focused,
7739
9389
  sourceUrl,
7740
9390
  claim
7741
9391
  };
9392
+ if (focusLimitation) {
9393
+ result.limitation = joinLimitation(result.limitation, focusLimitation);
9394
+ }
7742
9395
  const delivered = await this.hub.notify({
7743
9396
  title: evidenceCardTitle(result),
7744
9397
  detail: evidenceCardDetail(
@@ -7779,7 +9432,7 @@ var ZenRuntime = class {
7779
9432
  failed: total,
7780
9433
  openedTabs: 0,
7781
9434
  reusedTabs: 0,
7782
- focused: focus,
9435
+ focused: false,
7783
9436
  results: [],
7784
9437
  error
7785
9438
  });
@@ -7916,11 +9569,15 @@ var ZenRuntime = class {
7916
9569
  }
7917
9570
  const firstTargetIndex = targets.findIndex((target) => target !== null);
7918
9571
  const firstTarget = firstTargetIndex >= 0 ? targets[firstTargetIndex] : null;
9572
+ let firstFocused = false;
9573
+ let firstFocusLimitation;
7919
9574
  if (focus && firstTarget) {
7920
- await this.hub.selectTab(
7921
- { tabId: firstTarget.tab.id, focusWindow: true },
9575
+ const brought = await this.#bringTabForward(
9576
+ firstTarget.tab.id,
7922
9577
  firstTarget.windowId
7923
- ).catch(() => void 0);
9578
+ );
9579
+ firstFocused = brought.focused;
9580
+ firstFocusLimitation = brought.limitation;
7924
9581
  }
7925
9582
  const openedTabIds = /* @__PURE__ */ new Set();
7926
9583
  const reusedTabIds = /* @__PURE__ */ new Set();
@@ -7930,7 +9587,7 @@ var ZenRuntime = class {
7930
9587
  if (target.reused) reusedTabIds.add(target.tab.id);
7931
9588
  else openedTabIds.add(target.tab.id);
7932
9589
  }
7933
- const highlightMs = clampInt(options.highlightMs, 1e3, 12e4, 25e3);
9590
+ const highlightMs = clampInt(options.highlightMs, 1e3, 12e4, 2e4);
7934
9591
  const results = new Array(total);
7935
9592
  let next = 0;
7936
9593
  let completed = 0;
@@ -7981,16 +9638,23 @@ var ZenRuntime = class {
7981
9638
  error: evidenceFailureFromError(error)
7982
9639
  };
7983
9640
  }
7984
- results[index] = {
9641
+ const citationResult = {
7985
9642
  ...op,
7986
9643
  tabId: op.tabId ?? target.tab.id,
7987
9644
  url: op.url || target.tab.url,
7988
9645
  title: op.title || target.tab.title || citation.sourceTitle?.trim() || "",
7989
9646
  tabReused: target.reused,
7990
- focused: focus && firstTarget?.tab.id === target.tab.id,
9647
+ focused: firstFocused && firstTarget?.tab.id === target.tab.id,
7991
9648
  sourceUrl: citation.url,
7992
9649
  claim
7993
9650
  };
9651
+ if (firstFocusLimitation && firstTarget?.tab.id === target.tab.id) {
9652
+ citationResult.limitation = joinLimitation(
9653
+ citationResult.limitation,
9654
+ firstFocusLimitation
9655
+ );
9656
+ }
9657
+ results[index] = citationResult;
7994
9658
  } finally {
7995
9659
  completed += 1;
7996
9660
  options.onProgress?.(completed, total);
@@ -8007,7 +9671,7 @@ var ZenRuntime = class {
8007
9671
  const verified = results.filter((result) => result.verified === true).length;
8008
9672
  const unverified = matched - verified;
8009
9673
  const failed = total - matched;
8010
- let limitation;
9674
+ let limitation = firstFocusLimitation;
8011
9675
  const failures = results.filter((result) => !result.ok).slice(0, MAX_BATCH_CARD_FAILURES).map(
8012
9676
  (result) => `${truncateText(
8013
9677
  collapseText(result.claim || result.sourceUrl),
@@ -8029,7 +9693,10 @@ var ZenRuntime = class {
8029
9693
  windowId: cardWindow
8030
9694
  }).then((response) => response.delivered).catch(() => false);
8031
9695
  if (!delivered) {
8032
- limitation = "The in-browser summary card could not be shown.";
9696
+ limitation = joinLimitation(
9697
+ limitation,
9698
+ "The in-browser summary card could not be shown."
9699
+ );
8033
9700
  }
8034
9701
  return {
8035
9702
  ok: failed === 0 && unverified === 0,
@@ -8039,7 +9706,7 @@ var ZenRuntime = class {
8039
9706
  failed,
8040
9707
  openedTabs: openedTabIds.size,
8041
9708
  reusedTabs: reusedTabIds.size,
8042
- focused: focus,
9709
+ focused: firstFocused,
8043
9710
  results,
8044
9711
  ...limitation ? { limitation } : {}
8045
9712
  };
@@ -8090,6 +9757,38 @@ var ZenRuntime = class {
8090
9757
  ...failure ? { error: failure } : {}
8091
9758
  };
8092
9759
  }
9760
+ /**
9761
+ * Selects a tab and reports only what was observed: `focused` is true when
9762
+ * the bridge reports the tab as active. A failed selection becomes a
9763
+ * limitation instead of a thrown error so the evidence check itself can
9764
+ * still finish in the background.
9765
+ */
9766
+ async #bringTabForward(tabId, windowId) {
9767
+ try {
9768
+ const selected = await this.hub.selectTab(
9769
+ { tabId, focusWindow: true },
9770
+ windowId
9771
+ );
9772
+ if (selected.tab.active !== true) {
9773
+ return {
9774
+ focused: false,
9775
+ limitation: "Zen did not activate the source tab, so it may still be in the background."
9776
+ };
9777
+ }
9778
+ if (selected.windowFocused === false) {
9779
+ return {
9780
+ focused: true,
9781
+ limitation: "The source tab is active, but the Zen window could not be raised."
9782
+ };
9783
+ }
9784
+ return { focused: true };
9785
+ } catch (error) {
9786
+ return {
9787
+ focused: false,
9788
+ limitation: `Could not bring the source tab forward: ${errorText(error)}`
9789
+ };
9790
+ }
9791
+ }
8093
9792
  #urlPermitted(url) {
8094
9793
  return isUrlAllowed(url, this.config.allowedDomains);
8095
9794
  }
@@ -8593,6 +10292,19 @@ program.command("setup").description("Detect Zen, write a config file, and print
8593
10292
  "Marionette port. Zen currently always uses 2828.",
8594
10293
  (value) => parseInteger(value, "marionette port")
8595
10294
  ).option("--skip-doctor", "Write the config without running diagnostics.").action((options) => setup(options));
10295
+ program.command("onboard").description(
10296
+ "Pick MCP clients and add Zen MCP to their configuration."
10297
+ ).option(
10298
+ "--clients <ids>",
10299
+ "Comma-separated client ids or 'all'. Skips the interactive picker."
10300
+ ).option(
10301
+ "--command <command>",
10302
+ "Command clients should run. Defaults to `zen-mcp`."
10303
+ ).option("--other", "Also print a setup prompt for any other client.").addHelpText(
10304
+ "after",
10305
+ `
10306
+ Client ids: ${clientIds().join(", ")}, other.`
10307
+ ).action((options) => onboard(options));
8596
10308
  var configCommand = program.command("config").description("Show or change the saved configuration.");
8597
10309
  configCommand.command("show").description("Print the config file path and resolved values.").action(() => configShow());
8598
10310
  configCommand.command("set").description(`Set one key: ${CONFIG_KEYS.join(", ")}.`).argument("<key>", "Config key.").argument("<value>", "New value. Use an empty string to clear a path.").action((key, value) => configSet(key, value));
@@ -8723,7 +10435,7 @@ async function setup(options) {
8723
10435
  if (options.marionettePort !== void 0) {
8724
10436
  updates.marionettePort = options.marionettePort;
8725
10437
  }
8726
- const firstTime = !existsSync9(configFilePath());
10438
+ const firstTime = !existsSync10(configFilePath());
8727
10439
  if (!updates.zenPath && !loadConfig().zenPath) {
8728
10440
  try {
8729
10441
  updates.zenPath = findZenExecutable(loadConfig());
@@ -8759,6 +10471,121 @@ async function setup(options) {
8759
10471
  console.log(
8760
10472
  '\nIf Zen MCP is not on your PATH, point command at the absolute path of dist/cli.js and keep args as ["serve"].'
8761
10473
  );
10474
+ console.log(
10475
+ "Run `zen-mcp onboard` to add Zen MCP to a supported MCP client."
10476
+ );
10477
+ }
10478
+ async function onboard(options) {
10479
+ const context = { command: options.command?.trim() || "zen-mcp" };
10480
+ const theme = createTheme(process.stdout);
10481
+ const rule = theme.unicode ? "\u2500".repeat(56) : "-".repeat(56);
10482
+ const entries = catalog(context);
10483
+ const known = new Set(entries.map((entry) => entry.id));
10484
+ let selected;
10485
+ let includeOther = Boolean(options.other);
10486
+ if (options.clients?.trim()) {
10487
+ const tokens = options.clients.split(",").map((token) => token.trim()).filter(Boolean);
10488
+ const unknown = tokens.filter(
10489
+ (token) => token !== "other" && token !== "all" && !known.has(token)
10490
+ );
10491
+ if (unknown.length > 0) {
10492
+ console.error(`Unknown client(s): ${unknown.join(", ")}.`);
10493
+ console.error(`Valid clients: ${[...known].join(", ")}, other, all.`);
10494
+ process.exitCode = 1;
10495
+ return;
10496
+ }
10497
+ selected = tokens.includes("all") ? entries.map((entry) => entry.id) : tokens.filter((token) => token !== "other");
10498
+ includeOther = includeOther || tokens.includes("other");
10499
+ } else {
10500
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
10501
+ console.error("The client picker needs an interactive terminal.");
10502
+ console.error("Use --clients with a comma-separated list instead:");
10503
+ console.error(" zen-mcp onboard --clients claude-code,cursor,other");
10504
+ console.error(`Valid clients: ${[...known].join(", ")}, other.`);
10505
+ process.exitCode = 1;
10506
+ return;
10507
+ }
10508
+ let result;
10509
+ try {
10510
+ result = await pickClients(buildOptions(entries));
10511
+ } catch (error) {
10512
+ if (error instanceof SelectionCancelled) {
10513
+ console.log("Cancelled. No client configuration was changed.");
10514
+ process.exitCode = 130;
10515
+ return;
10516
+ }
10517
+ throw error;
10518
+ }
10519
+ selected = result.selected;
10520
+ includeOther = includeOther || result.other;
10521
+ }
10522
+ if (selected.length === 0 && !includeOther) {
10523
+ console.log(
10524
+ theme.dim(" Nothing selected. No client configuration was changed.")
10525
+ );
10526
+ return;
10527
+ }
10528
+ if (!existsSync10(configFilePath())) {
10529
+ const updates = {};
10530
+ try {
10531
+ updates.zenPath = findZenExecutable(loadConfig());
10532
+ } catch {
10533
+ }
10534
+ const path = saveConfig(updates);
10535
+ const mark = theme.unicode ? theme.green("\u2713") : "[ ok ]";
10536
+ console.log(` ${mark} Saved config ${theme.dim(path)}`);
10537
+ console.log("");
10538
+ }
10539
+ let failed = 0;
10540
+ if (selected.length > 0) {
10541
+ let connected = 0;
10542
+ console.log(` ${theme.bold("Client configuration")}`);
10543
+ console.log(` ${theme.dim(rule)}`);
10544
+ for (const id of selected) {
10545
+ const result = applyClient(id, context);
10546
+ if (result.status === "ok") {
10547
+ connected += 1;
10548
+ const mark = theme.unicode ? theme.green("\u2713") : "[ ok ]";
10549
+ console.log(
10550
+ ` ${mark} ${result.label.padEnd(18)} ${theme.dim(result.message)}`
10551
+ );
10552
+ } else {
10553
+ failed += 1;
10554
+ const mark = theme.unicode ? theme.red("\u2717") : "[FAIL]";
10555
+ console.log(
10556
+ ` ${mark} ${result.label.padEnd(18)} ${theme.red(result.message)}`
10557
+ );
10558
+ }
10559
+ }
10560
+ console.log("");
10561
+ console.log(
10562
+ ` ${failed === 0 ? theme.green(
10563
+ `${connected} client${connected === 1 ? "" : "s"} connected`
10564
+ ) : theme.yellow(`${connected} connected, ${failed} failed`)}`
10565
+ );
10566
+ }
10567
+ if (includeOther) {
10568
+ console.log("");
10569
+ console.log(` ${theme.bold("Other client")}`);
10570
+ console.log(` ${theme.dim(rule)}`);
10571
+ console.log(` ${theme.dim("Paste this prompt into your agent.")}`);
10572
+ console.log("");
10573
+ console.log(agentSetupPrompt(context.command));
10574
+ }
10575
+ console.log("");
10576
+ console.log(
10577
+ theme.dim(
10578
+ 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."
10579
+ )
10580
+ );
10581
+ if (!options.command) {
10582
+ console.log(
10583
+ theme.dim(
10584
+ " If `zen-mcp` is not on your PATH, rerun with --command <absolute path to dist/cli.js>."
10585
+ )
10586
+ );
10587
+ }
10588
+ if (failed > 0) process.exitCode = 1;
8762
10589
  }
8763
10590
  function configShow() {
8764
10591
  console.log(configFilePath());