@parcha/agentrun-serve 0.1.0-beta.30 → 0.1.0-beta.31

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.
Files changed (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +182 -26
  3. package/dist/agents.d.ts +8 -3
  4. package/dist/agents.js +4 -1
  5. package/dist/app.js +23 -8
  6. package/dist/background.d.ts +2 -1
  7. package/dist/background.js +41 -20
  8. package/dist/box-egress-vm.d.ts +125 -0
  9. package/dist/box-egress-vm.js +350 -0
  10. package/dist/box-egress.d.ts +3 -2
  11. package/dist/box-relay-vm.d.ts +4 -0
  12. package/dist/box-relay-vm.js +76 -55
  13. package/dist/boxes.d.ts +7 -2
  14. package/dist/boxes.js +30 -11
  15. package/dist/cap.d.ts +2 -1
  16. package/dist/cap.js +2 -1
  17. package/dist/cli.js +30 -4
  18. package/dist/console/assets/{index-34jfpIbQ.js → index-CnJBf7Lc.js} +90 -85
  19. package/dist/console/index.html +1 -1
  20. package/dist/decisions.d.ts +3 -3
  21. package/dist/decisions.js +4 -3
  22. package/dist/files.d.ts +3 -0
  23. package/dist/files.js +3 -0
  24. package/dist/grade.d.ts +5 -2
  25. package/dist/grade.js +13 -5
  26. package/dist/harness-app.js +10 -1
  27. package/dist/host-check.d.ts +12 -0
  28. package/dist/host-check.js +34 -0
  29. package/dist/key-words.d.ts +37 -0
  30. package/dist/key-words.js +40 -0
  31. package/dist/learn/grade.d.ts +3 -0
  32. package/dist/learn/grade.js +3 -1
  33. package/dist/learn/index.d.ts +1 -1
  34. package/dist/learn/index.js +1 -1
  35. package/dist/learn/reflect.js +2 -0
  36. package/dist/learn/skills.d.ts +2 -0
  37. package/dist/learn/skills.js +16 -0
  38. package/dist/learning-routes.d.ts +30 -1
  39. package/dist/learning-routes.js +173 -19
  40. package/dist/learning-run.d.ts +1 -1
  41. package/dist/learning-run.js +25 -4
  42. package/dist/learning-words.d.ts +7 -3
  43. package/dist/learning-words.js +26 -8
  44. package/dist/learning.d.ts +9 -1
  45. package/dist/learning.js +57 -2
  46. package/dist/mcp-gateway.d.ts +96 -0
  47. package/dist/mcp-gateway.js +408 -0
  48. package/dist/mcp-meta.d.ts +17 -0
  49. package/dist/mcp-meta.js +38 -0
  50. package/dist/mcp-servers.d.ts +26 -5
  51. package/dist/mcp-servers.js +53 -10
  52. package/dist/openapi.js +52 -9
  53. package/dist/page.d.ts +2 -0
  54. package/dist/page.js +3 -0
  55. package/dist/place.d.ts +3 -2
  56. package/dist/place.js +11 -3
  57. package/dist/print.d.ts +7 -0
  58. package/dist/print.js +13 -0
  59. package/dist/run-box.js +15 -5
  60. package/dist/runnable.d.ts +8 -1
  61. package/dist/runnable.js +51 -2
  62. package/dist/runs.d.ts +15 -8
  63. package/dist/runs.js +66 -13
  64. package/dist/secrets.d.ts +15 -0
  65. package/dist/secrets.js +20 -2
  66. package/dist/server.d.ts +10 -1
  67. package/dist/server.js +111 -29
  68. package/dist/tool-gate.d.ts +18 -3
  69. package/dist/tool-gate.js +44 -13
  70. package/dist/tool-keys.d.ts +2 -1
  71. package/dist/tool-keys.js +4 -8
  72. package/dist/tool-plane.d.ts +5 -1
  73. package/dist/tool-plane.js +30 -6
  74. package/dist/tools.js +8 -5
  75. package/dist/web-fetch.js +3 -3
  76. package/package.json +12 -16
@@ -0,0 +1,96 @@
1
+ import { type ToolRegistration } from "@earendil-works/pi-durable";
2
+ import type { McpCallResult, McpTool, SessionMcp } from "@parcha/agentrun-kernel";
3
+ import { type Gate, type Park } from "./tool-gate.js";
4
+ /** The run's pinned MCP tools, in its directory: written once, at its first launch. */
5
+ export declare const MCP_PIN = "mcp-tools.json";
6
+ /** A catalog name of an MCP tool: `mcp:<server>/<tool>`. A server name has no `_`, so `mcp__<server>__<tool>` splits one way. */
7
+ export declare const MCP_NAME: RegExp;
8
+ /** The longest answer the model reads whole; the rest is filed in the run's work/ (monid's rule). */
9
+ export declare const MCP_CLIP = 60000;
10
+ /** The most of one upstream answer read. */
11
+ export declare const MAX_RESPONSE: number;
12
+ /** The longest one upstream call may take, and its first connection. */
13
+ export declare const CALL_MS = 120000;
14
+ export declare const CONNECT_MS = 30000;
15
+ /** Each pinned server: its URL then, the granted tools as it listed them, and the prices its owner declared for them. */
16
+ export type McpPin = Record<string, {
17
+ url: string;
18
+ tools: McpTool[];
19
+ prices?: Record<string, number>;
20
+ }>;
21
+ /** The pipe's entry: each granted server's URL now, and its credential's headers when that URL is the pinned one. */
22
+ export type McpCredentials = Record<string, {
23
+ url: string;
24
+ headers?: Record<string, string>;
25
+ }>;
26
+ /** The servers saved on this server (mcp-servers.ts), as a launch reads them. */
27
+ export interface McpServerSource {
28
+ server(name: string): {
29
+ url: string;
30
+ tools: readonly McpTool[];
31
+ prices?: Readonly<Record<string, number>>;
32
+ } | undefined;
33
+ /** The server's credential, opened now: its headers, or undefined when it has none or it does not open. */
34
+ headers(name: string): Record<string, string> | undefined;
35
+ }
36
+ /** `mcp:<server>/<tool>` read, or undefined for a name that is not one. */
37
+ export declare const mcpNameOf: (name: string) => {
38
+ server: string;
39
+ tool: string;
40
+ } | undefined;
41
+ /** The most schema nodes, and the deepest nesting, a tool's declarations are checked through: past either the tool is
42
+ * refused, never walked further. */
43
+ export declare const HEADER_SCAN_NODES = 10000;
44
+ export declare const HEADER_SCAN_DEPTH = 64;
45
+ /** Why a tool's `x-mcp-header` declarations (SEP-2243, the 2026-07-28 revision) cannot be mirrored into `Mcp-Param-*`
46
+ * headers, by the rules the SDK client applies when it lists tools: only on a property reached through `properties`
47
+ * alone, a non-empty RFC 9110 token, on a string, integer or boolean, unique without regard to case. Undefined when they
48
+ * can, or there are none. The SDK does the mirroring itself (callTool's `toolDefinition`), but it exports no form of this
49
+ * check, which it runs only inside its own `listTools()`. Each object is visited once, from an explicit stack, within
50
+ * HEADER_SCAN_NODES and HEADER_SCAN_DEPTH. */
51
+ export declare function mcpHeaderProblem(inputSchema: unknown): string | undefined;
52
+ /** The pin of a run granted `names`: each MCP tool among them, as its server's snapshot holds it. Keyed by server name
53
+ * with no prototype, as every map of names here is: a server named `constructor` is a server like any other. A granted
54
+ * tool that cannot be pinned (its server no longer saved, the tool gone since a refresh, a header declaration it cannot
55
+ * send) throws, naming it and why: the run is refused, never started without it. */
56
+ export declare function mcpPinOf(names: readonly string[], source: McpServerSource): McpPin;
57
+ /** What a launch hands the run for its pin: each pinned server's URL now, with its headers only when it has not moved. A
58
+ * server no longer saved is absent. */
59
+ export declare function mcpCredentialsOf(pin: McpPin, source: McpServerSource): McpCredentials;
60
+ export interface McpGatewayOptions {
61
+ pin: McpPin;
62
+ credentials: McpCredentials;
63
+ /** The run's work/, where an answer too long for the model is filed. */
64
+ work: () => string;
65
+ /** For tests: the fetch the upstream client sends with. */
66
+ fetch?: typeof fetch;
67
+ /** For tests: the bound on one call (CALL_MS) and on a server's first connection (CONNECT_MS). */
68
+ bounds?: {
69
+ callMs?: number;
70
+ connectMs?: number;
71
+ };
72
+ /** The run's tool gate, which every run's process passes (app.ts): each call enters it here, the only place an MCP
73
+ * call is gated (pi's wrapper and the harnesses' hooks leave MCP calls to it). Only a test omits it, and then every
74
+ * call is let go. Its `executor` and `spill`, where it has them, run an approved call and pass a result through. */
75
+ gate?: Pick<Gate, "enter"> & Partial<Pick<Gate, "executor" | "spill">>;
76
+ /** The run's commit to its store, once it is open: a parked call's request, a priced call's mark and charge, and an
77
+ * unpriced call's "not metered" are written on its root. None: a priced call is refused unsent, as a paid call with
78
+ * nowhere to book it is (paid-calls.ts). */
79
+ commit?: () => Park["commit"] | undefined;
80
+ }
81
+ /** The gateway: a session's servers, and a call that takes the gate's `park` of the harness it came from (its journal's
82
+ * commit, and how it ends a parked call's turn); none, the run's root commit. */
83
+ export type McpGateway = Omit<SessionMcp, "call"> & {
84
+ call(server: string, tool: string, args: Record<string, unknown>, context: {
85
+ signal: AbortSignal;
86
+ callId?: string;
87
+ park?: Park;
88
+ }): Promise<McpCallResult>;
89
+ };
90
+ export declare function mcpGateway(options: McpGatewayOptions): McpGateway;
91
+ /** Whether the gateway's answer is a call the gate parked for a person's approval: the harness ends the turn on it. A
92
+ * symbol, so it never reaches a harness's MCP client in the answer's JSON. */
93
+ export declare const isParked: (result: McpCallResult) => boolean;
94
+ /** pi's tools for the gateway's servers: each granted tool under its wire name (`mcp__<server>__<tool>`), with the pinned
95
+ * description and schema, never run again after a crash. */
96
+ export declare function mcpRegistrations(gateway: McpGateway): ToolRegistration[];
@@ -0,0 +1,408 @@
1
+ // A run's remote MCP servers, in the run's process: the one place every harness's MCP call goes through. pi calls it
2
+ // in-process, as the tools it binds for each granted `mcp:<server>/<tool>` (mcpRegistrations); a harness with its own
3
+ // MCP client calls it through the session proxy's /mcp/<server> (@parcha/agentrun-kernel/host mcpRoute).
4
+ // - What a run may call is pinned at its first launch (runs.ts writes MCP_PIN in the run's directory): each granted
5
+ // tool as the server listed it when its owner saved it, and the server's URL then. A later refresh of the server
6
+ // never changes a running agent's tools.
7
+ // - Its credentials come over the run's secrets pipe (secrets.ts mcpCredentials), only for the servers it grants, with
8
+ // each server's URL now: one whose URL is not the pinned one is never sent anything, and the credential the pipe
9
+ // holds for a moved server is none.
10
+ // - One upstream client per server (the official SDK), connected at its first call; no redirect is followed, so a
11
+ // credential goes nowhere but the pinned URL, and an answer past MAX_RESPONSE is cut off.
12
+ // - A call is never sent twice: each harness records its intent before it reaches here (pi-durable's tool intent,
13
+ // Claude's PreToolUse), and one a crash cut off is answered interrupted there. An aborted call aborts upstream.
14
+ // - Every failure is a result the model reads, naming the server and never a header.
15
+ // - Every call passes the run's tool gate first (tool-gate.ts), as `mcp:<server>/<tool>`: a denied one is refused, and
16
+ // one set to ask is parked: its answer is the gate's waiting text, marked parked (isParked), and the harness ends the
17
+ // turn, as for any tool. Nothing is sent. Once a person allows it, the gate runs it through the executor this gateway
18
+ // registers (`mcp:`), once, and resumes the session with its result.
19
+ // - A tool its owner priced (the server's `prices`) is held at that price under the run's cap and booked as the run's
20
+ // tool cost, as any paid call (cap.ts paidCall): refused unsent when the cap cannot take it. A tool with no price runs,
21
+ // marked "not metered" on the run's root (TOOL_UNMETERED), outside the run's cost.
22
+ import { randomUUID } from "node:crypto";
23
+ import { lstat } from "node:fs/promises";
24
+ import { join } from "node:path";
25
+ import { defineTool, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
26
+ import { TOOL_COST, TOOL_STARTED, TOOL_UNMETERED } from "@parcha/pi-durable-agent/timeline";
27
+ import { paidCall } from "./cap.js";
28
+ import { wireName } from "./catalog.js";
29
+ import { metaToolOf } from "./mcp-meta.js";
30
+ import { GATED_BY_GATEWAY, mcpToolName } from "./tool-gate.js";
31
+ import { forModel } from "./result.js";
32
+ import { writeInWork } from "./workspace.js";
33
+ /** The run's pinned MCP tools, in its directory: written once, at its first launch. */
34
+ export const MCP_PIN = "mcp-tools.json";
35
+ /** A catalog name of an MCP tool: `mcp:<server>/<tool>`. A server name has no `_`, so `mcp__<server>__<tool>` splits one way. */
36
+ export const MCP_NAME = /^mcp:([a-z][a-z0-9-]{0,31})\/([A-Za-z0-9_-]{1,64})$/;
37
+ /** The longest answer the model reads whole; the rest is filed in the run's work/ (monid's rule). */
38
+ export const MCP_CLIP = 60_000;
39
+ /** The most of one upstream answer read. */
40
+ export const MAX_RESPONSE = 4 * 1024 * 1024;
41
+ /** The longest one upstream call may take, and its first connection. */
42
+ export const CALL_MS = 120_000;
43
+ export const CONNECT_MS = 30_000;
44
+ /** `mcp:<server>/<tool>` read, or undefined for a name that is not one. */
45
+ export const mcpNameOf = (name) => {
46
+ const match = MCP_NAME.exec(name);
47
+ return match ? { server: match[1], tool: match[2] } : undefined;
48
+ };
49
+ /** The most schema nodes, and the deepest nesting, a tool's declarations are checked through: past either the tool is
50
+ * refused, never walked further. */
51
+ export const HEADER_SCAN_NODES = 10_000;
52
+ export const HEADER_SCAN_DEPTH = 64;
53
+ /** Why a tool's `x-mcp-header` declarations (SEP-2243, the 2026-07-28 revision) cannot be mirrored into `Mcp-Param-*`
54
+ * headers, by the rules the SDK client applies when it lists tools: only on a property reached through `properties`
55
+ * alone, a non-empty RFC 9110 token, on a string, integer or boolean, unique without regard to case. Undefined when they
56
+ * can, or there are none. The SDK does the mirroring itself (callTool's `toolDefinition`), but it exports no form of this
57
+ * check, which it runs only inside its own `listTools()`. Each object is visited once, from an explicit stack, within
58
+ * HEADER_SCAN_NODES and HEADER_SCAN_DEPTH. */
59
+ export function mcpHeaderProblem(inputSchema) {
60
+ const seen = new Map();
61
+ const visited = new WeakSet();
62
+ const stack = [{ node: inputSchema, path: [], reachable: true }];
63
+ for (let nodes = 0; stack.length;) {
64
+ const { node, path, reachable } = stack.pop();
65
+ if (!node || typeof node !== "object" || visited.has(node))
66
+ continue;
67
+ visited.add(node);
68
+ if (++nodes > HEADER_SCAN_NODES)
69
+ return `its input schema is larger than ${HEADER_SCAN_NODES} parts, more than its headers are checked through`;
70
+ if (path.length > HEADER_SCAN_DEPTH)
71
+ return `its input schema nests deeper than ${HEADER_SCAN_DEPTH} levels, more than its headers are checked through`;
72
+ if (Array.isArray(node)) {
73
+ for (const item of node)
74
+ stack.push({ node: item, path, reachable: false });
75
+ continue;
76
+ }
77
+ const schema = node;
78
+ const where = path.length ? path.join(".") : "the schema's root";
79
+ if (Object.hasOwn(schema, "x-mcp-header")) {
80
+ const name = schema["x-mcp-header"];
81
+ if (!reachable || !path.length)
82
+ return `${where}: x-mcp-header is only allowed on a property reached through properties alone`;
83
+ if (typeof name !== "string" || !/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name))
84
+ return `${where}: x-mcp-header must be a header name (an RFC 9110 token)`;
85
+ if (!["string", "integer", "boolean"].includes(schema.type))
86
+ return `${where}: x-mcp-header is only allowed on a string, integer or boolean`;
87
+ const prior = seen.get(name.toLowerCase());
88
+ if (prior !== undefined)
89
+ return `x-mcp-header ${name} is declared twice (also as ${prior})`;
90
+ seen.set(name.toLowerCase(), name);
91
+ }
92
+ for (const [key, child] of Object.entries(schema)) {
93
+ if (!child || typeof child !== "object" || key === "x-mcp-header")
94
+ continue;
95
+ if (key === "properties" && !Array.isArray(child))
96
+ for (const [name, property] of Object.entries(child))
97
+ stack.push({ node: property, path: [...path, name], reachable });
98
+ else
99
+ stack.push({ node: child, path: [...path, `<${key}>`], reachable: false });
100
+ }
101
+ }
102
+ return undefined;
103
+ }
104
+ /** The pin of a run granted `names`: each MCP tool among them, as its server's snapshot holds it. Keyed by server name
105
+ * with no prototype, as every map of names here is: a server named `constructor` is a server like any other. A granted
106
+ * tool that cannot be pinned (its server no longer saved, the tool gone since a refresh, a header declaration it cannot
107
+ * send) throws, naming it and why: the run is refused, never started without it. */
108
+ export function mcpPinOf(names, source) {
109
+ const pin = Object.create(null);
110
+ for (const name of names) {
111
+ const parsed = mcpNameOf(name);
112
+ const saved = parsed && source.server(parsed.server);
113
+ const tool = saved?.tools.find((t) => t.name === parsed.tool);
114
+ if (!parsed)
115
+ continue;
116
+ // Gone since the run's check (deleted, or a refresh removed the tool): the run is refused, never started without it.
117
+ if (!saved)
118
+ throw new Error(`The MCP tool ${name} cannot be pinned: the MCP server ${parsed.server} is no longer saved.`);
119
+ if (!tool)
120
+ throw new Error(`The MCP tool ${name} cannot be pinned: ${parsed.tool} is no longer one of its tools since the last refresh.`);
121
+ // A meta tool granted before the rule (mcp-meta.ts): refused here, never run.
122
+ const meta = metaToolOf(saved.url, tool.name);
123
+ if (meta)
124
+ throw new Error(`${name} can't be granted: ${meta.reason}`);
125
+ const declared = mcpHeaderProblem(tool.inputSchema);
126
+ if (declared)
127
+ throw new Error(`The MCP tool ${name} declares a header it cannot send: ${declared}.`);
128
+ if (!Object.hasOwn(pin, parsed.server))
129
+ pin[parsed.server] = { url: saved.url, tools: [] };
130
+ const pinned = pin[parsed.server];
131
+ pinned.tools.push(tool);
132
+ const price = saved.prices && Object.hasOwn(saved.prices, tool.name) ? saved.prices[tool.name] : undefined;
133
+ // Keyed by a tool's name, which may be an object's own property (`__proto__`): no prototype to fall into.
134
+ if (price !== undefined)
135
+ (pinned.prices ??= Object.create(null))[tool.name] = price;
136
+ }
137
+ return pin;
138
+ }
139
+ /** What a launch hands the run for its pin: each pinned server's URL now, with its headers only when it has not moved. A
140
+ * server no longer saved is absent. */
141
+ export function mcpCredentialsOf(pin, source) {
142
+ const out = Object.create(null);
143
+ for (const [name, pinned] of Object.entries(pin)) {
144
+ const saved = source.server(name);
145
+ if (!saved)
146
+ continue;
147
+ const headers = saved.url === pinned.url ? source.headers(name) : undefined;
148
+ out[name] = { url: saved.url, ...(headers ? { headers } : {}) };
149
+ }
150
+ return out;
151
+ }
152
+ const said = (text, isError = false) => ({ content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) });
153
+ /** `text` with every credential value in it replaced, with or without its `Bearer `: an upstream answer or error that
154
+ * echoes a header never shows it to the model, the harness or the run's files. */
155
+ const scrub = (text, headers) => Object.values(headers).flatMap((value) => [value, value.replace(/^Bearer\s+/i, "")]).sort((a, b) => b.length - a.length).reduce((out, value) => (value.length >= 8 ? out.split(value).join("[redacted]") : out), text);
156
+ /** `work` until `signal` aborts: a connection shared by calls is never held by one that stopped. */
157
+ const until = (work, signal) => new Promise((resolve, reject) => {
158
+ if (signal.aborted)
159
+ return reject(signal.reason);
160
+ const stop = () => reject(signal.reason);
161
+ signal.addEventListener("abort", stop, { once: true });
162
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
163
+ });
164
+ /** The gateways that hold their run's gate: each of their calls enters it, in `call`. */
165
+ const gating = new WeakSet();
166
+ export function mcpGateway(options) {
167
+ const clients = new Map();
168
+ const pins = new Map(Object.entries(options.pin));
169
+ const credentials = new Map(Object.entries(options.credentials));
170
+ /** Each server's last HTTP status, which tells a refused credential from another failure. */
171
+ const statuses = new Map();
172
+ const send = options.fetch ?? fetch;
173
+ /** The fetch one server's client sends with: its credential added, no redirect followed, at most MAX_RESPONSE read. */
174
+ const guarded = (headers, status) => async (input, init = {}) => {
175
+ const sent = new Headers(init.headers);
176
+ for (const [name, value] of Object.entries(headers))
177
+ sent.set(name, value);
178
+ const response = await send(input, { ...init, headers: sent, redirect: "manual" });
179
+ status.last = response.status;
180
+ if (response.status >= 300 && response.status < 400)
181
+ throw new Error(`it answered a redirect (HTTP ${response.status}), which is never followed`);
182
+ if (!response.body)
183
+ return response;
184
+ let read = 0;
185
+ const capped = response.body.pipeThrough(new TransformStream({
186
+ transform(chunk, controller) {
187
+ read += chunk.byteLength;
188
+ if (read > MAX_RESPONSE)
189
+ controller.error(new Error(`its answer is longer than ${MAX_RESPONSE} bytes`));
190
+ else
191
+ controller.enqueue(chunk);
192
+ },
193
+ }));
194
+ return new Response(capped, { status: response.status, statusText: response.statusText, headers: response.headers });
195
+ };
196
+ const connect = (server, url, headers) => {
197
+ let upstream = clients.get(server);
198
+ if (!upstream) {
199
+ const status = {};
200
+ statuses.set(server, status);
201
+ upstream = (async () => {
202
+ const { Client, StreamableHTTPClientTransport } = await import("@modelcontextprotocol/client");
203
+ // The 2026-07-28 revision first, a 2025-era server through its initialize, as a preview connects.
204
+ const client = new Client({ name: "agentrun", version: "1.0.0" }, { capabilities: {}, versionNegotiation: { mode: "auto" } });
205
+ await client.connect(new StreamableHTTPClientTransport(new URL(url), { fetch: guarded(headers, status) }), { timeout: options.bounds?.connectMs ?? CONNECT_MS });
206
+ return client;
207
+ })();
208
+ clients.set(server, upstream);
209
+ // A server that did not connect is tried again at the next call.
210
+ upstream.catch(() => clients.delete(server));
211
+ }
212
+ return upstream;
213
+ };
214
+ /** The model's text of `result`: its text blocks joined, its structured content when it has no text; past MCP_CLIP, or
215
+ * with blocks that are not text, the whole result is filed under work/evidence/mcp/<server>/ and the text says where. */
216
+ const textOf = async (server, tool, result, headers) => {
217
+ const blocks = Array.isArray(result.content) ? result.content : [];
218
+ const texts = blocks.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text);
219
+ let text = scrub(texts.join("\n\n"), headers);
220
+ if (!text && result.structuredContent !== undefined)
221
+ text = scrub(JSON.stringify(result.structuredContent), headers);
222
+ const other = blocks.length - texts.length;
223
+ if (text.length <= MCP_CLIP && other === 0)
224
+ return text;
225
+ const name = `${tool}-${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}.json`;
226
+ const head = text.length > MCP_CLIP ? `${text.slice(0, MCP_CLIP)}\n[cut at ${MCP_CLIP} of ${text.length} characters; ` : `${text}\n[${other} block${other > 1 ? "s" : ""} that ${other > 1 ? "are" : "is"} not text; `;
227
+ try {
228
+ await writeInWork(options.work(), ["evidence", "mcp", server], name, scrub(JSON.stringify(result), headers)).catch(async (error) => {
229
+ if (error.code !== "EEXIST" || !(await lstat(join(options.work(), "evidence", "mcp", server, name)).then((held) => held.isFile(), () => false)))
230
+ throw error;
231
+ });
232
+ }
233
+ catch (error) {
234
+ return `${head}the whole answer could not be saved (${error?.code ?? "write failed"})]`;
235
+ }
236
+ return `${head}the whole answer is in the run's files at evidence/mcp/${server}/${name}]`;
237
+ };
238
+ /** The call itself, to a server whose address is the pinned one. A gate's decision or a paid call's hold goes around
239
+ * it, in `call` below: the one place every harness's call passes before anything is sent. */
240
+ /** `sending`, when given, runs once the server is connected and right before the call leaves: its refusal (a text)
241
+ * keeps the call from leaving. A call that never got that far (a failed connect, a stop) never ran it. */
242
+ const forward = async (server, url, headers, tool, args, signal, sending) => {
243
+ try {
244
+ const upstream = await until(connect(server, url, headers), signal);
245
+ if (sending && !signal.aborted) {
246
+ const refused = await sending();
247
+ if (refused)
248
+ return said(refused, true);
249
+ }
250
+ // The pinned definition, so the SDK mirrors its x-mcp-header parameters into Mcp-Param-* headers on a 2026-07-28
251
+ // server, as its own listing would have it do.
252
+ const result = (await upstream.callTool({ name: tool.name, arguments: args }, { signal, timeout: options.bounds?.callMs ?? CALL_MS, toolDefinition: { name: tool.name, inputSchema: tool.inputSchema } }));
253
+ return said(await textOf(server, tool.name, result, headers), result.isError === true);
254
+ }
255
+ catch (error) {
256
+ if (signal.aborted)
257
+ return said(`The call to the MCP server ${server} was stopped.`, true);
258
+ // The next call connects again (a server that dropped its session, say); this one is never sent again.
259
+ clients.delete(server);
260
+ const status = statuses.get(server)?.last;
261
+ if (status === 401 || status === 403)
262
+ return said(`The MCP server ${server} refused its credential; update it in Settings → MCP servers.`, true);
263
+ const why = scrub(String(error?.message ?? error), headers).slice(0, 300);
264
+ return said(`The MCP server ${server} failed${status && status >= 400 ? ` (HTTP ${status})` : ""}: ${why}`, true);
265
+ }
266
+ };
267
+ /** A record on the run's root, through its commit. */
268
+ const record = (commit, kind, data) => commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind, data })));
269
+ /** Why `tool` of `server` cannot be sent now, or undefined. */
270
+ const unsendable = (server, tool) => {
271
+ const pinned = pins.get(server);
272
+ if (!pinned?.tools.some((t) => t.name === tool))
273
+ return `${tool} is not a tool of the MCP server ${server} in this run.`;
274
+ const meta = metaToolOf(pinned.url, tool);
275
+ if (meta)
276
+ return `mcp:${server}/${tool} can't be granted: ${meta.reason} Nothing was sent.`;
277
+ const now = credentials.get(server);
278
+ if (!now)
279
+ return `The MCP server ${server} is no longer saved on this server; nothing was sent.`;
280
+ if (now.url !== pinned.url)
281
+ return `The MCP server ${server}'s address changed since this run started; nothing was sent. Start a new run to use it at its new address.`;
282
+ return undefined;
283
+ };
284
+ /** A call the gate let go: a priced one under the run's cap and booked, an unpriced one marked not metered. */
285
+ const sent = async (server, tool, args, callId, signal) => {
286
+ const why = unsendable(server, tool);
287
+ if (why)
288
+ return said(why, true);
289
+ const { url, prices, tools: pinnedTools } = pins.get(server);
290
+ const listed = pinnedTools.find((t) => t.name === tool);
291
+ // Whether the call left for the server: only then is it booked, at its price or as not metered.
292
+ let went = false;
293
+ const call = (mark = async () => undefined) => forward(server, url, credentials.get(server).headers ?? {}, listed, args, signal, async () => {
294
+ const refused = await mark();
295
+ went = refused === undefined;
296
+ return refused;
297
+ });
298
+ const name = mcpToolName(server, tool);
299
+ const label = { tool: name, charged_by: server, call: callId };
300
+ const commit = options.commit?.();
301
+ const price = prices && Object.hasOwn(prices, tool) ? prices[tool] : undefined;
302
+ if (price === undefined) {
303
+ const result = await call();
304
+ if (commit && went)
305
+ await record(commit, TOOL_UNMETERED, label).catch(() => undefined);
306
+ return result;
307
+ }
308
+ if (!commit)
309
+ return said(`${name} was not sent: this call has no run to book its price under.`, true);
310
+ const paid = await paidCall(name, async () => {
311
+ // Held at its price meanwhile; marked right before it leaves, and settled at its price once it left, whatever it
312
+ // answers: its owner says each call costs that. One that never left (a failed connect, a stop) books nothing.
313
+ const result = await call(async () => {
314
+ try {
315
+ await record(commit, TOOL_STARTED, { ...label, heldUsd: price });
316
+ return undefined;
317
+ }
318
+ catch (error) {
319
+ return `${name} was not sent: its mark could not be written (${String(error?.message ?? error).slice(0, 200)})`;
320
+ }
321
+ });
322
+ if (went)
323
+ await record(commit, TOOL_COST, { ...label, usd: price }).catch(() => undefined);
324
+ return result;
325
+ }, () => (went ? price : 0), { usd: price, basis: `the price its owner set for ${name}` });
326
+ return "refused" in paid ? said(paid.refused, true) : paid.result;
327
+ };
328
+ // An approved call, run by the gate once a person allows it: through the same path, once. It has the same deadline as
329
+ // any call: forward() gives callTool CALL_MS and a server's first connection CONNECT_MS, so a server that never answers
330
+ // ends the call as an error the model reads, the upstream request aborted, and the run goes on; the gate's own stop or
331
+ // cancel reaches it through `signal`.
332
+ options.gate?.executor?.("mcp:", async (name, args, callId, signal) => {
333
+ const parsed = /^mcp:([^/]+)\/(.+)$/.exec(name);
334
+ const result = parsed ? await sent(parsed[1], parsed[2], (args ?? {}), callId, signal) : said(`${name} is not an MCP tool.`, true);
335
+ return { text: result.content.map((block) => block.text).join("\n\n"), isError: result.isError === true };
336
+ });
337
+ const gateway = {
338
+ servers: [...pins].map(([name, pinned]) => ({ name, tools: pinned.tools })),
339
+ async call(server, tool, args, { signal, callId, park: given }) {
340
+ const why = unsendable(server, tool);
341
+ if (why)
342
+ return said(why, true);
343
+ const gate = options.gate;
344
+ // A parked call is answered and resumed by its id, the harness's own: a call with none is never parked.
345
+ if (gate && !callId)
346
+ return said(`The ${mcpToolName(server, tool)} call was not sent: it came with no call id, so it cannot wait for a person's approval.`, true);
347
+ const id = callId ?? `mcp_${randomUUID()}`;
348
+ if (gate) {
349
+ const name = mcpToolName(server, tool);
350
+ // A call parks only where its harness can end the turn on it (a park with `parked`). Anywhere else the gate's
351
+ // commit of the request is refused, so an ask leaves no approval waiting, and the call is answered so.
352
+ const park = given?.parked ? given : { commit: () => Promise.reject(new CannotPark()) };
353
+ const cannot = said(`The ${name} call needs a person's approval, which this harness can't wait for yet; nothing was sent.`, true);
354
+ let entered;
355
+ try {
356
+ // The approval card shows the call's declared price, or that it is not metered.
357
+ const price = pins.get(server).prices;
358
+ entered = await gate.enter(name, args, id, park, { price: price && Object.hasOwn(price, tool) ? price[tool] : "not metered" });
359
+ }
360
+ catch (error) {
361
+ if (error instanceof CannotPark)
362
+ return cannot;
363
+ return said(`The ${name} call was not sent: the tool gate failed (${String(error?.message ?? error).slice(0, 200)}).`, true);
364
+ }
365
+ if (entered?.parked)
366
+ return park === given ? Object.assign(said(entered.text), { [PARKED]: true }) : cannot;
367
+ if (entered)
368
+ return said(entered.text, entered.isError);
369
+ const result = await sent(server, tool, args, id, signal);
370
+ const text = result.content.map((block) => block.text).join("\n\n");
371
+ return said(gate.spill ? gate.spill(id, text) : text, result.isError === true);
372
+ }
373
+ return sent(server, tool, args, id, signal);
374
+ },
375
+ };
376
+ if (options.gate)
377
+ gating.add(gateway);
378
+ return gateway;
379
+ }
380
+ const PARKED = Symbol("agentrun.mcp.parked");
381
+ /** A park refused: the call came from a harness that cannot end its turn on a parked call. */
382
+ class CannotPark extends Error {
383
+ }
384
+ /** Whether the gateway's answer is a call the gate parked for a person's approval: the harness ends the turn on it. A
385
+ * symbol, so it never reaches a harness's MCP client in the answer's JSON. */
386
+ export const isParked = (result) => result[PARKED] === true;
387
+ /** pi's tools for the gateway's servers: each granted tool under its wire name (`mcp__<server>__<tool>`), with the pinned
388
+ * description and schema, never run again after a crash. */
389
+ export function mcpRegistrations(gateway) {
390
+ // Marked when the gateway holds the run's gate: its calls enter the gate in the gateway, so the gate's own wrapper
391
+ // (tool-gate.ts extension) leaves them be. Unmarked, the wrapper gates them as any tool.
392
+ const marked = gating.has(gateway) ? { [GATED_BY_GATEWAY]: true } : {};
393
+ return gateway.servers.flatMap((server) => server.tools.map((tool) => Object.assign(defineTool({
394
+ name: wireName(`mcp:${server.name}/${tool.name}`),
395
+ description: tool.description || tool.title || `${tool.name}, a tool of the MCP server ${server.name}.`,
396
+ replay: "unsafe",
397
+ parameters: tool.inputSchema,
398
+ execute: async (args, api, context) => {
399
+ // The gate's park is this call's own journal commit, as for every pi tool.
400
+ // pi ends the turn on a parked answer itself (below), so its park needs nothing told.
401
+ const park = { commit: (change) => api.commit(change, context), parked: () => undefined };
402
+ const result = await gateway.call(server.name, tool.name, (args ?? {}), { signal: context?.abortSignal ?? new AbortController().signal, ...(api?.callId ? { callId: api.callId, park } : {}) });
403
+ const text = result.content.map((block) => block.text).join("\n\n");
404
+ // A parked call ends the turn, as ask_person's does; the gate resumes the session once a person answers.
405
+ return isParked(result) ? forModel(text, { control: { terminate: true } }) : forModel(text, { isError: result.isError === true });
406
+ },
407
+ }), marked)));
408
+ }
@@ -0,0 +1,17 @@
1
+ /** Why a meta tool is not granted: what the save's refusal, the launch's and the tool's `reason` say. */
2
+ export declare const META_REASON = "it runs other actions by name, so a grant can't name the real action. Use the server's direct tools instead.";
3
+ type MetaTool = {
4
+ /** The tool's exact name, or, with `prefix`, the start of the names its server generates. */
5
+ name: string;
6
+ prefix?: true;
7
+ /** For a generic name: the hosts it is a meta tool on (the host itself or a subdomain of it). */
8
+ hosts?: readonly string[];
9
+ /** Where the name is documented. */
10
+ source: string;
11
+ };
12
+ export declare const MCP_META_TOOLS: readonly MetaTool[];
13
+ /** The known meta tool `tool` of the server at `url` is, with why it is not granted; undefined for any other tool. */
14
+ export declare function metaToolOf(url: string, tool: string): {
15
+ reason: string;
16
+ } | undefined;
17
+ export {};
@@ -0,0 +1,38 @@
1
+ // Known MCP meta tools: a tool that runs other actions by name (or by code the model writes), so a grant of it can't name
2
+ // the real action. Allow would cover every inner action, and deny could target none of them, so none is ever granted.
3
+ // The rule is this closed list, never a guess from a schema's shape. A name that only a provider uses matches on any
4
+ // host; a generic name matches only on its provider's host. A meta tool the list does not know stays an MCP tool like
5
+ // any other, asked by default at the tool gate. Each entry says where its name is documented (read 2026-11-05).
6
+ /** Why a meta tool is not granted: what the save's refusal, the launch's and the tool's `reason` say. */
7
+ export const META_REASON = "it runs other actions by name, so a grant can't name the real action. Use the server's direct tools instead.";
8
+ export const MCP_META_TOOLS = [
9
+ // Composio's session MCP and Connect (ComposioHQ/composio@29698b7e5, ts/packages/cli/src/utils/meta-tool-slugs.ts and
10
+ // docs/public/data/meta-tools.json): up to 50 tools by slug, Python in a remote workbench, a shell, raw HTTP to an app.
11
+ ...["COMPOSIO_MULTI_EXECUTE_TOOL", "COMPOSIO_REMOTE_WORKBENCH", "COMPOSIO_REMOTE_BASH_TOOL", "COMPOSIO_PROXY_EXECUTE"].map((name) => ({ name, source: "composio@29698b7e5 meta-tool-slugs.ts, meta-tools.json" })),
12
+ // Klavis Strata (klavis@7cab53e94, open-strata/src/strata/tools.py and docs/concepts/strata.mdx): server_name + action_name.
13
+ { name: "execute_action", hosts: ["klavis.ai"], source: "klavis@7cab53e94 open-strata tools.py, docs/concepts/strata.mdx" },
14
+ // Zapier MCP's agentic mode (docs.zapier.com/mcp/overview/how-tools-work#meta-tools): an action by name, or generated code.
15
+ { name: "execute_zapier_read_action", source: "docs.zapier.com/mcp/overview/how-tools-work#meta-tools" },
16
+ { name: "execute_zapier_write_action", source: "docs.zapier.com/mcp/overview/how-tools-work#meta-tools" },
17
+ { name: "write_code_action", hosts: ["mcp.zapier.com"], source: "docs.zapier.com/mcp/overview/how-tools-work#meta-tools" },
18
+ // Arcade MCP gateways' tool recommendation (ArcadeAI/docs@dd84f015c, mcp-gateways/tool-recommendation/index.mdx).
19
+ { name: "Arcade_UseTool", source: "ArcadeAI/docs@dd84f015c tool-recommendation/index.mdx" },
20
+ // Docker's MCP gateway with dynamic tools (docker/mcp-gateway@7e0f34277, pkg/gateway/dynamic_mcps.go and
21
+ // pkg/codemode/codemode.go): a session tool by name, and the code-mode tools it generates.
22
+ { name: "mcp-exec", source: "docker/mcp-gateway@7e0f34277 pkg/gateway/dynamic_mcps.go" },
23
+ // prefix: Docker generates these names; a non-Docker tool named code-mode-* is refused too, by design (code mode is
24
+ // never granted, and a false match only refuses a grant).
25
+ { name: "code-mode-", prefix: true, source: "docker/mcp-gateway@7e0f34277 pkg/codemode/codemode.go" },
26
+ // Cloudflare MCP server portals (developers.cloudflare.com/cloudflare-one/access-controls/ai-controls/mcp-portals/):
27
+ // search_and_execute's execute, and Code Mode's JavaScript.
28
+ { name: "portal_execute", source: "developers.cloudflare.com mcp-portals#optimize-context" },
29
+ { name: "portal_codemode_execute", source: "developers.cloudflare.com mcp-portals code mode" },
30
+ ];
31
+ /** A URL's host as compared here: lowercase, and with no final dot (`klavis.ai.` names the same host as `klavis.ai`). */
32
+ const hostOf = (url) => URL.parse(url)?.hostname.toLowerCase().replace(/\.$/, "");
33
+ /** The known meta tool `tool` of the server at `url` is, with why it is not granted; undefined for any other tool. */
34
+ export function metaToolOf(url, tool) {
35
+ const host = hostOf(url);
36
+ const known = MCP_META_TOOLS.find((meta) => (meta.prefix ? tool.startsWith(meta.name) && tool.length > meta.name.length : tool === meta.name) && (!meta.hosts || (host !== undefined && meta.hosts.some((at) => host === at || host.endsWith(`.${at}`)))));
37
+ return known ? { reason: META_REASON } : undefined;
38
+ }
@@ -18,6 +18,9 @@ type Listed = {
18
18
  instructions?: string;
19
19
  tools: McpTool[];
20
20
  };
