@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.28
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 +716 -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 +5 -0
- package/dist/context/file-spill.js +25 -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 +6 -0
- package/dist/context/spill.js +14 -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 +34 -0
- package/dist/credentials/allowlist.js +77 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +70 -0
- package/dist/credentials/egress-proxy.js +482 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/index.d.ts +9 -0
- package/dist/credentials/index.js +10 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +16 -0
- package/dist/credentials/scrub.js +93 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +56 -0
- package/dist/errors.js +63 -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 +35 -0
- package/dist/sandbox/base.js +60 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +35 -0
- package/dist/sandbox/docker/index.js +448 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +16 -0
- package/dist/sandbox/errors.js +22 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +63 -0
- package/dist/sandbox/host-files.js +248 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +8 -0
- package/dist/sandbox/index.js +8 -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/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 +35 -0
- package/dist/sandbox/srt/index.js +264 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +48 -0
- package/dist/sandbox/srt/settings.js +31 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +88 -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 +34 -0
- package/dist/testing/fake-sandbox.js +221 -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 +361 -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/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 +8 -0
- package/dist/tools/index.js +8 -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 +435 -0
- package/package.json +118 -3
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { McpError } from "./errors.js";
|
|
2
|
+
const MAX_NAME_CHARS = 128;
|
|
3
|
+
const MAX_DESCRIPTION_CHARS = 4096;
|
|
4
|
+
const MAX_SCHEMA_BYTES = 64 * 1024;
|
|
5
|
+
const MAX_ERROR_CHARS = 500;
|
|
6
|
+
const IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
|
|
7
|
+
// The control characters of ASCII and Latin-1, which a name shown in a log or a prompt should never carry.
|
|
8
|
+
const isControl = (code) => code <= 0x1f || (code >= 0x7f && code <= 0x9f);
|
|
9
|
+
const hasControl = (text) => [...text].some((char) => isControl(char.codePointAt(0) ?? 0));
|
|
10
|
+
const encoder = new TextEncoder();
|
|
11
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12
|
+
/**
|
|
13
|
+
* `text` cut to at most `max` UTF-16 units, with `…` after it when it was cut. It never splits a surrogate pair, since a
|
|
14
|
+
* lone half would make the canonical JSON that the record hashes refuse the text, and the server's whole list with it.
|
|
15
|
+
*/
|
|
16
|
+
export function cut(text, max) {
|
|
17
|
+
if (text.length <= max)
|
|
18
|
+
return text;
|
|
19
|
+
const last = text.charCodeAt(max - 1);
|
|
20
|
+
const end = last >= 0xd800 && last <= 0xdbff ? max - 1 : max;
|
|
21
|
+
return `${text.slice(0, end)}…`;
|
|
22
|
+
}
|
|
23
|
+
/** A server's text cut to `max` characters, with its control characters replaced, for an error message. */
|
|
24
|
+
export function shortText(text, max = MAX_ERROR_CHARS) {
|
|
25
|
+
const plain = [...text].map((char) => (isControl(char.codePointAt(0) ?? 0) ? " " : char)).join("");
|
|
26
|
+
return cut(plain, max);
|
|
27
|
+
}
|
|
28
|
+
function refuse(server, why) {
|
|
29
|
+
return new McpError("mcp_tool_list_refused", server, `its tool list was refused, so none of its tools was registered: ${why}`);
|
|
30
|
+
}
|
|
31
|
+
/** One listed tool, checked, or the reason it can't be used. */
|
|
32
|
+
function checkTool(server, tool, index) {
|
|
33
|
+
if (!isRecord(tool))
|
|
34
|
+
throw refuse(server, `tool ${index} is not an object`);
|
|
35
|
+
const { name, description, inputSchema, annotations } = tool;
|
|
36
|
+
if (typeof name !== "string" || name.length === 0 || name.length > MAX_NAME_CHARS || hasControl(name)) {
|
|
37
|
+
throw refuse(server, `tool ${index} has no name of 1 to ${MAX_NAME_CHARS} characters without control characters`);
|
|
38
|
+
}
|
|
39
|
+
if (!isRecord(inputSchema) || inputSchema.type !== "object") {
|
|
40
|
+
throw refuse(server, `the tool ${JSON.stringify(name)} has an input schema that is not an object schema`);
|
|
41
|
+
}
|
|
42
|
+
let schemaBytes;
|
|
43
|
+
try {
|
|
44
|
+
schemaBytes = encoder.encode(JSON.stringify(inputSchema)).length;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
throw refuse(server, `the tool ${JSON.stringify(name)} has an input schema that is not JSON`);
|
|
48
|
+
}
|
|
49
|
+
if (schemaBytes > MAX_SCHEMA_BYTES) {
|
|
50
|
+
throw refuse(server, `the tool ${JSON.stringify(name)} has an input schema over ${MAX_SCHEMA_BYTES} bytes`);
|
|
51
|
+
}
|
|
52
|
+
const text = typeof description === "string" ? description : "";
|
|
53
|
+
return {
|
|
54
|
+
name,
|
|
55
|
+
description: cut(text, MAX_DESCRIPTION_CHARS),
|
|
56
|
+
inputSchema,
|
|
57
|
+
...(isRecord(annotations) ? { annotations } : {}),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The server's tool list, checked as a whole: it is refused when it is longer than `maxTools`, when any tool fails its
|
|
62
|
+
* check, or when two names match once normalised (NFKC, then lower case), since they would read as one tool to a
|
|
63
|
+
* person approving a call.
|
|
64
|
+
*/
|
|
65
|
+
export function checkToolList(server, tools, maxTools) {
|
|
66
|
+
if (!Array.isArray(tools))
|
|
67
|
+
throw refuse(server, "it did not send a list of tools");
|
|
68
|
+
if (tools.length > maxTools)
|
|
69
|
+
throw refuse(server, `it listed ${tools.length} tools, over the limit of ${maxTools}`);
|
|
70
|
+
const seen = new Map();
|
|
71
|
+
return tools.map((tool, index) => {
|
|
72
|
+
const checked = checkTool(server, tool, index);
|
|
73
|
+
const key = checked.name.normalize("NFKC").toLowerCase();
|
|
74
|
+
const earlier = seen.get(key);
|
|
75
|
+
if (earlier !== undefined) {
|
|
76
|
+
throw refuse(server, `the names ${JSON.stringify(earlier)} and ${JSON.stringify(checked.name)} name one tool`);
|
|
77
|
+
}
|
|
78
|
+
seen.set(key, checked.name);
|
|
79
|
+
return checked;
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
// Keywords whose value is one subschema, a list of them, or a map of names to them. Everything else in a schema is
|
|
83
|
+
// data, such as `enum` or `default`, and is copied as it is.
|
|
84
|
+
const ONE_SCHEMA = new Set([
|
|
85
|
+
"additionalProperties",
|
|
86
|
+
"items",
|
|
87
|
+
"additionalItems",
|
|
88
|
+
"contains",
|
|
89
|
+
"propertyNames",
|
|
90
|
+
"unevaluatedProperties",
|
|
91
|
+
"unevaluatedItems",
|
|
92
|
+
"not",
|
|
93
|
+
"if",
|
|
94
|
+
"then",
|
|
95
|
+
"else",
|
|
96
|
+
]);
|
|
97
|
+
const SCHEMA_LIST = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
|
|
98
|
+
const SCHEMA_MAP = new Set(["properties", "dependentSchemas", "$defs", "definitions"]);
|
|
99
|
+
// Keywords that make the validator run a regular expression the server wrote, or a format check, on the model's input.
|
|
100
|
+
const REGEX_KEYWORDS = new Set(["pattern", "patternProperties", "format"]);
|
|
101
|
+
const MAX_SCHEMA_DEPTH = 64;
|
|
102
|
+
/**
|
|
103
|
+
* The server's input schema with every keyword removed that runs a regular expression on the model's input: `pattern`,
|
|
104
|
+
* `patternProperties` and `format`. The SDK checks a call's input against the schema before the permission gate, and a
|
|
105
|
+
* pattern such as `^(a+)+$` runs on a backtracking engine, so a server could freeze the harness with a schema alone. The
|
|
106
|
+
* server still checks its own input, and the model still reads the description. A schema nested deeper than 64 levels
|
|
107
|
+
* is refused, since no real tool needs one and walking it could exhaust the stack.
|
|
108
|
+
*/
|
|
109
|
+
export function safeSchema(schema, depth = 0) {
|
|
110
|
+
if (depth > MAX_SCHEMA_DEPTH)
|
|
111
|
+
throw new Error(`the input schema is nested deeper than ${MAX_SCHEMA_DEPTH} levels`);
|
|
112
|
+
if (!isRecord(schema))
|
|
113
|
+
return schema;
|
|
114
|
+
// Built from entries, so a key such as `__proto__` stays a plain property and never sets a prototype.
|
|
115
|
+
const entries = Object.entries(schema)
|
|
116
|
+
.filter(([key]) => !REGEX_KEYWORDS.has(key))
|
|
117
|
+
.map(([key, value]) => [key, subschemas(key, value, depth + 1)]);
|
|
118
|
+
return Object.fromEntries(entries);
|
|
119
|
+
}
|
|
120
|
+
/** One keyword's value with its subschemas made safe, by the shape the keyword has. */
|
|
121
|
+
function subschemas(key, value, depth) {
|
|
122
|
+
const each = (map, visit) => Object.fromEntries(Object.entries(map).map(([name, item]) => [name, visit(item)]));
|
|
123
|
+
// Draft 7's `items` may be a list of schemas, one per position.
|
|
124
|
+
if ((ONE_SCHEMA.has(key) || SCHEMA_LIST.has(key)) && Array.isArray(value)) {
|
|
125
|
+
return value.map((item) => safeSchema(item, depth));
|
|
126
|
+
}
|
|
127
|
+
if (ONE_SCHEMA.has(key))
|
|
128
|
+
return safeSchema(value, depth);
|
|
129
|
+
if (SCHEMA_MAP.has(key) && isRecord(value))
|
|
130
|
+
return each(value, (item) => safeSchema(item, depth));
|
|
131
|
+
// Draft 7: each value is a schema or a list of property names.
|
|
132
|
+
if (key === "dependencies" && isRecord(value)) {
|
|
133
|
+
return each(value, (item) => (Array.isArray(item) ? item : safeSchema(item, depth)));
|
|
134
|
+
}
|
|
135
|
+
return value;
|
|
136
|
+
}
|
|
137
|
+
/** One content block of a result, as the model reads it. A kind the model can't read becomes a short note. */
|
|
138
|
+
function blockOf(block) {
|
|
139
|
+
if (!isRecord(block))
|
|
140
|
+
return { type: "text", text: "[a content block that is not an object was left out]" };
|
|
141
|
+
const { type } = block;
|
|
142
|
+
if (type === "text" && typeof block.text === "string")
|
|
143
|
+
return { type: "text", text: block.text };
|
|
144
|
+
if (type === "image" && typeof block.data === "string" && typeof block.mimeType === "string") {
|
|
145
|
+
if (IMAGE_TYPES.includes(block.mimeType))
|
|
146
|
+
return { type: "image", mediaType: block.mimeType, data: block.data };
|
|
147
|
+
return { type: "text", text: `[an image of type ${shortText(block.mimeType, 64)} was left out]` };
|
|
148
|
+
}
|
|
149
|
+
if (type === "resource" && isRecord(block.resource) && typeof block.resource.text === "string") {
|
|
150
|
+
return { type: "text", text: block.resource.text };
|
|
151
|
+
}
|
|
152
|
+
if (type === "resource_link" && typeof block.uri === "string") {
|
|
153
|
+
return { type: "text", text: `[a link to the resource ${shortText(block.uri, 256)}]` };
|
|
154
|
+
}
|
|
155
|
+
const kind = typeof type === "string" ? shortText(type, 64) : "unknown";
|
|
156
|
+
return { type: "text", text: `[a ${kind} content block was left out]` };
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* A `tools/call` result as the model reads it. Structured content stands in, as JSON, only when there is no content,
|
|
160
|
+
* so a result is never empty by accident.
|
|
161
|
+
*/
|
|
162
|
+
export function resultOf(result) {
|
|
163
|
+
const record = isRecord(result) ? result : {};
|
|
164
|
+
const blocks = Array.isArray(record.content) ? record.content.map(blockOf) : [];
|
|
165
|
+
if (blocks.length === 0 && record.structuredContent !== undefined) {
|
|
166
|
+
let text;
|
|
167
|
+
try {
|
|
168
|
+
text = JSON.stringify(record.structuredContent) ?? "";
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
text = "[structured content that is not JSON was left out]";
|
|
172
|
+
}
|
|
173
|
+
blocks.push({ type: "text", text });
|
|
174
|
+
}
|
|
175
|
+
return { content: blocks, isError: record.isError === true };
|
|
176
|
+
}
|
|
177
|
+
//# sourceMappingURL=content.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"content.js","sourceRoot":"","sources":["../../src/mcp/content.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAGvC,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,CAAC;AACnC,MAAM,eAAe,GAAG,GAAG,CAAC;AAC5B,MAAM,WAAW,GAAsB,CAAC,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,YAA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YACH,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,iBAAiB,CAAC,IAAI,EAAE,CAAC;QACxD,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,GAAG,oDAAoD,CAAC;QAC9D,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IACtC,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;AAC/D,CAAC","sourcesContent":["/**\n * What the harness takes from a server's replies: a tool list it checks before any tool is registered, and tool\n * results mapped to the text and image blocks the model reads. Everything here reads untrusted data, so every field is\n * checked for its type and size, and anything unexpected becomes a refusal or a short note, never a crash.\n */\nimport type { ModelContent } from \"@buildanagent/gateway\";\nimport { McpError } from \"./errors.js\";\nimport type { McpCallResult, McpTool } from \"./types.js\";\n\nconst MAX_NAME_CHARS = 128;\nconst MAX_DESCRIPTION_CHARS = 4096;\nconst MAX_SCHEMA_BYTES = 64 * 1024;\nconst MAX_ERROR_CHARS = 500;\nconst IMAGE_TYPES: readonly string[] = [\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"];\n// The control characters of ASCII and Latin-1, which a name shown in a log or a prompt should never carry.\nconst isControl = (code: number): boolean => code <= 0x1f || (code >= 0x7f && code <= 0x9f);\nconst hasControl = (text: string): boolean => [...text].some((char) => isControl(char.codePointAt(0) ?? 0));\nconst encoder = new TextEncoder();\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * `text` cut to at most `max` UTF-16 units, with `…` after it when it was cut. It never splits a surrogate pair, since a\n * lone half would make the canonical JSON that the record hashes refuse the text, and the server's whole list with it.\n */\nexport function cut(text: string, max: number): string {\n if (text.length <= max) return text;\n const last = text.charCodeAt(max - 1);\n const end = last >= 0xd800 && last <= 0xdbff ? max - 1 : max;\n return `${text.slice(0, end)}…`;\n}\n\n/** A server's text cut to `max` characters, with its control characters replaced, for an error message. */\nexport function shortText(text: string, max = MAX_ERROR_CHARS): string {\n const plain = [...text].map((char) => (isControl(char.codePointAt(0) ?? 0) ? \" \" : char)).join(\"\");\n return cut(plain, max);\n}\n\nfunction refuse(server: string, why: string): McpError {\n return new McpError(\n \"mcp_tool_list_refused\",\n server,\n `its tool list was refused, so none of its tools was registered: ${why}`,\n );\n}\n\n/** One listed tool, checked, or the reason it can't be used. */\nfunction checkTool(server: string, tool: unknown, index: number): McpTool {\n if (!isRecord(tool)) throw refuse(server, `tool ${index} is not an object`);\n const { name, description, inputSchema, annotations } = tool;\n if (typeof name !== \"string\" || name.length === 0 || name.length > MAX_NAME_CHARS || hasControl(name)) {\n throw refuse(server, `tool ${index} has no name of 1 to ${MAX_NAME_CHARS} characters without control characters`);\n }\n if (!isRecord(inputSchema) || inputSchema.type !== \"object\") {\n throw refuse(server, `the tool ${JSON.stringify(name)} has an input schema that is not an object schema`);\n }\n let schemaBytes: number;\n try {\n schemaBytes = encoder.encode(JSON.stringify(inputSchema)).length;\n } catch {\n throw refuse(server, `the tool ${JSON.stringify(name)} has an input schema that is not JSON`);\n }\n if (schemaBytes > MAX_SCHEMA_BYTES) {\n throw refuse(server, `the tool ${JSON.stringify(name)} has an input schema over ${MAX_SCHEMA_BYTES} bytes`);\n }\n const text = typeof description === \"string\" ? description : \"\";\n return {\n name,\n description: cut(text, MAX_DESCRIPTION_CHARS),\n inputSchema,\n ...(isRecord(annotations) ? { annotations } : {}),\n };\n}\n\n/**\n * The server's tool list, checked as a whole: it is refused when it is longer than `maxTools`, when any tool fails its\n * check, or when two names match once normalised (NFKC, then lower case), since they would read as one tool to a\n * person approving a call.\n */\nexport function checkToolList(server: string, tools: unknown, maxTools: number): McpTool[] {\n if (!Array.isArray(tools)) throw refuse(server, \"it did not send a list of tools\");\n if (tools.length > maxTools) throw refuse(server, `it listed ${tools.length} tools, over the limit of ${maxTools}`);\n const seen = new Map<string, string>();\n return tools.map((tool, index) => {\n const checked = checkTool(server, tool, index);\n const key = checked.name.normalize(\"NFKC\").toLowerCase();\n const earlier = seen.get(key);\n if (earlier !== undefined) {\n throw refuse(server, `the names ${JSON.stringify(earlier)} and ${JSON.stringify(checked.name)} name one tool`);\n }\n seen.set(key, checked.name);\n return checked;\n });\n}\n\n// Keywords whose value is one subschema, a list of them, or a map of names to them. Everything else in a schema is\n// data, such as `enum` or `default`, and is copied as it is.\nconst ONE_SCHEMA = new Set([\n \"additionalProperties\",\n \"items\",\n \"additionalItems\",\n \"contains\",\n \"propertyNames\",\n \"unevaluatedProperties\",\n \"unevaluatedItems\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n]);\nconst SCHEMA_LIST = new Set([\"allOf\", \"anyOf\", \"oneOf\", \"prefixItems\"]);\nconst SCHEMA_MAP = new Set([\"properties\", \"dependentSchemas\", \"$defs\", \"definitions\"]);\n// Keywords that make the validator run a regular expression the server wrote, or a format check, on the model's input.\nconst REGEX_KEYWORDS = new Set([\"pattern\", \"patternProperties\", \"format\"]);\nconst MAX_SCHEMA_DEPTH = 64;\n\n/**\n * The server's input schema with every keyword removed that runs a regular expression on the model's input: `pattern`,\n * `patternProperties` and `format`. The SDK checks a call's input against the schema before the permission gate, and a\n * pattern such as `^(a+)+$` runs on a backtracking engine, so a server could freeze the harness with a schema alone. The\n * server still checks its own input, and the model still reads the description. A schema nested deeper than 64 levels\n * is refused, since no real tool needs one and walking it could exhaust the stack.\n */\nexport function safeSchema(schema: unknown, depth = 0): unknown {\n if (depth > MAX_SCHEMA_DEPTH) throw new Error(`the input schema is nested deeper than ${MAX_SCHEMA_DEPTH} levels`);\n if (!isRecord(schema)) return schema;\n // Built from entries, so a key such as `__proto__` stays a plain property and never sets a prototype.\n const entries = Object.entries(schema)\n .filter(([key]) => !REGEX_KEYWORDS.has(key))\n .map(([key, value]): [string, unknown] => [key, subschemas(key, value, depth + 1)]);\n return Object.fromEntries(entries);\n}\n\n/** One keyword's value with its subschemas made safe, by the shape the keyword has. */\nfunction subschemas(key: string, value: unknown, depth: number): unknown {\n const each = (map: Record<string, unknown>, visit: (item: unknown) => unknown) =>\n Object.fromEntries(Object.entries(map).map(([name, item]) => [name, visit(item)]));\n // Draft 7's `items` may be a list of schemas, one per position.\n if ((ONE_SCHEMA.has(key) || SCHEMA_LIST.has(key)) && Array.isArray(value)) {\n return value.map((item) => safeSchema(item, depth));\n }\n if (ONE_SCHEMA.has(key)) return safeSchema(value, depth);\n if (SCHEMA_MAP.has(key) && isRecord(value)) return each(value, (item) => safeSchema(item, depth));\n // Draft 7: each value is a schema or a list of property names.\n if (key === \"dependencies\" && isRecord(value)) {\n return each(value, (item) => (Array.isArray(item) ? item : safeSchema(item, depth)));\n }\n return value;\n}\n\n/** One content block of a result, as the model reads it. A kind the model can't read becomes a short note. */\nfunction blockOf(block: unknown): ModelContent {\n if (!isRecord(block)) return { type: \"text\", text: \"[a content block that is not an object was left out]\" };\n const { type } = block;\n if (type === \"text\" && typeof block.text === \"string\") return { type: \"text\", text: block.text };\n if (type === \"image\" && typeof block.data === \"string\" && typeof block.mimeType === \"string\") {\n if (IMAGE_TYPES.includes(block.mimeType)) return { type: \"image\", mediaType: block.mimeType, data: block.data };\n return { type: \"text\", text: `[an image of type ${shortText(block.mimeType, 64)} was left out]` };\n }\n if (type === \"resource\" && isRecord(block.resource) && typeof block.resource.text === \"string\") {\n return { type: \"text\", text: block.resource.text };\n }\n if (type === \"resource_link\" && typeof block.uri === \"string\") {\n return { type: \"text\", text: `[a link to the resource ${shortText(block.uri, 256)}]` };\n }\n const kind = typeof type === \"string\" ? shortText(type, 64) : \"unknown\";\n return { type: \"text\", text: `[a ${kind} content block was left out]` };\n}\n\n/**\n * A `tools/call` result as the model reads it. Structured content stands in, as JSON, only when there is no content,\n * so a result is never empty by accident.\n */\nexport function resultOf(result: unknown): McpCallResult {\n const record = isRecord(result) ? result : {};\n const blocks = Array.isArray(record.content) ? record.content.map(blockOf) : [];\n if (blocks.length === 0 && record.structuredContent !== undefined) {\n let text: string;\n try {\n text = JSON.stringify(record.structuredContent) ?? \"\";\n } catch {\n text = \"[structured content that is not JSON was left out]\";\n }\n blocks.push({ type: \"text\", text });\n }\n return { content: blocks, isError: record.isError === true };\n}\n"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The MCP client's named error: a `HarnessError` that names the server it came from. */
|
|
2
|
+
import { HarnessError, type HarnessErrorCode } from "../errors.js";
|
|
3
|
+
/** Why an MCP tool call ended without a result. */
|
|
4
|
+
export type McpCallFailure = "closed" | "timeout" | "aborted" | "input_required" | "server_error";
|
|
5
|
+
/**
|
|
6
|
+
* Thrown for a server that could not connect (`mcp_connect_failed`), a tool list the harness refuses
|
|
7
|
+
* (`mcp_tool_list_refused`) and a tool call that ended with no result (`mcp_call_failed`, with `failure` saying why).
|
|
8
|
+
* Its message names the server and never holds the server's standard error.
|
|
9
|
+
*/
|
|
10
|
+
export declare class McpError extends HarnessError {
|
|
11
|
+
readonly name = "McpError";
|
|
12
|
+
/** The name of the server, from its config. */
|
|
13
|
+
readonly server: string;
|
|
14
|
+
/** Why a call failed, for `mcp_call_failed`. */
|
|
15
|
+
readonly failure?: McpCallFailure;
|
|
16
|
+
constructor(code: Extract<HarnessErrorCode, "mcp_connect_failed" | "mcp_tool_list_refused" | "mcp_call_failed">, server: string, message: string, options?: ErrorOptions & {
|
|
17
|
+
readonly failure?: McpCallFailure;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** The MCP client's named error: a `HarnessError` that names the server it came from. */
|
|
2
|
+
import { HarnessError } from "../errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Thrown for a server that could not connect (`mcp_connect_failed`), a tool list the harness refuses
|
|
5
|
+
* (`mcp_tool_list_refused`) and a tool call that ended with no result (`mcp_call_failed`, with `failure` saying why).
|
|
6
|
+
* Its message names the server and never holds the server's standard error.
|
|
7
|
+
*/
|
|
8
|
+
export class McpError extends HarnessError {
|
|
9
|
+
name = "McpError";
|
|
10
|
+
/** The name of the server, from its config. */
|
|
11
|
+
server;
|
|
12
|
+
/** Why a call failed, for `mcp_call_failed`. */
|
|
13
|
+
failure;
|
|
14
|
+
constructor(code, server, message, options) {
|
|
15
|
+
super(code, `MCP server "${server}": ${message}`, options);
|
|
16
|
+
this.server = server;
|
|
17
|
+
if (options?.failure !== undefined)
|
|
18
|
+
this.failure = options.failure;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/mcp/errors.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,OAAO,EAAE,YAAY,EAAyB,MAAM,cAAc,CAAC;AAKnE;;;;GAIG;AACH,MAAM,OAAO,QAAS,SAAQ,YAAY;IACtB,IAAI,GAAG,UAAU,CAAC;IACpC,+CAA+C;IACtC,MAAM,CAAS;IACxB,gDAAgD;IACvC,OAAO,CAAkB;IAElC,YACE,IAAmG,EACnG,MAAc,EACd,OAAe,EACf,OAA8D;QAE9D,KAAK,CAAC,IAAI,EAAE,eAAe,MAAM,MAAM,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;QAC3D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,OAAO,EAAE,OAAO,KAAK,SAAS;YAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IACrE,CAAC;CACF","sourcesContent":["/** The MCP client's named error: a `HarnessError` that names the server it came from. */\nimport { HarnessError, type HarnessErrorCode } from \"../errors.js\";\n\n/** Why an MCP tool call ended without a result. */\nexport type McpCallFailure = \"closed\" | \"timeout\" | \"aborted\" | \"input_required\" | \"server_error\";\n\n/**\n * Thrown for a server that could not connect (`mcp_connect_failed`), a tool list the harness refuses\n * (`mcp_tool_list_refused`) and a tool call that ended with no result (`mcp_call_failed`, with `failure` saying why).\n * Its message names the server and never holds the server's standard error.\n */\nexport class McpError extends HarnessError {\n override readonly name = \"McpError\";\n /** The name of the server, from its config. */\n readonly server: string;\n /** Why a call failed, for `mcp_call_failed`. */\n readonly failure?: McpCallFailure;\n\n constructor(\n code: Extract<HarnessErrorCode, \"mcp_connect_failed\" | \"mcp_tool_list_refused\" | \"mcp_call_failed\">,\n server: string,\n message: string,\n options?: ErrorOptions & { readonly failure?: McpCallFailure },\n ) {\n super(code, `MCP server \"${server}\": ${message}`, options);\n this.server = server;\n if (options?.failure !== undefined) this.failure = options.failure;\n }\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/harness/mcp`: the MCP client. `createMcpManager()` connects each configured server, negotiates its
|
|
3
|
+
* protocol era, and registers its tools as `mcp__<server>__<tool>`, deferred by default. `connectMcpServer()` connects
|
|
4
|
+
* one server without registering anything. The stdio transport is Node-only; an in-process server works on any runtime.
|
|
5
|
+
*/
|
|
6
|
+
export { connectMcpServer } from "./connection.js";
|
|
7
|
+
export { type McpCallFailure, McpError } from "./errors.js";
|
|
8
|
+
export { createMcpManager } from "./manager.js";
|
|
9
|
+
export { killMcpServersOnSignal } from "./stdio.js";
|
|
10
|
+
export type { McpCallResult, McpChannel, McpConnection, McpEra, McpInProcessTransport, McpManager, McpManagerOptions, McpServerConfig, McpServerStatus, McpStdioTransport, McpTool, } from "./types.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/harness/mcp`: the MCP client. `createMcpManager()` connects each configured server, negotiates its
|
|
3
|
+
* protocol era, and registers its tools as `mcp__<server>__<tool>`, deferred by default. `connectMcpServer()` connects
|
|
4
|
+
* one server without registering anything. The stdio transport is Node-only; an in-process server works on any runtime.
|
|
5
|
+
*/
|
|
6
|
+
export { connectMcpServer } from "./connection.js";
|
|
7
|
+
export { McpError } from "./errors.js";
|
|
8
|
+
export { createMcpManager } from "./manager.js";
|
|
9
|
+
export { killMcpServersOnSignal } from "./stdio.js";
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/mcp/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAuB,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/mcp`: the MCP client. `createMcpManager()` connects each configured server, negotiates its\n * protocol era, and registers its tools as `mcp__<server>__<tool>`, deferred by default. `connectMcpServer()` connects\n * one server without registering anything. The stdio transport is Node-only; an in-process server works on any runtime.\n */\nexport { connectMcpServer } from \"./connection.js\";\nexport { type McpCallFailure, McpError } from \"./errors.js\";\nexport { createMcpManager } from \"./manager.js\";\nexport { killMcpServersOnSignal } from \"./stdio.js\";\nexport type {\n McpCallResult,\n McpChannel,\n McpConnection,\n McpEra,\n McpInProcessTransport,\n McpManager,\n McpManagerOptions,\n McpServerConfig,\n McpServerStatus,\n McpStdioTransport,\n McpTool,\n} from \"./types.js\";\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { McpManager, McpManagerOptions } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Creates the MCP client for a set of servers. It checks every config now and starts nothing until `connect()`.
|
|
4
|
+
* Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be used, two servers with one name, or a
|
|
5
|
+
* registry without `register()`, `registerAll()` and `list()`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function createMcpManager(options: McpManagerOptions): McpManager;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createMcpManager()`: the MCP client as one removable component. It connects each server on its own, so one slow or
|
|
3
|
+
* broken server never holds back the others, and registers each server's tools with the registry under the source
|
|
4
|
+
* `mcp:<name>`, which names them `mcp__<name>__<tool>` and defers them by default.
|
|
5
|
+
*
|
|
6
|
+
* A server's tools are registered all or none: the list is checked, then registered through `registerAll()`, which
|
|
7
|
+
* removes the tools it added when any one is refused, so a list the registry would refuse halfway leaves nothing
|
|
8
|
+
* behind. Every tool is marked as not first-party and as a write, whatever its annotations say, so a server's
|
|
9
|
+
* `readOnlyHint` can't make the loop run its calls together or run one again after a crash. The calls reach the server
|
|
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
|
+
import { defineTool } from "@buildanagent/sdk";
|
|
13
|
+
import { HarnessError } from "../errors.js";
|
|
14
|
+
import { checkServerConfig, connectMcpServer } from "./connection.js";
|
|
15
|
+
import { safeSchema } from "./content.js";
|
|
16
|
+
import { McpError } from "./errors.js";
|
|
17
|
+
import { mcpRecordOf } from "./record.js";
|
|
18
|
+
// A placeholder that passes defineTool()'s name check; the registry names every tool by its canonical name.
|
|
19
|
+
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) {
|
|
22
|
+
return defineTool({
|
|
23
|
+
name: PLACEHOLDER_NAME,
|
|
24
|
+
description: tool.description,
|
|
25
|
+
kind: "dynamic",
|
|
26
|
+
// The server's own schema runs no regular expression here: see safeSchema().
|
|
27
|
+
inputSchema: safeSchema(tool.inputSchema),
|
|
28
|
+
firstParty: false,
|
|
29
|
+
// A server's hints are claims by code the harness does not control, so every call is treated as a write.
|
|
30
|
+
effect: { kind: "write" },
|
|
31
|
+
async execute(input, ctx) {
|
|
32
|
+
const result = await connection.callTool(tool.name, input, ctx.signal);
|
|
33
|
+
return { content: result.content, ...(result.isError ? { isError: true } : {}) };
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
}
|
|
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
|
+
/** 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) {
|
|
47
|
+
return tools.map((tool) => {
|
|
48
|
+
try {
|
|
49
|
+
return registrationOf(config, connection, tool);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
throw refused(config.name, error);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function refused(server, error) {
|
|
57
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
58
|
+
return new McpError("mcp_tool_list_refused", server, `its tool list was refused, so none of its tools was registered: ${why}`, { cause: error });
|
|
59
|
+
}
|
|
60
|
+
function checkServers(servers) {
|
|
61
|
+
if (!Array.isArray(servers))
|
|
62
|
+
throw new HarnessError("invalid_mcp_config", "servers must be a list");
|
|
63
|
+
const names = new Set();
|
|
64
|
+
for (const config of servers) {
|
|
65
|
+
checkServerConfig(config);
|
|
66
|
+
const key = config.name.toLowerCase();
|
|
67
|
+
if (names.has(key)) {
|
|
68
|
+
throw new HarnessError("invalid_mcp_config", `two MCP servers are named "${config.name}", in some letter case`);
|
|
69
|
+
}
|
|
70
|
+
names.add(key);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
class Manager {
|
|
74
|
+
#options;
|
|
75
|
+
#connections = new Map();
|
|
76
|
+
#records = new Map();
|
|
77
|
+
// Every connection that exists, registered or not, so a close can end one whose tool list is still being read.
|
|
78
|
+
#open = new Set();
|
|
79
|
+
#abort = new AbortController();
|
|
80
|
+
#connecting;
|
|
81
|
+
#closing;
|
|
82
|
+
constructor(options) {
|
|
83
|
+
this.#options = options;
|
|
84
|
+
}
|
|
85
|
+
connect() {
|
|
86
|
+
if (this.#closing !== undefined) {
|
|
87
|
+
return Promise.reject(new HarnessError("invalid_mcp_config", "the MCP manager was closed"));
|
|
88
|
+
}
|
|
89
|
+
this.#connecting ??=
|
|
90
|
+
this.#options.mcp === false
|
|
91
|
+
? Promise.resolve([])
|
|
92
|
+
: Promise.all(this.#options.servers.map((config) => this.#connectOne(config)));
|
|
93
|
+
return this.#connecting;
|
|
94
|
+
}
|
|
95
|
+
async #connectOne(config) {
|
|
96
|
+
const log = this.#options.log ?? (() => { });
|
|
97
|
+
let connection;
|
|
98
|
+
try {
|
|
99
|
+
connection = await connectMcpServer(config, { log, signal: this.#abort.signal });
|
|
100
|
+
this.#open.add(connection);
|
|
101
|
+
// A close that began during the handshake must still end this server.
|
|
102
|
+
if (this.#closing !== undefined)
|
|
103
|
+
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);
|
|
106
|
+
let record;
|
|
107
|
+
try {
|
|
108
|
+
record = await mcpRecordOf(config, connection, listed);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
throw refused(config.name, error);
|
|
112
|
+
}
|
|
113
|
+
if (this.#closing !== undefined)
|
|
114
|
+
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;
|
|
122
|
+
try {
|
|
123
|
+
tools = this.#options.registry.registerAll(registrations).map((tool) => tool.canonicalName);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
throw refused(config.name, error);
|
|
127
|
+
}
|
|
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 };
|
|
131
|
+
}
|
|
132
|
+
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 };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
records() {
|
|
142
|
+
return this.#options.servers.flatMap((config) => this.#records.get(config.name) ?? []);
|
|
143
|
+
}
|
|
144
|
+
connection(server) {
|
|
145
|
+
return this.#connections.get(server);
|
|
146
|
+
}
|
|
147
|
+
close() {
|
|
148
|
+
this.#closing ??= (async () => {
|
|
149
|
+
// Aborting ends every handshake still running, and closing every open connection fails any tool list still being
|
|
150
|
+
// read, so a server that hangs can't hold the others up.
|
|
151
|
+
this.#abort.abort();
|
|
152
|
+
await Promise.all([...this.#open].map((connection) => connection.close()));
|
|
153
|
+
await this.#connecting?.catch(() => { });
|
|
154
|
+
})();
|
|
155
|
+
return this.#closing;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
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()`.
|
|
162
|
+
*/
|
|
163
|
+
export function createMcpManager(options) {
|
|
164
|
+
const registry = options?.registry;
|
|
165
|
+
for (const method of ["register", "registerAll", "list"]) {
|
|
166
|
+
if (typeof registry?.[method] !== "function") {
|
|
167
|
+
throw new HarnessError("invalid_mcp_config", `createMcpManager() needs a tool registry with ${method}()`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
checkServers(options.servers);
|
|
171
|
+
return new Manager(options);
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/mcp/manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,UAAU,EAAuB,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAU1C,4GAA4G;AAC5G,MAAM,gBAAgB,GAAG,UAAU,CAAC;AAEpC,gHAAgH;AAChH,SAAS,YAAY,CAAC,UAAyB,EAAE,IAAa;IAC5D,OAAO,UAAU,CAA4B;QAC3C,IAAI,EAAE,gBAAgB;QACtB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,IAAI,EAAE,SAAS;QACf,6EAA6E;QAC7E,WAAW,EAAE,UAAU,CAAC,IAAI,CAAC,WAAW,CAAsC;QAC9E,UAAU,EAAE,KAAK;QACjB,yGAAyG;QACzG,MAAM,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;QACzB,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG;YACtB,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;YACvE,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC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AAI,OAAO,QAAQ,EAAE,CAAC,MAAM,CAAC,KAAK,UAAU,EAAE,CAAC;YAC7C,MAAM,IAAI,YAAY,CAAC,oBAAoB,EAAE,iDAAiD,MAAM,IAAI,CAAC,CAAC;QAC5G,CAAC;IACH,CAAC;IACD,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC9B,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * `createMcpManager()`: the MCP client as one removable component. It connects each server on its own, so one slow or\n * broken server never holds back the others, and registers each server's tools with the registry under the source\n * `mcp:<name>`, which names them `mcp__<name>__<tool>` and defers them by default.\n *\n * A server's tools are registered all or none: the list is checked, then registered through `registerAll()`, which\n * removes the tools it added when any one is refused, so a list the registry would refuse halfway leaves nothing\n * behind. Every tool is marked as not first-party and as a write, whatever its annotations say, so a server's\n * `readOnlyHint` can't make the loop run its calls together or run one again after a crash. The calls reach the server\n * only through the turn's tool pipeline, so the permission gate and the write cap apply to them as to any tool.\n */\nimport { defineTool, type ToolDefinition } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { ExtensionLoadedRecord } from \"../extensions/types.js\";\nimport type { ToolRegistration } from \"../tools/types.js\";\nimport { checkServerConfig, connectMcpServer } from \"./connection.js\";\nimport { safeSchema } from \"./content.js\";\nimport { McpError } from \"./errors.js\";\nimport { mcpRecordOf } from \"./record.js\";\nimport type {\n McpConnection,\n McpManager,\n McpManagerOptions,\n McpServerConfig,\n McpServerStatus,\n McpTool,\n} from \"./types.js\";\n\n// A placeholder that passes defineTool()'s name check; the registry names every tool by its canonical name.\nconst PLACEHOLDER_NAME = \"mcp_tool\";\n\n/** The definition of one server tool. Its `execute` calls the tool by the name the server listed at connect. */\nfunction definitionOf(connection: McpConnection, tool: McpTool): ToolDefinition<unknown, unknown, unknown> {\n return defineTool<unknown, unknown, unknown>({\n name: PLACEHOLDER_NAME,\n description: tool.description,\n kind: \"dynamic\",\n // The server's own schema runs no regular expression here: see safeSchema().\n inputSchema: safeSchema(tool.inputSchema) as Readonly<Record<string, unknown>>,\n firstParty: false,\n // A server's hints are claims by code the harness does not control, so every call is treated as a write.\n effect: { kind: \"write\" },\n async execute(input, ctx) {\n const result = await connection.callTool(tool.name, input, ctx.signal);\n return { content: result.content, ...(result.isError ? { isError: true } : {}) };\n },\n });\n}\n\nfunction registrationOf(config: McpServerConfig, connection: McpConnection, tool: McpTool): ToolRegistration {\n return {\n name: tool.name,\n source: `mcp:${config.name}`,\n ...(config.exposure === undefined ? {} : { exposure: config.exposure }),\n definition: definitionOf(connection, tool),\n };\n}\n\n/** The server's registrations, built before any is registered, so a tool the SDK refuses fails the whole list. */\nfunction registrationsOf(config: McpServerConfig, connection: McpConnection, tools: readonly McpTool[]) {\n return tools.map((tool) => {\n try {\n return registrationOf(config, connection, tool);\n } catch (error) {\n throw refused(config.name, error);\n }\n });\n}\n\nfunction refused(server: string, error: unknown): McpError {\n const why = error instanceof Error ? error.message : String(error);\n return new McpError(\n \"mcp_tool_list_refused\",\n server,\n `its tool list was refused, so none of its tools was registered: ${why}`,\n { cause: error },\n );\n}\n\nfunction checkServers(servers: readonly McpServerConfig[]): void {\n if (!Array.isArray(servers)) throw new HarnessError(\"invalid_mcp_config\", \"servers must be a list\");\n const names = new Set<string>();\n for (const config of servers) {\n checkServerConfig(config);\n const key = config.name.toLowerCase();\n if (names.has(key)) {\n throw new HarnessError(\"invalid_mcp_config\", `two MCP servers are named \"${config.name}\", in some letter case`);\n }\n names.add(key);\n }\n}\n\nclass Manager implements McpManager {\n readonly #options: McpManagerOptions;\n readonly #connections = new Map<string, McpConnection>();\n readonly #records = new Map<string, ExtensionLoadedRecord>();\n // Every connection that exists, registered or not, so a close can end one whose tool list is still being read.\n readonly #open = new Set<McpConnection>();\n readonly #abort = new AbortController();\n #connecting: Promise<readonly McpServerStatus[]> | undefined;\n #closing: Promise<void> | undefined;\n\n constructor(options: McpManagerOptions) {\n this.#options = options;\n }\n\n connect(): Promise<readonly McpServerStatus[]> {\n if (this.#closing !== undefined) {\n return Promise.reject(new HarnessError(\"invalid_mcp_config\", \"the MCP manager was closed\"));\n }\n this.#connecting ??=\n this.#options.mcp === false\n ? Promise.resolve([])\n : Promise.all(this.#options.servers.map((config) => this.#connectOne(config)));\n return this.#connecting;\n }\n\n async #connectOne(config: McpServerConfig): Promise<McpServerStatus> {\n const log = this.#options.log ?? (() => {});\n let connection: McpConnection | undefined;\n try {\n connection = await connectMcpServer(config, { log, signal: this.#abort.signal });\n this.#open.add(connection);\n // A close that began during the handshake must still end this server.\n if (this.#closing !== undefined) throw new McpError(\"mcp_connect_failed\", config.name, \"the manager was closed\");\n const listed = await connection.listTools();\n const registrations = registrationsOf(config, connection, listed);\n let record: ExtensionLoadedRecord;\n try {\n record = await mcpRecordOf(config, connection, listed);\n } catch (error) {\n throw refused(config.name, error);\n }\n if (this.#closing !== undefined) throw new McpError(\"mcp_connect_failed\", config.name, \"the manager was closed\");\n // Nothing awaits between this check and the registration, so another manager on the same registry can't\n // register the source in between, and registerAll() leaves nothing behind when any tool is refused.\n const source = `mcp:${config.name}`;\n if (this.#options.registry.list().some((tool) => tool.source === source)) {\n throw new McpError(\"mcp_tool_list_refused\", config.name, `the registry already holds tools from ${source}`);\n }\n let tools: string[];\n try {\n tools = this.#options.registry.registerAll(registrations).map((tool) => tool.canonicalName);\n } catch (error) {\n throw refused(config.name, error);\n }\n this.#connections.set(config.name, connection);\n this.#records.set(config.name, record);\n return { server: config.name, status: \"connected\", era: connection.era, tools };\n } catch (error) {\n if (connection !== undefined) this.#open.delete(connection);\n await connection?.close();\n const failure = error instanceof Error ? error : new Error(String(error));\n log(`the MCP server \"${config.name}\" was not connected: ${failure.message}`);\n return { server: config.name, status: \"failed\", error: failure };\n }\n }\n\n records(): readonly ExtensionLoadedRecord[] {\n return this.#options.servers.flatMap((config) => this.#records.get(config.name) ?? []);\n }\n\n connection(server: string): McpConnection | undefined {\n return this.#connections.get(server);\n }\n\n close(): Promise<void> {\n this.#closing ??= (async () => {\n // Aborting ends every handshake still running, and closing every open connection fails any tool list still being\n // read, so a server that hangs can't hold the others up.\n this.#abort.abort();\n await Promise.all([...this.#open].map((connection) => connection.close()));\n await this.#connecting?.catch(() => {});\n })();\n return this.#closing;\n }\n}\n\n/**\n * Creates the MCP client for a set of servers. It checks every config now and starts nothing until `connect()`.\n * Throws a `HarnessError`, code `invalid_mcp_config`, for a config that can't be used, two servers with one name, or a\n * registry without `register()`, `registerAll()` and `list()`.\n */\nexport function createMcpManager(options: McpManagerOptions): McpManager {\n const registry = options?.registry;\n for (const method of [\"register\", \"registerAll\", \"list\"] as const) {\n if (typeof registry?.[method] !== \"function\") {\n throw new HarnessError(\"invalid_mcp_config\", `createMcpManager() needs a tool registry with ${method}()`);\n }\n }\n checkServers(options.servers);\n return new Manager(options);\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ExtensionLoadedRecord } from "../extensions/types.js";
|
|
2
|
+
import type { McpConnection, McpServerConfig, McpTool } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* The record for a server whose tools were registered. The tools hash covers each tool's name, description and input
|
|
5
|
+
* schema, sorted by name, and leaves out the annotations, which change nothing the harness does.
|
|
6
|
+
*/
|
|
7
|
+
export declare function mcpRecordOf(config: McpServerConfig, connection: McpConnection, tools: readonly McpTool[]): Promise<ExtensionLoadedRecord>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { canonicalInputHash } from "@buildanagent/sdk";
|
|
2
|
+
const hash = async (value) => `sha256:${await canonicalInputHash(value)}`;
|
|
3
|
+
/**
|
|
4
|
+
* The record for a server whose tools were registered. The tools hash covers each tool's name, description and input
|
|
5
|
+
* schema, sorted by name, and leaves out the annotations, which change nothing the harness does.
|
|
6
|
+
*/
|
|
7
|
+
export async function mcpRecordOf(config, connection, tools) {
|
|
8
|
+
const listed = [...tools]
|
|
9
|
+
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
10
|
+
.map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));
|
|
11
|
+
const transport = config.transport;
|
|
12
|
+
const mcp = {
|
|
13
|
+
transport: transport.kind,
|
|
14
|
+
...(transport.kind === "stdio" ? { commandHash: await hash([transport.command, ...(transport.args ?? [])]) } : {}),
|
|
15
|
+
era: connection.era,
|
|
16
|
+
toolsHash: await hash(listed),
|
|
17
|
+
};
|
|
18
|
+
return { name: config.name, tier: "mcp", contentHash: await hash(mcp), mcp };
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=record.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"record.js","sourceRoot":"","sources":["../../src/mcp/record.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAIvD,MAAM,IAAI,GAAG,KAAK,EAAE,KAAc,EAAmB,EAAE,CAAC,UAAU,MAAM,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;AAEpG;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,MAAuB,EACvB,UAAyB,EACzB,KAAyB;IAEzB,MAAM,MAAM,GAAG,CAAC,GAAG,KAAK,CAAC;SACtB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAChE,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC;IACrF,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;IACnC,MAAM,GAAG,GAAoB;QAC3B,SAAS,EAAE,SAAS,CAAC,IAAI;QACzB,GAAG,CAAC,SAAS,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,IAAI,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAClH,GAAG,EAAE,UAAU,CAAC,GAAG;QACnB,SAAS,EAAE,MAAM,IAAI,CAAC,MAAM,CAAC;KAC9B,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC;AAC/E,CAAC","sourcesContent":["/**\n * The `extension_loaded` record of a connected MCP server. It holds hashes and never a raw argument or an environment\n * value, because a server's command line or variables can carry a token. Every hash is `sha256:` and the hex SHA-256 of\n * canonical JSON (RFC 8785), the hash the permission pipeline uses for tool inputs, so the record is the same on every\n * runtime and across reconnects of an unchanged server.\n */\nimport type { McpServerRecord } from \"@buildanagent/protocol\";\nimport { canonicalInputHash } from \"@buildanagent/sdk\";\nimport type { ExtensionLoadedRecord } from \"../extensions/types.js\";\nimport type { McpConnection, McpServerConfig, McpTool } from \"./types.js\";\n\nconst hash = async (value: unknown): Promise<string> => `sha256:${await canonicalInputHash(value)}`;\n\n/**\n * The record for a server whose tools were registered. The tools hash covers each tool's name, description and input\n * schema, sorted by name, and leaves out the annotations, which change nothing the harness does.\n */\nexport async function mcpRecordOf(\n config: McpServerConfig,\n connection: McpConnection,\n tools: readonly McpTool[],\n): Promise<ExtensionLoadedRecord> {\n const listed = [...tools]\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n .map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));\n const transport = config.transport;\n const mcp: McpServerRecord = {\n transport: transport.kind,\n ...(transport.kind === \"stdio\" ? { commandHash: await hash([transport.command, ...(transport.args ?? [])]) } : {}),\n era: connection.era,\n toolsHash: await hash(listed),\n };\n return { name: config.name, tier: \"mcp\", contentHash: await hash(mcp), mcp };\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { McpChannel, McpStdioTransport } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Opts this process in to ending every MCP server on `SIGINT`, `SIGTERM` or `SIGHUP`, for a host whose process those
|
|
4
|
+
* signals end, such as a one-shot command. The harness adds no signal listener unless asked, because a listener changes
|
|
5
|
+
* what a signal does to the host.
|
|
6
|
+
*
|
|
7
|
+
* On the first of those signals, the handler kills every server's process group, removes its listeners and raises the
|
|
8
|
+
* signal again, so the process then behaves as it would have without them: it ends when nothing else listens, and a
|
|
9
|
+
* listener that re-raises only when it is alone, as `signal-exit` does, sees itself alone. A host that handles `SIGINT`
|
|
10
|
+
* to cancel a turn should not opt in, since the first `SIGINT` ends its servers; such a host calls `manager.close()`.
|
|
11
|
+
* Returns a function that removes the listeners again.
|
|
12
|
+
*/
|
|
13
|
+
export declare function killMcpServersOnSignal(): () => void;
|
|
14
|
+
/** Checks a stdio transport's settings, so a typo fails when the manager is made and not when the server starts. */
|
|
15
|
+
export declare function checkStdioTransport(transport: McpStdioTransport): void;
|
|
16
|
+
/** A stdio server as a channel. The `pid` and `stderr` fields also tell the MCP client library it is a stdio channel. */
|
|
17
|
+
export declare class StdioChannel implements McpChannel {
|
|
18
|
+
#private;
|
|
19
|
+
onmessage?: ((message: object) => void) | undefined;
|
|
20
|
+
onclose?: (() => void) | undefined;
|
|
21
|
+
onerror?: ((error: Error) => void) | undefined;
|
|
22
|
+
constructor(transport: McpStdioTransport, log: (line: string) => void);
|
|
23
|
+
/** The child's process id once it has started. */
|
|
24
|
+
get pid(): number | undefined;
|
|
25
|
+
/** The newest bytes the child wrote to standard error, as text. */
|
|
26
|
+
get stderr(): string;
|
|
27
|
+
/** True when the server exited before anything asked the channel to close. */
|
|
28
|
+
get endedByServer(): boolean;
|
|
29
|
+
/**
|
|
30
|
+
* True when the server exited cleanly, with code 0, after the client sent it the `server/discover` probe: what a
|
|
31
|
+
* server on an SDK that closes on any request before `initialize` does.
|
|
32
|
+
*/
|
|
33
|
+
get exitedOnProbe(): boolean;
|
|
34
|
+
/** True once the channel has closed, whoever closed it. */
|
|
35
|
+
get closed(): boolean;
|
|
36
|
+
start(): Promise<void>;
|
|
37
|
+
send(message: object): Promise<void>;
|
|
38
|
+
close(): Promise<void>;
|
|
39
|
+
}
|