turno-cli 0.2.0 → 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 (112) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.md +127 -39
  3. package/dist/accounts/audit.js +27 -15
  4. package/dist/accounts/builtin.js +35 -7
  5. package/dist/accounts/delegate.js +30 -7
  6. package/dist/accounts/policy.js +4 -2
  7. package/dist/accounts/registry.js +3 -1
  8. package/dist/agents/adapter.js +22 -0
  9. package/dist/agents/claude.js +54 -3
  10. package/dist/agents/codex.js +94 -6
  11. package/dist/agents/copilot.js +19 -2
  12. package/dist/agents/cursor.js +19 -2
  13. package/dist/agents/index.js +1 -1
  14. package/dist/agents/snippets.js +37 -10
  15. package/dist/cli/args.js +32 -15
  16. package/dist/cli/commands/accounts.js +29 -7
  17. package/dist/cli/commands/auto.js +50 -12
  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 +159 -59
  22. package/dist/cli/commands/complete.js +13 -3
  23. package/dist/cli/commands/completion.js +4 -0
  24. package/dist/cli/commands/config.js +90 -13
  25. package/dist/cli/commands/demo.js +36 -7
  26. package/dist/cli/commands/doctor.js +170 -36
  27. package/dist/cli/commands/identity.js +99 -12
  28. package/dist/cli/commands/init.js +42 -10
  29. package/dist/cli/commands/limit.js +65 -9
  30. package/dist/cli/commands/mcp-call.js +240 -0
  31. package/dist/cli/commands/mcp-oauth.js +33 -6
  32. package/dist/cli/commands/mcp-observe.js +128 -23
  33. package/dist/cli/commands/mcp-share.js +201 -0
  34. package/dist/cli/commands/mcp.js +203 -42
  35. package/dist/cli/commands/mcpd.js +76 -12
  36. package/dist/cli/commands/open.js +26 -3
  37. package/dist/cli/commands/profile.js +212 -30
  38. package/dist/cli/commands/resolve.js +8 -1
  39. package/dist/cli/commands/run.js +24 -4
  40. package/dist/cli/commands/secret.js +23 -38
  41. package/dist/cli/commands/session.js +16 -5
  42. package/dist/cli/commands/sessions.js +7 -1
  43. package/dist/cli/commands/setup.js +83 -11
  44. package/dist/cli/commands/status.js +67 -15
  45. package/dist/cli/commands/statusline.js +7 -2
  46. package/dist/cli/commands/ui.js +17 -5
  47. package/dist/cli/commands/undo.js +39 -7
  48. package/dist/cli/commands/uninstall.js +24 -5
  49. package/dist/cli/commands/upgrade.js +113 -76
  50. package/dist/cli/commands/usage.js +11 -10
  51. package/dist/cli/commands/version.js +20 -8
  52. package/dist/cli/commands/which.js +5 -3
  53. package/dist/cli/diagnostics.js +184 -0
  54. package/dist/cli/exit.js +65 -0
  55. package/dist/cli/group.js +20 -8
  56. package/dist/cli/help.js +6 -1
  57. package/dist/cli/hints.js +30 -0
  58. package/dist/cli/io.js +24 -8
  59. package/dist/cli/launch.js +31 -2
  60. package/dist/cli/launchers.js +25 -10
  61. package/dist/cli/main.js +52 -18
  62. package/dist/cli/optional.js +144 -0
  63. package/dist/cli/output.js +123 -0
  64. package/dist/cli/picker.js +17 -5
  65. package/dist/cli/registry.js +20 -2
  66. package/dist/cli/safe.js +87 -0
  67. package/dist/cli/secret-input.js +63 -0
  68. package/dist/cli/security.js +31 -9
  69. package/dist/cli/style.js +35 -5
  70. package/dist/cli/topics.js +142 -0
  71. package/dist/core/config.js +39 -3
  72. package/dist/core/fsutil.js +2 -10
  73. package/dist/core/journal.js +19 -11
  74. package/dist/core/manifest.js +28 -1
  75. package/dist/core/paths.js +6 -112
  76. package/dist/core/profiles.js +28 -8
  77. package/dist/core/resolve.js +13 -3
  78. package/dist/core/secrets.js +4 -154
  79. package/dist/core/state-file.js +107 -0
  80. package/dist/core/update.js +14 -11
  81. package/dist/core/version.js +57 -10
  82. package/dist/demo/server.js +10 -2
  83. package/dist/mcpd/cache.js +6 -7
  84. package/dist/mcpd/calllog.js +10 -9
  85. package/dist/mcpd/client-names.js +8 -13
  86. package/dist/mcpd/connectors.js +42 -3
  87. package/dist/mcpd/daemon.js +29 -8
  88. package/dist/mcpd/folder-sets.js +5 -2
  89. package/dist/mcpd/gateway.js +57 -29
  90. package/dist/mcpd/health.js +69 -25
  91. package/dist/mcpd/importer.js +106 -9
  92. package/dist/mcpd/instances.js +59 -31
  93. package/dist/mcpd/jsonrpc.js +3 -1
  94. package/dist/mcpd/middleware.js +144 -0
  95. package/dist/mcpd/modern.js +57 -19
  96. package/dist/mcpd/oauth.js +71 -17
  97. package/dist/mcpd/peerpid.js +15 -3
  98. package/dist/mcpd/pressure.js +4 -1
  99. package/dist/mcpd/rss.js +34 -19
  100. package/dist/mcpd/service.js +28 -4
  101. package/dist/mcpd/share.js +217 -0
  102. package/dist/mcpd/state.js +16 -16
  103. package/dist/mcpd/sync.js +22 -12
  104. package/dist/mcpd/systemd.js +4 -1
  105. package/dist/mcpd/tokens.js +4 -8
  106. package/dist/mcpd/upstream.js +12 -5
  107. package/dist/statusline/cost.js +17 -4
  108. package/dist/statusline/input.js +15 -3
  109. package/dist/ui/fonts.js +1 -1
  110. package/dist/ui/settings.js +6 -1
  111. package/npm-shrinkwrap.json +12 -3
  112. package/package.json +7 -6
