@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
@@ -8,6 +8,9 @@ import { Client } from "@modelcontextprotocol/client";
8
8
  import { HarnessError } from "../errors.js";
9
9
  import { checkToolList, resultOf, shortText } from "./content.js";
10
10
  import { McpError } from "./errors.js";
11
+ import { RemoteRefusal } from "./guarded-fetch.js";
12
+ import { remoteChannel } from "./remote.js";
13
+ import { checkRemoteTransport, redact } from "./remote-config.js";
11
14
  import { checkStdioTransport, StdioChannel } from "./stdio.js";
12
15
  const MODERN_VERSION = "2026-07-28";
13
16
  const DEFAULT_CONNECT_TIMEOUT_MS = 30_000;
@@ -20,7 +23,36 @@ const MAX_LIST_PAGES = 8;
20
23
  const MAX_TIMER_MS = 2 ** 31 - 1;
21
24
  const SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,31}$/;
22
25
  const CLIENT_INFO = { name: "buildanagent-harness", version: "0.0.0" };
23
- const describe = (error) => shortText(error instanceof Error ? error.message : String(error));
26
+ // A `subscriptions/listen` stream that drops is opened again after one second, doubling to a minute. One that stayed
27
+ // open for five minutes counts as healthy and resets the count; after eight short-lived streams in a row the harness
28
+ // stops opening it, so a server that acknowledges and drops at once can't keep the client busy.
29
+ const LISTEN_BASE_MS = 1000;
30
+ const LISTEN_MAX_MS = 60_000;
31
+ const LISTEN_HEALTHY_MS = 5 * 60 * 1000;
32
+ const MAX_LISTEN_DROPS = 8;
33
+ /** The platform's timers, which never hold a Node process open on their own. */
34
+ export const systemTimers = {
35
+ setTimeout(run, ms) {
36
+ const handle = setTimeout(run, ms);
37
+ handle.unref?.();
38
+ return handle;
39
+ },
40
+ clearTimeout(handle) {
41
+ clearTimeout(handle);
42
+ },
43
+ now: () => Date.now(),
44
+ };
45
+ /** The message of an error, with a refusal from a remote server's fetch named first, so a 401 reads as one. */
46
+ function messageOf(error) {
47
+ let current = error;
48
+ for (let depth = 0; depth < 4 && current instanceof Error; depth += 1) {
49
+ if (current instanceof RemoteRefusal)
50
+ return current.message;
51
+ current = current.cause;
52
+ }
53
+ return error instanceof Error ? error.message : String(error);
54
+ }
55
+ const describe = (error, secrets = []) => shortText(redact(messageOf(error), secrets));
24
56
  function timeout(name, value, fallback) {
25
57
  if (value === undefined)
26
58
  return fallback;
@@ -35,10 +67,13 @@ export function checkServerConfig(config) {
35
67
  throw new HarnessError("invalid_mcp_config", `an MCP server name must be 1 to 32 characters from A-Z, a-z, 0-9 and -, starting with a letter or digit, got ${JSON.stringify(config?.name)}`);
36
68
  }
37
69
  const transport = config.transport;
70
+ let secrets = [];
38
71
  if (transport?.kind === "stdio")
39
72
  checkStdioTransport(transport);
73
+ else if (transport?.kind === "http" || transport?.kind === "sse")
74
+ secrets = checkRemoteTransport(transport).secrets;
40
75
  else if (transport?.kind !== "in_process" || typeof transport.channel?.send !== "function") {
41
- throw new HarnessError("invalid_mcp_config", `the MCP server "${config.name}" needs a stdio or in_process transport`);
76
+ throw new HarnessError("invalid_mcp_config", `the MCP server "${config.name}" needs a stdio, in_process, http or sse transport`);
42
77
  }
43
78
  const maxTools = config.maxTools ?? DEFAULT_MAX_TOOLS;
44
79
  if (!Number.isInteger(maxTools) || maxTools < 1) {
@@ -55,6 +90,7 @@ export function checkServerConfig(config) {
55
90
  probeMs: timeout("probeTimeoutMs", config.probeTimeoutMs, Math.min(DEFAULT_PROBE_TIMEOUT_MS, Math.ceil(connectMs / 2))),
56
91
  requestMs: timeout("requestTimeoutMs", config.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS),
57
92
  maxTools,
93
+ secrets,
58
94
  };
59
95
  }
60
96
  /** Why a call failed, read from what the client library threw. */
@@ -78,6 +114,7 @@ const FAILURE_TEXT = {
78
114
  aborted: "the call was aborted",
79
115
  input_required: "the server asked for input from the user, which this harness does not supply yet",
80
116
  server_error: "the server answered with an error",
117
+ disabled: "the tool is disabled until a person approves its definition",
81
118
  };
82
119
  class Connection {
83
120
  server;
@@ -86,21 +123,107 @@ class Connection {
86
123
  #client;
87
124
  #channel;
88
125
  #settings;
126
+ #timers;
127
+ #log;
128
+ #refusal;
129
+ #plannedListenCut;
130
+ #watchers = new Set();
89
131
  #closed = false;
90
132
  #closing;
91
- constructor(server, client, channel, settings, era, version) {
92
- this.server = server;
93
- this.#client = client;
94
- this.#channel = channel;
95
- this.#settings = settings;
96
- this.era = era;
97
- this.protocolVersion = version;
98
- const previous = channel.onclose;
99
- channel.onclose = () => {
133
+ #subscription;
134
+ #listenTimer;
135
+ #listenDrops = 0;
136
+ constructor(parts) {
137
+ this.server = parts.server;
138
+ this.#client = parts.client;
139
+ this.#channel = parts.channel;
140
+ this.#settings = parts.settings;
141
+ this.#timers = parts.timers;
142
+ this.#log = parts.log;
143
+ this.#refusal = parts.refusal;
144
+ this.#plannedListenCut = parts.plannedListenCut;
145
+ this.era = parts.era;
146
+ this.protocolVersion = parts.version;
147
+ parts.hub.fire = () => this.#changed();
148
+ const previous = parts.channel.onclose;
149
+ parts.channel.onclose = () => {
100
150
  this.#closed = true;
101
151
  previous?.();
102
152
  };
103
153
  }
154
+ watchTools(listener) {
155
+ this.#watchers.add(listener);
156
+ return () => this.#watchers.delete(listener);
157
+ }
158
+ #changed() {
159
+ if (this.#closed)
160
+ return;
161
+ for (const watcher of this.#watchers) {
162
+ try {
163
+ watcher();
164
+ }
165
+ catch {
166
+ // A watcher that throws must not stop the others.
167
+ }
168
+ }
169
+ }
170
+ /**
171
+ * Opens the `subscriptions/listen` stream for tool-list changes, on a 2026-07-28 server that advertises them, and
172
+ * opens it again when it drops, with a growing delay and a limit on short-lived streams.
173
+ */
174
+ listen() {
175
+ if (this.era !== MODERN_VERSION || this.#client.getServerCapabilities()?.tools?.listChanged !== true)
176
+ return;
177
+ void this.#openListen(false);
178
+ }
179
+ async #openListen(reopened) {
180
+ if (this.#closed)
181
+ return;
182
+ const opened = this.#timers.now();
183
+ let subscription;
184
+ try {
185
+ subscription = await this.#client.listen({ toolsListChanged: true }, { timeout: this.#settings.requestMs });
186
+ }
187
+ catch (error) {
188
+ this.#dropped(opened, `it could not be opened: ${describe(error, this.#settings.secrets)}`);
189
+ return;
190
+ }
191
+ if (this.#closed) {
192
+ await subscription.close().catch(() => { });
193
+ return;
194
+ }
195
+ this.#subscription = subscription;
196
+ // Changes the server made while no stream was open were never announced, so the list is read again.
197
+ if (reopened)
198
+ this.#changed();
199
+ const cause = await subscription.closed;
200
+ if (cause === "local" || this.#closed)
201
+ return;
202
+ // A stream the harness cut itself, for going quiet or for its total bytes, is opened again at once and is not a drop.
203
+ if (this.#plannedListenCut())
204
+ this.#reopenListen(LISTEN_BASE_MS, "the harness cut it");
205
+ else
206
+ this.#dropped(opened, cause === "graceful" ? "the server ended it" : "it dropped");
207
+ }
208
+ #dropped(opened, why) {
209
+ if (this.#closed)
210
+ return;
211
+ if (this.#timers.now() - opened >= LISTEN_HEALTHY_MS)
212
+ this.#listenDrops = 0;
213
+ this.#listenDrops += 1;
214
+ if (this.#listenDrops > MAX_LISTEN_DROPS) {
215
+ this.#log(`the change stream of "${this.server}" ended ${MAX_LISTEN_DROPS} times in a row, so it is not opened again`);
216
+ return;
217
+ }
218
+ this.#reopenListen(Math.min(LISTEN_MAX_MS, LISTEN_BASE_MS * 2 ** (this.#listenDrops - 1)), why);
219
+ }
220
+ #reopenListen(delay, why) {
221
+ this.#log(`the change stream of "${this.server}" closed (${why}); it is opened again in ${delay} ms`);
222
+ this.#listenTimer = this.#timers.setTimeout(() => {
223
+ this.#listenTimer = undefined;
224
+ void this.#openListen(true);
225
+ }, delay);
226
+ }
104
227
  get closed() {
105
228
  return this.#closed;
106
229
  }
@@ -140,7 +263,8 @@ class Connection {
140
263
  : await this.#client.listTools({ cursor }, options);
141
264
  }
142
265
  catch (error) {
143
- throw new McpError("mcp_tool_list_refused", this.server, `its tool list could not be read: ${describe(error)}`, {
266
+ const why = describe(this.#refusal() ?? error, this.#settings.secrets);
267
+ throw new McpError("mcp_tool_list_refused", this.server, `its tool list could not be read: ${why}`, {
144
268
  cause: error,
145
269
  });
146
270
  }
@@ -156,7 +280,9 @@ class Connection {
156
280
  }
157
281
  catch (error) {
158
282
  const failure = failureOf(error, signal, this.#closed);
159
- const detail = failure === "server_error" ? `: ${describe(error)}` : "";
283
+ const refusal = this.#refusal();
284
+ const shown = refusal ?? (failure === "server_error" ? error : undefined);
285
+ const detail = shown === undefined ? "" : `: ${describe(shown, this.#settings.secrets)}`;
160
286
  throw new McpError("mcp_call_failed", this.server, `${FAILURE_TEXT[failure]}${detail}`, {
161
287
  cause: error,
162
288
  failure,
@@ -169,17 +295,29 @@ class Connection {
169
295
  close() {
170
296
  this.#closing ??= (async () => {
171
297
  this.#closed = true;
298
+ this.#watchers.clear();
299
+ if (this.#listenTimer !== undefined)
300
+ this.#timers.clearTimeout(this.#listenTimer);
301
+ await this.#subscription?.close().catch(() => { });
172
302
  await this.#client.close().catch(() => { });
173
303
  await this.#channel.close().catch(() => { });
174
304
  })();
175
305
  return this.#closing;
176
306
  }
177
307
  }
178
- function channelOf(config, log) {
179
- return config.transport.kind === "stdio" ? new StdioChannel(config.transport, log) : config.transport.channel;
308
+ function channelOf(config, log, timers) {
309
+ const transport = config.transport;
310
+ const none = () => undefined;
311
+ if (transport.kind === "stdio")
312
+ return { channel: new StdioChannel(transport, log), refusal: none };
313
+ if (transport.kind === "http" || transport.kind === "sse")
314
+ return remoteChannel(transport, log, timers);
315
+ return { channel: transport.channel, refusal: none };
180
316
  }
181
317
  /** Connects through `channel`, bounded by `connectMs`, and closes everything when it fails. */
182
- async function handshake(config, settings, channel, prior, log, deadline) {
318
+ async function handshake(context, opened, prior, deadline) {
319
+ const { config, settings, log } = context;
320
+ const { channel } = opened;
183
321
  const client = new Client(CLIENT_INFO, {
184
322
  capabilities: {},
185
323
  versionNegotiation: { mode: "auto", probe: { timeoutMs: settings.probeMs } },
@@ -192,9 +330,12 @@ async function handshake(config, settings, channel, prior, log, deadline) {
192
330
  getValidator: () => (input) => ({ valid: true, data: input, errorMessage: undefined }),
193
331
  },
194
332
  });
195
- // The tool list stays as registered at connect. A changed list is announced, and a later todo diffs it against a pin.
333
+ // A changed list is passed to the connection's watchers, which read it again and diff it against the pins. The same
334
+ // handler serves a legacy server's unsolicited notice and a 2026-07-28 server's notice on its listen stream.
335
+ const hub = { fire: () => { } };
196
336
  client.setNotificationHandler("notifications/tools/list_changed", () => {
197
- log(`the server "${config.name}" says its tool list changed; its tools stay as they were registered`);
337
+ log(`the server "${config.name}" says its tool list changed`);
338
+ hub.fire();
198
339
  });
199
340
  let timer;
200
341
  let onAbort;
@@ -218,7 +359,19 @@ async function handshake(config, settings, channel, prior, log, deadline) {
218
359
  if (era === "modern" && version !== MODERN_VERSION) {
219
360
  throw new Error(`the server negotiated the revision ${shortText(version, 32)}, which this harness does not know`);
220
361
  }
221
- return new Connection(config.name, client, channel, settings, era === "modern" ? MODERN_VERSION : "legacy", version);
362
+ return new Connection({
363
+ server: config.name,
364
+ client,
365
+ channel,
366
+ settings,
367
+ era: era === "modern" ? MODERN_VERSION : "legacy",
368
+ version,
369
+ hub,
370
+ timers: context.timers,
371
+ log,
372
+ refusal: opened.refusal,
373
+ plannedListenCut: opened.plannedListenCut ?? (() => false),
374
+ });
222
375
  }
223
376
  catch (error) {
224
377
  await client.close().catch(() => { });
@@ -234,8 +387,10 @@ async function handshake(config, settings, channel, prior, log, deadline) {
234
387
  /**
235
388
  * Connects one server and negotiates its era. A stdio server that exits cleanly after the `server/discover` probe, as
236
389
  * servers on some older SDKs do on any request before `initialize`, is started once more and spoken to as a legacy
237
- * server; a server that crashes runs once. The whole connect, a restart included, takes at most `connectTimeoutMs`.
238
- * `signal` aborts it, and the server is closed.
390
+ * server; a server that crashes runs once. An `sse` server is spoken to as a legacy server, with no probe. The whole
391
+ * connect, a restart included, takes at most `connectTimeoutMs`. `signal` aborts it, and the server is closed. On a
392
+ * 2026-07-28 server that advertises tool-list changes, the connection opens a `subscriptions/listen` stream for them.
393
+ * `timers` runs the stream's reopen delays; the default is the platform's.
239
394
  *
240
395
  * Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be used, and an `McpError`, code
241
396
  * `mcp_connect_failed`, when the server does not start, does not finish the handshake within `connectTimeoutMs`, is
@@ -244,12 +399,22 @@ async function handshake(config, settings, channel, prior, log, deadline) {
244
399
  export async function connectMcpServer(config, options = {}) {
245
400
  const settings = checkServerConfig(config);
246
401
  const log = options.log ?? (() => { });
402
+ const timers = options.timers ?? systemTimers;
403
+ const context = { config, settings, log, timers };
247
404
  const ends = Date.now() + settings.connectMs;
248
405
  const left = () => ({ ms: ends - Date.now(), signal: options.signal });
249
- const failed = (error) => new McpError("mcp_connect_failed", config.name, `it did not connect: ${describe(error)}`, { cause: error });
250
- const channel = channelOf(config, log);
406
+ const opened = channelOf(config, log, timers);
407
+ const failed = (error) => {
408
+ const cause = opened.refusal() ?? error;
409
+ return new McpError("mcp_connect_failed", config.name, `it did not connect: ${describe(cause, settings.secrets)}`, {
410
+ cause: error,
411
+ });
412
+ };
413
+ const channel = opened.channel;
414
+ const prior = config.transport.kind === "sse" ? "legacy" : undefined;
415
+ let connection;
251
416
  try {
252
- return await handshake(config, settings, channel, undefined, log, left());
417
+ connection = await handshake(context, opened, prior, left());
253
418
  }
254
419
  catch (first) {
255
420
  const exitedOnProbe = channel instanceof StdioChannel && channel.exitedOnProbe;
@@ -257,11 +422,13 @@ export async function connectMcpServer(config, options = {}) {
257
422
  throw failed(first);
258
423
  log(`the server "${config.name}" closed after the probe, so it is started again as a legacy server`);
259
424
  try {
260
- return await handshake(config, settings, channelOf(config, log), "legacy", log, left());
425
+ connection = await handshake(context, channelOf(config, log, timers), "legacy", left());
261
426
  }
262
427
  catch (second) {
263
428
  throw failed(second);
264
429
  }
265
430
  }
431
+ connection.listen();
432
+ return connection;
266
433
  }
267
434
  //# sourceMappingURL=connection.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/mcp/connection.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,MAAM,EAAkB,MAAM,8BAA8B,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAClE,OAAO,EAAuB,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAG/D,MAAM,cAAc,GAAG,YAAY,CAAC;AACpC,MAAM,0BAA0B,GAAG,MAAM,CAAC;AAC1C,MAAM,wBAAwB,GAAG,KAAK,CAAC;AACvC,MAAM,0BAA0B,GAAG,MAAM,CAAC;AAC1C,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,gGAAgG;AAChG,MAAM,cAAc,GAAG,CAAC,CAAC;AACzB,+DAA+D;AAC/D,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACjC,MAAM,WAAW,GAAG,iCAAiC,CAAC;AACtD,MAAM,WAAW,GAAG,EAAE,IAAI,EAAE,sBAAsB,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAEvE,M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;YACH,OAAO,MAAM,SAAS,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1F,CAAC;QAAC,OAAO,MAAM,EAAE,CAAC;YAChB,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/**\n * `connectMcpServer()`: one server behind `McpConnection`, over `@modelcontextprotocol/client` 2.4.0 (ADR 0021). The\n * client negotiates the era per connection: it probes with `server/discover` and falls back to `initialize` when the\n * server gives no sign of the 2026-07-28 revision. This module reads the result through the client's\n * `getProtocolEra()`, and only it imports the client, so the base can change without touching the registry.\n */\nimport { Client, type Transport } from \"@modelcontextprotocol/client\";\nimport { HarnessError } from \"../errors.js\";\nimport { checkToolList, resultOf, shortText } from \"./content.js\";\nimport { type McpCallFailure, McpError } from \"./errors.js\";\nimport { checkStdioTransport, StdioChannel } from \"./stdio.js\";\nimport type { McpCallResult, McpChannel, McpConnection, McpEra, McpServerConfig, McpTool } from \"./types.js\";\n\nconst MODERN_VERSION = \"2026-07-28\";\nconst DEFAULT_CONNECT_TIMEOUT_MS = 30_000;\nconst DEFAULT_PROBE_TIMEOUT_MS = 5_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 60_000;\nconst DEFAULT_MAX_TOOLS = 256;\n// The pages a tool list may take. A server whose cursor never ends can't keep the connect busy.\nconst MAX_LIST_PAGES = 8;\n// The longest delay a timer takes: a larger one fires at once.\nconst MAX_TIMER_MS = 2 ** 31 - 1;\nconst SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,31}$/;\nconst CLIENT_INFO = { name: \"buildanagent-harness\", version: \"0.0.0\" };\n\nconst describe = (error: unknown): string => shortText(error instanceof Error ? error.message : String(error));\n\nfunction timeout(name: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (!(Number.isInteger(value) && value >= 1 && value <= MAX_TIMER_MS)) {\n throw new HarnessError(\n \"invalid_mcp_config\",\n `${name} must be a whole number of milliseconds from 1 to ${MAX_TIMER_MS}`,\n );\n }\n return value;\n}\n\n/** A server's settings with their defaults, checked. Throws a `HarnessError`, code `invalid_mcp_config`. */\nexport function checkServerConfig(config: McpServerConfig) {\n if (typeof config?.name !== \"string\" || !SERVER_NAME.test(config.name)) {\n throw new HarnessError(\n \"invalid_mcp_config\",\n `an MCP server name must be 1 to 32 characters from A-Z, a-z, 0-9 and -, starting with a letter or digit, got ${JSON.stringify(config?.name)}`,\n );\n }\n const transport = config.transport;\n if (transport?.kind === \"stdio\") checkStdioTransport(transport);\n else if (transport?.kind !== \"in_process\" || typeof transport.channel?.send !== \"function\") {\n throw new HarnessError(\n \"invalid_mcp_config\",\n `the MCP server \"${config.name}\" needs a stdio or in_process transport`,\n );\n }\n const maxTools = config.maxTools ?? DEFAULT_MAX_TOOLS;\n if (!Number.isInteger(maxTools) || maxTools < 1) {\n throw new HarnessError(\"invalid_mcp_config\", \"maxTools must be a whole number, 1 or more\");\n }\n const connectMs = timeout(\"connectTimeoutMs\", config.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS);\n // A probe that outlasts the handshake would never let a silent server fall back to legacy, so a probe timeout the\n // config names must be shorter, and the default shrinks to half the handshake when it would not be.\n if (config.probeTimeoutMs !== undefined && config.probeTimeoutMs >= connectMs) {\n throw new HarnessError(\"invalid_mcp_config\", \"probeTimeoutMs must be shorter than connectTimeoutMs\");\n }\n return {\n connectMs,\n probeMs: timeout(\n \"probeTimeoutMs\",\n config.probeTimeoutMs,\n Math.min(DEFAULT_PROBE_TIMEOUT_MS, Math.ceil(connectMs / 2)),\n ),\n requestMs: timeout(\"requestTimeoutMs\", config.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS),\n maxTools,\n };\n}\n\ntype Settings = ReturnType<typeof checkServerConfig>;\n\n/** Why a call failed, read from what the client library threw. */\nfunction failureOf(error: unknown, signal: AbortSignal, closed: boolean): McpCallFailure {\n if (signal.aborted) return \"aborted\";\n if (closed) return \"closed\";\n const code = (error as { code?: unknown } | null)?.code;\n if (code === \"REQUEST_TIMEOUT\") return \"timeout\";\n if (code === \"CONNECTION_CLOSED\" || code === \"NOT_CONNECTED\" || code === \"SEND_FAILED\") return \"closed\";\n if (code === \"UNSUPPORTED_RESULT_TYPE\" || code === \"INPUT_REQUIRED_ROUNDS_EXCEEDED\") return \"input_required\";\n return \"server_error\";\n}\n\nconst FAILURE_TEXT: Record<McpCallFailure, string> = {\n closed: \"the connection closed before the call finished\",\n timeout: \"the call timed out\",\n aborted: \"the call was aborted\",\n input_required: \"the server asked for input from the user, which this harness does not supply yet\",\n server_error: \"the server answered with an error\",\n};\n\nclass Connection implements McpConnection {\n readonly server: string;\n readonly era: McpEra;\n readonly protocolVersion: string;\n readonly #client: Client;\n readonly #channel: McpChannel;\n readonly #settings: Settings;\n #closed = false;\n #closing: Promise<void> | undefined;\n\n constructor(server: string, client: Client, channel: McpChannel, settings: Settings, era: McpEra, version: string) {\n this.server = server;\n this.#client = client;\n this.#channel = channel;\n this.#settings = settings;\n this.era = era;\n this.protocolVersion = version;\n const previous = channel.onclose;\n channel.onclose = () => {\n this.#closed = true;\n previous?.();\n };\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * The server's tools, read one page at a time. The walk stops as soon as the list passes `maxTools` or runs past\n * eight pages, so a server can make the harness hold at most one page beyond the limit, each page bounded by the\n * line limit. The client's own walk would gather every page before anything counted them.\n */\n async listTools(): Promise<readonly McpTool[]> {\n const listed: unknown[] = [];\n let cursor: string | undefined;\n for (let page = 1; ; page += 1) {\n const result = await this.#page(cursor);\n const tools = (result as { tools?: unknown }).tools;\n if (!Array.isArray(tools)) return checkToolList(this.server, tools, this.#settings.maxTools);\n listed.push(...tools);\n // One past the limit is enough for checkToolList() to refuse, so no later page is asked for.\n if (listed.length > this.#settings.maxTools) break;\n const next = (result as { nextCursor?: unknown }).nextCursor;\n if (typeof next !== \"string\" || next === \"\") break;\n if (page >= MAX_LIST_PAGES) {\n throw new McpError(\n \"mcp_tool_list_refused\",\n this.server,\n `its tool list was refused, so none of its tools was registered: it runs past ${MAX_LIST_PAGES} pages`,\n );\n }\n cursor = next;\n }\n return checkToolList(this.server, listed, this.#settings.maxTools);\n }\n\n async #page(cursor: string | undefined): Promise<unknown> {\n const options = { timeout: this.#settings.requestMs };\n try {\n // The first page goes as a plain request, since the client's listTools() with no cursor walks every page itself.\n return cursor === undefined\n ? await this.#client.request({ method: \"tools/list\" }, options)\n : await this.#client.listTools({ cursor }, options);\n } catch (error) {\n throw new McpError(\"mcp_tool_list_refused\", this.server, `its tool list could not be read: ${describe(error)}`, {\n cause: error,\n });\n }\n }\n\n async callTool(name: string, args: unknown, signal: AbortSignal): Promise<McpCallResult> {\n if (this.#closed) {\n throw new McpError(\"mcp_call_failed\", this.server, FAILURE_TEXT.closed, { failure: \"closed\" });\n }\n const input = typeof args === \"object\" && args !== null && !Array.isArray(args) ? args : {};\n try {\n const result = await this.#client.callTool(\n { name, arguments: input as Record<string, unknown> },\n { signal, timeout: this.#settings.requestMs },\n );\n return resultOf(result);\n } catch (error) {\n const failure = failureOf(error, signal, this.#closed);\n const detail = failure === \"server_error\" ? `: ${describe(error)}` : \"\";\n throw new McpError(\"mcp_call_failed\", this.server, `${FAILURE_TEXT[failure]}${detail}`, {\n cause: error,\n failure,\n });\n }\n }\n\n stderr(): string {\n return this.#channel instanceof StdioChannel ? this.#channel.stderr : \"\";\n }\n\n close(): Promise<void> {\n this.#closing ??= (async () => {\n this.#closed = true;\n await this.#client.close().catch(() => {});\n await this.#channel.close().catch(() => {});\n })();\n return this.#closing;\n }\n}\n\nfunction channelOf(config: McpServerConfig, log: (line: string) => void): McpChannel {\n return config.transport.kind === \"stdio\" ? new StdioChannel(config.transport, log) : config.transport.channel;\n}\n\n/** Connects through `channel`, bounded by `connectMs`, and closes everything when it fails. */\nasync function handshake(\n config: McpServerConfig,\n settings: Settings,\n channel: McpChannel,\n prior: \"legacy\" | undefined,\n log: (line: string) => void,\n deadline: { readonly ms: number; readonly signal: AbortSignal | undefined },\n): Promise<Connection> {\n const client = new Client(CLIENT_INFO, {\n capabilities: {},\n versionNegotiation: { mode: \"auto\", probe: { timeoutMs: settings.probeMs } },\n // A server's request for user input fails the call: whether it may pause a turn waits on the owner.\n inputRequired: { autoFulfill: false },\n listMaxPages: MAX_LIST_PAGES,\n // The harness reads a result's content, not its structured content, so a server's output schema is never compiled:\n // a hostile pattern or reference in it can cost nothing.\n jsonSchemaValidator: {\n getValidator: () => (input: unknown) => ({ valid: true, data: input as never, errorMessage: undefined }),\n },\n });\n // The tool list stays as registered at connect. A changed list is announced, and a later todo diffs it against a pin.\n client.setNotificationHandler(\"notifications/tools/list_changed\", () => {\n log(`the server \"${config.name}\" says its tool list changed; its tools stay as they were registered`);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onAbort: (() => void) | undefined;\n const expired = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`the handshake did not finish in ${settings.connectMs} ms`)),\n Math.max(1, deadline.ms),\n );\n onAbort = () => reject(new Error(\"the connect was aborted\"));\n if (deadline.signal?.aborted) onAbort();\n else deadline.signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n try {\n const connecting = client.connect(channel as unknown as Transport, {\n timeout: Math.max(1, deadline.ms),\n ...(prior === undefined ? {} : { prior: { kind: prior } }),\n });\n connecting.catch(() => {});\n await Promise.race([connecting, expired]);\n const era = client.getProtocolEra();\n const version = client.getNegotiatedProtocolVersion() ?? \"\";\n if (era === \"modern\" && version !== MODERN_VERSION) {\n throw new Error(`the server negotiated the revision ${shortText(version, 32)}, which this harness does not know`);\n }\n return new Connection(\n config.name,\n client,\n channel,\n settings,\n era === \"modern\" ? MODERN_VERSION : \"legacy\",\n version,\n );\n } catch (error) {\n await client.close().catch(() => {});\n await channel.close().catch(() => {});\n throw error;\n } finally {\n clearTimeout(timer);\n if (onAbort !== undefined) deadline.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/**\n * Connects one server and negotiates its era. A stdio server that exits cleanly after the `server/discover` probe, as\n * servers on some older SDKs do on any request before `initialize`, is started once more and spoken to as a legacy\n * server; a server that crashes runs once. The whole connect, a restart included, takes at most `connectTimeoutMs`.\n * `signal` aborts it, and the server is closed.\n *\n * Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be used, and an `McpError`, code\n * `mcp_connect_failed`, when the server does not start, does not finish the handshake within `connectTimeoutMs`, is\n * aborted, or negotiates a revision this harness does not know.\n */\nexport async function connectMcpServer(\n config: McpServerConfig,\n options: { readonly log?: (line: string) => void; readonly signal?: AbortSignal } = {},\n): Promise<McpConnection> {\n const settings = checkServerConfig(config);\n const log = options.log ?? (() => {});\n const ends = Date.now() + settings.connectMs;\n const left = () => ({ ms: ends - Date.now(), signal: options.signal });\n const failed = (error: unknown) =>\n new McpError(\"mcp_connect_failed\", config.name, `it did not connect: ${describe(error)}`, { cause: error });\n const channel = channelOf(config, log);\n try {\n return await handshake(config, settings, channel, undefined, log, left());\n } catch (first) {\n const exitedOnProbe = channel instanceof StdioChannel && channel.exitedOnProbe;\n if (!exitedOnProbe || options.signal?.aborted === true || left().ms <= 0) throw failed(first);\n log(`the server \"${config.name}\" closed after the probe, so it is started again as a legacy server`);\n try {\n return await handshake(config, settings, channelOf(config, log), \"legacy\", log, left());\n } catch (second) {\n throw failed(second);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/mcp/connection.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,MAAM,EAAwC,MAAM,8BAA8B,CAAC;AAC5F,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAClE,OAAO,EAAuB,QAAQ,EAAE,MAAM,aAAa,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connectMcpServer()`: one server behind `McpConnection`, over `@modelcontextprotocol/client` 2.4.0 (ADR 0021). The\n * client negotiates the era per connection: it probes with `server/discover` and falls back to `initialize` when the\n * server gives no sign of the 2026-07-28 revision. This module reads the result through the client's\n * `getProtocolEra()`, and only it imports the client, so the base can change without touching the registry.\n */\nimport { Client, type McpSubscription, type Transport } from \"@modelcontextprotocol/client\";\nimport { HarnessError } from \"../errors.js\";\nimport { checkToolList, resultOf, shortText } from \"./content.js\";\nimport { type McpCallFailure, McpError } from \"./errors.js\";\nimport { RemoteRefusal } from \"./guarded-fetch.js\";\nimport { remoteChannel } from \"./remote.js\";\nimport { checkRemoteTransport, redact } from \"./remote-config.js\";\nimport { checkStdioTransport, StdioChannel } from \"./stdio.js\";\nimport type { McpCallResult, McpChannel, McpConnection, McpEra, McpServerConfig, McpTimers, McpTool } from \"./types.js\";\n\nconst MODERN_VERSION = \"2026-07-28\";\nconst DEFAULT_CONNECT_TIMEOUT_MS = 30_000;\nconst DEFAULT_PROBE_TIMEOUT_MS = 5_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 60_000;\nconst DEFAULT_MAX_TOOLS = 256;\n// The pages a tool list may take. A server whose cursor never ends can't keep the connect busy.\nconst MAX_LIST_PAGES = 8;\n// The longest delay a timer takes: a larger one fires at once.\nconst MAX_TIMER_MS = 2 ** 31 - 1;\nconst SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,31}$/;\nconst CLIENT_INFO = { name: \"buildanagent-harness\", version: \"0.0.0\" };\n\n// A `subscriptions/listen` stream that drops is opened again after one second, doubling to a minute. One that stayed\n// open for five minutes counts as healthy and resets the count; after eight short-lived streams in a row the harness\n// stops opening it, so a server that acknowledges and drops at once can't keep the client busy.\nconst LISTEN_BASE_MS = 1000;\nconst LISTEN_MAX_MS = 60_000;\nconst LISTEN_HEALTHY_MS = 5 * 60 * 1000;\nconst MAX_LISTEN_DROPS = 8;\n\n/** The platform's timers, which never hold a Node process open on their own. */\nexport const systemTimers: McpTimers = {\n setTimeout(run, ms) {\n const handle = setTimeout(run, ms);\n (handle as { unref?: () => void }).unref?.();\n return handle;\n },\n clearTimeout(handle) {\n clearTimeout(handle as ReturnType<typeof setTimeout>);\n },\n now: () => Date.now(),\n};\n\n/** The message of an error, with a refusal from a remote server's fetch named first, so a 401 reads as one. */\nfunction messageOf(error: unknown): string {\n let current: unknown = error;\n for (let depth = 0; depth < 4 && current instanceof Error; depth += 1) {\n if (current instanceof RemoteRefusal) return current.message;\n current = current.cause;\n }\n return error instanceof Error ? error.message : String(error);\n}\n\nconst describe = (error: unknown, secrets: readonly string[] = []): string =>\n shortText(redact(messageOf(error), secrets));\n\nfunction timeout(name: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (!(Number.isInteger(value) && value >= 1 && value <= MAX_TIMER_MS)) {\n throw new HarnessError(\n \"invalid_mcp_config\",\n `${name} must be a whole number of milliseconds from 1 to ${MAX_TIMER_MS}`,\n );\n }\n return value;\n}\n\n/** A server's settings with their defaults, checked. Throws a `HarnessError`, code `invalid_mcp_config`. */\nexport function checkServerConfig(config: McpServerConfig) {\n if (typeof config?.name !== \"string\" || !SERVER_NAME.test(config.name)) {\n throw new HarnessError(\n \"invalid_mcp_config\",\n `an MCP server name must be 1 to 32 characters from A-Z, a-z, 0-9 and -, starting with a letter or digit, got ${JSON.stringify(config?.name)}`,\n );\n }\n const transport = config.transport;\n let secrets: readonly string[] = [];\n if (transport?.kind === \"stdio\") checkStdioTransport(transport);\n else if (transport?.kind === \"http\" || transport?.kind === \"sse\") secrets = checkRemoteTransport(transport).secrets;\n else if (transport?.kind !== \"in_process\" || typeof transport.channel?.send !== \"function\") {\n throw new HarnessError(\n \"invalid_mcp_config\",\n `the MCP server \"${config.name}\" needs a stdio, in_process, http or sse transport`,\n );\n }\n const maxTools = config.maxTools ?? DEFAULT_MAX_TOOLS;\n if (!Number.isInteger(maxTools) || maxTools < 1) {\n throw new HarnessError(\"invalid_mcp_config\", \"maxTools must be a whole number, 1 or more\");\n }\n const connectMs = timeout(\"connectTimeoutMs\", config.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS);\n // A probe that outlasts the handshake would never let a silent server fall back to legacy, so a probe timeout the\n // config names must be shorter, and the default shrinks to half the handshake when it would not be.\n if (config.probeTimeoutMs !== undefined && config.probeTimeoutMs >= connectMs) {\n throw new HarnessError(\"invalid_mcp_config\", \"probeTimeoutMs must be shorter than connectTimeoutMs\");\n }\n return {\n connectMs,\n probeMs: timeout(\n \"probeTimeoutMs\",\n config.probeTimeoutMs,\n Math.min(DEFAULT_PROBE_TIMEOUT_MS, Math.ceil(connectMs / 2)),\n ),\n requestMs: timeout(\"requestTimeoutMs\", config.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS),\n maxTools,\n secrets,\n };\n}\n\ntype Settings = ReturnType<typeof checkServerConfig>;\n\n/** Why a call failed, read from what the client library threw. */\nfunction failureOf(error: unknown, signal: AbortSignal, closed: boolean): McpCallFailure {\n if (signal.aborted) return \"aborted\";\n if (closed) return \"closed\";\n const code = (error as { code?: unknown } | null)?.code;\n if (code === \"REQUEST_TIMEOUT\") return \"timeout\";\n if (code === \"CONNECTION_CLOSED\" || code === \"NOT_CONNECTED\" || code === \"SEND_FAILED\") return \"closed\";\n if (code === \"UNSUPPORTED_RESULT_TYPE\" || code === \"INPUT_REQUIRED_ROUNDS_EXCEEDED\") return \"input_required\";\n return \"server_error\";\n}\n\nconst FAILURE_TEXT: Record<McpCallFailure, string> = {\n closed: \"the connection closed before the call finished\",\n timeout: \"the call timed out\",\n aborted: \"the call was aborted\",\n input_required: \"the server asked for input from the user, which this harness does not supply yet\",\n server_error: \"the server answered with an error\",\n disabled: \"the tool is disabled until a person approves its definition\",\n};\n\n/** Where a server's change notices go: the connection sets `fire` once it exists. */\ninterface ChangeHub {\n fire: () => void;\n}\n\n/** What a connection is built from, once its handshake is done. */\ninterface Parts {\n readonly server: string;\n readonly client: Client;\n readonly channel: McpChannel;\n readonly settings: Settings;\n readonly era: McpEra;\n readonly version: string;\n readonly hub: ChangeHub;\n readonly timers: McpTimers;\n readonly log: (line: string) => void;\n readonly refusal: () => Error | undefined;\n readonly plannedListenCut: () => boolean;\n}\n\nclass Connection implements McpConnection {\n readonly server: string;\n readonly era: McpEra;\n readonly protocolVersion: string;\n readonly #client: Client;\n readonly #channel: McpChannel;\n readonly #settings: Settings;\n readonly #timers: McpTimers;\n readonly #log: (line: string) => void;\n readonly #refusal: () => Error | undefined;\n readonly #plannedListenCut: () => boolean;\n readonly #watchers = new Set<() => void>();\n #closed = false;\n #closing: Promise<void> | undefined;\n #subscription: McpSubscription | undefined;\n #listenTimer: unknown;\n #listenDrops = 0;\n\n constructor(parts: Parts) {\n this.server = parts.server;\n this.#client = parts.client;\n this.#channel = parts.channel;\n this.#settings = parts.settings;\n this.#timers = parts.timers;\n this.#log = parts.log;\n this.#refusal = parts.refusal;\n this.#plannedListenCut = parts.plannedListenCut;\n this.era = parts.era;\n this.protocolVersion = parts.version;\n parts.hub.fire = () => this.#changed();\n const previous = parts.channel.onclose;\n parts.channel.onclose = () => {\n this.#closed = true;\n previous?.();\n };\n }\n\n watchTools(listener: () => void): () => void {\n this.#watchers.add(listener);\n return () => this.#watchers.delete(listener);\n }\n\n #changed(): void {\n if (this.#closed) return;\n for (const watcher of this.#watchers) {\n try {\n watcher();\n } catch {\n // A watcher that throws must not stop the others.\n }\n }\n }\n\n /**\n * Opens the `subscriptions/listen` stream for tool-list changes, on a 2026-07-28 server that advertises them, and\n * opens it again when it drops, with a growing delay and a limit on short-lived streams.\n */\n listen(): void {\n if (this.era !== MODERN_VERSION || this.#client.getServerCapabilities()?.tools?.listChanged !== true) return;\n void this.#openListen(false);\n }\n\n async #openListen(reopened: boolean): Promise<void> {\n if (this.#closed) return;\n const opened = this.#timers.now();\n let subscription: McpSubscription;\n try {\n subscription = await this.#client.listen({ toolsListChanged: true }, { timeout: this.#settings.requestMs });\n } catch (error) {\n this.#dropped(opened, `it could not be opened: ${describe(error, this.#settings.secrets)}`);\n return;\n }\n if (this.#closed) {\n await subscription.close().catch(() => {});\n return;\n }\n this.#subscription = subscription;\n // Changes the server made while no stream was open were never announced, so the list is read again.\n if (reopened) this.#changed();\n const cause = await subscription.closed;\n if (cause === \"local\" || this.#closed) return;\n // A stream the harness cut itself, for going quiet or for its total bytes, is opened again at once and is not a drop.\n if (this.#plannedListenCut()) this.#reopenListen(LISTEN_BASE_MS, \"the harness cut it\");\n else this.#dropped(opened, cause === \"graceful\" ? \"the server ended it\" : \"it dropped\");\n }\n\n #dropped(opened: number, why: string): void {\n if (this.#closed) return;\n if (this.#timers.now() - opened >= LISTEN_HEALTHY_MS) this.#listenDrops = 0;\n this.#listenDrops += 1;\n if (this.#listenDrops > MAX_LISTEN_DROPS) {\n this.#log(\n `the change stream of \"${this.server}\" ended ${MAX_LISTEN_DROPS} times in a row, so it is not opened again`,\n );\n return;\n }\n this.#reopenListen(Math.min(LISTEN_MAX_MS, LISTEN_BASE_MS * 2 ** (this.#listenDrops - 1)), why);\n }\n\n #reopenListen(delay: number, why: string): void {\n this.#log(`the change stream of \"${this.server}\" closed (${why}); it is opened again in ${delay} ms`);\n this.#listenTimer = this.#timers.setTimeout(() => {\n this.#listenTimer = undefined;\n void this.#openListen(true);\n }, delay);\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * The server's tools, read one page at a time. The walk stops as soon as the list passes `maxTools` or runs past\n * eight pages, so a server can make the harness hold at most one page beyond the limit, each page bounded by the\n * line limit. The client's own walk would gather every page before anything counted them.\n */\n async listTools(): Promise<readonly McpTool[]> {\n const listed: unknown[] = [];\n let cursor: string | undefined;\n for (let page = 1; ; page += 1) {\n const result = await this.#page(cursor);\n const tools = (result as { tools?: unknown }).tools;\n if (!Array.isArray(tools)) return checkToolList(this.server, tools, this.#settings.maxTools);\n listed.push(...tools);\n // One past the limit is enough for checkToolList() to refuse, so no later page is asked for.\n if (listed.length > this.#settings.maxTools) break;\n const next = (result as { nextCursor?: unknown }).nextCursor;\n if (typeof next !== \"string\" || next === \"\") break;\n if (page >= MAX_LIST_PAGES) {\n throw new McpError(\n \"mcp_tool_list_refused\",\n this.server,\n `its tool list was refused, so none of its tools was registered: it runs past ${MAX_LIST_PAGES} pages`,\n );\n }\n cursor = next;\n }\n return checkToolList(this.server, listed, this.#settings.maxTools);\n }\n\n async #page(cursor: string | undefined): Promise<unknown> {\n const options = { timeout: this.#settings.requestMs };\n try {\n // The first page goes as a plain request, since the client's listTools() with no cursor walks every page itself.\n return cursor === undefined\n ? await this.#client.request({ method: \"tools/list\" }, options)\n : await this.#client.listTools({ cursor }, options);\n } catch (error) {\n const why = describe(this.#refusal() ?? error, this.#settings.secrets);\n throw new McpError(\"mcp_tool_list_refused\", this.server, `its tool list could not be read: ${why}`, {\n cause: error,\n });\n }\n }\n\n async callTool(name: string, args: unknown, signal: AbortSignal): Promise<McpCallResult> {\n if (this.#closed) {\n throw new McpError(\"mcp_call_failed\", this.server, FAILURE_TEXT.closed, { failure: \"closed\" });\n }\n const input = typeof args === \"object\" && args !== null && !Array.isArray(args) ? args : {};\n try {\n const result = await this.#client.callTool(\n { name, arguments: input as Record<string, unknown> },\n { signal, timeout: this.#settings.requestMs },\n );\n return resultOf(result);\n } catch (error) {\n const failure = failureOf(error, signal, this.#closed);\n const refusal = this.#refusal();\n const shown = refusal ?? (failure === \"server_error\" ? error : undefined);\n const detail = shown === undefined ? \"\" : `: ${describe(shown, this.#settings.secrets)}`;\n throw new McpError(\"mcp_call_failed\", this.server, `${FAILURE_TEXT[failure]}${detail}`, {\n cause: error,\n failure,\n });\n }\n }\n\n stderr(): string {\n return this.#channel instanceof StdioChannel ? this.#channel.stderr : \"\";\n }\n\n close(): Promise<void> {\n this.#closing ??= (async () => {\n this.#closed = true;\n this.#watchers.clear();\n if (this.#listenTimer !== undefined) this.#timers.clearTimeout(this.#listenTimer);\n await this.#subscription?.close().catch(() => {});\n await this.#client.close().catch(() => {});\n await this.#channel.close().catch(() => {});\n })();\n return this.#closing;\n }\n}\n\n/** A channel, and for a remote one the bound that closed it, which explains a failure better than the library can. */\ninterface Opened {\n readonly channel: McpChannel;\n readonly refusal: () => Error | undefined;\n readonly plannedListenCut?: () => boolean;\n}\n\nfunction channelOf(config: McpServerConfig, log: (line: string) => void, timers: McpTimers): Opened {\n const transport = config.transport;\n const none = () => undefined;\n if (transport.kind === \"stdio\") return { channel: new StdioChannel(transport, log), refusal: none };\n if (transport.kind === \"http\" || transport.kind === \"sse\") return remoteChannel(transport, log, timers);\n return { channel: transport.channel, refusal: none };\n}\n\n/** What a handshake works with besides the channel. */\ninterface HandshakeContext {\n readonly config: McpServerConfig;\n readonly settings: Settings;\n readonly log: (line: string) => void;\n readonly timers: McpTimers;\n}\n\n/** Connects through `channel`, bounded by `connectMs`, and closes everything when it fails. */\nasync function handshake(\n context: HandshakeContext,\n opened: Opened,\n prior: \"legacy\" | undefined,\n deadline: { readonly ms: number; readonly signal: AbortSignal | undefined },\n): Promise<Connection> {\n const { config, settings, log } = context;\n const { channel } = opened;\n const client = new Client(CLIENT_INFO, {\n capabilities: {},\n versionNegotiation: { mode: \"auto\", probe: { timeoutMs: settings.probeMs } },\n // A server's request for user input fails the call: whether it may pause a turn waits on the owner.\n inputRequired: { autoFulfill: false },\n listMaxPages: MAX_LIST_PAGES,\n // The harness reads a result's content, not its structured content, so a server's output schema is never compiled:\n // a hostile pattern or reference in it can cost nothing.\n jsonSchemaValidator: {\n getValidator: () => (input: unknown) => ({ valid: true, data: input as never, errorMessage: undefined }),\n },\n });\n // A changed list is passed to the connection's watchers, which read it again and diff it against the pins. The same\n // handler serves a legacy server's unsolicited notice and a 2026-07-28 server's notice on its listen stream.\n const hub: ChangeHub = { fire: () => {} };\n client.setNotificationHandler(\"notifications/tools/list_changed\", () => {\n log(`the server \"${config.name}\" says its tool list changed`);\n hub.fire();\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onAbort: (() => void) | undefined;\n const expired = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`the handshake did not finish in ${settings.connectMs} ms`)),\n Math.max(1, deadline.ms),\n );\n onAbort = () => reject(new Error(\"the connect was aborted\"));\n if (deadline.signal?.aborted) onAbort();\n else deadline.signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n try {\n const connecting = client.connect(channel as unknown as Transport, {\n timeout: Math.max(1, deadline.ms),\n ...(prior === undefined ? {} : { prior: { kind: prior } }),\n });\n connecting.catch(() => {});\n await Promise.race([connecting, expired]);\n const era = client.getProtocolEra();\n const version = client.getNegotiatedProtocolVersion() ?? \"\";\n if (era === \"modern\" && version !== MODERN_VERSION) {\n throw new Error(`the server negotiated the revision ${shortText(version, 32)}, which this harness does not know`);\n }\n return new Connection({\n server: config.name,\n client,\n channel,\n settings,\n era: era === \"modern\" ? MODERN_VERSION : \"legacy\",\n version,\n hub,\n timers: context.timers,\n log,\n refusal: opened.refusal,\n plannedListenCut: opened.plannedListenCut ?? (() => false),\n });\n } catch (error) {\n await client.close().catch(() => {});\n await channel.close().catch(() => {});\n throw error;\n } finally {\n clearTimeout(timer);\n if (onAbort !== undefined) deadline.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/**\n * Connects one server and negotiates its era. A stdio server that exits cleanly after the `server/discover` probe, as\n * servers on some older SDKs do on any request before `initialize`, is started once more and spoken to as a legacy\n * server; a server that crashes runs once. An `sse` server is spoken to as a legacy server, with no probe. The whole\n * connect, a restart included, takes at most `connectTimeoutMs`. `signal` aborts it, and the server is closed. On a\n * 2026-07-28 server that advertises tool-list changes, the connection opens a `subscriptions/listen` stream for them.\n * `timers` runs the stream's reopen delays; the default is the platform's.\n *\n * Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be used, and an `McpError`, code\n * `mcp_connect_failed`, when the server does not start, does not finish the handshake within `connectTimeoutMs`, is\n * aborted, or negotiates a revision this harness does not know.\n */\nexport async function connectMcpServer(\n config: McpServerConfig,\n options: { readonly log?: (line: string) => void; readonly signal?: AbortSignal; readonly timers?: McpTimers } = {},\n): Promise<McpConnection> {\n const settings = checkServerConfig(config);\n const log = options.log ?? (() => {});\n const timers = options.timers ?? systemTimers;\n const context: HandshakeContext = { config, settings, log, timers };\n const ends = Date.now() + settings.connectMs;\n const left = () => ({ ms: ends - Date.now(), signal: options.signal });\n const opened = channelOf(config, log, timers);\n const failed = (error: unknown) => {\n const cause = opened.refusal() ?? error;\n return new McpError(\"mcp_connect_failed\", config.name, `it did not connect: ${describe(cause, settings.secrets)}`, {\n cause: error,\n });\n };\n const channel = opened.channel;\n const prior = config.transport.kind === \"sse\" ? \"legacy\" : undefined;\n let connection: Connection;\n try {\n connection = await handshake(context, opened, prior, left());\n } catch (first) {\n const exitedOnProbe = channel instanceof StdioChannel && channel.exitedOnProbe;\n if (!exitedOnProbe || options.signal?.aborted === true || left().ms <= 0) throw failed(first);\n log(`the server \"${config.name}\" closed after the probe, so it is started again as a legacy server`);\n try {\n connection = await handshake(context, channelOf(config, log, timers), \"legacy\", left());\n } catch (second) {\n throw failed(second);\n }\n }\n connection.listen();\n return connection;\n}\n"]}
@@ -1,7 +1,10 @@
1
1
  /** The MCP client's named error: a `HarnessError` that names the server it came from. */
2
2
  import { HarnessError, type HarnessErrorCode } from "../errors.js";
3
- /** Why an MCP tool call ended without a result. */
4
- export type McpCallFailure = "closed" | "timeout" | "aborted" | "input_required" | "server_error";
3
+ /**
4
+ * Why an MCP tool call ended without a result. `disabled`: the tool is new, changed or removed since it was pinned,
5
+ * and the call never reached the server.
6
+ */
7
+ export type McpCallFailure = "closed" | "timeout" | "aborted" | "input_required" | "server_error" | "disabled";
5
8
  /**
6
9
  * Thrown for a server that could not connect (`mcp_connect_failed`), a tool list the harness refuses
7
10
  * (`mcp_tool_list_refused`) and a tool call that ended with no result (`mcp_call_failed`, with `failure` saying why).
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/mcp/errors.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,OAAO,EAAE,YAAY,EAAyB,MAAM,cAAc,CAAC;AAKnE;;;;GAIG;AACH,MAAM,OAAO,QAAS,SAAQ,YAAY;IACtB,IAAI,GAAG,UAAU,CAAC;IACpC,+CAA+C;IACtC,MAAM,CAAS;IACxB,gDAAgD;IACvC,OAAO,CAAkB;IAElC,YACE,IAAmG,EACnG,MAAc,EACd,OAAe,EACf,OAA8D;QAE9D,KAAK,CAAC,IAAI,EAAE,eAAe,MAAM,MAAM,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;QAC3D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,OAAO,EAAE,OAAO,KAAK,SAAS;YAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IACrE,CAAC;CACF","sourcesContent":["/** The MCP client's named error: a `HarnessError` that names the server it came from. */\nimport { HarnessError, type HarnessErrorCode } from \"../errors.js\";\n\n/** Why an MCP tool call ended without a result. */\nexport type McpCallFailure = \"closed\" | \"timeout\" | \"aborted\" | \"input_required\" | \"server_error\";\n\n/**\n * Thrown for a server that could not connect (`mcp_connect_failed`), a tool list the harness refuses\n * (`mcp_tool_list_refused`) and a tool call that ended with no result (`mcp_call_failed`, with `failure` saying why).\n * Its message names the server and never holds the server's standard error.\n */\nexport class McpError extends HarnessError {\n override readonly name = \"McpError\";\n /** The name of the server, from its config. */\n readonly server: string;\n /** Why a call failed, for `mcp_call_failed`. */\n readonly failure?: McpCallFailure;\n\n constructor(\n code: Extract<HarnessErrorCode, \"mcp_connect_failed\" | \"mcp_tool_list_refused\" | \"mcp_call_failed\">,\n server: string,\n message: string,\n options?: ErrorOptions & { readonly failure?: McpCallFailure },\n ) {\n super(code, `MCP server \"${server}\": ${message}`, options);\n this.server = server;\n if (options?.failure !== undefined) this.failure = options.failure;\n }\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/mcp/errors.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,OAAO,EAAE,YAAY,EAAyB,MAAM,cAAc,CAAC;AAQnE;;;;GAIG;AACH,MAAM,OAAO,QAAS,SAAQ,YAAY;IACtB,IAAI,GAAG,UAAU,CAAC;IACpC,+CAA+C;IACtC,MAAM,CAAS;IACxB,gDAAgD;IACvC,OAAO,CAAkB;IAElC,YACE,IAAmG,EACnG,MAAc,EACd,OAAe,EACf,OAA8D;QAE9D,KAAK,CAAC,IAAI,EAAE,eAAe,MAAM,MAAM,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;QAC3D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,OAAO,EAAE,OAAO,KAAK,SAAS;YAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IACrE,CAAC;CACF","sourcesContent":["/** The MCP client's named error: a `HarnessError` that names the server it came from. */\nimport { HarnessError, type HarnessErrorCode } from \"../errors.js\";\n\n/**\n * Why an MCP tool call ended without a result. `disabled`: the tool is new, changed or removed since it was pinned,\n * and the call never reached the server.\n */\nexport type McpCallFailure = \"closed\" | \"timeout\" | \"aborted\" | \"input_required\" | \"server_error\" | \"disabled\";\n\n/**\n * Thrown for a server that could not connect (`mcp_connect_failed`), a tool list the harness refuses\n * (`mcp_tool_list_refused`) and a tool call that ended with no result (`mcp_call_failed`, with `failure` saying why).\n * Its message names the server and never holds the server's standard error.\n */\nexport class McpError extends HarnessError {\n override readonly name = \"McpError\";\n /** The name of the server, from its config. */\n readonly server: string;\n /** Why a call failed, for `mcp_call_failed`. */\n readonly failure?: McpCallFailure;\n\n constructor(\n code: Extract<HarnessErrorCode, \"mcp_connect_failed\" | \"mcp_tool_list_refused\" | \"mcp_call_failed\">,\n server: string,\n message: string,\n options?: ErrorOptions & { readonly failure?: McpCallFailure },\n ) {\n super(code, `MCP server \"${server}\": ${message}`, options);\n this.server = server;\n if (options?.failure !== undefined) this.failure = options.failure;\n }\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import type { RemoteSettings } from "./remote-config.js";
2
+ /** A fetch, as the client library calls it. */
3
+ export type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;
4
+ /** An error from the guard, with a code the connection maps to a clear message. */
5
+ export declare class RemoteRefusal extends Error {
6
+ /**
7
+ * `too_large` for a body, an event or a line past its bound; `full` for a stream past `maxStreamBytes` in all;
8
+ * `timeout` for a time bound.
9
+ */
10
+ readonly code: "unauthorized" | "redirect" | "refused" | "too_large" | "full" | "timeout";
11
+ constructor(code: RemoteRefusal["code"], message: string);
12
+ }
13
+ /**
14
+ * What a response is for: `request` answers one request; `get` is a streamable HTTP server's `GET` stream and
15
+ * `listen` a `subscriptions/listen` stream, both meant to stay open and both opened again when they end; `events` is
16
+ * a legacy SSE server's one stream, which nothing can open again.
17
+ */
18
+ export type StreamKind = "request" | "get" | "listen" | "events";
19
+ /**
20
+ * The checks a remote server's fetch adds. `onGet` decides whether a `GET` may go out; false refuses it. `endless`
21
+ * marks a `GET` as a legacy SSE server's one stream, which has no time or total-byte bound. `onBroken` hears of a body
22
+ * cut for a bound: `fatal` for an event, a line or a body past its size, or any bound on the answer to one request,
23
+ * since the server is then broken or hostile. A time or total-byte cut of a `get` or `listen` stream is planned, not
24
+ * fatal: the stream ends and is opened again.
25
+ */
26
+ export interface GuardHooks {
27
+ readonly onGet?: () => boolean;
28
+ readonly endless?: boolean;
29
+ readonly onBroken?: (error: RemoteRefusal, fatal: boolean, kind: StreamKind) => void;
30
+ readonly log: (line: string) => void;
31
+ }
32
+ /** `base` wrapped in the checks this module describes. */
33
+ export declare function guardedFetch(base: FetchLike, settings: RemoteSettings, hooks: GuardHooks): FetchLike;