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