@foldrun/core 24.8.1 → 24.9.1
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/dist/src/engine-common.d.ts +16 -0
- package/dist/src/engine-common.js +22 -4
- package/dist/src/engine-compact.d.ts +61 -0
- package/dist/src/engine-compact.js +293 -0
- package/dist/src/engine-loop.d.ts +1 -1
- package/dist/src/engine-loop.js +199 -15
- package/dist/src/engine-mcp.d.ts +63 -0
- package/dist/src/engine-mcp.js +275 -0
- package/dist/src/engine-tools.d.ts +11 -0
- package/dist/src/ops-log.js +2 -2
- package/dist/src/providers.js +3 -3
- package/dist/src/runner.js +3 -2
- package/dist/src/script-tools.d.ts +3 -1
- package/dist/src/script-tools.js +34 -6
- package/dist/src/step-exec.d.ts +6 -0
- package/dist/src/step-exec.js +43 -2
- package/package.json +2 -1
- package/src/engine-common.ts +30 -4
- package/src/engine-compact.ts +288 -0
- package/src/engine-loop.ts +175 -16
- package/src/engine-mcp.ts +281 -0
- package/src/engine-tools.ts +4 -0
- package/src/ops-log.ts +2 -2
- package/src/providers.ts +3 -3
- package/src/runner.ts +3 -2
- package/src/script-tools.ts +27 -4
- package/src/step-exec.ts +49 -2
package/dist/src/engine-loop.js
CHANGED
|
@@ -35,6 +35,8 @@
|
|
|
35
35
|
// on the result, as it does from the SDK.
|
|
36
36
|
import crypto from "node:crypto";
|
|
37
37
|
import { killGroups } from "./engine-tools.js";
|
|
38
|
+
import { connectMcp } from "./engine-mcp.js";
|
|
39
|
+
import { SUMMARIZATION_SYSTEM_PROMPT, compacted, cutPoints, estimateTokens, fileLists, findCut, isContextOverflow, previousSummary, summaryRequest } from "./engine-compact.js";
|
|
38
40
|
import { DEFAULT_MAX_TOKENS, readOptions, decide, after, emptyUsage, addUsage } from "./engine-common.js";
|
|
39
41
|
const DEFAULT_BASE = "https://api.anthropic.com";
|
|
40
42
|
const API_VERSION = "2023-06-01";
|
|
@@ -82,8 +84,9 @@ export function endOf(stopReason, calls) {
|
|
|
82
84
|
return { subtype: "error_unknown_stop", error: `the model stopped for a reason this engine does not know (${stopReason ?? "none given"}) — the step did not finish` };
|
|
83
85
|
}
|
|
84
86
|
}
|
|
85
|
-
export function buildRequest(o, messages) {
|
|
86
|
-
|
|
87
|
+
export function buildRequest(o, messages, cache = true, maxTokens) {
|
|
88
|
+
// A one-off request (a summary) writes nothing to the cache.
|
|
89
|
+
const mark = cache ? { cache_control: { type: "ephemeral" } } : {};
|
|
87
90
|
const tools = o.tools.map((t, i) => ({
|
|
88
91
|
name: t.name,
|
|
89
92
|
description: t.description,
|
|
@@ -99,7 +102,7 @@ export function buildRequest(o, messages) {
|
|
|
99
102
|
const asked = Number(o.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS);
|
|
100
103
|
return {
|
|
101
104
|
model: o.model,
|
|
102
|
-
max_tokens: Number.isFinite(asked) && asked > 0 ? asked : DEFAULT_MAX_TOKENS,
|
|
105
|
+
max_tokens: Math.min(maxTokens ?? Infinity, Number.isFinite(asked) && asked > 0 ? asked : DEFAULT_MAX_TOKENS),
|
|
103
106
|
...(o.systemPrompt ? { system: [{ type: "text", text: o.systemPrompt, ...mark }] } : {}),
|
|
104
107
|
...(tools.length ? { tools } : {}),
|
|
105
108
|
messages: sent,
|
|
@@ -135,7 +138,7 @@ async function openStream(o, body, signal) {
|
|
|
135
138
|
lastError = `the model endpoint answered ${res.status}: ${text}`;
|
|
136
139
|
const retryable = res.status === 408 || res.status === 409 || res.status === 429 || res.status >= 500;
|
|
137
140
|
if (!retryable)
|
|
138
|
-
throw new Error(lastError);
|
|
141
|
+
throw Object.assign(new Error(lastError), { status: res.status });
|
|
139
142
|
const after = Number(res.headers.get("retry-after"));
|
|
140
143
|
if (attempt < MODEL_TRIES)
|
|
141
144
|
await sleep(Math.min(RETRY_AFTER_CAP_MS, Number.isFinite(after) && after > 0 ? after * 1000 : 1000 * 2 ** (attempt - 1)), signal);
|
|
@@ -182,9 +185,13 @@ async function* sse(res) {
|
|
|
182
185
|
}
|
|
183
186
|
}
|
|
184
187
|
/** One model call: yields the raw stream events, returns the whole turn. */
|
|
185
|
-
async function* modelTurn(o, messages, signal) {
|
|
186
|
-
const res = await openStream(o, buildRequest(o, messages), signal);
|
|
188
|
+
async function* modelTurn(o, messages, signal, cache = true, maxTokens, track) {
|
|
189
|
+
const res = await openStream(o, buildRequest(o, messages, cache, maxTokens), signal);
|
|
187
190
|
const turn = { id: "", model: o.model, content: [], stopReason: null, usage: emptyUsage(), malformed: new Set() };
|
|
191
|
+
// A caller that must count what a stream that breaks part-way had
|
|
192
|
+
// already reported (a summary request) reads it here.
|
|
193
|
+
if (track)
|
|
194
|
+
track.turn = turn;
|
|
188
195
|
const partialJson = new Map();
|
|
189
196
|
const open = new Set();
|
|
190
197
|
let stopped = false;
|
|
@@ -284,13 +291,157 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
284
291
|
permission_denials: [],
|
|
285
292
|
session_id: sessionId,
|
|
286
293
|
});
|
|
287
|
-
|
|
294
|
+
// The step's MCP servers, connected before the first model call: their
|
|
295
|
+
// tools sit after the built-in and host ones (engine-mcp.ts). One that
|
|
296
|
+
// does not start refuses the step here, before anything is paid for.
|
|
297
|
+
let mcp = null;
|
|
288
298
|
try {
|
|
299
|
+
if (Object.keys(o.mcpServers).length) {
|
|
300
|
+
mcp = await connectMcp(o.mcpServers, { env: o.env, toolEnv: o.shellEnv, cwd: o.cwd, signal });
|
|
301
|
+
for (const t of mcp.tools) {
|
|
302
|
+
if (byName.has(t.name))
|
|
303
|
+
throw new Error(`the MCP tool ${t.name} has the name of a tool the step already has`);
|
|
304
|
+
byName.set(t.name, t);
|
|
305
|
+
}
|
|
306
|
+
o.tools = [...o.tools, ...mcp.tools];
|
|
307
|
+
if (mcp.instructions.length) {
|
|
308
|
+
o.systemPrompt = [o.systemPrompt, "# MCP Server Instructions", ...mcp.instructions.map((i) => `## ${i.server}\n${i.text}`)].filter(Boolean).join("\n\n");
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
// A tool the step was granted that its server does not offer: the step
|
|
312
|
+
// would run without it, and the model be told it has none.
|
|
313
|
+
const missing = o.mcpGranted.filter((g) => mcp?.owner.get(g.name) !== g.server).map((g) => g.name);
|
|
314
|
+
if (missing.length)
|
|
315
|
+
throw new Error(`granted but not offered by its MCP server: ${missing.join(", ")}`);
|
|
316
|
+
yield { type: "system", subtype: "init", session_id: sessionId, cwd: o.cwd, model: o.model, tools: o.tools.map((t) => t.name), mcp_servers: mcp?.servers ?? [], engine: "foldrun" };
|
|
317
|
+
// ---- Compaction (engine-compact.ts). What the context holds is the last
|
|
318
|
+
// turn's own count (everything it was sent, and its reply) plus an
|
|
319
|
+
// estimate of what has been added since; before any turn, an estimate of
|
|
320
|
+
// it all.
|
|
321
|
+
let measured = null;
|
|
322
|
+
const filesRead = new Set();
|
|
323
|
+
const filesChanged = new Set();
|
|
324
|
+
let autoCompaction = o.compaction !== false;
|
|
325
|
+
const contextNow = () => {
|
|
326
|
+
if (measured)
|
|
327
|
+
return measured.tokens + messages.slice(measured.at).reduce((n, m) => n + estimateTokens(m), 0);
|
|
328
|
+
const fixed = Math.ceil((o.systemPrompt.length + JSON.stringify(o.tools.map((t) => [t.name, t.description, t.input_schema])).length) / 4);
|
|
329
|
+
return fixed + messages.reduce((n, m) => n + estimateTokens(m), 0);
|
|
330
|
+
};
|
|
331
|
+
/** Summarise the older part and go on from the summary and the newest
|
|
332
|
+
* part. False, with the reason, when there is nothing to cut or the
|
|
333
|
+
* summary did not come back whole. */
|
|
334
|
+
// `asked`: a summary was asked for (and paid for) and did not come back.
|
|
335
|
+
async function* compactNow(trigger, before) {
|
|
336
|
+
if (o.compaction === false)
|
|
337
|
+
return { ok: false, why: "compaction is off" };
|
|
338
|
+
const room = o.compaction.contextWindow - o.compaction.reserveTokens;
|
|
339
|
+
// The kept part leaves room for the summary (a few thousand tokens).
|
|
340
|
+
// After an overflow the real window is smaller than assumed: the kept
|
|
341
|
+
// part is held to the keep budget itself.
|
|
342
|
+
let cut = findCut(messages, o.compaction.keepRecentTokens, trigger === "overflow" ? o.compaction.keepRecentTokens : Math.max(0, room - 4_096));
|
|
343
|
+
if (cut < 1)
|
|
344
|
+
return { ok: false, why: "there was nothing older to summarise" };
|
|
345
|
+
// A summary of a few words makes no room and is not worth paying for:
|
|
346
|
+
// a later cut is tried (the newest message is always kept).
|
|
347
|
+
const older = (c) => messages.slice(0, c).reduce((n, m) => n + estimateTokens(m), 0);
|
|
348
|
+
for (const later of cutPoints(messages))
|
|
349
|
+
if (later > cut && older(cut) < 1_024)
|
|
350
|
+
cut = later;
|
|
351
|
+
if (older(cut) < 1_024)
|
|
352
|
+
return { ok: false, why: "there was too little older to summarise" };
|
|
353
|
+
const ask = { ...o, systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, tools: [], partial: false };
|
|
354
|
+
// The request itself must fit: the conversation's text is held to the
|
|
355
|
+
// window less the reply's reserve and the prompts, newest part kept.
|
|
356
|
+
const request = [{ role: "user", content: [{ type: "text", text: summaryRequest(messages.slice(0, cut), previousSummary(messages), Math.max(4_000, (room - 3_000) * 4)) }] }];
|
|
357
|
+
let reply;
|
|
358
|
+
const track = {};
|
|
359
|
+
try {
|
|
360
|
+
// Its reply is held to the window's reserve: input and output must fit.
|
|
361
|
+
const stream = modelTurn(ask, request, signal, false, o.compaction.reserveTokens, track);
|
|
362
|
+
for (;;) {
|
|
363
|
+
const step = await stream.next();
|
|
364
|
+
if (step.done) {
|
|
365
|
+
reply = step.value;
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
catch (err) {
|
|
371
|
+
// What the endpoint had counted before the stream broke was paid for.
|
|
372
|
+
const spent = track.turn?.usage;
|
|
373
|
+
if (spent && Object.values(spent).some((n) => n > 0)) {
|
|
374
|
+
for (const k of Object.keys(total))
|
|
375
|
+
total[k] += spent[k];
|
|
376
|
+
yield { type: "system", subtype: "compact_failed", session_id: sessionId, error: `the summary request failed: ${err.message}`, model: track.turn.model, usage: { ...spent } };
|
|
377
|
+
}
|
|
378
|
+
if (signal.aborted)
|
|
379
|
+
throw err;
|
|
380
|
+
return { ok: false, asked: true, why: `the summary request failed: ${err.message}` };
|
|
381
|
+
}
|
|
382
|
+
// Paid for like any turn: in the total, and reported with what it
|
|
383
|
+
// came to so the step's cost and budget count it (step-exec).
|
|
384
|
+
for (const k of Object.keys(total))
|
|
385
|
+
total[k] += reply.usage[k];
|
|
386
|
+
const summary = reply.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
|
|
387
|
+
if (reply.stopReason !== "end_turn" || reply.content.some((b) => b.type === "tool_use") || !summary) {
|
|
388
|
+
const why = `the summary did not come back whole (stop reason ${reply.stopReason ?? "none"})`;
|
|
389
|
+
yield { type: "system", subtype: "compact_failed", session_id: sessionId, error: why, model: reply.model, usage: { ...reply.usage } };
|
|
390
|
+
return { ok: false, asked: true, why };
|
|
391
|
+
}
|
|
392
|
+
const next = compacted(summary + fileLists(filesRead, filesChanged), messages.slice(cut));
|
|
393
|
+
messages.splice(0, messages.length, ...next);
|
|
394
|
+
measured = null;
|
|
395
|
+
yield {
|
|
396
|
+
type: "system",
|
|
397
|
+
subtype: "compact_boundary",
|
|
398
|
+
session_id: sessionId,
|
|
399
|
+
compact_metadata: { trigger, pre_tokens: before, post_tokens: contextNow(), summarized_messages: cut },
|
|
400
|
+
model: reply.model,
|
|
401
|
+
usage: { ...reply.usage },
|
|
402
|
+
// The conversation as it now stands, so a caller that keeps one
|
|
403
|
+
// (foldrun code) goes on from it rather than the whole history.
|
|
404
|
+
conversation: messages.map((m) => ({ role: m.role, content: [...m.content] })),
|
|
405
|
+
};
|
|
406
|
+
return { ok: true };
|
|
407
|
+
}
|
|
408
|
+
// Set when a request was refused as too long and compacted: the same
|
|
409
|
+
// request is asked again once, not compacted again and again.
|
|
410
|
+
let overflowed = false;
|
|
289
411
|
for (;;) {
|
|
290
412
|
if (o.maxTurns !== null && turns >= o.maxTurns) {
|
|
291
413
|
yield result("error_max_turns", null);
|
|
292
414
|
return;
|
|
293
415
|
}
|
|
416
|
+
// Not on the retry after an overflow (that request is asked again as
|
|
417
|
+
// compacted), and not while the model's own turn is being continued
|
|
418
|
+
// (pause_turn): the conversation must end on a user turn to be cut.
|
|
419
|
+
if (autoCompaction && !overflowed && o.compaction !== false && messages.at(-1)?.role === "user") {
|
|
420
|
+
const now = contextNow();
|
|
421
|
+
if (now > o.compaction.contextWindow - o.compaction.reserveTokens) {
|
|
422
|
+
let done;
|
|
423
|
+
try {
|
|
424
|
+
done = yield* compactNow("auto", now);
|
|
425
|
+
}
|
|
426
|
+
catch (err) {
|
|
427
|
+
if (interrupted() || signal.aborted)
|
|
428
|
+
return;
|
|
429
|
+
throw err;
|
|
430
|
+
}
|
|
431
|
+
if (interrupted() || signal.aborted)
|
|
432
|
+
return;
|
|
433
|
+
// A summary asked for and not given is not asked for again before
|
|
434
|
+
// every turn after: the request goes as it is, and the endpoint says
|
|
435
|
+
// if it is too long. Nothing to cut yet costs nothing: looked at
|
|
436
|
+
// again next turn.
|
|
437
|
+
if (!done.ok && done.asked)
|
|
438
|
+
autoCompaction = false;
|
|
439
|
+
// A summary that could not bring the context under the line will
|
|
440
|
+
// not by summarising again before every turn.
|
|
441
|
+
if (done.ok && contextNow() > o.compaction.contextWindow - o.compaction.reserveTokens)
|
|
442
|
+
autoCompaction = false;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
294
445
|
let turn;
|
|
295
446
|
try {
|
|
296
447
|
const stream = modelTurn(o, messages, signal);
|
|
@@ -308,9 +459,21 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
308
459
|
// knows why and reports it. Anything else is the step's failure.
|
|
309
460
|
if (interrupted() || signal.aborted)
|
|
310
461
|
return;
|
|
462
|
+
// The endpoint said the prompt does not fit (a model with a smaller
|
|
463
|
+
// window than assumed): compact and ask again — once per request.
|
|
464
|
+
if (!overflowed && o.compaction !== false && messages.at(-1)?.role === "user" && isContextOverflow(err.status, err.message)) {
|
|
465
|
+
overflowed = true;
|
|
466
|
+
const done = yield* compactNow("overflow", contextNow());
|
|
467
|
+
if (interrupted() || signal.aborted)
|
|
468
|
+
return;
|
|
469
|
+
if (!done.ok)
|
|
470
|
+
throw new Error(`${err.message} — and the conversation could not be compacted: ${done.why}`);
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
311
473
|
throw err;
|
|
312
474
|
}
|
|
313
475
|
turns++;
|
|
476
|
+
overflowed = false;
|
|
314
477
|
for (const k of Object.keys(total))
|
|
315
478
|
total[k] += turn.usage[k];
|
|
316
479
|
const text = turn.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
|
|
@@ -322,7 +485,15 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
322
485
|
parent_tool_use_id: null,
|
|
323
486
|
session_id: sessionId,
|
|
324
487
|
};
|
|
325
|
-
|
|
488
|
+
// A paused turn's continuation is the same turn: joined to it, so the
|
|
489
|
+
// conversation still alternates (what foldrun code keeps, and a cut).
|
|
490
|
+
const prev = messages[messages.length - 1];
|
|
491
|
+
if (prev?.role === "assistant")
|
|
492
|
+
prev.content = [...prev.content, ...turn.content];
|
|
493
|
+
else
|
|
494
|
+
messages.push({ role: "assistant", content: turn.content });
|
|
495
|
+
// The turn's own count: all it was sent, and its reply.
|
|
496
|
+
measured = { tokens: turn.usage.input_tokens + turn.usage.cache_read_input_tokens + turn.usage.cache_creation_input_tokens + turn.usage.output_tokens, at: messages.length };
|
|
326
497
|
if (interrupted())
|
|
327
498
|
return;
|
|
328
499
|
const calls = turn.content.filter((b) => b.type === "tool_use");
|
|
@@ -357,6 +528,14 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
357
528
|
catch (err) {
|
|
358
529
|
outcome = { text: `${p.tool.name} failed: ${err.message}`, isError: true };
|
|
359
530
|
}
|
|
531
|
+
// For a summary's file lists: what ran, as the hooks left it, and did not fail.
|
|
532
|
+
const file = p.decision.input.file_path;
|
|
533
|
+
if (!outcome.isError && typeof file === "string") {
|
|
534
|
+
if (p.tool.name === "Read")
|
|
535
|
+
filesRead.add(file);
|
|
536
|
+
else if (p.tool.name === "Write" || p.tool.name === "Edit")
|
|
537
|
+
filesChanged.add(file);
|
|
538
|
+
}
|
|
360
539
|
const context = await after(o, p.tool.name, String(p.block.id), p.decision.input, outcome, sessionId, signal);
|
|
361
540
|
return { outcome, context };
|
|
362
541
|
};
|
|
@@ -383,12 +562,15 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
383
562
|
}
|
|
384
563
|
if (interrupted())
|
|
385
564
|
return;
|
|
386
|
-
const results = planned.map((p, i) =>
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
565
|
+
const results = planned.map((p, i) => {
|
|
566
|
+
const { text, isError, parts } = done[i].outcome;
|
|
567
|
+
// An image a tool returned (an MCP server's screenshot) goes to the
|
|
568
|
+
// model as an image, in its place among the text.
|
|
569
|
+
const content = parts
|
|
570
|
+
? parts.map((p) => p.type === "text" ? { type: "text", text: p.text } : { type: "image", source: { type: "base64", media_type: p.mediaType, data: p.data } })
|
|
571
|
+
: text;
|
|
572
|
+
return { type: "tool_result", tool_use_id: String(p.block.id), content, ...(isError ? { is_error: true } : {}) };
|
|
573
|
+
});
|
|
392
574
|
const context = done.flatMap((d) => d.context);
|
|
393
575
|
const content = [...results, ...context.map((c) => ({ type: "text", text: c }))];
|
|
394
576
|
messages.push({ role: "user", content });
|
|
@@ -397,8 +579,10 @@ async function* run(prompt, o, signal, interrupted) {
|
|
|
397
579
|
}
|
|
398
580
|
finally {
|
|
399
581
|
// However the loop ended — an answer, a stop, a consumer that walked
|
|
400
|
-
// away — nothing a command started outlives the step
|
|
582
|
+
// away — nothing a command started outlives the step, and no MCP server
|
|
583
|
+
// it started either.
|
|
401
584
|
killGroups(ctx);
|
|
585
|
+
await mcp?.close();
|
|
402
586
|
}
|
|
403
587
|
}
|
|
404
588
|
/** The foldrun engine, as executeStep's model loop. */
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
2
|
+
import type { EngineTool, ToolOutcome } from "./engine-tools.ts";
|
|
3
|
+
type Json = Record<string, unknown>;
|
|
4
|
+
/** The server a granted name belongs to: `mcp__<server>`, `mcp__<server>__*`
|
|
5
|
+
* (the runner grants a whole server so) or `mcp__<server>__<tool>`. Matched
|
|
6
|
+
* against the step's own server names, the longest first, so a server named
|
|
7
|
+
* `sales__eu` is not read as `sales`. */
|
|
8
|
+
export declare function grantedServer(name: string, servers: string[]): {
|
|
9
|
+
server: string;
|
|
10
|
+
tool: string | null;
|
|
11
|
+
} | null;
|
|
12
|
+
/** A server as the SDK's `mcpServers` option holds it. */
|
|
13
|
+
export interface McpSpec {
|
|
14
|
+
type?: string;
|
|
15
|
+
name?: string;
|
|
16
|
+
instance?: {
|
|
17
|
+
connect(t: Transport): Promise<void>;
|
|
18
|
+
};
|
|
19
|
+
command?: string;
|
|
20
|
+
args?: string[];
|
|
21
|
+
env?: Record<string, string>;
|
|
22
|
+
url?: string;
|
|
23
|
+
headers?: Record<string, string>;
|
|
24
|
+
/** Milliseconds one call may take; below 1000 is ignored, as in the SDK. */
|
|
25
|
+
timeout?: number;
|
|
26
|
+
/** The SDK's per-tool permission policy — refused here (checkMcpSpecs). */
|
|
27
|
+
tools?: unknown;
|
|
28
|
+
}
|
|
29
|
+
/** Refused before a model call is paid for: a server this loop cannot connect. */
|
|
30
|
+
export declare function checkMcpSpecs(servers: Record<string, unknown>, engine: string): Record<string, McpSpec>;
|
|
31
|
+
export interface McpConnection {
|
|
32
|
+
tools: EngineTool[];
|
|
33
|
+
/** Which server offered each tool, by its full name. */
|
|
34
|
+
owner: Map<string, string>;
|
|
35
|
+
/** What each server told its client to tell the model (MCP `instructions`),
|
|
36
|
+
* which the SDK put in the system prompt; so does the loop. */
|
|
37
|
+
instructions: {
|
|
38
|
+
server: string;
|
|
39
|
+
text: string;
|
|
40
|
+
}[];
|
|
41
|
+
servers: {
|
|
42
|
+
name: string;
|
|
43
|
+
status: "connected";
|
|
44
|
+
}[];
|
|
45
|
+
close(): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
/** A call's result as the loop hands it on: its text and images in the
|
|
48
|
+
* order the server gave them (a caption stays beside its picture), the text
|
|
49
|
+
* cut to a size, marked an error when the server says it is one. */
|
|
50
|
+
export declare function outcomeOf(result: Json): ToolOutcome;
|
|
51
|
+
/** Connect every server and list its tools. All or none: one that fails
|
|
52
|
+
* closes the rest and refuses the step, naming it. */
|
|
53
|
+
/** `env` is the step's options' environment (where MCP_TOOL_TIMEOUT is
|
|
54
|
+
* read, as the SDK read it); `toolEnv` is what a tool's process starts
|
|
55
|
+
* from — the loop's shellEnv, which a caller keeps apart from the model's
|
|
56
|
+
* credentials. */
|
|
57
|
+
export declare function connectMcp(servers: Record<string, McpSpec>, ctx: {
|
|
58
|
+
env: Record<string, string | undefined>;
|
|
59
|
+
toolEnv: Record<string, string | undefined>;
|
|
60
|
+
cwd: string;
|
|
61
|
+
signal: AbortSignal;
|
|
62
|
+
}): Promise<McpConnection>;
|
|
63
|
+
export {};
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// MCP servers on foldrun's own loop (FOL-213): every tool beyond the six
|
|
2
|
+
// file and shell tools reaches a step as an MCP server — foldrun's own, made
|
|
3
|
+
// in this process (createSdkMcpServer: `foldrun_scripts` with `web` search,
|
|
4
|
+
// fetch and browse; agents, apis, a2a, install, ask, peers, history), and an
|
|
5
|
+
// agent's own `mcpServers:` (stdio, http, sse). The SDK connected them inside
|
|
6
|
+
// the Claude Code binary; this connects them here, so the loop offers the
|
|
7
|
+
// same tools under the same names.
|
|
8
|
+
//
|
|
9
|
+
// What stays where it was:
|
|
10
|
+
// - the tools run where they always ran — the browser pod, the egress
|
|
11
|
+
// proxy and its search door, the vault's site-bound secrets are behind
|
|
12
|
+
// the server, not in this file;
|
|
13
|
+
// - each tool is offered as `mcp__<server>__<tool>`, the SDK's name, so
|
|
14
|
+
// step-exec's grant (`mcpNames`), limits, hooks and the run record read
|
|
15
|
+
// it as before, and every call goes through the loop's permission order
|
|
16
|
+
// (engine-common.ts decide/after);
|
|
17
|
+
// - a server that does not connect refuses the step by name. The SDK went
|
|
18
|
+
// on without its tools; a step that runs without a tool it was given is
|
|
19
|
+
// the failure this engine refuses to have.
|
|
20
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
21
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
22
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
23
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
24
|
+
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
25
|
+
/** The server a granted name belongs to: `mcp__<server>`, `mcp__<server>__*`
|
|
26
|
+
* (the runner grants a whole server so) or `mcp__<server>__<tool>`. Matched
|
|
27
|
+
* against the step's own server names, the longest first, so a server named
|
|
28
|
+
* `sales__eu` is not read as `sales`. */
|
|
29
|
+
export function grantedServer(name, servers) {
|
|
30
|
+
for (const s of [...servers].sort((a, b) => b.length - a.length)) {
|
|
31
|
+
const head = `mcp__${s}`;
|
|
32
|
+
if (name === head || name === `${head}__*`)
|
|
33
|
+
return { server: s, tool: null };
|
|
34
|
+
if (name.startsWith(`${head}__`) && name.length > head.length + 2)
|
|
35
|
+
return { server: s, tool: name };
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
/** Longest a call may run when its server names no timeout: the step's own
|
|
40
|
+
* timeout ends it sooner (the loop's signal). */
|
|
41
|
+
const DEFAULT_CALL_MS = 24 * 60 * 60 * 1000;
|
|
42
|
+
/** The longest a timer holds (2^31 − 1 ms, ~24.8 days); past it Node fires at once. */
|
|
43
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
44
|
+
const CONNECT_MS = 60_000;
|
|
45
|
+
/** The most text one call hands the model; the rest is said to be cut. */
|
|
46
|
+
const MAX_TEXT = 100_000;
|
|
47
|
+
const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
48
|
+
/** Refused before a model call is paid for: a server this loop cannot connect. */
|
|
49
|
+
export function checkMcpSpecs(servers, engine) {
|
|
50
|
+
// No prototype: a server named __proto__ is a server, not a prototype.
|
|
51
|
+
const out = Object.create(null);
|
|
52
|
+
for (const [name, raw] of Object.entries(servers)) {
|
|
53
|
+
const s = (raw ?? {});
|
|
54
|
+
const type = s.type ?? "stdio";
|
|
55
|
+
const ok = (type === "sdk" && typeof s.instance?.connect === "function") ||
|
|
56
|
+
(type === "stdio" && typeof s.command === "string" && !!s.command) ||
|
|
57
|
+
((type === "http" || type === "sse") && typeof s.url === "string" && !!s.url);
|
|
58
|
+
if (!ok)
|
|
59
|
+
throw new Error(`the ${engine} engine cannot connect the MCP server ${name} (type ${type}) — run this agent on the default engine.`);
|
|
60
|
+
if (!/^[A-Za-z0-9_-]+$/.test(name))
|
|
61
|
+
throw new Error(`the MCP server name ${name} has characters a tool name cannot hold (letters, digits, _ and -)`);
|
|
62
|
+
// The SDK honours a per-tool always_deny / always_ask; this loop would
|
|
63
|
+
// offer such a tool like any other, so it refuses the spec instead.
|
|
64
|
+
if (Array.isArray(s.tools) && s.tools.length)
|
|
65
|
+
throw new Error(`the ${engine} engine does not apply per-tool permission policies (MCP server ${name}) — run this agent on the default engine.`);
|
|
66
|
+
out[name] = { ...s, type };
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function transportFor(s, env, cwd) {
|
|
71
|
+
if (s.type === "sdk") {
|
|
72
|
+
const [client, server] = InMemoryTransport.createLinkedPair();
|
|
73
|
+
return { client, server };
|
|
74
|
+
}
|
|
75
|
+
if (s.type === "stdio") {
|
|
76
|
+
// The step's environment, as the SDK gave it: already the allowlisted
|
|
77
|
+
// one (host-env.ts: the clock, the proxy that is the way out, declared
|
|
78
|
+
// secrets), never this process's. Then what the spec names. The MCP
|
|
79
|
+
// library adds PATH, HOME, SHELL, TERM, USER and LOGNAME from this
|
|
80
|
+
// process where the step has none: names a program needs, no secrets.
|
|
81
|
+
const base = {};
|
|
82
|
+
for (const [k, v] of Object.entries(env))
|
|
83
|
+
if (typeof v === "string")
|
|
84
|
+
base[k] = v;
|
|
85
|
+
return { client: new StdioClientTransport({ command: s.command, args: s.args ?? [], env: { ...base, ...(s.env ?? {}) }, cwd, stderr: "ignore" }) };
|
|
86
|
+
}
|
|
87
|
+
const url = new URL(s.url);
|
|
88
|
+
const requestInit = { headers: s.headers ?? {} };
|
|
89
|
+
// SSE is the older MCP transport (deprecated in the SDK); still accepted,
|
|
90
|
+
// because an agent may name a server that has nothing newer.
|
|
91
|
+
return { client: s.type === "sse" ? new SSEClientTransport(url, { requestInit }) : new StreamableHTTPClientTransport(url, { requestInit }) };
|
|
92
|
+
}
|
|
93
|
+
/** A call's result as the loop hands it on: its text and images in the
|
|
94
|
+
* order the server gave them (a caption stays beside its picture), the text
|
|
95
|
+
* cut to a size, marked an error when the server says it is one. */
|
|
96
|
+
export function outcomeOf(result) {
|
|
97
|
+
const parts = [];
|
|
98
|
+
const add = (text) => parts.push({ type: "text", text });
|
|
99
|
+
for (const c of (Array.isArray(result.content) ? result.content : [])) {
|
|
100
|
+
if (c.type === "text" && typeof c.text === "string")
|
|
101
|
+
add(c.text);
|
|
102
|
+
else if (c.type === "image" && typeof c.data === "string" && typeof c.mimeType === "string")
|
|
103
|
+
parts.push({ type: "image", data: c.data, mediaType: c.mimeType });
|
|
104
|
+
else if (c.type === "resource") {
|
|
105
|
+
const r = (c.resource ?? {});
|
|
106
|
+
add(typeof r.text === "string" ? r.text : `[resource ${String(r.uri ?? "")}${r.mimeType ? ` (${String(r.mimeType)})` : ""}]`);
|
|
107
|
+
}
|
|
108
|
+
else if (c.type === "resource_link")
|
|
109
|
+
add(`[resource ${String(c.uri ?? "")}]`);
|
|
110
|
+
else if (c.type === "audio")
|
|
111
|
+
add("[audio — not shown]");
|
|
112
|
+
}
|
|
113
|
+
if (!parts.some((p) => p.type === "text") && result.structuredContent !== undefined)
|
|
114
|
+
add(JSON.stringify(result.structuredContent));
|
|
115
|
+
if (!parts.length && "toolResult" in result)
|
|
116
|
+
add(typeof result.toolResult === "string" ? result.toolResult : JSON.stringify(result.toolResult));
|
|
117
|
+
// One budget across every text part, in order, the newline between two
|
|
118
|
+
// counted; a part past it is dropped, not kept empty.
|
|
119
|
+
let left = MAX_TEXT;
|
|
120
|
+
let cut = 0;
|
|
121
|
+
const kept = [];
|
|
122
|
+
let any = false;
|
|
123
|
+
for (const p of parts) {
|
|
124
|
+
if (p.type !== "text") {
|
|
125
|
+
kept.push(p);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const sep = any ? 1 : 0;
|
|
129
|
+
const room = left - sep;
|
|
130
|
+
// An empty part still fits when only its newline does.
|
|
131
|
+
if (room < 0 || (room === 0 && p.text.length > 0)) {
|
|
132
|
+
cut += p.text.length;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (p.text.length > room) {
|
|
136
|
+
let end = room;
|
|
137
|
+
// Never half a character: a cut between a surrogate pair drops both.
|
|
138
|
+
if (/[\uD800-\uDBFF]/.test(p.text[end - 1] ?? ""))
|
|
139
|
+
end--;
|
|
140
|
+
cut += p.text.length - end;
|
|
141
|
+
p.text = p.text.slice(0, end);
|
|
142
|
+
}
|
|
143
|
+
left -= p.text.length + sep;
|
|
144
|
+
any = true;
|
|
145
|
+
kept.push(p);
|
|
146
|
+
}
|
|
147
|
+
parts.length = 0;
|
|
148
|
+
parts.push(...kept);
|
|
149
|
+
if (cut)
|
|
150
|
+
add(`[cut: ${cut} more characters]`);
|
|
151
|
+
const texts = parts.filter((p) => p.type === "text");
|
|
152
|
+
const text = texts.map((p) => p.text).join("\n");
|
|
153
|
+
const hasImage = parts.some((p) => p.type === "image");
|
|
154
|
+
return { text, isError: result.isError === true, ...(hasImage ? { parts } : {}) };
|
|
155
|
+
}
|
|
156
|
+
/** A promise held to a time and a signal — the MCP client waits for a
|
|
157
|
+
* transport to start before its own timeout begins (an SSE server that
|
|
158
|
+
* never sends its endpoint would hold the step open forever). */
|
|
159
|
+
function bounded(work, ms, signal, what) {
|
|
160
|
+
return new Promise((resolve, reject) => {
|
|
161
|
+
const done = () => { clearTimeout(timer); signal.removeEventListener("abort", onAbort); };
|
|
162
|
+
const onAbort = () => { done(); reject(new Error(`${what}: stopped`)); };
|
|
163
|
+
const timer = setTimeout(() => { done(); reject(new Error(`${what}: no answer in ${Math.round(ms / 1000)} s`)); }, ms);
|
|
164
|
+
// Handled first, so the work failing after a stop is never unhandled.
|
|
165
|
+
work.then((v) => { done(); resolve(v); }, (e) => { done(); reject(e); });
|
|
166
|
+
if (signal.aborted)
|
|
167
|
+
return onAbort();
|
|
168
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/** Connect every server and list its tools. All or none: one that fails
|
|
172
|
+
* closes the rest and refuses the step, naming it. */
|
|
173
|
+
/** `env` is the step's options' environment (where MCP_TOOL_TIMEOUT is
|
|
174
|
+
* read, as the SDK read it); `toolEnv` is what a tool's process starts
|
|
175
|
+
* from — the loop's shellEnv, which a caller keeps apart from the model's
|
|
176
|
+
* credentials. */
|
|
177
|
+
export async function connectMcp(servers, ctx) {
|
|
178
|
+
const open = [];
|
|
179
|
+
const close = async () => {
|
|
180
|
+
await Promise.all(open.map(async (o) => {
|
|
181
|
+
// A streamable HTTP server that gave a session is told it is over
|
|
182
|
+
// (DELETE), so it is not left holding one; then the local side closes.
|
|
183
|
+
if (o.transport instanceof StreamableHTTPClientTransport && o.transport.sessionId) {
|
|
184
|
+
await bounded(o.transport.terminateSession(), 5_000, new AbortController().signal, "end session").catch(() => undefined);
|
|
185
|
+
}
|
|
186
|
+
await o.client.close().catch(() => undefined);
|
|
187
|
+
await o.server?.close().catch(() => undefined);
|
|
188
|
+
}));
|
|
189
|
+
};
|
|
190
|
+
const tools = [];
|
|
191
|
+
const owner = new Map();
|
|
192
|
+
const instructions = [];
|
|
193
|
+
const envTimeout = Number(ctx.env.MCP_TOOL_TIMEOUT);
|
|
194
|
+
try {
|
|
195
|
+
for (const [name, s] of Object.entries(servers)) {
|
|
196
|
+
const t = transportFor(s, ctx.toolEnv, ctx.cwd);
|
|
197
|
+
const client = new Client({ name: "foldrun-engine", version: "1.0.0" });
|
|
198
|
+
open.push({ client, transport: t.client, server: t.server });
|
|
199
|
+
let listed;
|
|
200
|
+
if (ctx.signal.aborted)
|
|
201
|
+
throw new Error(`the MCP server ${name} did not start: connect: stopped`);
|
|
202
|
+
try {
|
|
203
|
+
const started = (async () => {
|
|
204
|
+
if (t.server)
|
|
205
|
+
await s.instance.connect(t.server);
|
|
206
|
+
await client.connect(t.client, { timeout: CONNECT_MS, signal: ctx.signal });
|
|
207
|
+
const found = [];
|
|
208
|
+
// A server that offers no tools says so in its capabilities.
|
|
209
|
+
if (!client.getServerCapabilities()?.tools)
|
|
210
|
+
return found;
|
|
211
|
+
let cursor;
|
|
212
|
+
do {
|
|
213
|
+
let page;
|
|
214
|
+
try {
|
|
215
|
+
page = await client.listTools(cursor ? { cursor } : undefined, { timeout: CONNECT_MS, signal: ctx.signal });
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
// Some say they have tools and answer tools/list with "method
|
|
219
|
+
// not found" when they have none (the Agent SDK's in-process
|
|
220
|
+
// server with an empty list): no tools, not a failed start.
|
|
221
|
+
if (err.code === -32601 && !cursor)
|
|
222
|
+
return found;
|
|
223
|
+
throw err;
|
|
224
|
+
}
|
|
225
|
+
found.push(...page.tools);
|
|
226
|
+
cursor = page.nextCursor;
|
|
227
|
+
} while (cursor);
|
|
228
|
+
// Each page replaced the client's output-schema checks with its
|
|
229
|
+
// own: give it every page's, so a tool on page one is still checked.
|
|
230
|
+
client.cacheToolMetadata?.(found);
|
|
231
|
+
return found;
|
|
232
|
+
})();
|
|
233
|
+
listed = await bounded(started, CONNECT_MS, ctx.signal, "connect");
|
|
234
|
+
}
|
|
235
|
+
catch (err) {
|
|
236
|
+
throw new Error(`the MCP server ${name} did not start: ${err.message}`);
|
|
237
|
+
}
|
|
238
|
+
// The server's own timeout, else MCP_TOOL_TIMEOUT, as the SDK read them.
|
|
239
|
+
const told = client.getInstructions();
|
|
240
|
+
if (typeof told === "string" && told.trim())
|
|
241
|
+
instructions.push({ server: name, text: told.trim() });
|
|
242
|
+
const timeout = Math.min(MAX_TIMER_MS, typeof s.timeout === "number" && s.timeout >= 1000 ? s.timeout : envTimeout >= 1000 ? envTimeout : DEFAULT_CALL_MS);
|
|
243
|
+
for (const tool of listed) {
|
|
244
|
+
const full = `mcp__${name}__${tool.name}`;
|
|
245
|
+
if (!TOOL_NAME.test(full))
|
|
246
|
+
throw new Error(`the MCP server ${name} offers a tool whose full name ${full} is not one a model accepts (at most 64 letters, digits, _ and -)`);
|
|
247
|
+
if (owner.has(full))
|
|
248
|
+
throw new Error(`two MCP servers offer a tool named ${full} (${owner.get(full)} and ${name})`);
|
|
249
|
+
// A name that reads as another server's (sales offering eu__find
|
|
250
|
+
// beside a server sales__eu) would be granted by the wrong server:
|
|
251
|
+
// the step is refused rather than guess.
|
|
252
|
+
const readAs = grantedServer(full, Object.keys(servers));
|
|
253
|
+
if (readAs?.server !== name)
|
|
254
|
+
throw new Error(`the MCP tool ${full} from ${name} reads as server ${readAs?.server ?? "none"}'s — rename the server or the tool`);
|
|
255
|
+
owner.set(full, name);
|
|
256
|
+
tools.push({
|
|
257
|
+
name: full,
|
|
258
|
+
description: tool.description ?? "",
|
|
259
|
+
input_schema: tool.inputSchema ?? { type: "object" },
|
|
260
|
+
// Run beside other reads only when the server says it changes nothing.
|
|
261
|
+
readOnly: tool.annotations?.readOnlyHint === true,
|
|
262
|
+
run: async (input, toolCtx) => {
|
|
263
|
+
const result = await client.callTool({ name: tool.name, arguments: input }, undefined, { signal: toolCtx.signal, timeout, maxTotalTimeout: timeout });
|
|
264
|
+
return outcomeOf(result);
|
|
265
|
+
},
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
catch (err) {
|
|
271
|
+
await close();
|
|
272
|
+
throw err;
|
|
273
|
+
}
|
|
274
|
+
return { tools, owner, instructions, servers: Object.keys(servers).map((name) => ({ name, status: "connected" })), close };
|
|
275
|
+
}
|
|
@@ -17,6 +17,17 @@ export declare function killGroups(ctx: ToolContext): void;
|
|
|
17
17
|
export interface ToolOutcome {
|
|
18
18
|
text: string;
|
|
19
19
|
isError?: boolean;
|
|
20
|
+
/** When the tool returned images (an MCP server's screenshot): its text and
|
|
21
|
+
* images in their order, sent to the model so. `text` is still the whole
|
|
22
|
+
* text, for the record and the hooks. */
|
|
23
|
+
parts?: ({
|
|
24
|
+
type: "text";
|
|
25
|
+
text: string;
|
|
26
|
+
} | {
|
|
27
|
+
type: "image";
|
|
28
|
+
data: string;
|
|
29
|
+
mediaType: string;
|
|
30
|
+
})[];
|
|
20
31
|
}
|
|
21
32
|
export interface EngineTool {
|
|
22
33
|
name: string;
|