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.
- package/CHANGELOG.md +148 -0
- package/README.md +127 -39
- package/dist/accounts/audit.js +27 -15
- package/dist/accounts/builtin.js +35 -7
- package/dist/accounts/delegate.js +30 -7
- package/dist/accounts/policy.js +4 -2
- package/dist/accounts/registry.js +3 -1
- package/dist/agents/adapter.js +22 -0
- package/dist/agents/claude.js +54 -3
- package/dist/agents/codex.js +94 -6
- package/dist/agents/copilot.js +19 -2
- package/dist/agents/cursor.js +19 -2
- package/dist/agents/index.js +1 -1
- package/dist/agents/snippets.js +37 -10
- package/dist/cli/args.js +32 -15
- package/dist/cli/commands/accounts.js +29 -7
- package/dist/cli/commands/auto.js +50 -12
- package/dist/cli/commands/browser-identity.js +514 -0
- package/dist/cli/commands/browser-session.js +102 -0
- package/dist/cli/commands/browser-vault.js +193 -0
- package/dist/cli/commands/browser.js +159 -59
- package/dist/cli/commands/complete.js +13 -3
- package/dist/cli/commands/completion.js +4 -0
- package/dist/cli/commands/config.js +90 -13
- package/dist/cli/commands/demo.js +36 -7
- package/dist/cli/commands/doctor.js +170 -36
- package/dist/cli/commands/identity.js +99 -12
- package/dist/cli/commands/init.js +42 -10
- package/dist/cli/commands/limit.js +65 -9
- package/dist/cli/commands/mcp-call.js +240 -0
- package/dist/cli/commands/mcp-oauth.js +33 -6
- package/dist/cli/commands/mcp-observe.js +128 -23
- package/dist/cli/commands/mcp-share.js +201 -0
- package/dist/cli/commands/mcp.js +203 -42
- package/dist/cli/commands/mcpd.js +76 -12
- package/dist/cli/commands/open.js +26 -3
- package/dist/cli/commands/profile.js +212 -30
- package/dist/cli/commands/resolve.js +8 -1
- package/dist/cli/commands/run.js +24 -4
- package/dist/cli/commands/secret.js +23 -38
- package/dist/cli/commands/session.js +16 -5
- package/dist/cli/commands/sessions.js +7 -1
- package/dist/cli/commands/setup.js +83 -11
- package/dist/cli/commands/status.js +67 -15
- package/dist/cli/commands/statusline.js +7 -2
- package/dist/cli/commands/ui.js +17 -5
- package/dist/cli/commands/undo.js +39 -7
- package/dist/cli/commands/uninstall.js +24 -5
- package/dist/cli/commands/upgrade.js +113 -76
- package/dist/cli/commands/usage.js +11 -10
- package/dist/cli/commands/version.js +20 -8
- package/dist/cli/commands/which.js +5 -3
- package/dist/cli/diagnostics.js +184 -0
- package/dist/cli/exit.js +65 -0
- package/dist/cli/group.js +20 -8
- package/dist/cli/help.js +6 -1
- package/dist/cli/hints.js +30 -0
- package/dist/cli/io.js +24 -8
- package/dist/cli/launch.js +31 -2
- package/dist/cli/launchers.js +25 -10
- package/dist/cli/main.js +52 -18
- package/dist/cli/optional.js +144 -0
- package/dist/cli/output.js +123 -0
- package/dist/cli/picker.js +17 -5
- package/dist/cli/registry.js +20 -2
- package/dist/cli/safe.js +87 -0
- package/dist/cli/secret-input.js +63 -0
- package/dist/cli/security.js +31 -9
- package/dist/cli/style.js +35 -5
- package/dist/cli/topics.js +142 -0
- package/dist/core/config.js +39 -3
- package/dist/core/fsutil.js +2 -10
- package/dist/core/journal.js +19 -11
- package/dist/core/manifest.js +28 -1
- package/dist/core/paths.js +6 -112
- package/dist/core/profiles.js +28 -8
- package/dist/core/resolve.js +13 -3
- package/dist/core/secrets.js +4 -154
- package/dist/core/state-file.js +107 -0
- package/dist/core/update.js +14 -11
- package/dist/core/version.js +57 -10
- package/dist/demo/server.js +10 -2
- package/dist/mcpd/cache.js +6 -7
- package/dist/mcpd/calllog.js +10 -9
- package/dist/mcpd/client-names.js +8 -13
- package/dist/mcpd/connectors.js +42 -3
- package/dist/mcpd/daemon.js +29 -8
- package/dist/mcpd/folder-sets.js +5 -2
- package/dist/mcpd/gateway.js +57 -29
- package/dist/mcpd/health.js +69 -25
- package/dist/mcpd/importer.js +106 -9
- package/dist/mcpd/instances.js +59 -31
- package/dist/mcpd/jsonrpc.js +3 -1
- package/dist/mcpd/middleware.js +144 -0
- package/dist/mcpd/modern.js +57 -19
- package/dist/mcpd/oauth.js +71 -17
- package/dist/mcpd/peerpid.js +15 -3
- package/dist/mcpd/pressure.js +4 -1
- package/dist/mcpd/rss.js +34 -19
- package/dist/mcpd/service.js +28 -4
- package/dist/mcpd/share.js +217 -0
- package/dist/mcpd/state.js +16 -16
- package/dist/mcpd/sync.js +22 -12
- package/dist/mcpd/systemd.js +4 -1
- package/dist/mcpd/tokens.js +4 -8
- package/dist/mcpd/upstream.js +12 -5
- package/dist/statusline/cost.js +17 -4
- package/dist/statusline/input.js +15 -3
- package/dist/ui/fonts.js +1 -1
- package/dist/ui/settings.js +6 -1
- package/npm-shrinkwrap.json +12 -3
- package/package.json +7 -6
package/dist/mcpd/importer.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { parse, stringify } from "smol-toml";
|
|
4
|
+
import { isGatewayEntry } from "../agents/adapter.js";
|
|
4
5
|
import { SCAN_ORDER, adapter, agentProfileDir } from "../agents/index.js";
|
|
5
6
|
import { tildify } from "../core/paths.js";
|
|
6
7
|
import { isObject, readJsonFile } from "../core/fsutil.js";
|
|
@@ -115,6 +116,67 @@ export function urlSecrets(url) {
|
|
|
115
116
|
out.push(v);
|
|
116
117
|
return out;
|
|
117
118
|
}
|
|
119
|
+
/**
|
|
120
|
+
* Whether the MCP server at `url` asks for an OAuth login: an unauthenticated `initialize`
|
|
121
|
+
* answered with 401 and a `WWW-Authenticate: Bearer` challenge (MCP authorization spec). Any
|
|
122
|
+
* other answer, an error or no answer within `timeoutMs` is no.
|
|
123
|
+
*/
|
|
124
|
+
export async function probeOAuth(url, timeoutMs = 5000) {
|
|
125
|
+
if (!/^https?:\/\//i.test(url))
|
|
126
|
+
return false;
|
|
127
|
+
try {
|
|
128
|
+
const res = await fetch(url, {
|
|
129
|
+
method: "POST",
|
|
130
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
|
|
131
|
+
body: JSON.stringify({
|
|
132
|
+
jsonrpc: "2.0",
|
|
133
|
+
id: 1,
|
|
134
|
+
method: "initialize",
|
|
135
|
+
params: {
|
|
136
|
+
protocolVersion: "2025-11-25",
|
|
137
|
+
capabilities: {},
|
|
138
|
+
clientInfo: { name: "turno-mcp-import", version: "0" },
|
|
139
|
+
},
|
|
140
|
+
}),
|
|
141
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
142
|
+
redirect: "manual",
|
|
143
|
+
});
|
|
144
|
+
await res.body?.cancel().catch(() => undefined);
|
|
145
|
+
const challenge = res.headers.get("www-authenticate") ?? "";
|
|
146
|
+
return res.status === 401 && /^\s*bearer\b/i.test(challenge);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Mark remote servers that ask for OAuth with `auth = "oauth"`, so mcpd logs in for
|
|
154
|
+
* them. Only servers with no auth of their own are probed: no `auth`, no Authorization header,
|
|
155
|
+
* no header that holds a secret or a variable. Returns the names it marked.
|
|
156
|
+
*/
|
|
157
|
+
export async function markOAuth(servers, probe, notes) {
|
|
158
|
+
const candidates = Object.entries(servers).filter(([, s]) => {
|
|
159
|
+
if (typeof s.url !== "string" || s.auth !== undefined)
|
|
160
|
+
return false;
|
|
161
|
+
const headers = (s.headers ?? {});
|
|
162
|
+
return !Object.entries(headers).some(([k, v]) => k.toLowerCase() === "authorization" ||
|
|
163
|
+
(typeof v === "string" &&
|
|
164
|
+
(v.startsWith("keychain:") || v.startsWith("env:") || ANY_VAR.test(v) || isSecretValue(k, v))));
|
|
165
|
+
});
|
|
166
|
+
const answers = await Promise.all(candidates.map(([, s]) => probe(s.url)));
|
|
167
|
+
const marked = [];
|
|
168
|
+
for (const [i, [name, s]] of candidates.entries()) {
|
|
169
|
+
if (!answers[i])
|
|
170
|
+
continue;
|
|
171
|
+
s.auth = "oauth";
|
|
172
|
+
marked.push(name);
|
|
173
|
+
const direct = notes.indexOf(`${name}: remote, written directly into profiles`);
|
|
174
|
+
if (direct >= 0)
|
|
175
|
+
notes.splice(direct, 1);
|
|
176
|
+
notes.push(`${name}: asks for an OAuth login; marked auth = "oauth" so mcpd logs in for your profiles (turno mcp login ${name})`);
|
|
177
|
+
}
|
|
178
|
+
return marked;
|
|
179
|
+
}
|
|
118
180
|
function packageName(spec) {
|
|
119
181
|
const at = spec.lastIndexOf("@");
|
|
120
182
|
return at > 0 ? spec.slice(0, at) : spec;
|
|
@@ -131,9 +193,13 @@ export function guessScope(text) {
|
|
|
131
193
|
for (const k of KNOWN)
|
|
132
194
|
if (k.match.test(text))
|
|
133
195
|
return { scope: k.scope, note: k.note };
|
|
134
|
-
return {
|
|
196
|
+
return {
|
|
197
|
+
scope: "project",
|
|
198
|
+
note: 'unknown server, one process per project folder; set scope = "shared" if it ignores its folder',
|
|
199
|
+
};
|
|
135
200
|
}
|
|
136
|
-
|
|
201
|
+
/** The key part of a Keychain service name for a secret: `turno/<server>/<key>`. */
|
|
202
|
+
export function serviceKey(key) {
|
|
137
203
|
return key.toLowerCase().replace(/[^a-z0-9]+/g, "-");
|
|
138
204
|
}
|
|
139
205
|
function mapStrings(v, f) {
|
|
@@ -291,6 +357,10 @@ export async function importServers(servers, opts = {}) {
|
|
|
291
357
|
notes.push(`${name}: remote, ${proxy ? "proxied by mcpd so its secrets stay out of profile configs" : "written directly into profiles"}`);
|
|
292
358
|
out[name] = server;
|
|
293
359
|
}
|
|
360
|
+
if (opts.probeAuth)
|
|
361
|
+
await markOAuth(out, opts.probeAuth, notes);
|
|
362
|
+
else if (Object.values(out).some((s) => typeof s.url === "string"))
|
|
363
|
+
notes.push("remote servers are checked for OAuth when written");
|
|
294
364
|
const toml = `${HEADER}${stringify({ server: out })}\n`;
|
|
295
365
|
const masks = new Map([...hidden].sort((a, b) => b.length - a.length).map((v) => [v, maskSecret(v)]));
|
|
296
366
|
const masked = mapStrings(out, (s) => {
|
|
@@ -306,13 +376,7 @@ export async function importServers(servers, opts = {}) {
|
|
|
306
376
|
.join("\n");
|
|
307
377
|
return { toml, preview: `${preview}\n`, notes, secrets, literalSecrets, fixedSecrets, servers: Object.keys(out) };
|
|
308
378
|
}
|
|
309
|
-
|
|
310
|
-
function isGatewayEntry(e) {
|
|
311
|
-
const headers = { ...(e.headers ?? {}), ...(e.http_headers ?? {}) };
|
|
312
|
-
if (Object.keys(headers).some((h) => h.toLowerCase() === "x-turno-profile"))
|
|
313
|
-
return true;
|
|
314
|
-
return e.bearer_token_env_var === "TURNO_MCPD_TOKEN";
|
|
315
|
-
}
|
|
379
|
+
// Entries turno itself wrote (gateway entries) are skipped: importing them back would loop.
|
|
316
380
|
function objectsOf(v) {
|
|
317
381
|
if (!v || typeof v !== "object" || Array.isArray(v))
|
|
318
382
|
return {};
|
|
@@ -333,6 +397,39 @@ function readConfig(file, store) {
|
|
|
333
397
|
const v = JSON.parse(text);
|
|
334
398
|
return v && typeof v === "object" ? v : {};
|
|
335
399
|
}
|
|
400
|
+
/**
|
|
401
|
+
* The MCP servers of one agent config file given to `turno mcp import <file>`, in Claude Code's
|
|
402
|
+
* shape: JSON with `mcpServers` (Claude Code, Cursor, Copilot CLI) or TOML with `[mcp_servers]`
|
|
403
|
+
* (Codex). Undefined when the text is neither. Gateway entries are skipped.
|
|
404
|
+
*/
|
|
405
|
+
export function agentConfigServers(text) {
|
|
406
|
+
let json;
|
|
407
|
+
let toml;
|
|
408
|
+
try {
|
|
409
|
+
json = JSON.parse(text);
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
try {
|
|
413
|
+
toml = parse(text);
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
return undefined;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
for (const id of SCAN_ORDER) {
|
|
420
|
+
const a = adapter(id);
|
|
421
|
+
const cfg = a.mcp.store.format === "json" ? json : toml;
|
|
422
|
+
if (!cfg || typeof cfg !== "object" || !(a.mcp.store.key in cfg))
|
|
423
|
+
continue;
|
|
424
|
+
const raw = objectsOf(cfg[a.mcp.store.key]);
|
|
425
|
+
const toImport = a.mcp.toImport;
|
|
426
|
+
return {
|
|
427
|
+
agent: a.label,
|
|
428
|
+
servers: toImport ? Object.fromEntries(Object.entries(raw).map(([k, e]) => [k, toImport(e)])) : raw,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
return undefined;
|
|
432
|
+
}
|
|
336
433
|
/**
|
|
337
434
|
* Every MCP server configured for an agent on this machine, in the order of SCAN_ORDER: each
|
|
338
435
|
* agent's hub file (Claude Code also its per-project servers and the folder's .mcp.json, Codex
|
package/dist/mcpd/instances.js
CHANGED
|
@@ -36,7 +36,10 @@ function memo(ttlMs, compute) {
|
|
|
36
36
|
/** Git top level of a folder (worktree-specific), else the folder itself. Async, cached for 10 s. */
|
|
37
37
|
export const projectRoot = memo(10_000, async (cwd) => {
|
|
38
38
|
try {
|
|
39
|
-
const { stdout } = await run("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
|
|
39
|
+
const { stdout } = await run("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
|
|
40
|
+
encoding: "utf8",
|
|
41
|
+
timeout: 3000,
|
|
42
|
+
});
|
|
40
43
|
return stdout.trim() || cwd;
|
|
41
44
|
}
|
|
42
45
|
catch {
|
|
@@ -59,7 +62,10 @@ export const processCwd = memo(60_000, async (pid) => {
|
|
|
59
62
|
}
|
|
60
63
|
}
|
|
61
64
|
try {
|
|
62
|
-
const { stdout } = await run("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fn"], {
|
|
65
|
+
const { stdout } = await run("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fn"], {
|
|
66
|
+
encoding: "utf8",
|
|
67
|
+
timeout: 3000,
|
|
68
|
+
});
|
|
63
69
|
const line = stdout.split("\n").find((l) => l.startsWith("n"));
|
|
64
70
|
return line ? line.slice(1) : undefined;
|
|
65
71
|
}
|
|
@@ -82,16 +88,25 @@ export function descriptionFingerprint(server, variant) {
|
|
|
82
88
|
if (server.kind === "remote")
|
|
83
89
|
return fingerprint({ url: server.url, headers: Object.keys(server.headers) });
|
|
84
90
|
const launch = effectiveLaunch(server, variant);
|
|
85
|
-
return fingerprint({
|
|
91
|
+
return fingerprint({
|
|
92
|
+
c: launch.command,
|
|
93
|
+
a: launch.args,
|
|
94
|
+
e: launch.env,
|
|
95
|
+
v: variant,
|
|
96
|
+
p: server.package ?? null,
|
|
97
|
+
b: server.builtin ?? null,
|
|
98
|
+
});
|
|
86
99
|
}
|
|
87
100
|
/**
|
|
88
101
|
* Fingerprint of the whole definition (launch, scope, cwd, exclusive, idle, lease, timeouts),
|
|
89
|
-
* except who gets it and which tools they see: tool filters apply per request
|
|
102
|
+
* except who gets it and which tools they see: tool filters apply per request, so a
|
|
90
103
|
* changed filter needs no new process.
|
|
91
104
|
*/
|
|
92
105
|
export function definitionFingerprint(server) {
|
|
93
106
|
const { tools: _tools, ...rest } = server;
|
|
94
|
-
const variants = rest.kind === "stdio"
|
|
107
|
+
const variants = rest.kind === "stdio"
|
|
108
|
+
? Object.fromEntries(Object.entries(rest.variants).map(([k, v]) => [k, { ...v, tools: null }]))
|
|
109
|
+
: undefined;
|
|
95
110
|
return fingerprint({ ...rest, profiles: null, ...(variants ? { variants } : {}) });
|
|
96
111
|
}
|
|
97
112
|
/** A server that is gone from the manifest (or no longer proxied) while sessions still use it. */
|
|
@@ -179,7 +194,12 @@ export class InstanceManager {
|
|
|
179
194
|
return { ...base, key: head, workdir: this.opts.home, workdirKnown: false };
|
|
180
195
|
if (scope === "project") {
|
|
181
196
|
const root = ctx.projectRoot ?? ctx.cwd;
|
|
182
|
-
return {
|
|
197
|
+
return {
|
|
198
|
+
...base,
|
|
199
|
+
key: `${head}|root:${root ?? this.opts.home}`,
|
|
200
|
+
workdir: root ?? this.opts.home,
|
|
201
|
+
workdirKnown: root !== undefined,
|
|
202
|
+
};
|
|
183
203
|
}
|
|
184
204
|
const workdir = ctx.cwd ?? this.opts.home;
|
|
185
205
|
const workdirKnown = ctx.cwd !== undefined;
|
|
@@ -245,28 +265,18 @@ export class InstanceManager {
|
|
|
245
265
|
* and retry once on a fresh instance when a remote server forgot our session. `cancelled`
|
|
246
266
|
* says whether the client cancelled the request while the instance was still starting: the
|
|
247
267
|
* upstream has no call to cancel yet, so the request is dropped here instead of sent.
|
|
268
|
+
* `onVariant` learns the variant of the instance that serves it (the call log's).
|
|
269
|
+
* A tools/call comes here through the call middleware (middleware.ts), never directly.
|
|
248
270
|
*/
|
|
249
|
-
async forward(client, method, params, originId, cancelled) {
|
|
250
|
-
const startedAt = Date.now();
|
|
251
|
-
const t0 = performance.now();
|
|
252
|
-
let variant;
|
|
253
|
-
const done = (outcome) => {
|
|
254
|
-
try {
|
|
255
|
-
this.opts.onCall?.({ ctx: client.ctx, method, params, ...(variant ? { variant } : {}), outcome, startedAt, durationMs: performance.now() - t0 });
|
|
256
|
-
}
|
|
257
|
-
catch {
|
|
258
|
-
/* observing a call never fails it */
|
|
259
|
-
}
|
|
260
|
-
return outcome;
|
|
261
|
-
};
|
|
271
|
+
async forward(client, method, params, originId, cancelled, onVariant) {
|
|
262
272
|
for (let attempt = 0;; attempt++) {
|
|
263
273
|
const inst = await this.acquire(client);
|
|
264
274
|
if ("error" in inst || "result" in inst)
|
|
265
|
-
return
|
|
266
|
-
|
|
275
|
+
return inst;
|
|
276
|
+
onVariant?.(inst.variant);
|
|
267
277
|
// Nothing awaits between this check and the call below, so a later cancellation finds it upstream.
|
|
268
278
|
if (cancelled?.())
|
|
269
|
-
return
|
|
279
|
+
return rpcError(ErrorCode.RequestCancelled, "cancelled by the client");
|
|
270
280
|
const timeout = inst.server.callTimeout ? inst.server.callTimeout * 1000 : undefined;
|
|
271
281
|
const out = await inst.upstream.call(method, params, client, originId, timeout);
|
|
272
282
|
if ("error" in out && inst.upstream.sessionLost && attempt === 0) {
|
|
@@ -275,7 +285,7 @@ export class InstanceManager {
|
|
|
275
285
|
this.instances.delete(inst.key);
|
|
276
286
|
continue;
|
|
277
287
|
}
|
|
278
|
-
return
|
|
288
|
+
return out;
|
|
279
289
|
}
|
|
280
290
|
}
|
|
281
291
|
/** resources/subscribe: one upstream subscription per URI and instance, many client subscribers. */
|
|
@@ -327,7 +337,9 @@ export class InstanceManager {
|
|
|
327
337
|
if (caps.prompts)
|
|
328
338
|
d.prompts = await inst.upstream.listAll("prompts/list", "prompts");
|
|
329
339
|
if (caps.resources)
|
|
330
|
-
d.resourceTemplates = await inst.upstream
|
|
340
|
+
d.resourceTemplates = await inst.upstream
|
|
341
|
+
.listAll("resources/templates/list", "resourceTemplates")
|
|
342
|
+
.catch(() => []);
|
|
331
343
|
const prev = this.opts.cache.peek(inst.descKey);
|
|
332
344
|
this.opts.cache.set(inst.descKey, d);
|
|
333
345
|
if (prev) {
|
|
@@ -540,7 +552,7 @@ export class InstanceManager {
|
|
|
540
552
|
this.opts.idleUnderPressure = seconds;
|
|
541
553
|
}
|
|
542
554
|
/**
|
|
543
|
-
* The memory pressure for /status and `turno mcp top
|
|
555
|
+
* The memory pressure for /status and `turno mcp top`: the level the last reap
|
|
544
556
|
* read (null while the feature is off or before the first read), the configured limit, and
|
|
545
557
|
* the idle cap that applies now (null when servers keep their own limits).
|
|
546
558
|
*/
|
|
@@ -549,7 +561,12 @@ export class InstanceManager {
|
|
|
549
561
|
const watched = this.opts.pressure !== undefined && under > 0 && this.pressureCheckedAt !== undefined;
|
|
550
562
|
const level = watched ? this.pressureLevel : null;
|
|
551
563
|
const cap = level ? effectiveIdle(Number.POSITIVE_INFINITY, level, under) : Number.POSITIVE_INFINITY;
|
|
552
|
-
return {
|
|
564
|
+
return {
|
|
565
|
+
level,
|
|
566
|
+
checkedAt: watched ? (this.pressureCheckedAt ?? null) : null,
|
|
567
|
+
idleUnderPressure: under,
|
|
568
|
+
idleCap: Number.isFinite(cap) ? cap : null,
|
|
569
|
+
};
|
|
553
570
|
}
|
|
554
571
|
/** Read memory pressure; a failing probe counts as normal. Logs when the level changes. */
|
|
555
572
|
async readPressure() {
|
|
@@ -577,7 +594,8 @@ export class InstanceManager {
|
|
|
577
594
|
}
|
|
578
595
|
/**
|
|
579
596
|
* Stop instances whose owner died, whose definition changed, or that sat idle too long; forget
|
|
580
|
-
* dead clients. Under memory pressure the idle limit shrinks
|
|
597
|
+
* dead clients. Under memory pressure the idle limit shrinks, and under critical
|
|
598
|
+
* pressure it applies to session servers too.
|
|
581
599
|
*/
|
|
582
600
|
async reap() {
|
|
583
601
|
const stopped = [];
|
|
@@ -592,13 +610,23 @@ export class InstanceManager {
|
|
|
592
610
|
const ownerAlive = inst.pid !== undefined && this.isAlive(inst.pid);
|
|
593
611
|
const ownerDead = inst.pid !== undefined && !ownerAlive;
|
|
594
612
|
const stale = quiet && !this.current(inst);
|
|
595
|
-
// A session server lives as long as its session: its state (a browser, a login) is the
|
|
596
|
-
|
|
613
|
+
// A session server lives as long as its session: its state (a browser, a login) is the
|
|
614
|
+
// point. Under critical memory pressure a quiet one stops like any other; the next call
|
|
615
|
+
// starts it again.
|
|
616
|
+
const idleApplies = !(inst.scope === "session" && ownerAlive && level !== "critical");
|
|
597
617
|
const limit = effectiveIdle(inst.server.idle, level, this.opts.idleUnderPressure ?? 0);
|
|
598
618
|
const idleFor = this.now() - inst.upstream.lastActivity;
|
|
599
619
|
const idle = idleApplies && quiet && idleFor > limit * 1000;
|
|
600
620
|
if (ownerDead || stale || idle) {
|
|
601
|
-
|
|
621
|
+
// Only pressure stops a session server whose launcher lives, whatever its own limit.
|
|
622
|
+
const ownLimit = idleFor > inst.server.idle * 1000 && !(inst.scope === "session" && ownerAlive);
|
|
623
|
+
const why = ownerDead
|
|
624
|
+
? "owner exited"
|
|
625
|
+
: stale
|
|
626
|
+
? "definition changed"
|
|
627
|
+
: ownLimit
|
|
628
|
+
? "idle"
|
|
629
|
+
: "idle (memory pressure)";
|
|
602
630
|
this.instances.delete(inst.key);
|
|
603
631
|
// That key never comes back (dead PID, old definition): forget its start count.
|
|
604
632
|
if (ownerDead || stale)
|
|
@@ -645,7 +673,7 @@ export class InstanceManager {
|
|
|
645
673
|
* Resolve a command against an installed package (turno mcp install). A declared package that
|
|
646
674
|
* is not installed still runs through `npx -y -p <package> <command>`, with a warning: `mcp
|
|
647
675
|
* import` writes `package` and `mcp install` is a separate step, so failing here would break
|
|
648
|
-
* imported setups
|
|
676
|
+
* imported setups.
|
|
649
677
|
*/
|
|
650
678
|
export function resolveCommand(server, command, args, serversDir) {
|
|
651
679
|
if (server.package) {
|
package/dist/mcpd/jsonrpc.js
CHANGED
|
@@ -19,7 +19,9 @@ export const ErrorCode = {
|
|
|
19
19
|
RequestCancelled: -32800,
|
|
20
20
|
};
|
|
21
21
|
export function toResponse(id, outcome) {
|
|
22
|
-
return "error" in outcome
|
|
22
|
+
return "error" in outcome
|
|
23
|
+
? { jsonrpc: "2.0", id, error: outcome.error }
|
|
24
|
+
: { jsonrpc: "2.0", id, result: outcome.result };
|
|
23
25
|
}
|
|
24
26
|
export function rpcError(code, message, data) {
|
|
25
27
|
return { error: data === undefined ? { code, message } : { code, message, data } };
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { filtersTools, toolAllowed, toolFilterFor } from "../core/manifest.js";
|
|
3
|
+
import { ErrorCode, rpcError } from "./jsonrpc.js";
|
|
4
|
+
/**
|
|
5
|
+
* The call middleware. Every `tools/call` mcpd relays, from a 2025-11-25 session
|
|
6
|
+
* (gateway.ts) or a 2026-07-28 stateless request (modern.ts), goes through one pipeline of
|
|
7
|
+
* named stages before `InstanceManager.forward`:
|
|
8
|
+
*
|
|
9
|
+
* filter -> <opt-in stages, in order> -> calllog -> session -> forward
|
|
10
|
+
*
|
|
11
|
+
* - `filter` refuses a tool the profile's `tools.allow` / `tools.deny` hides. A
|
|
12
|
+
* refused call reaches no other stage and is not logged.
|
|
13
|
+
* - opt-in stages (none ship yet; later tool-output trimming, local telemetry counters, a cost
|
|
14
|
+
* meter) are off by default: each is a `CallStage` that something turns on explicitly. They
|
|
15
|
+
* see the call as the client sent it, and the outcome the client gets.
|
|
16
|
+
* - `calllog` times the call and hands one event to the call log when it is on.
|
|
17
|
+
* - `session` puts the client session id in the forwarded `_meta` (`io.turno/session`).
|
|
18
|
+
*
|
|
19
|
+
* Stage names are unique, lowercase, and never a built-in name.
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* The `_meta` key of the client session id. Typed by turno-browser's own constant (a type
|
|
23
|
+
* import, erased at build): if the two ever differ, the typecheck fails.
|
|
24
|
+
*/
|
|
25
|
+
export const SESSION_META = "io.turno/session";
|
|
26
|
+
const BUILT_IN = ["filter", "calllog", "session"];
|
|
27
|
+
const STAGE_NAME = /^[a-z][a-z0-9-]*$/;
|
|
28
|
+
/** A profile's tool filter for a client's server, or undefined when it filters nothing. */
|
|
29
|
+
export function toolFilterOf(manifest, ctx) {
|
|
30
|
+
const server = manifest.servers[ctx.serverName];
|
|
31
|
+
if (!server)
|
|
32
|
+
return undefined;
|
|
33
|
+
const f = toolFilterFor(server, ctx.profile);
|
|
34
|
+
return filtersTools(f) ? f : undefined;
|
|
35
|
+
}
|
|
36
|
+
/** `filter`: a tool the profile's filter hides is refused here, before anything else runs. */
|
|
37
|
+
function filterStage(manifest) {
|
|
38
|
+
return {
|
|
39
|
+
name: "filter",
|
|
40
|
+
run(call, next) {
|
|
41
|
+
const filter = toolFilterOf(manifest(), call.client.ctx);
|
|
42
|
+
if (filter && !toolAllowed(filter, call.tool)) {
|
|
43
|
+
const { serverName, profile } = call.client.ctx;
|
|
44
|
+
return Promise.resolve(rpcError(ErrorCode.InvalidParams, `tool ${call.tool} of ${serverName} is not available to profile ${profile ?? "default"} (tools.allow / tools.deny in mcp.toml)`));
|
|
45
|
+
}
|
|
46
|
+
return next(call);
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** `calllog`: times the call and reports it to the call log, when one is on (read per call). */
|
|
51
|
+
function callLogStage(sink) {
|
|
52
|
+
return {
|
|
53
|
+
name: "calllog",
|
|
54
|
+
async run(call, next) {
|
|
55
|
+
const startedAt = Date.now();
|
|
56
|
+
const t0 = performance.now();
|
|
57
|
+
const params = call.params;
|
|
58
|
+
const outcome = await next(call);
|
|
59
|
+
const record = sink();
|
|
60
|
+
if (record) {
|
|
61
|
+
try {
|
|
62
|
+
record({
|
|
63
|
+
ctx: call.client.ctx,
|
|
64
|
+
method: "tools/call",
|
|
65
|
+
params,
|
|
66
|
+
...(call.variant ? { variant: call.variant } : {}),
|
|
67
|
+
outcome,
|
|
68
|
+
startedAt,
|
|
69
|
+
durationMs: performance.now() - t0,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
/* observing a call never fails it */
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return outcome;
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* `session`: the client session id in `_meta[SESSION_META]`. A random UUID per client handle
|
|
82
|
+
* (one 2025-11-25 session, or one stateless client: profile, server, PID and folder), kept for
|
|
83
|
+
* the life of the handle. It is not the Mcp-Session-Id, so a server learns nothing it could use
|
|
84
|
+
* against mcpd. A value the client sent under the same key is replaced.
|
|
85
|
+
*/
|
|
86
|
+
function sessionStage() {
|
|
87
|
+
const ids = new WeakMap();
|
|
88
|
+
return {
|
|
89
|
+
name: "session",
|
|
90
|
+
run(call, next) {
|
|
91
|
+
let id = ids.get(call.client);
|
|
92
|
+
if (!id) {
|
|
93
|
+
id = randomUUID();
|
|
94
|
+
ids.set(call.client, id);
|
|
95
|
+
}
|
|
96
|
+
const meta = typeof call.params._meta === "object" && call.params._meta !== null
|
|
97
|
+
? call.params._meta
|
|
98
|
+
: {};
|
|
99
|
+
call.params = { ...call.params, _meta: { ...meta, [SESSION_META]: id } };
|
|
100
|
+
return next(call);
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/** The ordered stages, and the relay through the instance manager at the end. */
|
|
105
|
+
export class CallPipeline {
|
|
106
|
+
manager;
|
|
107
|
+
stages;
|
|
108
|
+
constructor(manager, stages) {
|
|
109
|
+
this.manager = manager;
|
|
110
|
+
const seen = new Set();
|
|
111
|
+
for (const s of stages) {
|
|
112
|
+
if (!STAGE_NAME.test(s.name))
|
|
113
|
+
throw new Error(`call stage name "${s.name}" must match ${STAGE_NAME}`);
|
|
114
|
+
if (seen.has(s.name))
|
|
115
|
+
throw new Error(`call stage "${s.name}" is registered twice`);
|
|
116
|
+
seen.add(s.name);
|
|
117
|
+
}
|
|
118
|
+
this.stages = [...stages];
|
|
119
|
+
}
|
|
120
|
+
/** The stage names in the order a call meets them. */
|
|
121
|
+
names() {
|
|
122
|
+
return this.stages.map((s) => s.name);
|
|
123
|
+
}
|
|
124
|
+
/** Relay one tools/call through every stage, then `InstanceManager.forward`. */
|
|
125
|
+
call(client, params, originId, cancelled) {
|
|
126
|
+
const relay = (c) => this.manager.forward(c.client, "tools/call", c.params, c.originId, c.cancelled, (variant) => (c.variant = variant));
|
|
127
|
+
const run = this.stages.reduceRight((next, stage) => (c) => stage.run(c, next), relay);
|
|
128
|
+
return run({ client, tool: typeof params.name === "string" ? params.name : "", params, originId, cancelled });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** mcpd's pipeline: the built-in stages around the opt-in ones. */
|
|
132
|
+
export function createCallPipeline(opts) {
|
|
133
|
+
const stages = opts.stages ?? [];
|
|
134
|
+
for (const s of stages)
|
|
135
|
+
if (BUILT_IN.includes(s.name))
|
|
136
|
+
throw new Error(`call stage "${s.name}" is registered twice`);
|
|
137
|
+
return new CallPipeline(opts.manager, [
|
|
138
|
+
filterStage(opts.manifest),
|
|
139
|
+
...stages,
|
|
140
|
+
callLogStage(opts.callLog ?? (() => undefined)),
|
|
141
|
+
sessionStage(),
|
|
142
|
+
]);
|
|
143
|
+
}
|
|
144
|
+
//# sourceMappingURL=middleware.js.map
|
package/dist/mcpd/modern.js
CHANGED
|
@@ -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
|
|
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, {
|
|
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, {
|
|
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, {
|
|
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
|
|
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", {
|
|
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
|
|
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, {
|
|
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 {
|
|
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])
|
|
558
|
-
|
|
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
|
|
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 =
|
|
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)
|
|
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);
|