turno-cli 0.1.1 → 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 +432 -0
- package/README.md +228 -73
- package/dist/accounts/audit.js +154 -12
- package/dist/accounts/builtin.js +100 -25
- package/dist/accounts/delegate.js +199 -35
- package/dist/accounts/policy.js +79 -0
- package/dist/accounts/registry.js +39 -21
- package/dist/agents/adapter.js +29 -0
- package/dist/agents/claude.js +246 -0
- package/dist/agents/codex.js +186 -0
- package/dist/agents/copilot.js +56 -0
- package/dist/agents/cursor.js +58 -0
- package/dist/agents/index.js +26 -86
- package/dist/agents/snippets.js +43 -13
- package/dist/cli/args.js +38 -6
- package/dist/cli/commands/accounts.js +119 -52
- package/dist/cli/commands/auto.js +121 -33
- 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 +319 -138
- package/dist/cli/commands/complete.js +14 -3
- package/dist/cli/commands/completion.js +8 -2
- package/dist/cli/commands/config.js +186 -24
- package/dist/cli/commands/demo.js +321 -0
- package/dist/cli/commands/doctor.js +525 -123
- package/dist/cli/commands/handoff.js +33 -22
- package/dist/cli/commands/identity.js +192 -54
- package/dist/cli/commands/init.js +648 -0
- package/dist/cli/commands/limit.js +84 -16
- package/dist/cli/commands/mcp-call.js +240 -0
- package/dist/cli/commands/mcp-oauth.js +221 -0
- package/dist/cli/commands/mcp-observe.js +539 -0
- package/dist/cli/commands/mcp-share.js +201 -0
- package/dist/cli/commands/mcp.js +816 -187
- package/dist/cli/commands/mcpd.js +388 -76
- package/dist/cli/commands/migrate.js +6 -4
- package/dist/cli/commands/open.js +115 -27
- package/dist/cli/commands/profile.js +396 -78
- package/dist/cli/commands/resolve.js +14 -3
- package/dist/cli/commands/run.js +36 -6
- package/dist/cli/commands/secret.js +80 -76
- package/dist/cli/commands/session.js +17 -6
- package/dist/cli/commands/sessions.js +48 -12
- package/dist/cli/commands/setup.js +214 -164
- package/dist/cli/commands/status.js +227 -44
- package/dist/cli/commands/statusline.js +311 -114
- package/dist/cli/commands/ui.js +78 -68
- package/dist/cli/commands/undo.js +193 -18
- package/dist/cli/commands/uninstall.js +481 -0
- package/dist/cli/commands/upgrade.js +172 -79
- package/dist/cli/commands/usage.js +125 -51
- package/dist/cli/commands/version.js +21 -7
- package/dist/cli/commands/which.js +9 -24
- package/dist/cli/compile-cache.js +32 -0
- package/dist/cli/diagnostics.js +184 -0
- package/dist/cli/exit.js +65 -0
- package/dist/cli/group.js +24 -12
- package/dist/cli/help.js +62 -0
- package/dist/cli/highlight.js +236 -0
- package/dist/cli/hints.js +30 -0
- package/dist/cli/io.js +186 -1
- package/dist/cli/launch.js +52 -39
- package/dist/cli/launchers.js +161 -95
- package/dist/cli/main.js +201 -31
- package/dist/cli/optional.js +144 -0
- package/dist/cli/output.js +123 -0
- package/dist/cli/picker.js +459 -0
- package/dist/cli/registry.js +61 -6
- package/dist/cli/safe.js +87 -0
- package/dist/cli/secret-input.js +63 -0
- package/dist/cli/security.js +561 -0
- package/dist/cli/style.js +311 -0
- package/dist/cli/topics.js +142 -0
- package/dist/core/config.js +181 -23
- package/dist/core/exhausted.js +6 -8
- package/dist/core/fsutil.js +39 -0
- package/dist/core/journal.js +294 -16
- package/dist/core/manifest.js +153 -6
- package/dist/core/paths.js +14 -13
- package/dist/core/profiles.js +160 -10
- package/dist/core/resolve.js +139 -23
- package/dist/core/secrets.js +68 -23
- package/dist/core/sessions.js +13 -20
- package/dist/core/state-file.js +107 -0
- package/dist/core/update.js +31 -18
- package/dist/core/version.js +57 -10
- package/dist/demo/server.js +42 -0
- package/dist/mcpd/cache.js +23 -10
- package/dist/mcpd/calllog.js +254 -0
- package/dist/mcpd/client-names.js +46 -0
- package/dist/mcpd/connectors.js +188 -18
- package/dist/mcpd/daemon.js +472 -115
- package/dist/mcpd/folder-sets.js +42 -0
- package/dist/mcpd/gateway.js +473 -51
- package/dist/mcpd/health.js +313 -0
- package/dist/mcpd/importer.js +453 -36
- package/dist/mcpd/instances.js +453 -65
- package/dist/mcpd/jsonrpc.js +11 -1
- package/dist/mcpd/launchd.js +65 -48
- package/dist/mcpd/middleware.js +144 -0
- package/dist/mcpd/modern.js +686 -0
- package/dist/mcpd/oauth.js +845 -0
- package/dist/mcpd/peerpid.js +134 -6
- package/dist/mcpd/pressure.js +88 -0
- package/dist/mcpd/rss.js +166 -0
- package/dist/mcpd/service.js +191 -0
- package/dist/mcpd/share.js +217 -0
- package/dist/mcpd/state.js +183 -0
- package/dist/mcpd/sync.js +72 -87
- package/dist/mcpd/systemd.js +83 -0
- package/dist/mcpd/tokens.js +85 -0
- package/dist/mcpd/upstream.js +163 -46
- package/dist/statusline/cost.js +167 -44
- package/dist/statusline/input.js +78 -0
- package/dist/statusline/render.js +9 -3
- package/dist/ui/fonts.js +8 -3
- package/dist/ui/settings.js +33 -16
- package/npm-shrinkwrap.json +1102 -0
- package/package.json +10 -9
- package/dist/cli/commands/available.js +0 -18
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { paths } from "../core/paths.js";
|
|
3
|
+
import { runTool, serviceArgs, serviceEnv } from "./service.js";
|
|
4
|
+
export const UNIT = "turno-mcpd.service";
|
|
5
|
+
export function unitPath(env = process.env) {
|
|
6
|
+
const base = env.XDG_CONFIG_HOME || join(paths(env).home, ".config");
|
|
7
|
+
return join(base, "systemd", "user", UNIT);
|
|
8
|
+
}
|
|
9
|
+
/** One word of ExecStart or Environment, quoted for systemd: specifiers and variables are escaped. */
|
|
10
|
+
function quote(s) {
|
|
11
|
+
return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
|
|
12
|
+
}
|
|
13
|
+
function unquote(s) {
|
|
14
|
+
return s
|
|
15
|
+
.replace(/\$\$/g, "$")
|
|
16
|
+
.replace(/%%/g, "%")
|
|
17
|
+
.replace(/\\(["\\])/g, "$1");
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* `systemd --user` unit that keeps `turno mcp daemon run` alive. Restart=on-failure: a clean
|
|
21
|
+
* exit (another mcpd already serves) is not restarted, a crash is.
|
|
22
|
+
*/
|
|
23
|
+
export function unit(spec) {
|
|
24
|
+
const env = Object.entries(serviceEnv(spec, "systemd"))
|
|
25
|
+
.map(([k, v]) => `Environment=${quote(`${k}=${v}`)}`)
|
|
26
|
+
.join("\n");
|
|
27
|
+
return `[Unit]
|
|
28
|
+
Description=turno MCP gateway (mcpd)
|
|
29
|
+
Documentation=https://github.com/wimo-dev/turno
|
|
30
|
+
|
|
31
|
+
[Service]
|
|
32
|
+
Type=simple
|
|
33
|
+
ExecStart=${serviceArgs(spec).map(quote).join(" ")}
|
|
34
|
+
${env}
|
|
35
|
+
Restart=on-failure
|
|
36
|
+
RestartSec=5
|
|
37
|
+
|
|
38
|
+
[Install]
|
|
39
|
+
WantedBy=default.target
|
|
40
|
+
`;
|
|
41
|
+
}
|
|
42
|
+
/** The ExecStart words of a unit written by `unit()`. */
|
|
43
|
+
export function unitProgram(text) {
|
|
44
|
+
const line = /^ExecStart=(.*)$/m.exec(text)?.[1];
|
|
45
|
+
if (!line)
|
|
46
|
+
return [];
|
|
47
|
+
return [...line.matchAll(/"((?:[^"\\]|\\.)*)"|(\S+)/g)].map((m) => (m[1] !== undefined ? unquote(m[1]) : m[2]));
|
|
48
|
+
}
|
|
49
|
+
const ctl = (env, ...args) => runTool("systemctl", ["--user", ...args], env);
|
|
50
|
+
export const systemd = {
|
|
51
|
+
kind: "systemd",
|
|
52
|
+
noun: "systemd user unit",
|
|
53
|
+
file: unitPath,
|
|
54
|
+
render: unit,
|
|
55
|
+
programOf: unitProgram,
|
|
56
|
+
async isLoaded(env) {
|
|
57
|
+
try {
|
|
58
|
+
await ctl(env, "is-enabled", "--quiet", UNIT);
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
try {
|
|
63
|
+
await ctl(env, "is-active", "--quiet", UNIT);
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
async load(env) {
|
|
72
|
+
await ctl(env, "daemon-reload");
|
|
73
|
+
await ctl(env, "enable", UNIT);
|
|
74
|
+
await ctl(env, "restart", UNIT);
|
|
75
|
+
},
|
|
76
|
+
async unload(env) {
|
|
77
|
+
await ctl(env, "disable", "--now", UNIT);
|
|
78
|
+
},
|
|
79
|
+
async restart(env) {
|
|
80
|
+
await ctl(env, "restart", UNIT);
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
//# sourceMappingURL=systemd.js.map
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { atomicWrite } from "../core/journal.js";
|
|
5
|
+
import { ensurePrivateDir, paths } from "../core/paths.js";
|
|
6
|
+
import { readState } from "../core/state-file.js";
|
|
7
|
+
/**
|
|
8
|
+
* Per-profile gateway tokens. Each profile's agent config carries its own token,
|
|
9
|
+
* derived from the master token so mcpd needs no list of them:
|
|
10
|
+
*
|
|
11
|
+
* tp1.<profile>.<base64url(HMAC-SHA256(master, "profile:" + profile))>
|
|
12
|
+
*
|
|
13
|
+
* The profile name travels in clear (it is not a secret, the MAC is), so the gateway reads the
|
|
14
|
+
* profile from the token itself and never from a header. Rotating the master token invalidates
|
|
15
|
+
* every derived token at once.
|
|
16
|
+
*/
|
|
17
|
+
const PREFIX = "tp1";
|
|
18
|
+
const SHAPE = /^tp1\.([a-z0-9][a-z0-9_-]*)\.([A-Za-z0-9_-]{43})$/;
|
|
19
|
+
/** The token profile `profile` uses to reach mcpd. */
|
|
20
|
+
export function profileToken(master, profile) {
|
|
21
|
+
const mac = createHmac("sha256", master).update(`profile:${profile}`).digest("base64url");
|
|
22
|
+
return `${PREFIX}.${profile}.${mac}`;
|
|
23
|
+
}
|
|
24
|
+
/** The profile a token was issued for under this master token, or undefined. */
|
|
25
|
+
export function tokenProfile(master, token) {
|
|
26
|
+
const m = SHAPE.exec(token);
|
|
27
|
+
if (!m)
|
|
28
|
+
return undefined;
|
|
29
|
+
const want = Buffer.from(profileToken(master, m[1]));
|
|
30
|
+
const got = Buffer.from(token);
|
|
31
|
+
return want.length === got.length && timingSafeEqual(want, got) ? m[1] : undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Where a profile's token waits for launchers of agents that read it from the environment
|
|
35
|
+
* (Codex, Copilot, Cursor, and agents set up by hand from `turno mcp config`).
|
|
36
|
+
*/
|
|
37
|
+
export function profileTokenFile(profile, env = process.env) {
|
|
38
|
+
return join(paths(env).state, "mcpd-tokens", `${profile}.token`);
|
|
39
|
+
}
|
|
40
|
+
export function readProfileTokenFile(profile, env = process.env) {
|
|
41
|
+
try {
|
|
42
|
+
return readFileSync(profileTokenFile(profile, env), "utf8").trim() || undefined;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Write the profile's token file (mode 600) when it is missing or stale. True when it changed. */
|
|
49
|
+
export function writeProfileTokenFile(profile, master, env = process.env) {
|
|
50
|
+
const token = profileToken(master, profile);
|
|
51
|
+
if (readProfileTokenFile(profile, env) === token)
|
|
52
|
+
return false;
|
|
53
|
+
const file = profileTokenFile(profile, env);
|
|
54
|
+
ensurePrivateDir(dirname(file), env);
|
|
55
|
+
atomicWrite(file, `${token}\n`, 0o600);
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Profiles whose token file `turno mcp sync` wrote, so a later sync removes only its own files
|
|
60
|
+
* once their profile is gone; files written for agents set up by hand (`turno mcp config`, any
|
|
61
|
+
* name) stay.
|
|
62
|
+
*/
|
|
63
|
+
function syncedListFile(env) {
|
|
64
|
+
return join(dirname(profileTokenFile("x", env)), "synced.json");
|
|
65
|
+
}
|
|
66
|
+
export function readSyncedTokenProfiles(env = process.env) {
|
|
67
|
+
const v = readState(syncedListFile(env), (x) => Array.isArray(x));
|
|
68
|
+
return (v ?? []).filter((x) => typeof x === "string");
|
|
69
|
+
}
|
|
70
|
+
export function writeSyncedTokenProfiles(names, env = process.env) {
|
|
71
|
+
const file = syncedListFile(env);
|
|
72
|
+
ensurePrivateDir(dirname(file), env);
|
|
73
|
+
atomicWrite(file, `${JSON.stringify([...new Set(names)].sort())}\n`, 0o600);
|
|
74
|
+
}
|
|
75
|
+
/** Delete a profile's token file; true when there was one. */
|
|
76
|
+
export function removeProfileTokenFile(profile, env = process.env) {
|
|
77
|
+
try {
|
|
78
|
+
rmSync(profileTokenFile(profile, env));
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=tokens.js.map
|
package/dist/mcpd/upstream.js
CHANGED
|
@@ -1,8 +1,23 @@
|
|
|
1
1
|
import { LATEST_PROTOCOL_VERSION } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
-
import { ErrorCode, isNotification, isRequest, isResponse, rpcError } from "./jsonrpc.js";
|
|
2
|
+
import { ErrorCode, isNotification, isRequest, isResponse, rpcError, } from "./jsonrpc.js";
|
|
3
|
+
/** Server-to-client requests and the client capability each needs. */
|
|
4
|
+
const CLIENT_CAPABILITY = {
|
|
5
|
+
"elicitation/create": "elicitation",
|
|
6
|
+
"sampling/createMessage": "sampling",
|
|
7
|
+
"roots/list": "roots",
|
|
8
|
+
};
|
|
9
|
+
/** Server notifications that belong to one call and are routed like server requests. */
|
|
10
|
+
const ROUTED_NOTIFICATIONS = new Set(["notifications/message", "notifications/elicitation/complete"]);
|
|
11
|
+
/** True for the error the SDK raises when a remote server no longer knows our session. */
|
|
12
|
+
function sessionGone(err, hadSession) {
|
|
13
|
+
const code = err.code;
|
|
14
|
+
return hadSession && code === 404;
|
|
15
|
+
}
|
|
3
16
|
/**
|
|
4
17
|
* One running MCP server, spoken to over a raw transport. Request ids and progress tokens
|
|
5
|
-
* are rewritten so several clients can share it without their messages crossing.
|
|
18
|
+
* are rewritten so several clients can share it without their messages crossing. Every
|
|
19
|
+
* request it relays is settled exactly once: by the server's answer, a cancellation, a
|
|
20
|
+
* timeout, the client going away, or the server stopping.
|
|
6
21
|
*/
|
|
7
22
|
export class Upstream {
|
|
8
23
|
opts;
|
|
@@ -14,6 +29,8 @@ export class Upstream {
|
|
|
14
29
|
init;
|
|
15
30
|
lastActivity = Date.now();
|
|
16
31
|
startedAt = Date.now();
|
|
32
|
+
/** A remote server answered 404 to our session: the instance must be replaced. */
|
|
33
|
+
sessionLost = false;
|
|
17
34
|
constructor(opts) {
|
|
18
35
|
this.opts = opts;
|
|
19
36
|
}
|
|
@@ -29,6 +46,22 @@ export class Upstream {
|
|
|
29
46
|
get isClosed() {
|
|
30
47
|
return this.closed;
|
|
31
48
|
}
|
|
49
|
+
/** Calls in flight on behalf of one client. */
|
|
50
|
+
inflightFor(client) {
|
|
51
|
+
let n = 0;
|
|
52
|
+
for (const p of this.pending.values())
|
|
53
|
+
if (p.origin === client)
|
|
54
|
+
n++;
|
|
55
|
+
return n;
|
|
56
|
+
}
|
|
57
|
+
/** Calls in flight per client session id, for /status. */
|
|
58
|
+
inflightByClient() {
|
|
59
|
+
const out = {};
|
|
60
|
+
for (const p of this.pending.values())
|
|
61
|
+
if (p.origin)
|
|
62
|
+
out[p.origin.id] = (out[p.origin.id] ?? 0) + 1;
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
32
65
|
async start() {
|
|
33
66
|
const t = await this.opts.connect();
|
|
34
67
|
this.transport = t;
|
|
@@ -40,7 +73,7 @@ export class Upstream {
|
|
|
40
73
|
await t.start();
|
|
41
74
|
const res = await this.call("initialize", {
|
|
42
75
|
protocolVersion: LATEST_PROTOCOL_VERSION,
|
|
43
|
-
capabilities: { roots: { listChanged: true }, elicitation: { form: {}
|
|
76
|
+
capabilities: this.opts.capabilities ?? { roots: { listChanged: true }, elicitation: { form: {} } },
|
|
44
77
|
clientInfo: { name: "turno-mcpd", version: "0.1.0" },
|
|
45
78
|
}, undefined, undefined, this.opts.initTimeoutMs ?? 60_000);
|
|
46
79
|
if ("error" in res) {
|
|
@@ -71,15 +104,28 @@ export class Upstream {
|
|
|
71
104
|
}
|
|
72
105
|
this.lastActivity = Date.now();
|
|
73
106
|
return new Promise((resolve) => {
|
|
74
|
-
const p = {
|
|
107
|
+
const p = {
|
|
108
|
+
resolve,
|
|
109
|
+
method,
|
|
110
|
+
...(origin ? { origin } : {}),
|
|
111
|
+
...(originId !== undefined ? { originId } : {}),
|
|
112
|
+
};
|
|
75
113
|
if (timeoutMs) {
|
|
76
114
|
p.timer = setTimeout(() => {
|
|
77
|
-
this.
|
|
78
|
-
|
|
115
|
+
this.cancelUpstream(id, "timed out");
|
|
116
|
+
const secs = Math.round(timeoutMs / 100) / 10;
|
|
117
|
+
this.settle(id, rpcError(ErrorCode.RequestTimeout, `${this.label}: ${method} timed out after ${secs}s`));
|
|
79
118
|
}, timeoutMs);
|
|
80
119
|
}
|
|
81
120
|
this.pending.set(id, p);
|
|
121
|
+
const hadSession = this.hasRemoteSession();
|
|
82
122
|
this.send({ jsonrpc: "2.0", id, method, ...(outParams ? { params: outParams } : {}) }).catch((err) => {
|
|
123
|
+
if (sessionGone(err, hadSession)) {
|
|
124
|
+
this.sessionLost = true;
|
|
125
|
+
this.settle(id, rpcError(ErrorCode.Unavailable, `${this.label}: the remote server forgot the session`));
|
|
126
|
+
void this.close("remote session expired");
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
83
129
|
this.settle(id, rpcError(ErrorCode.Unavailable, `${this.label}: ${err.message}`));
|
|
84
130
|
});
|
|
85
131
|
});
|
|
@@ -88,21 +134,35 @@ export class Upstream {
|
|
|
88
134
|
notify(method, params, origin) {
|
|
89
135
|
if (this.closed)
|
|
90
136
|
return;
|
|
91
|
-
|
|
92
|
-
|
|
137
|
+
if (method === "notifications/cancelled") {
|
|
138
|
+
if (params?.requestId === undefined)
|
|
139
|
+
return;
|
|
93
140
|
const upstreamId = this.findUpstreamId(params.requestId, origin?.id);
|
|
94
141
|
if (!upstreamId)
|
|
95
142
|
return;
|
|
96
|
-
|
|
143
|
+
// The server will never answer a cancelled request (the spec says it must not), so
|
|
144
|
+
// settle it here: otherwise it stays in flight forever and the instance never idles out.
|
|
145
|
+
this.cancelUpstream(upstreamId, typeof params.reason === "string" ? params.reason : undefined);
|
|
146
|
+
this.settle(upstreamId, rpcError(ErrorCode.RequestCancelled, "cancelled by the client"));
|
|
147
|
+
return;
|
|
97
148
|
}
|
|
98
149
|
this.lastActivity = Date.now();
|
|
99
|
-
void this.send({ jsonrpc: "2.0", method, ...(
|
|
150
|
+
void this.send({ jsonrpc: "2.0", method, ...(params ? { params } : {}) }).catch(() => { });
|
|
100
151
|
}
|
|
101
|
-
/**
|
|
102
|
-
forgetClient(client) {
|
|
152
|
+
/** A client went away: cancel and settle everything it had in flight, forget its progress tokens. */
|
|
153
|
+
forgetClient(client, reason = "client disconnected") {
|
|
154
|
+
let n = 0;
|
|
155
|
+
for (const [id, p] of [...this.pending]) {
|
|
156
|
+
if (p.origin !== client)
|
|
157
|
+
continue;
|
|
158
|
+
this.cancelUpstream(id, reason);
|
|
159
|
+
this.settle(id, rpcError(ErrorCode.RequestCancelled, reason));
|
|
160
|
+
n++;
|
|
161
|
+
}
|
|
103
162
|
for (const [token, p] of this.progress)
|
|
104
163
|
if (p.origin === client)
|
|
105
164
|
this.progress.delete(token);
|
|
165
|
+
return n;
|
|
106
166
|
}
|
|
107
167
|
/** Fetch every page of a list method. */
|
|
108
168
|
async listAll(method, key) {
|
|
@@ -119,23 +179,27 @@ export class Upstream {
|
|
|
119
179
|
}
|
|
120
180
|
return items;
|
|
121
181
|
}
|
|
122
|
-
async close() {
|
|
182
|
+
async close(reason = "closed") {
|
|
123
183
|
if (this.closed)
|
|
124
184
|
return;
|
|
125
185
|
this.closed = true;
|
|
126
|
-
|
|
127
|
-
if (p.timer)
|
|
128
|
-
clearTimeout(p.timer);
|
|
129
|
-
p.resolve(rpcError(ErrorCode.Unavailable, `${this.label} stopped`));
|
|
130
|
-
this.pending.delete(id);
|
|
131
|
-
}
|
|
186
|
+
this.failAll(`${this.label} stopped`);
|
|
132
187
|
try {
|
|
133
188
|
await this.transport?.close();
|
|
134
189
|
}
|
|
135
190
|
catch {
|
|
136
191
|
/* already gone */
|
|
137
192
|
}
|
|
138
|
-
this.opts.onClose?.(
|
|
193
|
+
this.opts.onClose?.(reason);
|
|
194
|
+
}
|
|
195
|
+
hasRemoteSession() {
|
|
196
|
+
return typeof this.transport?.sessionId === "string";
|
|
197
|
+
}
|
|
198
|
+
cancelUpstream(id, reason) {
|
|
199
|
+
if (this.closed || !this.transport)
|
|
200
|
+
return;
|
|
201
|
+
const params = { requestId: id, ...(reason ? { reason } : {}) };
|
|
202
|
+
void this.send({ jsonrpc: "2.0", method: "notifications/cancelled", params }).catch(() => { });
|
|
139
203
|
}
|
|
140
204
|
findUpstreamId(clientId, originId) {
|
|
141
205
|
for (const [id, p] of this.pending) {
|
|
@@ -159,23 +223,55 @@ export class Upstream {
|
|
|
159
223
|
clearTimeout(p.timer);
|
|
160
224
|
p.resolve(o);
|
|
161
225
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
return;
|
|
165
|
-
this.closed = true;
|
|
166
|
-
for (const [id, p] of this.pending) {
|
|
226
|
+
failAll(message) {
|
|
227
|
+
for (const [id, p] of [...this.pending]) {
|
|
167
228
|
if (p.timer)
|
|
168
229
|
clearTimeout(p.timer);
|
|
169
|
-
p.resolve(rpcError(ErrorCode.Unavailable, `${this.label} exited`));
|
|
170
230
|
this.pending.delete(id);
|
|
231
|
+
p.resolve(rpcError(ErrorCode.Unavailable, message));
|
|
171
232
|
}
|
|
233
|
+
this.progress.clear();
|
|
234
|
+
}
|
|
235
|
+
handleClose(reason) {
|
|
236
|
+
if (this.closed)
|
|
237
|
+
return;
|
|
238
|
+
this.closed = true;
|
|
239
|
+
this.failAll(`${this.label} exited`);
|
|
172
240
|
this.opts.onClose?.(reason);
|
|
173
241
|
}
|
|
174
|
-
/**
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
242
|
+
/**
|
|
243
|
+
* The client a server-to-client message belongs to. Stdio carries no link between a server
|
|
244
|
+
* request and the call that caused it, so: an explicit related request id wins; else the one
|
|
245
|
+
* client with calls in flight; else the only attached client. With calls in flight from
|
|
246
|
+
* several clients the message is refused rather than sent to a guess.
|
|
247
|
+
*/
|
|
248
|
+
route(method, params) {
|
|
249
|
+
const meta = params?._meta;
|
|
250
|
+
const related = meta?.relatedRequestId;
|
|
251
|
+
if (typeof related === "string" || typeof related === "number") {
|
|
252
|
+
const p = this.pending.get(related);
|
|
253
|
+
if (p?.origin)
|
|
254
|
+
return { origin: p.origin, ...(p.originId !== undefined ? { originId: p.originId } : {}) };
|
|
255
|
+
}
|
|
256
|
+
const latest = new Map();
|
|
257
|
+
for (const p of this.pending.values())
|
|
258
|
+
if (p.origin)
|
|
259
|
+
latest.set(p.origin, p);
|
|
260
|
+
if (latest.size === 1) {
|
|
261
|
+
const [[origin, p]] = [...latest.entries()];
|
|
262
|
+
return { origin, ...(p.originId !== undefined ? { originId: p.originId } : {}) };
|
|
263
|
+
}
|
|
264
|
+
if (latest.size > 1) {
|
|
265
|
+
return {
|
|
266
|
+
code: ErrorCode.Ambiguous,
|
|
267
|
+
error: `${this.label} is shared by ${latest.size} sessions with calls in flight, so turno cannot tell which one this ${method} belongs to. ` +
|
|
268
|
+
`Retry when the other calls finish, or set scope = "session" (or exclusive = true) for this server in mcp.toml.`,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
const attached = this.opts.attached?.() ?? [];
|
|
272
|
+
if (attached.length === 1)
|
|
273
|
+
return { origin: attached[0] };
|
|
274
|
+
return { code: ErrorCode.MethodNotFound, error: `no client session is waiting on ${this.label}` };
|
|
179
275
|
}
|
|
180
276
|
onMessage(m) {
|
|
181
277
|
this.lastActivity = Date.now();
|
|
@@ -190,20 +286,38 @@ export class Upstream {
|
|
|
190
286
|
if (isNotification(m))
|
|
191
287
|
this.relayNotification(m);
|
|
192
288
|
}
|
|
193
|
-
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
289
|
+
declared(capability) {
|
|
290
|
+
const caps = this.opts.capabilities ?? { roots: {}, elicitation: {} };
|
|
291
|
+
return caps[capability] !== undefined;
|
|
292
|
+
}
|
|
293
|
+
async answer(method, params) {
|
|
294
|
+
if (method === "ping")
|
|
295
|
+
return { result: {} };
|
|
296
|
+
const capability = CLIENT_CAPABILITY[method];
|
|
297
|
+
if (method === "roots/list") {
|
|
298
|
+
const local = this.opts.localRoots?.();
|
|
299
|
+
if (local)
|
|
300
|
+
return { result: local };
|
|
301
|
+
}
|
|
302
|
+
if (capability && !this.declared(capability)) {
|
|
303
|
+
return rpcError(ErrorCode.MethodNotFound, `turno did not offer ${capability} to ${this.label}`);
|
|
199
304
|
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
: rpcError(ErrorCode.MethodNotFound, `no client session is waiting on ${this.label}`);
|
|
305
|
+
const target = this.route(method, params);
|
|
306
|
+
if ("error" in target) {
|
|
307
|
+
this.opts.log?.(`${this.label}: refused ${method}: ${target.error}`);
|
|
308
|
+
return rpcError(target.code, target.error);
|
|
205
309
|
}
|
|
206
|
-
|
|
310
|
+
if (capability && target.origin.supports && !target.origin.supports(capability)) {
|
|
311
|
+
return rpcError(ErrorCode.MethodNotFound, `the client session behind ${this.label} does not support ${capability}`);
|
|
312
|
+
}
|
|
313
|
+
return target.origin.request(method, params, target.originId);
|
|
314
|
+
}
|
|
315
|
+
async relayRequest(m) {
|
|
316
|
+
const id = m.id;
|
|
317
|
+
const outcome = await this.answer(m.method, m.params);
|
|
318
|
+
const reply = "error" in outcome
|
|
319
|
+
? { jsonrpc: "2.0", id, error: outcome.error }
|
|
320
|
+
: { jsonrpc: "2.0", id, result: outcome.result };
|
|
207
321
|
await this.send(reply).catch(() => { });
|
|
208
322
|
}
|
|
209
323
|
relayNotification(m) {
|
|
@@ -219,12 +333,15 @@ export class Upstream {
|
|
|
219
333
|
// The server gave up on a request it sent us; nothing to undo on our side.
|
|
220
334
|
return;
|
|
221
335
|
}
|
|
222
|
-
if (method
|
|
223
|
-
const target = this.
|
|
224
|
-
if (target) {
|
|
336
|
+
if (ROUTED_NOTIFICATIONS.has(method)) {
|
|
337
|
+
const target = this.route(method, m.params);
|
|
338
|
+
if (!("error" in target)) {
|
|
225
339
|
target.origin.notify(method, m.params, target.originId);
|
|
226
340
|
return;
|
|
227
341
|
}
|
|
342
|
+
// Several sessions in flight: a log line or completion for one of them must not reach the others.
|
|
343
|
+
if (target.code === ErrorCode.Ambiguous)
|
|
344
|
+
return;
|
|
228
345
|
}
|
|
229
346
|
this.opts.onBroadcast?.(method, m.params);
|
|
230
347
|
}
|