21
+ /** A tool's declared price in USD a call, by its name: what a run's cap holds and books for each call (mcp-gateway.ts). */
22
+ export type McpPrices = Record<string, number>;
23
+ type HeaderMap = Record<string, string>;
21
24
  export declare class McpServers {
22
25
  private readonly version;
23
26
  readonly file: string;
@@ -38,8 +41,12 @@ export declare class McpServers {
38
41
  protocol: string;
39
42
  server_info: unknown;
40
43
  instructions?: string;
41
- tools: McpTool[];
44
+ tools: McpTool[] & (McpTool & {
45
+ grantable?: false;
46
+ reason?: string;
47
+ })[];
42
48
  url: string;
49
+ prices?: McpPrices;
43
50
  listed_at: string;
44
51
  updated_at: string;
45
52
  name: string;
@@ -55,8 +62,12 @@ export declare class McpServers {
55
62
  protocol: string;
56
63
  server_info: unknown;
57
64
  instructions?: string;
58
- tools: McpTool[];
65
+ tools: McpTool[] & (McpTool & {
66
+ grantable?: false;
67
+ reason?: string;
68
+ })[];
59
69
  url: string;
70
+ prices?: McpPrices;
60
71
  listed_at: string;
61
72
  updated_at: string;
62
73
  name: string;
@@ -74,8 +85,12 @@ export declare class McpServers {
74
85
  protocol: string;
75
86
  server_info: unknown;
76
87
  instructions?: string;
77
- tools: McpTool[];
88
+ tools: McpTool[] & (McpTool & {
89
+ grantable?: false;
90
+ reason?: string;
91
+ })[];
78
92
  url: string;
93
+ prices?: McpPrices;
79
94
  listed_at: string;
80
95
  updated_at: string;
81
96
  name: string;
@@ -94,20 +109,26 @@ export declare class McpServers {
94
109
  protocol: string;
95
110
  server_info: unknown;
96
111
  instructions?: string;
97
- tools: McpTool[];
112
+ tools: McpTool[] & (McpTool & {
113
+ grantable?: false;
114
+ reason?: string;
115
+ })[];
98
116
  url: string;
117
+ prices?: McpPrices;
99
118
  listed_at: string;
100
119
  updated_at: string;
101
120
  name: string;
102
121
  };
103
122
  }>;
123
+ /** The saved server's credential, opened, for a run's launch: its headers; undefined when it has none, or none that opens. */
124
+ headers(name: string): HeaderMap | undefined;
104
125
  remove(name: string): void;
105
126
  private need;
106
127
  private view;
107
128
  private open;
108
129
  /** The saved credential, opened, or the refusal that asks for it again. */
109
130
  private opened;
110
- /** A body's URL and auth, or 422. */
131
+ /** A body's URL, auth and prices, or 422. */
111
132
  private admit;
112
133
  /** The saved servers: none with no file, "unreadable" when the file does not read as this format. */
113
134
  private kept;