@@ -16,7 +16,7 @@ import { describeOwner, peerPid, portOwner } from "./peerpid.js";
16
16
  import { memoryPressureProbe } from "./pressure.js";
17
17
  import { RssSampler } from "./rss.js";
18
18
  import { pidAlive } from "../core/fsutil.js";
19
- import { answersAsMcpd, daemonFiles, ensureToken, isMcpdProcess, loadConfigSafe, readLock, readToken } from "./state.js";
19
+ import { answersAsMcpd, daemonFiles, ensureToken, isMcpdProcess, loadConfigSafe, readLock, readToken, } from "./state.js";
20
20
  export { daemonFiles, loadConfigSafe, masterToken, mcpdPort, readStartError, readToken, rotateToken } from "./state.js";
21
21
  /** Another mcpd already holds the lock or answers on the port. Not a failure for a supervisor. */
22
22
  export class AlreadyRunningError extends Error {
@@ -173,7 +173,18 @@ export function createLogger(file, opts = {}) {
173
173
  return log;
174
174
  }
175
175
  /** Errors a socket or the disk raises that do not leave the daemon in a bad state. */
176
- const RECOVERABLE = new Set(["EPIPE", "ECONNRESET", "ECONNABORTED", "ETIMEDOUT", "ENOSPC", "EIO", "EAGAIN", "ERR_STREAM_DESTROYED", "ERR_STREAM_WRITE_AFTER_END", "ERR_STREAM_PREMATURE_CLOSE"]);
176
+ const RECOVERABLE = new Set([
177
+ "EPIPE",
178
+ "ECONNRESET",
179
+ "ECONNABORTED",
180
+ "ETIMEDOUT",
181
+ "ENOSPC",
182
+ "EIO",
183
+ "EAGAIN",
184
+ "ERR_STREAM_DESTROYED",
185
+ "ERR_STREAM_WRITE_AFTER_END",
186
+ "ERR_STREAM_PREMATURE_CLOSE",
187
+ ]);
177
188
  /**
178
189
  * For the daemon process only (not for tests that start mcpd in process): log unhandled
179
190
  * rejections and recoverable exceptions and keep serving; on anything else log it, stop
@@ -280,12 +291,16 @@ export async function startDaemon(opts = {}) {
280
291
  const env = opts.env ?? process.env;
281
292
  const p = paths(env);
282
293
  const files = daemonFiles(env);
283
- const log = createLogger(files.log, { env, toStdout: Boolean(opts.logToStdout), ...(opts.logMaxBytes ? { maxBytes: opts.logMaxBytes } : {}) });
294
+ const log = createLogger(files.log, {
295
+ env,
296
+ toStdout: Boolean(opts.logToStdout),
297
+ ...(opts.logMaxBytes ? { maxBytes: opts.logMaxBytes } : {}),
298
+ });
284
299
  const { config, error: firstConfigError } = loadConfigSafe(env);
285
300
  let configError = firstConfigError;
286
301
  if (configError)
287
302
  log(`config.toml is invalid, using defaults: ${configError}`);
288
- // Folder server sets (ADR 0031): the last good [[projects]] rules, reloaded with config.toml.
303
+ // Folder server sets: the last good [[projects]] rules, reloaded with config.toml.
289
304
  let folderRules = config.projects;
290
305
  const wanted = opts.port ?? config.mcpd.port;
291
306
  const fail = async (err) => {
@@ -319,11 +334,10 @@ export async function startDaemon(opts = {}) {
319
334
  logsDir: p.logsDir,
320
335
  vars: env,
321
336
  builtins: await loadBuiltins(),
322
- baseEnv: Object.fromEntries(["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "TMPDIR"].flatMap((k) => (env[k] ? [[k, env[k]]] : []))),
337
+ baseEnv: Object.fromEntries(["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "TMPDIR"].flatMap((k) => env[k] ? [[k, env[k]]] : [])),
323
338
  }),
324
339
  home: p.home,
325
340
  log,
326
- onCall: (e) => calls?.record(e),
327
341
  pressure: memoryPressureProbe(),
328
342
  idleUnderPressure: config.mcpd.idleUnderPressure,
329
343
  });
@@ -336,13 +350,18 @@ export async function startDaemon(opts = {}) {
336
350
  folderRules: () => folderRules,
337
351
  home: p.home,
338
352
  clientNames: new ClientNames(join(p.state, "mcpd-clients.json"), pidAlive),
353
+ callLog: () => (calls ? (e) => calls?.record(e) : undefined),
339
354
  ...(config.mcpd.maxRequestBody ? { maxRequestBodyBytes: config.mcpd.maxRequestBody } : {}),
340
355
  };
341
356
  const gateway = new DaemonGateway(gwOpts, () => ({
342
357
  version: packageInfo().version,
343
358
  port,
344
359
  startedAt,
345
- manifest: { source: state.source, servers: Object.keys(state.manifest.servers).length, error: state.error ?? null },
360
+ manifest: {
361
+ source: state.source,
362
+ servers: Object.keys(state.manifest.servers).length,
363
+ error: state.error ?? null,
364
+ },
346
365
  config: { error: configError ?? null, folderSets: folderRules.filter((r) => r.mcp || r.mcpDeny).length },
347
366
  callLog: { enabled: Boolean(calls) },
348
367
  serverRss: sampler.samples(),
@@ -360,7 +379,9 @@ export async function startDaemon(opts = {}) {
360
379
  const owner = await portOwner(wanted, { env });
361
380
  throw new PortBusyError(`port ${wanted} is in use by ${describeOwner(owner)}. mcpd does not move to another port, because every synced profile points at this one: free the port, or pick another with \`turno config set mcpd.port <port>\` and run \`turno mcp sync\``, wanted);
362
381
  }
363
- writeFileSync(files.lock, `${JSON.stringify({ pid: process.pid, port, startedAt })}\n`, { mode: PRIVATE_FILE_MODE });
382
+ writeFileSync(files.lock, `${JSON.stringify({ pid: process.pid, port, startedAt })}\n`, {
383
+ mode: PRIVATE_FILE_MODE,
384
+ });
364
385
  ensurePrivateDir(dirname(p.mcpdPort), env);
365
386
  atomicWrite(p.mcpdPort, `${port}\n`, PRIVATE_FILE_MODE);
366
387
  writeStartError(env, undefined);
@@ -3,7 +3,7 @@ import { realpath } from "node:fs/promises";
3
3
  import { promisify } from "node:util";
4
4
  const run = promisify(execFile);
5
5
  /**
6
- * The folders a session's server set is matched against (ADR 0031): the session folder, and
6
+ * The folders a session's server set is matched against: the session folder, and
7
7
  * for a git worktree the main repository it belongs to, the same candidates `turno auto` uses
8
8
  * for profile rules. Async (mcpd must not block on git) and cached for 10 s, because an agent
9
9
  * opens one session per server at the same time.
@@ -23,7 +23,10 @@ async function compute(cwd) {
23
23
  const own = await realpath(cwd).catch(() => cwd);
24
24
  const out = [own];
25
25
  try {
26
- const { stdout } = await run("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf8", timeout: 3000 });
26
+ const { stdout } = await run("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
27
+ encoding: "utf8",
28
+ timeout: 3000,
29
+ });
27
30
  const common = stdout.trim();
28
31
  if (common.endsWith("/.git")) {
29
32
  const main = await realpath(common.slice(0, -5)).catch(() => common.slice(0, -5));
@@ -3,13 +3,14 @@ import { createServer } from "node:http";
3
3
  import { isAbsolute } from "node:path";
4
4
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
5
  import { LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS } from "@modelcontextprotocol/sdk/types.js";
6
- import { filtersTools, servesProfile, toolAllowed, toolFilterFor } from "../core/manifest.js";
6
+ import { servesProfile, toolAllowed } from "../core/manifest.js";
7
7
  import { tildify } from "../core/paths.js";
8
8
  import { folderMcpSet, mcpSetAllows } from "../core/resolve.js";
9
9
  import { cleanAgentName } from "./calllog.js";
10
10
  import { folderRoots } from "./folder-sets.js";
11
- import { isDirectory, processCwd, projectRoot, scopeOf } from "./instances.js";
12
- import { ErrorCode, isNotification, isRequest, isResponse, rpcError, toResponse } from "./jsonrpc.js";
11
+ import { isDirectory, processCwd, projectRoot, scopeOf, } from "./instances.js";
12
+ import { ErrorCode, isNotification, isRequest, isResponse, rpcError, toResponse, } from "./jsonrpc.js";
13
+ import { createCallPipeline, toolFilterOf } from "./middleware.js";
13
14
  import { StatelessFront, isInitialize, readJsonBody, wantsModern } from "./modern.js";
14
15
  import { tokenProfile } from "./tokens.js";
15
16
  const DEFAULT_MAX_REQUEST_BODY = 32 * 1024 * 1024;
@@ -37,7 +38,9 @@ function safeEqual(a, b) {
37
38
  return ab.length === bb.length && timingSafeEqual(ab, bb);
38
39
  }
39
40
  function negotiateVersion(requested) {
40
- return typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;
41
+ return typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
42
+ ? requested
43
+ : LATEST_PROTOCOL_VERSION;
41
44
  }
42
45
  /**
43
46
  * The session folder from the request headers. `X-Turno-Cwd-B64` (base64url of the UTF-8
@@ -84,7 +87,7 @@ const EMPTY_LISTS = {
84
87
  "resources/templates/list": "resourceTemplates",
85
88
  };
86
89
  /**
87
- * What a session gets for a server its folder's set leaves out (ADR 0031): an initialize with
90
+ * What a session gets for a server its folder's set leaves out: an initialize with
88
91
  * no capabilities and an instructions line that says why, empty lists, and an error naming
89
92
  * the rule for anything else. The session stays open, so the agent shows the server as
90
93
  * connected with nothing in it rather than as a failure it may retry.
@@ -134,7 +137,9 @@ class ClientSession {
134
137
  }
135
138
  notify(method, params, related) {
136
139
  const m = { jsonrpc: "2.0", method, ...(params ? { params } : {}) };
137
- void this.transport.send(m, related !== undefined ? { relatedRequestId: related } : undefined).catch(() => { });
140
+ void this.transport
141
+ .send(m, related !== undefined ? { relatedRequestId: related } : undefined)
142
+ .catch(() => { });
138
143
  }
139
144
  request(method, params, related) {
140
145
  const id = `s${this.nextId++}`;
@@ -145,7 +150,9 @@ class ClientSession {
145
150
  }, this.gw.clientRequestTimeoutMs);
146
151
  this.waiting.set(id, { resolve, timer });
147
152
  const m = { jsonrpc: "2.0", id, method, ...(params ? { params } : {}) };
148
- this.transport.send(m, related !== undefined ? { relatedRequestId: related } : undefined).catch((err) => {
153
+ this.transport
154
+ .send(m, related !== undefined ? { relatedRequestId: related } : undefined)
155
+ .catch((err) => {
149
156
  clearTimeout(timer);
150
157
  this.waiting.delete(id);
151
158
  resolve(rpcError(ErrorCode.Internal, `cannot reach client: ${err.message}`));
@@ -187,10 +194,12 @@ class ClientSession {
187
194
  const state = { cancelled: false };
188
195
  this.handling.set(id, state);
189
196
  try {
190
- // Outside the folder's server set (ADR 0031): answer from mcpd, never start the server.
197
+ // Outside the folder's server set: answer from mcpd, never start the server.
191
198
  const hidden = this.gw.hiddenBySet(this);
192
199
  if (hidden) {
193
- const agent = method === "initialize" ? cleanAgentName(m.params?.clientInfo?.name) : undefined;
200
+ const agent = method === "initialize"
201
+ ? cleanAgentName(m.params?.clientInfo?.name)
202
+ : undefined;
194
203
  if (agent)
195
204
  this.gw.nameClient(this, agent);
196
205
  this.reply(id, hiddenAnswer(m, this.ctx.serverName, hidden));
@@ -232,12 +241,9 @@ class ClientSession {
232
241
  return;
233
242
  }
234
243
  if (method === "tools/call") {
235
- const filter = this.gw.toolFilter(this.ctx);
236
- const tool = typeof m.params?.name === "string" ? m.params.name : "";
237
- if (filter && !toolAllowed(filter, tool)) {
238
- this.reply(id, rpcError(ErrorCode.InvalidParams, `tool ${tool} of ${this.ctx.serverName} is not available to profile ${this.ctx.profile ?? "default"} (tools.allow / tools.deny in mcp.toml)`));
239
- return;
240
- }
244
+ // The call middleware: tool filter, call log, session id, then the relay.
245
+ this.reply(id, await this.gw.calls.call(this, m.params ?? {}, id, () => state.cancelled));
246
+ return;
241
247
  }
242
248
  if (method === "logging/setLevel" && !manager.existing(this)) {
243
249
  this.reply(id, { result: {} });
@@ -249,7 +255,9 @@ class ClientSession {
249
255
  this.reply(id, rpcError(ErrorCode.InvalidParams, `${method} needs a uri`));
250
256
  return;
251
257
  }
252
- this.reply(id, method === "resources/subscribe" ? await manager.subscribe(this, uri, id) : await manager.unsubscribe(this, uri, id));
258
+ this.reply(id, method === "resources/subscribe"
259
+ ? await manager.subscribe(this, uri, id)
260
+ : await manager.unsubscribe(this, uri, id));
253
261
  return;
254
262
  }
255
263
  this.reply(id, await manager.forward(this, method, m.params, id, () => state.cancelled));
@@ -295,19 +303,28 @@ class ClientSession {
295
303
  export class Gateway {
296
304
  opts;
297
305
  manager;
306
+ /** Every tools/call of both protocol paths goes through it. */
307
+ calls;
298
308
  clientRequestTimeoutMs;
299
309
  sessions = new Map();
300
310
  recreating = new Map();
301
311
  http;
302
- /** MCP 2026-07-28 stateless requests (ADR 0028). */
312
+ /** MCP 2026-07-28 stateless requests. */
303
313
  front;
304
314
  constructor(opts) {
305
315
  this.opts = opts;
306
316
  this.manager = opts.manager;
307
317
  this.manager.useManifest(opts.manifest);
308
318
  this.clientRequestTimeoutMs = opts.clientRequestTimeoutMs ?? 10 * 60_000;
319
+ this.calls = createCallPipeline({
320
+ manager: this.manager,
321
+ manifest: opts.manifest,
322
+ ...(opts.callLog ? { callLog: opts.callLog } : {}),
323
+ ...(opts.callStages ? { stages: opts.callStages } : {}),
324
+ });
309
325
  this.front = new StatelessFront({
310
326
  manager: this.manager,
327
+ calls: this.calls,
311
328
  toolFilter: (ctx) => this.toolFilter(ctx),
312
329
  context: (req, name, profile) => this.sessionContext(req, name, profile),
313
330
  capabilities: announcedCapabilities,
@@ -380,13 +397,16 @@ export class Gateway {
380
397
  }
381
398
  /**
382
399
  * Call before a config.toml or mcp.toml change: notes what each open session sees (its
383
- * folder's server set, ADR 0031, and its tool filter, ADR 0023). The returned function, called
400
+ * folder's server set and its tool filter). The returned function, called
384
401
  * after the change, sends list_changed to the sessions whose view changed, so their agents
385
402
  * list again without reconnecting, and returns how many it told. Stateless 2026-07-28 clients
386
403
  * are not told: they see the change when their list results expire (`ttlMs`).
387
404
  */
388
405
  beforeViewChange() {
389
- const view = (s) => ({ hidden: this.hiddenBySet(s) !== undefined, filter: JSON.stringify(this.toolFilter(s.ctx) ?? null) });
406
+ const view = (s) => ({
407
+ hidden: this.hiddenBySet(s) !== undefined,
408
+ filter: JSON.stringify(this.toolFilter(s.ctx) ?? null),
409
+ });
390
410
  const before = new Map([...this.sessions.values()].map((s) => [s, view(s)]));
391
411
  return () => {
392
412
  let told = 0;
@@ -410,11 +430,7 @@ export class Gateway {
410
430
  }
411
431
  /** The tool filter for a session, or undefined when its server filters nothing. */
412
432
  toolFilter(ctx) {
413
- const server = this.opts.manifest().servers[ctx.serverName];
414
- if (!server)
415
- return undefined;
416
- const f = toolFilterFor(server, ctx.profile);
417
- return filtersTools(f) ? f : undefined;
433
+ return toolFilterOf(this.opts.manifest(), ctx);
418
434
  }
419
435
  /**
420
436
  * Record the agent name a session gave in initialize. Sessions of the same process that mcpd
@@ -431,7 +447,7 @@ export class Gateway {
431
447
  this.opts.clientNames?.set(pid, name);
432
448
  }
433
449
  /**
434
- * Why a session's folder hides its server (ADR 0031), or undefined when the server is
450
+ * Why a session's folder hides its server, or undefined when the server is
435
451
  * shown. Read on every use, so a changed config.toml applies to open sessions on their next
436
452
  * list or call. A session whose folder mcpd could not learn is never hidden.
437
453
  */
@@ -512,7 +528,7 @@ export class Gateway {
512
528
  json(res, 403, { error: `session ${sid} belongs to another profile` });
513
529
  return;
514
530
  }
515
- // MCP 2026-07-28: the version header names a newer revision (ADR 0028).
531
+ // MCP 2026-07-28: the version header names a newer revision.
516
532
  let parsed;
517
533
  if (wantsModern(req)) {
518
534
  const body = await readJsonBody(req, this.opts.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY);
@@ -525,7 +541,11 @@ export class Gateway {
525
541
  return;
526
542
  }
527
543
  if (sid) {
528
- json(res, 400, { jsonrpc: "2.0", id: null, error: { code: ErrorCode.InvalidRequest, message: "initialize cannot carry an Mcp-Session-Id" } });
544
+ json(res, 400, {
545
+ jsonrpc: "2.0",
546
+ id: null,
547
+ error: { code: ErrorCode.InvalidRequest, message: "initialize cannot carry an Mcp-Session-Id" },
548
+ });
529
549
  return;
530
550
  }
531
551
  // A dual-era client asking for a 2025-era session: the SDK takes it from here.
@@ -640,7 +660,10 @@ export class Gateway {
640
660
  s.id = fixedId;
641
661
  ctx.sessionId = fixedId;
642
662
  // A rebuilt session never sees initialize: take the name its process gave before.
643
- const known = ctx.pid ? ([...this.sessions.values()].find((o) => o.ctx.pid === ctx.pid && o.ctx.clientName)?.ctx.clientName ?? this.opts.clientNames?.get(ctx.pid)) : undefined;
663
+ const known = ctx.pid
664
+ ? ([...this.sessions.values()].find((o) => o.ctx.pid === ctx.pid && o.ctx.clientName)?.ctx.clientName ??
665
+ this.opts.clientNames?.get(ctx.pid))
666
+ : undefined;
644
667
  if (known)
645
668
  ctx.clientName = known;
646
669
  this.sessions.set(fixedId, s);
@@ -654,7 +677,12 @@ export class Gateway {
654
677
  const by = new Map();
655
678
  for (const s of [...this.sessions.values(), ...this.front.list()]) {
656
679
  const key = s.ctx.pid ? `pid:${s.ctx.pid}` : `sid:${s.id}`;
657
- const a = by.get(key) ?? { pid: s.ctx.pid ?? null, profile: s.ctx.profile ?? null, agent: s.ctx.clientName ?? null, servers: [] };
680
+ const a = by.get(key) ?? {
681
+ pid: s.ctx.pid ?? null,
682
+ profile: s.ctx.profile ?? null,
683
+ agent: s.ctx.clientName ?? null,
684
+ servers: [],
685
+ };
658
686
  if (!a.servers.includes(s.ctx.serverName))
659
687
  a.servers.push(s.ctx.serverName);
660
688
  a.agent ??= s.ctx.clientName ?? null;
@@ -5,6 +5,7 @@ import { loadConfig } from "../core/config.js";
5
5
  import { paths, tildify } from "../core/paths.js";
6
6
  import { agentOf, listProfiles } from "../core/profiles.js";
7
7
  import { profileTokenFile, tokenProfile } from "./tokens.js";
8
+ import { isRecord, readState } from "../core/state-file.js";
8
9
  const startFix = {
9
10
  label: "turno mcp daemon start",
10
11
  run: async (io) => (await import("../cli/commands/mcpd.js")).installDaemonService(io),
@@ -31,14 +32,26 @@ async function serviceChecks(env) {
31
32
  if (!program.length)
32
33
  out.push({ level: "fail", text: `mcpd: ${shown} has no program to run`, fix: startFix });
33
34
  else if (missing.length)
34
- out.push({ level: "fail", text: `mcpd: ${shown} runs ${missing.map((m) => tildify(m, env)).join(", ")}, which no longer exists`, fix: startFix });
35
+ out.push({
36
+ level: "fail",
37
+ text: `mcpd: ${shown} runs ${missing.map((m) => tildify(m, env)).join(", ")}, which no longer exists`,
38
+ fix: startFix,
39
+ });
35
40
  else if (program.some((a) => a.startsWith("/") && isUnstablePath(a))) {
36
- out.push({ level: "warn", text: `mcpd: ${shown} runs a versioned path (${tildify(program[0], env)}) that breaks when that version is removed`, fix: startFix });
41
+ out.push({
42
+ level: "warn",
43
+ text: `mcpd: ${shown} runs a versioned path (${tildify(program[0], env)}) that breaks when that version is removed`,
44
+ fix: startFix,
45
+ });
37
46
  }
38
47
  else
39
48
  out.push({ level: "ok", text: `mcpd: ${backend.noun} ${shown}` });
40
49
  if (backend.kind === "launchd" && /<key>ProcessType<\/key>\s*<string>Background<\/string>/.test(text)) {
41
- out.push({ level: "warn", text: "mcpd: the LaunchAgent runs as a Background process, which macOS throttles", fix: startFix });
50
+ out.push({
51
+ level: "warn",
52
+ text: "mcpd: the LaunchAgent runs as a Background process, which macOS throttles",
53
+ fix: startFix,
54
+ });
42
55
  }
43
56
  return out;
44
57
  }
@@ -48,12 +61,19 @@ function tokenCheck(env) {
48
61
  const st = statSync(file);
49
62
  const uid = process.getuid?.();
50
63
  if (uid !== undefined && st.uid !== uid)
51
- return { level: "fail", text: `mcpd: ${tildify(file, env)} belongs to uid ${st.uid}`, hint: `sudo chown "$(id -un)" ${tildify(file, env)}` };
64
+ return {
65
+ level: "fail",
66
+ text: `mcpd: ${tildify(file, env)} belongs to uid ${st.uid}`,
67
+ hint: `sudo chown "$(id -un)" ${tildify(file, env)}`,
68
+ };
52
69
  if (st.mode & 0o077) {
53
70
  return {
54
71
  level: "warn",
55
72
  text: `mcpd: ${tildify(file, env)} is readable by others (mode ${(st.mode & 0o777).toString(8)})`,
56
- fix: { label: `chmod 600 ${tildify(file, env)}`, run: async () => (await import("./state.js")).readToken(env, () => { }) },
73
+ fix: {
74
+ label: `chmod 600 ${tildify(file, env)}`,
75
+ run: async () => (await import("./state.js")).readToken(env, () => { }),
76
+ },
57
77
  };
58
78
  }
59
79
  return undefined;
@@ -69,7 +89,11 @@ async function portChecks(env) {
69
89
  const port = mcpdPort(env);
70
90
  const token = readToken(env, () => { });
71
91
  if (!token) {
72
- out.push({ level: "info", text: `mcpd: no token at ${tildify(paths(env).mcpdToken, env)}, so it has not started yet`, hint: "turno mcp daemon start" });
92
+ out.push({
93
+ level: "info",
94
+ text: `mcpd: no token at ${tildify(paths(env).mcpdToken, env)}, so it has not started yet`,
95
+ hint: "turno mcp daemon start",
96
+ });
73
97
  return out;
74
98
  }
75
99
  const ours = await answersAsMcpd(port, token);
@@ -77,15 +101,26 @@ async function portChecks(env) {
77
101
  const uid = process.getuid?.();
78
102
  if (ours) {
79
103
  if (owner?.uid !== undefined && uid !== undefined && owner.uid !== uid) {
80
- out.push({ level: "fail", text: `mcpd: port ${port} answers with your token but belongs to uid ${owner.uid}`, hint: "turno mcp token rotate" });
104
+ out.push({
105
+ level: "fail",
106
+ text: `mcpd: port ${port} answers with your token but belongs to uid ${owner.uid}`,
107
+ hint: "turno mcp token rotate",
108
+ });
81
109
  }
82
110
  else if (owner?.pid !== undefined && ours.pid !== undefined && owner.pid !== ours.pid) {
83
- out.push({ level: "warn", text: `mcpd: port ${port} is held by pid ${owner.pid}, but mcpd reports pid ${ours.pid}`, hint: "turno mcp daemon restart" });
111
+ out.push({
112
+ level: "warn",
113
+ text: `mcpd: port ${port} is held by pid ${owner.pid}, but mcpd reports pid ${ours.pid}`,
114
+ hint: "turno mcp daemon restart",
115
+ });
84
116
  }
85
117
  else
86
118
  out.push({ level: "ok", text: `mcpd: reachable on port ${port}${ours.pid ? ` (pid ${ours.pid})` : ""}` });
87
119
  try {
88
- const res = await fetch(`http://127.0.0.1:${port}/status`, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(2000) });
120
+ const res = await fetch(`http://127.0.0.1:${port}/status`, {
121
+ headers: { authorization: `Bearer ${token}` },
122
+ signal: AbortSignal.timeout(2000),
123
+ });
89
124
  const s = (await res.json());
90
125
  if (s.manifest?.error) {
91
126
  out.push({
@@ -95,7 +130,11 @@ async function portChecks(env) {
95
130
  });
96
131
  }
97
132
  if (s.config?.error)
98
- out.push({ level: "warn", text: `mcpd: config.toml is invalid, mcpd uses defaults: ${s.config.error}`, hint: "turno config edit" });
133
+ out.push({
134
+ level: "warn",
135
+ text: `mcpd: config.toml is invalid, mcpd uses defaults: ${s.config.error}`,
136
+ hint: "turno config edit",
137
+ });
99
138
  }
100
139
  catch {
101
140
  /* answered a moment ago; nothing more to add */
@@ -116,19 +155,26 @@ async function portChecks(env) {
116
155
  out.push({ level: "info", text: `mcpd: config.toml says port ${configured}, the last mcpd used ${port}` });
117
156
  const e = readStartError(env);
118
157
  if (e)
119
- out.push({ level: "warn", text: `mcpd: last start failed at ${e.at}: ${e.message}`, hint: "turno mcp daemon start" });
158
+ out.push({
159
+ level: "warn",
160
+ text: `mcpd: last start failed at ${e.at}: ${e.message}`,
161
+ hint: "turno mcp daemon start",
162
+ });
120
163
  const lock = readLock(env);
121
164
  if (lock)
122
- out.push({ level: "info", text: `mcpd: stale lock from pid ${lock.pid} in ${tildify(daemonFiles(env).lock, env)} (the next start clears it)` });
165
+ out.push({
166
+ level: "info",
167
+ text: `mcpd: stale lock from pid ${lock.pid} in ${tildify(daemonFiles(env).lock, env)} (the next start clears it)`,
168
+ });
123
169
  return out;
124
170
  }
125
171
  async function syncedPortCheck(env) {
126
- const { readManaged } = await import("./sync.js");
172
+ const { peekManaged } = await import("./sync.js");
127
173
  const { mcpdPort } = await import("./state.js");
128
174
  const port = mcpdPort(env);
129
175
  const off = [];
130
176
  const seen = new Set();
131
- for (const file of Object.keys(readManaged(paths(env).mcpdManaged))) {
177
+ for (const file of Object.keys(peekManaged(paths(env).mcpdManaged))) {
132
178
  let text;
133
179
  try {
134
180
  text = readFileSync(file, "utf8");
@@ -159,15 +205,9 @@ const PROFILE_BEARER = /Bearer (tp1\.[a-z0-9][a-z0-9_-]*\.[A-Za-z0-9_-]{43})/g;
159
205
  */
160
206
  function syncedFiles(env) {
161
207
  const files = new Set();
162
- try {
163
- const managed = JSON.parse(readFileSync(paths(env).mcpdManaged, "utf8"));
164
- if (managed && typeof managed === "object")
165
- for (const f of Object.keys(managed))
166
- files.add(f);
167
- }
168
- catch {
169
- /* no mcp-managed.json */
170
- }
208
+ // No mcp-managed.json, or one that cannot be used: the profiles' configs are still checked.
209
+ for (const f of Object.keys(readState(paths(env).mcpdManaged, isRecord) ?? {}))
210
+ files.add(f);
171
211
  try {
172
212
  const config = loadConfig(env);
173
213
  for (const name of listProfiles(config, env))
@@ -180,7 +220,7 @@ function syncedFiles(env) {
180
220
  return [...files];
181
221
  }
182
222
  /**
183
- * Synced configs and launcher token files that mcpd would refuse (ADR 0023): configs written
223
+ * Synced configs and launcher token files that mcpd would refuse: configs written
184
224
  * before per-profile tokens still carry the master token, and every derived token dies with a
185
225
  * `turno mcp token rotate`. Both are fixed by `turno mcp sync`. Works without mcp-managed.json.
186
226
  * Never prints a token.
@@ -252,7 +292,11 @@ export async function mcpdChecks(env) {
252
292
  out.push(...(await serviceChecks(env)));
253
293
  }
254
294
  catch (err) {
255
- out.push({ level: "warn", text: `mcpd: cannot read the service file: ${err.message}`, hint: "turno mcp daemon start" });
295
+ out.push({
296
+ level: "warn",
297
+ text: `mcpd: cannot read the service file: ${err.message}`,
298
+ hint: "turno mcp daemon start",
299
+ });
256
300
  }
257
301
  const t = tokenCheck(env);
258
302
  if (t)