turno-cli 0.2.0 → 0.4.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 (116) hide show
  1. package/CHANGELOG.md +266 -0
  2. package/README.md +134 -42
  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-do-session.js +170 -0
  19. package/dist/cli/commands/browser-do.js +740 -0
  20. package/dist/cli/commands/browser-flows.js +300 -0
  21. package/dist/cli/commands/browser-identity.js +952 -0
  22. package/dist/cli/commands/browser-live.js +118 -0
  23. package/dist/cli/commands/browser-session.js +102 -0
  24. package/dist/cli/commands/browser-vault.js +193 -0
  25. package/dist/cli/commands/browser.js +303 -62
  26. package/dist/cli/commands/complete.js +13 -3
  27. package/dist/cli/commands/completion.js +4 -0
  28. package/dist/cli/commands/config.js +90 -13
  29. package/dist/cli/commands/demo.js +36 -7
  30. package/dist/cli/commands/doctor.js +170 -36
  31. package/dist/cli/commands/identity.js +101 -12
  32. package/dist/cli/commands/init.js +42 -10
  33. package/dist/cli/commands/limit.js +65 -9
  34. package/dist/cli/commands/mcp-call.js +240 -0
  35. package/dist/cli/commands/mcp-oauth.js +33 -6
  36. package/dist/cli/commands/mcp-observe.js +128 -23
  37. package/dist/cli/commands/mcp-share.js +201 -0
  38. package/dist/cli/commands/mcp.js +203 -42
  39. package/dist/cli/commands/mcpd.js +76 -12
  40. package/dist/cli/commands/open.js +26 -3
  41. package/dist/cli/commands/profile.js +212 -30
  42. package/dist/cli/commands/resolve.js +8 -1
  43. package/dist/cli/commands/run.js +24 -4
  44. package/dist/cli/commands/secret.js +23 -38
  45. package/dist/cli/commands/session.js +16 -5
  46. package/dist/cli/commands/sessions.js +7 -1
  47. package/dist/cli/commands/setup.js +83 -11
  48. package/dist/cli/commands/status.js +67 -15
  49. package/dist/cli/commands/statusline.js +7 -2
  50. package/dist/cli/commands/ui.js +17 -5
  51. package/dist/cli/commands/undo.js +39 -7
  52. package/dist/cli/commands/uninstall.js +24 -5
  53. package/dist/cli/commands/upgrade.js +113 -76
  54. package/dist/cli/commands/usage.js +11 -10
  55. package/dist/cli/commands/version.js +20 -8
  56. package/dist/cli/commands/which.js +5 -3
  57. package/dist/cli/diagnostics.js +184 -0
  58. package/dist/cli/exit.js +65 -0
  59. package/dist/cli/group.js +20 -8
  60. package/dist/cli/help.js +6 -1
  61. package/dist/cli/hints.js +30 -0
  62. package/dist/cli/io.js +24 -8
  63. package/dist/cli/launch.js +31 -2
  64. package/dist/cli/launchers.js +25 -10
  65. package/dist/cli/main.js +52 -18
  66. package/dist/cli/optional.js +144 -0
  67. package/dist/cli/output.js +123 -0
  68. package/dist/cli/picker.js +17 -5
  69. package/dist/cli/registry.js +20 -2
  70. package/dist/cli/safe.js +87 -0
  71. package/dist/cli/secret-input.js +63 -0
  72. package/dist/cli/security.js +31 -9
  73. package/dist/cli/style.js +35 -5
  74. package/dist/cli/topics.js +155 -0
  75. package/dist/core/config.js +39 -3
  76. package/dist/core/fsutil.js +2 -10
  77. package/dist/core/journal.js +19 -11
  78. package/dist/core/manifest.js +28 -1
  79. package/dist/core/paths.js +6 -112
  80. package/dist/core/profiles.js +28 -8
  81. package/dist/core/resolve.js +13 -3
  82. package/dist/core/secrets.js +4 -154
  83. package/dist/core/state-file.js +107 -0
  84. package/dist/core/update.js +14 -11
  85. package/dist/core/version.js +57 -10
  86. package/dist/demo/server.js +10 -2
  87. package/dist/mcpd/cache.js +6 -7
  88. package/dist/mcpd/calllog.js +10 -9
  89. package/dist/mcpd/client-names.js +8 -13
  90. package/dist/mcpd/connectors.js +42 -3
  91. package/dist/mcpd/daemon.js +29 -8
  92. package/dist/mcpd/folder-sets.js +5 -2
  93. package/dist/mcpd/gateway.js +57 -29
  94. package/dist/mcpd/health.js +70 -26
  95. package/dist/mcpd/importer.js +106 -9
  96. package/dist/mcpd/instances.js +70 -32
  97. package/dist/mcpd/jsonrpc.js +3 -1
  98. package/dist/mcpd/middleware.js +156 -0
  99. package/dist/mcpd/modern.js +57 -19
  100. package/dist/mcpd/oauth.js +71 -17
  101. package/dist/mcpd/peerpid.js +63 -17
  102. package/dist/mcpd/pressure.js +4 -1
  103. package/dist/mcpd/rss.js +34 -19
  104. package/dist/mcpd/service.js +28 -4
  105. package/dist/mcpd/share.js +217 -0
  106. package/dist/mcpd/state.js +16 -16
  107. package/dist/mcpd/sync.js +22 -12
  108. package/dist/mcpd/systemd.js +4 -1
  109. package/dist/mcpd/tokens.js +4 -8
  110. package/dist/mcpd/upstream.js +12 -5
  111. package/dist/statusline/cost.js +17 -4
  112. package/dist/statusline/input.js +15 -3
  113. package/dist/ui/fonts.js +1 -1
  114. package/dist/ui/settings.js +6 -1
  115. package/npm-shrinkwrap.json +12 -3
  116. package/package.json +7 -6
