turno-cli 0.1.0 → 0.2.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.
Files changed (105) hide show
  1. package/CHANGELOG.md +293 -0
  2. package/README.md +143 -75
  3. package/dist/accounts/audit.js +137 -7
  4. package/dist/accounts/builtin.js +68 -21
  5. package/dist/accounts/delegate.js +176 -35
  6. package/dist/accounts/policy.js +77 -0
  7. package/dist/accounts/registry.js +37 -21
  8. package/dist/agents/adapter.js +7 -0
  9. package/dist/agents/claude.js +195 -0
  10. package/dist/agents/codex.js +98 -0
  11. package/dist/agents/copilot.js +39 -0
  12. package/dist/agents/cursor.js +41 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +7 -4
  15. package/dist/cli/args.js +19 -4
  16. package/dist/cli/commands/accounts.js +96 -51
  17. package/dist/cli/commands/auto.js +82 -32
  18. package/dist/cli/commands/browser.js +216 -135
  19. package/dist/cli/commands/complete.js +2 -1
  20. package/dist/cli/commands/completion.js +4 -2
  21. package/dist/cli/commands/config.js +103 -18
  22. package/dist/cli/commands/demo.js +292 -0
  23. package/dist/cli/commands/doctor.js +387 -119
  24. package/dist/cli/commands/handoff.js +33 -22
  25. package/dist/cli/commands/identity.js +101 -50
  26. package/dist/cli/commands/init.js +616 -0
  27. package/dist/cli/commands/limit.js +25 -13
  28. package/dist/cli/commands/mcp-oauth.js +194 -0
  29. package/dist/cli/commands/mcp-observe.js +434 -0
  30. package/dist/cli/commands/mcp.js +653 -185
  31. package/dist/cli/commands/mcpd.js +323 -75
  32. package/dist/cli/commands/migrate.js +6 -4
  33. package/dist/cli/commands/open.js +92 -27
  34. package/dist/cli/commands/profile.js +205 -69
  35. package/dist/cli/commands/resolve.js +6 -2
  36. package/dist/cli/commands/run.js +15 -5
  37. package/dist/cli/commands/secret.js +61 -42
  38. package/dist/cli/commands/session.js +2 -2
  39. package/dist/cli/commands/sessions.js +42 -12
  40. package/dist/cli/commands/setup.js +136 -158
  41. package/dist/cli/commands/status.js +172 -41
  42. package/dist/cli/commands/statusline.js +305 -113
  43. package/dist/cli/commands/ui.js +64 -66
  44. package/dist/cli/commands/undo.js +161 -18
  45. package/dist/cli/commands/uninstall.js +462 -0
  46. package/dist/cli/commands/upgrade.js +75 -19
  47. package/dist/cli/commands/usage.js +117 -44
  48. package/dist/cli/commands/version.js +7 -5
  49. package/dist/cli/commands/which.js +7 -24
  50. package/dist/cli/compile-cache.js +32 -0
  51. package/dist/cli/group.js +10 -10
  52. package/dist/cli/help.js +57 -0
  53. package/dist/cli/highlight.js +236 -0
  54. package/dist/cli/io.js +170 -1
  55. package/dist/cli/launch.js +21 -37
  56. package/dist/cli/launchers.js +145 -94
  57. package/dist/cli/main.js +163 -27
  58. package/dist/cli/picker.js +447 -0
  59. package/dist/cli/registry.js +42 -5
  60. package/dist/cli/security.js +539 -0
  61. package/dist/cli/style.js +281 -0
  62. package/dist/core/config.js +145 -23
  63. package/dist/core/exhausted.js +6 -8
  64. package/dist/core/fsutil.js +47 -0
  65. package/dist/core/journal.js +281 -11
  66. package/dist/core/manifest.js +126 -6
  67. package/dist/core/paths.js +114 -7
  68. package/dist/core/profiles.js +139 -9
  69. package/dist/core/resolve.js +129 -23
  70. package/dist/core/secrets.js +215 -20
  71. package/dist/core/sessions.js +13 -20
  72. package/dist/core/update.js +18 -8
  73. package/dist/core/version.js +6 -0
  74. package/dist/demo/server.js +34 -0
  75. package/dist/mcpd/cache.js +18 -4
  76. package/dist/mcpd/calllog.js +253 -0
  77. package/dist/mcpd/client-names.js +51 -0
  78. package/dist/mcpd/connectors.js +148 -17
  79. package/dist/mcpd/daemon.js +452 -116
  80. package/dist/mcpd/folder-sets.js +39 -0
  81. package/dist/mcpd/gateway.js +441 -47
  82. package/dist/mcpd/health.js +269 -0
  83. package/dist/mcpd/importer.js +356 -36
  84. package/dist/mcpd/instances.js +425 -65
  85. package/dist/mcpd/jsonrpc.js +8 -0
  86. package/dist/mcpd/launchd.js +65 -48
  87. package/dist/mcpd/modern.js +648 -0
  88. package/dist/mcpd/oauth.js +791 -0
  89. package/dist/mcpd/peerpid.js +122 -6
  90. package/dist/mcpd/pressure.js +85 -0
  91. package/dist/mcpd/rss.js +151 -0
  92. package/dist/mcpd/service.js +167 -0
  93. package/dist/mcpd/state.js +183 -0
  94. package/dist/mcpd/sync.js +55 -80
  95. package/dist/mcpd/systemd.js +80 -0
  96. package/dist/mcpd/tokens.js +89 -0
  97. package/dist/mcpd/upstream.js +154 -44
  98. package/dist/statusline/cost.js +154 -44
  99. package/dist/statusline/input.js +66 -0
  100. package/dist/statusline/render.js +9 -3
  101. package/dist/ui/fonts.js +8 -3
  102. package/dist/ui/settings.js +27 -15
  103. package/npm-shrinkwrap.json +1093 -0
  104. package/package.json +9 -9
  105. package/dist/cli/commands/available.js +0 -18
