turno-cli 0.1.1 → 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 (104) hide show
  1. package/CHANGELOG.md +284 -0
  2. package/README.md +120 -53
  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/demo/server.js +34 -0
  74. package/dist/mcpd/cache.js +18 -4
  75. package/dist/mcpd/calllog.js +253 -0
  76. package/dist/mcpd/client-names.js +51 -0
  77. package/dist/mcpd/connectors.js +148 -17
  78. package/dist/mcpd/daemon.js +452 -116
  79. package/dist/mcpd/folder-sets.js +39 -0
  80. package/dist/mcpd/gateway.js +441 -47
  81. package/dist/mcpd/health.js +269 -0
  82. package/dist/mcpd/importer.js +356 -36
  83. package/dist/mcpd/instances.js +425 -65
  84. package/dist/mcpd/jsonrpc.js +8 -0
  85. package/dist/mcpd/launchd.js +65 -48
  86. package/dist/mcpd/modern.js +648 -0
  87. package/dist/mcpd/oauth.js +791 -0
  88. package/dist/mcpd/peerpid.js +122 -6
  89. package/dist/mcpd/pressure.js +85 -0
  90. package/dist/mcpd/rss.js +151 -0
  91. package/dist/mcpd/service.js +167 -0
  92. package/dist/mcpd/state.js +183 -0
  93. package/dist/mcpd/sync.js +55 -80
  94. package/dist/mcpd/systemd.js +80 -0
  95. package/dist/mcpd/tokens.js +89 -0
  96. package/dist/mcpd/upstream.js +154 -44
  97. package/dist/statusline/cost.js +154 -44
  98. package/dist/statusline/input.js +66 -0
  99. package/dist/statusline/render.js +9 -3
  100. package/dist/ui/fonts.js +8 -3
  101. package/dist/ui/settings.js +27 -15
  102. package/npm-shrinkwrap.json +1093 -0
  103. package/package.json +6 -6
  104. package/dist/cli/commands/available.js +0 -18
@@ -1,152 +1,352 @@
1
1
  import { execFile } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { chmodSync, existsSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { promisify } from "node:util";
5
- import { adapter, mcpFileFor } from "../../agents/index.js";
5
+ import { DEFAULT_AGENT, adapter, mcpFileFor } from "../../agents/index.js";
6
6
  import { gatewaySnippet, isSnippetAgent, SNIPPET_AGENTS } from "../../agents/snippets.js";
7
- import { loadConfig } from "../../core/config.js";
8
- import { loadManifest, parseManifest } from "../../core/manifest.js";
7
+ import { isValidProfileName, loadConfig } from "../../core/config.js";
9
8
  import { Journal } from "../../core/journal.js";
10
- import { paths, profileDir, tildify } from "../../core/paths.js";
9
+ import { loadManifest, parseManifest, servesProfile } from "../../core/manifest.js";
10
+ import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE, ensurePrivateDir, paths, tildify } from "../../core/paths.js";
11
11
  import { agentOf, listProfiles } from "../../core/profiles.js";
12
- import { fail, paint } from "../io.js";
12
+ import { liveSessions } from "../../core/sessions.js";
13
+ import { DRY_RUN, FORCE, JSON_FLAG, bool, parseFlags, printJson, str } from "../args.js";
14
+ import { group } from "../group.js";
15
+ import { highlightJson, highlightToml } from "../highlight.js";
16
+ import { colors, fail, paint, plural } from "../io.js";
17
+ import { duration, profileColor, style } from "../style.js";
18
+ import { LOG_FLAGS, SAVINGS_FLAGS, TOP_FLAGS } from "./mcp-observe.js";
19
+ import { LOGIN_FLAGS, LOGOUT_FLAGS, describeLogin, oauthLogins } from "./mcp-oauth.js";
13
20
  const run = promisify(execFile);