@@ -3,7 +3,7 @@ import { toolAllowed } from "../core/manifest.js";
3
3
  import { cleanAgentName } from "./calllog.js";
4
4
  import { ErrorCode, rpcError } from "./jsonrpc.js";
5
5
  /**
6
- * MCP revision 2026-07-28 on mcpd's HTTP endpoint (ADR 0028): stateless requests that carry
6
+ * MCP revision 2026-07-28 on mcpd's HTTP endpoint: stateless requests that carry
7
7
  * their protocol version, client capabilities and identity in `_meta`, with no `initialize` and
8
8
  * no `Mcp-Session-Id`. 2025-11-25 sessions keep going through the SDK transport in gateway.ts;
9
9
  * the upstream servers are still spoken to as 2025-11-25 clients.
@@ -190,7 +190,12 @@ function sendJson(res, status, body) {
190
190
  function openSse(res) {
191
191
  if (res.headersSent)
192
192
  return;
193
- res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive", "x-accel-buffering": "no" });
193
+ res.writeHead(200, {
194
+ "content-type": "text/event-stream",
195
+ "cache-control": "no-cache",
196
+ connection: "keep-alive",
197
+ "x-accel-buffering": "no",
198
+ });
194
199
  res.flushHeaders();
195
200
  }
196
201
  function writeSse(res, m) {
@@ -235,7 +240,11 @@ class Listener {
235
240
  return;
236
241
  }
237
242
  const meta = isObject(params?._meta) ? params._meta : {};
238
- writeSse(this.res, { jsonrpc: "2.0", method, params: { ...(params ?? {}), _meta: { ...meta, [SUBSCRIPTION_ID]: this.id } } });
243
+ writeSse(this.res, {
244
+ jsonrpc: "2.0",
245
+ method,
246
+ params: { ...(params ?? {}), _meta: { ...meta, [SUBSCRIPTION_ID]: this.id } },
247
+ });
239
248
  }
240
249
  /** Send the acknowledgment, then whatever arrived while the subscription was being set up. */
