turno-cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +293 -0
  2. package/README.md +143 -75
  3. package/dist/accounts/audit.js +137 -7
  4. package/dist/accounts/builtin.js +68 -21
  5. package/dist/accounts/delegate.js +176 -35
  6. package/dist/accounts/policy.js +77 -0
  7. package/dist/accounts/registry.js +37 -21
  8. package/dist/agents/adapter.js +7 -0
  9. package/dist/agents/claude.js +195 -0
  10. package/dist/agents/codex.js +98 -0
  11. package/dist/agents/copilot.js +39 -0
  12. package/dist/agents/cursor.js +41 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +7 -4
  15. package/dist/cli/args.js +19 -4
  16. package/dist/cli/commands/accounts.js +96 -51
  17. package/dist/cli/commands/auto.js +82 -32
  18. package/dist/cli/commands/browser.js +216 -135
  19. package/dist/cli/commands/complete.js +2 -1
  20. package/dist/cli/commands/completion.js +4 -2
  21. package/dist/cli/commands/config.js +103 -18
  22. package/dist/cli/commands/demo.js +292 -0
  23. package/dist/cli/commands/doctor.js +387 -119
  24. package/dist/cli/commands/handoff.js +33 -22
  25. package/dist/cli/commands/identity.js +101 -50
  26. package/dist/cli/commands/init.js +616 -0
  27. package/dist/cli/commands/limit.js +25 -13
  28. package/dist/cli/commands/mcp-oauth.js +194 -0
  29. package/dist/cli/commands/mcp-observe.js +434 -0
  30. package/dist/cli/commands/mcp.js +653 -185
  31. package/dist/cli/commands/mcpd.js +323 -75
  32. package/dist/cli/commands/migrate.js +6 -4
  33. package/dist/cli/commands/open.js +92 -27
  34. package/dist/cli/commands/profile.js +205 -69
  35. package/dist/cli/commands/resolve.js +6 -2
  36. package/dist/cli/commands/run.js +15 -5
  37. package/dist/cli/commands/secret.js +61 -42
  38. package/dist/cli/commands/session.js +2 -2
  39. package/dist/cli/commands/sessions.js +42 -12
  40. package/dist/cli/commands/setup.js +136 -158
  41. package/dist/cli/commands/status.js +172 -41
  42. package/dist/cli/commands/statusline.js +305 -113
  43. package/dist/cli/commands/ui.js +64 -66
  44. package/dist/cli/commands/undo.js +161 -18
  45. package/dist/cli/commands/uninstall.js +462 -0
  46. package/dist/cli/commands/upgrade.js +75 -19
  47. package/dist/cli/commands/usage.js +117 -44
  48. package/dist/cli/commands/version.js +7 -5
  49. package/dist/cli/commands/which.js +7 -24
  50. package/dist/cli/compile-cache.js +32 -0
  51. package/dist/cli/group.js +10 -10
  52. package/dist/cli/help.js +57 -0
  53. package/dist/cli/highlight.js +236 -0
  54. package/dist/cli/io.js +170 -1
  55. package/dist/cli/launch.js +21 -37
  56. package/dist/cli/launchers.js +145 -94
  57. package/dist/cli/main.js +163 -27
  58. package/dist/cli/picker.js +447 -0
  59. package/dist/cli/registry.js +42 -5
  60. package/dist/cli/security.js +539 -0
  61. package/dist/cli/style.js +281 -0
  62. package/dist/core/config.js +145 -23
  63. package/dist/core/exhausted.js +6 -8
  64. package/dist/core/fsutil.js +47 -0
  65. package/dist/core/journal.js +281 -11
  66. package/dist/core/manifest.js +126 -6
  67. package/dist/core/paths.js +114 -7
  68. package/dist/core/profiles.js +139 -9
  69. package/dist/core/resolve.js +129 -23
  70. package/dist/core/secrets.js +215 -20
  71. package/dist/core/sessions.js +13 -20
  72. package/dist/core/update.js +18 -8
  73. package/dist/core/version.js +6 -0
  74. package/dist/demo/server.js +34 -0
  75. package/dist/mcpd/cache.js +18 -4
  76. package/dist/mcpd/calllog.js +253 -0
  77. package/dist/mcpd/client-names.js +51 -0
  78. package/dist/mcpd/connectors.js +148 -17
  79. package/dist/mcpd/daemon.js +452 -116
  80. package/dist/mcpd/folder-sets.js +39 -0
  81. package/dist/mcpd/gateway.js +441 -47
  82. package/dist/mcpd/health.js +269 -0
  83. package/dist/mcpd/importer.js +356 -36
  84. package/dist/mcpd/instances.js +425 -65
  85. package/dist/mcpd/jsonrpc.js +8 -0
  86. package/dist/mcpd/launchd.js +65 -48
  87. package/dist/mcpd/modern.js +648 -0
  88. package/dist/mcpd/oauth.js +791 -0
  89. package/dist/mcpd/peerpid.js +122 -6
  90. package/dist/mcpd/pressure.js +85 -0
  91. package/dist/mcpd/rss.js +151 -0
  92. package/dist/mcpd/service.js +167 -0
  93. package/dist/mcpd/state.js +183 -0
  94. package/dist/mcpd/sync.js +55 -80
  95. package/dist/mcpd/systemd.js +80 -0
  96. package/dist/mcpd/tokens.js +89 -0
  97. package/dist/mcpd/upstream.js +154 -44
  98. package/dist/statusline/cost.js +154 -44
  99. package/dist/statusline/input.js +66 -0
  100. package/dist/statusline/render.js +9 -3
  101. package/dist/ui/fonts.js +8 -3
  102. package/dist/ui/settings.js +27 -15
  103. package/npm-shrinkwrap.json +1093 -0
  104. package/package.json +9 -9
  105. package/dist/cli/commands/available.js +0 -18
