@buildanagent/harness 0.1.0-alpha.30 → 0.1.0-alpha.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 (58) hide show
  1. package/README.md +69 -3
  2. package/dist/credentials/addresses.d.ts +9 -0
  3. package/dist/credentials/addresses.js +52 -0
  4. package/dist/credentials/addresses.js.map +1 -1
  5. package/dist/credentials/egress-proxy.js +34 -4
  6. package/dist/credentials/egress-proxy.js.map +1 -1
  7. package/dist/extensions/load.js +5 -2
  8. package/dist/extensions/load.js.map +1 -1
  9. package/dist/extensions/lock.d.ts +16 -2
  10. package/dist/extensions/lock.js +155 -21
  11. package/dist/extensions/lock.js.map +1 -1
  12. package/dist/extensions/mcp-pins-node.d.ts +16 -0
  13. package/dist/extensions/mcp-pins-node.js +18 -0
  14. package/dist/extensions/mcp-pins-node.js.map +1 -0
  15. package/dist/extensions/node.d.ts +4 -2
  16. package/dist/extensions/node.js +4 -2
  17. package/dist/extensions/node.js.map +1 -1
  18. package/dist/harness.d.ts +7 -1
  19. package/dist/harness.js.map +1 -1
  20. package/dist/mcp/connection.d.ts +9 -3
  21. package/dist/mcp/connection.js +192 -25
  22. package/dist/mcp/connection.js.map +1 -1
  23. package/dist/mcp/errors.d.ts +5 -2
  24. package/dist/mcp/errors.js.map +1 -1
  25. package/dist/mcp/guarded-fetch.d.ts +33 -0
  26. package/dist/mcp/guarded-fetch.js +391 -0
  27. package/dist/mcp/guarded-fetch.js.map +1 -0
  28. package/dist/mcp/http-node.d.ts +15 -0
  29. package/dist/mcp/http-node.js +179 -0
  30. package/dist/mcp/http-node.js.map +1 -0
  31. package/dist/mcp/index.d.ts +6 -3
  32. package/dist/mcp/index.js +5 -2
  33. package/dist/mcp/index.js.map +1 -1
  34. package/dist/mcp/manager.d.ts +4 -3
  35. package/dist/mcp/manager.js +432 -47
  36. package/dist/mcp/manager.js.map +1 -1
  37. package/dist/mcp/pins.d.ts +9 -0
  38. package/dist/mcp/pins.js +54 -0
  39. package/dist/mcp/pins.js.map +1 -0
  40. package/dist/mcp/record.js +6 -0
  41. package/dist/mcp/record.js.map +1 -1
  42. package/dist/mcp/remote-config.d.ts +20 -0
  43. package/dist/mcp/remote-config.js +208 -0
  44. package/dist/mcp/remote-config.js.map +1 -0
  45. package/dist/mcp/remote.d.ts +20 -0
  46. package/dist/mcp/remote.js +146 -0
  47. package/dist/mcp/remote.js.map +1 -0
  48. package/dist/mcp/types.d.ts +198 -8
  49. package/dist/mcp/types.js.map +1 -1
  50. package/dist/server/protocol.schema.json +6 -3
  51. package/dist/session/runner.js +39 -6
  52. package/dist/session/runner.js.map +1 -1
  53. package/dist/tools/index.d.ts +1 -1
  54. package/dist/tools/index.js.map +1 -1
  55. package/dist/tools/types.d.ts +16 -0
  56. package/dist/tools/types.js.map +1 -1
  57. package/llms.txt +18 -2
  58. package/package.json +7 -6