241
250
  acknowledge() {
@@ -252,7 +261,11 @@ class Listener {
252
261
  end() {
253
262
  if (this.timer)
254
263
  clearInterval(this.timer);
255
- writeSse(this.res, { jsonrpc: "2.0", id: this.id, result: { resultType: "complete", _meta: { [SUBSCRIPTION_ID]: this.id } } });
264
+ writeSse(this.res, {
265
+ jsonrpc: "2.0",
266
+ id: this.id,
267
+ result: { resultType: "complete", _meta: { [SUBSCRIPTION_ID]: this.id } },
268
+ });
256
269
  if (!this.res.writableEnded)
257
270
  this.res.end();
258
271
  }
@@ -270,7 +283,7 @@ export class StatelessClient {
270
283
  calls = new Map();
271
284
  listeners = new Set();
272
285
  constructor(ctx,
273
- /** The client folder and, for a worktree, its main repository: what folder sets match (ADR 0031). */
286
+ /** The client folder and, for a worktree, its main repository: what folder sets match. */
274
287
  folders = []) {
275
288
  this.ctx = ctx;
276
289
  this.folders = folders;
@@ -404,7 +417,10 @@ export class StatelessFront {
404
417
  const id = body.id;
405
418
  const version = header(req, "mcp-protocol-version")?.trim() ?? "";
406
419
  if (!MODERN_PROTOCOL_VERSIONS.includes(version)) {
407
- sendJson(res, 400, errorBody(id, ModernErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version", { supported: ALL_PROTOCOL_VERSIONS, requested: version }));
420
+ sendJson(res, 400, errorBody(id, ModernErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version", {
421
+ supported: ALL_PROTOCOL_VERSIONS,
422
+ requested: version,
423
+ }));
408
424
  return;
409
425
  }
410
426
  const params = isObject(body.params) ? body.params : {};
@@ -445,7 +461,7 @@ export class StatelessFront {
445
461
  const agent = cleanAgentName(isObject(meta[CLIENT_INFO]) ? meta[CLIENT_INFO].name : undefined);
446
462
  if (agent)
447
463
  client.ctx.clientName = agent;
448
- // Outside the folder's server set (ADR 0031): answer from mcpd, never start the server.
464
+ // Outside the folder's server set: answer from mcpd, never start the server.
449
465
  const hidden = this.opts.hiddenBySet?.(client);
450
466
  if (hidden)
451
467
  return this.hiddenReply(res, id, method, hidden);
@@ -465,7 +481,15 @@ export class StatelessFront {
465
481
  /** A hidden server: no capabilities, empty lists that are not cached, every other request refused. */
466
482
  hiddenReply(res, id, method, why) {
467
483
  if (method === "server/discover") {
468
- this.reply(res, id, method, { result: { supportedVersions: ALL_PROTOCOL_VERSIONS, capabilities: {}, instructions: why, ttlMs: 0, cacheScope: "private" } });
484
+ this.reply(res, id, method, {
485
+ result: {
486
+ supportedVersions: ALL_PROTOCOL_VERSIONS,
487
+ capabilities: {},
488
+ instructions: why,
489
+ ttlMs: 0,
490
+ cacheScope: "private",
491
+ },
492
+ });
469
493
  return;
470
494
  }
471
495
  const spec = LISTS[method] ?? (method === "resources/list" ? { field: "resources" } : undefined);
@@ -481,7 +505,11 @@ export class StatelessFront {
481
505
  }
482
506
  stamp(result, serverInfo) {
483
507
  const meta = isObject(result._meta) ? result._meta : {};
484
- return { ...result, resultType: typeof result.resultType === "string" ? result.resultType : "complete", ...(serverInfo ? { _meta: { ...meta, [SERVER_INFO]: serverInfo } } : {}) };
508
+ return {
509
+ ...result,
510
+ resultType: typeof result.resultType === "string" ? result.resultType : "complete",
511
+ ...(serverInfo ? { _meta: { ...meta, [SERVER_INFO]: serverInfo } } : {}),
512
+ };
485
513
  }
486
514
  reply(res, id, method, outcome, serverInfo) {
487
515
  let msg;
@@ -536,12 +564,9 @@ export class StatelessFront {
536
564
  async forward(req, res, id, method, params, meta, client) {
537
565
  const manager = this.opts.manager;
538
566
  if (method === "tools/call") {
567
+ // The Mcp-Param-* headers are this revision's transport check, so they come before the
568
+ // call middleware (whose first stage is the tool filter).
539
569
  const tool = typeof params.name === "string" ? params.name : "";
540
- const filter = this.opts.toolFilter(client.ctx);
541
- if (filter && !toolAllowed(filter, tool)) {
542
- this.reply(res, id, method, rpcError(ErrorCode.InvalidParams, `tool ${tool} of ${client.ctx.serverName} is not available to profile ${client.ctx.profile ?? "default"} (tools.allow / tools.deny in mcp.toml)`));
543
- return;
544
- }
545
570
  const d = await manager.describe(client);
546
571
  const def = (d.tools ?? []).find((t) => isObject(t) && t.name === tool);
547
572
  const problem = def ? paramHeaderProblem(def, params.arguments, req.headers) : undefined;
@@ -554,8 +579,14 @@ export class StatelessFront {
554
579
  const upMeta = Object.fromEntries(Object.entries(meta).filter(([k]) => !k.startsWith("io.modelcontextprotocol/")));
555
580
  const { _meta: _drop, ...rest } = params;
556
581
  const upParams = { ...rest, ...(Object.keys(upMeta).length ? { _meta: upMeta } : {}) };
557
- const logLevel = typeof meta[LOG_LEVEL] === "string" && LOG_LEVELS.includes(meta[LOG_LEVEL]) ? meta[LOG_LEVEL] : undefined;
558
- const call = { res, stream: meta.progressToken !== undefined || logLevel !== undefined, ...(logLevel ? { logLevel } : {}) };
582
+ const logLevel = typeof meta[LOG_LEVEL] === "string" && LOG_LEVELS.includes(meta[LOG_LEVEL])
583
+ ? meta[LOG_LEVEL]
584
+ : undefined;
585
+ const call = {
586
+ res,
587
+ stream: meta.progressToken !== undefined || logLevel !== undefined,
588
+ ...(logLevel ? { logLevel } : {}),
589
+ };
559
590
  // Our own id for the call, so two requests of one client never collide upstream.
560
591
  const internal = `h${++this.seq}`;
561
592
  client.calls.set(internal, call);
@@ -569,7 +600,9 @@ export class StatelessFront {
569
600
  closed = true;
570
601
  // Closing the response is the cancellation signal in this revision.
571
602
  try {
572
- manager.existing(client)?.upstream.notify("notifications/cancelled", { requestId: internal, reason: "the client closed the request" }, client);
603
+ manager
604
+ .existing(client)
605
+ ?.upstream.notify("notifications/cancelled", { requestId: internal, reason: "the client closed the request" }, client);
573
606
  }
574
607
  catch {
575
608
  /* the server left the manifest; nothing to cancel */
@@ -577,7 +610,10 @@ export class StatelessFront {
577
610
  });
578
611
  let outcome;
579
612
  try {
580
- outcome = await manager.forward(client, method, upParams, internal, () => closed);
613
+ outcome =
614
+ method === "tools/call"
615
+ ? await this.opts.calls.call(client, upParams, internal, () => closed)
616
+ : await manager.forward(client, method, upParams, internal, () => closed);
581
617
  }
582
618
  finally {
583
619
  settled = true;
@@ -600,7 +636,9 @@ export class StatelessFront {
600
636
  filter.promptsListChanged = true;
601
637
  if (asked.resourcesListChanged === true && caps.resources)
602
638
  filter.resourcesListChanged = true;
603
- const uris = Array.isArray(asked.resourceSubscriptions) ? asked.resourceSubscriptions.filter((u) => typeof u === "string" && u !== "") : [];
639
+ const uris = Array.isArray(asked.resourceSubscriptions)
640
+ ? asked.resourceSubscriptions.filter((u) => typeof u === "string" && u !== "")
641
+ : [];
604
642
  const listener = new Listener(res, id, filter);
605
643
  openSse(res);
606
644
  client.listeners.add(listener);
@@ -1,13 +1,13 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
  import { createServer } from "node:http";
3
3
  import { buildDiscoveryUrls, discoverOAuthProtectedResourceMetadata, exchangeAuthorization, extractWWWAuthenticateParams, isHttpsUrl, refreshAuthorization, registerClient, startAuthorization, } from "@modelcontextprotocol/sdk/client/auth.js";
4
- import { InvalidClientError, InvalidGrantError, UnauthorizedClientError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
4
+ import { InvalidClientError, InvalidGrantError, UnauthorizedClientError, } from "@modelcontextprotocol/sdk/server/auth/errors.js";
5
5
  import { OAuthMetadataSchema, OpenIdProviderDiscoveryMetadataSchema, } from "@modelcontextprotocol/sdk/shared/auth.js";
6
6
  import { checkResourceAllowed, resourceUrlFromServerUrl } from "@modelcontextprotocol/sdk/shared/auth-utils.js";
7
7
  import { LATEST_PROTOCOL_VERSION } from "@modelcontextprotocol/sdk/types.js";
8
8
  import { packageInfo } from "../core/version.js";
9
9
  /**
10
- * mcpd as the OAuth client of remote MCP servers (ADR 0029), following the MCP authorization
10
+ * mcpd as the OAuth client of remote MCP servers, following the MCP authorization
11
11
  * specification (revision 2026-07-28): protected resource metadata (RFC 9728), authorization
12
12
  * server metadata (RFC 8414, OpenID Connect Discovery) with issuer validation, pre-registration,
13
13
  * Client ID Metadata Documents or Dynamic Client Registration (RFC 7591), PKCE with S256
@@ -48,7 +48,9 @@ export function parseRecord(raw) {
48
48
  return undefined;
49
49
  try {
50
50
  const r = JSON.parse(raw);
51
- return r && r.v === 1 && typeof r.issuer === "string" && r.client && typeof r.client.client_id === "string" ? r : undefined;
51
+ return r && r.v === 1 && typeof r.issuer === "string" && r.client && typeof r.client.client_id === "string"
52
+ ? r
53
+ : undefined;
52
54
  }
53
55
  catch {
54
56
  return undefined;
@@ -127,7 +129,10 @@ async function authorizationServerMetadata(issuer, fetchFn = fetch) {
127
129
  for (const { url, type } of buildDiscoveryUrls(issuer)) {
128
130
  let res;
129
131
  try {
130
- res = await fetchFn(url, { headers: { Accept: "application/json", "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION }, redirect: "error" });
132
+ res = await fetchFn(url, {
133
+ headers: { Accept: "application/json", "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION },
134
+ redirect: "error",
135
+ });
131
136
  }
132
137
  catch (err) {
133
138
  throw new OAuthFlowError(`cannot reach the authorization server at ${url.origin}: ${err.message}`);
@@ -150,7 +155,12 @@ async function authorizationServerMetadata(issuer, fetchFn = fetch) {
150
155
  }
151
156
  if (!m.response_types_supported.includes("code"))
152
157
  throw new OAuthFlowError(`the authorization server ${issuer} does not support the authorization code flow`);
153
- for (const [k, v] of Object.entries({ authorization_endpoint: m.authorization_endpoint, token_endpoint: m.token_endpoint, registration_endpoint: m.registration_endpoint, revocation_endpoint: revocationEndpoint(m) })) {
158
+ for (const [k, v] of Object.entries({
159
+ authorization_endpoint: m.authorization_endpoint,
160
+ token_endpoint: m.token_endpoint,
161
+ registration_endpoint: m.registration_endpoint,
162
+ revocation_endpoint: revocationEndpoint(m),
163
+ })) {
154
164
  if (typeof v === "string")
155
165
  requireSecure(v, k);
156
166
  }
@@ -164,12 +174,20 @@ async function probe(serverUrl, fetchFn) {
164
174
  try {
165
175
  res = await fetchFn(serverUrl, {
166
176
  method: "POST",
167
- headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION },
177
+ headers: {
178
+ "Content-Type": "application/json",
179
+ Accept: "application/json, text/event-stream",
180
+ "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION,
181
+ },
168
182
  body: JSON.stringify({
169
183
  jsonrpc: "2.0",
170
184
  id: 1,
171
185
  method: "initialize",
172
- params: { protocolVersion: LATEST_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "turno-mcpd", version: packageInfo().version } },
186
+ params: {
187
+ protocolVersion: LATEST_PROTOCOL_VERSION,
188
+ capabilities: {},
189
+ clientInfo: { name: "turno-mcpd", version: packageInfo().version },
190
+ },
173
191
  }),
174
192
  redirect: "error",
175
193
  });
@@ -216,7 +234,13 @@ async function discover(server, fetchFn = fetch, challenge = false) {
216
234
  if (!issuer)
217
235
  throw new OAuthFlowError(`${server.name}: authorization_server ${wanted} is not one of ${listed.join(", ")}`);
218
236
  const metadata = await authorizationServerMetadata(issuer, fetchFn);
219
- return { resourceMetadata, resource: resourceMetadata.resource, issuer, metadata, ...(challengeScope ? { challengeScope } : {}) };
237
+ return {
238
+ resourceMetadata,
239
+ resource: resourceMetadata.resource,
240
+ issuer,
241
+ metadata,
242
+ ...(challengeScope ? { challengeScope } : {}),
243
+ };
220
244
  }
221
245
  /** Space-separated union, keeping the first order. */
222
246
  function unionScopes(...lists) {
@@ -242,14 +266,19 @@ function toStored(t, now) {
242
266
  token_type: t.token_type,
243
267
  ...(t.refresh_token ? { refresh_token: t.refresh_token } : {}),
244
268
  ...(t.scope ? { scope: t.scope } : {}),
245
- ...(typeof t.expires_in === "number" && Number.isFinite(t.expires_in) ? { expires_at: now + t.expires_in * 1000 } : {}),
269
+ ...(typeof t.expires_in === "number" && Number.isFinite(t.expires_in)
270
+ ? { expires_at: now + t.expires_in * 1000 }
271
+ : {}),
246
272
  };
247
273
  }
248
274
  /** The client information to present: pre-registered ones get their secret from mcp.toml at use time. */
249
275
  async function clientFor(rec, settings, resolve) {
250
276
  if (rec.registration !== "pre-registered")
251
277
  return rec.client;
252
- return { client_id: rec.client.client_id, ...(settings?.clientSecret ? { client_secret: await resolve(settings.clientSecret) } : {}) };
278
+ return {
279
+ client_id: rec.client.client_id,
280
+ ...(settings?.clientSecret ? { client_secret: await resolve(settings.clientSecret) } : {}),
281
+ };
253
282
  }
254
283
  /** A one-shot HTTP listener on 127.0.0.1 (RFC 8252 section 7.3, loopback IP literal). */
255
284
  async function callbackServer(port) {
@@ -309,7 +338,8 @@ function portOf(uris) {
309
338
  */
310
339
  export function checkIssuerParam(q, issuer, metadata) {
311
340
  const iss = q.get("iss");
312
- const advertised = metadata.authorization_response_iss_parameter_supported === true;
341
+ const advertised = metadata
342
+ .authorization_response_iss_parameter_supported === true;
313
343
  if (iss !== null) {
314
344
  if (iss !== issuer)
315
345
  throw new OAuthFlowError(`the authorization response came from issuer ${iss}, not ${issuer}; refusing it (RFC 9207)`);
@@ -375,7 +405,12 @@ export async function login(o) {
375
405
  }
376
406
  else {
377
407
  try {
378
- client = await registerClient(d.issuer, { metadata: d.metadata, clientMetadata: clientMetadata(cb.redirectUri, scope), ...(scope ? { scope } : {}), fetchFn });
408
+ client = await registerClient(d.issuer, {
409
+ metadata: d.metadata,
410
+ clientMetadata: clientMetadata(cb.redirectUri, scope),
411
+ ...(scope ? { scope } : {}),
412
+ fetchFn,
413
+ });
379
414
  }
380
415
  catch (err) {
381
416
  throw new OAuthFlowError(`dynamic client registration at ${d.issuer} failed: ${scrub(err.message, [])}`);
@@ -458,11 +493,21 @@ export async function revoke(server, rec, resolve, fetchFn = fetch) {
458
493
  if (!endpoint)
459
494
  return "the authorization server has no revocation endpoint";
460
495
  const client = await clientFor(rec, server.oauth, resolve);
461
- const body = new URLSearchParams({ token, token_type_hint: rec.tokens?.refresh_token ? "refresh_token" : "access_token", client_id: client.client_id });
496
+ const body = new URLSearchParams({
497
+ token,
498
+ token_type_hint: rec.tokens?.refresh_token ? "refresh_token" : "access_token",
499
+ client_id: client.client_id,
500
+ });
462
501
  const headers = { "Content-Type": "application/x-www-form-urlencoded" };
463
502
  if (client.client_secret)
464
503
  headers.Authorization = `Basic ${Buffer.from(`${encodeURIComponent(client.client_id)}:${encodeURIComponent(client.client_secret)}`).toString("base64")}`;
465
- const res = await fetchFn(endpoint, { method: "POST", headers, body, redirect: "error", signal: AbortSignal.timeout(10_000) });
504
+ const res = await fetchFn(endpoint, {
505
+ method: "POST",
506
+ headers,
507
+ body,
508
+ redirect: "error",
509
+ signal: AbortSignal.timeout(10_000),
510
+ });
466
511
  await res.body?.cancel().catch(() => { });
467
512
  return res.ok ? undefined : `the revocation endpoint answered HTTP ${res.status}`;
468
513
  }
@@ -604,7 +649,10 @@ export class OAuthSession {
604
649
  return t !== undefined && (t.expires_at === undefined || t.expires_at - EXPIRY_SKEW_MS > this.now());
605
650
  }
606
651
  checkBinding(server, rec) {
607
- if (!checkResourceAllowed({ requestedResource: resourceUrlFromServerUrl(server.url), configuredResource: rec.resource })) {
652
+ if (!checkResourceAllowed({
653
+ requestedResource: resourceUrlFromServerUrl(server.url),
654
+ configuredResource: rec.resource,
655
+ })) {
608
656
  throw new LoginRequiredError(this.name, this.variant, `the login is for ${rec.resource}, and mcp.toml now says ${server.url}`);
609
657
  }
610
658
  const id = server.oauth?.clientId;
@@ -671,7 +719,9 @@ export class OAuthSession {
671
719
  });
672
720
  }
673
721
  catch (err) {
674
- if (err instanceof InvalidGrantError || err instanceof InvalidClientError || err instanceof UnauthorizedClientError) {
722
+ if (err instanceof InvalidGrantError ||
723
+ err instanceof InvalidClientError ||
724
+ err instanceof UnauthorizedClientError) {
675
725
  // A login in another process may have replaced the token we hold: read the store again once.
676
726
  const latest = retried ? undefined : await this.load(true);
677
727
  if (latest?.tokens?.refresh_token && latest.tokens.refresh_token !== refreshToken) {
@@ -786,6 +836,10 @@ export async function loginState(store, name, variant, now = Date.now()) {
786
836
  const expired = t.expires_at !== undefined && t.expires_at <= now;
787
837
  if (expired && !t.refresh_token)
788
838
  return { state: "login required" };
789
- return { state: expired ? "expired" : "logged in", ...(t.expires_at ? { expiresAt: t.expires_at } : {}), refresh: Boolean(t.refresh_token) };
839
+ return {
840
+ state: expired ? "expired" : "logged in",
841
+ ...(t.expires_at ? { expiresAt: t.expires_at } : {}),
842
+ refresh: Boolean(t.refresh_token),
843
+ };
790
844
  }
791
845
  //# sourceMappingURL=oauth.js.map
@@ -1,5 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { readFileSync, readdirSync, readlinkSync } from "node:fs";
3
+ import { connect } from "node:net";
3
4
  import { join } from "node:path";
4
5
  import { promisify } from "node:util";
5
6
  const run = promisify(execFile);
@@ -22,7 +23,13 @@ function procTcpRows(procRoot = "/proc") {
22
23
  const f = line.trim().split(/\s+/);
23
24
  if (f.length < 10)
24
25
  continue;
25
- rows.push({ localPort: hexPort(f[1]), remotePort: hexPort(f[2]), state: f[3] ?? "", uid: Number(f[7]), inode: f[9] ?? "" });
26
+ rows.push({
27
+ localPort: hexPort(f[1]),
28
+ remotePort: hexPort(f[2]),
29
+ state: f[3] ?? "",
30
+ uid: Number(f[7]),
31
+ inode: f[9] ?? "",
32
+ });
26
33
  }
27
34
  }
28
35
  return rows;
@@ -63,7 +70,10 @@ function pidOfInode(inode, procRoot = "/proc", skip) {
63
70
  }
64
71
  async function lsofPeer(remotePort, self, env) {
65
72
  try {
66
- const { stdout } = await run("lsof", ["-nP", `-iTCP:${remotePort}`, "-sTCP:ESTABLISHED", "-Fpn"], { timeout: 3000, env });
73
+ const { stdout } = await run("lsof", ["-nP", `-iTCP:${remotePort}`, "-sTCP:ESTABLISHED", "-Fpn"], {
74
+ timeout: 3000,
75
+ env,
76
+ });
67
77
  let pid;
68
78
  for (const line of stdout.split("\n")) {
69
79
  if (line.startsWith("p"))
@@ -95,7 +105,39 @@ export async function peerPid(remotePort, self = process.pid, opts = {}) {
95
105
  }
96
106
  return lsofPeer(remotePort, self, opts.env ?? process.env);
97
107
  }
98
- /** Which process listens on 127.0.0.1:`port`, as far as this user can tell. Undefined when unknown or free. */
108
+ /** Whether something accepts TCP connections on 127.0.0.1:`port`, the address mcpd binds. */
109
+ function listensOn(port, timeoutMs = 1000) {
110
+ return new Promise((resolve) => {
111
+ const socket = connect({ host: "127.0.0.1", port });
112
+ const done = (yes) => {
113
+ socket.destroy();
114
+ resolve(yes);
115
+ };
116
+ socket.setTimeout(timeoutMs, () => done(true)); // accepted the SYN but slow to finish: busy
117
+ socket.once("connect", () => done(true));
118
+ socket.once("error", () => done(false));
119
+ });
120
+ }
121
+ function parseLsof(stdout) {
122
+ const owner = {};
123
+ for (const line of stdout.split("\n")) {
124
+ if (line.startsWith("p") && owner.pid === undefined)
125
+ owner.pid = Number(line.slice(1));
126
+ else if (line.startsWith("c") && owner.command === undefined)
127
+ owner.command = line.slice(1);
128
+ else if (line.startsWith("u") && owner.uid === undefined)
129
+ owner.uid = Number(line.slice(1));
130
+ }
131
+ return owner.pid !== undefined ? owner : undefined;
132
+ }
133
+ /**
134
+ * Which process listens on 127.0.0.1:`port`, as far as this user can tell. Undefined when the
135
+ * port is free; an empty object when something listens but the system cannot say what.
136
+ *
137
+ * On macOS lsof scans every process and can take many seconds on a busy machine, so a free port
138
+ * is told by a refused connection without lsof, and `opts.pid` (a process expected to hold the
139
+ * port) is checked alone first.
140
+ */
99
141
  export async function portOwner(port, opts = {}) {
100
142
  const platform = opts.platform ?? process.platform;
101
143
  if (platform === "linux") {
@@ -114,22 +156,26 @@ export async function portOwner(port, opts = {}) {
114
156
  return { uid: row.uid, ...(pid ? { pid } : {}), ...(command ? { command } : {}) };
115
157
  }
116
158
  }
117
- try {
118
- const { stdout } = await run("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpcu"], { timeout: 3000, env: opts.env ?? process.env });
119
- const owner = {};
120
- for (const line of stdout.split("\n")) {
121
- if (line.startsWith("p") && owner.pid === undefined)
122
- owner.pid = Number(line.slice(1));
123
- else if (line.startsWith("c") && owner.command === undefined)
124
- owner.command = line.slice(1);
125
- else if (line.startsWith("u") && owner.uid === undefined)
126
- owner.uid = Number(line.slice(1));
127
- }
128
- return owner.pid !== undefined ? owner : undefined;
129
- }
130
- catch {
159
+ if (!(await listensOn(port)))
131
160
  return undefined;
161
+ const lsof = async (args) => {
162
+ try {
163
+ const { stdout } = await run("lsof", ["-nP", ...args, `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpcu"], {
164
+ timeout: 3000,
165
+ env: opts.env ?? process.env,
166
+ });
167
+ return parseLsof(stdout);
168
+ }
169
+ catch {
170
+ return undefined; // lsof exits 1 when it finds nothing; also missing or too slow
171
+ }
172
+ };
173
+ if (opts.pid !== undefined) {
174
+ const own = await lsof(["-a", "-p", String(opts.pid)]);
175
+ if (own)
176
+ return own;
132
177
  }
178
+ return (await lsof([])) ?? {};
133
179
  }
134
180
  /** "node (pid 123, uid 501)" for messages. */
135
181
  export function describeOwner(o) {
@@ -37,7 +37,10 @@ export function freeMemLevel(free, total) {
37
37
  return share < 0.05 ? "critical" : share < 0.1 ? "warn" : "normal";
38
38
  }
39
39
  async function realSysctl() {
40
- const { stdout } = await run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_vm_pressure_level"], { encoding: "utf8", timeout: 2000 });
40
+ const { stdout } = await run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_vm_pressure_level"], {
41
+ encoding: "utf8",
42
+ timeout: 2000,
43
+ });
41
44
  return stdout;
42
45
  }
43
46
  /**
package/dist/mcpd/rss.js CHANGED
@@ -3,14 +3,24 @@ import { readFileSync, readdirSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { promisify } from "node:util";
5
5
  import { atomicWrite } from "../core/journal.js";
6
+ import { hasFields, isRecord, readState } from "../core/state-file.js";
6
7
  const run = promisify(execFile);
7
- /** `ps -A -o pid=,ppid=,rss=` output (rss in KiB, as both macOS and procps print it). */
8
+ /**
9
+ * `ps -A -o pid=,ppid=,pgid=,rss=` output (rss in KiB, as both macOS and procps print it). The
10
+ * three column form without pgid is read too.
11
+ */
8
12
  export function parsePs(stdout) {
9
13
  const t = new Map();
10
14
  for (const line of stdout.split("\n")) {
11
- const [pid, ppid, rss] = line.trim().split(/\s+/).map(Number);
15
+ const cols = line.trim().split(/\s+/).map(Number);
16
+ const [pid, ppid] = cols;
17
+ const pgid = cols.length >= 4 ? cols[2] : undefined;
18
+ const rss = cols.length >= 4 ? cols[3] : cols[2];
12
19
  if (Number.isInteger(pid) && pid > 0 && Number.isInteger(ppid) && Number.isFinite(rss)) {
13
- t.set(pid, { ppid: ppid, rss: rss * 1024 });
20
+ const bytes = rss * 1024;
21
+ t.set(pid, Number.isInteger(pgid)
22
+ ? { ppid: ppid, pgid: pgid, rss: bytes }
23
+ : { ppid: ppid, rss: bytes });
14
24
  }
15
25
  }
16
26
  return t;
@@ -48,7 +58,7 @@ export function procfsTable(root = "/proc") {
48
58
  export async function processTable(opts = {}) {
49
59
  try {
50
60
  const env = opts.env ?? process.env;
51
- const { stdout } = await run("ps", ["-A", "-o", "pid=,ppid=,rss="], {
61
+ const { stdout } = await run("ps", ["-A", "-o", "pid=,ppid=,pgid=,rss="], {
52
62
  encoding: "utf8",
53
63
  timeout: 5000,
54
64
  maxBuffer: 16 * 1024 * 1024,
@@ -63,19 +73,29 @@ export async function processTable(opts = {}) {
63
73
  }
64
74
  return procfsTable(opts.procRoot);
65
75
  }
66
- /** RSS of a process and all its descendants (npx and shell wrappers start the real server as a child). */
76
+ /**
77
+ * RSS of a process and all its descendants (npx and shell wrappers start the real server as a
78
+ * child). A descendant that leads its own process group brings the whole group: a browser server
79
+ * starts Chrome as a group leader, and a Chrome helper whose parent went away stays in that
80
+ * group.
81
+ */
67
82
  export function treeRss(table, pid) {
68
83
  if (!table.has(pid))
69
84
  return undefined;
70
85
  const children = new Map();
71
- for (const [p, { ppid }] of table) {
72
- if (p === ppid)
73
- continue;
74
- const list = children.get(ppid);
86
+ const add = (key, p) => {
87
+ const list = children.get(key);
75
88
  if (list)
76
89
  list.push(p);
77
90
  else
78
- children.set(ppid, [p]);
91
+ children.set(key, [p]);
92
+ };
93
+ for (const [p, { ppid, pgid }] of table) {
94
+ if (p !== ppid)
95
+ add(ppid, p);
96
+ // Members of a group count under its leader too (the leader's own PID is its pgid).
97
+ if (pgid !== undefined && pgid !== p && pgid !== ppid && table.get(pgid)?.pgid === pgid)
98
+ add(pgid, p);
79
99
  }
80
100
  let total = 0;
81
101
  const seen = new Set();
@@ -103,15 +123,10 @@ export class RssSampler {
103
123
  constructor(file, opts = {}) {
104
124
  this.file = file;
105
125
  this.opts = opts;
106
- try {
107
- const v = JSON.parse(readFileSync(file, "utf8"));
108
- for (const [k, s] of Object.entries(v ?? {}))
109
- if (typeof s?.bytes === "number" && typeof s.at === "string")
110
- this.known[k] = s;
111
- }
112
- catch {
113
- /* first run */
114
- }
126
+ // None on the first run; entries of another shape are dropped.
127
+ for (const [k, s] of Object.entries(readState(file, isRecord) ?? {}))
128
+ if (hasFields(s, { bytes: "number", at: "string" }))
129
+ this.known[k] = s;
115
130
  }
116
131
  samples() {
117
132
  return { ...this.known };
@@ -6,7 +6,7 @@ import { paths, tildify } from "../core/paths.js";
6
6
  import { realOr } from "../core/fsutil.js";
7
7
  const exec = promisify(execFile);
8
8
  /**
9
- * How mcpd is kept alive across logins (ADR 0017): a LaunchAgent on macOS, a `systemd --user`
9
+ * How mcpd is kept alive across logins: a LaunchAgent on macOS, a `systemd --user`
10
10
  * unit on Linux, nothing elsewhere. Every backend writes one file (journaled, so `turno undo`
11
11
  * restores it) and drives the service manager through its command-line tool.
12
12
  */
@@ -29,7 +29,15 @@ export function serviceEnv(spec, kind) {
29
29
  PATH: spec.env.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
30
30
  HOME: paths(spec.env).home,
31
31
  };
32
- for (const k of ["XDG_CONFIG_HOME", "XDG_STATE_HOME", "XDG_DATA_HOME", "LANG", "TURNO_CONFIG_DIR", "TURNO_STATE_DIR", "TURNO_DATA_DIR"]) {
32
+ for (const k of [
33
+ "XDG_CONFIG_HOME",
34
+ "XDG_STATE_HOME",
35
+ "XDG_DATA_HOME",
36
+ "LANG",
37
+ "TURNO_CONFIG_DIR",
38
+ "TURNO_STATE_DIR",
39
+ "TURNO_DATA_DIR",
40
+ ]) {
33
41
  if (spec.env[k])
34
42
  vars[k] = spec.env[k];
35
43
  }
@@ -57,7 +65,19 @@ export async function runTool(tool, args, env, timeout = 10_000) {
57
65
  * Paths that change when a version manager or Homebrew switches versions. A service that
58
66
  * runs them breaks after `nvm uninstall`, `brew cleanup` and the like.
59
67
  */
60
- const UNSTABLE = [/\/\.nvm\/versions\//, /\/Cellar\//, /\/\.volta\/tools\/image\//, /\/fnm\/node-versions\//, /\/\.asdf\/installs\//, /\/mise\/installs\//, /\/_npx\//, /\/\.npm\/_npx\//, /\/n\/versions\//, /\/\.local\/share\/pnpm\/\.tools\//, /\/\.local\/share\/pnpm\/dlx-/];
68
+ const UNSTABLE = [
69
+ /\/\.nvm\/versions\//,
70
+ /\/Cellar\//,
71
+ /\/\.volta\/tools\/image\//,
72
+ /\/fnm\/node-versions\//,
73
+ /\/\.asdf\/installs\//,
74
+ /\/mise\/installs\//,
75
+ /\/_npx\//,
76
+ /\/\.npm\/_npx\//,
77
+ /\/n\/versions\//,
78
+ /\/\.local\/share\/pnpm\/\.tools\//,
79
+ /\/\.local\/share\/pnpm\/dlx-/,
80
+ ];
61
81
  export function isUnstablePath(p) {
62
82
  return UNSTABLE.some((re) => re.test(p));
63
83
  }
@@ -131,7 +151,11 @@ export async function serviceBackend(env, platform = process.platform) {
131
151
  }
132
152
  /** The backend whose file is installed, without asking the service manager. */
133
153
  export async function installedBackend(env, platform = process.platform) {
134
- const b = platform === "darwin" ? (await import("./launchd.js")).launchd : platform === "linux" ? (await import("./systemd.js")).systemd : undefined;
154
+ const b = platform === "darwin"
155
+ ? (await import("./launchd.js")).launchd
156
+ : platform === "linux"
157
+ ? (await import("./systemd.js")).systemd
158
+ : undefined;
135
159
  return b && existsSync(b.file(env)) ? b : undefined;
136
160
  }
137
161
  /** Write the service file through the journal and (unless dry) load it. */