@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +822 -2
- package/dist/ablation.d.ts +2 -0
- package/dist/ablation.js +3 -0
- package/dist/ablation.js.map +1 -0
- package/dist/completion/check.d.ts +64 -0
- package/dist/completion/check.js +152 -0
- package/dist/completion/check.js.map +1 -0
- package/dist/completion/checks.d.ts +45 -0
- package/dist/completion/checks.js +173 -0
- package/dist/completion/checks.js.map +1 -0
- package/dist/completion/flags.d.ts +25 -0
- package/dist/completion/flags.js +87 -0
- package/dist/completion/flags.js.map +1 -0
- package/dist/completion/index.d.ts +8 -0
- package/dist/completion/index.js +9 -0
- package/dist/completion/index.js.map +1 -0
- package/dist/completion/snapshot.d.ts +33 -0
- package/dist/completion/snapshot.js +83 -0
- package/dist/completion/snapshot.js.map +1 -0
- package/dist/context/cap.d.ts +32 -0
- package/dist/context/cap.js +50 -0
- package/dist/context/cap.js.map +1 -0
- package/dist/context/estimate.d.ts +18 -0
- package/dist/context/estimate.js +20 -0
- package/dist/context/estimate.js.map +1 -0
- package/dist/context/file-spill.d.ts +15 -0
- package/dist/context/file-spill.js +40 -0
- package/dist/context/file-spill.js.map +1 -0
- package/dist/context/index.d.ts +10 -0
- package/dist/context/index.js +10 -0
- package/dist/context/index.js.map +1 -0
- package/dist/context/mask.d.ts +27 -0
- package/dist/context/mask.js +71 -0
- package/dist/context/mask.js.map +1 -0
- package/dist/context/mid-turn.d.ts +40 -0
- package/dist/context/mid-turn.js +82 -0
- package/dist/context/mid-turn.js.map +1 -0
- package/dist/context/policy.d.ts +9 -0
- package/dist/context/policy.js +140 -0
- package/dist/context/policy.js.map +1 -0
- package/dist/context/spill-ledger.d.ts +25 -0
- package/dist/context/spill-ledger.js +54 -0
- package/dist/context/spill-ledger.js.map +1 -0
- package/dist/context/spill.d.ts +10 -0
- package/dist/context/spill.js +18 -0
- package/dist/context/spill.js.map +1 -0
- package/dist/context/summarize.d.ts +53 -0
- package/dist/context/summarize.js +204 -0
- package/dist/context/summarize.js.map +1 -0
- package/dist/context/summary-template.d.ts +29 -0
- package/dist/context/summary-template.js +69 -0
- package/dist/context/summary-template.js.map +1 -0
- package/dist/context/types.d.ts +150 -0
- package/dist/context/types.js +2 -0
- package/dist/context/types.js.map +1 -0
- package/dist/context/write-cap.d.ts +19 -0
- package/dist/context/write-cap.js +41 -0
- package/dist/context/write-cap.js.map +1 -0
- package/dist/create-harness.d.ts +7 -0
- package/dist/create-harness.js +21 -0
- package/dist/create-harness.js.map +1 -0
- package/dist/credentials/addresses.d.ts +14 -0
- package/dist/credentials/addresses.js +144 -0
- package/dist/credentials/addresses.js.map +1 -0
- package/dist/credentials/allowlist.d.ts +54 -0
- package/dist/credentials/allowlist.js +134 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-policy.d.ts +69 -0
- package/dist/credentials/egress-policy.js +170 -0
- package/dist/credentials/egress-policy.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +82 -0
- package/dist/credentials/egress-proxy.js +650 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/git-route.d.ts +68 -0
- package/dist/credentials/git-route.js +288 -0
- package/dist/credentials/git-route.js.map +1 -0
- package/dist/credentials/index.d.ts +13 -0
- package/dist/credentials/index.js +14 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +23 -0
- package/dist/credentials/scrub.js +115 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +60 -0
- package/dist/errors.js +67 -0
- package/dist/errors.js.map +1 -0
- package/dist/extensions/compose.d.ts +27 -0
- package/dist/extensions/compose.js +83 -0
- package/dist/extensions/compose.js.map +1 -0
- package/dist/extensions/context-files-node.d.ts +28 -0
- package/dist/extensions/context-files-node.js +74 -0
- package/dist/extensions/context-files-node.js.map +1 -0
- package/dist/extensions/context-files.d.ts +68 -0
- package/dist/extensions/context-files.js +214 -0
- package/dist/extensions/context-files.js.map +1 -0
- package/dist/extensions/digest.d.ts +6 -0
- package/dist/extensions/digest.js +68 -0
- package/dist/extensions/digest.js.map +1 -0
- package/dist/extensions/index.d.ts +10 -0
- package/dist/extensions/index.js +10 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/load.d.ts +42 -0
- package/dist/extensions/load.js +211 -0
- package/dist/extensions/load.js.map +1 -0
- package/dist/extensions/lock.d.ts +8 -0
- package/dist/extensions/lock.js +95 -0
- package/dist/extensions/lock.js.map +1 -0
- package/dist/extensions/node.d.ts +10 -0
- package/dist/extensions/node.js +11 -0
- package/dist/extensions/node.js.map +1 -0
- package/dist/extensions/project-dirs.d.ts +24 -0
- package/dist/extensions/project-dirs.js +97 -0
- package/dist/extensions/project-dirs.js.map +1 -0
- package/dist/extensions/skills-node.d.ts +34 -0
- package/dist/extensions/skills-node.js +123 -0
- package/dist/extensions/skills-node.js.map +1 -0
- package/dist/extensions/skills.d.ts +51 -0
- package/dist/extensions/skills.js +175 -0
- package/dist/extensions/skills.js.map +1 -0
- package/dist/extensions/trust-file.d.ts +3 -0
- package/dist/extensions/trust-file.js +62 -0
- package/dist/extensions/trust-file.js.map +1 -0
- package/dist/extensions/trust-store-node.d.ts +10 -0
- package/dist/extensions/trust-store-node.js +33 -0
- package/dist/extensions/trust-store-node.js.map +1 -0
- package/dist/extensions/types.d.ts +42 -0
- package/dist/extensions/types.js +2 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/harness.d.ts +156 -0
- package/dist/harness.js +2 -0
- package/dist/harness.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/connection.d.ts +22 -0
- package/dist/mcp/connection.js +267 -0
- package/dist/mcp/connection.js.map +1 -0
- package/dist/mcp/content.d.ts +27 -0
- package/dist/mcp/content.js +177 -0
- package/dist/mcp/content.js.map +1 -0
- package/dist/mcp/errors.d.ts +19 -0
- package/dist/mcp/errors.js +21 -0
- package/dist/mcp/errors.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +7 -0
- package/dist/mcp/manager.js +173 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/record.d.ts +7 -0
- package/dist/mcp/record.js +20 -0
- package/dist/mcp/record.js.map +1 -0
- package/dist/mcp/stdio.d.ts +39 -0
- package/dist/mcp/stdio.js +382 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/types.d.ts +172 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.js +3 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/permissions/default-rules.d.ts +7 -0
- package/dist/permissions/default-rules.js +42 -0
- package/dist/permissions/default-rules.js.map +1 -0
- package/dist/permissions/errors.d.ts +11 -0
- package/dist/permissions/errors.js +14 -0
- package/dist/permissions/errors.js.map +1 -0
- package/dist/permissions/index.d.ts +9 -0
- package/dist/permissions/index.js +9 -0
- package/dist/permissions/index.js.map +1 -0
- package/dist/permissions/match.d.ts +33 -0
- package/dist/permissions/match.js +287 -0
- package/dist/permissions/match.js.map +1 -0
- package/dist/permissions/pipeline.d.ts +9 -0
- package/dist/permissions/pipeline.js +235 -0
- package/dist/permissions/pipeline.js.map +1 -0
- package/dist/permissions/rules.d.ts +22 -0
- package/dist/permissions/rules.js +74 -0
- package/dist/permissions/rules.js.map +1 -0
- package/dist/permissions/shadow.d.ts +5 -0
- package/dist/permissions/shadow.js +22 -0
- package/dist/permissions/shadow.js.map +1 -0
- package/dist/permissions/types.d.ts +104 -0
- package/dist/permissions/types.js +2 -0
- package/dist/permissions/types.js.map +1 -0
- package/dist/sandbox/base.d.ts +45 -0
- package/dist/sandbox/base.js +74 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +41 -0
- package/dist/sandbox/docker/index.js +497 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +44 -0
- package/dist/sandbox/errors.js +57 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +65 -0
- package/dist/sandbox/host-files.js +258 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +10 -0
- package/dist/sandbox/index.js +10 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/none.d.ts +17 -0
- package/dist/sandbox/none.js +108 -0
- package/dist/sandbox/none.js.map +1 -0
- package/dist/sandbox/policy.d.ts +49 -0
- package/dist/sandbox/policy.js +149 -0
- package/dist/sandbox/policy.js.map +1 -0
- package/dist/sandbox/process.d.ts +61 -0
- package/dist/sandbox/process.js +253 -0
- package/dist/sandbox/process.js.map +1 -0
- package/dist/sandbox/spawn-env.d.ts +20 -0
- package/dist/sandbox/spawn-env.js +128 -0
- package/dist/sandbox/spawn-env.js.map +1 -0
- package/dist/sandbox/srt/index.d.ts +38 -0
- package/dist/sandbox/srt/index.js +283 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +60 -0
- package/dist/sandbox/srt/settings.js +84 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +125 -0
- package/dist/sandbox/types.js +6 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/server/answers.d.ts +16 -0
- package/dist/server/answers.js +43 -0
- package/dist/server/answers.js.map +1 -0
- package/dist/server/connection.d.ts +99 -0
- package/dist/server/connection.js +309 -0
- package/dist/server/connection.js.map +1 -0
- package/dist/server/dispatcher.d.ts +86 -0
- package/dist/server/dispatcher.js +800 -0
- package/dist/server/dispatcher.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/local-transport.d.ts +44 -0
- package/dist/server/local-transport.js +103 -0
- package/dist/server/local-transport.js.map +1 -0
- package/dist/server/outbox.d.ts +31 -0
- package/dist/server/outbox.js +130 -0
- package/dist/server/outbox.js.map +1 -0
- package/dist/server/params.d.ts +25 -0
- package/dist/server/params.js +112 -0
- package/dist/server/params.js.map +1 -0
- package/dist/server/protocol.schema.json +2448 -0
- package/dist/server/rpc-session.d.ts +43 -0
- package/dist/server/rpc-session.js +167 -0
- package/dist/server/rpc-session.js.map +1 -0
- package/dist/server/stdio-streams.d.ts +67 -0
- package/dist/server/stdio-streams.js +218 -0
- package/dist/server/stdio-streams.js.map +1 -0
- package/dist/server/stdio.d.ts +59 -0
- package/dist/server/stdio.js +189 -0
- package/dist/server/stdio.js.map +1 -0
- package/dist/server/websocket.d.ts +106 -0
- package/dist/server/websocket.js +327 -0
- package/dist/server/websocket.js.map +1 -0
- package/dist/session/approvals.d.ts +81 -0
- package/dist/session/approvals.js +217 -0
- package/dist/session/approvals.js.map +1 -0
- package/dist/session/code-call-log.d.ts +42 -0
- package/dist/session/code-call-log.js +63 -0
- package/dist/session/code-call-log.js.map +1 -0
- package/dist/session/code-call-result.d.ts +19 -0
- package/dist/session/code-call-result.js +95 -0
- package/dist/session/code-call-result.js.map +1 -0
- package/dist/session/code-call.d.ts +49 -0
- package/dist/session/code-call.js +345 -0
- package/dist/session/code-call.js.map +1 -0
- package/dist/session/effect-scope.d.ts +11 -0
- package/dist/session/effect-scope.js +10 -0
- package/dist/session/effect-scope.js.map +1 -0
- package/dist/session/errors.d.ts +19 -0
- package/dist/session/errors.js +27 -0
- package/dist/session/errors.js.map +1 -0
- package/dist/session/file-index.d.ts +8 -0
- package/dist/session/file-index.js +70 -0
- package/dist/session/file-index.js.map +1 -0
- package/dist/session/file-key-store.d.ts +16 -0
- package/dist/session/file-key-store.js +169 -0
- package/dist/session/file-key-store.js.map +1 -0
- package/dist/session/file-lock.d.ts +52 -0
- package/dist/session/file-lock.js +324 -0
- package/dist/session/file-lock.js.map +1 -0
- package/dist/session/index.d.ts +22 -0
- package/dist/session/index.js +20 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/jsonl-store.d.ts +37 -0
- package/dist/session/jsonl-store.js +386 -0
- package/dist/session/jsonl-store.js.map +1 -0
- package/dist/session/jsonl.d.ts +9 -0
- package/dist/session/jsonl.js +10 -0
- package/dist/session/jsonl.js.map +1 -0
- package/dist/session/lock.d.ts +19 -0
- package/dist/session/lock.js +2 -0
- package/dist/session/lock.js.map +1 -0
- package/dist/session/memory-store.d.ts +12 -0
- package/dist/session/memory-store.js +60 -0
- package/dist/session/memory-store.js.map +1 -0
- package/dist/session/migrate.d.ts +41 -0
- package/dist/session/migrate.js +86 -0
- package/dist/session/migrate.js.map +1 -0
- package/dist/session/pointer.d.ts +15 -0
- package/dist/session/pointer.js +22 -0
- package/dist/session/pointer.js.map +1 -0
- package/dist/session/rebuild.d.ts +53 -0
- package/dist/session/rebuild.js +230 -0
- package/dist/session/rebuild.js.map +1 -0
- package/dist/session/resume.d.ts +26 -0
- package/dist/session/resume.js +128 -0
- package/dist/session/resume.js.map +1 -0
- package/dist/session/retention.d.ts +97 -0
- package/dist/session/retention.js +702 -0
- package/dist/session/retention.js.map +1 -0
- package/dist/session/runner.d.ts +156 -0
- package/dist/session/runner.js +656 -0
- package/dist/session/runner.js.map +1 -0
- package/dist/session/scheduler.d.ts +47 -0
- package/dist/session/scheduler.js +85 -0
- package/dist/session/scheduler.js.map +1 -0
- package/dist/session/secret-key-store.d.ts +47 -0
- package/dist/session/secret-key-store.js +79 -0
- package/dist/session/secret-key-store.js.map +1 -0
- package/dist/session/session.d.ts +106 -0
- package/dist/session/session.js +353 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/sticky.d.ts +48 -0
- package/dist/session/sticky.js +232 -0
- package/dist/session/sticky.js.map +1 -0
- package/dist/session/store.d.ts +108 -0
- package/dist/session/store.js +163 -0
- package/dist/session/store.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/testing/fake-sandbox.d.ts +52 -0
- package/dist/testing/fake-sandbox.js +370 -0
- package/dist/testing/fake-sandbox.js.map +1 -0
- package/dist/testing/index.d.ts +10 -0
- package/dist/testing/index.js +11 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/key-store-conformance.d.ts +22 -0
- package/dist/testing/key-store-conformance.js +97 -0
- package/dist/testing/key-store-conformance.js.map +1 -0
- package/dist/testing/run-cases.d.ts +21 -0
- package/dist/testing/run-cases.js +20 -0
- package/dist/testing/run-cases.js.map +1 -0
- package/dist/testing/sandbox-conformance.d.ts +64 -0
- package/dist/testing/sandbox-conformance.js +468 -0
- package/dist/testing/sandbox-conformance.js.map +1 -0
- package/dist/testing/scheduler-conformance.d.ts +32 -0
- package/dist/testing/scheduler-conformance.js +72 -0
- package/dist/testing/scheduler-conformance.js.map +1 -0
- package/dist/testing/store-conformance.d.ts +21 -0
- package/dist/testing/store-conformance.js +320 -0
- package/dist/testing/store-conformance.js.map +1 -0
- package/dist/tools/builtins/bash.d.ts +9 -0
- package/dist/tools/builtins/bash.js +75 -0
- package/dist/tools/builtins/bash.js.map +1 -0
- package/dist/tools/builtins/builtins.d.ts +38 -0
- package/dist/tools/builtins/builtins.js +48 -0
- package/dist/tools/builtins/builtins.js.map +1 -0
- package/dist/tools/builtins/descriptions.d.ts +69 -0
- package/dist/tools/builtins/descriptions.js +94 -0
- package/dist/tools/builtins/descriptions.js.map +1 -0
- package/dist/tools/builtins/fetch.d.ts +12 -0
- package/dist/tools/builtins/fetch.js +157 -0
- package/dist/tools/builtins/fetch.js.map +1 -0
- package/dist/tools/builtins/files.d.ts +27 -0
- package/dist/tools/builtins/files.js +274 -0
- package/dist/tools/builtins/files.js.map +1 -0
- package/dist/tools/builtins/paths.d.ts +30 -0
- package/dist/tools/builtins/paths.js +62 -0
- package/dist/tools/builtins/paths.js.map +1 -0
- package/dist/tools/builtins/results.d.ts +15 -0
- package/dist/tools/builtins/results.js +31 -0
- package/dist/tools/builtins/results.js.map +1 -0
- package/dist/tools/builtins/search.d.ts +18 -0
- package/dist/tools/builtins/search.js +217 -0
- package/dist/tools/builtins/search.js.map +1 -0
- package/dist/tools/errors.d.ts +13 -0
- package/dist/tools/errors.js +17 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/index.d.ts +12 -0
- package/dist/tools/index.js +11 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/registry.d.ts +3 -0
- package/dist/tools/registry.js +234 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/tools/tool-search.d.ts +30 -0
- package/dist/tools/tool-search.js +118 -0
- package/dist/tools/tool-search.js.map +1 -0
- package/dist/tools/types.d.ts +106 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/llms.txt +469 -0
- package/package.json +118 -3
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The stdio channel: one MCP server as a child process, one JSON message per line on its standard input and output.
|
|
3
|
+
* The harness spawns the child itself, with `spawnEnv()` plus the server's declared variables, because the MCP client
|
|
4
|
+
* library's own stdio transport adds the parent's `HOME`, `LOGNAME`, `PATH`, `SHELL`, `TERM` and `USER` to whatever
|
|
5
|
+
* environment it is given. It is Node-only, and loads Node's modules by `process.getBuiltinModule()` when a server
|
|
6
|
+
* starts, not by an import, so the `mcp` entry still loads on a runtime without them.
|
|
7
|
+
*
|
|
8
|
+
* Everything the child writes is bounded: a line longer than `maxLineBytes` closes the connection, a line that is not
|
|
9
|
+
* a JSON object is dropped, and only the newest `maxStderrBytes` of standard error are kept. On POSIX the child runs in
|
|
10
|
+
* its own process group, and closing kills the group: the server and whatever it started that stayed in the group. A
|
|
11
|
+
* descendant that leaves the group, by `setsid` or a detached spawn, survives the close. On Windows there are no process
|
|
12
|
+
* groups here, so closing ends the server alone and every descendant survives.
|
|
13
|
+
*/
|
|
14
|
+
import { HarnessError } from "../errors.js";
|
|
15
|
+
import { spawnEnv } from "../sandbox/spawn-env.js";
|
|
16
|
+
const DEFAULT_MAX_LINE_BYTES = 8 * 1024 * 1024;
|
|
17
|
+
const DEFAULT_MAX_STDERR_BYTES = 64 * 1024;
|
|
18
|
+
const DEFAULT_CLOSE_GRACE_MS = 2000;
|
|
19
|
+
const NEWLINE = 0x0a;
|
|
20
|
+
// The process groups still running. The harness kills them if its own process exits without closing them; the exit
|
|
21
|
+
// handler must be synchronous, and `process.kill()` is. A signal whose default action ends the process emits no `exit`
|
|
22
|
+
// event, so a host that wants the groups killed on a signal opts in with `killMcpServersOnSignal()`.
|
|
23
|
+
const live = new Set();
|
|
24
|
+
let exitHooked = false;
|
|
25
|
+
const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
26
|
+
function killGroup(pid, signal) {
|
|
27
|
+
try {
|
|
28
|
+
if (process.platform === "win32")
|
|
29
|
+
process.kill(pid, signal);
|
|
30
|
+
else
|
|
31
|
+
process.kill(-pid, signal);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// The group is already gone.
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function killAll() {
|
|
38
|
+
for (const group of live)
|
|
39
|
+
killGroup(group, "SIGKILL");
|
|
40
|
+
live.clear();
|
|
41
|
+
}
|
|
42
|
+
function track(pid) {
|
|
43
|
+
if (!exitHooked) {
|
|
44
|
+
exitHooked = true;
|
|
45
|
+
process.once("exit", killAll);
|
|
46
|
+
}
|
|
47
|
+
live.add(pid);
|
|
48
|
+
}
|
|
49
|
+
/** Forgets a group that has ended, and removes the exit handler once none is left. */
|
|
50
|
+
function untrack(pid) {
|
|
51
|
+
live.delete(pid);
|
|
52
|
+
if (live.size === 0 && exitHooked) {
|
|
53
|
+
exitHooked = false;
|
|
54
|
+
process.removeListener("exit", killAll);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
let signalsHooked = false;
|
|
58
|
+
function unhookSignals() {
|
|
59
|
+
signalsHooked = false;
|
|
60
|
+
for (const signal of SIGNALS)
|
|
61
|
+
process.removeListener(signal, onSignal);
|
|
62
|
+
}
|
|
63
|
+
function onSignal(signal) {
|
|
64
|
+
killAll();
|
|
65
|
+
unhookSignals();
|
|
66
|
+
// Raised again with this listener gone, the signal does what it would have done without it: Node's default exit when
|
|
67
|
+
// nothing else listens, and a library such as `signal-exit`, which re-raises only when it is alone, now is.
|
|
68
|
+
process.kill(process.pid, signal);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Opts this process in to ending every MCP server on `SIGINT`, `SIGTERM` or `SIGHUP`, for a host whose process those
|
|
72
|
+
* signals end, such as a one-shot command. The harness adds no signal listener unless asked, because a listener changes
|
|
73
|
+
* what a signal does to the host.
|
|
74
|
+
*
|
|
75
|
+
* On the first of those signals, the handler kills every server's process group, removes its listeners and raises the
|
|
76
|
+
* signal again, so the process then behaves as it would have without them: it ends when nothing else listens, and a
|
|
77
|
+
* listener that re-raises only when it is alone, as `signal-exit` does, sees itself alone. A host that handles `SIGINT`
|
|
78
|
+
* to cancel a turn should not opt in, since the first `SIGINT` ends its servers; such a host calls `manager.close()`.
|
|
79
|
+
* Returns a function that removes the listeners again.
|
|
80
|
+
*/
|
|
81
|
+
export function killMcpServersOnSignal() {
|
|
82
|
+
if (!signalsHooked) {
|
|
83
|
+
signalsHooked = true;
|
|
84
|
+
for (const signal of SIGNALS)
|
|
85
|
+
process.on(signal, onSignal);
|
|
86
|
+
}
|
|
87
|
+
return unhookSignals;
|
|
88
|
+
}
|
|
89
|
+
function wholeNumber(name, value, fallback) {
|
|
90
|
+
if (value === undefined)
|
|
91
|
+
return fallback;
|
|
92
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
93
|
+
throw new HarnessError("invalid_mcp_config", `${name} must be a whole number, 1 or more`);
|
|
94
|
+
}
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
function concat(chunks, size) {
|
|
98
|
+
const all = new Uint8Array(size);
|
|
99
|
+
let at = 0;
|
|
100
|
+
for (const chunk of chunks) {
|
|
101
|
+
all.set(chunk, at);
|
|
102
|
+
at += chunk.length;
|
|
103
|
+
}
|
|
104
|
+
return all;
|
|
105
|
+
}
|
|
106
|
+
/** Checks that a stdio server's command, args and cwd are strings without a NUL, which no program name can hold. */
|
|
107
|
+
function checkText(transport, args) {
|
|
108
|
+
if (transport.cwd !== undefined && typeof transport.cwd !== "string") {
|
|
109
|
+
throw new HarnessError("invalid_mcp_config", "a stdio server's cwd must be a string");
|
|
110
|
+
}
|
|
111
|
+
for (const [field, value] of [
|
|
112
|
+
["command", transport.command],
|
|
113
|
+
["cwd", transport.cwd ?? ""],
|
|
114
|
+
...args.map((arg) => ["args", arg]),
|
|
115
|
+
]) {
|
|
116
|
+
if (value.includes("\0"))
|
|
117
|
+
throw new HarnessError("invalid_mcp_config", `a stdio server's ${field} holds a NUL character`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** Checks a stdio transport's settings, so a typo fails when the manager is made and not when the server starts. */
|
|
121
|
+
export function checkStdioTransport(transport) {
|
|
122
|
+
if (typeof transport.command !== "string" || transport.command === "") {
|
|
123
|
+
throw new HarnessError("invalid_mcp_config", "a stdio server needs a command");
|
|
124
|
+
}
|
|
125
|
+
const args = transport.args ?? [];
|
|
126
|
+
if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string")) {
|
|
127
|
+
throw new HarnessError("invalid_mcp_config", "a stdio server's args must be a list of strings");
|
|
128
|
+
}
|
|
129
|
+
checkText(transport, args);
|
|
130
|
+
if (transport.env !== undefined && !Array.isArray(transport.env)) {
|
|
131
|
+
throw new HarnessError("invalid_mcp_config", "a stdio server's env must be a list of variable names");
|
|
132
|
+
}
|
|
133
|
+
// spawnEnv() checks the names and values now; a HOME of the caller's own makes it create no folder. Without Node it
|
|
134
|
+
// can't run, and start() says so.
|
|
135
|
+
if (typeof process !== "undefined" && typeof process.getBuiltinModule === "function") {
|
|
136
|
+
try {
|
|
137
|
+
spawnEnv(transport.env ?? [], { ...transport.setEnv, HOME: "/" });
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
141
|
+
throw new HarnessError("invalid_mcp_config", `a stdio server's environment can't be used: ${why}`, {
|
|
142
|
+
cause: error,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
wholeNumber("maxLineBytes", transport.maxLineBytes, DEFAULT_MAX_LINE_BYTES);
|
|
147
|
+
wholeNumber("maxStderrBytes", transport.maxStderrBytes, DEFAULT_MAX_STDERR_BYTES);
|
|
148
|
+
wholeNumber("closeGraceMs", transport.closeGraceMs, DEFAULT_CLOSE_GRACE_MS);
|
|
149
|
+
}
|
|
150
|
+
/** A stdio server as a channel. The `pid` and `stderr` fields also tell the MCP client library it is a stdio channel. */
|
|
151
|
+
export class StdioChannel {
|
|
152
|
+
onmessage;
|
|
153
|
+
onclose;
|
|
154
|
+
onerror;
|
|
155
|
+
#transport;
|
|
156
|
+
#maxLine;
|
|
157
|
+
#maxStderr;
|
|
158
|
+
#grace;
|
|
159
|
+
#log;
|
|
160
|
+
#child;
|
|
161
|
+
#home;
|
|
162
|
+
#pending = [];
|
|
163
|
+
#pendingBytes = 0;
|
|
164
|
+
#stderr = new Uint8Array();
|
|
165
|
+
#exited;
|
|
166
|
+
#closing;
|
|
167
|
+
#closed = false;
|
|
168
|
+
#endedByServer = false;
|
|
169
|
+
#probed = false;
|
|
170
|
+
#outputEnded;
|
|
171
|
+
#decoder = new TextDecoder("utf-8", { fatal: true });
|
|
172
|
+
constructor(transport, log) {
|
|
173
|
+
checkStdioTransport(transport);
|
|
174
|
+
this.#transport = transport;
|
|
175
|
+
this.#maxLine = transport.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;
|
|
176
|
+
this.#maxStderr = transport.maxStderrBytes ?? DEFAULT_MAX_STDERR_BYTES;
|
|
177
|
+
this.#grace = transport.closeGraceMs ?? DEFAULT_CLOSE_GRACE_MS;
|
|
178
|
+
this.#log = log;
|
|
179
|
+
}
|
|
180
|
+
/** The child's process id once it has started. */
|
|
181
|
+
get pid() {
|
|
182
|
+
return this.#child?.pid;
|
|
183
|
+
}
|
|
184
|
+
/** The newest bytes the child wrote to standard error, as text. */
|
|
185
|
+
get stderr() {
|
|
186
|
+
return new TextDecoder().decode(this.#stderr);
|
|
187
|
+
}
|
|
188
|
+
/** True when the server exited before anything asked the channel to close. */
|
|
189
|
+
get endedByServer() {
|
|
190
|
+
return this.#endedByServer;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* True when the server exited cleanly, with code 0, after the client sent it the `server/discover` probe: what a
|
|
194
|
+
* server on an SDK that closes on any request before `initialize` does.
|
|
195
|
+
*/
|
|
196
|
+
get exitedOnProbe() {
|
|
197
|
+
const child = this.#child;
|
|
198
|
+
return this.#endedByServer && this.#probed && child?.exitCode === 0 && child.signalCode === null;
|
|
199
|
+
}
|
|
200
|
+
/** True once the channel has closed, whoever closed it. */
|
|
201
|
+
get closed() {
|
|
202
|
+
return this.#closed;
|
|
203
|
+
}
|
|
204
|
+
async start() {
|
|
205
|
+
if (this.#child !== undefined)
|
|
206
|
+
throw new HarnessError("invalid_mcp_config", "a stdio channel starts only once");
|
|
207
|
+
if (typeof process === "undefined" || typeof process.getBuiltinModule !== "function") {
|
|
208
|
+
throw new HarnessError("invalid_mcp_config", "a stdio MCP server needs Node's child_process, which this runtime lacks");
|
|
209
|
+
}
|
|
210
|
+
const cp = process.getBuiltinModule("node:child_process");
|
|
211
|
+
const env = spawnEnv(this.#transport.env ?? [], this.#transport.setEnv ?? {});
|
|
212
|
+
// spawnEnv() made this folder unless the server's own HOME replaced it, and the channel removes what it made.
|
|
213
|
+
if (this.#transport.setEnv?.HOME === undefined)
|
|
214
|
+
this.#home = env.HOME;
|
|
215
|
+
const child = cp.spawn(this.#transport.command, [...(this.#transport.args ?? [])], {
|
|
216
|
+
env,
|
|
217
|
+
...(this.#transport.cwd === undefined ? {} : { cwd: this.#transport.cwd }),
|
|
218
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
219
|
+
detached: process.platform !== "win32",
|
|
220
|
+
shell: false,
|
|
221
|
+
windowsHide: true,
|
|
222
|
+
});
|
|
223
|
+
this.#child = child;
|
|
224
|
+
this.#exited = new Promise((resolve) => child.once("exit", () => resolve()));
|
|
225
|
+
// Node gives no promise that a child's output has been read by the time it exits, so the channel reads on until
|
|
226
|
+
// its standard output ends.
|
|
227
|
+
this.#outputEnded = new Promise((resolve) => {
|
|
228
|
+
child.stdout?.once("end", () => resolve());
|
|
229
|
+
child.stdout?.once("close", () => resolve());
|
|
230
|
+
});
|
|
231
|
+
try {
|
|
232
|
+
await new Promise((resolve, reject) => {
|
|
233
|
+
child.once("spawn", () => resolve());
|
|
234
|
+
child.once("error", reject);
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
this.#removeHome();
|
|
239
|
+
this.#closed = true;
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
if (child.pid !== undefined)
|
|
243
|
+
track(child.pid);
|
|
244
|
+
child.on("error", (error) => this.onerror?.(error));
|
|
245
|
+
child.stdin?.on("error", () => {
|
|
246
|
+
// A server that exits stops reading; the exit closes the channel, so a failed write needs no second report.
|
|
247
|
+
});
|
|
248
|
+
child.stdout?.on("data", (chunk) => this.#read(chunk));
|
|
249
|
+
child.stderr?.on("data", (chunk) => this.#keepStderr(chunk));
|
|
250
|
+
void this.#exited.then(async () => {
|
|
251
|
+
if (this.#closing !== undefined)
|
|
252
|
+
return;
|
|
253
|
+
this.#endedByServer = true;
|
|
254
|
+
this.#log(`the server exited with code ${String(child.exitCode)} and signal ${String(child.signalCode)}`);
|
|
255
|
+
// A child the server left behind can hold the pipe open, so the wait for the rest of the output is bounded.
|
|
256
|
+
await this.#within(this.#outputEnded, this.#grace);
|
|
257
|
+
void this.close();
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
async send(message) {
|
|
261
|
+
const stdin = this.#child?.stdin;
|
|
262
|
+
if (this.#closing !== undefined || stdin === undefined || stdin === null) {
|
|
263
|
+
throw new HarnessError("mcp_call_failed", "the server's channel is closed");
|
|
264
|
+
}
|
|
265
|
+
if (message.method === "server/discover")
|
|
266
|
+
this.#probed = true;
|
|
267
|
+
const line = `${JSON.stringify(message)}\n`;
|
|
268
|
+
await new Promise((resolve, reject) => {
|
|
269
|
+
stdin.write(line, (error) => (error ? reject(error) : resolve()));
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
close() {
|
|
273
|
+
this.#closing ??= this.#shutdown();
|
|
274
|
+
return this.#closing;
|
|
275
|
+
}
|
|
276
|
+
async #shutdown() {
|
|
277
|
+
const child = this.#child;
|
|
278
|
+
const pid = child?.pid;
|
|
279
|
+
if (child !== undefined && pid !== undefined) {
|
|
280
|
+
const running = () => child.exitCode === null && child.signalCode === null;
|
|
281
|
+
try {
|
|
282
|
+
child.stdin?.end();
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
// The pipe is already closed.
|
|
286
|
+
}
|
|
287
|
+
if (running() && !(await this.#exitWithin(this.#grace))) {
|
|
288
|
+
killGroup(pid, "SIGTERM");
|
|
289
|
+
if (!(await this.#exitWithin(this.#grace)))
|
|
290
|
+
killGroup(pid, "SIGKILL");
|
|
291
|
+
}
|
|
292
|
+
// The server may have left children in its group, and they hold nothing the harness needs.
|
|
293
|
+
killGroup(pid, "SIGKILL");
|
|
294
|
+
await this.#exitWithin(this.#grace);
|
|
295
|
+
untrack(pid);
|
|
296
|
+
child.stdout?.destroy();
|
|
297
|
+
child.stderr?.destroy();
|
|
298
|
+
child.stdin?.destroy();
|
|
299
|
+
}
|
|
300
|
+
this.#removeHome();
|
|
301
|
+
this.#pending = [];
|
|
302
|
+
this.#pendingBytes = 0;
|
|
303
|
+
this.#closed = true;
|
|
304
|
+
this.onclose?.();
|
|
305
|
+
}
|
|
306
|
+
#exitWithin(ms) {
|
|
307
|
+
return this.#within(this.#exited, ms);
|
|
308
|
+
}
|
|
309
|
+
async #within(event, ms) {
|
|
310
|
+
if (event === undefined)
|
|
311
|
+
return true;
|
|
312
|
+
let timer;
|
|
313
|
+
const expired = new Promise((resolve) => {
|
|
314
|
+
timer = setTimeout(() => resolve(false), ms);
|
|
315
|
+
});
|
|
316
|
+
const result = await Promise.race([event.then(() => true), expired]);
|
|
317
|
+
clearTimeout(timer);
|
|
318
|
+
return result;
|
|
319
|
+
}
|
|
320
|
+
#removeHome() {
|
|
321
|
+
const home = this.#home;
|
|
322
|
+
this.#home = undefined;
|
|
323
|
+
if (home === undefined)
|
|
324
|
+
return;
|
|
325
|
+
try {
|
|
326
|
+
process.getBuiltinModule("node:fs").rmSync(home, { recursive: true, force: true });
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
// A temp folder left behind is harmless, and the close must still finish.
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
#keepStderr(chunk) {
|
|
333
|
+
const joined = concat([this.#stderr, chunk], this.#stderr.length + chunk.length);
|
|
334
|
+
this.#stderr = joined.length <= this.#maxStderr ? joined : joined.slice(joined.length - this.#maxStderr);
|
|
335
|
+
}
|
|
336
|
+
#read(chunk) {
|
|
337
|
+
if (this.#closing !== undefined)
|
|
338
|
+
return;
|
|
339
|
+
let start = 0;
|
|
340
|
+
for (;;) {
|
|
341
|
+
const end = chunk.indexOf(NEWLINE, start);
|
|
342
|
+
const piece = chunk.subarray(start, end === -1 ? chunk.length : end);
|
|
343
|
+
if (this.#pendingBytes + piece.length > this.#maxLine) {
|
|
344
|
+
this.#log(`the server wrote a line over ${this.#maxLine} bytes, so the connection was closed`);
|
|
345
|
+
this.onerror?.(new Error(`the server wrote a line over ${this.#maxLine} bytes`));
|
|
346
|
+
void this.close();
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (end === -1) {
|
|
350
|
+
if (piece.length > 0) {
|
|
351
|
+
this.#pending.push(piece.slice());
|
|
352
|
+
this.#pendingBytes += piece.length;
|
|
353
|
+
}
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
const line = this.#pending.length === 0 ? piece : concat([...this.#pending, piece], this.#pendingBytes + piece.length);
|
|
357
|
+
this.#pending = [];
|
|
358
|
+
this.#pendingBytes = 0;
|
|
359
|
+
this.#deliver(line);
|
|
360
|
+
start = end + 1;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
#deliver(bytes) {
|
|
364
|
+
let message;
|
|
365
|
+
try {
|
|
366
|
+
const text = this.#decoder.decode(bytes).replace(/\r$/, "");
|
|
367
|
+
if (text.trim() === "")
|
|
368
|
+
return;
|
|
369
|
+
message = JSON.parse(text);
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
message = undefined;
|
|
373
|
+
}
|
|
374
|
+
if (typeof message !== "object" || message === null || Array.isArray(message)) {
|
|
375
|
+
this.#log("the server wrote a line that is not a JSON object, and it was dropped");
|
|
376
|
+
this.onerror?.(new Error("the server wrote a line that is not a JSON object"));
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
this.onmessage?.(message);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
//# sourceMappingURL=stdio.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../src/mcp/stdio.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAGnD,MAAM,sBAAsB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAC/C,MAAM,wBAAwB,GAAG,EAAE,GAAG,IAAI,CAAC;AAC3C,MAAM,sBAAsB,GAAG,IAAI,CAAC;AACpC,MAA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,QAAQ,IAAI,OAAO,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;YAC9E,IAAI,CAAC,IAAI,CAAC,uEAAuE,CAAC,CAAC;YACnF,IAAI,CAAC,OAAO,EAAE,CAAC,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC,CAAC;YAC/E,OAAO;QACT,CAAC;QACD,IAAI,CAAC,SAAS,EAAE,CAAC,OAAO,CAAC,CAAC;IAC5B,CAAC;CACF","sourcesContent":["/**\n * The stdio channel: one MCP server as a child process, one JSON message per line on its standard input and output.\n * The harness spawns the child itself, with `spawnEnv()` plus the server's declared variables, because the MCP client\n * library's own stdio transport adds the parent's `HOME`, `LOGNAME`, `PATH`, `SHELL`, `TERM` and `USER` to whatever\n * environment it is given. It is Node-only, and loads Node's modules by `process.getBuiltinModule()` when a server\n * starts, not by an import, so the `mcp` entry still loads on a runtime without them.\n *\n * Everything the child writes is bounded: a line longer than `maxLineBytes` closes the connection, a line that is not\n * a JSON object is dropped, and only the newest `maxStderrBytes` of standard error are kept. On POSIX the child runs in\n * its own process group, and closing kills the group: the server and whatever it started that stayed in the group. A\n * descendant that leaves the group, by `setsid` or a detached spawn, survives the close. On Windows there are no process\n * groups here, so closing ends the server alone and every descendant survives.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { spawnEnv } from \"../sandbox/spawn-env.js\";\nimport type { McpChannel, McpStdioTransport } from \"./types.js\";\n\nconst DEFAULT_MAX_LINE_BYTES = 8 * 1024 * 1024;\nconst DEFAULT_MAX_STDERR_BYTES = 64 * 1024;\nconst DEFAULT_CLOSE_GRACE_MS = 2000;\nconst NEWLINE = 0x0a;\n\ntype ChildProcess = import(\"node:child_process\").ChildProcess;\n\n// The process groups still running. The harness kills them if its own process exits without closing them; the exit\n// handler must be synchronous, and `process.kill()` is. A signal whose default action ends the process emits no `exit`\n// event, so a host that wants the groups killed on a signal opts in with `killMcpServersOnSignal()`.\nconst live = new Set<number>();\nlet exitHooked = false;\nconst SIGNALS: readonly NodeJS.Signals[] = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"];\n\nfunction killGroup(pid: number, signal: NodeJS.Signals): void {\n try {\n if (process.platform === \"win32\") process.kill(pid, signal);\n else process.kill(-pid, signal);\n } catch {\n // The group is already gone.\n }\n}\n\nfunction killAll(): void {\n for (const group of live) killGroup(group, \"SIGKILL\");\n live.clear();\n}\n\nfunction track(pid: number): void {\n if (!exitHooked) {\n exitHooked = true;\n process.once(\"exit\", killAll);\n }\n live.add(pid);\n}\n\n/** Forgets a group that has ended, and removes the exit handler once none is left. */\nfunction untrack(pid: number): void {\n live.delete(pid);\n if (live.size === 0 && exitHooked) {\n exitHooked = false;\n process.removeListener(\"exit\", killAll);\n }\n}\n\nlet signalsHooked = false;\n\nfunction unhookSignals(): void {\n signalsHooked = false;\n for (const signal of SIGNALS) process.removeListener(signal, onSignal);\n}\n\nfunction onSignal(signal: NodeJS.Signals): void {\n killAll();\n unhookSignals();\n // Raised again with this listener gone, the signal does what it would have done without it: Node's default exit when\n // nothing else listens, and a library such as `signal-exit`, which re-raises only when it is alone, now is.\n process.kill(process.pid, signal);\n}\n\n/**\n * Opts this process in to ending every MCP server on `SIGINT`, `SIGTERM` or `SIGHUP`, for a host whose process those\n * signals end, such as a one-shot command. The harness adds no signal listener unless asked, because a listener changes\n * what a signal does to the host.\n *\n * On the first of those signals, the handler kills every server's process group, removes its listeners and raises the\n * signal again, so the process then behaves as it would have without them: it ends when nothing else listens, and a\n * listener that re-raises only when it is alone, as `signal-exit` does, sees itself alone. A host that handles `SIGINT`\n * to cancel a turn should not opt in, since the first `SIGINT` ends its servers; such a host calls `manager.close()`.\n * Returns a function that removes the listeners again.\n */\nexport function killMcpServersOnSignal(): () => void {\n if (!signalsHooked) {\n signalsHooked = true;\n for (const signal of SIGNALS) process.on(signal, onSignal);\n }\n return unhookSignals;\n}\n\nfunction wholeNumber(name: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || value < 1) {\n throw new HarnessError(\"invalid_mcp_config\", `${name} must be a whole number, 1 or more`);\n }\n return value;\n}\n\nfunction concat(chunks: readonly Uint8Array[], size: number): Uint8Array {\n const all = new Uint8Array(size);\n let at = 0;\n for (const chunk of chunks) {\n all.set(chunk, at);\n at += chunk.length;\n }\n return all;\n}\n\n/** Checks that a stdio server's command, args and cwd are strings without a NUL, which no program name can hold. */\nfunction checkText(transport: McpStdioTransport, args: readonly string[]): void {\n if (transport.cwd !== undefined && typeof transport.cwd !== \"string\") {\n throw new HarnessError(\"invalid_mcp_config\", \"a stdio server's cwd must be a string\");\n }\n for (const [field, value] of [\n [\"command\", transport.command],\n [\"cwd\", transport.cwd ?? \"\"],\n ...args.map((arg) => [\"args\", arg] as const),\n ] as const) {\n if (value.includes(\"\\0\"))\n throw new HarnessError(\"invalid_mcp_config\", `a stdio server's ${field} holds a NUL character`);\n }\n}\n\n/** Checks a stdio transport's settings, so a typo fails when the manager is made and not when the server starts. */\nexport function checkStdioTransport(transport: McpStdioTransport): void {\n if (typeof transport.command !== \"string\" || transport.command === \"\") {\n throw new HarnessError(\"invalid_mcp_config\", \"a stdio server needs a command\");\n }\n const args = transport.args ?? [];\n if (!Array.isArray(args) || args.some((arg) => typeof arg !== \"string\")) {\n throw new HarnessError(\"invalid_mcp_config\", \"a stdio server's args must be a list of strings\");\n }\n checkText(transport, args);\n if (transport.env !== undefined && !Array.isArray(transport.env)) {\n throw new HarnessError(\"invalid_mcp_config\", \"a stdio server's env must be a list of variable names\");\n }\n // spawnEnv() checks the names and values now; a HOME of the caller's own makes it create no folder. Without Node it\n // can't run, and start() says so.\n if (typeof process !== \"undefined\" && typeof process.getBuiltinModule === \"function\") {\n try {\n spawnEnv(transport.env ?? [], { ...transport.setEnv, HOME: \"/\" });\n } catch (error) {\n const why = error instanceof Error ? error.message : String(error);\n throw new HarnessError(\"invalid_mcp_config\", `a stdio server's environment can't be used: ${why}`, {\n cause: error,\n });\n }\n }\n wholeNumber(\"maxLineBytes\", transport.maxLineBytes, DEFAULT_MAX_LINE_BYTES);\n wholeNumber(\"maxStderrBytes\", transport.maxStderrBytes, DEFAULT_MAX_STDERR_BYTES);\n wholeNumber(\"closeGraceMs\", transport.closeGraceMs, DEFAULT_CLOSE_GRACE_MS);\n}\n\n/** A stdio server as a channel. The `pid` and `stderr` fields also tell the MCP client library it is a stdio channel. */\nexport class StdioChannel implements McpChannel {\n onmessage?: ((message: object) => void) | undefined;\n onclose?: (() => void) | undefined;\n onerror?: ((error: Error) => void) | undefined;\n\n readonly #transport: McpStdioTransport;\n readonly #maxLine: number;\n readonly #maxStderr: number;\n readonly #grace: number;\n readonly #log: (line: string) => void;\n #child: ChildProcess | undefined;\n #home: string | undefined;\n #pending: Uint8Array[] = [];\n #pendingBytes = 0;\n #stderr: Uint8Array = new Uint8Array();\n #exited: Promise<void> | undefined;\n #closing: Promise<void> | undefined;\n #closed = false;\n #endedByServer = false;\n #probed = false;\n #outputEnded: Promise<void> | undefined;\n readonly #decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\n constructor(transport: McpStdioTransport, log: (line: string) => void) {\n checkStdioTransport(transport);\n this.#transport = transport;\n this.#maxLine = transport.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;\n this.#maxStderr = transport.maxStderrBytes ?? DEFAULT_MAX_STDERR_BYTES;\n this.#grace = transport.closeGraceMs ?? DEFAULT_CLOSE_GRACE_MS;\n this.#log = log;\n }\n\n /** The child's process id once it has started. */\n get pid(): number | undefined {\n return this.#child?.pid;\n }\n\n /** The newest bytes the child wrote to standard error, as text. */\n get stderr(): string {\n return new TextDecoder().decode(this.#stderr);\n }\n\n /** True when the server exited before anything asked the channel to close. */\n get endedByServer(): boolean {\n return this.#endedByServer;\n }\n\n /**\n * True when the server exited cleanly, with code 0, after the client sent it the `server/discover` probe: what a\n * server on an SDK that closes on any request before `initialize` does.\n */\n get exitedOnProbe(): boolean {\n const child = this.#child;\n return this.#endedByServer && this.#probed && child?.exitCode === 0 && child.signalCode === null;\n }\n\n /** True once the channel has closed, whoever closed it. */\n get closed(): boolean {\n return this.#closed;\n }\n\n async start(): Promise<void> {\n if (this.#child !== undefined) throw new HarnessError(\"invalid_mcp_config\", \"a stdio channel starts only once\");\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new HarnessError(\n \"invalid_mcp_config\",\n \"a stdio MCP server needs Node's child_process, which this runtime lacks\",\n );\n }\n const cp = process.getBuiltinModule(\"node:child_process\");\n const env = spawnEnv(this.#transport.env ?? [], this.#transport.setEnv ?? {});\n // spawnEnv() made this folder unless the server's own HOME replaced it, and the channel removes what it made.\n if (this.#transport.setEnv?.HOME === undefined) this.#home = env.HOME;\n const child = cp.spawn(this.#transport.command, [...(this.#transport.args ?? [])], {\n env,\n ...(this.#transport.cwd === undefined ? {} : { cwd: this.#transport.cwd }),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n shell: false,\n windowsHide: true,\n });\n this.#child = child;\n this.#exited = new Promise((resolve) => child.once(\"exit\", () => resolve()));\n // Node gives no promise that a child's output has been read by the time it exits, so the channel reads on until\n // its standard output ends.\n this.#outputEnded = new Promise((resolve) => {\n child.stdout?.once(\"end\", () => resolve());\n child.stdout?.once(\"close\", () => resolve());\n });\n try {\n await new Promise<void>((resolve, reject) => {\n child.once(\"spawn\", () => resolve());\n child.once(\"error\", reject);\n });\n } catch (error) {\n this.#removeHome();\n this.#closed = true;\n throw error;\n }\n if (child.pid !== undefined) track(child.pid);\n child.on(\"error\", (error) => this.onerror?.(error));\n child.stdin?.on(\"error\", () => {\n // A server that exits stops reading; the exit closes the channel, so a failed write needs no second report.\n });\n child.stdout?.on(\"data\", (chunk: Uint8Array) => this.#read(chunk));\n child.stderr?.on(\"data\", (chunk: Uint8Array) => this.#keepStderr(chunk));\n void this.#exited.then(async () => {\n if (this.#closing !== undefined) return;\n this.#endedByServer = true;\n this.#log(`the server exited with code ${String(child.exitCode)} and signal ${String(child.signalCode)}`);\n // A child the server left behind can hold the pipe open, so the wait for the rest of the output is bounded.\n await this.#within(this.#outputEnded, this.#grace);\n void this.close();\n });\n }\n\n async send(message: object): Promise<void> {\n const stdin = this.#child?.stdin;\n if (this.#closing !== undefined || stdin === undefined || stdin === null) {\n throw new HarnessError(\"mcp_call_failed\", \"the server's channel is closed\");\n }\n if ((message as { method?: unknown }).method === \"server/discover\") this.#probed = true;\n const line = `${JSON.stringify(message)}\\n`;\n await new Promise<void>((resolve, reject) => {\n stdin.write(line, (error) => (error ? reject(error) : resolve()));\n });\n }\n\n close(): Promise<void> {\n this.#closing ??= this.#shutdown();\n return this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n const child = this.#child;\n const pid = child?.pid;\n if (child !== undefined && pid !== undefined) {\n const running = () => child.exitCode === null && child.signalCode === null;\n try {\n child.stdin?.end();\n } catch {\n // The pipe is already closed.\n }\n if (running() && !(await this.#exitWithin(this.#grace))) {\n killGroup(pid, \"SIGTERM\");\n if (!(await this.#exitWithin(this.#grace))) killGroup(pid, \"SIGKILL\");\n }\n // The server may have left children in its group, and they hold nothing the harness needs.\n killGroup(pid, \"SIGKILL\");\n await this.#exitWithin(this.#grace);\n untrack(pid);\n child.stdout?.destroy();\n child.stderr?.destroy();\n child.stdin?.destroy();\n }\n this.#removeHome();\n this.#pending = [];\n this.#pendingBytes = 0;\n this.#closed = true;\n this.onclose?.();\n }\n\n #exitWithin(ms: number): Promise<boolean> {\n return this.#within(this.#exited, ms);\n }\n\n async #within(event: Promise<void> | undefined, ms: number): Promise<boolean> {\n if (event === undefined) return true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), ms);\n });\n const result = await Promise.race([event.then(() => true), expired]);\n clearTimeout(timer);\n return result;\n }\n\n #removeHome(): void {\n const home = this.#home;\n this.#home = undefined;\n if (home === undefined) return;\n try {\n process.getBuiltinModule(\"node:fs\").rmSync(home, { recursive: true, force: true });\n } catch {\n // A temp folder left behind is harmless, and the close must still finish.\n }\n }\n\n #keepStderr(chunk: Uint8Array): void {\n const joined = concat([this.#stderr, chunk], this.#stderr.length + chunk.length);\n this.#stderr = joined.length <= this.#maxStderr ? joined : joined.slice(joined.length - this.#maxStderr);\n }\n\n #read(chunk: Uint8Array): void {\n if (this.#closing !== undefined) return;\n let start = 0;\n for (;;) {\n const end = chunk.indexOf(NEWLINE, start);\n const piece = chunk.subarray(start, end === -1 ? chunk.length : end);\n if (this.#pendingBytes + piece.length > this.#maxLine) {\n this.#log(`the server wrote a line over ${this.#maxLine} bytes, so the connection was closed`);\n this.onerror?.(new Error(`the server wrote a line over ${this.#maxLine} bytes`));\n void this.close();\n return;\n }\n if (end === -1) {\n if (piece.length > 0) {\n this.#pending.push(piece.slice());\n this.#pendingBytes += piece.length;\n }\n return;\n }\n const line =\n this.#pending.length === 0 ? piece : concat([...this.#pending, piece], this.#pendingBytes + piece.length);\n this.#pending = [];\n this.#pendingBytes = 0;\n this.#deliver(line);\n start = end + 1;\n }\n }\n\n #deliver(bytes: Uint8Array): void {\n let message: unknown;\n try {\n const text = this.#decoder.decode(bytes).replace(/\\r$/, \"\");\n if (text.trim() === \"\") return;\n message = JSON.parse(text);\n } catch {\n message = undefined;\n }\n if (typeof message !== \"object\" || message === null || Array.isArray(message)) {\n this.#log(\"the server wrote a line that is not a JSON object, and it was dropped\");\n this.onerror?.(new Error(\"the server wrote a line that is not a JSON object\"));\n return;\n }\n this.onmessage?.(message);\n }\n}\n"]}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The types of `@buildanagent/harness/mcp`. The registry and the rest of the harness see these and never the MCP client
|
|
3
|
+
* library, so the library can change without touching them (ADR 0021).
|
|
4
|
+
*/
|
|
5
|
+
import type { ModelContent } from "@buildanagent/gateway";
|
|
6
|
+
import type { ExtensionLoadedRecord } from "../extensions/types.js";
|
|
7
|
+
import type { ToolExposure, ToolRegistry } from "../tools/types.js";
|
|
8
|
+
/** The protocol era a server speaks: the 2026-07-28 revision, or `legacy` for the 2025 revisions and their `initialize`. */
|
|
9
|
+
export type McpEra = "2026-07-28" | "legacy";
|
|
10
|
+
/**
|
|
11
|
+
* A server the harness starts as a child process and speaks to over its standard input and output, one JSON message
|
|
12
|
+
* per line. The child gets `spawnEnv()`'s environment (`PATH`, a fresh temp `HOME`, `TMPDIR` and `LANG`) plus what
|
|
13
|
+
* `env` and `setEnv` declare, and nothing else from the parent.
|
|
14
|
+
*/
|
|
15
|
+
export interface McpStdioTransport {
|
|
16
|
+
readonly kind: "stdio";
|
|
17
|
+
/** The program to run, found on the child's `PATH` unless it is a path. It runs without a shell. */
|
|
18
|
+
readonly command: string;
|
|
19
|
+
readonly args?: readonly string[];
|
|
20
|
+
/** The folder the server starts in. Default the harness's own working folder. */
|
|
21
|
+
readonly cwd?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Parent variables the server may read, by name, such as `DOCKER_HOST`. `spawnEnv()`'s rules apply: a name that looks
|
|
24
|
+
* like a credential, such as `GITHUB_TOKEN`, is refused here and goes in `setEnv` with a value the host supplies.
|
|
25
|
+
*/
|
|
26
|
+
readonly env?: readonly string[];
|
|
27
|
+
/** Variables set to these values, such as a token the host read from its own secret store. */
|
|
28
|
+
readonly setEnv?: Readonly<Record<string, string>>;
|
|
29
|
+
/** The longest line the server may write, in bytes. A longer one closes the connection. Default 8 MiB. */
|
|
30
|
+
readonly maxLineBytes?: number;
|
|
31
|
+
/** How much of the server's standard error is kept, the newest bytes. It never reaches the model. Default 64 KiB. */
|
|
32
|
+
readonly maxStderrBytes?: number;
|
|
33
|
+
/**
|
|
34
|
+
* How long a closing server has to exit after its input ends, and again after a `SIGTERM`, before its process group
|
|
35
|
+
* is killed. Default 2,000 ms.
|
|
36
|
+
*/
|
|
37
|
+
readonly closeGraceMs?: number;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A message channel to a server in this process, such as an `InMemoryTransport` from `@modelcontextprotocol/server`.
|
|
41
|
+
* Its shape is the MCP SDK's transport, so that SDK's own transports fit it. Messages are JSON-RPC objects.
|
|
42
|
+
*/
|
|
43
|
+
export interface McpChannel {
|
|
44
|
+
/** Opens the channel. The client calls it once, after it has set the three handlers. */
|
|
45
|
+
start(): Promise<void>;
|
|
46
|
+
/** Sends one message to the server. */
|
|
47
|
+
send(message: object): Promise<void>;
|
|
48
|
+
/** Closes the channel, and calls `onclose`. */
|
|
49
|
+
close(): Promise<void>;
|
|
50
|
+
/** Set by the client: called with each message the server sends. */
|
|
51
|
+
onmessage?: ((message: object) => void) | undefined;
|
|
52
|
+
/** Set by the client: called once when the channel closes, whoever closed it. */
|
|
53
|
+
onclose?: (() => void) | undefined;
|
|
54
|
+
/** Set by the client: called with a problem that does not close the channel. */
|
|
55
|
+
onerror?: ((error: Error) => void) | undefined;
|
|
56
|
+
}
|
|
57
|
+
/** A server in this process, reached through a channel the host built. */
|
|
58
|
+
export interface McpInProcessTransport {
|
|
59
|
+
readonly kind: "in_process";
|
|
60
|
+
readonly channel: McpChannel;
|
|
61
|
+
}
|
|
62
|
+
/** One MCP server the harness connects to. */
|
|
63
|
+
export interface McpServerConfig {
|
|
64
|
+
/**
|
|
65
|
+
* The server's name in its tools' canonical names, `mcp__<name>__<tool>`: 1 to 32 characters from `A-Z`, `a-z`, `0-9`
|
|
66
|
+
* and `-`, starting with a letter or digit. Two servers of one harness can't share a name, in any letter case.
|
|
67
|
+
*/
|
|
68
|
+
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. */
|
|
71
|
+
readonly exposure?: ToolExposure;
|
|
72
|
+
/** How long the start and the handshake may take, the probe included. Default 30,000 ms. */
|
|
73
|
+
readonly connectTimeoutMs?: number;
|
|
74
|
+
/**
|
|
75
|
+
* How long the `server/discover` probe waits before it treats the server as legacy and sends `initialize`. Default
|
|
76
|
+
* 5,000 ms.
|
|
77
|
+
*/
|
|
78
|
+
readonly probeTimeoutMs?: number;
|
|
79
|
+
/** How long one request, such as a tool call, may wait for its answer. Default 60,000 ms. */
|
|
80
|
+
readonly requestTimeoutMs?: number;
|
|
81
|
+
/** The most tools the server may list. A longer list is refused, and none of its tools is registered. Default 256. */
|
|
82
|
+
readonly maxTools?: number;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A tool as a server lists it. Every field is what the server says, so none of it is trusted: the name and
|
|
86
|
+
* description reach the model only as data, and `annotations` change nothing the harness does.
|
|
87
|
+
*/
|
|
88
|
+
export interface McpTool {
|
|
89
|
+
/** The tool's name on its server. */
|
|
90
|
+
readonly name: string;
|
|
91
|
+
/** The server's description, cut to 4,096 characters. */
|
|
92
|
+
readonly description: string;
|
|
93
|
+
/**
|
|
94
|
+
* The tool's input schema as the server sent it. The registered tool's schema leaves out `pattern`,
|
|
95
|
+
* `patternProperties` and `format`, so the harness never runs a server's regular expression.
|
|
96
|
+
*/
|
|
97
|
+
readonly inputSchema: Readonly<Record<string, unknown>>;
|
|
98
|
+
/** The server's hints, such as `readOnlyHint`, kept for display only. */
|
|
99
|
+
readonly annotations?: Readonly<Record<string, unknown>>;
|
|
100
|
+
}
|
|
101
|
+
/** What one tool call returned. `content` is what the model reads; `isError` is the server's own failure flag. */
|
|
102
|
+
export interface McpCallResult {
|
|
103
|
+
readonly content: readonly ModelContent[];
|
|
104
|
+
readonly isError: boolean;
|
|
105
|
+
}
|
|
106
|
+
/** One connected server. */
|
|
107
|
+
export interface McpConnection {
|
|
108
|
+
/** The server's name from its config. */
|
|
109
|
+
readonly server: string;
|
|
110
|
+
/** The era the server negotiated: `2026-07-28` when it answered the `server/discover` probe, `legacy` otherwise. */
|
|
111
|
+
readonly era: McpEra;
|
|
112
|
+
/** The protocol revision negotiated, such as `2026-07-28` or `2025-11-25`. */
|
|
113
|
+
readonly protocolVersion: string;
|
|
114
|
+
/** True once the connection has closed, by `close()` or because the server ended it. */
|
|
115
|
+
readonly closed: boolean;
|
|
116
|
+
/**
|
|
117
|
+
* The server's tools, checked: at most `maxTools`, each with a usable name and schema, and no two whose names match
|
|
118
|
+
* once normalised. Throws an `McpError`, code `mcp_tool_list_refused`, for a list that fails a check.
|
|
119
|
+
*/
|
|
120
|
+
listTools(): Promise<readonly McpTool[]>;
|
|
121
|
+
/**
|
|
122
|
+
* Calls one tool by its name on the server. Throws an `McpError`, code `mcp_call_failed`, when the call ends with no
|
|
123
|
+
* result: the server closed or answered with an error, the request timed out or `signal` aborted it, or the server
|
|
124
|
+
* asked for input, which this harness does not supply.
|
|
125
|
+
*/
|
|
126
|
+
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. */
|
|
128
|
+
stderr(): string;
|
|
129
|
+
/** Ends the connection and, for a stdio server, its process group. Calling it again does nothing. */
|
|
130
|
+
close(): Promise<void>;
|
|
131
|
+
}
|
|
132
|
+
/** What `createMcpManager()` takes. */
|
|
133
|
+
export interface McpManagerOptions {
|
|
134
|
+
readonly servers: readonly McpServerConfig[];
|
|
135
|
+
/** Where the servers' tools are registered, under the source `mcp:<name>`. */
|
|
136
|
+
readonly registry: ToolRegistry;
|
|
137
|
+
/** `false` switches MCP off: `connect()` starts no server and registers nothing. Default true. */
|
|
138
|
+
readonly mcp?: boolean;
|
|
139
|
+
/** Told of events a host may want to see, such as a server's notice that its tool list changed. */
|
|
140
|
+
readonly log?: (line: string) => void;
|
|
141
|
+
}
|
|
142
|
+
/** How one server's connection went. */
|
|
143
|
+
export type McpServerStatus = {
|
|
144
|
+
readonly server: string;
|
|
145
|
+
readonly status: "connected";
|
|
146
|
+
readonly era: McpEra;
|
|
147
|
+
/** The canonical names of the tools registered for it, in its order. */
|
|
148
|
+
readonly tools: readonly string[];
|
|
149
|
+
} | {
|
|
150
|
+
readonly server: string;
|
|
151
|
+
readonly status: "failed";
|
|
152
|
+
readonly error: Error;
|
|
153
|
+
};
|
|
154
|
+
/** The MCP client as one removable component: it connects the servers and registers their tools. */
|
|
155
|
+
export interface McpManager {
|
|
156
|
+
/**
|
|
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.
|
|
160
|
+
*/
|
|
161
|
+
connect(): Promise<readonly McpServerStatus[]>;
|
|
162
|
+
/**
|
|
163
|
+
* One `extension_loaded` record of tier `mcp` per connected server, in config order, for
|
|
164
|
+
* `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
|
|
165
|
+
* has no record: its status says why, and nothing of it ran in a turn.
|
|
166
|
+
*/
|
|
167
|
+
records(): readonly ExtensionLoadedRecord[];
|
|
168
|
+
/** The connection of a connected server, by name. */
|
|
169
|
+
connection(server: string): McpConnection | undefined;
|
|
170
|
+
/** Closes every connection and ends every server process. A tool of a closed server fails when called. */
|
|
171
|
+
close(): Promise<void>;
|
|
172
|
+
}
|
|
@@ -0,0 +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"]}
|