@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,17 +8,28 @@
8
8
  * behind. Every tool is marked as not first-party and as a write, whatever its annotations say, so a server's
9
9
  * `readOnlyHint` can't make the loop run its calls together or run one again after a crash. The calls reach the server
10
10
  * only through the turn's tool pipeline, so the permission gate and the write cap apply to them as to any tool.
11
+ *
12
+ * Servers connect in the background, and everything that changes a session's tools waits for a turn boundary:
13
+ * `beginTurn()` registers the servers that connected since the last turn, sets which tools may run, and writes a
14
+ * notice of what changed. A tool runs only while its server's current definition matches its pin, so a server that
15
+ * changes a tool after it was approved gets the tool disabled at the next turn, never mid-turn, and never silently.
11
16
  */
12
17
  import { defineTool } from "@buildanagent/sdk";
13
18
  import { HarnessError } from "../errors.js";
14
- import { checkServerConfig, connectMcpServer } from "./connection.js";
19
+ import { checkServerConfig, connectMcpServer, systemTimers } from "./connection.js";
15
20
  import { safeSchema } from "./content.js";
16
21
  import { McpError } from "./errors.js";
22
+ import { checkPins, toolPinOf } from "./pins.js";
17
23
  import { mcpRecordOf } from "./record.js";
18
24
  // A placeholder that passes defineTool()'s name check; the registry names every tool by its canonical name.
19
25
  const PLACEHOLDER_NAME = "mcp_tool";