@@ -0,0 +1,146 @@
1
+ /**
2
+ * A remote server as a channel: the client library's streamable HTTP or SSE transport, with every request sent through
3
+ * `guardedFetch()`. The network under it is the egress proxy when one is configured, the pinned Node fetch on Node,
4
+ * and the platform's own `fetch` elsewhere, Cloudflare's workerd included, where the harness can't resolve a name itself.
5
+ *
6
+ * The library's reconnects are bounded here too. A streamable HTTP stream that drops is reopened by the library after
7
+ * a delay this module sets: one second, doubling to thirty, whatever the server says, and at most `MAX_REOPENS` times
8
+ * in ten minutes before the connection closes. A legacy SSE stream is opened once: when it ends, the connection closes.
9
+ */
10
+ import { SSEClientTransport, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
11
+ import { isAddressLiteral, isLoopbackAddress } from "../credentials/addresses.js";
12
+ import { guardedFetch, RemoteRefusal } from "./guarded-fetch.js";
13
+ import { hasNodeNetwork, nodeFetch } from "./http-node.js";
14
+ import { checkRemoteTransport, redact } from "./remote-config.js";
15
+ const MIN_REOPEN_MS = 1000;
16
+ const MAX_REOPEN_MS = 30_000;
17
+ const MAX_REOPENS = 10;
18
+ const REOPEN_WINDOW_MS = 10 * 60 * 1000;
19
+ /**
20
+ * The platform's fetch, for a runtime without Node's network modules. It can't resolve a name, so it checks a literal
21
+ * address, counts `localhost` and a name under `.localhost` as loopback, and leaves where any other name goes to the
22
+ * platform. Plain `http:` reaches a loopback literal or a localhost name only.
23
+ */
24
+ export function platformFetch(settings) {
25
+ return (input, init) => {
26
+ const url = new URL(typeof input === "string" ? input : input.href);
27
+ // A name may end in a dot, which names the same host: `localhost.` is `localhost`.
28
+ const host = url.hostname
29
+ .replace(/^\[|\]$/g, "")
30
+ .replace(/\.$/, "")
31
+ .toLowerCase();
32
+ const local = host === "localhost" || host.endsWith(".localhost");
33
+ if ((isAddressLiteral(host) && !settings.allows(host)) || (local && !settings.allows("127.0.0.1"))) {
34
+ return Promise.reject(new RemoteRefusal("refused", "the server's address is one it may not reach"));
35
+ }
36
+ if (url.protocol === "http:" && !(local || (isAddressLiteral(host) && isLoopbackAddress(host)))) {
37
+ return Promise.reject(new RemoteRefusal("refused", "plain http: reaches only a loopback address"));
38
+ }
39
+ return globalThis.fetch(url, { ...init, redirect: "manual" });
40
+ };
41
+ }
42
+ /** The network a remote server's requests go out on. */
43
+ function networkOf(transport, settings) {
44
+ const proxy = transport.proxy;
45
+ if (proxy !== undefined)
46
+ return (input, init) => proxy.fetch(input, { ...init, redirect: "manual" });
47
+ if (hasNodeNetwork())
48
+ return nodeFetch(settings, { resolve: transport.resolve, ca: transport.ca });
49
+ return platformFetch(settings);
50
+ }
51
+ /**
52
+ * The reconnect schedule the library's streamable HTTP transport uses: a delay of its own choosing within one to
53
+ * thirty seconds, and a budget of reopens per window. A reopen after a planned cut waits the shortest delay and is not
54
+ * counted. Past the budget it closes the channel instead.
55
+ */
56
+ function reopenSchedule(timers, planned, onExhausted) {
57
+ const recent = [];
58
+ return (reconnect, _delay, attempt) => {
59
+ const later = (ms) => {
60
+ const handle = timers.setTimeout(reconnect, ms);
61
+ return () => timers.clearTimeout(handle);
62
+ };
63
+ if (planned.get > 0) {
64
+ planned.get -= 1;
65
+ return later(MIN_REOPEN_MS);
66
+ }
67
+ const now = timers.now();
68
+ while (recent.length > 0 && now - recent[0] > REOPEN_WINDOW_MS)
69
+ recent.shift();
70
+ if (recent.length >= MAX_REOPENS) {
71
+ onExhausted();
72
+ return () => { };
73
+ }
74
+ recent.push(now);
75
+ return later(Math.min(MAX_REOPEN_MS, MIN_REOPEN_MS * 2 ** Math.max(attempt, recent.length - 1)));
76
+ };
77
+ }
78
+ /** Builds the channel for a remote server. Nothing is sent until the client starts it. */
79
+ export function remoteChannel(transport, log, timers) {
80
+ const settings = checkRemoteTransport(transport);
81
+ const say = (line) => log(redact(line, settings.secrets));
82
+ let channel;
83
+ const closeChannel = () => {
84
+ void channel?.close().catch(() => { });
85
+ };
86
+ let gets = 0;
87
+ const onGet = transport.kind === "sse"
88
+ ? () => {
89
+ gets += 1;
90
+ if (gets === 1)
91
+ return true;
92
+ say("the server's event stream ended, so the connection was closed; nothing reconnects it");
93
+ closeChannel();
94
+ return false;
95
+ }
96
+ : undefined;
97
+ let refusal;
98
+ const planned = { get: 0, listen: 0 };
99
+ const onBroken = (error, fatal, kind) => {
100
+ if (!fatal) {
101
+ if (kind === "get")
102
+ planned.get += 1;
103
+ if (kind === "listen")
104
+ planned.listen += 1;
105
+ say(`a stream of the server was cut and is opened again: ${error.message}`);
106
+ return;
107
+ }
108
+ refusal ??= error;
109
+ say(`the connection was closed: ${error.message}`);
110
+ closeChannel();
111
+ };
112
+ const fetch = guardedFetch(networkOf(transport, settings), settings, {
113
+ ...(onGet === undefined ? {} : { onGet, endless: true }),
114
+ onBroken,
115
+ log: say,
116
+ });
117
+ if (transport.kind === "sse") {
118
+ channel = new SSEClientTransport(settings.url, { fetch, eventSourceInit: { fetch } });
119
+ }
120
+ else {
121
+ const schedule = reopenSchedule(timers, planned, () => {
122
+ say(`the server's stream dropped ${MAX_REOPENS} times in ten minutes, so the connection was closed`);
123
+ closeChannel();
124
+ });
125
+ channel = new StreamableHTTPClientTransport(settings.url, {
126
+ fetch,
127
+ reconnectionScheduler: schedule,
128
+ reconnectionOptions: {
129
+ initialReconnectionDelay: MIN_REOPEN_MS,
130
+ maxReconnectionDelay: MAX_REOPEN_MS,
131
+ reconnectionDelayGrowFactor: 2,
132
+ // The library gives up after maxRetries failed reopens and leaves the connection open with no stream, so its
133
+ // limit sits past the schedule's budget, which closes the connection instead.
134
+ maxRetries: MAX_REOPENS * 4,
135
+ },
136
+ });
137
+ }
138
+ const plannedListenCut = () => {
139
+ if (planned.listen === 0)
140
+ return false;
141
+ planned.listen -= 1;
142
+ return true;
143
+ };
144
+ return { channel, settings, refusal: () => refusal, plannedListenCut };
145
+ }
146
+ //# sourceMappingURL=remote.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote.js","sourceRoot":"","sources":["../../src/mcp/remote.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AACjG,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAClF,OAAO,EAAkB,YAAY,EAAE,aAAa,EAAmB,MAAM,oBAAoB,CAAC;AAClG,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAuB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAGvF,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,aAAa,GAAG,MAAM,CAAC;AAC7B,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,gBAAgB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAExC;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,QAAwB;IACpD,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;QACrB,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CA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,CAA0B,CAAC;IAC9B,CAAC;IACD,MAAM,gBAAgB,GAAG,GAAG,EAAE;QAC5B,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACvC,OAAO,CAAC,MAAM,IAAI,CAAC,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IACF,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,gBAAgB,EAAE,CAAC;AACzE,CAAC","sourcesContent":["/**\n * A remote server as a channel: the client library's streamable HTTP or SSE transport, with every request sent through\n * `guardedFetch()`. The network under it is the egress proxy when one is configured, the pinned Node fetch on Node,\n * and the platform's own `fetch` elsewhere, Cloudflare's workerd included, where the harness can't resolve a name itself.\n *\n * The library's reconnects are bounded here too. A streamable HTTP stream that drops is reopened by the library after\n * a delay this module sets: one second, doubling to thirty, whatever the server says, and at most `MAX_REOPENS` times\n * in ten minutes before the connection closes. A legacy SSE stream is opened once: when it ends, the connection closes.\n */\nimport { SSEClientTransport, StreamableHTTPClientTransport } from \"@modelcontextprotocol/client\";\nimport { isAddressLiteral, isLoopbackAddress } from \"../credentials/addresses.js\";\nimport { type FetchLike, guardedFetch, RemoteRefusal, type StreamKind } from \"./guarded-fetch.js\";\nimport { hasNodeNetwork, nodeFetch } from \"./http-node.js\";\nimport { checkRemoteTransport, type RemoteSettings, redact } from \"./remote-config.js\";\nimport type { McpChannel, McpHttpTransport, McpSseTransport, McpTimers } from \"./types.js\";\n\nconst MIN_REOPEN_MS = 1000;\nconst MAX_REOPEN_MS = 30_000;\nconst MAX_REOPENS = 10;\nconst REOPEN_WINDOW_MS = 10 * 60 * 1000;\n\n/**\n * The platform's fetch, for a runtime without Node's network modules. It can't resolve a name, so it checks a literal\n * address, counts `localhost` and a name under `.localhost` as loopback, and leaves where any other name goes to the\n * platform. Plain `http:` reaches a loopback literal or a localhost name only.\n */\nexport function platformFetch(settings: RemoteSettings): FetchLike {\n return (input, init) => {\n const url = new URL(typeof input === \"string\" ? input : input.href);\n // A name may end in a dot, which names the same host: `localhost.` is `localhost`.\n const host = url.hostname\n .replace(/^\\[|\\]$/g, \"\")\n .replace(/\\.$/, \"\")\n .toLowerCase();\n const local = host === \"localhost\" || host.endsWith(\".localhost\");\n if ((isAddressLiteral(host) && !settings.allows(host)) || (local && !settings.allows(\"127.0.0.1\"))) {\n return Promise.reject(new RemoteRefusal(\"refused\", \"the server's address is one it may not reach\"));\n }\n if (url.protocol === \"http:\" && !(local || (isAddressLiteral(host) && isLoopbackAddress(host)))) {\n return Promise.reject(new RemoteRefusal(\"refused\", \"plain http: reaches only a loopback address\"));\n }\n return globalThis.fetch(url, { ...init, redirect: \"manual\" });\n };\n}\n\n/** The network a remote server's requests go out on. */\nfunction networkOf(transport: McpHttpTransport | McpSseTransport, settings: RemoteSettings): FetchLike {\n const proxy = transport.proxy;\n if (proxy !== undefined) return (input, init) => proxy.fetch(input, { ...init, redirect: \"manual\" });\n if (hasNodeNetwork()) return nodeFetch(settings, { resolve: transport.resolve, ca: transport.ca });\n return platformFetch(settings);\n}\n\n/**\n * The harness's own cuts of long-lived streams, which end a stream on purpose: each is spent once, by the reopen it\n * causes, so a planned cut never counts against a budget that stops a looping server. A cut needs a real idle period,\n * a full stream or an hour, so the credits can't make a hot loop.\n */\ninterface PlannedCuts {\n get: number;\n listen: number;\n}\n\n/**\n * The reconnect schedule the library's streamable HTTP transport uses: a delay of its own choosing within one to\n * thirty seconds, and a budget of reopens per window. A reopen after a planned cut waits the shortest delay and is not\n * counted. Past the budget it closes the channel instead.\n */\nfunction reopenSchedule(timers: McpTimers, planned: PlannedCuts, onExhausted: () => void) {\n const recent: number[] = [];\n return (reconnect: () => void, _delay: number, attempt: number): (() => void) => {\n const later = (ms: number) => {\n const handle = timers.setTimeout(reconnect, ms);\n return () => timers.clearTimeout(handle);\n };\n if (planned.get > 0) {\n planned.get -= 1;\n return later(MIN_REOPEN_MS);\n }\n const now = timers.now();\n while (recent.length > 0 && now - (recent[0] as number) > REOPEN_WINDOW_MS) recent.shift();\n if (recent.length >= MAX_REOPENS) {\n onExhausted();\n return () => {};\n }\n recent.push(now);\n return later(Math.min(MAX_REOPEN_MS, MIN_REOPEN_MS * 2 ** Math.max(attempt, recent.length - 1)));\n };\n}\n\n/** A remote channel and what the connection needs to know about it. */\nexport interface RemoteChannel {\n readonly channel: McpChannel;\n readonly settings: RemoteSettings;\n /** The bound a response broke that closed the connection, if one did. */\n readonly refusal: () => RemoteRefusal | undefined;\n /** Whether the listen stream that just ended was the harness's own cut; true spends that cut. */\n readonly plannedListenCut: () => boolean;\n}\n\n/** Builds the channel for a remote server. Nothing is sent until the client starts it. */\nexport function remoteChannel(\n transport: McpHttpTransport | McpSseTransport,\n log: (line: string) => void,\n timers: McpTimers,\n): RemoteChannel {\n const settings = checkRemoteTransport(transport);\n const say = (line: string) => log(redact(line, settings.secrets));\n let channel: McpChannel | undefined;\n const closeChannel = () => {\n void channel?.close().catch(() => {});\n };\n let gets = 0;\n const onGet =\n transport.kind === \"sse\"\n ? () => {\n gets += 1;\n if (gets === 1) return true;\n say(\"the server's event stream ended, so the connection was closed; nothing reconnects it\");\n closeChannel();\n return false;\n }\n : undefined;\n let refusal: RemoteRefusal | undefined;\n const planned: PlannedCuts = { get: 0, listen: 0 };\n const onBroken = (error: RemoteRefusal, fatal: boolean, kind: StreamKind) => {\n if (!fatal) {\n if (kind === \"get\") planned.get += 1;\n if (kind === \"listen\") planned.listen += 1;\n say(`a stream of the server was cut and is opened again: ${error.message}`);\n return;\n }\n refusal ??= error;\n say(`the connection was closed: ${error.message}`);\n closeChannel();\n };\n const fetch = guardedFetch(networkOf(transport, settings), settings, {\n ...(onGet === undefined ? {} : { onGet, endless: true }),\n onBroken,\n log: say,\n });\n if (transport.kind === \"sse\") {\n channel = new SSEClientTransport(settings.url, { fetch, eventSourceInit: { fetch } }) as unknown as McpChannel;\n } else {\n const schedule = reopenSchedule(timers, planned, () => {\n say(`the server's stream dropped ${MAX_REOPENS} times in ten minutes, so the connection was closed`);\n closeChannel();\n });\n channel = new StreamableHTTPClientTransport(settings.url, {\n fetch,\n reconnectionScheduler: schedule,\n reconnectionOptions: {\n initialReconnectionDelay: MIN_REOPEN_MS,\n maxReconnectionDelay: MAX_REOPEN_MS,\n reconnectionDelayGrowFactor: 2,\n // The library gives up after maxRetries failed reopens and leaves the connection open with no stream, so its\n // limit sits past the schedule's budget, which closes the connection instead.\n maxRetries: MAX_REOPENS * 4,\n },\n }) as unknown as McpChannel;\n }\n const plannedListenCut = () => {\n if (planned.listen === 0) return false;\n planned.listen -= 1;\n return true;\n };\n return { channel, settings, refusal: () => refusal, plannedListenCut };\n}\n"]}
@@ -4,7 +4,8 @@
4
4
  */
5
5
  import type { ModelContent } from "@buildanagent/gateway";
6
6
  import type { ExtensionLoadedRecord } from "../extensions/types.js";
7
- import type { ToolExposure, ToolRegistry } from "../tools/types.js";
7
+ import type { PermissionHook } from "../permissions/types.js";
8
+ import type { ToolExposure, ToolRegistry, TurnBoundary } from "../tools/types.js";
8
9
  /** The protocol era a server speaks: the 2026-07-28 revision, or `legacy` for the 2025 revisions and their `initialize`. */
9
10
  export type McpEra = "2026-07-28" | "legacy";
10
11
  /**
@@ -59,6 +60,94 @@ export interface McpInProcessTransport {
59
60
  readonly kind: "in_process";
60
61
  readonly channel: McpChannel;
61
62
  }
63
+ /** The part of an egress proxy a remote server's requests go through: `startEgressProxy()` returns one. */
64
+ export interface McpEgressFetch {
65
+ /** Sends one request under the proxy's allowlist and resolves with its response. */
66
+ fetch(input: string | URL, init?: RequestInit): Promise<Response>;
67
+ }
68
+ /**
69
+ * The settings a remote server shares, over streamable HTTP or legacy SSE. A remote server is untrusted code on
70
+ * another machine, and the harness reaches it with its own network identity, so the URL, every address it resolves to
71
+ * and every byte that comes back are checked.
72
+ */
73
+ export interface McpRemoteSettings {
74
+ /**
75
+ * The server's endpoint. It must be `https:`, hold no user name or password and no fragment, and have no query
76
+ * parameter whose name looks like a credential, such as `token` or `api_key`: a credential goes in `headers`. Plain
77
+ * `http:` is accepted only with `unsafeAllowLoopback`, for a test server on this machine.
78
+ */
79
+ readonly url: string;
80
+ /**
81
+ * Headers sent with every request, such as `Authorization` with a token the host read from its own secret store.
82
+ * Nothing is read from the environment. The values never reach a log line, an error message, the session log or
83
+ * the model. A name the transport sets itself, such as `Host`, `Content-Type` or `Mcp-Session-Id`, is refused.
84
+ */
85
+ readonly headers?: Readonly<Record<string, string>>;
86
+ /**
87
+ * The egress proxy to send every request through, so its allowlist, address checks and log apply. The URL
88
+ * must then be `https:` and its host on the proxy's allowlist. Left out, the harness connects itself, with the
89
+ * address checks that `allowAddresses` describes.
90
+ */
91
+ readonly proxy?: McpEgressFetch;
92
+ /**
93
+ * Address ranges this server may resolve to although they are not public, such as `10.20.0.0/16` for a server on the
94
+ * host's own network. Every other loopback, private, carrier-grade NAT, link-local (with the cloud metadata address
95
+ * `169.254.169.254`), unspecified, multicast or reserved address is refused, and so is an IPv6 address that wraps one.
96
+ * A loopback address is never allowed here; see `unsafeAllowLoopback`. A `/0` range is refused, and so is an IPv6
97
+ * range that holds IPv4 in a wrapped form, such as `::ffff:0:0/96` or `::ffff:10.0.0.0/8`, and a range in brackets.
98
+ * Default none.
99
+ */
100
+ readonly allowAddresses?: readonly string[];
101
+ /**
102
+ * Lets the server be on a loopback address, and over plain `http:` when every address it resolves to is loopback.
103
+ * It exists so a test can serve MCP on `127.0.0.1`; never set it for a real run. Default false.
104
+ */
105
+ readonly unsafeAllowLoopback?: boolean;
106
+ /**
107
+ * Resolves a name to its addresses, in place of the system resolver, such as a test's table. Every address it
108
+ * returns is checked, and the request connects to the first. Ignored with `proxy`, which resolves names itself.
109
+ */
110
+ readonly resolve?: (host: string) => Promise<readonly string[]>;
111
+ /**
112
+ * The certificate authorities to trust for this server instead of the system's, such as a test's own. Certificates
113
+ * are always verified. Ignored with `proxy`, which has its own.
114
+ */
115
+ readonly ca?: string | readonly string[];
116
+ /** The largest JSON body, and the largest server-sent event or line, in bytes. Default 8 MiB. */
117
+ readonly maxMessageBytes?: number;
118
+ /**
119
+ * The most bytes one response stream may carry in all. Default 64 MiB. A long-lived stream past it is cut and opened
120
+ * again; a legacy SSE server's one stream has no such bound.
121
+ */
122
+ readonly maxStreamBytes?: number;
123
+ /** How long a response may take to start: its status line and headers. Default 30,000 ms. */
124
+ readonly headersTimeoutMs?: number;
125
+ /**
126
+ * How long a response stream may go without a byte before it is cut. Default 120,000 ms. A streamable HTTP GET or
127
+ * listen stream that is cut is opened again; a legacy SSE server's one stream is never cut for time.
128
+ */
129
+ readonly streamIdleMs?: number;
130
+ /** How long one response stream may stay open in all before it is cut. Default 3,600,000 ms, an hour; as above. */
131
+ readonly maxStreamMs?: number;
132
+ /** How many responses may be open at once on one connection. A request past it fails. Default 8. */
133
+ readonly maxStreams?: number;
134
+ }
135
+ /**
136
+ * A server reached over MCP's streamable HTTP transport: each message is a `POST`, and the answer is JSON or a
137
+ * server-sent event stream. The era is negotiated as for any other server.
138
+ */
139
+ export interface McpHttpTransport extends McpRemoteSettings {
140
+ readonly kind: "http";
141
+ }
142
+ /**
143
+ * A server reached over the HTTP+SSE transport of the 2024-11-05 revision, which MCP has deprecated since 2025-03-26.
144
+ * It is for legacy servers only: the harness connects in the legacy era without a probe. Its event stream carries every
145
+ * answer and has only the event and line bounds, never a time or total-byte one. When it ends, the connection closes,
146
+ * and nothing reconnects it.
147
+ */
148
+ export interface McpSseTransport extends McpRemoteSettings {
149
+ readonly kind: "sse";
150
+ }
62
151
  /** One MCP server the harness connects to. */
63
152
  export interface McpServerConfig {
64
153
  /**
@@ -66,8 +155,12 @@ export interface McpServerConfig {
66
155
  * and `-`, starting with a letter or digit. Two servers of one harness can't share a name, in any letter case.
67
156
  */
68
157
  readonly name: string;
69
- readonly transport: McpStdioTransport | McpInProcessTransport;
70
- /** How the model reaches the server's tools. Default `deferred`, so a tool is sent only once tool search names it. */
158
+ readonly transport: McpStdioTransport | McpInProcessTransport | McpHttpTransport | McpSseTransport;
159
+ /**
160
+ * How the model reaches the server's tools. Default `deferred`, so a tool is sent only once tool search names it.
161
+ * The first turn waits for a `direct` server, up to the manager's `directWaitMs`; a `direct` server that connects
162
+ * after that wait is registered as `deferred`, so the tools a request sends never change because a server was slow.
163
+ */
71
164
  readonly exposure?: ToolExposure;
72
165
  /** How long the start and the handshake may take, the probe included. Default 30,000 ms. */
73
166
  readonly connectTimeoutMs?: number;
@@ -124,11 +217,37 @@ export interface McpConnection {
124
217
  * asked for input, which this harness does not supply.
125
218
  */
126
219
  callTool(name: string, args: unknown, signal: AbortSignal): Promise<McpCallResult>;
127
- /** The newest bytes the server wrote to standard error, for the host's diagnostics. Empty for an in-process server. */
220
+ /** The newest bytes the server wrote to standard error, for the host's diagnostics. Empty for other transports. */
128
221
  stderr(): string;
222
+ /**
223
+ * Calls `listener` each time the server says its tool list changed: by `notifications/tools/list_changed` from a
224
+ * legacy server, or on the `subscriptions/listen` stream that a 2026-07-28 server with `tools.listChanged` opens.
225
+ * The listener is told nothing else, so it reads the list again itself. Returns a function that removes it.
226
+ */
227
+ watchTools(listener: () => void): () => void;
129
228
  /** Ends the connection and, for a stdio server, its process group. Calling it again does nothing. */
130
229
  close(): Promise<void>;
131
230
  }
231
+ /** The timers the MCP client waits with, so a test can run its waits on a clock of its own. */
232
+ export interface McpTimers {
233
+ /** Calls `run` once after `ms` milliseconds, and returns a handle for `clearTimeout`. */
234
+ setTimeout(run: () => void, ms: number): unknown;
235
+ /** Cancels a timer `setTimeout` returned, if it has not run yet. */
236
+ clearTimeout(handle: unknown): void;
237
+ /** The time now, in milliseconds. */
238
+ now(): number;
239
+ }
240
+ /**
241
+ * Where the approved definitions of each server's tools are kept: for each server, its tool names and the hash of each
242
+ * one's definition. `fileMcpPinStore()` from `@buildanagent/harness/extensions/node` keeps them in a project's
243
+ * `extensions.lock.json`.
244
+ */
245
+ export interface McpPinStore {
246
+ /** The pins of one server, by tool name, or `undefined` when it has none yet. */
247
+ read(server: string): Promise<Readonly<Record<string, string>> | undefined>;
248
+ /** Replaces the pins of one server. */
249
+ write(server: string, pins: Readonly<Record<string, string>>): Promise<void>;
250
+ }
132
251
  /** What `createMcpManager()` takes. */
133
252
  export interface McpManagerOptions {
134
253
  readonly servers: readonly McpServerConfig[];
@@ -138,6 +257,33 @@ export interface McpManagerOptions {
138
257
  readonly mcp?: boolean;
139
258
  /** Told of events a host may want to see, such as a server's notice that its tool list changed. */
140
259
  readonly log?: (line: string) => void;
260
+ /**
261
+ * The approved tool definitions. With a store, a tool whose definition has no pin, or a different one, starts
262
+ * disabled until `approve()`, and a server the store holds nothing for has every tool disabled. Without one, each
263
+ * server's tools as listed at connect are its pins for the life of the manager.
264
+ */
265
+ readonly pins?: McpPinStore;
266
+ /** How long the first turn waits for the `direct` servers to connect. Default 10,000 ms. */
267
+ readonly directWaitMs?: number;
268
+ /** The shortest time between two reads of one server's tool list after it says the list changed. Default 2,000 ms. */
269
+ readonly relistIntervalMs?: number;
270
+ /** The timers of the first turn's wait, the re-reads and the stream re-opens. Default the platform's own. */
271
+ readonly timers?: McpTimers;
272
+ }
273
+ /** How a server's current definition of a tool compares with its pin. */
274
+ export type McpToolState = "unchanged" | "new" | "changed" | "removed";
275
+ /** A tool whose current definition has no matching pin, so it waits for a person's approval. */
276
+ export interface McpPendingTool {
277
+ readonly server: string;
278
+ /** The tool's name on its server, which is the server's text: show it as data. */
279
+ readonly tool: string;
280
+ /** Its canonical name, when it is registered in this session. A tool a server added mid-session is not. */
281
+ readonly canonicalName?: string;
282
+ readonly state: "new" | "changed";
283
+ /** The hash of the definition a person would approve, for `approve()`. */
284
+ readonly hash: string;
285
+ /** The definition as the server sent it, for a person to read before approving. None of it is trusted. */
286
+ readonly definition: McpTool;
141
287
  }
142
288
  /** How one server's connection went. */
143
289
  export type McpServerStatus = {
@@ -146,19 +292,63 @@ export type McpServerStatus = {
146
292
  readonly era: McpEra;
147
293
  /** The canonical names of the tools registered for it, in its order. */
148
294
  readonly tools: readonly string[];
295
+ /** The canonical names of those tools that start disabled, because no pin matches their definition. */
296
+ readonly disabled: readonly string[];
149
297
  } | {
150
298
  readonly server: string;
151
299
  readonly status: "failed";
152
300
  readonly error: Error;
153
301
  };
154
302
  /** The MCP client as one removable component: it connects the servers and registers their tools. */
155
- export interface McpManager {
303
+ export interface McpManager extends TurnBoundary {
156
304
  /**
157
- * Connects every server at once and registers each one's tools, and resolves with a status per server, in config
158
- * order. A server that fails is reported and closed, and the others still connect. Calling it again returns the same
159
- * result. With `mcp: false` it resolves with an empty list.
305
+ * Connects every server at once, registers each one's tools as soon as it connects, and resolves with a status per
306
+ * server, in config order, once all have connected or failed. Call it before a session's first turn, never while a
307
+ * turn runs; to connect in the background instead, use `start()`. A server that fails is reported and closed, and the
308
+ * others still connect. Calling it again returns the same result. With `mcp: false` it resolves with an empty list.
160
309
  */
161
310
  connect(): Promise<readonly McpServerStatus[]>;
311
+ /**
312
+ * Starts connecting every server in the background and returns at once. A server's tools are registered at the start
313
+ * of the first turn after it connects, through `beginTurn()`, which the runner calls when the manager is in
314
+ * `HarnessOptions.turnBoundaries`. Each server connects once; one that fails stays failed.
315
+ */
316
+ start(): void;
317
+ /**
318
+ * The status of every server now, in config order: `connecting` until its tools are registered or it has failed.
319
+ */
320
+ statuses(): readonly (McpServerStatus | {
321
+ readonly server: string;
322
+ readonly status: "connecting";
323
+ })[];
324
+ /**
325
+ * Waits for the `direct` servers, once, up to `directWaitMs`, then registers every server that has connected, sets
326
+ * which tools may run this turn and returns a notice for what changed since the last turn. A tool may run when its
327
+ * server's current definition matches its pin; a new, changed or removed one is disabled. The `tools` a request sends
328
+ * stay as they were built: a tool a server adds mid-session is announced by count and joins a later session.
329
+ */
330
+ beginTurn(signal?: AbortSignal): Promise<readonly string[]>;
331
+ /**
332
+ * Marks the last `beginTurn()`'s notice as told. The runner calls it once the turn has written the notice; until
333
+ * then, the next `beginTurn()` announces the same changes again, so a turn that fails before its input is written
334
+ * loses no notice.
335
+ */
336
+ commitNotices(): void;
337
+ /** The tools that wait for a person: those whose current definition has no matching pin. */
338
+ pending(): readonly McpPendingTool[];
339
+ /**
340
+ * Records a person's approval of one tool's definition, by the hash `pending()` gave, and writes it to the pin store.
341
+ * The tool may run from the next turn on. Throws a `HarnessError`, code `invalid_mcp_config`, when the server's
342
+ * current definition has another hash, so an approval never covers a definition the person did not see. A store
343
+ * write that fails rejects, and the approval is not held.
344
+ */
345
+ approve(server: string, tool: string, hash: string): Promise<void>;
346
+ /**
347
+ * A permission hook that denies a call to a disabled tool of these servers before anything else decides, so a sticky
348
+ * allowance, an allow rule or `bypass` can't run it. Put it in the pipeline's `hooks`. A tool's own `execute` refuses
349
+ * a disabled call too, so the server is never reached without the hook either.
350
+ */
351
+ permissionHook(): PermissionHook;
162
352
  /**
163
353
  * One `extension_loaded` record of tier `mcp` per connected server, in config order, for
164
354
  * `HarnessOptions.extensionRecords`. A turn then writes an entry for each record its session's log does not hold yet. A server that failed to connect
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/mcp/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The types of `@buildanagent/harness/mcp`. The registry and the rest of the harness see these and never the MCP client\n * library, so the library can change without touching them (ADR 0021).\n */\nimport type { ModelContent } from \"@buildanagent/gateway\";\nimport type { ExtensionLoadedRecord } from \"../extensions/types.js\";\nimport type { ToolExposure, ToolRegistry } from \"../tools/types.js\";\n\n/** The protocol era a server speaks: the 2026-07-28 revision, or `legacy` for the 2025 revisions and their `initialize`. */\nexport type McpEra = \"2026-07-28\" | \"legacy\";\n\n/**\n * A server the harness starts as a child process and speaks to over its standard input and output, one JSON message\n * per line. The child gets `spawnEnv()`'s environment (`PATH`, a fresh temp `HOME`, `TMPDIR` and `LANG`) plus what\n * `env` and `setEnv` declare, and nothing else from the parent.\n */\nexport interface McpStdioTransport {\n readonly kind: \"stdio\";\n /** The program to run, found on the child's `PATH` unless it is a path. It runs without a shell. */\n readonly command: string;\n readonly args?: readonly string[];\n /** The folder the server starts in. Default the harness's own working folder. */\n readonly cwd?: string;\n /**\n * Parent variables the server may read, by name, such as `DOCKER_HOST`. `spawnEnv()`'s rules apply: a name that looks\n * like a credential, such as `GITHUB_TOKEN`, is refused here and goes in `setEnv` with a value the host supplies.\n */\n readonly env?: readonly string[];\n /** Variables set to these values, such as a token the host read from its own secret store. */\n readonly setEnv?: Readonly<Record<string, string>>;\n /** The longest line the server may write, in bytes. A longer one closes the connection. Default 8 MiB. */\n readonly maxLineBytes?: number;\n /** How much of the server's standard error is kept, the newest bytes. It never reaches the model. Default 64 KiB. */\n readonly maxStderrBytes?: number;\n /**\n * How long a closing server has to exit after its input ends, and again after a `SIGTERM`, before its process group\n * is killed. Default 2,000 ms.\n */\n readonly closeGraceMs?: number;\n}\n\n/**\n * A message channel to a server in this process, such as an `InMemoryTransport` from `@modelcontextprotocol/server`.\n * Its shape is the MCP SDK's transport, so that SDK's own transports fit it. Messages are JSON-RPC objects.\n */\nexport interface McpChannel {\n /** Opens the channel. The client calls it once, after it has set the three handlers. */\n start(): Promise<void>;\n /** Sends one message to the server. */\n send(message: object): Promise<void>;\n /** Closes the channel, and calls `onclose`. */\n close(): Promise<void>;\n /** Set by the client: called with each message the server sends. */\n onmessage?: ((message: object) => void) | undefined;\n /** Set by the client: called once when the channel closes, whoever closed it. */\n onclose?: (() => void) | undefined;\n /** Set by the client: called with a problem that does not close the channel. */\n onerror?: ((error: Error) => void) | undefined;\n}\n\n/** A server in this process, reached through a channel the host built. */\nexport interface McpInProcessTransport {\n readonly kind: \"in_process\";\n readonly channel: McpChannel;\n}\n\n/** One MCP server the harness connects to. */\nexport interface McpServerConfig {\n /**\n * The server's name in its tools' canonical names, `mcp__<name>__<tool>`: 1 to 32 characters from `A-Z`, `a-z`, `0-9`\n * and `-`, starting with a letter or digit. Two servers of one harness can't share a name, in any letter case.\n */\n readonly name: string;\n readonly transport: McpStdioTransport | McpInProcessTransport;\n /** How the model reaches the server's tools. Default `deferred`, so a tool is sent only once tool search names it. */\n readonly exposure?: ToolExposure;\n /** How long the start and the handshake may take, the probe included. Default 30,000 ms. */\n readonly connectTimeoutMs?: number;\n /**\n * How long the `server/discover` probe waits before it treats the server as legacy and sends `initialize`. Default\n * 5,000 ms.\n */\n readonly probeTimeoutMs?: number;\n /** How long one request, such as a tool call, may wait for its answer. Default 60,000 ms. */\n readonly requestTimeoutMs?: number;\n /** The most tools the server may list. A longer list is refused, and none of its tools is registered. Default 256. */\n readonly maxTools?: number;\n}\n\n/**\n * A tool as a server lists it. Every field is what the server says, so none of it is trusted: the name and\n * description reach the model only as data, and `annotations` change nothing the harness does.\n */\nexport interface McpTool {\n /** The tool's name on its server. */\n readonly name: string;\n /** The server's description, cut to 4,096 characters. */\n readonly description: string;\n /**\n * The tool's input schema as the server sent it. The registered tool's schema leaves out `pattern`,\n * `patternProperties` and `format`, so the harness never runs a server's regular expression.\n */\n readonly inputSchema: Readonly<Record<string, unknown>>;\n /** The server's hints, such as `readOnlyHint`, kept for display only. */\n readonly annotations?: Readonly<Record<string, unknown>>;\n}\n\n/** What one tool call returned. `content` is what the model reads; `isError` is the server's own failure flag. */\nexport interface McpCallResult {\n readonly content: readonly ModelContent[];\n readonly isError: boolean;\n}\n\n/** One connected server. */\nexport interface McpConnection {\n /** The server's name from its config. */\n readonly server: string;\n /** The era the server negotiated: `2026-07-28` when it answered the `server/discover` probe, `legacy` otherwise. */\n readonly era: McpEra;\n /** The protocol revision negotiated, such as `2026-07-28` or `2025-11-25`. */\n readonly protocolVersion: string;\n /** True once the connection has closed, by `close()` or because the server ended it. */\n readonly closed: boolean;\n /**\n * The server's tools, checked: at most `maxTools`, each with a usable name and schema, and no two whose names match\n * once normalised. Throws an `McpError`, code `mcp_tool_list_refused`, for a list that fails a check.\n */\n listTools(): Promise<readonly McpTool[]>;\n /**\n * Calls one tool by its name on the server. Throws an `McpError`, code `mcp_call_failed`, when the call ends with no\n * result: the server closed or answered with an error, the request timed out or `signal` aborted it, or the server\n * asked for input, which this harness does not supply.\n */\n callTool(name: string, args: unknown, signal: AbortSignal): Promise<McpCallResult>;\n /** The newest bytes the server wrote to standard error, for the host's diagnostics. Empty for an in-process server. */\n stderr(): string;\n /** Ends the connection and, for a stdio server, its process group. Calling it again does nothing. */\n close(): Promise<void>;\n}\n\n/** What `createMcpManager()` takes. */\nexport interface McpManagerOptions {\n readonly servers: readonly McpServerConfig[];\n /** Where the servers' tools are registered, under the source `mcp:<name>`. */\n readonly registry: ToolRegistry;\n /** `false` switches MCP off: `connect()` starts no server and registers nothing. Default true. */\n readonly mcp?: boolean;\n /** Told of events a host may want to see, such as a server's notice that its tool list changed. */\n readonly log?: (line: string) => void;\n}\n\n/** How one server's connection went. */\nexport type McpServerStatus =\n | {\n readonly server: string;\n readonly status: \"connected\";\n readonly era: McpEra;\n /** The canonical names of the tools registered for it, in its order. */\n readonly tools: readonly string[];\n }\n | { readonly server: string; readonly status: \"failed\"; readonly error: Error };\n\n/** The MCP client as one removable component: it connects the servers and registers their tools. */\nexport interface McpManager {\n /**\n * Connects every server at once and registers each one's tools, and resolves with a status per server, in config\n * order. A server that fails is reported and closed, and the others still connect. Calling it again returns the same\n * result. With `mcp: false` it resolves with an empty list.\n */\n connect(): Promise<readonly McpServerStatus[]>;\n /**\n * One `extension_loaded` record of tier `mcp` per connected server, in config order, for\n * `HarnessOptions.extensionRecords`. A turn then writes an entry for each record its session's log does not hold yet. A server that failed to connect\n * has no record: its status says why, and nothing of it ran in a turn.\n */\n records(): readonly ExtensionLoadedRecord[];\n /** The connection of a connected server, by name. */\n connection(server: string): McpConnection | undefined;\n /** Closes every connection and ends every server process. A tool of a closed server fails when called. */\n close(): Promise<void>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/mcp/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The types of `@buildanagent/harness/mcp`. The registry and the rest of the harness see these and never the MCP client\n * library, so the library can change without touching them (ADR 0021).\n */\nimport type { ModelContent } from \"@buildanagent/gateway\";\nimport type { ExtensionLoadedRecord } from \"../extensions/types.js\";\nimport type { PermissionHook } from \"../permissions/types.js\";\nimport type { ToolExposure, ToolRegistry, TurnBoundary } from \"../tools/types.js\";\n\n/** The protocol era a server speaks: the 2026-07-28 revision, or `legacy` for the 2025 revisions and their `initialize`. */\nexport type McpEra = \"2026-07-28\" | \"legacy\";\n\n/**\n * A server the harness starts as a child process and speaks to over its standard input and output, one JSON message\n * per line. The child gets `spawnEnv()`'s environment (`PATH`, a fresh temp `HOME`, `TMPDIR` and `LANG`) plus what\n * `env` and `setEnv` declare, and nothing else from the parent.\n */\nexport interface McpStdioTransport {\n readonly kind: \"stdio\";\n /** The program to run, found on the child's `PATH` unless it is a path. It runs without a shell. */\n readonly command: string;\n readonly args?: readonly string[];\n /** The folder the server starts in. Default the harness's own working folder. */\n readonly cwd?: string;\n /**\n * Parent variables the server may read, by name, such as `DOCKER_HOST`. `spawnEnv()`'s rules apply: a name that looks\n * like a credential, such as `GITHUB_TOKEN`, is refused here and goes in `setEnv` with a value the host supplies.\n */\n readonly env?: readonly string[];\n /** Variables set to these values, such as a token the host read from its own secret store. */\n readonly setEnv?: Readonly<Record<string, string>>;\n /** The longest line the server may write, in bytes. A longer one closes the connection. Default 8 MiB. */\n readonly maxLineBytes?: number;\n /** How much of the server's standard error is kept, the newest bytes. It never reaches the model. Default 64 KiB. */\n readonly maxStderrBytes?: number;\n /**\n * How long a closing server has to exit after its input ends, and again after a `SIGTERM`, before its process group\n * is killed. Default 2,000 ms.\n */\n readonly closeGraceMs?: number;\n}\n\n/**\n * A message channel to a server in this process, such as an `InMemoryTransport` from `@modelcontextprotocol/server`.\n * Its shape is the MCP SDK's transport, so that SDK's own transports fit it. Messages are JSON-RPC objects.\n */\nexport interface McpChannel {\n /** Opens the channel. The client calls it once, after it has set the three handlers. */\n start(): Promise<void>;\n /** Sends one message to the server. */\n send(message: object): Promise<void>;\n /** Closes the channel, and calls `onclose`. */\n close(): Promise<void>;\n /** Set by the client: called with each message the server sends. */\n onmessage?: ((message: object) => void) | undefined;\n /** Set by the client: called once when the channel closes, whoever closed it. */\n onclose?: (() => void) | undefined;\n /** Set by the client: called with a problem that does not close the channel. */\n onerror?: ((error: Error) => void) | undefined;\n}\n\n/** A server in this process, reached through a channel the host built. */\nexport interface McpInProcessTransport {\n readonly kind: \"in_process\";\n readonly channel: McpChannel;\n}\n\n/** The part of an egress proxy a remote server's requests go through: `startEgressProxy()` returns one. */\nexport interface McpEgressFetch {\n /** Sends one request under the proxy's allowlist and resolves with its response. */\n fetch(input: string | URL, init?: RequestInit): Promise<Response>;\n}\n\n/**\n * The settings a remote server shares, over streamable HTTP or legacy SSE. A remote server is untrusted code on\n * another machine, and the harness reaches it with its own network identity, so the URL, every address it resolves to\n * and every byte that comes back are checked.\n */\nexport interface McpRemoteSettings {\n /**\n * The server's endpoint. It must be `https:`, hold no user name or password and no fragment, and have no query\n * parameter whose name looks like a credential, such as `token` or `api_key`: a credential goes in `headers`. Plain\n * `http:` is accepted only with `unsafeAllowLoopback`, for a test server on this machine.\n */\n readonly url: string;\n /**\n * Headers sent with every request, such as `Authorization` with a token the host read from its own secret store.\n * Nothing is read from the environment. The values never reach a log line, an error message, the session log or\n * the model. A name the transport sets itself, such as `Host`, `Content-Type` or `Mcp-Session-Id`, is refused.\n */\n readonly headers?: Readonly<Record<string, string>>;\n /**\n * The egress proxy to send every request through, so its allowlist, address checks and log apply. The URL\n * must then be `https:` and its host on the proxy's allowlist. Left out, the harness connects itself, with the\n * address checks that `allowAddresses` describes.\n */\n readonly proxy?: McpEgressFetch;\n /**\n * Address ranges this server may resolve to although they are not public, such as `10.20.0.0/16` for a server on the\n * host's own network. Every other loopback, private, carrier-grade NAT, link-local (with the cloud metadata address\n * `169.254.169.254`), unspecified, multicast or reserved address is refused, and so is an IPv6 address that wraps one.\n * A loopback address is never allowed here; see `unsafeAllowLoopback`. A `/0` range is refused, and so is an IPv6\n * range that holds IPv4 in a wrapped form, such as `::ffff:0:0/96` or `::ffff:10.0.0.0/8`, and a range in brackets.\n * Default none.\n */\n readonly allowAddresses?: readonly string[];\n /**\n * Lets the server be on a loopback address, and over plain `http:` when every address it resolves to is loopback.\n * It exists so a test can serve MCP on `127.0.0.1`; never set it for a real run. Default false.\n */\n readonly unsafeAllowLoopback?: boolean;\n /**\n * Resolves a name to its addresses, in place of the system resolver, such as a test's table. Every address it\n * returns is checked, and the request connects to the first. Ignored with `proxy`, which resolves names itself.\n */\n readonly resolve?: (host: string) => Promise<readonly string[]>;\n /**\n * The certificate authorities to trust for this server instead of the system's, such as a test's own. Certificates\n * are always verified. Ignored with `proxy`, which has its own.\n */\n readonly ca?: string | readonly string[];\n /** The largest JSON body, and the largest server-sent event or line, in bytes. Default 8 MiB. */\n readonly maxMessageBytes?: number;\n /**\n * The most bytes one response stream may carry in all. Default 64 MiB. A long-lived stream past it is cut and opened\n * again; a legacy SSE server's one stream has no such bound.\n */\n readonly maxStreamBytes?: number;\n /** How long a response may take to start: its status line and headers. Default 30,000 ms. */\n readonly headersTimeoutMs?: number;\n /**\n * How long a response stream may go without a byte before it is cut. Default 120,000 ms. A streamable HTTP GET or\n * listen stream that is cut is opened again; a legacy SSE server's one stream is never cut for time.\n */\n readonly streamIdleMs?: number;\n /** How long one response stream may stay open in all before it is cut. Default 3,600,000 ms, an hour; as above. */\n readonly maxStreamMs?: number;\n /** How many responses may be open at once on one connection. A request past it fails. Default 8. */\n readonly maxStreams?: number;\n}\n\n/**\n * A server reached over MCP's streamable HTTP transport: each message is a `POST`, and the answer is JSON or a\n * server-sent event stream. The era is negotiated as for any other server.\n */\nexport interface McpHttpTransport extends McpRemoteSettings {\n readonly kind: \"http\";\n}\n\n/**\n * A server reached over the HTTP+SSE transport of the 2024-11-05 revision, which MCP has deprecated since 2025-03-26.\n * It is for legacy servers only: the harness connects in the legacy era without a probe. Its event stream carries every\n * answer and has only the event and line bounds, never a time or total-byte one. When it ends, the connection closes,\n * and nothing reconnects it.\n */\nexport interface McpSseTransport extends McpRemoteSettings {\n readonly kind: \"sse\";\n}\n\n/** One MCP server the harness connects to. */\nexport interface McpServerConfig {\n /**\n * The server's name in its tools' canonical names, `mcp__<name>__<tool>`: 1 to 32 characters from `A-Z`, `a-z`, `0-9`\n * and `-`, starting with a letter or digit. Two servers of one harness can't share a name, in any letter case.\n */\n readonly name: string;\n readonly transport: McpStdioTransport | McpInProcessTransport | McpHttpTransport | McpSseTransport;\n /**\n * How the model reaches the server's tools. Default `deferred`, so a tool is sent only once tool search names it.\n * The first turn waits for a `direct` server, up to the manager's `directWaitMs`; a `direct` server that connects\n * after that wait is registered as `deferred`, so the tools a request sends never change because a server was slow.\n */\n readonly exposure?: ToolExposure;\n /** How long the start and the handshake may take, the probe included. Default 30,000 ms. */\n readonly connectTimeoutMs?: number;\n /**\n * How long the `server/discover` probe waits before it treats the server as legacy and sends `initialize`. Default\n * 5,000 ms.\n */\n readonly probeTimeoutMs?: number;\n /** How long one request, such as a tool call, may wait for its answer. Default 60,000 ms. */\n readonly requestTimeoutMs?: number;\n /** The most tools the server may list. A longer list is refused, and none of its tools is registered. Default 256. */\n readonly maxTools?: number;\n}\n\n/**\n * A tool as a server lists it. Every field is what the server says, so none of it is trusted: the name and\n * description reach the model only as data, and `annotations` change nothing the harness does.\n */\nexport interface McpTool {\n /** The tool's name on its server. */\n readonly name: string;\n /** The server's description, cut to 4,096 characters. */\n readonly description: string;\n /**\n * The tool's input schema as the server sent it. The registered tool's schema leaves out `pattern`,\n * `patternProperties` and `format`, so the harness never runs a server's regular expression.\n */\n readonly inputSchema: Readonly<Record<string, unknown>>;\n /** The server's hints, such as `readOnlyHint`, kept for display only. */\n readonly annotations?: Readonly<Record<string, unknown>>;\n}\n\n/** What one tool call returned. `content` is what the model reads; `isError` is the server's own failure flag. */\nexport interface McpCallResult {\n readonly content: readonly ModelContent[];\n readonly isError: boolean;\n}\n\n/** One connected server. */\nexport interface McpConnection {\n /** The server's name from its config. */\n readonly server: string;\n /** The era the server negotiated: `2026-07-28` when it answered the `server/discover` probe, `legacy` otherwise. */\n readonly era: McpEra;\n /** The protocol revision negotiated, such as `2026-07-28` or `2025-11-25`. */\n readonly protocolVersion: string;\n /** True once the connection has closed, by `close()` or because the server ended it. */\n readonly closed: boolean;\n /**\n * The server's tools, checked: at most `maxTools`, each with a usable name and schema, and no two whose names match\n * once normalised. Throws an `McpError`, code `mcp_tool_list_refused`, for a list that fails a check.\n */\n listTools(): Promise<readonly McpTool[]>;\n /**\n * Calls one tool by its name on the server. Throws an `McpError`, code `mcp_call_failed`, when the call ends with no\n * result: the server closed or answered with an error, the request timed out or `signal` aborted it, or the server\n * asked for input, which this harness does not supply.\n */\n callTool(name: string, args: unknown, signal: AbortSignal): Promise<McpCallResult>;\n /** The newest bytes the server wrote to standard error, for the host's diagnostics. Empty for other transports. */\n stderr(): string;\n /**\n * Calls `listener` each time the server says its tool list changed: by `notifications/tools/list_changed` from a\n * legacy server, or on the `subscriptions/listen` stream that a 2026-07-28 server with `tools.listChanged` opens.\n * The listener is told nothing else, so it reads the list again itself. Returns a function that removes it.\n */\n watchTools(listener: () => void): () => void;\n /** Ends the connection and, for a stdio server, its process group. Calling it again does nothing. */\n close(): Promise<void>;\n}\n\n/** The timers the MCP client waits with, so a test can run its waits on a clock of its own. */\nexport interface McpTimers {\n /** Calls `run` once after `ms` milliseconds, and returns a handle for `clearTimeout`. */\n setTimeout(run: () => void, ms: number): unknown;\n /** Cancels a timer `setTimeout` returned, if it has not run yet. */\n clearTimeout(handle: unknown): void;\n /** The time now, in milliseconds. */\n now(): number;\n}\n\n/**\n * Where the approved definitions of each server's tools are kept: for each server, its tool names and the hash of each\n * one's definition. `fileMcpPinStore()` from `@buildanagent/harness/extensions/node` keeps them in a project's\n * `extensions.lock.json`.\n */\nexport interface McpPinStore {\n /** The pins of one server, by tool name, or `undefined` when it has none yet. */\n read(server: string): Promise<Readonly<Record<string, string>> | undefined>;\n /** Replaces the pins of one server. */\n write(server: string, pins: Readonly<Record<string, string>>): Promise<void>;\n}\n\n/** What `createMcpManager()` takes. */\nexport interface McpManagerOptions {\n readonly servers: readonly McpServerConfig[];\n /** Where the servers' tools are registered, under the source `mcp:<name>`. */\n readonly registry: ToolRegistry;\n /** `false` switches MCP off: `connect()` starts no server and registers nothing. Default true. */\n readonly mcp?: boolean;\n /** Told of events a host may want to see, such as a server's notice that its tool list changed. */\n readonly log?: (line: string) => void;\n /**\n * The approved tool definitions. With a store, a tool whose definition has no pin, or a different one, starts\n * disabled until `approve()`, and a server the store holds nothing for has every tool disabled. Without one, each\n * server's tools as listed at connect are its pins for the life of the manager.\n */\n readonly pins?: McpPinStore;\n /** How long the first turn waits for the `direct` servers to connect. Default 10,000 ms. */\n readonly directWaitMs?: number;\n /** The shortest time between two reads of one server's tool list after it says the list changed. Default 2,000 ms. */\n readonly relistIntervalMs?: number;\n /** The timers of the first turn's wait, the re-reads and the stream re-opens. Default the platform's own. */\n readonly timers?: McpTimers;\n}\n\n/** How a server's current definition of a tool compares with its pin. */\nexport type McpToolState = \"unchanged\" | \"new\" | \"changed\" | \"removed\";\n\n/** A tool whose current definition has no matching pin, so it waits for a person's approval. */\nexport interface McpPendingTool {\n readonly server: string;\n /** The tool's name on its server, which is the server's text: show it as data. */\n readonly tool: string;\n /** Its canonical name, when it is registered in this session. A tool a server added mid-session is not. */\n readonly canonicalName?: string;\n readonly state: \"new\" | \"changed\";\n /** The hash of the definition a person would approve, for `approve()`. */\n readonly hash: string;\n /** The definition as the server sent it, for a person to read before approving. None of it is trusted. */\n readonly definition: McpTool;\n}\n\n/** How one server's connection went. */\nexport type McpServerStatus =\n | {\n readonly server: string;\n readonly status: \"connected\";\n readonly era: McpEra;\n /** The canonical names of the tools registered for it, in its order. */\n readonly tools: readonly string[];\n /** The canonical names of those tools that start disabled, because no pin matches their definition. */\n readonly disabled: readonly string[];\n }\n | { readonly server: string; readonly status: \"failed\"; readonly error: Error };\n\n/** The MCP client as one removable component: it connects the servers and registers their tools. */\nexport interface McpManager extends TurnBoundary {\n /**\n * Connects every server at once, registers each one's tools as soon as it connects, and resolves with a status per\n * server, in config order, once all have connected or failed. Call it before a session's first turn, never while a\n * turn runs; to connect in the background instead, use `start()`. A server that fails is reported and closed, and the\n * others still connect. Calling it again returns the same result. With `mcp: false` it resolves with an empty list.\n */\n connect(): Promise<readonly McpServerStatus[]>;\n /**\n * Starts connecting every server in the background and returns at once. A server's tools are registered at the start\n * of the first turn after it connects, through `beginTurn()`, which the runner calls when the manager is in\n * `HarnessOptions.turnBoundaries`. Each server connects once; one that fails stays failed.\n */\n start(): void;\n /**\n * The status of every server now, in config order: `connecting` until its tools are registered or it has failed.\n */\n statuses(): readonly (McpServerStatus | { readonly server: string; readonly status: \"connecting\" })[];\n /**\n * Waits for the `direct` servers, once, up to `directWaitMs`, then registers every server that has connected, sets\n * which tools may run this turn and returns a notice for what changed since the last turn. A tool may run when its\n * server's current definition matches its pin; a new, changed or removed one is disabled. The `tools` a request sends\n * stay as they were built: a tool a server adds mid-session is announced by count and joins a later session.\n */\n beginTurn(signal?: AbortSignal): Promise<readonly string[]>;\n /**\n * Marks the last `beginTurn()`'s notice as told. The runner calls it once the turn has written the notice; until\n * then, the next `beginTurn()` announces the same changes again, so a turn that fails before its input is written\n * loses no notice.\n */\n commitNotices(): void;\n /** The tools that wait for a person: those whose current definition has no matching pin. */\n pending(): readonly McpPendingTool[];\n /**\n * Records a person's approval of one tool's definition, by the hash `pending()` gave, and writes it to the pin store.\n * The tool may run from the next turn on. Throws a `HarnessError`, code `invalid_mcp_config`, when the server's\n * current definition has another hash, so an approval never covers a definition the person did not see. A store\n * write that fails rejects, and the approval is not held.\n */\n approve(server: string, tool: string, hash: string): Promise<void>;\n /**\n * A permission hook that denies a call to a disabled tool of these servers before anything else decides, so a sticky\n * allowance, an allow rule or `bypass` can't run it. Put it in the pipeline's `hooks`. A tool's own `execute` refuses\n * a disabled call too, so the server is never reached without the hook either.\n */\n permissionHook(): PermissionHook;\n /**\n * One `extension_loaded` record of tier `mcp` per connected server, in config order, for\n * `HarnessOptions.extensionRecords`. A turn then writes an entry for each record its session's log does not hold yet. A server that failed to connect\n * has no record: its status says why, and nothing of it ran in a turn.\n */\n records(): readonly ExtensionLoadedRecord[];\n /** The connection of a connected server, by name. */\n connection(server: string): McpConnection | undefined;\n /** Closes every connection and ends every server process. A tool of a closed server fails when called. */\n close(): Promise<void>;\n}\n"]}
@@ -1285,7 +1285,7 @@
1285
1285
  "$ref": "#/$defs/shape-edc9ba2d47"
1286
1286
  },
1287
1287
  {
1288
- "$ref": "#/$defs/shape-bd3038f936"
1288
+ "$ref": "#/$defs/shape-e3591bd29a"
1289
1289
  },
1290
1290
  {
1291
1291
  "$ref": "#/$defs/shape-16c3a65781"
@@ -2193,7 +2193,7 @@
2193
2193
  "required": ["id", "parentId", "seq", "timestamp", "origin", "type", "name", "path"],
2194
2194
  "additionalProperties": false
2195
2195
  },
2196
- "shape-bd3038f936": {
2196
+ "shape-e3591bd29a": {
2197
2197
  "type": "object",
2198
2198
  "properties": {
2199
2199
  "id": {
@@ -2230,11 +2230,14 @@
2230
2230
  "properties": {
2231
2231
  "transport": {
2232
2232
  "type": "string",
2233
- "enum": ["stdio", "in_process"]
2233
+ "enum": ["stdio", "in_process", "http", "sse"]
2234
2234
  },
2235
2235
  "commandHash": {
2236
2236
  "type": "string"
2237
2237
  },
2238
+ "urlHash": {
2239
+ "type": "string"
2240
+ },
2238
2241
  "era": {
2239
2242
  "type": "string",
2240
2243
  "enum": ["2026-07-28", "legacy"]
@@ -137,11 +137,17 @@ async function recordLoadout(harness, writer, model, tools, started) {
137
137
  await writer.write("harness", { ...record, type: "extension_loaded" });
138
138
  }
139
139
  }
140
- async function writeInput(writer, options, newId) {
140
+ async function writeInput(writer, options, newId, notices = []) {
141
141
  const blocks = typeof options.input === "string" ? [{ type: "text", text: options.input }] : options.input;
142
142
  const messageId = newId();
143
- for (const [index, block] of blocks.entries()) {
144
- await writer.write(options.inputOrigin ?? "user", {
143
+ // A boundary's notice goes first, in the same user message, with the harness as its origin: the gateway's transcript
144
+ // has no system role, so this is how an append-only log tells the model that tools changed (HD3).
145
+ const all = [
146
+ ...notices.map((text) => ({ origin: "harness", block: { type: "text", text } })),
147
+ ...blocks.map((block) => ({ origin: options.inputOrigin ?? "user", block })),
148
+ ];
149
+ for (const [index, { origin, block }] of all.entries()) {
150
+ await writer.write(origin, {
145
151
  type: "message_block",
146
152
  messageId,
147
153
  role: "user",
@@ -151,6 +157,24 @@ async function writeInput(writer, options, newId) {
151
157
  });
152
158
  }
153
159
  }
160
+ /** The turn's input with the boundaries' notices in front, as the log holds it. */
161
+ function withNotices(input, notices) {
162
+ if (notices.length === 0)
163
+ return input;
164
+ const blocks = typeof input === "string" ? [{ type: "text", text: input }] : input;
165
+ return [...notices.map((text) => ({ type: "text", text })), ...blocks];
166
+ }
167
+ /** Runs every turn boundary in order and gathers their notices, before the turn builds its tools. */
168
+ async function crossBoundaries(harness, signal) {
169
+ const notices = [];
170
+ for (const boundary of harness.turnBoundaries ?? []) {
171
+ for (const notice of await boundary.beginTurn(signal)) {
172
+ if (typeof notice === "string" && notice !== "")
173
+ notices.push(notice);
174
+ }
175
+ }
176
+ return notices;
177
+ }
154
178
  /** Turns the run's events into entries. It keeps the last model message back until the next event shows it was kept. */
155
179
  class EventRecorder {
156
180
  #writer;
@@ -467,8 +491,11 @@ async function recordCompletion(session, settings, start, options, result) {
467
491
  async function runTurnOnce(session, harness, options) {
468
492
  const model = options.model ?? harness.model;
469
493
  const system = options.system ?? harness.system;
470
- const tools = toolsOf(harness, options);
471
494
  const { signal, newId, writer } = turnPlumbing(session, options);
495
+ // Tools change only here, between turns: a boundary registers what arrived since the last turn before the tools
496
+ // are built, so nothing it does lands inside the run.
497
+ const notices = await crossBoundaries(harness, signal);
498
+ const tools = toolsOf(harness, options);
472
499
  // What a crash left open is settled first, so the log reads as a whole and the context has no call without a result.
473
500
  let path = await session.path();
474
501
  const wrote = await settleOpenCalls(path, harness, (origin, body) => writer.write(origin, body), !session.headMoved());
@@ -487,14 +514,20 @@ async function runTurnOnce(session, harness, options) {
487
514
  path = await session.path();
488
515
  }
489
516
  const history = options.history ?? contextOf(path).messages;
490
- await writeInput(writer, options, newId);
517
+ await writeInput(writer, options, newId, notices);
518
+ // A notice counts as told only once it is in the log; a turn that failed before here tells it again next time.
519
+ await writer.settled();
520
+ if (writer.failure() === undefined)
521
+ for (const boundary of harness.turnBoundaries ?? [])
522
+ boundary.commitNotices?.();
523
+ const input = withNotices(options.input, notices);
491
524
  const recorder = new EventRecorder(writer, harness, system, newId, "run", turnContext?.spillOf);
492
525
  turnContext?.attach(attachment(writer, recorder));
493
526
  const observer = (event) => recorder.handle(event);
494
527
  const handle = run({
495
528
  model,
496
529
  system,
497
- input: options.input,
530
+ input,
498
531
  tools,
499
532
  signal,
500
533
  interceptors: interceptorsOf(harness, session, writer, recorder, options.hostContext, model, turnContext),