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.
- package/CHANGELOG.md +266 -0
- package/README.md +134 -42
- 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-do-session.js +170 -0
- package/dist/cli/commands/browser-do.js +740 -0
- package/dist/cli/commands/browser-flows.js +300 -0
- package/dist/cli/commands/browser-identity.js +952 -0
- package/dist/cli/commands/browser-live.js +118 -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 +303 -62
- 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 +101 -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 +155 -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 +70 -26
- package/dist/mcpd/importer.js +106 -9
- package/dist/mcpd/instances.js +70 -32
- package/dist/mcpd/jsonrpc.js +3 -1
- package/dist/mcpd/middleware.js +156 -0
- package/dist/mcpd/modern.js +57 -19
- package/dist/mcpd/oauth.js +71 -17
- package/dist/mcpd/peerpid.js +63 -17
- 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
|
@@ -6,6 +6,7 @@ import { promisify } from "node:util";
|
|
|
6
6
|
import { effectiveLaunch, variantKey } from "../core/manifest.js";
|
|
7
7
|
import { fingerprint } from "./cache.js";
|
|
8
8
|
import { ErrorCode, rpcError } from "./jsonrpc.js";
|
|
9
|
+
import { SESSION_CAPABILITY, SESSION_ENDED, sessionIdOf } from "./middleware.js";
|
|
9
10
|
import { LoginRequiredError } from "./oauth.js";
|
|
10
11
|
import { effectiveIdle } from "./pressure.js";
|
|
11
12
|
import { Upstream } from "./upstream.js";
|
|
@@ -36,7 +37,10 @@ function memo(ttlMs, compute) {
|
|
|
36
37
|
/** Git top level of a folder (worktree-specific), else the folder itself. Async, cached for 10 s. */
|
|
37
38
|
export const projectRoot = memo(10_000, async (cwd) => {
|
|
38
39
|
try {
|
|
39
|
-
const { stdout } = await run("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
|
|
40
|
+
const { stdout } = await run("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
|
|
41
|
+
encoding: "utf8",
|
|
42
|
+
timeout: 3000,
|
|
43
|
+
});
|
|
40
44
|
return stdout.trim() || cwd;
|
|
41
45
|
}
|
|
42
46
|
catch {
|
|
@@ -59,7 +63,10 @@ export const processCwd = memo(60_000, async (pid) => {
|
|
|
59
63
|
}
|
|
60
64
|
}
|
|
61
65
|
try {
|
|
62
|
-
const { stdout } = await run("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fn"], {
|
|
66
|
+
const { stdout } = await run("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fn"], {
|
|
67
|
+
encoding: "utf8",
|
|
68
|
+
timeout: 3000,
|
|
69
|
+
});
|
|
63
70
|
const line = stdout.split("\n").find((l) => l.startsWith("n"));
|
|
64
71
|
return line ? line.slice(1) : undefined;
|
|
65
72
|
}
|
|
@@ -82,16 +89,32 @@ export function descriptionFingerprint(server, variant) {
|
|
|
82
89
|
if (server.kind === "remote")
|
|
83
90
|
return fingerprint({ url: server.url, headers: Object.keys(server.headers) });
|
|
84
91
|
const launch = effectiveLaunch(server, variant);
|
|
85
|
-
return fingerprint({
|
|
92
|
+
return fingerprint({
|
|
93
|
+
c: launch.command,
|
|
94
|
+
a: launch.args,
|
|
95
|
+
e: launch.env,
|
|
96
|
+
v: variant,
|
|
97
|
+
p: server.package ?? null,
|
|
98
|
+
b: server.builtin ?? null,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** A server that declared `SESSION_CAPABILITY` hears that a session it served ended. */
|
|
102
|
+
function tellSessionEnded(inst, session) {
|
|
103
|
+
const experimental = inst.upstream.init?.capabilities.experimental;
|
|
104
|
+
if (typeof experimental !== "object" || experimental === null || !(SESSION_CAPABILITY in experimental))
|
|
105
|
+
return;
|
|
106
|
+
inst.upstream.notify(SESSION_ENDED, { session });
|
|
86
107
|
}
|
|
87
108
|
/**
|
|
88
109
|
* 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
|
|
110
|
+
* except who gets it and which tools they see: tool filters apply per request, so a
|
|
90
111
|
* changed filter needs no new process.
|
|
91
112
|
*/
|
|
92
113
|
export function definitionFingerprint(server) {
|
|
93
114
|
const { tools: _tools, ...rest } = server;
|
|
94
|
-
const variants = rest.kind === "stdio"
|
|
115
|
+
const variants = rest.kind === "stdio"
|
|
116
|
+
? Object.fromEntries(Object.entries(rest.variants).map(([k, v]) => [k, { ...v, tools: null }]))
|
|
117
|
+
: undefined;
|
|
95
118
|
return fingerprint({ ...rest, profiles: null, ...(variants ? { variants } : {}) });
|
|
96
119
|
}
|
|
97
120
|
/** A server that is gone from the manifest (or no longer proxied) while sessions still use it. */
|
|
@@ -142,11 +165,13 @@ export class InstanceManager {
|
|
|
142
165
|
/** A client session ended: cancel its calls, drop it from every instance and release its leases. */
|
|
143
166
|
detach(client) {
|
|
144
167
|
this.clients.delete(client);
|
|
168
|
+
const session = sessionIdOf(client);
|
|
145
169
|
for (const inst of this.instances.values()) {
|
|
146
170
|
const cancelled = inst.upstream.forgetClient(client);
|
|
147
171
|
if (cancelled)
|
|
148
172
|
this.opts.log?.(`cancelled ${cancelled} call(s) of a closed session on ${inst.upstream.label}`);
|
|
149
|
-
inst.clients.delete(client)
|
|
173
|
+
if (inst.clients.delete(client) && session)
|
|
174
|
+
tellSessionEnded(inst, session);
|
|
150
175
|
for (const [uri, subs] of inst.subscriptions) {
|
|
151
176
|
if (subs.delete(client) && subs.size === 0) {
|
|
152
177
|
inst.subscriptions.delete(uri);
|
|
@@ -179,7 +204,12 @@ export class InstanceManager {
|
|
|
179
204
|
return { ...base, key: head, workdir: this.opts.home, workdirKnown: false };
|
|
180
205
|
if (scope === "project") {
|
|
181
206
|
const root = ctx.projectRoot ?? ctx.cwd;
|
|
182
|
-
return {
|
|
207
|
+
return {
|
|
208
|
+
...base,
|
|
209
|
+
key: `${head}|root:${root ?? this.opts.home}`,
|
|
210
|
+
workdir: root ?? this.opts.home,
|
|
211
|
+
workdirKnown: root !== undefined,
|
|
212
|
+
};
|
|
183
213
|
}
|
|
184
214
|
const workdir = ctx.cwd ?? this.opts.home;
|
|
185
215
|
const workdirKnown = ctx.cwd !== undefined;
|
|
@@ -245,28 +275,18 @@ export class InstanceManager {
|
|
|
245
275
|
* and retry once on a fresh instance when a remote server forgot our session. `cancelled`
|
|
246
276
|
* says whether the client cancelled the request while the instance was still starting: the
|
|
247
277
|
* upstream has no call to cancel yet, so the request is dropped here instead of sent.
|
|
278
|
+
* `onVariant` learns the variant of the instance that serves it (the call log's).
|
|
279
|
+
* A tools/call comes here through the call middleware (middleware.ts), never directly.
|
|
248
280
|
*/
|
|
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
|
-
};
|
|
281
|
+
async forward(client, method, params, originId, cancelled, onVariant) {
|
|
262
282
|
for (let attempt = 0;; attempt++) {
|
|
263
283
|
const inst = await this.acquire(client);
|
|
264
284
|
if ("error" in inst || "result" in inst)
|
|
265
|
-
return
|
|
266
|
-
|
|
285
|
+
return inst;
|
|
286
|
+
onVariant?.(inst.variant);
|
|
267
287
|
// Nothing awaits between this check and the call below, so a later cancellation finds it upstream.
|
|
268
288
|
if (cancelled?.())
|
|
269
|
-
return
|
|
289
|
+
return rpcError(ErrorCode.RequestCancelled, "cancelled by the client");
|
|
270
290
|
const timeout = inst.server.callTimeout ? inst.server.callTimeout * 1000 : undefined;
|
|
271
291
|
const out = await inst.upstream.call(method, params, client, originId, timeout);
|
|
272
292
|
if ("error" in out && inst.upstream.sessionLost && attempt === 0) {
|
|
@@ -275,7 +295,7 @@ export class InstanceManager {
|
|
|
275
295
|
this.instances.delete(inst.key);
|
|
276
296
|
continue;
|
|
277
297
|
}
|
|
278
|
-
return
|
|
298
|
+
return out;
|
|
279
299
|
}
|
|
280
300
|
}
|
|
281
301
|
/** resources/subscribe: one upstream subscription per URI and instance, many client subscribers. */
|
|
@@ -327,7 +347,9 @@ export class InstanceManager {
|
|
|
327
347
|
if (caps.prompts)
|
|
328
348
|
d.prompts = await inst.upstream.listAll("prompts/list", "prompts");
|
|
329
349
|
if (caps.resources)
|
|
330
|
-
d.resourceTemplates = await inst.upstream
|
|
350
|
+
d.resourceTemplates = await inst.upstream
|
|
351
|
+
.listAll("resources/templates/list", "resourceTemplates")
|
|
352
|
+
.catch(() => []);
|
|
331
353
|
const prev = this.opts.cache.peek(inst.descKey);
|
|
332
354
|
this.opts.cache.set(inst.descKey, d);
|
|
333
355
|
if (prev) {
|
|
@@ -540,7 +562,7 @@ export class InstanceManager {
|
|
|
540
562
|
this.opts.idleUnderPressure = seconds;
|
|
541
563
|
}
|
|
542
564
|
/**
|
|
543
|
-
* The memory pressure for /status and `turno mcp top
|
|
565
|
+
* The memory pressure for /status and `turno mcp top`: the level the last reap
|
|
544
566
|
* read (null while the feature is off or before the first read), the configured limit, and
|
|
545
567
|
* the idle cap that applies now (null when servers keep their own limits).
|
|
546
568
|
*/
|
|
@@ -549,7 +571,12 @@ export class InstanceManager {
|
|
|
549
571
|
const watched = this.opts.pressure !== undefined && under > 0 && this.pressureCheckedAt !== undefined;
|
|
550
572
|
const level = watched ? this.pressureLevel : null;
|
|
551
573
|
const cap = level ? effectiveIdle(Number.POSITIVE_INFINITY, level, under) : Number.POSITIVE_INFINITY;
|
|
552
|
-
return {
|
|
574
|
+
return {
|
|
575
|
+
level,
|
|
576
|
+
checkedAt: watched ? (this.pressureCheckedAt ?? null) : null,
|
|
577
|
+
idleUnderPressure: under,
|
|
578
|
+
idleCap: Number.isFinite(cap) ? cap : null,
|
|
579
|
+
};
|
|
553
580
|
}
|
|
554
581
|
/** Read memory pressure; a failing probe counts as normal. Logs when the level changes. */
|
|
555
582
|
async readPressure() {
|
|
@@ -577,7 +604,8 @@ export class InstanceManager {
|
|
|
577
604
|
}
|
|
578
605
|
/**
|
|
579
606
|
* 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
|
|
607
|
+
* dead clients. Under memory pressure the idle limit shrinks, and under critical
|
|
608
|
+
* pressure it applies to session servers too.
|
|
581
609
|
*/
|
|
582
610
|
async reap() {
|
|
583
611
|
const stopped = [];
|
|
@@ -592,13 +620,23 @@ export class InstanceManager {
|
|
|
592
620
|
const ownerAlive = inst.pid !== undefined && this.isAlive(inst.pid);
|
|
593
621
|
const ownerDead = inst.pid !== undefined && !ownerAlive;
|
|
594
622
|
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
|
-
|
|
623
|
+
// A session server lives as long as its session: its state (a browser, a login) is the
|
|
624
|
+
// point. Under critical memory pressure a quiet one stops like any other; the next call
|
|
625
|
+
// starts it again.
|
|
626
|
+
const idleApplies = !(inst.scope === "session" && ownerAlive && level !== "critical");
|
|
597
627
|
const limit = effectiveIdle(inst.server.idle, level, this.opts.idleUnderPressure ?? 0);
|
|
598
628
|
const idleFor = this.now() - inst.upstream.lastActivity;
|
|
599
629
|
const idle = idleApplies && quiet && idleFor > limit * 1000;
|
|
600
630
|
if (ownerDead || stale || idle) {
|
|
601
|
-
|
|
631
|
+
// Only pressure stops a session server whose launcher lives, whatever its own limit.
|
|
632
|
+
const ownLimit = idleFor > inst.server.idle * 1000 && !(inst.scope === "session" && ownerAlive);
|
|
633
|
+
const why = ownerDead
|
|
634
|
+
? "owner exited"
|
|
635
|
+
: stale
|
|
636
|
+
? "definition changed"
|
|
637
|
+
: ownLimit
|
|
638
|
+
? "idle"
|
|
639
|
+
: "idle (memory pressure)";
|
|
602
640
|
this.instances.delete(inst.key);
|
|
603
641
|
// That key never comes back (dead PID, old definition): forget its start count.
|
|
604
642
|
if (ownerDead || stale)
|
|
@@ -645,7 +683,7 @@ export class InstanceManager {
|
|
|
645
683
|
* Resolve a command against an installed package (turno mcp install). A declared package that
|
|
646
684
|
* is not installed still runs through `npx -y -p <package> <command>`, with a warning: `mcp
|
|
647
685
|
* import` writes `package` and `mcp install` is a separate step, so failing here would break
|
|
648
|
-
* imported setups
|
|
686
|
+
* imported setups.
|
|
649
687
|
*/
|
|
650
688
|
export function resolveCommand(server, command, args, serversDir) {
|
|
651
689
|
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,156 @@
|
|
|
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
|
+
/**
|
|
27
|
+
* A server that declares this experimental capability in `initialize` hears, with
|
|
28
|
+
* `SESSION_ENDED`, when a client session that made a call to it ends (`InstanceManager.detach`).
|
|
29
|
+
* turno-browser uses it to free that session's tabs at once (`"sharing": "tabs"`).
|
|
30
|
+
*/
|
|
31
|
+
export const SESSION_CAPABILITY = "io.turno/sessions";
|
|
32
|
+
export const SESSION_ENDED = "notifications/io.turno/session_ended";
|
|
33
|
+
/** The session id of each client handle, made on its first call. */
|
|
34
|
+
const sessionIds = new WeakMap();
|
|
35
|
+
/** The id the `session` stage gave this client, or undefined when it made no call. */
|
|
36
|
+
export function sessionIdOf(client) {
|
|
37
|
+
return sessionIds.get(client);
|
|
38
|
+
}
|
|
39
|
+
const BUILT_IN = ["filter", "calllog", "session"];
|
|
40
|
+
const STAGE_NAME = /^[a-z][a-z0-9-]*$/;
|
|
41
|
+
/** A profile's tool filter for a client's server, or undefined when it filters nothing. */
|
|
42
|
+
export function toolFilterOf(manifest, ctx) {
|
|
43
|
+
const server = manifest.servers[ctx.serverName];
|
|
44
|
+
if (!server)
|
|
45
|
+
return undefined;
|
|
46
|
+
const f = toolFilterFor(server, ctx.profile);
|
|
47
|
+
return filtersTools(f) ? f : undefined;
|
|
48
|
+
}
|
|
49
|
+
/** `filter`: a tool the profile's filter hides is refused here, before anything else runs. */
|
|
50
|
+
function filterStage(manifest) {
|
|
51
|
+
return {
|
|
52
|
+
name: "filter",
|
|
53
|
+
run(call, next) {
|
|
54
|
+
const filter = toolFilterOf(manifest(), call.client.ctx);
|
|
55
|
+
if (filter && !toolAllowed(filter, call.tool)) {
|
|
56
|
+
const { serverName, profile } = call.client.ctx;
|
|
57
|
+
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)`));
|
|
58
|
+
}
|
|
59
|
+
return next(call);
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** `calllog`: times the call and reports it to the call log, when one is on (read per call). */
|
|
64
|
+
function callLogStage(sink) {
|
|
65
|
+
return {
|
|
66
|
+
name: "calllog",
|
|
67
|
+
async run(call, next) {
|
|
68
|
+
const startedAt = Date.now();
|
|
69
|
+
const t0 = performance.now();
|
|
70
|
+
const params = call.params;
|
|
71
|
+
const outcome = await next(call);
|
|
72
|
+
const record = sink();
|
|
73
|
+
if (record) {
|
|
74
|
+
try {
|
|
75
|
+
record({
|
|
76
|
+
ctx: call.client.ctx,
|
|
77
|
+
method: "tools/call",
|
|
78
|
+
params,
|
|
79
|
+
...(call.variant ? { variant: call.variant } : {}),
|
|
80
|
+
outcome,
|
|
81
|
+
startedAt,
|
|
82
|
+
durationMs: performance.now() - t0,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
/* observing a call never fails it */
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return outcome;
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* `session`: the client session id in `_meta[SESSION_META]`. A random UUID per client handle
|
|
95
|
+
* (one 2025-11-25 session, or one stateless client: profile, server, PID and folder), kept for
|
|
96
|
+
* the life of the handle. It is not the Mcp-Session-Id, so a server learns nothing it could use
|
|
97
|
+
* against mcpd. A value the client sent under the same key is replaced.
|
|
98
|
+
*/
|
|
99
|
+
function sessionStage() {
|
|
100
|
+
return {
|
|
101
|
+
name: "session",
|
|
102
|
+
run(call, next) {
|
|
103
|
+
let id = sessionIds.get(call.client);
|
|
104
|
+
if (!id) {
|
|
105
|
+
id = randomUUID();
|
|
106
|
+
sessionIds.set(call.client, id);
|
|
107
|
+
}
|
|
108
|
+
const meta = typeof call.params._meta === "object" && call.params._meta !== null
|
|
109
|
+
? call.params._meta
|
|
110
|
+
: {};
|
|
111
|
+
call.params = { ...call.params, _meta: { ...meta, [SESSION_META]: id } };
|
|
112
|
+
return next(call);
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** The ordered stages, and the relay through the instance manager at the end. */
|
|
117
|
+
export class CallPipeline {
|
|
118
|
+
manager;
|
|
119
|
+
stages;
|
|
120
|
+
constructor(manager, stages) {
|
|
121
|
+
this.manager = manager;
|
|
122
|
+
const seen = new Set();
|
|
123
|
+
for (const s of stages) {
|
|
124
|
+
if (!STAGE_NAME.test(s.name))
|
|
125
|
+
throw new Error(`call stage name "${s.name}" must match ${STAGE_NAME}`);
|
|
126
|
+
if (seen.has(s.name))
|
|
127
|
+
throw new Error(`call stage "${s.name}" is registered twice`);
|
|
128
|
+
seen.add(s.name);
|
|
129
|
+
}
|
|
130
|
+
this.stages = [...stages];
|
|
131
|
+
}
|
|
132
|
+
/** The stage names in the order a call meets them. */
|
|
133
|
+
names() {
|
|
134
|
+
return this.stages.map((s) => s.name);
|
|
135
|
+
}
|
|
136
|
+
/** Relay one tools/call through every stage, then `InstanceManager.forward`. */
|
|
137
|
+
call(client, params, originId, cancelled) {
|
|
138
|
+
const relay = (c) => this.manager.forward(c.client, "tools/call", c.params, c.originId, c.cancelled, (variant) => (c.variant = variant));
|
|
139
|
+
const run = this.stages.reduceRight((next, stage) => (c) => stage.run(c, next), relay);
|
|
140
|
+
return run({ client, tool: typeof params.name === "string" ? params.name : "", params, originId, cancelled });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** mcpd's pipeline: the built-in stages around the opt-in ones. */
|
|
144
|
+
export function createCallPipeline(opts) {
|
|
145
|
+
const stages = opts.stages ?? [];
|
|
146
|
+
for (const s of stages)
|
|
147
|
+
if (BUILT_IN.includes(s.name))
|
|
148
|
+
throw new Error(`call stage "${s.name}" is registered twice`);
|
|
149
|
+
return new CallPipeline(opts.manager, [
|
|
150
|
+
filterStage(opts.manifest),
|
|
151
|
+
...stages,
|
|
152
|
+
callLogStage(opts.callLog ?? (() => undefined)),
|
|
153
|
+
sessionStage(),
|
|
154
|
+
]);
|
|
155
|
+
}
|
|
156
|
+
//# sourceMappingURL=middleware.js.map
|