20
- /** The definition of one server tool. Its `execute` calls the tool by the name the server listed at connect. */
21
- function definitionOf(connection, tool) {
26
+ const DEFAULT_DIRECT_WAIT_MS = 10_000;
27
+ const DEFAULT_RELIST_INTERVAL_MS = 2_000;
28
+ // The most lines one notice holds; the rest are counted, so a server that changes many tools can't flood a turn.
29
+ const MAX_NOTICE_LINES = 20;
30
+ const MAX_TIMER_MS = 2 ** 31 - 1;
31
+ /** The definition of one server tool. Its `execute` refuses a disabled tool and calls the rest by their listed name. */
32
+ function definitionOf(state, connection, tool) {
22
33
  return defineTool({
23
34
  name: PLACEHOLDER_NAME,
24
35
  description: tool.description,
@@ -29,24 +40,25 @@ function definitionOf(connection, tool) {
29
40
  // A server's hints are claims by code the harness does not control, so every call is treated as a write.
30
41
  effect: { kind: "write" },
31
42
  async execute(input, ctx) {
43
+ if (!state.enabled.has(tool.name)) {
44
+ throw new McpError("mcp_call_failed", state.config.name, "the tool is disabled: its definition is new, changed or gone since it was pinned, and no person has approved it", { failure: "disabled" });
45
+ }
32
46
  const result = await connection.callTool(tool.name, input, ctx.signal);
33
47
  return { content: result.content, ...(result.isError ? { isError: true } : {}) };
34
48
  },
35
49
  });
36
50
  }
37
- function registrationOf(config, connection, tool) {
38
- return {
39
- name: tool.name,
40
- source: `mcp:${config.name}`,
41
- ...(config.exposure === undefined ? {} : { exposure: config.exposure }),
42
- definition: definitionOf(connection, tool),
43
- };
44
- }
45
51
  /** The server's registrations, built before any is registered, so a tool the SDK refuses fails the whole list. */
46
- function registrationsOf(config, connection, tools) {
52
+ function registrationsOf(state, connection, tools) {
53
+ const { config } = state;
47
54
  return tools.map((tool) => {
48
55
  try {
49
- return registrationOf(config, connection, tool);
56
+ return {
57
+ name: tool.name,
58
+ source: `mcp:${config.name}`,
59
+ ...(config.exposure === undefined ? {} : { exposure: config.exposure }),
60
+ definition: definitionOf(state, connection, tool),
61
+ };
50
62
  }
51
63
  catch (error) {
52
64
  throw refused(config.name, error);
@@ -70,95 +82,464 @@ function checkServers(servers) {
70
82
  names.add(key);
71
83
  }
72
84
  }
85
+ function wait(name, value, fallback) {
86
+ if (value === undefined)
87
+ return fallback;
88
+ if (!(Number.isInteger(value) && value >= 0 && value <= MAX_TIMER_MS)) {
89
+ throw new HarnessError("invalid_mcp_config", `${name} must be a whole number of milliseconds from 0 to ${MAX_TIMER_MS}`);
90
+ }
91
+ return value;
92
+ }
93
+ /** The hashes of a list, by tool name. */
94
+ async function listedOf(tools) {
95
+ const hashes = await Promise.all(tools.map(toolPinOf));
96
+ return new Map(tools.map((tool, index) => [tool.name, { tool, hash: hashes[index] }]));
97
+ }
98
+ /** The label a registered tool has now. */
99
+ function labelOf(state, name) {
100
+ if (state.enabled.has(name))
101
+ return "enabled";
102
+ if (state.unreadable)
103
+ return "unreadable";
104
+ const now = state.latest.get(name);
105
+ if (now === undefined)
106
+ return "removed";
107
+ const pin = state.pinned.get(name);
108
+ if (pin === undefined)
109
+ return "new";
110
+ return pin === now.hash ? "stale" : "changed";
111
+ }
112
+ const SENTENCES = {
113
+ enabled: "was approved and may be called again",
114
+ new: "is new on its server and is disabled until a person approves it",
115
+ changed: "changed its definition on its server and is disabled until a person approves it",
116
+ removed: "was removed by its server and is disabled",
117
+ unreadable: "is disabled, because its server's tool list could not be read",
118
+ stale: "is disabled for this session, because the definition it was registered with is not the approved one; a new session registers the approved one",
119
+ };
120
+ /** The notice lines of one server: each tool whose label changed, and the count of tools it added mid-session. */
121
+ function noticeLinesOf(state, commits) {
122
+ const lines = [];
123
+ for (const [name, canonical] of state.registered) {
124
+ const label = labelOf(state, name);
125
+ if (label === (state.announced.get(name) ?? "enabled"))
126
+ continue;
127
+ commits.push(() => state.announced.set(name, label));
128
+ lines.push(`- ${canonical} ${SENTENCES[label]}.`);
129
+ }
130
+ const added = state.unreadable ? 0 : [...state.latest.keys()].filter((name) => !state.registered.has(name)).length;
131
+ if (added === state.announcedAdded)
132
+ return lines;
133
+ commits.push(() => {
134
+ state.announcedAdded = added;
135
+ });
136
+ // The server's name comes from the host's config; the new tools' names are the server's text, so only their number
137
+ // is given.
138
+ if (added > 0) {
139
+ const tools = added === 1 ? "1 tool" : `${added} tools`;
140
+ const them = added === 1 ? "it" : "them";
141
+ lines.push(`- The server "${state.config.name}" lists ${tools} this session does not have; a person may approve ${them} for a later session.`);
142
+ }
143
+ return lines;
144
+ }
145
+ const newState = (config) => ({
146
+ config,
147
+ status: "connecting",
148
+ done: Promise.resolve(),
149
+ pinned: new Map(),
150
+ latest: new Map(),
151
+ unreadable: false,
152
+ registered: new Map(),
153
+ registeredHash: new Map(),
154
+ enabled: new Set(),
155
+ announced: new Map(),
156
+ announcedAdded: 0,
157
+ relist: { timer: undefined, running: false, dirty: false, last: Number.NEGATIVE_INFINITY },
158
+ pinWrites: Promise.resolve(),
159
+ });
73
160
  class Manager {
74
161
  #options;
75
- #connections = new Map();
162
+ #timers;
163
+ #directWaitMs;
164
+ #relistMs;
165
+ #states;
76
166
  #records = new Map();
77
167
  // Every connection that exists, registered or not, so a close can end one whose tool list is still being read.
78
168
  #open = new Set();
79
169
  #abort = new AbortController();
170
+ #started = false;
171
+ #firstTurnDone = false;
172
+ // What the last notice told, kept back until the turn has written it, so a turn that fails first loses no notice.
173
+ #uncommitted = [];
80
174
  #connecting;
81
175
  #closing;
82
176
  constructor(options) {
83
177
  this.#options = options;
178
+ this.#timers = options.timers ?? systemTimers;
179
+ this.#directWaitMs = wait("directWaitMs", options.directWaitMs, DEFAULT_DIRECT_WAIT_MS);
180
+ this.#relistMs = wait("relistIntervalMs", options.relistIntervalMs, DEFAULT_RELIST_INTERVAL_MS);
181
+ this.#states = options.servers.map(newState);
182
+ }
183
+ #log(line) {
184
+ try {
185
+ this.#options.log?.(line);
186
+ }
187
+ catch {
188
+ // A logger that throws must not stop a connect.
189
+ }
190
+ }
191
+ start() {
192
+ if (this.#started || this.#options.mcp === false || this.#closing !== undefined)
193
+ return;
194
+ this.#started = true;
195
+ for (const state of this.#states)
196
+ state.done = this.#connectOne(state);
84
197
  }
85
198
  connect() {
86
199
  if (this.#closing !== undefined) {
87
200
  return Promise.reject(new HarnessError("invalid_mcp_config", "the MCP manager was closed"));
88
201
  }
89
- this.#connecting ??=
90
- this.#options.mcp === false
91
- ? Promise.resolve([])
92
- : Promise.all(this.#options.servers.map((config) => this.#connectOne(config)));
202
+ this.#connecting ??= (async () => {
203
+ if (this.#options.mcp === false)
204
+ return [];
205
+ this.start();
206
+ // Each server is registered as soon as it connects, so one that hangs holds back no other.
207
+ await Promise.all(this.#states.map((state) => state.done.then(() => this.#registerReady(this.#firstTurnDone))));
208
+ // Every server has connected or failed by now, and registerReady() registered or failed each connected one.
209
+ return this.statuses().filter((status) => status.status !== "connecting");
210
+ })();
93
211
  return this.#connecting;
94
212
  }
95
- async #connectOne(config) {
96
- const log = this.#options.log ?? (() => { });
213
+ statuses() {
214
+ if (this.#options.mcp === false)
215
+ return [];
216
+ return this.#states.map((state) => {
217
+ const server = state.config.name;
218
+ if (state.status === "failed")
219
+ return { server, status: "failed", error: state.error };
220
+ if (state.status !== "registered" || state.connection === undefined)
221
+ return { server, status: "connecting" };
222
+ const names = [...state.registered];
223
+ return {
224
+ server,
225
+ status: "connected",
226
+ era: state.connection.era,
227
+ tools: names.map(([, canonical]) => canonical),
228
+ disabled: names.filter(([name]) => !state.enabled.has(name)).map(([, canonical]) => canonical),
229
+ };
230
+ });
231
+ }
232
+ async #connectOne(state) {
233
+ const { config } = state;
97
234
  let connection;
98
235
  try {
99
- connection = await connectMcpServer(config, { log, signal: this.#abort.signal });
236
+ connection = await connectMcpServer(config, {
237
+ log: (line) => this.#log(line),
238
+ signal: this.#abort.signal,
239
+ timers: this.#timers,
240
+ });
100
241
  this.#open.add(connection);
101
242
  // A close that began during the handshake must still end this server.
102
243
  if (this.#closing !== undefined)
103
244
  throw new McpError("mcp_connect_failed", config.name, "the manager was closed");
104
- const listed = await connection.listTools();
105
- const registrations = registrationsOf(config, connection, listed);
245
+ // A notice that comes while the first list is read is kept, and the list is read again once it is in.
246
+ connection.watchTools(() => this.#scheduleRelist(state));
247
+ const tools = await connection.listTools();
248
+ const registrations = registrationsOf(state, connection, tools);
106
249
  let record;
250
+ let latest;
107
251
  try {
108
- record = await mcpRecordOf(config, connection, listed);
252
+ record = await mcpRecordOf(config, connection, tools);
253
+ latest = await listedOf(tools);
109
254
  }
110
255
  catch (error) {
111
256
  throw refused(config.name, error);
112
257
  }
258
+ const pinned = await this.#pinsOf(config.name, latest);
113
259
  if (this.#closing !== undefined)
114
260
  throw new McpError("mcp_connect_failed", config.name, "the manager was closed");
115
- // Nothing awaits between this check and the registration, so another manager on the same registry can't
116
- // register the source in between, and registerAll() leaves nothing behind when any tool is refused.
117
- const source = `mcp:${config.name}`;
118
- if (this.#options.registry.list().some((tool) => tool.source === source)) {
119
- throw new McpError("mcp_tool_list_refused", config.name, `the registry already holds tools from ${source}`);
120
- }
121
- let tools;
261
+ // The hashes come from the list the registrations were built from, never from a later re-read, so a server that
262
+ // lists another definition before the turn boundary can't make the registered one look approved.
263
+ const hashes = new Map([...latest].map(([name, listed]) => [name, listed.hash]));
264
+ Object.assign(state, {
265
+ connection,
266
+ latest,
267
+ pinned,
268
+ staged: { registrations, record, hashes },
269
+ status: "connected",
270
+ });
271
+ if (state.relist.dirty)
272
+ this.#scheduleRelist(state);
273
+ }
274
+ catch (error) {
275
+ if (connection !== undefined)
276
+ this.#open.delete(connection);
277
+ await connection?.close();
278
+ this.#fail(state, error);
279
+ }
280
+ }
281
+ /** The server's pins: the store's, or the list it gave at connect when the manager has no store. */
282
+ async #pinsOf(server, latest) {
283
+ const store = this.#options.pins;
284
+ if (store === undefined)
285
+ return new Map([...latest].map(([name, listed]) => [name, listed.hash]));
286
+ const stored = await store.read(server);
287
+ return stored === undefined ? new Map() : checkPins(server, stored);
288
+ }
289
+ #fail(state, error) {
290
+ const failure = error instanceof Error ? error : new Error(String(error));
291
+ state.status = "failed";
292
+ state.error = failure;
293
+ this.#log(`the MCP server "${state.config.name}" was not connected: ${failure.message}`);
294
+ }
295
+ /**
296
+ * Registers every server that has connected and is not registered yet. `late` is true after the first turn's wait,
297
+ * when a `direct` server is registered as `deferred`, so the tools a request sends never change mid-session.
298
+ */
299
+ #registerReady(late) {
300
+ for (const state of this.#states) {
301
+ const staged = state.staged;
302
+ const connection = state.connection;
303
+ if (state.status !== "connected" || staged === undefined || connection === undefined)
304
+ continue;
305
+ state.staged = undefined;
122
306
  try {
123
- tools = this.#options.registry.registerAll(registrations).map((tool) => tool.canonicalName);
307
+ this.#register(state, staged, late && state.config.exposure === "direct");
124
308
  }
125
309
  catch (error) {
126
- throw refused(config.name, error);
310
+ this.#open.delete(connection);
311
+ void connection.close();
312
+ this.#fail(state, error);
127
313
  }
128
- this.#connections.set(config.name, connection);
129
- this.#records.set(config.name, record);
130
- return { server: config.name, status: "connected", era: connection.era, tools };
314
+ }
315
+ }
316
+ #register(state, staged, demote) {
317
+ const { config } = state;
318
+ if (demote) {
319
+ this.#log(`the direct MCP server "${config.name}" connected after the first turn, so its tools are deferred`);
320
+ }
321
+ // Nothing awaits between this check and the registration, so another manager on the same registry can't register
322
+ // the source in between, and registerAll() leaves nothing behind when any tool is refused.
323
+ const source = `mcp:${config.name}`;
324
+ if (this.#options.registry.list().some((tool) => tool.source === source)) {
325
+ throw new McpError("mcp_tool_list_refused", config.name, `the registry already holds tools from ${source}`);
326
+ }
327
+ const registrations = demote
328
+ ? staged.registrations.map((registration) => ({ ...registration, exposure: "deferred" }))
329
+ : staged.registrations;
330
+ let tools;
331
+ try {
332
+ tools = this.#options.registry.registerAll(registrations).map((tool) => tool.canonicalName);
131
333
  }
132
334
  catch (error) {
133
- if (connection !== undefined)
134
- this.#open.delete(connection);
135
- await connection?.close();
136
- const failure = error instanceof Error ? error : new Error(String(error));
137
- log(`the MCP server "${config.name}" was not connected: ${failure.message}`);
138
- return { server: config.name, status: "failed", error: failure };
335
+ throw refused(config.name, error);
139
336
  }
337
+ state.registered = new Map(registrations.map((registration, index) => [registration.name, tools[index]]));
338
+ state.registeredHash = new Map(registrations.map(({ name }) => [name, staged.hashes.get(name) ?? ""]));
339
+ state.status = "registered";
340
+ this.#records.set(config.name, staged.record);
341
+ this.#settle(state);
342
+ }
343
+ /** Sets which of a server's tools may run: those whose current definition matches their pin. */
344
+ #settle(state) {
345
+ const enabled = new Set();
346
+ if (!state.unreadable) {
347
+ for (const name of state.registered.keys()) {
348
+ const now = state.latest.get(name);
349
+ // The model reads the definition registered at connect, so that one must be the approved one too, or a server
350
+ // could register an unapproved definition and then list the approved one to have it enabled.
351
+ const pin = state.pinned.get(name);
352
+ if (now !== undefined && pin === now.hash && pin === state.registeredHash.get(name))
353
+ enabled.add(name);
354
+ }
355
+ }
356
+ state.enabled = enabled;
357
+ }
358
+ async beginTurn(signal = new AbortController().signal) {
359
+ if (this.#options.mcp === false || this.#closing !== undefined)
360
+ return [];
361
+ this.start();
362
+ if (!this.#firstTurnDone) {
363
+ await this.#waitForDirect(signal);
364
+ this.#registerReady(false);
365
+ this.#firstTurnDone = true;
366
+ }
367
+ else {
368
+ this.#registerReady(true);
369
+ }
370
+ for (const state of this.#states)
371
+ if (state.status === "registered")
372
+ this.#settle(state);
373
+ this.#uncommitted = [];
374
+ const lines = this.#noticeLines(this.#uncommitted);
375
+ if (lines.length === 0)
376
+ return [];
377
+ const shown = lines.slice(0, MAX_NOTICE_LINES);
378
+ if (lines.length > shown.length)
379
+ shown.push(`- and ${lines.length - shown.length} more changes.`);
380
+ return [
381
+ [
382
+ "Harness notice: the MCP tools changed since the last turn. The tools you were given are the same, and a",
383
+ "disabled tool's call is refused before it reaches its server.",
384
+ ...shown,
385
+ ].join("\n"),
386
+ ];
387
+ }
388
+ /** Waits, once, for every `direct` server to connect or fail, up to `directWaitMs`, or until `signal` aborts. */
389
+ async #waitForDirect(signal) {
390
+ const direct = this.#states.filter((state) => state.config.exposure === "direct");
391
+ if (direct.length === 0 || signal.aborted)
392
+ return;
393
+ let handle;
394
+ let onAbort;
395
+ await new Promise((resolve) => {
396
+ handle = this.#timers.setTimeout(resolve, this.#directWaitMs);
397
+ onAbort = () => resolve();
398
+ signal.addEventListener("abort", onAbort, { once: true });
399
+ void Promise.all(direct.map((state) => state.done)).then(() => resolve());
400
+ });
401
+ this.#timers.clearTimeout(handle);
402
+ if (onAbort !== undefined)
403
+ signal.removeEventListener("abort", onAbort);
404
+ }
405
+ /** One line per tool whose label changed since the last notice, naming it by canonical name only. */
406
+ #noticeLines(commits) {
407
+ return this.#states
408
+ .filter((state) => state.status === "registered")
409
+ .flatMap((state) => noticeLinesOf(state, commits));
410
+ }
411
+ commitNotices() {
412
+ for (const commit of this.#uncommitted.splice(0))
413
+ commit();
414
+ }
415
+ /** Reads a server's list again after it said the list changed, at most once per `relistIntervalMs`. */
416
+ #scheduleRelist(state) {
417
+ if (this.#closing !== undefined || state.status === "failed")
418
+ return;
419
+ const relist = state.relist;
420
+ if (state.status === "connecting" || relist.running || relist.timer !== undefined) {
421
+ relist.dirty = true;
422
+ return;
423
+ }
424
+ const delay = Math.max(0, relist.last + this.#relistMs - this.#timers.now());
425
+ relist.timer = this.#timers.setTimeout(() => {
426
+ relist.timer = undefined;
427
+ void this.#relist(state);
428
+ }, delay);
429
+ }
430
+ async #relist(state) {
431
+ const relist = state.relist;
432
+ const connection = state.connection;
433
+ if (connection === undefined || this.#closing !== undefined)
434
+ return;
435
+ relist.running = true;
436
+ relist.dirty = false;
437
+ relist.last = this.#timers.now();
438
+ try {
439
+ state.latest = await listedOf(await connection.listTools());
440
+ state.unreadable = false;
441
+ }
442
+ catch (error) {
443
+ if (!state.unreadable) {
444
+ const why = error instanceof Error ? error.message : String(error);
445
+ this.#log(`the changed tool list of "${state.config.name}" could not be read, so its tools are disabled from the next turn: ${why}`);
446
+ }
447
+ state.unreadable = true;
448
+ }
449
+ finally {
450
+ relist.running = false;
451
+ }
452
+ if (relist.dirty)
453
+ this.#scheduleRelist(state);
454
+ }
455
+ pending() {
456
+ const waiting = [];
457
+ for (const state of this.#states) {
458
+ for (const [name, listed] of state.latest) {
459
+ if (state.pinned.get(name) === listed.hash)
460
+ continue;
461
+ const canonicalName = state.registered.get(name);
462
+ waiting.push({
463
+ server: state.config.name,
464
+ tool: name,
465
+ ...(canonicalName === undefined ? {} : { canonicalName }),
466
+ state: state.pinned.has(name) ? "changed" : "new",
467
+ hash: listed.hash,
468
+ definition: listed.tool,
469
+ });
470
+ }
471
+ }
472
+ return waiting;
473
+ }
474
+ async approve(server, tool, hash) {
475
+ const state = this.#states.find((candidate) => candidate.config.name === server);
476
+ const listed = state?.latest.get(tool);
477
+ if (state === undefined || listed === undefined || listed.hash !== hash) {
478
+ throw new HarnessError("invalid_mcp_config", "that tool's current definition does not have this hash, so it was not approved; read pending() again");
479
+ }
480
+ const store = this.#options.pins;
481
+ if (store === undefined) {
482
+ state.pinned.set(tool, hash);
483
+ return;
484
+ }
485
+ // Writes of one server run one after another, and each builds its pins when its turn comes, so a later approval
486
+ // never lands under an earlier one. The pin is held in memory only once the store has it, so a failed write
487
+ // enables nothing.
488
+ const write = state.pinWrites.then(async () => {
489
+ await store.write(server, Object.fromEntries([...state.pinned, [tool, hash]]));
490
+ state.pinned.set(tool, hash);
491
+ });
492
+ state.pinWrites = write.catch(() => { });
493
+ await write;
494
+ }
495
+ permissionHook() {
496
+ return async (call) => {
497
+ const canonical = this.#options.registry.get?.(call.tool)?.canonicalName ?? call.tool;
498
+ for (const state of this.#states) {
499
+ for (const [name, registered] of state.registered) {
500
+ if (registered !== canonical)
501
+ continue;
502
+ if (state.enabled.has(name))
503
+ return undefined;
504
+ return {
505
+ decision: "deny",
506
+ reason: `${canonical} is disabled: its definition is new, changed or gone since it was pinned, and no person has approved it`,
507
+ rule: "mcp_pin",
508
+ };
509
+ }
510
+ }
511
+ return undefined;
512
+ };
140
513
  }
141
514
  records() {
142
- return this.#options.servers.flatMap((config) => this.#records.get(config.name) ?? []);
515
+ return this.#states.flatMap((state) => this.#records.get(state.config.name) ?? []);
143
516
  }
144
517
  connection(server) {
145
- return this.#connections.get(server);
518
+ const state = this.#states.find((candidate) => candidate.config.name === server);
519
+ return state?.status === "registered" ? state.connection : undefined;
146
520
  }
147
521
  close() {
148
522
  this.#closing ??= (async () => {
149
523
  // Aborting ends every handshake still running, and closing every open connection fails any tool list still being
150
524
  // read, so a server that hangs can't hold the others up.
151
525
  this.#abort.abort();
526
+ for (const state of this.#states) {
527
+ if (state.relist.timer !== undefined)
528
+ this.#timers.clearTimeout(state.relist.timer);
529
+ state.relist.timer = undefined;
530
+ }
152
531
  await Promise.all([...this.#open].map((connection) => connection.close()));
532
+ await Promise.all(this.#states.map((state) => state.done));
153
533
  await this.#connecting?.catch(() => { });
154
534
  })();
155
535
  return this.#closing;
156
536
  }
157
537
  }
158
538
  /**
159
- * Creates the MCP client for a set of servers. It checks every config now and starts nothing until `connect()`.
160
- * Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be used, two servers with one name, or a
161
- * registry without `register()`, `registerAll()` and `list()`.
539
+ * Creates the MCP client for a set of servers. It checks every config now and starts nothing until `start()`,
540
+ * `connect()` or the first `beginTurn()`. Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be
541
+ * used, two servers with one name, a registry without `register()`, `registerAll()` and `list()`, a pin store
542
+ * without `read()` and `write()`, or a wait that is not a whole number of milliseconds.
162
543
  */
163
544
  export function createMcpManager(options) {
164
545
  const registry = options?.registry;
@@ -168,6 +549,10 @@ export function createMcpManager(options) {
168
549
  }
169
550
  }
170
551
  checkServers(options.servers);
552
+ const pins = options.pins;
553
+ if (pins !== undefined && (typeof pins.read !== "function" || typeof pins.write !== "function")) {
554
+ throw new HarnessError("invalid_mcp_config", "createMcpManager() needs a pin store with read() and write()");
555
+ }
171
556
  return new Manager(options);
172
557
  }
173
558
  //# sourceMappingURL=manager.js.map