@@ -1,6 +1,9 @@
1
1
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { stringify } from "smol-toml";
3
+ import { parse, stringify } from "smol-toml";
4
+ import { SCAN_ORDER, adapter, agentProfileDir } from "../agents/index.js";
5
+ import { tildify } from "../core/paths.js";
6
+ import { isObject, readJsonFile } from "../core/fsutil.js";
4
7
  /** Scope defaults for servers we know; unknown servers default to "project" (safe for folder-bound tools). */
5
8
  const KNOWN = [
6
9
  { match: /chrome-devtools-mcp/, scope: "session", note: "drives its own browser per session" },
@@ -10,7 +13,108 @@ const KNOWN = [
10
13
  { match: /codebase-memory-mcp/, scope: "shared", note: "one index for every repository" },
11
14
  { match: /@calcom\/cal-mcp/, scope: "shared", note: "stateless API client" },
12
15
  ];
13
- const SECRET_KEY = /(key|token|secret|password|passwd|pat|auth|credential)/i;
16
+ /** Words in a key name that mark its value as a secret (PWD, PATH and the like do not match). */
17
+ const SECRET_WORDS = new Set([
18
+ "key",
19
+ "apikey",
20
+ "token",
21
+ "secret",
22
+ "password",
23
+ "passwd",
24
+ "pass",
25
+ "pat",
26
+ "auth",
27
+ "authorization",
28
+ "credential",
29
+ "credentials",
30
+ "bearer",
31
+ ]);
32
+ /** Values that are tokens whatever their key is called. */
33
+ const TOKEN_VALUE = /^(gh[pousr]_|github_pat_|sk-|sk_live_|rk_live_|xox[abprs]-|glpat-|AKIA[0-9A-Z]{12})/;
34
+ /** Values that are clearly not secrets even under a secret-looking key (paths, plain URLs, flags). */
35
+ const PLAIN_VALUE = /^(?:[/~.]|https?:\/\/[^@?]*$|true$|false$|\d+$)/i;
36
+ /** `${VAR}`, `${VAR:-default}` and Cursor's `${env:VAR}`, as the whole value. */
37
+ const WHOLE_VAR = /^\$\{(?:env:)?([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}$/;
38
+ const ANY_VAR = /\$\{[^}]*\}/;
39
+ /** Cursor's own placeholders: not environment variables. */
40
+ const CURSOR_VARS = new Set(["userHome", "workspaceFolder", "workspaceFolderBasename", "pathSeparator"]);
41
+ /** Split a key name into lowercase words: `GITHUB_TOKEN`, `apiKey`, `X-Api-Key`. */
42
+ function words(key) {
43
+ return key
44
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
45
+ .toLowerCase()
46
+ .split(/[^a-z0-9]+/)
47
+ .filter(Boolean);
48
+ }
49
+ function isSecretKey(key) {
50
+ return words(key).some((w) => SECRET_WORDS.has(w));
51
+ }
52
+ /** Whether a value under `key` holds a secret. */
53
+ export function isSecretValue(key, value) {
54
+ if (!value || value.startsWith("keychain:") || value.startsWith("env:") || ANY_VAR.test(value))
55
+ return false;
56
+ if (TOKEN_VALUE.test(value) || /^bearer\s+\S/i.test(value))
57
+ return true;
58
+ return isSecretKey(key) && !PLAIN_VALUE.test(value);
59
+ }
60
+ /** Show the kind of a secret and its last characters, never enough to use it: `ghp_****1234`. */
61
+ export function maskSecret(value) {
62
+ const bearer = /^(bearer\s+)(.*)$/i.exec(value);
63
+ if (bearer)
64
+ return `${bearer[1]}${maskSecret(bearer[2])}`;
65
+ const prefix = /^([A-Za-z]{2,10}[_-])/.exec(value)?.[1] ?? "";
66
+ const keepPrefix = prefix && value.length - prefix.length >= 8 ? prefix : "";
67
+ const tail = value.length >= 16 ? value.slice(-4) : "";
68
+ return `${keepPrefix}****${tail}`;
69
+ }
70
+ /** The `env:` reference for a value that is exactly `${VAR}` or `${VAR:-default}`, if it is one. */
71
+ function envRef(value) {
72
+ const m = WHOLE_VAR.exec(value);
73
+ if (!m || CURSOR_VARS.has(m[1]))
74
+ return undefined;
75
+ return m[2] !== undefined ? `env:${m[1]}:-${m[2]}` : `env:${m[1]}`;
76
+ }
77
+ /** Secret values in a stdio server's args: `--api-key=x`, `--token x` and bare tokens. */
78
+ export function argSecrets(args) {
79
+ const out = [];
80
+ for (let i = 0; i < args.length; i++) {
81
+ const a = args[i];
82
+ const eq = /^--?([A-Za-z][\w-]*)=(.*)$/.exec(a);
83
+ if (eq) {
84
+ if (isSecretValue(eq[1], eq[2]))
85
+ out.push(eq[2]);
86
+ continue;
87
+ }
88
+ const flag = /^--?([A-Za-z][\w-]*)$/.exec(a);
89
+ const next = args[i + 1];
90
+ if (flag && next !== undefined && !next.startsWith("-") && isSecretKey(flag[1])) {
91
+ if (isSecretValue(flag[1], next))
92
+ out.push(next);
93
+ i++;
94
+ continue;
95
+ }
96
+ if (TOKEN_VALUE.test(a))
97
+ out.push(a);
98
+ }
99
+ return out;
100
+ }
101
+ /** Secret values in a URL: query parameters such as `?api_key=...` and a password in the user part. */
102
+ export function urlSecrets(url) {
103
+ let u;
104
+ try {
105
+ u = new URL(url);
106
+ }
107
+ catch {
108
+ return [];
109
+ }
110
+ const out = [];
111
+ if (u.password)
112
+ out.push(decodeURIComponent(u.password));
113
+ for (const [k, v] of u.searchParams)
114
+ if (isSecretValue(k, v))
115
+ out.push(v);
116
+ return out;
117
+ }
14
118
  function packageName(spec) {
15
119
  const at = spec.lastIndexOf("@");
16
120
  return at > 0 ? spec.slice(0, at) : spec;
@@ -27,45 +131,108 @@ export function guessScope(text) {
27
131
  for (const k of KNOWN)
28
132
  if (k.match.test(text))
29
133
  return { scope: k.scope, note: k.note };
30
- return { scope: "project", note: "unknown server: started per project folder (change to shared if it does not use its folder)" };
134
+ return { scope: "project", note: 'unknown server, one process per project folder; set scope = "shared" if it ignores its folder' };
135
+ }
136
+ function serviceKey(key) {
137
+ return key.toLowerCase().replace(/[^a-z0-9]+/g, "-");
138
+ }
139
+ function mapStrings(v, f) {
140
+ if (typeof v === "string")
141
+ return f(v);
142
+ if (Array.isArray(v))
143
+ return v.map((x) => mapStrings(x, f));
144
+ if (v && typeof v === "object")
145
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, mapStrings(x, f)]));
146
+ return v;
31
147
  }
