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
package/dist/mcpd/gateway.js
CHANGED
|
@@ -1,15 +1,28 @@
|
|
|
1
1
|
import { randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import { createServer } from "node:http";
|
|
3
|
+
import { isAbsolute } from "node:path";
|
|
3
4
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
4
5
|
import { LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS } from "@modelcontextprotocol/sdk/types.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
6
|
+
import { servesProfile, toolAllowed } from "../core/manifest.js";
|
|
7
|
+
import { tildify } from "../core/paths.js";
|
|
8
|
+
import { folderMcpSet, mcpSetAllows } from "../core/resolve.js";
|
|
9
|
+
import { cleanAgentName } from "./calllog.js";
|
|
10
|
+
import { folderRoots } from "./folder-sets.js";
|
|
11
|
+
import { isDirectory, processCwd, projectRoot, scopeOf, } from "./instances.js";
|
|
12
|
+
import { ErrorCode, isNotification, isRequest, isResponse, rpcError, toResponse, } from "./jsonrpc.js";
|
|
13
|
+
import { createCallPipeline, toolFilterOf } from "./middleware.js";
|
|
14
|
+
import { StatelessFront, isInitialize, readJsonBody, wantsModern } from "./modern.js";
|
|
15
|
+
import { tokenProfile } from "./tokens.js";
|
|
16
|
+
const DEFAULT_MAX_REQUEST_BODY = 32 * 1024 * 1024;
|
|
17
|
+
/** List methods answered from the description cache. resources/list is not one of them. */
|
|
7
18
|
const LIST_METHODS = {
|
|
8
19
|
"tools/list": { cap: "tools", key: "tools", field: "tools" },
|
|
9
20
|
"prompts/list": { cap: "prompts", key: "prompts", field: "prompts" },
|
|
10
|
-
"resources/list": { cap: "resources", key: "resources", field: "resources" },
|
|
11
21
|
"resources/templates/list": { cap: "resources", key: "resourceTemplates", field: "resourceTemplates" },
|
|
12
22
|
};
|
|
23
|
+
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
24
|
+
const MASTER_TOKEN_REFUSED = "this agent config sends the master gateway token, which turno no longer accepts for MCP sessions (each profile has its own token now); run: turno mcp sync";
|
|
25
|
+
const BAD_TOKEN = "bad token (after an upgrade or turno mcp token rotate, run: turno mcp sync)";
|
|
13
26
|
function header(req, name) {
|
|
14
27
|
const v = req.headers[name];
|
|
15
28
|
return Array.isArray(v) ? v[0] : v;
|
|
@@ -24,26 +37,109 @@ function safeEqual(a, b) {
|
|
|
24
37
|
const bb = Buffer.from(b);
|
|
25
38
|
return ab.length === bb.length && timingSafeEqual(ab, bb);
|
|
26
39
|
}
|
|
27
|
-
|
|
28
|
-
return typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
|
|
40
|
+
function negotiateVersion(requested) {
|
|
41
|
+
return typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
|
|
42
|
+
? requested
|
|
43
|
+
: LATEST_PROTOCOL_VERSION;
|
|
29
44
|
}
|
|
30
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
* The session folder from the request headers. `X-Turno-Cwd-B64` (base64url of the UTF-8
|
|
47
|
+
* path, set by the launchers) is preferred: raw non-Latin-1 paths cannot travel in an HTTP
|
|
48
|
+
* header. The legacy `X-Turno-Cwd` is still read; a client that sent raw UTF-8 bytes arrives
|
|
49
|
+
* as Latin-1 text, which is repaired here. Returns undefined unless the path is absolute.
|
|
50
|
+
*/
|
|
51
|
+
export function decodeCwdHeaders(headers) {
|
|
52
|
+
const pick = (name) => {
|
|
53
|
+
const v = headers[name];
|
|
54
|
+
return (Array.isArray(v) ? v[0] : v)?.trim() || undefined;
|
|
55
|
+
};
|
|
56
|
+
const b64 = pick("x-turno-cwd-b64");
|
|
57
|
+
if (b64 && /^[A-Za-z0-9_-]+={0,2}$/.test(b64)) {
|
|
58
|
+
const path = Buffer.from(b64, "base64url").toString("utf8");
|
|
59
|
+
if (isAbsolute(path) && !path.includes("�") && !path.includes("\0"))
|
|
60
|
+
return path;
|
|
61
|
+
}
|
|
62
|
+
const raw = pick("x-turno-cwd");
|
|
63
|
+
if (!raw || !isAbsolute(raw))
|
|
64
|
+
return undefined;
|
|
65
|
+
if (/[\u0080-ÿ]/.test(raw)) {
|
|
66
|
+
const repaired = Buffer.from(raw, "latin1").toString("utf8");
|
|
67
|
+
if (!repaired.includes("�"))
|
|
68
|
+
return repaired;
|
|
69
|
+
}
|
|
70
|
+
return raw;
|
|
71
|
+
}
|
|
72
|
+
/** listChanged on the lists mcpd can announce itself (it relists after every start). */
|
|
73
|
+
function announcedCapabilities(caps) {
|
|
74
|
+
const out = { ...caps };
|
|
75
|
+
for (const k of ["tools", "prompts", "resources"]) {
|
|
76
|
+
const c = out[k];
|
|
77
|
+
if (c && typeof c === "object")
|
|
78
|
+
out[k] = { ...c, listChanged: true };
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
/** Lists a hidden server answers with: empty, so a client that asks anyway gets nothing. */
|
|
83
|
+
const EMPTY_LISTS = {
|
|
84
|
+
"tools/list": "tools",
|
|
85
|
+
"prompts/list": "prompts",
|
|
86
|
+
"resources/list": "resources",
|
|
87
|
+
"resources/templates/list": "resourceTemplates",
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* What a session gets for a server its folder's set leaves out: an initialize with
|
|
91
|
+
* no capabilities and an instructions line that says why, empty lists, and an error naming
|
|
92
|
+
* the rule for anything else. The session stays open, so the agent shows the server as
|
|
93
|
+
* connected with nothing in it rather than as a failure it may retry.
|
|
94
|
+
*/
|
|
95
|
+
function hiddenAnswer(m, server, why) {
|
|
96
|
+
const method = m.method;
|
|
97
|
+
if (method === "initialize") {
|
|
98
|
+
return {
|
|
99
|
+
result: {
|
|
100
|
+
protocolVersion: negotiateVersion(m.params?.protocolVersion),
|
|
101
|
+
capabilities: {},
|
|
102
|
+
serverInfo: { name: server, version: "hidden" },
|
|
103
|
+
instructions: why,
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
if (method === "ping" || method === "logging/setLevel")
|
|
108
|
+
return { result: {} };
|
|
109
|
+
const list = EMPTY_LISTS[method];
|
|
110
|
+
if (list)
|
|
111
|
+
return { result: { [list]: [] } };
|
|
112
|
+
return rpcError(ErrorCode.InvalidParams, why);
|
|
113
|
+
}
|
|
114
|
+
/** One MCP client session against one server path. */
|
|
31
115
|
class ClientSession {
|
|
32
116
|
ctx;
|
|
33
117
|
transport;
|
|
34
118
|
gw;
|
|
119
|
+
folders;
|
|
35
120
|
id = "";
|
|
36
121
|
lastSeen = Date.now();
|
|
37
122
|
nextId = 1;
|
|
38
123
|
waiting = new Map();
|
|
39
|
-
|
|
124
|
+
/** Requests of this client being handled, and whether the client cancelled each one. */
|
|
125
|
+
handling = new Map();
|
|
126
|
+
constructor(ctx, transport, gw,
|
|
127
|
+
/** The session folder and, for a worktree, its main repository: what folder sets match. */
|
|
128
|
+
folders = []) {
|
|
40
129
|
this.ctx = ctx;
|
|
41
130
|
this.transport = transport;
|
|
42
131
|
this.gw = gw;
|
|
132
|
+
this.folders = folders;
|
|
133
|
+
}
|
|
134
|
+
supports(capability) {
|
|
135
|
+
const caps = this.ctx.clientCapabilities;
|
|
136
|
+
return caps === undefined || caps[capability] !== undefined;
|
|
43
137
|
}
|
|
44
138
|
notify(method, params, related) {
|
|
45
139
|
const m = { jsonrpc: "2.0", method, ...(params ? { params } : {}) };
|
|
46
|
-
void this.transport
|
|
140
|
+
void this.transport
|
|
141
|
+
.send(m, related !== undefined ? { relatedRequestId: related } : undefined)
|
|
142
|
+
.catch(() => { });
|
|
47
143
|
}
|
|
48
144
|
request(method, params, related) {
|
|
49
145
|
const id = `s${this.nextId++}`;
|
|
@@ -54,7 +150,9 @@ class ClientSession {
|
|
|
54
150
|
}, this.gw.clientRequestTimeoutMs);
|
|
55
151
|
this.waiting.set(id, { resolve, timer });
|
|
56
152
|
const m = { jsonrpc: "2.0", id, method, ...(params ? { params } : {}) };
|
|
57
|
-
this.transport
|
|
153
|
+
this.transport
|
|
154
|
+
.send(m, related !== undefined ? { relatedRequestId: related } : undefined)
|
|
155
|
+
.catch((err) => {
|
|
58
156
|
clearTimeout(timer);
|
|
59
157
|
this.waiting.delete(id);
|
|
60
158
|
resolve(rpcError(ErrorCode.Internal, `cannot reach client: ${err.message}`));
|
|
@@ -93,16 +191,31 @@ class ClientSession {
|
|
|
93
191
|
const id = m.id;
|
|
94
192
|
const method = m.method;
|
|
95
193
|
const manager = this.gw.manager;
|
|
194
|
+
const state = { cancelled: false };
|
|
195
|
+
this.handling.set(id, state);
|
|
96
196
|
try {
|
|
197
|
+
// Outside the folder's server set: answer from mcpd, never start the server.
|
|
198
|
+
const hidden = this.gw.hiddenBySet(this);
|
|
199
|
+
if (hidden) {
|
|
200
|
+
const agent = method === "initialize"
|
|
201
|
+
? cleanAgentName(m.params?.clientInfo?.name)
|
|
202
|
+
: undefined;
|
|
203
|
+
if (agent)
|
|
204
|
+
this.gw.nameClient(this, agent);
|
|
205
|
+
this.reply(id, hiddenAnswer(m, this.ctx.serverName, hidden));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
97
208
|
if (method === "initialize") {
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
209
|
+
const init = m.params;
|
|
210
|
+
this.ctx.clientCapabilities = init?.capabilities ?? {};
|
|
211
|
+
const agent = cleanAgentName(init?.clientInfo?.name);
|
|
212
|
+
if (agent)
|
|
213
|
+
this.gw.nameClient(this, agent);
|
|
101
214
|
const d = await manager.describe(this);
|
|
102
215
|
this.reply(id, {
|
|
103
216
|
result: {
|
|
104
217
|
protocolVersion: negotiateVersion(m.params?.protocolVersion),
|
|
105
|
-
capabilities: d.capabilities,
|
|
218
|
+
capabilities: announcedCapabilities(d.capabilities),
|
|
106
219
|
serverInfo: d.serverInfo,
|
|
107
220
|
...(d.instructions ? { instructions: d.instructions } : {}),
|
|
108
221
|
},
|
|
@@ -117,35 +230,68 @@ class ClientSession {
|
|
|
117
230
|
if (list) {
|
|
118
231
|
const d = await manager.describe(this);
|
|
119
232
|
if (!d.capabilities[list.cap]) {
|
|
120
|
-
this.reply(id, rpcError(ErrorCode.MethodNotFound, `${this.ctx.
|
|
233
|
+
this.reply(id, rpcError(ErrorCode.MethodNotFound, `${this.ctx.serverName} has no ${list.cap}`));
|
|
121
234
|
return;
|
|
122
235
|
}
|
|
123
|
-
|
|
236
|
+
let items = d[list.key] ?? [];
|
|
237
|
+
const filter = list.key === "tools" ? this.gw.toolFilter(this.ctx) : undefined;
|
|
238
|
+
if (filter)
|
|
239
|
+
items = items.filter((t) => toolAllowed(filter, String(t.name ?? "")));
|
|
240
|
+
this.reply(id, { result: { [list.field]: items } });
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (method === "tools/call") {
|
|
244
|
+
// The call middleware: tool filter, call log, session id, then the relay.
|
|
245
|
+
this.reply(id, await this.gw.calls.call(this, m.params ?? {}, id, () => state.cancelled));
|
|
124
246
|
return;
|
|
125
247
|
}
|
|
126
248
|
if (method === "logging/setLevel" && !manager.existing(this)) {
|
|
127
249
|
this.reply(id, { result: {} });
|
|
128
250
|
return;
|
|
129
251
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
252
|
+
if (method === "resources/subscribe" || method === "resources/unsubscribe") {
|
|
253
|
+
const uri = typeof m.params?.uri === "string" ? m.params.uri : "";
|
|
254
|
+
if (!uri) {
|
|
255
|
+
this.reply(id, rpcError(ErrorCode.InvalidParams, `${method} needs a uri`));
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
this.reply(id, method === "resources/subscribe"
|
|
259
|
+
? await manager.subscribe(this, uri, id)
|
|
260
|
+
: await manager.unsubscribe(this, uri, id));
|
|
133
261
|
return;
|
|
134
262
|
}
|
|
135
|
-
this.reply(id, await
|
|
263
|
+
this.reply(id, await manager.forward(this, method, m.params, id, () => state.cancelled));
|
|
136
264
|
}
|
|
137
265
|
catch (err) {
|
|
138
|
-
this.reply(id, rpcError(ErrorCode.Unavailable, `${this.ctx.
|
|
266
|
+
this.reply(id, rpcError(ErrorCode.Unavailable, `${this.ctx.serverName}: ${err.message}`));
|
|
267
|
+
}
|
|
268
|
+
finally {
|
|
269
|
+
if (this.handling.get(id) === state)
|
|
270
|
+
this.handling.delete(id);
|
|
139
271
|
}
|
|
140
272
|
}
|
|
141
273
|
handleNotification(m) {
|
|
142
274
|
const method = m.method;
|
|
143
275
|
if (method === "notifications/initialized")
|
|
144
276
|
return;
|
|
145
|
-
|
|
277
|
+
if (method === "notifications/cancelled") {
|
|
278
|
+
// Remembered for a request still waiting for its instance to start (forward drops it).
|
|
279
|
+
const state = this.handling.get(m.params?.requestId);
|
|
280
|
+
if (state)
|
|
281
|
+
state.cancelled = true;
|
|
282
|
+
}
|
|
283
|
+
if (this.gw.hiddenBySet(this))
|
|
284
|
+
return;
|
|
285
|
+
let inst;
|
|
286
|
+
try {
|
|
287
|
+
inst = this.gw.manager.existing(this);
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
146
292
|
if (!inst)
|
|
147
293
|
return;
|
|
148
|
-
if (method === "notifications/roots/list_changed" && scopeOf(
|
|
294
|
+
if (method === "notifications/roots/list_changed" && (scopeOf(inst.server) === "shared" || inst.workdirKnown))
|
|
149
295
|
return;
|
|
150
296
|
inst.upstream.notify(method, m.params, this);
|
|
151
297
|
}
|
|
@@ -157,13 +303,36 @@ class ClientSession {
|
|
|
157
303
|
export class Gateway {
|
|
158
304
|
opts;
|
|
159
305
|
manager;
|
|
306
|
+
/** Every tools/call of both protocol paths goes through it. */
|
|
307
|
+
calls;
|
|
160
308
|
clientRequestTimeoutMs;
|
|
161
309
|
sessions = new Map();
|
|
310
|
+
recreating = new Map();
|
|
162
311
|
http;
|
|
312
|
+
/** MCP 2026-07-28 stateless requests. */
|
|
313
|
+
front;
|
|
163
314
|
constructor(opts) {
|
|
164
315
|
this.opts = opts;
|
|
165
316
|
this.manager = opts.manager;
|
|
317
|
+
this.manager.useManifest(opts.manifest);
|
|
166
318
|
this.clientRequestTimeoutMs = opts.clientRequestTimeoutMs ?? 10 * 60_000;
|
|
319
|
+
this.calls = createCallPipeline({
|
|
320
|
+
manager: this.manager,
|
|
321
|
+
manifest: opts.manifest,
|
|
322
|
+
...(opts.callLog ? { callLog: opts.callLog } : {}),
|
|
323
|
+
...(opts.callStages ? { stages: opts.callStages } : {}),
|
|
324
|
+
});
|
|
325
|
+
this.front = new StatelessFront({
|
|
326
|
+
manager: this.manager,
|
|
327
|
+
calls: this.calls,
|
|
328
|
+
toolFilter: (ctx) => this.toolFilter(ctx),
|
|
329
|
+
context: (req, name, profile) => this.sessionContext(req, name, profile),
|
|
330
|
+
capabilities: announcedCapabilities,
|
|
331
|
+
...(opts.peerPid ? { peerPid: opts.peerPid } : {}),
|
|
332
|
+
folders: async (ctx) => (ctx.cwd && this.opts.folderRules ? folderRoots(ctx.cwd) : []),
|
|
333
|
+
hiddenBySet: (c) => this.hiddenBySet(c),
|
|
334
|
+
...(opts.log ? { log: opts.log } : {}),
|
|
335
|
+
});
|
|
167
336
|
}
|
|
168
337
|
listen(port, host = "127.0.0.1") {
|
|
169
338
|
this.http = createServer((req, res) => {
|
|
@@ -182,6 +351,7 @@ export class Gateway {
|
|
|
182
351
|
});
|
|
183
352
|
}
|
|
184
353
|
async close() {
|
|
354
|
+
this.front.close();
|
|
185
355
|
for (const s of this.sessions.values()) {
|
|
186
356
|
s.close();
|
|
187
357
|
await s.transport.close().catch(() => { });
|
|
@@ -193,12 +363,13 @@ export class Gateway {
|
|
|
193
363
|
sessionCount() {
|
|
194
364
|
return this.sessions.size;
|
|
195
365
|
}
|
|
196
|
-
/** Drop sessions whose
|
|
366
|
+
/** Drop sessions (and stateless clients) whose client process is gone. */
|
|
197
367
|
pruneSessions(isAlive) {
|
|
198
368
|
for (const [id, s] of this.sessions) {
|
|
199
369
|
if (s.ctx.pid && !isAlive(s.ctx.pid))
|
|
200
370
|
this.dropSession(id);
|
|
201
371
|
}
|
|
372
|
+
this.front.prune(isAlive);
|
|
202
373
|
}
|
|
203
374
|
dropSession(id) {
|
|
204
375
|
const s = this.sessions.get(id);
|
|
@@ -208,64 +379,262 @@ export class Gateway {
|
|
|
208
379
|
s.close();
|
|
209
380
|
this.manager.detach(s);
|
|
210
381
|
}
|
|
211
|
-
|
|
382
|
+
/** Local, not a browser, and a valid token: the master (admin) or a profile token. */
|
|
383
|
+
authenticate(req) {
|
|
212
384
|
const addr = req.socket.remoteAddress ?? "";
|
|
213
385
|
if (!["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(addr))
|
|
214
|
-
return "not local";
|
|
386
|
+
return { status: 403, error: "not local" };
|
|
215
387
|
const host = header(req, "host") ?? "";
|
|
216
388
|
if (!/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(host))
|
|
217
|
-
return "bad host";
|
|
389
|
+
return { status: 403, error: "bad host" };
|
|
218
390
|
if (header(req, "origin") !== undefined)
|
|
219
|
-
return "browser origin";
|
|
391
|
+
return { status: 403, error: "browser origin" };
|
|
220
392
|
const auth = header(req, "authorization") ?? "";
|
|
221
|
-
if (
|
|
222
|
-
return
|
|
223
|
-
|
|
393
|
+
if (safeEqual(auth, `Bearer ${this.opts.token}`))
|
|
394
|
+
return { admin: true };
|
|
395
|
+
const profile = auth.startsWith("Bearer ") ? tokenProfile(this.opts.token, auth.slice(7).trim()) : undefined;
|
|
396
|
+
return profile ? { admin: false, profile } : { status: 401, error: BAD_TOKEN };
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Call before a config.toml or mcp.toml change: notes what each open session sees (its
|
|
400
|
+
* folder's server set and its tool filter). The returned function, called
|
|
401
|
+
* after the change, sends list_changed to the sessions whose view changed, so their agents
|
|
402
|
+
* list again without reconnecting, and returns how many it told. Stateless 2026-07-28 clients
|
|
403
|
+
* are not told: they see the change when their list results expire (`ttlMs`).
|
|
404
|
+
*/
|
|
405
|
+
beforeViewChange() {
|
|
406
|
+
const view = (s) => ({
|
|
407
|
+
hidden: this.hiddenBySet(s) !== undefined,
|
|
408
|
+
filter: JSON.stringify(this.toolFilter(s.ctx) ?? null),
|
|
409
|
+
});
|
|
410
|
+
const before = new Map([...this.sessions.values()].map((s) => [s, view(s)]));
|
|
411
|
+
return () => {
|
|
412
|
+
let told = 0;
|
|
413
|
+
for (const [s, was] of before) {
|
|
414
|
+
if (this.sessions.get(s.id) !== s)
|
|
415
|
+
continue;
|
|
416
|
+
const now = view(s);
|
|
417
|
+
if (now.hidden === was.hidden && now.filter === was.filter)
|
|
418
|
+
continue;
|
|
419
|
+
s.notify("notifications/tools/list_changed", undefined);
|
|
420
|
+
if (now.hidden !== was.hidden) {
|
|
421
|
+
s.notify("notifications/prompts/list_changed", undefined);
|
|
422
|
+
s.notify("notifications/resources/list_changed", undefined);
|
|
423
|
+
}
|
|
424
|
+
told++;
|
|
425
|
+
}
|
|
426
|
+
if (told)
|
|
427
|
+
this.opts.log?.(`told ${told} session${told === 1 ? "" : "s"} that their server lists changed`);
|
|
428
|
+
return told;
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
/** The tool filter for a session, or undefined when its server filters nothing. */
|
|
432
|
+
toolFilter(ctx) {
|
|
433
|
+
return toolFilterOf(this.opts.manifest(), ctx);
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Record the agent name a session gave in initialize. Sessions of the same process that mcpd
|
|
437
|
+
* rebuilt without one (after a restart) take it too, and it is kept for the next restart.
|
|
438
|
+
*/
|
|
439
|
+
nameClient(session, name) {
|
|
440
|
+
session.ctx.clientName = name;
|
|
441
|
+
const pid = session.ctx.pid;
|
|
442
|
+
if (!pid)
|
|
443
|
+
return;
|
|
444
|
+
for (const s of this.sessions.values())
|
|
445
|
+
if (s.ctx.pid === pid && !s.ctx.clientName)
|
|
446
|
+
s.ctx.clientName = name;
|
|
447
|
+
this.opts.clientNames?.set(pid, name);
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Why a session's folder hides its server, or undefined when the server is
|
|
451
|
+
* shown. Read on every use, so a changed config.toml applies to open sessions on their next
|
|
452
|
+
* list or call. A session whose folder mcpd could not learn is never hidden.
|
|
453
|
+
*/
|
|
454
|
+
hiddenBySet(s) {
|
|
455
|
+
const rules = this.opts.folderRules?.();
|
|
456
|
+
if (!rules?.length || !s.folders.length)
|
|
457
|
+
return undefined;
|
|
458
|
+
const set = folderMcpSet(s.folders, rules, s.ctx.profile);
|
|
459
|
+
if (mcpSetAllows(set, s.ctx.serverName))
|
|
460
|
+
return undefined;
|
|
461
|
+
const where = this.opts.home ? tildify(set.path, { HOME: this.opts.home }) : set.path;
|
|
462
|
+
return `${s.ctx.serverName} is not in the MCP set of ${where} (mcp / mcp_deny of its [[projects]] rule in config.toml); turno hides it in this folder`;
|
|
463
|
+
}
|
|
464
|
+
lastMasterWarning = 0;
|
|
465
|
+
refuseMaster(res, name) {
|
|
466
|
+
if (Date.now() - this.lastMasterWarning > 60_000) {
|
|
467
|
+
this.lastMasterWarning = Date.now();
|
|
468
|
+
this.opts.log?.(`refused a session for ${name ?? "?"} that sent the master token: an agent config predates per-profile tokens (turno mcp sync fixes it)`);
|
|
469
|
+
}
|
|
470
|
+
json(res, 403, { error: MASTER_TOKEN_REFUSED });
|
|
471
|
+
}
|
|
472
|
+
servable(name) {
|
|
473
|
+
const server = name ? this.opts.manifest().servers[name] : undefined;
|
|
474
|
+
return server !== undefined && !(server.kind === "remote" && !server.proxy);
|
|
224
475
|
}
|
|
225
476
|
async handle(req, res) {
|
|
226
|
-
const
|
|
227
|
-
if (
|
|
228
|
-
json(res,
|
|
477
|
+
const caller = this.authenticate(req);
|
|
478
|
+
if ("status" in caller) {
|
|
479
|
+
json(res, caller.status, { error: caller.error });
|
|
229
480
|
return;
|
|
230
481
|
}
|
|
231
482
|
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
232
|
-
|
|
233
|
-
|
|
483
|
+
const refresh = /^\/refresh(?:\/([^/]+))?\/?$/.exec(url.pathname);
|
|
484
|
+
const logout = /^\/logout\/([^/]+)\/?$/.exec(url.pathname);
|
|
485
|
+
if ((url.pathname === "/status" && req.method === "GET") || ((refresh || logout) && req.method === "POST")) {
|
|
486
|
+
if (!caller.admin) {
|
|
487
|
+
json(res, 403, { error: "a profile token cannot use the admin endpoints" });
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
if (refresh)
|
|
491
|
+
await this.handleRefresh(refresh[1] ? decodeURIComponent(refresh[1]) : undefined, res);
|
|
492
|
+
else if (logout?.[1])
|
|
493
|
+
this.handleLogout(decodeURIComponent(logout[1]), url.searchParams.getAll("variant"), res);
|
|
494
|
+
else
|
|
495
|
+
json(res, 200, this.status());
|
|
234
496
|
return;
|
|
235
497
|
}
|
|
236
498
|
const m = /^\/mcp\/([^/]+)\/?$/.exec(url.pathname);
|
|
237
499
|
const name = m?.[1] ? decodeURIComponent(m[1]) : undefined;
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
500
|
+
if (caller.admin) {
|
|
501
|
+
if (m)
|
|
502
|
+
this.refuseMaster(res, name);
|
|
503
|
+
else
|
|
504
|
+
json(res, 404, { error: "unknown server " });
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
// The profile comes from the token; a header that disagrees is a config copied across
|
|
508
|
+
// profiles or a forgery, and is refused rather than ignored.
|
|
509
|
+
const claimed = header(req, "x-turno-profile")?.trim();
|
|
510
|
+
if (claimed && claimed !== caller.profile) {
|
|
511
|
+
json(res, 403, { error: `X-Turno-Profile says ${claimed}, but the token belongs to profile ${caller.profile}` });
|
|
241
512
|
return;
|
|
242
513
|
}
|
|
243
514
|
const sid = header(req, "mcp-session-id");
|
|
515
|
+
const open = sid ? this.sessions.get(sid) : undefined;
|
|
516
|
+
// An open session goes on even if its server left the manifest: it then gets a JSON-RPC
|
|
517
|
+
// error that says so, instead of an HTTP 404 the client reports as a transport failure.
|
|
518
|
+
if (!name || (!this.servable(name) && open?.ctx.serverName !== name)) {
|
|
519
|
+
json(res, 404, { error: `unknown server ${name ?? ""}` });
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
const def = this.opts.manifest().servers[name];
|
|
523
|
+
if (def && !servesProfile(def, caller.profile)) {
|
|
524
|
+
json(res, 403, { error: `server ${name} is not enabled for profile ${caller.profile} (profiles in mcp.toml)` });
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
if (open && open.ctx.profile !== caller.profile) {
|
|
528
|
+
json(res, 403, { error: `session ${sid} belongs to another profile` });
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
// MCP 2026-07-28: the version header names a newer revision.
|
|
532
|
+
let parsed;
|
|
533
|
+
if (wantsModern(req)) {
|
|
534
|
+
const body = await readJsonBody(req, this.opts.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY);
|
|
535
|
+
if (!("value" in body)) {
|
|
536
|
+
json(res, body.status, { jsonrpc: "2.0", id: null, error: { code: body.code, message: body.message } });
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
if (!isInitialize(body.value)) {
|
|
540
|
+
await this.front.handle(req, res, name, caller.profile, body.value);
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
if (sid) {
|
|
544
|
+
json(res, 400, {
|
|
545
|
+
jsonrpc: "2.0",
|
|
546
|
+
id: null,
|
|
547
|
+
error: { code: ErrorCode.InvalidRequest, message: "initialize cannot carry an Mcp-Session-Id" },
|
|
548
|
+
});
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
// A dual-era client asking for a 2025-era session: the SDK takes it from here.
|
|
552
|
+
parsed = body.value;
|
|
553
|
+
}
|
|
244
554
|
if (sid) {
|
|
245
|
-
|
|
246
|
-
|
|
555
|
+
let s = open;
|
|
556
|
+
// mcpd restarted (upgrade, refresh, crash): rebuild the session under the same id from
|
|
557
|
+
// the request headers instead of a 404 that ends the client's conversation.
|
|
558
|
+
if (!s && (req.method === "POST" || req.method === "GET") && SESSION_ID.test(sid))
|
|
559
|
+
s = await this.recreate(req, name, sid, caller.profile);
|
|
560
|
+
if (!s || s.ctx.serverName !== name || s.ctx.profile !== caller.profile) {
|
|
247
561
|
json(res, 404, { jsonrpc: "2.0", error: { code: -32001, message: "Session not found" }, id: null });
|
|
248
562
|
return;
|
|
249
563
|
}
|
|
250
564
|
await s.transport.handleRequest(req, res);
|
|
251
565
|
return;
|
|
252
566
|
}
|
|
253
|
-
|
|
254
|
-
|
|
567
|
+
const session = await this.createSession(req, name, caller.profile);
|
|
568
|
+
await session?.transport.handleRequest(req, res, parsed);
|
|
569
|
+
if (session && !session.transport.sessionId)
|
|
570
|
+
await session.transport.close().catch(() => { });
|
|
571
|
+
}
|
|
572
|
+
/** `POST /refresh` (every server) or `POST /refresh/<server>`: relearn tool lists without a restart. */
|
|
573
|
+
async handleRefresh(name, res) {
|
|
574
|
+
const servers = this.opts.manifest().servers;
|
|
575
|
+
if (name !== undefined && !servers[name]) {
|
|
576
|
+
json(res, 404, { error: `unknown server ${name}` });
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
const names = name !== undefined ? [name] : Object.keys(servers).sort();
|
|
580
|
+
const out = {};
|
|
581
|
+
for (const n of names)
|
|
582
|
+
out[n] = await this.manager.refresh(n);
|
|
583
|
+
this.opts.log?.(`refreshed ${names.join(", ") || "nothing"}`);
|
|
584
|
+
json(res, 200, name !== undefined ? { server: name, ...out[name] } : { servers: out });
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* `POST /logout/<server>[?variant=v...]`, sent by `turno mcp logout` after it removed the
|
|
588
|
+
* login: mcpd drops its copy of those variants (every variant when none are named), so the
|
|
589
|
+
* next request reads the secret store at once instead of up to a minute later.
|
|
590
|
+
*/
|
|
591
|
+
handleLogout(name, variants, res) {
|
|
592
|
+
this.manager.forgetLogin(name, variants.length ? variants : undefined);
|
|
593
|
+
this.opts.log?.(`${name}: OAuth login removed (${variants.length ? variants.join(", ") : "every variant"}); reading the secret store again`);
|
|
594
|
+
json(res, 200, { server: name, variants: variants.length ? variants : null });
|
|
595
|
+
}
|
|
596
|
+
/** Identity and folder of a new session: profile (from its token), PID (header, else TCP peer), folder (header, else the PID's). */
|
|
597
|
+
async sessionContext(req, name, profile) {
|
|
255
598
|
let pid = Number.parseInt(header(req, "x-turno-pid") ?? "0", 10) || undefined;
|
|
256
599
|
if (!pid && this.opts.peerPid && req.socket.remotePort)
|
|
257
600
|
pid = await this.opts.peerPid(req.socket.remotePort);
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
601
|
+
let cwd = decodeCwdHeaders(req.headers);
|
|
602
|
+
if (cwd && !isDirectory(cwd)) {
|
|
603
|
+
this.opts.log?.(`session folder ${cwd} for ${name} does not exist; looking at the client process instead`);
|
|
604
|
+
cwd = undefined;
|
|
605
|
+
}
|
|
606
|
+
if (!cwd && pid) {
|
|
607
|
+
const fromPid = await (this.opts.processCwd ?? processCwd)(pid);
|
|
608
|
+
if (fromPid && isDirectory(fromPid))
|
|
609
|
+
cwd = fromPid;
|
|
610
|
+
}
|
|
611
|
+
const root = cwd ? await projectRoot(cwd) : undefined;
|
|
612
|
+
return {
|
|
613
|
+
serverName: name,
|
|
261
614
|
sessionId: "",
|
|
262
|
-
|
|
615
|
+
profile,
|
|
263
616
|
...(pid ? { pid } : {}),
|
|
264
617
|
...(cwd ? { cwd } : {}),
|
|
618
|
+
...(root ? { projectRoot: root } : {}),
|
|
265
619
|
};
|
|
620
|
+
}
|
|
621
|
+
/** One recreation per id, even when the client's GET stream and next POST arrive together. */
|
|
622
|
+
recreate(req, name, sid, profile) {
|
|
623
|
+
let p = this.recreating.get(sid);
|
|
624
|
+
if (!p) {
|
|
625
|
+
p = this.createSession(req, name, profile, sid);
|
|
626
|
+
this.recreating.set(sid, p);
|
|
627
|
+
p.finally(() => this.recreating.delete(sid)).catch(() => { });
|
|
628
|
+
}
|
|
629
|
+
return p;
|
|
630
|
+
}
|
|
631
|
+
async createSession(req, name, profile, fixedId) {
|
|
632
|
+
const ctx = await this.sessionContext(req, name, profile);
|
|
633
|
+
const folders = ctx.cwd && this.opts.folderRules ? await folderRoots(ctx.cwd) : [];
|
|
266
634
|
let session;
|
|
267
635
|
const transport = new StreamableHTTPServerTransport({
|
|
268
|
-
sessionIdGenerator: () => randomUUID(),
|
|
636
|
+
sessionIdGenerator: () => fixedId ?? randomUUID(),
|
|
637
|
+
maxRequestBodySize: this.opts.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY,
|
|
269
638
|
onsessioninitialized: (id) => {
|
|
270
639
|
if (!session)
|
|
271
640
|
return;
|
|
@@ -276,33 +645,86 @@ export class Gateway {
|
|
|
276
645
|
},
|
|
277
646
|
onsessionclosed: (id) => this.dropSession(id),
|
|
278
647
|
});
|
|
279
|
-
session = new ClientSession(ctx, transport, this);
|
|
648
|
+
session = new ClientSession(ctx, transport, this, folders);
|
|
280
649
|
const s = session;
|
|
281
650
|
transport.onmessage = (msg) => s.onMessage(msg);
|
|
282
651
|
transport.onclose = () => {
|
|
283
652
|
if (s.id)
|
|
284
653
|
this.dropSession(s.id);
|
|
285
654
|
};
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
655
|
+
if (fixedId) {
|
|
656
|
+
if (!markInitialized(transport, fixedId)) {
|
|
657
|
+
await transport.close().catch(() => { });
|
|
658
|
+
return undefined;
|
|
659
|
+
}
|
|
660
|
+
s.id = fixedId;
|
|
661
|
+
ctx.sessionId = fixedId;
|
|
662
|
+
// A rebuilt session never sees initialize: take the name its process gave before.
|
|
663
|
+
const known = ctx.pid
|
|
664
|
+
? ([...this.sessions.values()].find((o) => o.ctx.pid === ctx.pid && o.ctx.clientName)?.ctx.clientName ??
|
|
665
|
+
this.opts.clientNames?.get(ctx.pid))
|
|
666
|
+
: undefined;
|
|
667
|
+
if (known)
|
|
668
|
+
ctx.clientName = known;
|
|
669
|
+
this.sessions.set(fixedId, s);
|
|
670
|
+
this.manager.register(s);
|
|
671
|
+
this.opts.log?.(`recreated session ${fixedId} for ${name} (unknown to this mcpd, likely after a restart)`);
|
|
672
|
+
}
|
|
673
|
+
return s;
|
|
674
|
+
}
|
|
675
|
+
/** Agent processes behind the open sessions: one entry per client PID (or per session without one). */
|
|
676
|
+
agents() {
|
|
677
|
+
const by = new Map();
|
|
678
|
+
for (const s of [...this.sessions.values(), ...this.front.list()]) {
|
|
679
|
+
const key = s.ctx.pid ? `pid:${s.ctx.pid}` : `sid:${s.id}`;
|
|
680
|
+
const a = by.get(key) ?? {
|
|
681
|
+
pid: s.ctx.pid ?? null,
|
|
682
|
+
profile: s.ctx.profile ?? null,
|
|
683
|
+
agent: s.ctx.clientName ?? null,
|
|
684
|
+
servers: [],
|
|
685
|
+
};
|
|
686
|
+
if (!a.servers.includes(s.ctx.serverName))
|
|
687
|
+
a.servers.push(s.ctx.serverName);
|
|
688
|
+
a.agent ??= s.ctx.clientName ?? null;
|
|
689
|
+
by.set(key, a);
|
|
690
|
+
}
|
|
691
|
+
return [...by.values()];
|
|
289
692
|
}
|
|
290
693
|
status() {
|
|
291
694
|
return {
|
|
292
695
|
pid: process.pid,
|
|
293
696
|
sessions: this.sessions.size,
|
|
697
|
+
agents: this.agents(),
|
|
698
|
+
memoryPressure: this.manager.memoryPressure(),
|
|
294
699
|
instances: this.manager.list().map((i) => ({
|
|
295
700
|
key: i.key,
|
|
296
701
|
server: i.server.name,
|
|
297
702
|
variant: i.variant,
|
|
703
|
+
scope: i.scope,
|
|
298
704
|
pid: i.upstream.pid ?? null,
|
|
299
705
|
clients: i.clients.size,
|
|
300
706
|
holder: i.holder ? { profile: i.holder.ctx.profile ?? null, pid: i.holder.ctx.pid ?? null } : null,
|
|
301
707
|
idleSeconds: Math.round((Date.now() - i.upstream.lastActivity) / 1000),
|
|
302
708
|
inflight: i.upstream.inflight,
|
|
709
|
+
inflightByClient: i.upstream.inflightByClient(),
|
|
303
710
|
startedAt: i.upstream.startedAt,
|
|
711
|
+
restarts: this.manager.restarts(i.key),
|
|
304
712
|
})),
|
|
305
713
|
};
|
|
306
714
|
}
|
|
307
715
|
}
|
|
716
|
+
/**
|
|
717
|
+
* Put a fresh SDK transport in the state it has after initialize, under a known session id.
|
|
718
|
+
* The SDK has no public way to adopt a session, so this sets two fields of its inner
|
|
719
|
+
* web-standard transport; the SDK version is pinned and a test covers it. Returns false
|
|
720
|
+
* (and the caller answers 404 as before) when the fields are not where they are expected.
|
|
721
|
+
*/
|
|
722
|
+
function markInitialized(transport, id) {
|
|
723
|
+
const inner = transport._webStandardTransport;
|
|
724
|
+
if (!inner || typeof inner._initialized !== "boolean")
|
|
725
|
+
return false;
|
|
726
|
+
inner.sessionId = id;
|
|
727
|
+
inner._initialized = true;
|
|
728
|
+
return true;
|
|
729
|
+
}
|
|
308
730
|
//# sourceMappingURL=gateway.js.map
|