14
- const USAGE = `Usage:
15
- turno mcp list [--json] servers in mcp.toml and where they run
16
- turno mcp sync [profile...] [--dry-run] [--force]
17
- write the gateway entries into each profile config
18
- (Claude Code, Codex, Copilot and Cursor profiles)
19
- turno mcp config --agent <agent> [--profile <p>]
20
- print the gateway entries for ${SNIPPET_AGENTS.join(", ")}
21
- turno mcp import [--write] [--force] [--move-secrets]
22
- draft mcp.toml from the current ~/.claude.json servers
23
- turno mcp install [server...] install declared packages (no npx at every start)
24
- turno mcp refresh [server...] forget cached tool lists (relearned on next use)
25
- turno mcp doctor find servers that bypass the gateway
26
- turno mcp daemon <start|stop|restart|status|logs|run>
27
- the gateway daemon (turno mcpd is the same)`;
28
- async function list(io, json = false) {
21
+ const flagsOf = (spec) => Object.keys(spec).map((k) => `--${k}`);
22
+ /**
23
+ * One authenticated request to the running mcpd, with the port and token `mcp sync` writes.
24
+ * "down" when there is no token or nothing answers. Kept small so the endpoints can change.
25
+ */
26
+ export async function mcpdRequest(env, method, path, timeoutMs = 2000) {
27
+ const { mcpdPort, readToken } = await import("../../mcpd/state.js");
28
+ const token = readToken(env);
29
+ if (!token)
30
+ return "down";
31
+ try {
32
+ const res = await fetch(`http://127.0.0.1:${mcpdPort(env)}${path}`, {
33
+ method,
34
+ headers: { authorization: `Bearer ${token}` },
35
+ signal: AbortSignal.timeout(timeoutMs),
36
+ });
37
+ const text = await res.text();
38
+ let body = text;
39
+ try {
40
+ body = JSON.parse(text);
41
+ }
42
+ catch {
43
+ /* not JSON */
44
+ }
45
+ return { status: res.status, body };
46
+ }
47
+ catch {
48
+ return "down";
49
+ }
50
+ }
51
+ async function mcpdAnswers(env) {
52
+ const r = await mcpdRequest(env, "GET", "/status");
53
+ return r !== "down" && r.status === 200;
54
+ }
55
+ // list ---------------------------------------------------------------------------------------
56
+ const LIST_FLAGS = { ...JSON_FLAG };
57
+ /** "allow get_*, list_*, deny *_delete": a tool filter (ADR 0023) as text, or "" when it filters nothing. */
58
+ function filterText(f) {
59
+ if (!f)
60
+ return "";
61
+ return [f.allow ? `allow ${f.allow.join(", ")}` : "", f.deny ? `deny ${f.deny.join(", ")}` : ""].filter(Boolean).join(", ");
62
+ }
63
+ async function list(args, io) {
64
+ const flags = parseFlags(args, LIST_FLAGS, 0);
29
65
  const m = loadManifest(io.env);
30
66
  const names = Object.keys(m.servers).sort();
31
- if (json) {
32
- io.out(JSON.stringify(names.map((n) => {
67
+ const logins = await oauthLogins(io.env);
68
+ const loginsOf = (name) => logins.filter((l) => l.server === name);
69
+ if (bool(flags, "json")) {
70
+ printJson(io, names.map((n) => {
33
71
  const s = m.servers[n];
72
+ const tools = s.tools ?? null;
34
73
  return s.kind === "remote"
35
- ? { name: n, kind: "remote", url: s.url, proxy: Boolean(s.proxy), profiles: s.profiles }
36
- : { name: n, kind: "stdio", command: s.builtin ? `builtin ${s.builtin}` : s.command, scope: s.scope, exclusive: Boolean(s.exclusive), idleSeconds: s.idle, profiles: s.profiles, package: s.package ?? null, variants: Object.keys(s.variants) };
37
- }), null, 2));
74
+ ? {
75
+ name: n,
76
+ kind: "remote",
77
+ url: s.url,
78
+ proxy: Boolean(s.proxy),
79
+ profiles: s.profiles,
80
+ tools,
81
+ ...(s.oauth ? { auth: "oauth", logins: Object.fromEntries(loginsOf(n).map((l) => [l.variant, l.state])) } : {}),
82
+ }
83
+ : {
84
+ name: n,
85
+ kind: "stdio",
86
+ command: s.builtin ? `builtin ${s.builtin}` : s.command,
87
+ scope: s.scope,
88
+ exclusive: Boolean(s.exclusive),
89
+ idleSeconds: s.idle,
90
+ profiles: s.profiles,
91
+ package: s.package ?? null,
92
+ variants: Object.keys(s.variants),
93
+ tools,
94
+ variantTools: Object.fromEntries(Object.entries(s.variants).flatMap(([v, d]) => (d.tools ? [[v, d.tools]] : []))),
95
+ };
96
+ }));
38
97
  return 0;
39
98
  }
40
99
  if (!names.length) {
41
- io.out(`no servers in ${tildify(paths(io.env).mcpFile, io.env)} (turno mcp import)`);
100
+ io.out(`no servers in ${tildify(paths(io.env).mcpFile, io.env)} yet; draft it from your agent configs with: turno mcp import`);
42
101
  return 0;
43
102
  }
103
+ const st = style(io);
104
+ let profileColors = {};
105
+ try {
106
+ profileColors = loadConfig(io.env).profiles;
107
+ }
108
+ catch {
109
+ /* pills without their configured colors */
110
+ }
111
+ const live = await runningServers(io.env);
112
+ const state = (s) => {
113
+ if (s.kind === "remote" && !s.proxy)
114
+ return st.muted("direct");
115
+ if (!live)
116
+ return st.muted("-");
117
+ return live.has(s.name) ? st.lead("on", st.ok("running")) : st.lead("off", st.muted("stopped"));
118
+ };
119
+ const auth = (s) => {
120
+ if (s.kind === "remote" && s.oauth) {
121
+ const rows = loginsOf(s.name);
122
+ const good = rows.every((l) => l.state === "logged in" || l.state === "expired");
123
+ return good ? st.lead("ok", "oauth") : st.lead("warn", st.warn("oauth"));
124
+ }
125
+ const refs = Object.values(s.kind === "remote" ? s.headers : { ...s.env, ...Object.assign({}, ...Object.values(s.variants).map((v) => v.env)) });
126
+ return refs.some((v) => typeof v === "string" && /^(keychain|env):/.test(v)) ? "secret" : st.muted("-");
127
+ };
128
+ // Column titles: muted lowercase on a terminal, as in turno status; uppercase in plain text.
129
+ const rows = [["SERVER", "KIND", "SCOPE", "IDLE", "PROFILES", "STATE", "AUTH", "DETAILS"].map((h) => st.muted(st.color ? h.toLowerCase() : h))];
130
+ const sep = st.muted("; ");
44
131
  for (const name of names) {
45
132
  const s = m.servers[name];
46
- const where = s.profiles.includes("*") ? "all profiles" : s.profiles.join(", ");
133
+ const where = s.profiles.includes("*") ? "all" : s.profiles.map((p) => st.profile(p, profileColor(profileColors, p))).join(st.color ? " " : ", ");
134
+ const tools = filterText(s.tools) ? `tools: ${filterText(s.tools)}` : "";
47
135
  if (s.kind === "remote") {
48
- io.out(`${paint(io, name, "1")} remote ${s.proxy ? "via mcpd" : "direct"} ${s.url} (${where})`);
136
+ const logins = loginsOf(name).map((l) => {
137
+ const text = `${l.variant === "default" ? "login" : `${l.variant} login`}: ${describeLogin(l)}`;
138
+ return l.state === "logged in" || l.state === "expired" ? text : st.warn(text);
139
+ });
140
+ const details = [st.accent(s.url), tools, ...logins].filter(Boolean).join(sep);
141
+ rows.push([st.bold(name), "remote", s.proxy ? "via mcpd" : "direct", s.proxy ? `${Math.round(s.idle / 60)}m` : st.muted("-"), where, state(s), auth(s), details]);
49
142
  continue;
50
143
  }
51
144
  const variants = Object.keys(s.variants);
52
145
  const installed = s.package && existsSync(join(paths(io.env).serversDir, s.name, "node_modules"));
53
- io.out(`${paint(io, name, "1")} ${s.builtin ? `builtin ${s.builtin}` : s.command} scope ${s.scope}${s.exclusive ? " exclusive" : ""} idle ${Math.round(s.idle / 60)}m (${where})` +
54
- (variants.length ? ` variants: ${variants.join(", ")}` : "") +
55
- (s.package ? ` package ${s.package}${installed ? "" : " (not installed)"}` : ""));
146
+ const details = [
147
+ st.accent(s.builtin ? `builtin ${s.builtin}` : tildify(s.command, io.env)),
148
+ variants.length ? `variants: ${variants.join(", ")}` : "",
149
+ s.package ? (installed ? `package ${s.package}` : st.warn(`package ${s.package} (not installed)`)) : "",
150
+ tools,
151
+ ...Object.entries(s.variants).map(([v, d]) => (filterText(d.tools) ? `${v} tools: ${filterText(d.tools)}` : "")),
152
+ ]
153
+ .filter(Boolean)
154
+ .join(sep);
155
+ rows.push([st.bold(name), s.builtin ? "builtin" : "stdio", `${s.scope}${s.exclusive ? ", exclusive" : ""}`, `${Math.round(s.idle / 60)}m`, where, state(s), auth(s), details]);
56
156
  }
157
+ io.out(st.header("MCP servers"));
158
+ // A narrow terminal drops idle times, then auth and scope; the details wrap under their column.
159
+ for (const l of st.table(rows, { columns: [{}, {}, { drop: 1 }, { drop: 3 }, {}, {}, { drop: 2 }, {}] }))
160
+ io.out(l);
161
+ if (!live)
162
+ io.out(st.wrap(" ", st.muted("mcpd is not running, so nothing is: servers start on first use once it runs (turno mcp daemon start)")));
57
163
  return 0;
58
164
  }
59
- function targets(io, only) {
60
- const p = paths(io.env);
61
- const config = loadConfig(io.env);
165
+ /** Names of the servers mcpd runs now, or undefined when mcpd does not answer. */
166
+ async function runningServers(env) {
167
+ const r = await mcpdRequest(env, "GET", "/status", 1000);
168
+ if (r === "down" || r.status !== 200 || typeof r.body !== "object" || r.body === null)
169
+ return undefined;
170
+ const instances = r.body.instances;
171
+ return new Set((Array.isArray(instances) ? instances : []).flatMap((i) => (typeof i?.server === "string" ? [i.server] : [])));
172
+ }
173
+ function targets(io, config, only) {
62
174
  const out = [];
63
- let cursorDone = false;
175
+ const sharedDone = new Set();
64
176
  for (const name of listProfiles(config, io.env)) {
65
177
  if (only.length && !only.includes(name))
66
178
  continue;
67
179
  const agent = agentOf(name, config);
68
- if (adapter(agent).sharedMcpFile) {
69
- // One file for every Cursor profile: entries route by the launcher's environment.
70
- if (cursorDone)
180
+ if (adapter(agent).mcp.shared) {
181
+ // One file for every profile of the agent (Cursor): entries route by the launcher's environment.
182
+ if (sharedDone.has(agent))
71
183
  continue;
72
- cursorDone = true;
184
+ sharedDone.add(agent);
73
185
  out.push({ profile: "", file: mcpFileFor(name, agent, io.env), agent });
74
186
  continue;
75
187
  }
76
- out.push({ profile: name, file: agent === "claude" ? join(profileDir(name, io.env), ".claude.json") : mcpFileFor(name, agent, io.env), agent });
188
+ out.push({ profile: name, file: mcpFileFor(name, agent, io.env), agent });
77
189
  }
78
- // The hub config belongs to the system profile (plain `claude`).
190
+ // The hub config belongs to the system profile (the default agent started without a launcher).
79
191
  const hubProfile = config.system ?? "default";
80
- if ((!only.length || only.includes(hubProfile) || only.includes("hub")) && existsSync(p.hubConfig)) {
81
- out.push({ profile: hubProfile, file: p.hubConfig, agent: "claude" });
192
+ const hubFile = adapter(DEFAULT_AGENT).mcp.hubFile(io.env);
193
+ if ((!only.length || only.includes(hubProfile) || only.includes("hub")) && existsSync(hubFile)) {
194
+ out.push({ profile: hubProfile, file: hubFile, agent: DEFAULT_AGENT, plain: true });
82
195
  }
83
196
  return out;
84
197
  }
85
- async function busySet(io) {
86
- try {
87
- const mod = (await import("../../core/sessions.js"));
88
- const res = mod.busyProfiles?.(loadConfig(io.env), io.env) ?? [];
89
- return new Set(res);
90
- }
91
- catch {
92
- return new Set();
93
- }
198
+ /**
199
+ * Who has a live session: profiles from launcher run records (or the system profile), and
200
+ * whether plain `claude` has one. Reads only the sandbox-able paths of `env`.
201
+ */
202
+ function busyState(env, config) {
203
+ const sessions = liveSessions(env, config);
204
+ return {
205
+ profiles: new Set(sessions.flatMap((s) => (s.profile ? [s.profile] : []))),
206
+ plain: sessions.some((s) => s.source === "system"),
207
+ };
94
208
  }
209
+ const SYNC_FLAGS = { ...DRY_RUN, ...FORCE };
95
210
  async function sync(args, io) {
96
- const dryRun = args.includes("--dry-run");
97
- const force = args.includes("--force");
98
- const only = args.filter((a) => !a.startsWith("--"));
99
- const { profileServers, readManaged, syncCodexToml, syncConfigFile, syncJsonServers, writeManaged } = await import("../../mcpd/sync.js");
100
- const { ensureToken, mcpdPort } = await import("../../mcpd/daemon.js");
211
+ const flags = parseFlags(args, SYNC_FLAGS);
212
+ const r = await syncProfiles(io, { dryRun: bool(flags, "dry-run"), force: bool(flags, "force"), only: flags.positionals, command: `mcp sync ${args.join(" ")}`.trim() });
213
+ return r.skipped ? 1 : 0;
214
+ }
215
+ /** Point every profile's agent config at the gateway. `changed` counts the files that change (or would). */
216
+ export async function syncProfiles(io, opts = {}) {
217
+ const dryRun = Boolean(opts.dryRun);
218
+ const force = Boolean(opts.force);
219
+ const only = opts.only ?? [];
220
+ const config = loadConfig(io.env);
221
+ const known = new Set([...listProfiles(config, io.env), config.system ?? "default", "hub"]);
222
+ for (const name of only)
223
+ if (!known.has(name))
224
+ fail(`no profile '${name}' (turno profile list shows them)`);
225
+ const { profileServers, readManaged, syncServers, writeManaged } = await import("../../mcpd/sync.js");
226
+ const { ensureToken, mcpdPort, readToken } = await import("../../mcpd/state.js");
101
227
  const manifest = loadManifest(io.env);
102
- const token = ensureToken(io.env);
228
+ // A dry run never creates the token; without one, entries show a placeholder. Entries get
229
+ // each profile's own token derived from this master token (ADR 0023), never the master.
230
+ const token = dryRun ? (readToken(io.env) ?? "<token>") : ensureToken(io.env);
103
231
  const port = mcpdPort(io.env);
104
232
  const p = paths(io.env);
105
233
  const managed = readManaged(p.mcpdManaged);
106
- const busy = await busySet(io);
234
+ const managedBefore = JSON.stringify(managed);
235
+ const busy = busyState(io.env, config);
107
236
  let skipped = 0;
108
- const journal = new Journal(io.env, `mcp sync ${args.join(" ")}`.trim(), dryRun);
109
- for (const t of targets(io, only)) {
110
- const label = `${t.profile || `${adapter(t.agent).label} profiles`} (${tildify(t.file, io.env)})`;
111
- if (t.profile && busy.has(t.profile) && !force && !dryRun) {
112
- io.out(`${paint(io, "skip", "33")} ${label}: has open sessions; close them or use --force`);
237
+ let changed = 0;
238
+ let gatewayTargets = 0;
239
+ const journal = opts.journal ?? new Journal(io.env, opts.command ?? "mcp sync", dryRun);
240
+ const st = style(io);
241
+ const started = Date.now();
242
+ const rows = [];
243
+ const notes = [];
244
+ for (const t of targets(io, config, only)) {
245
+ const where = tildify(t.file, io.env);
246
+ const a = adapter(t.agent);
247
+ const label = t.plain
248
+ ? st.bold(`plain ${a.command}${config.system ? `, profile ${config.system}` : ""}`)
249
+ : t.profile
250
+ ? st.profile(t.profile, profileColor(config.profiles, t.profile))
251
+ : st.bold(`${a.label} profiles`);
252
+ const isBusy = t.plain ? busy.plain || busy.profiles.has(t.profile) : Boolean(t.profile) && busy.profiles.has(t.profile);
253
+ if (isBusy && !force) {
254
+ rows.push([st.icon("warn"), label, st.muted(where), st.warn(`${dryRun ? "would skip" : "skipped"}: has open sessions; close them or use --force`)]);
113
255
  skipped++;
114
256
  continue;
115
257
  }
116
258
  const wanted = profileServers(manifest, t.profile, port, token, t.agent);
117
- const before = journal.save(t.file);
259
+ if (Object.values(manifest.servers).some((s) => servesProfile(s, t.profile) && !(s.kind === "remote" && !s.proxy)))
260
+ gatewayTargets++;
118
261
  const prev = managed[t.file] ?? [];
119
- const res = t.agent === "codex"
120
- ? syncCodexToml(t.file, wanted, prev, { dryRun })
121
- : t.agent === "claude"
122
- ? syncConfigFile(t.file, wanted, prev, { dryRun })
123
- : syncJsonServers(t.file, "mcpServers", wanted, prev, { dryRun });
124
- journal.settle(before);
262
+ const apply = (dry) => syncServers(t.file, a.mcp.store, wanted, prev, { dryRun: dry });
263
+ // Plan first, so a file that would not change is neither backed up nor rewritten.
264
+ let res = apply(true);
265
+ if (res.changed && !dryRun) {
266
+ const before = journal.save(t.file);
267
+ res = apply(false);
268
+ journal.settle(before);
269
+ }
270
+ if (res.changed)
271
+ changed++;
125
272
  if (!dryRun)
126
273
  managed[t.file] = Object.keys(wanted);
127
- const parts = [
128
- res.added.length ? `added ${res.added.join(", ")}` : "",
129
- res.updated.length ? `updated ${res.updated.join(", ")}` : "",
130
- res.removed.length ? `removed ${res.removed.join(", ")}` : "",
131
- res.foreign.length ? `left alone ${res.foreign.join(", ")}` : "",
132
- ].filter(Boolean);
133
- io.out(`${paint(io, dryRun ? "plan" : res.changed ? "sync" : "same", res.changed ? "32" : "2")} ${label}${parts.length ? `: ${parts.join("; ")}` : ""}`);
134
- if (t.agent === "cursor" && res.added.length && !dryRun) {
135
- io.out(` Cursor asks to approve new servers once: cursor-agent mcp enable <name> (${res.added.join(", ")})`);
136
- }
274
+ const verbs = dryRun ? ["would add", "would update", "would remove", "would leave alone"] : ["added", "updated", "removed", "left alone"];
275
+ const parts = [res.added, res.updated, res.removed, res.foreign].map((names, i) => (names.length ? `${verbs[i]} ${names.join(", ")}` : "")).filter(Boolean);
276
+ const detail = parts.length ? parts.join("; ") : res.changed ? "" : st.muted("no changes");
277
+ rows.push([st.icon(!res.changed ? "skip" : dryRun ? "info" : "ok"), label, st.muted(where), detail]);
278
+ const after = res.added.length && !dryRun ? a.mcp.afterSync?.(res.added) : undefined;
279
+ if (after)
280
+ notes.push(after);
137
281
  }
138
- if (!dryRun)
282
+ for (const line of st.table(rows, { columns: [{}, {}, { drop: 1 }, {}] }))
283
+ io.out(line);
284
+ for (const n of notes)
285
+ io.out(n);
286
+ if (!dryRun && JSON.stringify(managed) !== managedBefore)
139
287
  writeManaged(p.mcpdManaged, managed);
140
- if (!dryRun)
141
- io.out("New sessions pick this up; open sessions keep their old servers until restarted.");
142
- const hint = journal.hint();
288
+ await syncTokenFiles(io, config, only, token, dryRun);
289
+ if (!dryRun && changed)
290
+ io.out(st.wrap(" ", st.muted("New sessions pick this up; open sessions keep their old servers until restarted.")));
291
+ if (!opts.journal)
292
+ io.out(` ${st.muted(`${dryRun ? "Planned" : "Synced"} ${plural(rows.length, "config")} in ${duration(Date.now() - started)}.`)}`);
293
+ const hint = changed && !dryRun && !opts.journal ? journal.hint() : undefined;
143
294
  if (hint)
144
295
  io.out(hint);
145
- return skipped ? 1 : 0;
296
+ if (gatewayTargets && !(await mcpdAnswers(io.env))) {
297
+ io.err(st.wrap("", `${paint(io, "warning", "33")}: mcpd is not running, so these profiles have no local MCP servers until you run: turno mcp daemon start`));
298
+ }
299
+ return { changed, skipped };
300
+ }
301
+ /**
302
+ * Agents that read the gateway token from the environment (Codex, Copilot, Cursor) get it from
303
+ * a private file per profile that their launcher reads (ADR 0023). Written even for profiles
304
+ * with open sessions: those already hold their token, and the next launch needs the new one.
305
+ */
306
+ async function syncTokenFiles(io, config, only, master, dryRun) {
307
+ const tokens = await import("../../mcpd/tokens.js");
308
+ const { profileToken, readProfileTokenFile, writeProfileTokenFile } = tokens;
309
+ const { isGenerated, launcherName } = await import("../launchers.js");
310
+ const changed = [];
311
+ const oldLaunchers = [];
312
+ const profiles = listProfiles(config, io.env);
313
+ const synced = new Set(tokens.readSyncedTokenProfiles(io.env));
314
+ const before = synced.size;
315
+ for (const name of profiles) {
316
+ if (only.length && !only.includes(name))
317
+ continue;
318
+ const agent = agentOf(name, config);
319
+ if (!adapter(agent).tokenFromEnv)
320
+ continue;
321
+ synced.add(name);
322
+ if (dryRun ? readProfileTokenFile(name, io.env) !== profileToken(master, name) : writeProfileTokenFile(name, master, io.env))
323
+ changed.push(name);
324
+ const launcher = join(paths(io.env).bin, launcherName(name, agent));
325
+ if (isGenerated(launcher) && !readFileSync(launcher, "utf8").includes("mcpd-tokens/"))
326
+ oldLaunchers.push(name);
327
+ }
328
+ const st = style(io);
329
+ if (changed.length)
330
+ io.out(st.note(dryRun ? "info" : "ok", `${dryRun ? "would write" : "wrote"} the gateway token of ${changed.join(", ")} for their launchers`));
331
+ // A full sync removes the token files it wrote for profiles that are gone. The token itself
332
+ // stays valid until a rotation (ADR 0023); the file is just no longer needed.
333
+ const gone = only.length ? [] : [...synced].filter((n) => !profiles.includes(n)).sort();
334
+ for (const name of gone) {
335
+ synced.delete(name);
336
+ if (dryRun ? !readProfileTokenFile(name, io.env) : !tokens.removeProfileTokenFile(name, io.env))
337
+ continue;
338
+ io.out(st.note(dryRun ? "info" : "ok", `${dryRun ? "would remove" : "removed"} the gateway token file of ${name} (no longer a profile)`));
339
+ }
340
+ if (!dryRun && (synced.size !== before || gone.length || changed.length))
341
+ tokens.writeSyncedTokenProfiles([...synced], io.env);
342
+ for (const name of oldLaunchers) {
343
+ io.err(st.wrap("", `${paint(io, "warning", "33")}: the launcher of ${name} still reads the old shared token; rewrite it with: turno profile repair ${name}`));
344
+ }
146
345
  }
346
+ // config -------------------------------------------------------------------------------------
347
+ const CONFIG_FLAGS = { agent: { type: "string" }, profile: { type: "string" }, ...JSON_FLAG };
147
348
  async function config(args, io) {
148
- const { parseFlags, str } = await import("../args.js");
149
- const p = parseFlags(args, { agent: { type: "string" }, profile: { type: "string" } }, 0);
349
+ const p = parseFlags(args, CONFIG_FLAGS, 0);
150
350
  const agent = str(p, "agent");
151
351
  if (!agent || !isSnippetAgent(agent)) {
152
352
  return fail(`usage: turno mcp config --agent <${SNIPPET_AGENTS.join("|")}> [--profile <p>]\n(Claude Code, Codex, Copilot and Cursor profiles get their entries from turno mcp sync)`);
@@ -154,20 +354,28 @@ async function config(args, io) {
154
354
  const cfg = loadConfig(io.env);
155
355
  const profile = str(p, "profile") ?? cfg.default ?? "default";
156
356
  const manifest = loadManifest(io.env);
157
- const { servesProfile } = await import("../../core/manifest.js");
158
357
  const servers = Object.entries(manifest.servers)
159
358
  .filter(([, def]) => servesProfile(def, profile) && !(def.kind === "remote" && !def.proxy))
160
359
  .map(([name]) => name);
161
360
  if (!servers.length)
162
361
  return fail(`no gateway servers for profile ${profile} in mcp.toml`);
163
- const { mcpdPort } = await import("../../mcpd/daemon.js");
164
- const s = gatewaySnippet(agent, servers, mcpdPort(io.env), profile);
165
- io.out(`# ${s.file}`);
362
+ const { ensureToken, mcpdPort } = await import("../../mcpd/state.js");
363
+ const { profileTokenFile, writeProfileTokenFile } = await import("../../mcpd/tokens.js");
364
+ // The snippet reads the profile's own token from a private file; it is never printed.
365
+ if (isValidProfileName(profile))
366
+ writeProfileTokenFile(profile, ensureToken(io.env), io.env);
367
+ const s = gatewaySnippet(agent, servers, mcpdPort(io.env), profile, tildify(profileTokenFile(profile, io.env), io.env));
368
+ if (bool(p, "json")) {
369
+ printJson(io, { agent, profile, servers, file: s.file, notes: s.notes, text: s.text });
370
+ return 0;
371
+ }
372
+ io.out(paint(io, `# ${s.file}`, "2"));
166
373
  for (const n of s.notes)
167
- io.out(`# ${n}`);
168
- io.out(s.text.trimEnd());
374
+ io.out(paint(io, `# ${n}`, "2"));
375
+ io.out(colors(io) && s.file.includes(".json") ? highlightJson(s.text.trimEnd()) : s.text.trimEnd());
169
376
  return 0;
170
377
  }
378
+ // import -------------------------------------------------------------------------------------
171
379
  /** The bin npx would run: the only one, else the one named after the package. */
172
380
  export function pickBin(pkg, bin) {
173
381
  const base = pkg.replace(/^@[^/]+\//, "");
@@ -178,9 +386,12 @@ export function pickBin(pkg, bin) {
178
386
  return names[0];
179
387
  return names.find((n) => n === base) ?? names.find((n) => n.includes("mcp"));
180
388
  }
181
- async function binOf(pkg) {
389
+ function npm(io, args, timeout) {
390
+ return run("npm", args, { timeout, env: io.env });
391
+ }
392
+ export async function binOf(io, pkg) {
182
393
  try {
183
- const { stdout } = await run("npm", ["view", pkg, "bin", "--json"], { timeout: 20_000 });
394
+ const { stdout } = await npm(io, ["view", pkg, "bin", "--json"], 20_000);
184
395
  const bin = JSON.parse(stdout || "null");
185
396
  if (!bin)
186
397
  return undefined;
@@ -190,86 +401,279 @@ async function binOf(pkg) {
190
401
  return undefined;
191
402
  }
192
403
  }
404
+ const IMPORT_FLAGS = { write: { type: "boolean" }, "move-secrets": { type: "boolean" }, ...FORCE, ...DRY_RUN };
193
405
  async function importCmd(args, io) {
194
- const { importServers } = await import("../../mcpd/importer.js");
195
- const { storeKeychainSecret } = await import("../../core/secrets.js");
406
+ const flags = parseFlags(args, IMPORT_FLAGS, 0);
407
+ const write = bool(flags, "write");
408
+ const moveSecrets = bool(flags, "move-secrets");
409
+ if (write && bool(flags, "dry-run"))
410
+ fail("--dry-run and --write do not go together (without --write it is a preview)");
411
+ const { collectSources, foundSummary, importServers, mergeSources } = await import("../../mcpd/importer.js");
196
412
  const p = paths(io.env);
197
- let hub = {};
198
- try {
199
- hub = JSON.parse(readFileSync(p.hubConfig, "utf8"));
413
+ const config = loadConfig(io.env);
414
+ const profiles = listProfiles(config, io.env).map((name) => ({ name, agent: agentOf(name, config) }));
415
+ const { sources, problems } = collectSources(io.env, process.cwd(), profiles);
416
+ for (const pr of problems)
417
+ io.err(`${paint(io, "warning", "33")}: ${pr}`);
418
+ const merged = mergeSources(sources);
419
+ const names = Object.keys(merged.servers);
420
+ if (!names.length) {
421
+ io.out("No MCP servers found in Claude Code (~/.claude.json, .mcp.json), Codex, Cursor or Copilot CLI configs, or in turno profile folders.");
422
+ io.out("Nothing written. Add servers to mcp.toml by hand: see docs/mcp.md in the turno repository.");
423
+ return write ? 1 : 0;
200
424
  }
201
- catch {
202
- return fail(`cannot read ${tildify(p.hubConfig, io.env)}`);
203
- }
204
- const servers = hub.mcpServers ?? {};
205
- const report = await importServers(servers, {
206
- moveSecrets: args.includes("--move-secrets"),
207
- binOf,
208
- store: (service, value) => storeKeychainSecret(service, value),
209
- });
425
+ io.err(foundSummary(names, merged.from));
426
+ // A preview stays offline; only --write asks npm for the command names of npx servers.
427
+ const report = await importServers(merged.servers, write ? { moveSecrets, binOf: (pkg) => binOf(io, pkg) } : { moveSecrets });
210
428
  parseManifest(report.toml); // never write something we cannot read back
211
- for (const n of report.notes)
429
+ for (const n of [...merged.notes, ...report.notes])
212
430
  io.err(` ${n}`);
213
- for (const s of report.secretsMoved)
214
- io.err(` moved ${s}`);
215
431
  if (report.literalSecrets.length) {
216
- io.err(` ${paint(io, "warning", "33")}: literal secrets kept (${report.literalSecrets.join(", ")}); rerun with --move-secrets to store them in the Keychain`);
432
+ io.err(` ${paint(io, "warning", "33")}: literal secrets kept (${report.literalSecrets.join(", ")}); add --move-secrets to store them in the Keychain`);
217
433
  }
218
- if (!args.includes("--write")) {
219
- io.out(report.toml);
434
+ const exists = existsSync(p.mcpFile);
435
+ if (!write) {
436
+ for (const s of report.secrets)
437
+ io.err(` would move ${s.where} to keychain:${s.service}`);
438
+ io.out(colors(io) ? highlightToml(report.preview.trimEnd()) : report.preview.trimEnd());
439
+ const again = ["turno mcp import --write", moveSecrets || report.literalSecrets.length ? "--move-secrets" : "", exists ? "--force" : ""].filter(Boolean).join(" ");
440
+ io.err(`Nothing written. Write it with: ${again}`);
220
441
  return 0;
221
442
  }
222
- if (existsSync(p.mcpFile) && !args.includes("--force"))
443
+ if (exists && !bool(flags, "force"))
223
444
  return fail(`${tildify(p.mcpFile, io.env)} exists; use --force (it is backed up)`);
445
+ const { storeKeychainSecret } = await import("../../core/secrets.js");
446
+ for (const s of report.secrets) {
447
+ if (s.value.includes("${"))
448
+ continue; // never store a placeholder
449
+ await storeKeychainSecret(s.service, s.value, io.env);
450
+ io.err(` moved ${s.where} to keychain:${s.service}`);
451
+ }
224
452
  const journal = new Journal(io.env, "mcp import --write");
225
453
  journal.write(p.mcpFile, report.toml, 0o600);
226
- io.out(`wrote ${tildify(p.mcpFile, io.env)}`);
454
+ io.out(`wrote ${tildify(p.mcpFile, io.env)} with ${plural(names.length, "server")}`);
227
455
  io.out(journal.hint());
228
456
  return 0;
229
457
  }
458
+ // install ------------------------------------------------------------------------------------
459
+ /** `@scope/pkg@^1.2` -> name `@scope/pkg`, range `^1.2`; a bare name has an empty range. */
460
+ export function splitSpec(spec) {
461
+ const at = spec.lastIndexOf("@");
462
+ return at > 0 ? { name: spec.slice(0, at), range: spec.slice(at + 1) } : { name: spec, range: "" };
463
+ }
464
+ const EXACT = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
465
+ /**
466
+ * Replace the `package` value of `[server.<name>]` in mcp.toml text, keeping everything else.
467
+ * Undefined when the line is not where we expect it (inline tables and the like).
468
+ */
469
+ export function pinPackage(text, server, spec) {
470
+ const lines = text.split("\n");
471
+ const header = /^\s*\[\s*server\.("(?:[^"\\]|\\.)*"|[A-Za-z0-9_.-]+?)\s*\]\s*(#.*)?$/;
472
+ let inside = false;
473
+ for (let i = 0; i < lines.length; i++) {
474
+ const h = header.exec(lines[i]);
475
+ if (h) {
476
+ const name = h[1].startsWith('"') ? JSON.parse(h[1]) : h[1];
477
+ inside = name === server;
478
+ continue;
479
+ }
480
+ if (/^\s*\[/.test(lines[i])) {
481
+ inside = false;
482
+ continue;
483
+ }
484
+ if (!inside)
485
+ continue;
486
+ const m = /^(\s*package\s*=\s*)("(?:[^"\\]|\\.)*"|'[^']*')(.*)$/.exec(lines[i]);
487
+ if (!m)
488
+ continue;
489
+ lines[i] = `${m[1]}${JSON.stringify(spec)}${m[3]}`;
490
+ const next = lines.join("\n");
491
+ try {
492
+ const s = parseManifest(next).servers[server];
493
+ return s?.kind === "stdio" && s.package === spec ? next : undefined;
494
+ }
495
+ catch {
496
+ return undefined;
497
+ }
498
+ }
499
+ return undefined;
500
+ }
501
+ async function exactVersion(io, spec) {
502
+ const { name, range } = splitSpec(spec);
503
+ if (EXACT.test(range))
504
+ return range;
505
+ const { stdout } = await npm(io, ["view", `${name}@${range || "latest"}`, "version", "--json"], 30_000);
506
+ const v = JSON.parse(stdout || "null");
507
+ const version = Array.isArray(v) ? v[v.length - 1] : v;
508
+ if (!version || !EXACT.test(version))
509
+ throw new Error(`npm found no version of ${spec}`);
510
+ return version;
511
+ }
512
+ const INSTALL_FLAGS = { ...DRY_RUN, "allow-scripts": { type: "boolean" } };
230
513
  async function install(args, io) {
514
+ const flags = parseFlags(args, INSTALL_FLAGS);
515
+ const dryRun = bool(flags, "dry-run");
516
+ const allowScripts = bool(flags, "allow-scripts");
517
+ const only = flags.positionals;
231
518
  const m = loadManifest(io.env);
519
+ for (const n of only)
520
+ if (!m.servers[n])
521
+ fail(`unknown server '${n}' (turno mcp list shows them)`);
232
522
  const p = paths(io.env);
233
- const wanted = Object.values(m.servers).filter((s) => s.kind === "stdio" && Boolean(s.package) && (!args.length || args.includes(s.name)));
523
+ const wanted = Object.values(m.servers).filter((s) => s.kind === "stdio" && Boolean(s.package) && (!only.length || only.includes(s.name)));
234
524
  if (!wanted.length) {
235
525
  io.out("nothing to install (no server declares a package)");
236
526
  return 0;
237
527
  }
528
+ let text = existsSync(p.mcpFile) ? readFileSync(p.mcpFile, "utf8") : "";
529
+ const pins = [];
238
530
  let failed = 0;
239
531
  for (const s of wanted) {
532
+ const { name } = splitSpec(s.package);
533
+ let version;
534
+ try {
535
+ version = await exactVersion(io, s.package);
536
+ }
537
+ catch (err) {
538
+ failed++;
539
+ io.err(`${s.name}: cannot resolve ${s.package}: ${err.message.split("\n")[0]}`);
540
+ continue;
541
+ }
542
+ const pinned = `${name}@${version}`;
240
543
  const dir = join(p.serversDir, s.name);
241
- mkdirSync(dir, { recursive: true });
544
+ const lock = join(dir, "package-lock.json");
545
+ let deps = {};
546
+ try {
547
+ deps = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).dependencies ?? {};
548
+ }
549
+ catch {
550
+ /* first install */
551
+ }
552
+ // Same version and a lockfile: reinstall exactly what was installed before.
553
+ const fromLock = existsSync(lock) && deps[name] === version;
554
+ if (dryRun) {
555
+ io.out(`would install ${pinned} for ${s.name}${fromLock ? " from its lockfile" : ""}${allowScripts ? "" : " without install scripts"}`);
556
+ if (pinned !== s.package)
557
+ io.out(`would pin package = "${pinned}" in ${tildify(p.mcpFile, io.env)}`);
558
+ continue;
559
+ }
560
+ // Private like the rest of turno's data: a server folder holds code mcpd runs.
561
+ ensurePrivateDir(dir, io.env);
562
+ for (const d of [p.serversDir, dir])
563
+ if ((statSync(d).mode & 0o777) !== PRIVATE_DIR_MODE)
564
+ chmodSync(d, PRIVATE_DIR_MODE);
242
565
  if (!existsSync(join(dir, "package.json")))
243
- writeFileSync(join(dir, "package.json"), `{ "private": true }\n`);
244
- io.out(`installing ${s.package} for ${s.name}...`);
566
+ writeFileSync(join(dir, "package.json"), `{ "private": true }\n`, { mode: PRIVATE_FILE_MODE });
567
+ const common = ["--no-audit", "--no-fund", "--prefix", dir, ...(allowScripts ? [] : ["--ignore-scripts"])];
568
+ const npmArgs = fromLock ? ["ci", ...common] : ["install", "--save-exact", "--package-lock=true", ...common, pinned];
569
+ io.out(`installing ${pinned} for ${s.name}${fromLock ? " from its lockfile" : ""}...`);
245
570
  try {
246
- await run("npm", ["install", "--no-audit", "--no-fund", "--prefix", dir, s.package], { timeout: 300_000 });
571
+ await npm(io, npmArgs, 300_000);
247
572
  const bin = join(dir, "node_modules", ".bin", s.command);
248
573
  io.out(existsSync(bin) ? ` ok: ${tildify(bin, io.env)}` : ` ${paint(io, "warning", "33")}: installed but no bin named ${s.command}`);
249
574
  }
250
575
  catch (err) {
251
576
  failed++;
252
577
  io.err(` failed: ${err.message.split("\n")[0]}`);
578
+ if (!allowScripts)
579
+ io.err(" if the package needs its install scripts, retry with --allow-scripts");
580
+ continue;
253
581
  }
582
+ if (pinned === s.package)
583
+ continue;
584
+ const next = pinPackage(text, s.name, pinned);
585
+ if (next === undefined) {
586
+ io.err(` ${paint(io, "warning", "33")}: could not pin ${s.name} in mcp.toml; set package = "${pinned}" by hand`);
587
+ continue;
588
+ }
589
+ text = next;
590
+ pins.push(`${s.name} to ${pinned}`);
591
+ }
592
+ if (pins.length) {
593
+ const journal = new Journal(io.env, "mcp install");
594
+ journal.write(p.mcpFile, text);
595
+ io.out(`pinned ${pins.join(", ")} in ${tildify(p.mcpFile, io.env)}`);
596
+ io.out(journal.hint());
254
597
  }
255
598
  return failed ? 1 : 0;
256
599
  }
600
+ // refresh ------------------------------------------------------------------------------------
601
+ const REFRESH_FLAGS = { ...DRY_RUN };
602
+ /**
603
+ * Ask mcpd to forget and relearn one server's descriptions (POST /refresh/<server>). A 200 can
604
+ * still carry per-instance failures (`errors`: `<server>@<variant>` to message): they come back
605
+ * as `failed`.
606
+ */
607
+ async function refreshInDaemon(env, server) {
608
+ const r = await mcpdRequest(env, "POST", `/refresh/${encodeURIComponent(server)}`, 15_000);
609
+ if (r === "down")
610
+ return "down";
611
+ if (r.status >= 200 && r.status < 300) {
612
+ const errors = typeof r.body === "object" && r.body ? r.body.errors : undefined;
613
+ const failed = {};
614
+ if (errors && typeof errors === "object")
615
+ for (const [k, v] of Object.entries(errors))
616
+ failed[k] = String(v);
617
+ return { failed };
618
+ }
619
+ if (r.status === 404)
620
+ return "unsupported";
621
+ const msg = typeof r.body === "object" && r.body && "error" in r.body ? String(r.body.error) : `HTTP ${r.status}`;
622
+ return msg;
623
+ }
257
624
  async function refresh(args, io) {
625
+ const flags = parseFlags(args, REFRESH_FLAGS);
626
+ const dryRun = bool(flags, "dry-run");
627
+ const only = flags.positionals;
258
628
  const dir = paths(io.env).mcpdCacheDir;
259
- if (!existsSync(dir)) {
260
- io.out("cache is empty");
629
+ const cached = existsSync(dir) ? readdirSync(dir) : [];
630
+ const manifest = loadManifest(io.env);
631
+ for (const n of only) {
632
+ if (!manifest.servers[n] && !cached.some((f) => f.startsWith(`${n}@`)))
633
+ fail(`unknown server '${n}' (turno mcp list shows them)`);
634
+ }
635
+ const files = cached.filter((f) => !only.length || only.some((a) => f.startsWith(`${a}@`)));
636
+ const servers = only.length ? only : Object.keys(manifest.servers).sort();
637
+ if (dryRun) {
638
+ io.out(`would forget ${plural(files.length, "cached description")}${servers.length ? ` and ask mcpd to relearn ${servers.join(", ")}` : ""}`);
261
639
  return 0;
262
640
  }
263
- const { readdirSync } = await import("node:fs");
264
- let n = 0;
265
- for (const f of readdirSync(dir)) {
266
- if (!args.length || args.some((a) => f.startsWith(`${a}@`))) {
267
- rmSync(join(dir, f), { force: true });
268
- n++;
641
+ for (const f of files)
642
+ rmSync(join(dir, f), { force: true });
643
+ io.out(`forgot ${plural(files.length, "cached description")}`);
644
+ if (!servers.length)
645
+ return 0;
646
+ let fallback = false;
647
+ let failed = 0;
648
+ const done = [];
649
+ for (const s of servers) {
650
+ const r = await refreshInDaemon(io.env, s);
651
+ if (r === "down") {
652
+ io.out("mcpd is not running; it learns them again when it starts");
653
+ return 0;
654
+ }
655
+ if (r === "unsupported") {
656
+ fallback = true;
657
+ break;
658
+ }
659
+ if (typeof r === "string") {
660
+ failed++;
661
+ io.err(`${s}: mcpd could not refresh it: ${r}`);
662
+ continue;
269
663
  }
664
+ const errors = Object.entries(r.failed);
665
+ for (const [instance, message] of errors)
666
+ io.err(`${instance}: mcpd could not refresh it: ${message.split("\n")[0]}`);
667
+ if (errors.length)
668
+ failed++;
669
+ else
670
+ done.push(s);
270
671
  }
271
- io.out(`forgot ${n} cached descriptions; restart mcpd (turno mcpd restart) so it relearns them`);
272
- return 0;
672
+ if (fallback)
673
+ io.out("restart mcpd so it relearns them: turno mcp daemon restart");
674
+ else if (done.length)
675
+ io.out(`mcpd refreshed ${done.join(", ")}`);
676
+ return failed ? 1 : 0;
273
677
  }
274
678
  /** Local servers that do not go through mcpd. */
275
679
  export async function bypassingServers(env) {
@@ -279,20 +683,31 @@ export async function bypassingServers(env) {
279
683
  const plugins = pluginServers(p.hub)
280
684
  .filter((s) => s.transport === "stdio")
281
685
  .map((s) => ({ plugin: s.plugin, name: s.name, command: String(s.command), toolPrefix: s.toolPrefix }));
282
- let hub = {};
283
- try {
284
- hub = JSON.parse(readFileSync(p.hubConfig, "utf8"));
285
- }
286
- catch {
287
- /* no hub config */
288
- }
289
- const direct = Object.entries(hub.mcpServers ?? {})
290
- .filter(([, e]) => typeof e.command === "string")
686
+ // No hub config, or one of another shape: no direct servers.
687
+ const hub = readJsonFile(p.hubConfig);
688
+ const servers = isObject(hub) && isObject(hub.mcpServers) ? hub.mcpServers : {};
689
+ const direct = Object.entries(servers)
690
+ .filter(([, e]) => isObject(e) && typeof e.command === "string")
291
691
  .map(([name]) => ({ name, inManifest: Boolean(manifest.servers[name]) }));
292
692
  return { plugins, direct };
293
693
  }
294
- async function doctor(io) {
295
- const { plugins, direct } = await bypassingServers(io.env);
694
+ const DOCTOR_FLAGS = { ...JSON_FLAG };
695
+ async function doctor(args, io) {
696
+ const flags = parseFlags(args, DOCTOR_FLAGS, 0);
697
+ const found = await bypassingServers(io.env);
698
+ const { plugins, direct } = found;
699
+ const logins = await oauthLogins(io.env);
700
+ const missing = logins.filter((l) => l.state === "not logged in" || l.state === "login required");
701
+ const code = plugins.length + direct.length + missing.length ? 1 : 0;
702
+ if (bool(flags, "json")) {
703
+ printJson(io, { ok: code === 0, ...found, ...(logins.length ? { logins: missing } : {}) });
704
+ return code;
705
+ }
706
+ if (missing.length) {
707
+ io.out(paint(io, "Remote OAuth servers that need a login (ADR 0029):", "1"));
708
+ for (const l of missing)
709
+ io.out(` ${l.server}${l.variant === "default" ? "" : `@${l.variant}`}: ${describeLogin(l)}`);
710
+ }
296
711
  if (plugins.length) {
297
712
  io.out(paint(io, "Plugin servers that start in every session (they bypass mcpd):", "1"));
298
713
  for (const s of plugins)
@@ -301,50 +716,103 @@ async function doctor(io) {
301
716
  io.out(` declare [server.plugin_<plugin>_<name>] in mcp.toml so tool names stay the same.`);
302
717
  }
303
718
  if (direct.length) {
304
- io.out(paint(io, "Stdio servers still configured directly in the hub config:", "1"));
719
+ io.out(paint(io, "Stdio servers still configured directly in plain claude (~/.claude.json):", "1"));
305
720
  for (const d of direct)
306
- io.out(` ${d.name}${d.inManifest ? " (in mcp.toml: run turno mcp sync)" : " (not in mcp.toml: turno mcp import)"}`);
721
+ io.out(` ${d.name}${d.inManifest ? ": in mcp.toml, run turno mcp sync" : ": not in mcp.toml, run turno mcp import"}`);
307
722
  }
308
- if (!plugins.length && !direct.length)
309
- io.out("Every local server goes through mcpd.");
310
- return plugins.length + direct.length ? 1 : 0;
723
+ if (!code)
724
+ io.out(`Every local server goes through mcpd${logins.length ? " and every OAuth server is logged in" : ""}.`);
725
+ return code;
311
726
  }
312
- export const command = {
313
- summary: "MCP servers behind the lazy gateway, and the gateway daemon itself",
314
- usage: USAGE,
315
- subcommands: {
316
- list: { flags: ["--json"] },
317
- sync: { args: ["profile"], flags: ["--dry-run", "--force"] },
318
- config: { flags: ["--agent", "--profile"] },
319
- import: { flags: ["--write", "--force", "--move-secrets"] },
320
- install: { args: ["server"] },
321
- refresh: { args: ["server"] },
322
- doctor: {},
323
- daemon: { args: ["any"] },
727
+ // command ------------------------------------------------------------------------------------
728
+ const SUBS = {
729
+ list: { synopsis: "[--json]", summary: "servers in mcp.toml and where they run", flags: flagsOf(LIST_FLAGS), run: list },
730
+ sync: {
731
+ synopsis: "[profile...] [--dry-run] [--force]",
732
+ summary: "write gateway entries into every profile config",
733
+ args: ["profile"],
734
+ flags: flagsOf(SYNC_FLAGS),
735
+ run: sync,
324
736
  },
325
- async run(args, io) {
326
- const [sub, ...rest] = args;
327
- switch (sub) {
328
- case "list":
329
- case undefined:
330
- return list(io, rest.includes("--json"));
331
- case "sync":
332
- return sync(rest, io);
333
- case "config":
334
- return config(rest, io);
335
- case "import":
336
- return importCmd(rest, io);
337
- case "install":
338
- return install(rest, io);
339
- case "refresh":
340
- return refresh(rest, io);
341
- case "daemon":
342
- return (await import("./mcpd.js")).command.run(rest, io);
343
- case "doctor":
344
- return doctor(io);
345
- default:
346
- return fail(`unknown mcp command "${sub}"\n${USAGE}`);
347
- }
737
+ config: {
738
+ synopsis: "--agent <a> [--profile <p>] [--json]",
739
+ summary: "print gateway entries for other agents",
740
+ flags: flagsOf(CONFIG_FLAGS),
741
+ run: config,
742
+ },
743
+ import: {
744
+ synopsis: "[--write] [--move-secrets] [--force]",
745
+ summary: "draft mcp.toml from your agent configs",
746
+ flags: flagsOf(IMPORT_FLAGS),
747
+ run: importCmd,
748
+ },
749
+ install: {
750
+ synopsis: "[server...] [--dry-run] [--allow-scripts]",
751
+ summary: "install packages at exact versions",
752
+ args: ["server"],
753
+ flags: flagsOf(INSTALL_FLAGS),
754
+ run: install,
755
+ },
756
+ refresh: { synopsis: "[server...] [--dry-run]", summary: "make mcpd relearn tool lists", args: ["server"], flags: flagsOf(REFRESH_FLAGS), run: refresh },
757
+ doctor: { synopsis: "[--json]", summary: "find servers that bypass the gateway", flags: flagsOf(DOCTOR_FLAGS), run: doctor },
758
+ login: {
759
+ synopsis: "<server> [--profile <p>] [--scope <s>] [--no-browser] [--dry-run] [--json]",
760
+ summary: "log mcpd in to a remote OAuth server, once per variant",
761
+ args: ["server"],
762
+ flags: flagsOf(LOGIN_FLAGS),
763
+ details: 'For servers declared with auth = "oauth" in mcp.toml. mcpd keeps the tokens in the secret store\n(Keychain or Secret Service) and refreshes them; agents reach the server through mcpd.\n--profile logs in the variant of that profile ([server.<name>.variant.<profile>]); without one,\nthe login serves every profile that has no variant of its own.',
764
+ run: async (rest, io) => (await import("./mcp-oauth.js")).login(rest, io),
765
+ },
766
+ logout: {
767
+ synopsis: "<server> [--profile <p> | --all] [--no-revoke] [--dry-run]",
768
+ summary: "forget an OAuth login and revoke its token",
769
+ args: ["server"],
770
+ flags: flagsOf(LOGOUT_FLAGS),
771
+ run: async (rest, io) => (await import("./mcp-oauth.js")).logout(rest, io),
772
+ },
773
+ log: {
774
+ synopsis: "[-f] [-n N] [--server S] [--profile P] [--json]",
775
+ summary: "tool calls mcpd relayed (no arguments or results)",
776
+ flags: flagsOf(LOG_FLAGS),
777
+ details: "One line per tool call: time, outcome, duration, server, tool, profile, agent and sizes.\n-f keeps printing new calls; --json prints one JSON record per line.\nTurn the log off with call_log = false under [mcpd] in config.toml.",
778
+ run: async (rest, io) => (await import("./mcp-observe.js")).log(rest, io),
779
+ },
780
+ top: {
781
+ synopsis: "[--once] [--json]",
782
+ summary: "memory, sessions and calls of each running server",
783
+ flags: flagsOf(TOP_FLAGS),
784
+ details: "Refreshes every 2 seconds in a terminal (Ctrl-C quits); prints one snapshot otherwise.",
785
+ run: async (rest, io) => (await import("./mcp-observe.js")).top(rest, io),
786
+ },
787
+ savings: {
788
+ synopsis: "[--json]",
789
+ summary: "memory mcpd saves compared with no gateway",
790
+ flags: flagsOf(SAVINGS_FLAGS),
791
+ details: "Compares mcpd plus its servers now with an estimate where each live agent session\nstarts its own copy of every stdio server its profile uses.",
792
+ run: async (rest, io) => (await import("./mcp-observe.js")).savings(rest, io),
793
+ },
794
+ daemon: {
795
+ synopsis: "<start|stop|restart|status|logs>",
796
+ summary: "the gateway daemon (same as turno mcpd)",
797
+ args: ["any"],
798
+ ownHelp: true,
799
+ run: async (rest, io) => (await import("./mcpd.js")).command.run(rest, io),
800
+ },
801
+ token: {
802
+ synopsis: "rotate [--dry-run]",
803
+ summary: "replace the gateway token, then run turno mcp sync",
804
+ args: ["any"],
805
+ flags: ["--dry-run"],
806
+ ownHelp: true,
807
+ run: async (rest, io) => (await import("./mcpd.js")).tokenCommand.run(rest, io),
348
808
  },
349
809
  };
810
+ export const command = group("mcp", "MCP servers behind the lazy gateway, and the gateway daemon itself", SUBS, {
811
+ fallback: "list",
812
+ footer: `config prints entries for ${SNIPPET_AGENTS.join(", ")}.
813
+ import reads ~/.claude.json, .mcp.json, ~/.codex, ~/.cursor and ~/.copilot.
814
+ It only previews, with secrets hidden, until --write.
815
+ Docs: docs/mcp.md in the turno repository.`,
816
+ });
817
+ import { isObject, readJsonFile } from "../../core/fsutil.js";
350
818
  //# sourceMappingURL=mcp.js.map