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