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