@@ -0,0 +1,648 @@
1
+ import { SUPPORTED_PROTOCOL_VERSIONS } from "@modelcontextprotocol/sdk/types.js";
2
+ import { toolAllowed } from "../core/manifest.js";
3
+ import { cleanAgentName } from "./calllog.js";
4
+ import { ErrorCode, rpcError } from "./jsonrpc.js";
5
+ /**
6
+ * MCP revision 2026-07-28 on mcpd's HTTP endpoint (ADR 0028): stateless requests that carry
7
+ * their protocol version, client capabilities and identity in `_meta`, with no `initialize` and
8
+ * no `Mcp-Session-Id`. 2025-11-25 sessions keep going through the SDK transport in gateway.ts;
9
+ * the upstream servers are still spoken to as 2025-11-25 clients.
10
+ */
11
+ export const MODERN_PROTOCOL_VERSION = "2026-07-28";
12
+ const MODERN_PROTOCOL_VERSIONS = [MODERN_PROTOCOL_VERSION];
13
+ /** What `server/discover` and UnsupportedProtocolVersion list: modern first, then every legacy one. */
14
+ const ALL_PROTOCOL_VERSIONS = [...MODERN_PROTOCOL_VERSIONS, ...SUPPORTED_PROTOCOL_VERSIONS];
15
+ /** Freshness hint for lists checked against a running server since mcpd started. */
16
+ const LIST_TTL_MS = 5 * 60_000;
17
+ /** A stateless client with nothing in flight is forgotten after this long without requests. */
18
+ const STATELESS_IDLE_MS = 30 * 60_000;
19
+ /** SSE comment sent on quiet `subscriptions/listen` streams. */
20
+ const KEEPALIVE_MS = 25_000;
21
+ const ModernErrorCode = {
22
+ HeaderMismatch: -32020,
23
+ MissingRequiredClientCapability: -32021,
24
+ UnsupportedProtocolVersion: -32022,
25
+ };
26
+ const PROTOCOL_VERSION = "io.modelcontextprotocol/protocolVersion";
27
+ const CLIENT_INFO = "io.modelcontextprotocol/clientInfo";
28
+ const CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
29
+ const LOG_LEVEL = "io.modelcontextprotocol/logLevel";
30
+ const SERVER_INFO = "io.modelcontextprotocol/serverInfo";
31
+ const SUBSCRIPTION_ID = "io.modelcontextprotocol/subscriptionId";
32
+ /** List methods answered from the description cache, as in gateway.ts. */
33
+ const LISTS = {
34
+ "tools/list": { cap: "tools", key: "tools", field: "tools" },
35
+ "prompts/list": { cap: "prompts", key: "prompts", field: "prompts" },
36
+ "resources/templates/list": { cap: "resources", key: "resourceTemplates", field: "resourceTemplates" },
37
+ };
38
+ /** Methods whose request carries `Mcp-Name`, and the body field it mirrors. */
39
+ const NAMED = { "tools/call": "name", "prompts/get": "name", "resources/read": "uri" };
40
+ /** 2025-11-25 methods that 2026-07-28 removed; they lean on session state mcpd does not keep for these clients. */
41
+ const REMOVED = new Set(["initialize", "ping", "logging/setLevel", "resources/subscribe", "resources/unsubscribe"]);
42
+ /** Results mcpd relays without caching; the revision requires caching hints on them. */
43
+ const UNCACHED = new Set(["resources/list", "resources/read"]);
44
+ /** Server-to-client requests: a 2026-07-28 client only answers them through MRTR, which mcpd does not bridge yet. */
45
+ const SERVER_REQUESTS = new Set(["elicitation", "sampling", "roots"]);
46
+ const LOG_LEVELS = ["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"];
47
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
48
+ function header(req, name) {
49
+ const v = req.headers[name];
50
+ return Array.isArray(v) ? v[0] : v;
51
+ }
52
+ /**
53
+ * Whether a POST goes the stateless way: its MCP-Protocol-Version is not a 2025-era one. A
54
+ * 2026-07-28 request is stateless even with an `Mcp-Session-Id`, which that revision says to
55
+ * ignore; an unknown version with a session id stays with the session (the SDK refuses it).
56
+ */
57
+ export function wantsModern(req) {
58
+ if (req.method !== "POST")
59
+ return false;
60
+ const v = header(req, "mcp-protocol-version")?.trim();
61
+ if (v === undefined || v === "" || SUPPORTED_PROTOCOL_VERSIONS.includes(v))
62
+ return false;
63
+ return header(req, "mcp-session-id") === undefined || MODERN_PROTOCOL_VERSIONS.includes(v);
64
+ }
65
+ /** Whether a parsed body is an initialize request (a dual-era client asking for a 2025-era session). */
66
+ export function isInitialize(body) {
67
+ return isObject(body) && body.method === "initialize" && body.id !== undefined && body.id !== null;
68
+ }
69
+ /** Read and parse a JSON body, refusing more than `limit` bytes. */
70
+ export function readJsonBody(req, limit) {
71
+ return new Promise((resolve) => {
72
+ const declared = Number(header(req, "content-length") ?? "0");
73
+ if (declared > limit) {
74
+ resolve({ status: 413, code: ErrorCode.InvalidRequest, message: `request body larger than ${limit} bytes` });
75
+ return;
76
+ }
77
+ const chunks = [];
78
+ let size = 0;
79
+ let done = false;
80
+ req.on("data", (c) => {
81
+ if (done)
82
+ return;
83
+ size += c.length;
84
+ if (size > limit) {
85
+ done = true;
86
+ resolve({ status: 413, code: ErrorCode.InvalidRequest, message: `request body larger than ${limit} bytes` });
87
+ return;
88
+ }
89
+ chunks.push(c);
90
+ });
91
+ req.on("end", () => {
92
+ if (done)
93
+ return;
94
+ done = true;
95
+ try {
96
+ resolve({ value: JSON.parse(Buffer.concat(chunks).toString("utf8")) });
97
+ }
98
+ catch {
99
+ resolve({ status: 400, code: ErrorCode.ParseError, message: "Parse error: the body is not JSON" });
100
+ }
101
+ });
102
+ req.on("error", (err) => {
103
+ if (done)
104
+ return;
105
+ done = true;
106
+ resolve({ status: 400, code: ErrorCode.InvalidRequest, message: err.message });
107
+ });
108
+ });
109
+ }
110
+ /** Decode the `=?base64?...?=` sentinel of Mcp-Name and Mcp-Param-* values; undefined when it is not valid Base64. */
111
+ export function decodeHeaderValue(v) {
112
+ const m = /^=\?base64\?(.*)\?=$/.exec(v);
113
+ if (!m)
114
+ return v;
115
+ const b64 = m[1] ?? "";
116
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64) || b64.length % 4 !== 0)
117
+ return undefined;
118
+ return Buffer.from(b64, "base64").toString("utf8");
119
+ }
120
+ /** Every `x-mcp-header` reachable from the schema root through `properties` keys only, with its path. */
121
+ function annotatedParams(schema, path = [], out = []) {
122
+ if (!isObject(schema) || !isObject(schema.properties))
123
+ return out;
124
+ for (const [key, sub] of Object.entries(schema.properties)) {
125
+ if (!isObject(sub))
126
+ continue;
127
+ const name = sub["x-mcp-header"];
128
+ if (typeof name === "string" && name)
129
+ out.push({ name, path: [...path, key], type: sub.type });
130
+ annotatedParams(sub, [...path, key], out);
131
+ }
132
+ return out;
133
+ }
134
+ function valueAt(args, path) {
135
+ let v = args;
136
+ for (const k of path)
137
+ v = isObject(v) ? v[k] : undefined;
138
+ return v;
139
+ }
140
+ /**
141
+ * Check the `Mcp-Param-{Name}` headers of a tools/call against its arguments, for the tool's
142
+ * `x-mcp-header` annotations. Returns the problem, or undefined when they agree.
143
+ */
144
+ export function paramHeaderProblem(tool, args, headers) {
145
+ const schema = isObject(tool) ? tool.inputSchema : undefined;
146
+ for (const p of annotatedParams(schema)) {
147
+ const hname = `mcp-param-${p.name.toLowerCase()}`;
148
+ const raw = headers[hname];
149
+ const sent = Array.isArray(raw) ? raw[0] : raw;
150
+ const value = valueAt(args, p.path);
151
+ if (value === undefined || value === null) {
152
+ if (sent !== undefined)
153
+ return `Mcp-Param-${p.name} was sent, but ${p.path.join(".")} is not in the arguments`;
154
+ continue;
155
+ }
156
+ if (sent === undefined)
157
+ return `missing Mcp-Param-${p.name} for ${p.path.join(".")}`;
158
+ const decoded = decodeHeaderValue(sent);
159
+ if (decoded === undefined)
160
+ return `Mcp-Param-${p.name} is not valid Base64`;
161
+ const agrees = typeof value === "number"
162
+ ? decoded.trim() !== "" && Number(decoded) === value
163
+ : typeof value === "boolean"
164
+ ? decoded === String(value)
165
+ : decoded === String(value);
166
+ if (!agrees)
167
+ return `Mcp-Param-${p.name} header value does not match the body value of ${p.path.join(".")}`;
168
+ }
169
+ return undefined;
170
+ }
171
+ /**
172
+ * Error codes for a 2026-07-28 client. The revision forbids -32002 (resource not found is now
173
+ * -32602) and -32042 (URL elicitation, 2025-11-25 only); mcpd's own -32002 ("server
174
+ * unavailable") becomes Internal error.
175
+ */
176
+ export function modernErrorCode(code, method) {
177
+ if (code === -32002)
178
+ return method === "resources/read" ? ErrorCode.InvalidParams : ErrorCode.Internal;
179
+ if (code === -32042)
180
+ return ErrorCode.Internal;
181
+ return code;
182
+ }
183
+ function sendJson(res, status, body) {
184
+ if (res.headersSent || res.writableEnded)
185
+ return;
186
+ const text = JSON.stringify(body);
187
+ res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(text) });
188
+ res.end(text);
189
+ }
190
+ function openSse(res) {
191
+ if (res.headersSent)
192
+ return;
193
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive", "x-accel-buffering": "no" });
194
+ res.flushHeaders();
195
+ }
196
+ function writeSse(res, m) {
197
+ if (!res.writableEnded && !res.destroyed)
198
+ res.write(`event: message\ndata: ${JSON.stringify(m)}\n\n`);
199
+ }
200
+ function errorBody(id, code, message, data) {
201
+ return { jsonrpc: "2.0", id, error: data === undefined ? { code, message } : { code, message, data } };
202
+ }
203
+ /** One `subscriptions/listen` stream. */
204
+ class Listener {
205
+ res;
206
+ id;
207
+ filter;
208
+ ready = false;
209
+ queue = [];
210
+ timer;
211
+ constructor(res, id, filter) {
212
+ this.res = res;
213
+ this.id = id;
214
+ this.filter = filter;
215
+ }
216
+ wants(method, params) {
217
+ switch (method) {
218
+ case "notifications/tools/list_changed":
219
+ return Boolean(this.filter.toolsListChanged);
220
+ case "notifications/prompts/list_changed":
221
+ return Boolean(this.filter.promptsListChanged);
222
+ case "notifications/resources/list_changed":
223
+ return Boolean(this.filter.resourcesListChanged);
224
+ case "notifications/resources/updated":
225
+ return typeof params?.uri === "string" && (this.filter.resourceSubscriptions ?? []).includes(params.uri);
226
+ default:
227
+ return false;
228
+ }
229
+ }
230
+ deliver(method, params) {
231
+ if (!this.wants(method, params))
232
+ return;
233
+ if (!this.ready) {
234
+ this.queue.push([method, params]);
235
+ return;
236
+ }
237
+ const meta = isObject(params?._meta) ? params._meta : {};
238
+ writeSse(this.res, { jsonrpc: "2.0", method, params: { ...(params ?? {}), _meta: { ...meta, [SUBSCRIPTION_ID]: this.id } } });
239
+ }
240
+ /** Send the acknowledgment, then whatever arrived while the subscription was being set up. */
241
+ acknowledge() {
242
+ writeSse(this.res, {
243
+ jsonrpc: "2.0",
244
+ method: "notifications/subscriptions/acknowledged",
245
+ params: { _meta: { [SUBSCRIPTION_ID]: this.id }, notifications: this.filter },
246
+ });
247
+ this.ready = true;
248
+ for (const [m, p] of this.queue.splice(0))
249
+ this.deliver(m, p);
250
+ }
251
+ /** Graceful end: the response to the listen request, then close (mcpd is stopping). */
252
+ end() {
253
+ if (this.timer)
254
+ clearInterval(this.timer);
255
+ writeSse(this.res, { jsonrpc: "2.0", id: this.id, result: { resultType: "complete", _meta: { [SUBSCRIPTION_ID]: this.id } } });
256
+ if (!this.res.writableEnded)
257
+ this.res.end();
258
+ }
259
+ }
260
+ /**
261
+ * The agent behind stateless requests: one per profile, server, client PID and folder, so an
262
+ * exclusive lease, a session-scoped instance and the call log see the same client across its
263
+ * requests, as they would see a 2025-11-25 session.
264
+ */
265
+ export class StatelessClient {
266
+ ctx;
267
+ folders;
268
+ id;
269
+ lastSeen = Date.now();
270
+ calls = new Map();
271
+ listeners = new Set();
272
+ constructor(ctx,
273
+ /** The client folder and, for a worktree, its main repository: what folder sets match (ADR 0031). */
274
+ folders = []) {
275
+ this.ctx = ctx;
276
+ this.folders = folders;
277
+ this.id = ctx.sessionId;
278
+ }
279
+ get listening() {
280
+ for (const l of this.listeners)
281
+ if (l.filter.resourcesListChanged)
282
+ return true;
283
+ return false;
284
+ }
285
+ supports(capability) {
286
+ return !SERVER_REQUESTS.has(capability);
287
+ }
288
+ /** Request-scoped notifications go to that request's stream; the rest to the listen streams. */
289
+ notify(method, params, related) {
290
+ if (related === undefined) {
291
+ for (const l of this.listeners)
292
+ l.deliver(method, params);
293
+ return;
294
+ }
295
+ const call = this.calls.get(related);
296
+ if (!call?.stream)
297
+ return;
298
+ if (method === "notifications/progress") {
299
+ writeSse(call.res, { jsonrpc: "2.0", method, ...(params ? { params } : {}) });
300
+ return;
301
+ }
302
+ // The revision: no notifications/message for a request that did not ask for a log level.
303
+ if (method === "notifications/message" && call.logLevel) {
304
+ const level = LOG_LEVELS.indexOf(String(params?.level ?? ""));
305
+ if (level >= LOG_LEVELS.indexOf(call.logLevel))
306
+ writeSse(call.res, { jsonrpc: "2.0", method, ...(params ? { params } : {}) });
307
+ }
308
+ }
309
+ request(method) {
310
+ return Promise.resolve(rpcError(ErrorCode.MethodNotFound, `${this.ctx.serverName} sent ${method}, but the agent speaks MCP ${MODERN_PROTOCOL_VERSION}, and turno does not relay server requests to it yet`));
311
+ }
312
+ }
313
+ /** Serves 2026-07-28 requests for the gateway. */
314
+ export class StatelessFront {
315
+ opts;
316
+ clients = new Map();
317
+ creating = new Map();
318
+ peers = new WeakMap();
319
+ seq = 0;
320
+ constructor(opts) {
321
+ this.opts = opts;
322
+ }
323
+ list() {
324
+ return [...this.clients.values()];
325
+ }
326
+ /** Forget clients whose process exited or that went quiet; their leases and subscriptions go with them. */
327
+ prune(isAlive, now = Date.now()) {
328
+ for (const [key, c] of this.clients) {
329
+ const dead = c.ctx.pid !== undefined && !isAlive(c.ctx.pid);
330
+ const quiet = c.calls.size === 0 && c.listeners.size === 0 && now - c.lastSeen > STATELESS_IDLE_MS;
331
+ if (!dead && !quiet)
332
+ continue;
333
+ this.clients.delete(key);
334
+ for (const l of c.listeners)
335
+ l.end();
336
+ c.listeners.clear();
337
+ this.opts.manager.detach(c);
338
+ }
339
+ }
340
+ /** mcpd is stopping: end every listen stream gracefully. */
341
+ close() {
342
+ for (const c of this.clients.values()) {
343
+ for (const l of c.listeners)
344
+ l.end();
345
+ c.listeners.clear();
346
+ }
347
+ }
348
+ pidOf(req) {
349
+ const h = Number.parseInt(header(req, "x-turno-pid") ?? "", 10);
350
+ if (h > 0)
351
+ return Promise.resolve(h);
352
+ const socket = req.socket;
353
+ if (!this.opts.peerPid || !socket.remotePort)
354
+ return Promise.resolve(undefined);
355
+ let p = this.peers.get(socket);
356
+ if (!p) {
357
+ p = this.opts.peerPid(socket.remotePort).catch(() => undefined);
358
+ this.peers.set(socket, p);
359
+ }
360
+ return p;
361
+ }
362
+ async client(req, name, profile) {
363
+ const pid = await this.pidOf(req);
364
+ const folder = header(req, "x-turno-cwd-b64") ?? header(req, "x-turno-cwd") ?? "";
365
+ const key = JSON.stringify([profile, name, pid ?? null, folder]);
366
+ const known = this.clients.get(key);
367
+ if (known)
368
+ return known;
369
+ let p = this.creating.get(key);
370
+ if (!p) {
371
+ p = (async () => {
372
+ const ctx = await this.opts.context(req, name, profile);
373
+ if (pid && !ctx.pid)
374
+ ctx.pid = pid;
375
+ ctx.sessionId = `stateless-${++this.seq}`;
376
+ const folders = this.opts.folders ? await this.opts.folders(ctx) : [];
377
+ const c = new StatelessClient(ctx, folders);
378
+ this.clients.set(key, c);
379
+ this.opts.manager.register(c);
380
+ return c;
381
+ })();
382
+ this.creating.set(key, p);
383
+ p.finally(() => this.creating.delete(key)).catch(() => { });
384
+ }
385
+ return p;
386
+ }
387
+ /** Answer one 2026-07-28 POST whose body is already parsed. */
388
+ async handle(req, res, name, profile, body) {
389
+ if (!isObject(body) || body.jsonrpc !== "2.0" || typeof body.method !== "string") {
390
+ sendJson(res, 400, errorBody(null, ErrorCode.InvalidRequest, "Invalid Request: the body must be one JSON-RPC request or notification"));
391
+ return;
392
+ }
393
+ const method = body.method;
394
+ const hasId = body.id !== undefined && body.id !== null;
395
+ if (!hasId) {
396
+ // No client notification is defined over HTTP in this revision (cancellation is closing the stream).
397
+ res.writeHead(202).end();
398
+ return;
399
+ }
400
+ if (typeof body.id !== "string" && typeof body.id !== "number") {
401
+ sendJson(res, 400, errorBody(null, ErrorCode.InvalidRequest, "Invalid Request: the id must be a string or a number"));
402
+ return;
403
+ }
404
+ const id = body.id;
405
+ const version = header(req, "mcp-protocol-version")?.trim() ?? "";
406
+ if (!MODERN_PROTOCOL_VERSIONS.includes(version)) {
407
+ sendJson(res, 400, errorBody(id, ModernErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version", { supported: ALL_PROTOCOL_VERSIONS, requested: version }));
408
+ return;
409
+ }
410
+ const params = isObject(body.params) ? body.params : {};
411
+ const mismatch = (message) => sendJson(res, 400, errorBody(id, ModernErrorCode.HeaderMismatch, `Header mismatch: ${message}`));
412
+ const mcpMethod = header(req, "mcp-method");
413
+ if (mcpMethod === undefined)
414
+ return mismatch("missing Mcp-Method header");
415
+ if (mcpMethod !== method)
416
+ return mismatch(`Mcp-Method header value '${mcpMethod}' does not match body value '${method}'`);
417
+ const field = NAMED[method];
418
+ if (field) {
419
+ const sent = header(req, "mcp-name");
420
+ if (sent === undefined)
421
+ return mismatch(`missing Mcp-Name header for ${method}`);
422
+ const decoded = decodeHeaderValue(sent);
423
+ if (decoded === undefined || decoded !== params[field])
424
+ return mismatch(`Mcp-Name header value does not match body value of params.${field}`);
425
+ }
426
+ const meta = isObject(params._meta) ? params._meta : {};
427
+ for (const k of [PROTOCOL_VERSION, CLIENT_CAPABILITIES]) {
428
+ const ok = k === PROTOCOL_VERSION ? typeof meta[k] === "string" : isObject(meta[k]);
429
+ if (!ok) {
430
+ sendJson(res, 400, errorBody(id, ErrorCode.InvalidParams, `Invalid params: _meta["${k}"] is required`));
431
+ return;
432
+ }
433
+ }
434
+ if (meta[PROTOCOL_VERSION] !== version)
435
+ return mismatch(`MCP-Protocol-Version header value '${version}' does not match _meta value '${String(meta[PROTOCOL_VERSION])}'`);
436
+ if (REMOVED.has(method)) {
437
+ sendJson(res, 404, errorBody(id, ErrorCode.MethodNotFound, `Method not found: ${method} is not part of MCP ${version}`));
438
+ return;
439
+ }
440
+ const client = await this.client(req, name, profile);
441
+ client.lastSeen = Date.now();
442
+ const caps = meta[CLIENT_CAPABILITIES];
443
+ // Capabilities mcpd cannot honor for this client are not passed on to the server.
444
+ client.ctx.clientCapabilities = Object.fromEntries(Object.entries(caps).filter(([k]) => !SERVER_REQUESTS.has(k)));
445
+ const agent = cleanAgentName(isObject(meta[CLIENT_INFO]) ? meta[CLIENT_INFO].name : undefined);
446
+ if (agent)
447
+ client.ctx.clientName = agent;
448
+ // Outside the folder's server set (ADR 0031): answer from mcpd, never start the server.
449
+ const hidden = this.opts.hiddenBySet?.(client);
450
+ if (hidden)
451
+ return this.hiddenReply(res, id, method, hidden);
452
+ try {
453
+ if (method === "server/discover")
454
+ return await this.discover(res, id, client);
455
+ if (LISTS[method])
456
+ return await this.answerList(res, id, method, client);
457
+ if (method === "subscriptions/listen")
458
+ return await this.listen(req, res, id, params, client);
459
+ return await this.forward(req, res, id, method, params, meta, client);
460
+ }
461
+ catch (err) {
462
+ this.reply(res, id, method, rpcError(ErrorCode.Internal, `${name}: ${err.message}`));
463
+ }
464
+ }
465
+ /** A hidden server: no capabilities, empty lists that are not cached, every other request refused. */
466
+ hiddenReply(res, id, method, why) {
467
+ if (method === "server/discover") {
468
+ this.reply(res, id, method, { result: { supportedVersions: ALL_PROTOCOL_VERSIONS, capabilities: {}, instructions: why, ttlMs: 0, cacheScope: "private" } });
469
+ return;
470
+ }
471
+ const spec = LISTS[method] ?? (method === "resources/list" ? { field: "resources" } : undefined);
472
+ if (spec) {
473
+ this.reply(res, id, method, { result: { [spec.field]: [], ttlMs: 0, cacheScope: "private" } });
474
+ return;
475
+ }
476
+ this.reply(res, id, method, rpcError(ErrorCode.InvalidParams, why));
477
+ }
478
+ /** ttlMs for a cached description: trusted only once a running server confirmed it. */
479
+ ttl(d) {
480
+ return this.opts.manager.verified(d) ? LIST_TTL_MS : 0;
481
+ }
482
+ stamp(result, serverInfo) {
483
+ const meta = isObject(result._meta) ? result._meta : {};
484
+ return { ...result, resultType: typeof result.resultType === "string" ? result.resultType : "complete", ...(serverInfo ? { _meta: { ...meta, [SERVER_INFO]: serverInfo } } : {}) };
485
+ }
486
+ reply(res, id, method, outcome, serverInfo) {
487
+ let msg;
488
+ let status = 200;
489
+ if ("error" in outcome) {
490
+ const code = modernErrorCode(outcome.error.code, method);
491
+ if (code === ErrorCode.MethodNotFound)
492
+ status = 404;
493
+ msg = { jsonrpc: "2.0", id, error: { ...outcome.error, code } };
494
+ }
495
+ else {
496
+ let result = this.stamp(outcome.result, serverInfo);
497
+ if (UNCACHED.has(method))
498
+ result = { ...result, ttlMs: 0, cacheScope: "private" };
499
+ msg = { jsonrpc: "2.0", id, result };
500
+ }
501
+ if (res.headersSent) {
502
+ writeSse(res, msg);
503
+ if (!res.writableEnded)
504
+ res.end();
505
+ return;
506
+ }
507
+ sendJson(res, status, msg);
508
+ }
509
+ async discover(res, id, client) {
510
+ const d = await this.opts.manager.describe(client);
511
+ // 2025-11-25 tasks are an extension in 2026-07-28, which mcpd does not offer.
512
+ const { tasks: _tasks, ...caps } = this.opts.capabilities(d.capabilities);
513
+ const result = {
514
+ supportedVersions: ALL_PROTOCOL_VERSIONS,
515
+ capabilities: caps,
516
+ ...(d.instructions ? { instructions: d.instructions } : {}),
517
+ ttlMs: this.ttl(d),
518
+ cacheScope: "private",
519
+ };
520
+ this.reply(res, id, "server/discover", { result }, d.serverInfo);
521
+ }
522
+ async answerList(res, id, method, client) {
523
+ const spec = LISTS[method];
524
+ const d = await this.opts.manager.describe(client);
525
+ if (!d.capabilities[spec.cap]) {
526
+ this.reply(res, id, method, rpcError(ErrorCode.MethodNotFound, `${client.ctx.serverName} has no ${spec.cap}`));
527
+ return;
528
+ }
529
+ let items = d[spec.key] ?? [];
530
+ const filter = spec.key === "tools" ? this.opts.toolFilter(client.ctx) : undefined;
531
+ if (filter)
532
+ items = items.filter((t) => toolAllowed(filter, String(t.name ?? "")));
533
+ // Private: lists differ by profile (variants, tool filters), and the profile token is the authorization context.
534
+ this.reply(res, id, method, { result: { [spec.field]: items, ttlMs: this.ttl(d), cacheScope: "private" } }, d.serverInfo);
535
+ }
536
+ async forward(req, res, id, method, params, meta, client) {
537
+ const manager = this.opts.manager;
538
+ if (method === "tools/call") {
539
+ 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
+ const d = await manager.describe(client);
546
+ const def = (d.tools ?? []).find((t) => isObject(t) && t.name === tool);
547
+ const problem = def ? paramHeaderProblem(def, params.arguments, req.headers) : undefined;
548
+ if (problem) {
549
+ sendJson(res, 400, errorBody(id, ModernErrorCode.HeaderMismatch, `Header mismatch: ${problem}`));
550
+ return;
551
+ }
552
+ }
553
+ // The upstream speaks 2025-11-25: the per-request protocol fields stay here.
554
+ const upMeta = Object.fromEntries(Object.entries(meta).filter(([k]) => !k.startsWith("io.modelcontextprotocol/")));
555
+ const { _meta: _drop, ...rest } = params;
556
+ 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 } : {}) };
559
+ // Our own id for the call, so two requests of one client never collide upstream.
560
+ const internal = `h${++this.seq}`;
561
+ client.calls.set(internal, call);
562
+ if (call.stream)
563
+ openSse(res);
564
+ let settled = false;
565
+ let closed = false;
566
+ res.on("close", () => {
567
+ if (settled)
568
+ return;
569
+ closed = true;
570
+ // Closing the response is the cancellation signal in this revision.
571
+ try {
572
+ manager.existing(client)?.upstream.notify("notifications/cancelled", { requestId: internal, reason: "the client closed the request" }, client);
573
+ }
574
+ catch {
575
+ /* the server left the manifest; nothing to cancel */
576
+ }
577
+ });
578
+ let outcome;
579
+ try {
580
+ outcome = await manager.forward(client, method, upParams, internal, () => closed);
581
+ }
582
+ finally {
583
+ settled = true;
584
+ client.calls.delete(internal);
585
+ client.lastSeen = Date.now();
586
+ }
587
+ if (res.destroyed || res.writableEnded)
588
+ return;
589
+ this.reply(res, id, method, outcome, manager.cachedDescription(client)?.serverInfo);
590
+ }
591
+ async listen(_req, res, id, params, client) {
592
+ const manager = this.opts.manager;
593
+ const asked = isObject(params.notifications) ? params.notifications : {};
594
+ const d = await manager.describe(client);
595
+ const caps = d.capabilities;
596
+ const filter = {};
597
+ if (asked.toolsListChanged === true && caps.tools)
598
+ filter.toolsListChanged = true;
599
+ if (asked.promptsListChanged === true && caps.prompts)
600
+ filter.promptsListChanged = true;
601
+ if (asked.resourcesListChanged === true && caps.resources)
602
+ filter.resourcesListChanged = true;
603
+ const uris = Array.isArray(asked.resourceSubscriptions) ? asked.resourceSubscriptions.filter((u) => typeof u === "string" && u !== "") : [];
604
+ const listener = new Listener(res, id, filter);
605
+ openSse(res);
606
+ client.listeners.add(listener);
607
+ let open = true;
608
+ const subscribed = [];
609
+ // Drop upstream subscriptions no other stream of this client still wants.
610
+ const release = (list) => {
611
+ for (const uri of list) {
612
+ if ([...client.listeners].some((l) => l.filter.resourceSubscriptions?.includes(uri)))
613
+ continue;
614
+ void manager.unsubscribe(client, uri, `h${++this.seq}`).catch(() => { });
615
+ }
616
+ };
617
+ res.on("close", () => {
618
+ open = false;
619
+ if (listener.timer)
620
+ clearInterval(listener.timer);
621
+ client.listeners.delete(listener);
622
+ release([...subscribed]);
623
+ });
624
+ const subscribes = isObject(caps.resources) && caps.resources.subscribe === true;
625
+ if (uris.length && subscribes) {
626
+ for (const uri of uris) {
627
+ const out = await manager.subscribe(client, uri, `h${++this.seq}`);
628
+ if ("error" in out)
629
+ this.opts.log?.(`${client.ctx.serverName}: subscriptions/listen could not subscribe to a resource: ${out.error.message}`);
630
+ else if (!open)
631
+ release([uri]);
632
+ else
633
+ subscribed.push(uri);
634
+ }
635
+ if (subscribed.length)
636
+ filter.resourceSubscriptions = [...subscribed];
637
+ }
638
+ if (!open)
639
+ return;
640
+ listener.acknowledge();
641
+ listener.timer = setInterval(() => {
642
+ if (!res.writableEnded && !res.destroyed)
643
+ res.write(": keep-alive\n\n");
644
+ }, KEEPALIVE_MS);
645
+ listener.timer.unref();
646
+ }
647
+ }
648
+ //# sourceMappingURL=modern.js.map