148
+ const HEADER = [
149
+ "# turno MCP manifest. Generated by `turno mcp import`; edit freely.",
150
+ "# scope: shared (one process for every session) | project (one per project folder)",
151
+ "# | session (one per Claude session). Servers start on first use and stop when idle.",
152
+ "# Docs: docs/mcp.md in the turno repository.",
153
+ "",
154
+ ].join("\n");
32
155
  export async function importServers(servers, opts = {}) {
33
156
  const out = {};
34
157
  const notes = [];
35
- const secretsMoved = [];
158
+ const secrets = [];
36
159
  const literalSecrets = [];
37
- const secretRef = async (server, key, value) => {
38
- if (value.startsWith("keychain:") || value.startsWith("env:") || /^\$\{.+\}$/.test(value))
160
+ const fixedSecrets = [];
161
+ /** Literal secret values left in the manifest, masked in the preview. */
162
+ const hidden = new Set();
163
+ const secretRef = (server, key, value) => {
164
+ // Never move a value that still holds a variable: the Keychain would get the placeholder.
165
+ if (value.includes("${"))
39
166
  return value;
40
- if (!opts.moveSecrets || !opts.store) {
167
+ if (!opts.moveSecrets) {
41
168
  literalSecrets.push(`${server}.${key}`);
169
+ hidden.add(value);
42
170
  return value;
43
171
  }
44
- const service = `turno/${server}/${key.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
45
- await opts.store(service, value);
46
- secretsMoved.push(`${server}.${key} -> keychain:${service}`);
172
+ const service = `turno/${server}/${serviceKey(key)}`;
173
+ secrets.push({ where: `${server}.${key}`, service, value });
47
174
  return `keychain:${service}`;
48
175
  };
176
+ const fixed = (server, where, values) => {
177
+ if (!values.length)
178
+ return;
179
+ for (const v of values)
180
+ hidden.add(v);
181
+ fixedSecrets.push(`${server}.${where}`);
182
+ notes.push(where === "args"
183
+ ? `${server}: its args hold a secret, kept in mcp.toml as written (args cannot come from the Keychain; if the server reads it from an environment variable, move it to env)`
184
+ : `${server}: its URL holds a secret, kept in mcp.toml as written (a URL cannot come from the Keychain; use a header if the server accepts one)`);
185
+ };
49
186
  for (const [name, entry] of Object.entries(servers)) {
50
187
  const type = entry.type ?? (entry.command ? "stdio" : "http");
51
- if (type === "stdio") {
188
+ if (type === "stdio" || type === "local") {
52
189
  const command = String(entry.command ?? "");
53
190
  const args = (entry.args ?? []).map(String);
54
191
  const env = {};
55
- for (const [k, v] of Object.entries(entry.env ?? {})) {
56
- env[k] = SECRET_KEY.test(k) ? await secretRef(name, k, String(v)) : String(v);
192
+ const fromEnv = [];
193
+ for (const [k, raw] of Object.entries(entry.env ?? {})) {
194
+ const v = String(raw);
195
+ if (v.startsWith("keychain:") || v.startsWith("env:")) {
196
+ env[k] = v;
197
+ continue;
198
+ }
199
+ const ref = envRef(v);
200
+ if (ref) {
201
+ env[k] = ref;
202
+ fromEnv.push(ref.slice(4).replace(/:-.*$/, ""));
203
+ continue;
204
+ }
205
+ if (ANY_VAR.test(v)) {
206
+ env[k] = v;
207
+ notes.push(`${name}: env ${k} mixes text and a variable (${v.match(ANY_VAR)[0]}); mcpd expands it from its own environment when it starts the server. If it is a secret, store the full value with turno secret set turno/${name}/${serviceKey(k)} and set ${k} = "keychain:turno/${name}/${serviceKey(k)}"`);
208
+ continue;
209
+ }
210
+ env[k] = isSecretValue(k, v) ? secretRef(name, k, v) : v;
57
211
  }
212
+ if (fromEnv.length) {
213
+ notes.push(`${name}: reads ${fromEnv.join(", ")} from mcpd's environment (env:); under the LaunchAgent mcpd only sees variables set with launchctl setenv, so prefer keychain: for secrets`);
214
+ }
215
+ if (args.some((a) => ANY_VAR.test(a))) {
216
+ notes.push(`${name}: its args use \${...} variables; mcpd expands them from its own environment, which under the LaunchAgent only has variables set with launchctl setenv`);
217
+ }
218
+ fixed(name, "args", argSecrets(args));
58
219
  const { scope, note } = guessScope(`${command} ${args.join(" ")}`);
59
220
  const server = {};
60
221
  if (command === "npx" || command.endsWith("/npx")) {
61
222
  const { pkg, rest } = parseNpx(args);
62
223
  if (pkg) {
63
- const bin = (await opts.binOf?.(packageName(pkg))) ?? packageName(pkg).replace(/^@[^/]+\//, "");
224
+ const guess = packageName(pkg).replace(/^@[^/]+\//, "");
225
+ const found = opts.binOf ? await opts.binOf(packageName(pkg)) : undefined;
226
+ const bin = found ?? guess;
227
+ if (!opts.binOf)
228
+ notes.push(`${name}: command name guessed as ${guess}; checked on npm when written`);
229
+ else if (!found)
230
+ notes.push(`${name}: npm did not name the command of ${packageName(pkg)}; using ${guess}, check it`);
64
231
  server.command = bin;
65
232
  server.package = pkg;
66
233
  if (rest.length)
67
234
  server.args = rest;
68
- notes.push(`${name}: runs ${pkg} (turno mcp install pins it and drops the npx wrapper)`);
235
+ notes.push(`${name}: runs ${pkg}; turno mcp install pins it to an exact version and drops the npx wrapper`);
69
236
  }
70
237
  else {
71
238
  server.command = command;
@@ -79,33 +246,190 @@ export async function importServers(servers, opts = {}) {
79
246
  }
80
247
  if (Object.keys(env).length)
81
248
  server.env = env;
249
+ if (typeof entry.cwd === "string" && entry.cwd)
250
+ server.cwd = entry.cwd;
82
251
  server.scope = scope;
83
- notes.push(`${name}: scope ${scope} (${note})`);
252
+ notes.push(`${name}: scope ${scope}: ${note}`);
84
253
  out[name] = server;
85
254
  continue;
86
255
  }
87
- // Remote server: keep it direct unless its headers carry secrets we moved to the Keychain.
256
+ // Remote server: keep it direct unless its headers carry secrets moved to the Keychain.
257
+ const url = String(entry.url ?? "");
88
258
  const headers = {};
89
- for (const [k, v] of Object.entries(entry.headers ?? {})) {
90
- headers[k] = SECRET_KEY.test(k) || /^bearer\s/i.test(String(v)) ? await secretRef(name, k, String(v)) : String(v);
259
+ const withVars = [];
260
+ for (const [k, raw] of Object.entries(entry.headers ?? {})) {
261
+ const v = String(raw);
262
+ if (ANY_VAR.test(v)) {
263
+ headers[k] = v;
264
+ withVars.push(k);
265
+ continue;
266
+ }
267
+ headers[k] = isSecretValue(k, v) ? secretRef(name, k, v) : v;
268
+ }
269
+ const proxied = Object.values(headers).some((v) => v.startsWith("keychain:") || v.startsWith("env:"));
270
+ for (const k of withVars) {
271
+ if (!proxied) {
272
+ notes.push(`${name}: header ${k} uses a variable; kept as written so Claude Code expands it when it connects`);
273
+ continue;
274
+ }
275
+ // mcpd proxies this server: whole variables become env: references, mixed ones it expands itself.
276
+ const ref = envRef(headers[k]);
277
+ if (ref)
278
+ headers[k] = ref;
279
+ else
280
+ notes.push(`${name}: header ${k} mixes text and a variable; mcpd expands it from its own environment. If it is a secret, store the full value in the Keychain instead`);
91
281
  }
92
- const server = { url: String(entry.url ?? "") };
282
+ fixed(name, "url", urlSecrets(url));
283
+ if (ANY_VAR.test(url))
284
+ notes.push(`${name}: its URL uses a variable; kept as written so Claude Code expands it`);
285
+ const server = { url };
93
286
  if (type !== "http")
94
287
  server.type = type;
95
288
  if (Object.keys(headers).length)
96
289
  server.headers = headers;
97
- const proxied = Object.values(headers).some((v) => v.startsWith("keychain:"));
98
- notes.push(`${name}: remote ${proxied ? "(proxied by mcpd, secrets in the Keychain)" : "(written directly into profiles)"}`);
290
+ const proxy = Object.values(headers).some((v) => v.startsWith("keychain:") || v.startsWith("env:"));
291
+ notes.push(`${name}: remote, ${proxy ? "proxied by mcpd so its secrets stay out of profile configs" : "written directly into profiles"}`);
99
292
  out[name] = server;
100
293
  }
101
- const header = [
102
- "# turno MCP manifest. Generated by `turno mcp import`; edit freely.",
103
- "# scope: shared (one process for every session) | project (one per project folder)",
104
- "# | session (one per Claude session). Servers start on first use and stop when idle.",
105
- "# Docs: docs/mcp.md in the turno repository.",
106
- "",
107
- ].join("\n");
108
- return { toml: `${header}${stringify({ server: out })}\n`, notes, secretsMoved, literalSecrets };
294
+ const toml = `${HEADER}${stringify({ server: out })}\n`;
295
+ const masks = new Map([...hidden].sort((a, b) => b.length - a.length).map((v) => [v, maskSecret(v)]));
296
+ const masked = mapStrings(out, (s) => {
297
+ let r = s;
298
+ for (const [v, m] of masks)
299
+ r = r.split(v).join(m);
300
+ return r;
301
+ });
302
+ const shown = [...masks.values()];
303
+ const preview = `${HEADER}${stringify({ server: masked })}`
304
+ .split("\n")
305
+ .map((l) => (!l.startsWith("#") && shown.some((m) => l.includes(m)) ? `${l} # secret, hidden` : l))
306
+ .join("\n");
307
+ return { toml, preview: `${preview}\n`, notes, secrets, literalSecrets, fixedSecrets, servers: Object.keys(out) };
308
+ }
309
+ /** Entries turno itself wrote (gateway entries): importing them back would loop. */
310
+ function isGatewayEntry(e) {
311
+ const headers = { ...(e.headers ?? {}), ...(e.http_headers ?? {}) };
312
+ if (Object.keys(headers).some((h) => h.toLowerCase() === "x-turno-profile"))
313
+ return true;
314
+ return e.bearer_token_env_var === "TURNO_MCPD_TOKEN";
315
+ }
316
+ function objectsOf(v) {
317
+ if (!v || typeof v !== "object" || Array.isArray(v))
318
+ return {};
319
+ const out = {};
320
+ for (const [k, e] of Object.entries(v)) {
321
+ if (e && typeof e === "object" && !Array.isArray(e) && !isGatewayEntry(e))
322
+ out[k] = e;
323
+ }
324
+ return out;
325
+ }
326
+ /** An agent config as an object: undefined when the file is missing, {} when it holds no object. */
327
+ function readConfig(file, store) {
328
+ if (!existsSync(file))
329
+ return undefined;
330
+ const text = readFileSync(file, "utf8");
331
+ if (store.format === "toml")
332
+ return parse(text);
333
+ const v = JSON.parse(text);
334
+ return v && typeof v === "object" ? v : {};
335
+ }
336
+ /**
337
+ * Every MCP server configured for an agent on this machine, in the order of SCAN_ORDER: each
338
+ * agent's hub file (Claude Code also its per-project servers and the folder's .mcp.json, Codex
339
+ * its config.toml tables in Claude Code's shape), then the config of each profile folder in
340
+ * `profiles`, so servers set up inside one account are found too (the hub wins a shared name).
341
+ * Missing files are skipped; unreadable ones are reported in `problems`.
342
+ */
343
+ export function collectSources(env, cwd, profiles = []) {
344
+ const sources = [];
345
+ const problems = [];
346
+ const t = (f) => tildify(f, env);
347
+ const attempt = (file, read) => {
348
+ try {
349
+ read();
350
+ }
351
+ catch (err) {
352
+ problems.push(`cannot read ${t(file)}: ${err.message.split("\n")[0]}`);
353
+ }
354
+ };
355
+ const add = (label, servers) => {
356
+ if (Object.keys(servers).length)
357
+ sources.push({ label, servers });
358
+ };
359
+ for (const id of SCAN_ORDER) {
360
+ const m = adapter(id).mcp;
361
+ const shape = (v) => {
362
+ const raw = objectsOf(v);
363
+ const toImport = m.toImport;
364
+ return toImport ? Object.fromEntries(Object.entries(raw).map(([k, e]) => [k, toImport(e)])) : raw;
365
+ };
366
+ const hubFile = m.hubFile(env);
367
+ attempt(hubFile, () => {
368
+ const cfg = readConfig(hubFile, m.store);
369
+ if (!cfg)
370
+ return;
371
+ add(t(hubFile), shape(cfg[m.store.key]));
372
+ for (const [dir, servers] of m.projectServers?.(cfg) ?? [])
373
+ add(`${t(hubFile)} project ${t(dir)}`, shape(servers));
374
+ });
375
+ if (m.folderFile) {
376
+ const folder = join(cwd, m.folderFile);
377
+ attempt(folder, () => {
378
+ const cfg = readConfig(folder, m.store);
379
+ if (cfg)
380
+ add(t(folder), shape(cfg[m.store.key]));
381
+ });
382
+ }
383
+ for (const p of profiles) {
384
+ if (p.agent !== id || m.shared)
385
+ continue;
386
+ const file = m.file(agentProfileDir(p.name, id, env), env);
387
+ if (file === hubFile)
388
+ continue;
389
+ attempt(file, () => {
390
+ const cfg = readConfig(file, m.store);
391
+ if (!cfg)
392
+ return;
393
+ add(t(file), shape(cfg[m.store.key]));
394
+ for (const [dir, servers] of m.projectServers?.(cfg) ?? [])
395
+ add(`${t(file)} project ${t(dir)}`, shape(servers));
396
+ });
397
+ }
398
+ }
399
+ return { sources, problems };
400
+ }
401
+ const SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
402
+ /** One server map from every source: first source wins a name; differing duplicates are noted. */
403
+ export function mergeSources(sources) {
404
+ const servers = {};
405
+ const from = {};
406
+ const notes = [];
407
+ for (const src of sources) {
408
+ for (const [raw, entry] of Object.entries(src.servers)) {
409
+ let name = raw;
410
+ if (!SERVER_NAME.test(name)) {
411
+ name = raw.replace(/^[^A-Za-z0-9]+/, "").replace(/[^A-Za-z0-9_.-]+/g, "-") || "server";
412
+ notes.push(`${raw}: renamed to ${name} (mcp.toml names use letters, digits, ".", "_" and "-")`);
413
+ }
414
+ const prev = servers[name];
415
+ if (prev) {
416
+ if (JSON.stringify(prev) !== JSON.stringify(entry))
417
+ notes.push(`${name}: also in ${src.label} with other settings; kept the one from ${from[name]}`);
418
+ continue;
419
+ }
420
+ servers[name] = entry;
421
+ from[name] = src.label;
422
+ }
423
+ }
424
+ return { servers, from, notes };
425
+ }
426
+ /** `found 3 servers: 2 in ~/.claude.json (a, b); 1 in ~/.codex/config.toml (c)`. */
427
+ export function foundSummary(names, from) {
428
+ const by = new Map();
429
+ for (const n of names)
430
+ by.set(from[n], [...(by.get(from[n]) ?? []), n]);
431
+ const parts = [...by].map(([src, ns]) => `${ns.length} in ${src} (${ns.join(", ")})`);
432
+ return `found ${names.length} server${names.length === 1 ? "" : "s"}: ${parts.join("; ")}`;
109
433
  }
110
434
  /** Stdio servers provided by enabled plugins: they bypass mcpd and start in every session. */
111
435
  export function pluginServers(hub) {
@@ -134,13 +458,9 @@ export function pluginServers(hub) {
134
458
  const latest = versions[0];
135
459
  if (!latest)
136
460
  continue;
137
- let mcp = {};
138
- try {
139
- mcp = JSON.parse(readFileSync(join(latest, ".mcp.json"), "utf8"));
140
- }
141
- catch {
461
+ const mcp = readJsonFile(join(latest, ".mcp.json"));
462
+ if (!isObject(mcp))
142
463
  continue;
143
- }
144
464
  const servers = (mcp.mcpServers ?? mcp);
145
465
  for (const [name, def] of Object.entries(servers)) {
146
466
  if (typeof def !== "object" || def === null)