@hydraharness/harness-mcp-client 0.1.1-rc.5

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # @hydraharness/harness-mcp-client
2
+
3
+ MCP client bridge plugin: connects to external [Model Context Protocol](https://modelcontextprotocol.io/) servers and registers their tools on `ctx.tools`, making them available to the model as native tools under server-qualified names (`mcp__<serverName>__<rawName>`).
4
+
5
+ ## Usage
6
+
7
+ One plugin instance per MCP server in `cordis.yml`:
8
+
9
+ ```yaml
10
+ - id: mcp-github
11
+ name: '@hydraharness/harness-mcp-client'
12
+ config:
13
+ serverName: github
14
+ transport: stdio
15
+ command: npx
16
+ args: ['-y', '@modelcontextprotocol/server-github']
17
+ env:
18
+ GITHUB_TOKEN: !!js process.env.GITHUB_TOKEN
19
+
20
+ - id: mcp-web
21
+ name: '@hydraharness/harness-mcp-client'
22
+ config:
23
+ serverName: web
24
+ transport: streamable-http
25
+ url: http://localhost:3000/mcp
26
+ headers:
27
+ Authorization: !!js '`Bearer ${process.env.MCP_TOKEN}`'
28
+ ```
29
+
30
+ The model sees `mcp__github__create_issue`, `mcp__web__search`, … — the same server-qualified shape Claude Code and Codex use. HMR hot-swaps: editing the entry triggers disconnect + reconnect without process restart; an unchanged `serverName` reproduces identical tool names.
31
+
32
+ ## Config
33
+
34
+ | Field | Transport | Required | Description |
35
+ |---|---|---|---|
36
+ | `transport` | both | yes | `"stdio"` or `"streamable-http"` |
37
+ | `serverName` | both | yes | Namespace for this server's model-facing tool names; `[A-Za-z0-9_-]{1,32}`, unique across live instances |
38
+ | `command` | stdio | yes | Executable to spawn |
39
+ | `args` | stdio | no | Arguments passed to the command |
40
+ | `env` | stdio | no | Extra env vars merged on top of scrubbed ambient env |
41
+ | `cwd` | stdio | no | Working directory for the child process |
42
+ | `url` | http | yes | MCP server URL |
43
+ | `headers` | http | no | Extra headers (e.g. auth tokens) |
44
+ | `bearerTokenEnvVar` | http | no | Environment variable resolved to a bearer token when each HTTP connection starts; its value is never stored in the config |
45
+ | `toolCallTimeoutMs` | both | no | Timeout per `callTool` invocation (default 60000) |
46
+ | `failOnStartupError` | both | no | Reject plugin activation when initial connection or tool synchronization fails (default `false`) |
47
+ | `reconnect.enabled` | both | no | Reconnect automatically after a lost connection (default `true`) |
48
+ | `reconnect.initialDelayMs` | both | no | First reconnect delay in ms; doubles per consecutive failed attempt (default 500) |
49
+ | `reconnect.maxDelayMs` | both | no | Backoff ceiling in ms; also the uptime after which the attempt budget resets (default 30000) |
50
+ | `reconnect.maxAttempts` | both | no | Consecutive failed attempts per outage before giving up for good (default 10) |
51
+
52
+ ## Tool naming
53
+
54
+ Every MCP tool has two names: the raw MCP name (sent on the wire in `tools/call`) and the public name `mcp__<serverName>__<rawName>` registered on `ctx.tools`. Public names are normalized to the DeepSeek function-name contract (64 chars, `[A-Za-z0-9_-]`); when replacement or truncation changes the name, a deterministic 12-hex-char hash of `(serverName, rawName)` is appended so distinct tools never collapse into one name. Names are pure functions of `(serverName, rawName)` — connection order, re-syncs, and other servers never rename a tool.
55
+
56
+ - Two servers publishing the same raw name (e.g. `search`) coexist under their namespaces.
57
+ - A duplicate `serverName` across live instances fails the later plugin instance at load.
58
+ - A server listing the same tool name twice is rejected as an invalid tool list.
59
+ - A foreign registration squatting on this server's namespace rolls back the whole generation (never a partial set), with a loud error.
60
+
61
+ ## Behavior
62
+
63
+ `publicToolName(serverName, rawName)` is exported for consumers that match raw MCP identities to registered tool names. Consumers must apply this same normalization instead of parsing a public name to recover the raw name.
64
+
65
+ - On connect: plugin activation awaits `listTools()` and registers each tool via `ctx.tools.register()` under its public name before the composition starts its first turn. Initial connection, discovery, or registration failure is always logged; it rejects activation when `failOnStartupError` is true and otherwise activates with no tools.
66
+ - Listens for `notifications/tools/list_changed` → re-syncs; a fetch-phase failure keeps the previous generation registered, while a registration conflict rolls back the attempted generation and leaves no tools from that server.
67
+ - Tool execute: `client.callTool({ name: rawName, arguments }, { signal })` with timeout + abort support—the public name is never sent to the server.
68
+ - Canonical success is `{ content: JsonValue[], structuredContent? }`; complete JSON MCP blocks survive for programmatic callers. A supported advertised `outputSchema` validates `structuredContent`; unsupported schema vocabulary falls back to unconstrained `JsonValue`.
69
+ - Native/model rendering preserves MCP block order. Text-like runs join with newlines; resource links keep their name and URI as text; supported images become durable core image blocks only when `ctx.attachments` is mounted and the exact calling model route explicitly declares image input. The whole image batch is decoded and admitted before any member is saved. A malformed/refused image batch, audio, embedded resources, and unsupported blocks become explicit diagnostic text rather than disappearing.
70
+ - On disconnect/crash: the supervisor restarts the original server config with exponential backoff (`reconnect.initialDelayMs` doubling up to `reconnect.maxDelayMs`) and re-runs discovery on success — the recovered generation replaces the previous one, so tools neither duplicate nor leak. During the outage the last good generation stays registered; calls against it fail until recovery.
71
+ - Reconnection is budgeted per outage: after `reconnect.maxAttempts` consecutive failures the server's tools are unregistered and reconnection stops until an HMR reload or Host restart. A connection that survives past `maxDelayMs` resets the budget, so an occasionally-crashing server recovers indefinitely while a crash-looping one — even with briefly successful connects — still exhausts the cap instead of restarting forever.
72
+ - Reconnect states are user-visible in logs: reconnecting (warn, with attempt count and delay), recovered (info), final failure and disabled-loss (error). Disposal cancels any pending reconnect. With `reconnect.enabled: false`, a lost connection keeps tools registered but failing until a reload — the manual-recovery behavior.
73
+
74
+ ## Services consumed
75
+
76
+ | Service | Usage |
77
+ |---|---|
78
+ | `ctx.tools` | Register/unregister MCP tools |
79
+ | `ctx.attachments` | Optionally validate and persist image result batches before model projection |
80
+ | `ctx.llm` | Optionally prove the exact calling route explicitly supports image input |
81
+
82
+ ## Model Experience
83
+
84
+ ### Discovered MCP tools
85
+
86
+ #### What the model sees
87
+
88
+ After initial discovery succeeds, each advertised MCP tool appears as a native tool named `mcp__<serverName>__<rawName>` (or its deterministic normalized form), with the server-provided description and input schema. A successful re-sync — including the one after an automatic reconnect — replaces the generation; plugin disposal or an exhausted reconnect budget removes it.
89
+
90
+ #### Token effect
91
+
92
+ Data-dependent schema cost is paid on every request while the tools are registered. Re-sync replaces rather than accumulates schemas, and the server-qualified name adds tokens to every tool definition and call.
93
+
94
+ #### KV Cache effect
95
+
96
+ Prefix-stable while the discovered tool set and schemas are unchanged. A re-sync that adds, removes, renames, or changes a tool replaces definitions and may invalidate reuse from the first changed schema token; a reconnect that recovers an unchanged list reproduces identical definitions and stays prefix-stable.
97
+
98
+ ### Tool-call history and results
99
+
100
+ #### What the model sees
101
+
102
+ The public tool name and JSON arguments remain in assistant history. The execution-local canonical value always retains the complete JSON MCP blocks and optional structured content for programmatic and Code Mode callers. In Native context, supported image blocks are durably projected beside text in their original order after exact route-capability proof; Code Mode additionally ferries that settled rich projection through the outer `run_code` result without changing the canonical binding value. Refused images, audio, embedded resources, resource links, and unknown blocks remain visible as bounded text diagnostics, and MCP `isError` rejects the call before image persistence.
103
+
104
+ #### Token effect
105
+
106
+ Arguments, mapped text, and durable image references are retained until compaction. Inline MCP base64 stays only in the execution-local canonical value and is never copied into a session event; the provider reads verified bytes from the attachment store. Audio and embedded-resource payloads stay out of model context.
107
+
108
+ #### KV Cache effect
109
+
110
+ Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries.
111
+
112
+ ## Known Limitations and Deferred Work
113
+
114
+ - **Tools are the only bridged MCP capability** — Resources and Prompts have no harness consumer and are deferred.
115
+ - **Startup timeout is inherited from the MCP SDK** — Hydra harness does not yet expose a connection/discovery timeout. Each initialize or paginated `tools/list` request uses the SDK's 60-second default, so an unresponsive server or cursor chain can delay both activation and teardown while the initial synchronization settles.
116
+ - **Reconnect triggers on transport close** — a crashed stdio child fires it; Streamable HTTP failures surface per request and through the SDK transport's own SSE-stream recovery, so an unreachable HTTP server is retried per call rather than respawned by the supervisor.
117
+ - **Image is the only durable rich-result bridge** — PNG, JPEG, WebP, and GIF can enter Native context after exact capability proof. Audio and embedded-resource payloads remain execution-local with explicit diagnostics, while resource links preserve only their name and URI as text.
118
+ - **Unsupported MCP output schemas are not enforced** — `structuredContent` falls back to `JsonValue` when the advertised schema uses vocabulary outside the harness subset.
package/lib/index.js ADDED
@@ -0,0 +1,797 @@
1
+ import z from "@hydraharness/schemastery";
2
+ import { MAX_TIMER_DELAY_MS } from "@hydraharness/harness-timeout";
3
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import { ListToolsResultSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
5
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
6
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
7
+ import { scrubbedParentEnv } from "@hydraharness/harness-subprocess";
8
+ import { createHash } from "node:crypto";
9
+ import { isDeepStrictEqual } from "node:util";
10
+ import { z as z$1 } from "zod";
11
+ import { isImageAdmissionError } from "@hydraharness/harness-attachment";
12
+ import { assertSupportedJsonSchema } from "@hydraharness/harness-tools";
13
+ //#region lib/types/transport.js
14
+ /**
15
+ * Transport factory: creates the appropriate MCP transport based on the
16
+ * plugin's resolved config. Stdio spawns a child process (with credential
17
+ * scrubbing); Streamable HTTP connects to a URL.
18
+ *
19
+ * @module
20
+ */
21
+ /**
22
+ * The subprocess seam's scrubbed parent env (credential-shaped and stale
23
+ * `HYDRA_*` names dropped), plus the spec's explicit env. The MCP SDK owns the
24
+ * actual spawn, so this transport shares the scrub definition rather than the
25
+ * spawn path.
26
+ */
27
+ function buildChildEnv(extra) {
28
+ return {
29
+ ...scrubbedParentEnv(),
30
+ ...extra
31
+ };
32
+ }
33
+ /** Resolve a configured bearer environment variable without exposing its value to callers. */
34
+ function httpHeaders(config) {
35
+ const headers = { ...config.headers };
36
+ const envName = config.bearerTokenEnvVar;
37
+ if (envName === void 0) return headers;
38
+ const token = process.env[envName]?.trim();
39
+ if (token === void 0 || token === "") return headers;
40
+ if (/[\u0000-\u001F\u007F]/u.test(token)) throw new Error(`mcp-client: bearer token environment variable ${envName} contains control characters`);
41
+ headers.Authorization = `Bearer ${token}`;
42
+ return headers;
43
+ }
44
+ /**
45
+ * Create an MCP transport from the resolved plugin config.
46
+ *
47
+ * @param config - Resolved plugin config discriminated on `transport`.
48
+ * @returns A connected-ready MCP Transport (stdio or Streamable HTTP).
49
+ */
50
+ function createTransport(config) {
51
+ switch (config.transport) {
52
+ case "stdio": return new StdioClientTransport({
53
+ command: config.command,
54
+ args: config.args,
55
+ env: buildChildEnv(config.env),
56
+ cwd: config.cwd
57
+ });
58
+ case "streamable-http": return new StreamableHTTPClientTransport(new URL(config.url), { requestInit: { headers: httpHeaders(config) } });
59
+ }
60
+ }
61
+ //#endregion
62
+ //#region lib/types/tools.js
63
+ /**
64
+ * Tool bridge: discovers MCP tools, registers them on the harness ToolRuntime
65
+ * under deterministic server-qualified public names, and handles re-sync when
66
+ * the server's tool list changes.
67
+ *
68
+ * Naming contract (see the mcp-client Agent Note "Naming invariants"): every MCP tool
69
+ * has the stable identity `(serverName, rawName)`; the model-facing public name
70
+ * is `mcp__<serverName>__<rawName>`, normalized to the DeepSeek function-name
71
+ * constraints. The raw name is only ever sent on the wire (`tools/call`); the
72
+ * public name is never parsed to recover it.
73
+ *
74
+ * @module
75
+ */
76
+ /**
77
+ * DeepSeek function-name contract: at most 64 characters. Wire-protocol
78
+ * constant, not configuration.
79
+ */
80
+ const MAX_PUBLIC_NAME_LENGTH = 64;
81
+ /** DeepSeek function-name contract: only `[A-Za-z0-9_-]` is allowed. */
82
+ const INVALID_NAME_CHARS = /[^A-Za-z0-9_-]/g;
83
+ /** Hex chars of the SHA-256 identity hash appended on lossy normalization. */
84
+ const HASH_LENGTH = 12;
85
+ /** Raw result record: the bridge owns JSON-value validation after transport. */
86
+ const RawCallToolResultSchema = z$1.record(z$1.string(), z$1.unknown());
87
+ /** Raster formats supported by the durable attachment vocabulary. */
88
+ const IMAGE_MEDIA_TYPES = [
89
+ "image/png",
90
+ "image/jpeg",
91
+ "image/webp",
92
+ "image/gif"
93
+ ];
94
+ /** Canonical RFC 4648 base64, excluding whitespace and URL-safe aliases. */
95
+ const CANONICAL_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
96
+ /** List without mutating the SDK's per-page output-validator cache. */
97
+ function listToolsUncached(client, cursor) {
98
+ return client.request({
99
+ method: "tools/list",
100
+ ...cursor === void 0 ? {} : { params: { cursor } }
101
+ }, ListToolsResultSchema);
102
+ }
103
+ /** Call without the SDK pre-validating an output schema the bridge may not support. */
104
+ function callToolUncached(client, rawName, args, exec, opts) {
105
+ return client.request({
106
+ method: "tools/call",
107
+ params: {
108
+ name: rawName,
109
+ arguments: args
110
+ }
111
+ }, RawCallToolResultSchema, {
112
+ signal: exec.signal,
113
+ timeout: opts.toolCallTimeoutMs
114
+ });
115
+ }
116
+ /**
117
+ * Derive the model-facing public name for one MCP tool.
118
+ *
119
+ * Deterministic pure function of `(serverName, rawName)`: the clean case is
120
+ * `mcp__<serverName>__<rawName>` verbatim. When character replacement or
121
+ * truncation to the DeepSeek function-name contract (64 chars,
122
+ * `[A-Za-z0-9_-]`) changes the name, a 12-hex-char SHA-256 hash of the
123
+ * identity is appended so distinct MCP identities never collapse into the
124
+ * same public name.
125
+ *
126
+ * @param serverName - Stable local namespace from plugin config.
127
+ * @param rawName - The MCP server's own tool name.
128
+ * @returns The globally unique, model-facing ToolRuntime name.
129
+ */
130
+ function publicToolName(serverName, rawName) {
131
+ const joined = `mcp__${serverName}__${rawName}`;
132
+ const normalized = joined.replace(INVALID_NAME_CHARS, "_");
133
+ if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH) return normalized;
134
+ const hash = createHash("sha256").update(`${serverName}\0${rawName}`).digest("hex").slice(0, HASH_LENGTH);
135
+ return `${normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1)}_${hash}`;
136
+ }
137
+ /**
138
+ * Sync the MCP server's tool list into the harness ToolRuntime.
139
+ *
140
+ * Two phases keep the swap safe:
141
+ *
142
+ * 1. Fetch: drain uncached `tools/list` pagination and build the full next
143
+ * generation of `ToolDefinition`s under public names. Any failure here
144
+ * (network error, duplicate raw name in the server's list) rejects and
145
+ * leaves the previous generation registered untouched.
146
+ * 2. Swap: dispose the previous generation, register the new one. A registry
147
+ * conflict here can only mean a foreign registration squats on this
148
+ * server's `mcp__<serverName>__` namespace — the partial generation is
149
+ * rolled back (zero tools from this server) and logged. Initial strict
150
+ * synchronization may propagate the conflict so its parent transaction
151
+ * rejects; ordinary clients and later re-syncs return an empty map.
152
+ *
153
+ * @param client - Connected MCP Client instance used to list and call tools.
154
+ * @param ctx - Cordis context providing the `tools` service for registration.
155
+ * @param opts - Bridge options: server namespace and per-call timeout.
156
+ * @param previous - Disposer map from the prior sync generation; disposed
157
+ * during the swap phase (only after the fetch phase succeeded).
158
+ * @returns A map of registered public tool names to their unregister
159
+ * disposers — the exact set of live registrations owned by this server.
160
+ */
161
+ async function syncTools(client, ctx, opts, previous) {
162
+ const definitions = /* @__PURE__ */ new Map();
163
+ let cursor;
164
+ do {
165
+ const response = await listToolsUncached(client, cursor);
166
+ for (const tool of response.tools) {
167
+ const publicName = publicToolName(opts.serverName, tool.name);
168
+ if (definitions.has(publicName)) throw new Error(`mcp-client(${opts.serverName}): server listed tool "${tool.name}" more than once — invalid tool list`);
169
+ definitions.set(publicName, createDefinition(client, ctx, publicName, tool.name, tool.description ?? "", tool.inputSchema, supportedOutputSchema(tool.outputSchema), tool.execution?.taskSupport === "required", opts));
170
+ }
171
+ cursor = response.nextCursor;
172
+ } while (cursor);
173
+ for (const dispose of previous.values()) dispose();
174
+ const disposers = /* @__PURE__ */ new Map();
175
+ try {
176
+ for (const [publicName, definition] of definitions) disposers.set(publicName, ctx.tools.register(definition));
177
+ } catch (error) {
178
+ for (const dispose of disposers.values()) dispose();
179
+ ctx.logger.error(`mcp-client(${opts.serverName}): tool registration failed, no tools registered: ${String(error)}`);
180
+ if (opts.registrationFailure === "throw") throw error;
181
+ return /* @__PURE__ */ new Map();
182
+ }
183
+ return disposers;
184
+ }
185
+ /** Keep a supported advertised schema; unsupported MCP vocabulary falls back to JsonValue. */
186
+ function supportedOutputSchema(candidate) {
187
+ if (candidate === void 0) return void 0;
188
+ try {
189
+ assertSupportedJsonSchema(candidate);
190
+ return candidate;
191
+ } catch {
192
+ return;
193
+ }
194
+ }
195
+ /**
196
+ * Build one generation-local tool definition and its execution-local rich projections.
197
+ * @param client - connected MCP client used for calls.
198
+ * @param ctx - plugin context carrying optional attachment and model services.
199
+ * @param publicName - registry-qualified public tool name.
200
+ * @param rawName - MCP wire tool name.
201
+ * @param description - model-facing tool description.
202
+ * @param parameters - MCP input schema.
203
+ * @param structuredSchema - supported structured-output schema, when advertised.
204
+ * @param taskRequired - whether this MCP tool requires unsupported task execution.
205
+ * @param opts - bridge timeout and namespace options.
206
+ * @returns a complete ToolRuntime definition.
207
+ */
208
+ function createDefinition(client, ctx, publicName, rawName, description, parameters, structuredSchema, taskRequired, opts) {
209
+ const projections = /* @__PURE__ */ new WeakMap();
210
+ return {
211
+ name: publicName,
212
+ description,
213
+ parameters,
214
+ output: createOutput(rawName, structuredSchema),
215
+ execute: createExecutor(client, ctx, rawName, taskRequired, opts, projections),
216
+ finalizeContent(exec, result) {
217
+ const projection = projections.get(exec);
218
+ if (projection === void 0) return void 0;
219
+ projections.delete(exec);
220
+ if (result.isError) return void 0;
221
+ if (!isDeepStrictEqual(result.value, projection.value)) return void 0;
222
+ if (!isDeepStrictEqual(result.content, projection.fallback)) return void 0;
223
+ return projection.content;
224
+ }
225
+ };
226
+ }
227
+ /** Build the canonical result schema and existing Native text projection. */
228
+ function createOutput(rawName, structuredSchema) {
229
+ return {
230
+ schema: {
231
+ type: "object",
232
+ properties: {
233
+ content: {
234
+ type: "array",
235
+ items: {}
236
+ },
237
+ structuredContent: structuredSchema ?? {}
238
+ },
239
+ required: structuredSchema === void 0 ? ["content"] : ["content", "structuredContent"],
240
+ additionalProperties: false
241
+ },
242
+ render(_args, value) {
243
+ return [{
244
+ type: "text",
245
+ text: extractText(value.content, rawName)
246
+ }];
247
+ }
248
+ };
249
+ }
250
+ /**
251
+ * Create an execute function for one MCP tool. The executor closes over the
252
+ * raw MCP tool name and sends an uncached `tools/call` request with it (never
253
+ * the public name), with abort signal and timeout, then maps the result to
254
+ * harness ContentBlocks. Owning the raw request prevents the SDK's internal
255
+ * per-page schema cache from pre-validating a different contract.
256
+ *
257
+ * When the MCP server returns `isError: true`, the executor throws so that
258
+ * the ToolRuntime's catch path produces an `isError` result for the model.
259
+ */
260
+ function createExecutor(client, ctx, rawName, taskRequired, opts, projections) {
261
+ return async (args, exec) => {
262
+ if (taskRequired) throw new Error(`Tool "${rawName}" requires task-based execution, which this bridge does not support`);
263
+ const result = await callToolUncached(client, rawName, typeof args === "object" && args !== null ? args : {}, exec, opts);
264
+ if (!Array.isArray(result.content)) {
265
+ const rendered = "toolResult" in result ? JSON.stringify(result.toolResult) : "(no output)";
266
+ const text = typeof rendered === "string" ? rendered : "(no output)";
267
+ if (result.isError === true) throw new Error(text);
268
+ return {
269
+ content: [{
270
+ type: "text",
271
+ text
272
+ }],
273
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}
274
+ };
275
+ }
276
+ const content = result.content;
277
+ const text = extractText(content, rawName);
278
+ if (result.isError === true) throw new Error(text);
279
+ const value = {
280
+ content,
281
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}
282
+ };
283
+ if (containsImage(content)) {
284
+ const fallback = [{
285
+ type: "text",
286
+ text: extractText(content, rawName)
287
+ }];
288
+ const projected = await prepareImageProjection(ctx, exec, content, rawName);
289
+ projections.set(exec, {
290
+ value,
291
+ fallback,
292
+ content: projected
293
+ });
294
+ }
295
+ return value;
296
+ };
297
+ }
298
+ /** Whether an untrusted MCP content array contains a declared image block. */
299
+ function containsImage(content) {
300
+ return content.some((value) => isRecord(value) && value.type === "image");
301
+ }
302
+ /** Narrow one JSON value to a string-keyed object. */
303
+ function isRecord(value) {
304
+ return typeof value === "object" && value !== null && !Array.isArray(value);
305
+ }
306
+ /** Narrow a declared MIME string to the durable image vocabulary. */
307
+ function isImageMediaType(value) {
308
+ return IMAGE_MEDIA_TYPES.includes(value);
309
+ }
310
+ /** Decode one untrusted MCP image block without accepting base64 aliases. */
311
+ function decodeImage(block) {
312
+ if (block.mimeType === void 0 || !isImageMediaType(block.mimeType)) throw new Error("the declared media type is not PNG, JPEG, WebP, or GIF");
313
+ if (block.data === void 0 || !CANONICAL_BASE64.test(block.data)) throw new Error("the image data is not canonical base64");
314
+ const data = Buffer.from(block.data, "base64");
315
+ if (data.toString("base64") !== block.data) throw new Error("the image data is not canonical base64");
316
+ return {
317
+ data,
318
+ mediaType: block.mimeType
319
+ };
320
+ }
321
+ /**
322
+ * Resolve the active model route and durable store for an image-bearing result.
323
+ * @param ctx - plugin context with optional services.
324
+ * @param exec - exact tool execution whose agent supplies the latest route.
325
+ * @returns the attachment store after exact positive image-capability proof.
326
+ */
327
+ async function resolveImageAdmission(ctx, exec) {
328
+ const attachments = ctx.get("attachments");
329
+ if (attachments === void 0) throw new Error("no attachment store is mounted");
330
+ const routed = exec.agent?.session.requestHeader()?.config;
331
+ const provider = routed?.provider ?? exec.agent?.options.provider;
332
+ const model = routed?.model ?? exec.agent?.options.model;
333
+ const llm = ctx.get("llm");
334
+ if (provider === void 0 || model === void 0 || llm === void 0) throw new Error("the current model route could not be resolved");
335
+ let info;
336
+ try {
337
+ info = await llm.resolveModelInfo(provider, model, exec.signal);
338
+ } catch {
339
+ throw new Error("the current model route could not be verified");
340
+ }
341
+ if (info.inputModalities === void 0 || !info.inputModalities.includes("image")) throw new Error(`model "${model}" does not declare image input`);
342
+ if (exec.signal.aborted) throw new Error("the tool call was canceled before image storage");
343
+ return attachments;
344
+ }
345
+ /** Stable diagnostic text for an image block that was not admitted. */
346
+ function imageDiagnostic(block, reason) {
347
+ return `[image unavailable: ${block.mimeType ?? "unknown media type"}; ${reason}; raw image data remains available to programmatic callers]`;
348
+ }
349
+ /**
350
+ * Decode, preflight, and durably save one MCP result's ordered image batch.
351
+ * Any refusal projects every image as text while retaining the canonical raw
352
+ * value for programmatic callers.
353
+ */
354
+ async function prepareImageProjection(ctx, exec, content, toolName) {
355
+ const decoded = [];
356
+ const validationErrors = /* @__PURE__ */ new Map();
357
+ const imageIndexes = [];
358
+ for (const [index, value] of content.entries()) {
359
+ if (!isRecord(value) || value.type !== "image") continue;
360
+ imageIndexes.push(index);
361
+ try {
362
+ decoded.push(decodeImage(value));
363
+ } catch (error) {
364
+ validationErrors.set(index, error.message);
365
+ }
366
+ }
367
+ if (validationErrors.size > 0) return projectContent(content, toolName, (block, index) => ({
368
+ type: "text",
369
+ text: imageDiagnostic(block, validationErrors.get(index) ?? "another image in the same result was invalid")
370
+ }));
371
+ let attachments;
372
+ try {
373
+ attachments = await resolveImageAdmission(ctx, exec);
374
+ } catch (error) {
375
+ const reason = error.message;
376
+ return projectContent(content, toolName, (block) => ({
377
+ type: "text",
378
+ text: imageDiagnostic(block, reason)
379
+ }));
380
+ }
381
+ try {
382
+ const refs = await attachments.saveImages(decoded);
383
+ const byIndex = new Map(imageIndexes.map((index, offset) => [index, refs[offset]]));
384
+ return projectContent(content, toolName, (_block, index) => ({
385
+ type: "image",
386
+ attachment: byIndex.get(index)
387
+ }));
388
+ } catch (error) {
389
+ const reason = isImageAdmissionError(error) ? `image admission rejected the result: ${error.message}` : "durable image storage rejected the result";
390
+ return projectContent(content, toolName, (block) => ({
391
+ type: "text",
392
+ text: imageDiagnostic(block, reason)
393
+ }));
394
+ }
395
+ }
396
+ /**
397
+ * Extract text from an MCP content array into a single string.
398
+ * - text blocks: join with '\n'
399
+ * - image/audio/resource blocks: replaced with a placeholder
400
+ *
401
+ * Defensive: fields that the MCP spec declares required (mimeType, text) are
402
+ * guarded with fallbacks because this is a network trust boundary.
403
+ */
404
+ function extractText(mcpContent, toolName) {
405
+ return projectContent(mcpContent, toolName).map((block) => block.text).join("\n");
406
+ }
407
+ /**
408
+ * Project ordered MCP blocks into the core content vocabulary.
409
+ * Text-like runs are newline-coalesced; admitted images split those runs at
410
+ * their original position.
411
+ */
412
+ function projectContent(mcpContent, toolName, image = (block) => ({
413
+ type: "text",
414
+ text: imageDiagnostic(block, "this result was not admitted to durable model context")
415
+ })) {
416
+ const projected = [];
417
+ const text = [];
418
+ const flushText = () => {
419
+ if (text.length === 0) return;
420
+ projected.push({
421
+ type: "text",
422
+ text: text.splice(0).join("\n")
423
+ });
424
+ };
425
+ for (const [index, value] of mcpContent.entries()) {
426
+ if (!isRecord(value)) {
427
+ text.push("[unsupported MCP content block: expected an object]");
428
+ continue;
429
+ }
430
+ const block = value;
431
+ switch (block.type) {
432
+ case "text":
433
+ if (block.text !== void 0) text.push(block.text);
434
+ break;
435
+ case "image":
436
+ flushText();
437
+ projected.push(image(block, index));
438
+ break;
439
+ case "resource_link":
440
+ if (block.name === void 0 || block.uri === void 0) text.push("[resource link unavailable: the MCP block is missing its name or URI]");
441
+ else text.push(`Resource link: ${block.name} (${block.uri})`);
442
+ break;
443
+ case "audio":
444
+ text.push(`[audio result unsupported: ${block.mimeType ?? "unknown media type"}; raw audio data remains available to programmatic callers]`);
445
+ break;
446
+ case "resource":
447
+ text.push("[embedded resource unsupported; raw resource data remains available to programmatic callers]");
448
+ break;
449
+ default: text.push(`[unsupported MCP content type: ${block.type}]`);
450
+ }
451
+ }
452
+ flushText();
453
+ return projected.length > 0 ? projected : [{
454
+ type: "text",
455
+ text: `(${toolName} returned no model-visible content)`
456
+ }];
457
+ }
458
+ //#endregion
459
+ //#region lib/types/connection.js
460
+ /**
461
+ * Connection supervisor: owns the MCP client/transport generations for one
462
+ * plugin instance, keeps the harness tool registry in sync with the live
463
+ * generation, and — when the connection drops — restarts the configured
464
+ * server with bounded exponential backoff.
465
+ *
466
+ * One outage shares one attempt budget (`maxAttempts` consecutive failed
467
+ * attempts, delays doubling from `initialDelayMs` up to `maxDelayMs`). A
468
+ * connection that stays up past the stability window closes the outage, so
469
+ * the next disconnect starts a fresh budget while a crash-looping server —
470
+ * even one whose connects briefly succeed — still exhausts the cap instead of
471
+ * restarting forever. Exhaustion unregisters the server's tools and stops;
472
+ * disposal (including HMR) is the only way back from that state.
473
+ *
474
+ * @module
475
+ */
476
+ /** Defaults shared by the Config schema and {@link resolveReconnectPolicy}. */
477
+ const RECONNECT_DEFAULTS = Object.freeze({
478
+ enabled: true,
479
+ initialDelayMs: 500,
480
+ maxDelayMs: 3e4,
481
+ maxAttempts: 10
482
+ });
483
+ const GENERATION_CLOSE_TIMEOUT_MS = 5e3;
484
+ /**
485
+ * The one explicit resolve step from raw reconnect config to the policy the
486
+ * supervisor runs. Programmatic construction may bypass Schemastery
487
+ * normalization, so every default and bound is re-judged here — misconfiguration
488
+ * fails the plugin instance at load.
489
+ *
490
+ * @param config - Raw `reconnect` config; omission uses the defaults.
491
+ * @param path - Diagnostic prefix naming the config location in thrown messages.
492
+ * @returns The frozen resolved policy.
493
+ */
494
+ function resolveReconnectPolicy(config, path) {
495
+ if (config !== void 0) {
496
+ for (const key of Object.keys(config)) if (!Object.hasOwn(RECONNECT_DEFAULTS, key)) throw new Error(`${path}.${key} is not a reconnect option`);
497
+ }
498
+ const enabled = config?.enabled ?? RECONNECT_DEFAULTS.enabled;
499
+ const initialDelayMs = config?.initialDelayMs ?? RECONNECT_DEFAULTS.initialDelayMs;
500
+ const maxDelayMs = config?.maxDelayMs ?? RECONNECT_DEFAULTS.maxDelayMs;
501
+ const maxAttempts = config?.maxAttempts ?? RECONNECT_DEFAULTS.maxAttempts;
502
+ if (!Number.isFinite(initialDelayMs) || initialDelayMs <= 0 || initialDelayMs > MAX_TIMER_DELAY_MS) throw new Error(`${path}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
503
+ if (!Number.isFinite(maxDelayMs) || maxDelayMs <= 0 || maxDelayMs > MAX_TIMER_DELAY_MS) throw new Error(`${path}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
504
+ if (initialDelayMs > maxDelayMs) throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);
505
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) throw new Error(`${path}.maxAttempts must be a positive integer`);
506
+ return Object.freeze({
507
+ enabled,
508
+ initialDelayMs,
509
+ maxDelayMs,
510
+ maxAttempts
511
+ });
512
+ }
513
+ /**
514
+ * Start the supervised connection for one MCP server and keep it alive per
515
+ * the reconnect policy.
516
+ *
517
+ * @param ctx - Cordis context providing the `tools` registry and logger.
518
+ * @param config - Resolved plugin config selecting the transport and server identity.
519
+ * @param policy - Resolved reconnect policy from {@link resolveReconnectPolicy}.
520
+ * @returns Handle with a `ready` promise for startup-await and a `dispose` for teardown.
521
+ */
522
+ function startConnection(ctx, config, policy) {
523
+ const label = `mcp-client(${config.serverName})`;
524
+ const opts = {
525
+ registrationFailure: "contain",
526
+ serverName: config.serverName,
527
+ toolCallTimeoutMs: config.toolCallTimeoutMs
528
+ };
529
+ const startupOpts = config.failOnStartupError ? {
530
+ ...opts,
531
+ registrationFailure: "throw"
532
+ } : opts;
533
+ let disposed = false;
534
+ /** Current generation: the connecting or connected client; undefined during backoff waits and after final failure. */
535
+ let client;
536
+ /** Close signal paired with {@link client}; captured by dispose before current ownership is cleared. */
537
+ let clientClosed;
538
+ /** Live tool registrations owned by this server; only {@link enqueueSync} and dispose swap it. */
539
+ let disposers = /* @__PURE__ */ new Map();
540
+ let reconnectTimer;
541
+ /** Consecutive failed connection attempts within the current outage. */
542
+ let failedAttempts = 0;
543
+ /** When the current generation finished connect + initial sync; undefined while down. */
544
+ let connectedAt;
545
+ /** The real error from the first connection attempt, for startup-await diagnostics. */
546
+ let firstAttemptError;
547
+ /** A generation may act only while it is the current one on a live plugin. */
548
+ const isCurrent = (generation) => !disposed && client === generation;
549
+ /**
550
+ * Serializes every syncTools call — initial syncs and notification re-syncs
551
+ * across all generations — so two syncs can never interleave their
552
+ * dispose-previous/register-next swap (which would double-dispose one
553
+ * generation and leak another).
554
+ */
555
+ let syncChain = Promise.resolve();
556
+ function enqueueSync(generation, syncOpts = opts) {
557
+ const run = syncChain.then(async () => {
558
+ if (!isCurrent(generation)) return;
559
+ disposers = await syncTools(generation, ctx, syncOpts, disposers);
560
+ });
561
+ syncChain = run.catch(() => {});
562
+ return run;
563
+ }
564
+ /** One disconnect decision per generation: the isCurrent guard makes racing close/error signals idempotent. */
565
+ function generationDown(generation) {
566
+ if (!isCurrent(generation)) return;
567
+ client = void 0;
568
+ clientClosed = void 0;
569
+ scheduleReconnect();
570
+ }
571
+ /** Wait for the transport-owned close signal without letting a broken transport wedge teardown forever. */
572
+ function waitForClose(closed) {
573
+ return new Promise((resolve) => {
574
+ const timeout = setTimeout(() => {
575
+ resolve(false);
576
+ }, GENERATION_CLOSE_TIMEOUT_MS);
577
+ timeout.unref();
578
+ closed.then(() => {
579
+ clearTimeout(timeout);
580
+ resolve(true);
581
+ });
582
+ });
583
+ }
584
+ function scheduleReconnect() {
585
+ const lostEstablishedConnection = connectedAt !== void 0;
586
+ if (!policy.enabled) {
587
+ const message = lostEstablishedConnection ? "connection lost and reconnect is disabled — registered tools will fail until an HMR reload or Host restart" : "connection failed and reconnect is disabled — no tools were registered; reload the plugin or restart the Host to connect";
588
+ ctx.logger.error(`${label}: ${message}`);
589
+ return;
590
+ }
591
+ if (connectedAt !== void 0 && Date.now() - connectedAt >= policy.maxDelayMs) failedAttempts = 0;
592
+ connectedAt = void 0;
593
+ failedAttempts += 1;
594
+ if (failedAttempts > policy.maxAttempts) {
595
+ syncChain = syncChain.then(() => {
596
+ for (const dispose of disposers.values()) dispose();
597
+ disposers = /* @__PURE__ */ new Map();
598
+ });
599
+ ctx.logger.error(`${label}: giving up after ${policy.maxAttempts} consecutive failed reconnect attempts — tools unregistered; reload the plugin or restart the Host to reconnect`);
600
+ return;
601
+ }
602
+ const delayMs = Math.min(policy.maxDelayMs, policy.initialDelayMs * 2 ** (failedAttempts - 1));
603
+ const action = lostEstablishedConnection ? "connection lost; reconnecting" : "connection failed; retrying";
604
+ ctx.logger.warn(`${label}: ${action} in ${delayMs}ms (attempt ${failedAttempts}/${policy.maxAttempts})`);
605
+ reconnectTimer = setTimeout(() => {
606
+ reconnectTimer = void 0;
607
+ settling = connectGeneration(false);
608
+ }, delayMs);
609
+ reconnectTimer.unref();
610
+ }
611
+ /**
612
+ * One connection attempt: fresh transport + client (the MCP SDK binds a
613
+ * Protocol to one transport for life), connect, then queue the initial tool
614
+ * sync. The startup flag belongs to the attempt rather than the shared sync
615
+ * queue, so an early notification cannot consume strict startup semantics.
616
+ * Every failure funnels through {@link generationDown}; success arms the
617
+ * onclose-driven disconnect path. Never rejects.
618
+ *
619
+ * @param startup - Whether this is the plugin's activation attempt.
620
+ */
621
+ async function connectGeneration(startup) {
622
+ const generation = new Client({
623
+ name: "hydra-mcp-client",
624
+ version: "0.0.1"
625
+ }, { capabilities: {} });
626
+ const closed = Promise.withResolvers();
627
+ let attemptSettled = false;
628
+ let closeObserved = false;
629
+ const hasClosed = () => closeObserved;
630
+ client = generation;
631
+ clientClosed = closed.promise;
632
+ generation.onclose = () => {
633
+ closeObserved = true;
634
+ closed.resolve();
635
+ if (attemptSettled) generationDown(generation);
636
+ };
637
+ generation.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
638
+ if (!isCurrent(generation)) return;
639
+ ctx.logger.info(`${label}: tool list changed, re-syncing`);
640
+ try {
641
+ await enqueueSync(generation);
642
+ } catch (error) {
643
+ if (!disposed) ctx.logger.error(`${label}: tool re-sync failed: ${String(error)}`);
644
+ }
645
+ });
646
+ try {
647
+ await generation.connect(createTransport(config));
648
+ if (hasClosed()) {
649
+ attemptSettled = true;
650
+ generationDown(generation);
651
+ return;
652
+ }
653
+ await enqueueSync(generation, startup ? startupOpts : opts);
654
+ } catch (error) {
655
+ if (firstAttemptError === void 0) firstAttemptError = error;
656
+ if (isCurrent(generation)) ctx.logger.warn(`${label}: connection attempt failed: ${String(error)}`);
657
+ try {
658
+ await generation.close();
659
+ } catch {}
660
+ const quiesced = hasClosed() || await waitForClose(closed.promise);
661
+ attemptSettled = true;
662
+ if (!isCurrent(generation)) return;
663
+ if (!quiesced) {
664
+ client = void 0;
665
+ clientClosed = void 0;
666
+ ctx.logger.error(`${label}: failed generation did not close within ${GENERATION_CLOSE_TIMEOUT_MS}ms — reconnect stopped to avoid overlapping server processes; reload the plugin or restart the Host to retry`);
667
+ return;
668
+ }
669
+ generationDown(generation);
670
+ return;
671
+ }
672
+ attemptSettled = true;
673
+ if (hasClosed()) {
674
+ generationDown(generation);
675
+ return;
676
+ }
677
+ if (!isCurrent(generation)) return;
678
+ connectedAt = Date.now();
679
+ if (failedAttempts > 0) ctx.logger.info(`${label}: reconnected and re-synced tools (attempt ${failedAttempts}/${policy.maxAttempts})`);
680
+ }
681
+ /** The in-flight (or last settled) connection attempt; dispose awaits it for quiescence. */
682
+ let settling = connectGeneration(true);
683
+ return {
684
+ ready: settling.then(() => {
685
+ if (client !== void 0) return {};
686
+ /* v8 ignore next -- defensive: firstAttemptError is always set when connect/sync fails */
687
+ return { error: firstAttemptError ?? /* @__PURE__ */ new Error(`${label}: initial connection failed`) };
688
+ }),
689
+ async dispose() {
690
+ disposed = true;
691
+ if (reconnectTimer !== void 0) {
692
+ clearTimeout(reconnectTimer);
693
+ reconnectTimer = void 0;
694
+ }
695
+ const current = client;
696
+ const currentClosed = clientClosed;
697
+ client = void 0;
698
+ clientClosed = void 0;
699
+ if (current !== void 0) {
700
+ try {
701
+ await current.close();
702
+ } catch {}
703
+ if (currentClosed !== void 0 && !await waitForClose(currentClosed)) ctx.logger.error(`${label}: generation did not close within ${GENERATION_CLOSE_TIMEOUT_MS}ms during disposal — server shutdown may be incomplete`);
704
+ }
705
+ await settling;
706
+ await syncChain;
707
+ for (const dispose of disposers.values()) dispose();
708
+ disposers = /* @__PURE__ */ new Map();
709
+ }
710
+ };
711
+ }
712
+ //#endregion
713
+ //#region lib/types/index.js
714
+ /**
715
+ * MCP client bridge plugin: connects to an external MCP server and registers
716
+ * its tools on `ctx.tools` under server-qualified public names
717
+ * (`mcp__<serverName>__<rawName>`). Each plugin instance connects to one MCP
718
+ * server; load multiple instances in `cordis.yml` for multiple servers.
719
+ *
720
+ * Namespace plugin (named exports, no default export). Lifecycle is
721
+ * effect-scoped: disposal disconnects from the server, unregisters all tools,
722
+ * and releases the `serverName` namespace reservation. HMR hot-swaps by
723
+ * disposing the old instance and creating a new one; identical `serverName`
724
+ * reproduces identical public tool names.
725
+ *
726
+ * @module @hydraharness/harness-mcp-client
727
+ */
728
+ /** Cordis plugin name used by loader diagnostics. */
729
+ const name = "mcp-client";
730
+ /** Services required by this plugin. */
731
+ const inject = ["tools"];
732
+ /** Default timeout for individual MCP tool calls (ms). */
733
+ const DEFAULT_TOOL_CALL_TIMEOUT_MS = 6e4;
734
+ /** Valid `serverName`, kept below the public tool-name budget. */
735
+ const SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
736
+ /**
737
+ * Live `serverName` reservations per app, keyed off `ctx.root` (multiple apps
738
+ * in one process — tests — must not see each other's names). A duplicate
739
+ * namespace is a configuration error surfaced at plugin load, never silent
740
+ * shadowing.
741
+ */
742
+ const activeServerNames = /* @__PURE__ */ new WeakMap();
743
+ const Reconnect = z.object({
744
+ enabled: z.boolean().default(RECONNECT_DEFAULTS.enabled),
745
+ initialDelayMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(RECONNECT_DEFAULTS.initialDelayMs),
746
+ maxDelayMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(RECONNECT_DEFAULTS.maxDelayMs),
747
+ maxAttempts: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(RECONNECT_DEFAULTS.maxAttempts)
748
+ });
749
+ const Config = z.union([z.object({
750
+ transport: z.const("stdio"),
751
+ serverName: z.string().required().pattern(SERVER_NAME_PATTERN),
752
+ command: z.string().required(),
753
+ args: z.array(String).default([]),
754
+ env: z.dict(String).default({}),
755
+ cwd: z.string().default(""),
756
+ toolCallTimeoutMs: z.number().default(DEFAULT_TOOL_CALL_TIMEOUT_MS),
757
+ failOnStartupError: z.boolean().default(false),
758
+ reconnect: Reconnect
759
+ }), z.object({
760
+ transport: z.const("streamable-http"),
761
+ serverName: z.string().required().pattern(SERVER_NAME_PATTERN),
762
+ url: z.string().required(),
763
+ headers: z.dict(String).default({}),
764
+ bearerTokenEnvVar: z.union([z.const(void 0), z.string().min(1)]),
765
+ toolCallTimeoutMs: z.number().default(DEFAULT_TOOL_CALL_TIMEOUT_MS),
766
+ failOnStartupError: z.boolean().default(false),
767
+ reconnect: Reconnect
768
+ })]);
769
+ /**
770
+ * Connect one MCP server and publish its initial tool generation before activation.
771
+ * This entry remains explicitly `async`: Cordis treats a prototype-bearing
772
+ * ordinary function as a constructor, whose returned Promise is not startup work.
773
+ * @param ctx - plugin context carrying the tool registry.
774
+ * @param config - resolved transport and server namespace configuration.
775
+ * @returns startup readiness after connection and initial tool discovery settle.
776
+ */
777
+ async function apply(ctx, config) {
778
+ const reconnect = resolveReconnectPolicy(config.reconnect, `mcp-client(${config.serverName}): reconnect`);
779
+ ctx.effect(() => {
780
+ let names = activeServerNames.get(ctx.root);
781
+ if (!names) {
782
+ names = /* @__PURE__ */ new Set();
783
+ activeServerNames.set(ctx.root, names);
784
+ }
785
+ if (names.has(config.serverName)) throw new Error(`mcp-client: serverName "${config.serverName}" is already in use by another mcp-client instance — pick a unique serverName in cordis.yml`);
786
+ names.add(config.serverName);
787
+ return () => void names.delete(config.serverName);
788
+ }, "mcp-client.serverName");
789
+ const connection = startConnection(ctx, config, reconnect);
790
+ ctx.effect(() => {
791
+ return () => connection.dispose();
792
+ }, "mcp-client.connection");
793
+ const outcome = await connection.ready;
794
+ if (outcome.error !== void 0 && config.failOnStartupError) throw new Error(`mcp-client(${config.serverName}): initial connection or tool synchronization failed`, { cause: outcome.error });
795
+ }
796
+ //#endregion
797
+ export { Config, apply, inject, name, publicToolName };
@@ -0,0 +1,23 @@
1
+ //#region lib/types/invariant.js
2
+ /**
3
+ * Package-owned invariant companion for `@hydraharness/harness-mcp-client`.
4
+ * @module @hydraharness/harness-mcp-client/invariant
5
+ */
6
+ const PACKAGE_NAME = "@hydraharness/harness-mcp-client";
7
+ /** Cordis companion plugin name. */
8
+ const name = "mcp-client-invariant";
9
+ /** Service required before the companion can reserve package ownership. */
10
+ const inject = ["invariants"];
11
+ /**
12
+ * No runtime invariant: MCP generations contribute through the tool registry, but the bridge
13
+ * exposes no independent server-to-tool snapshot after an asynchronous resync.
14
+ */
15
+ const install = () => {};
16
+ /**
17
+ * Register this package's invariant companion.
18
+ * @param ctx - Cordis context carrying the invariant service.
19
+ * @returns the installed registration's disposer after setup succeeds.
20
+ */
21
+ const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
22
+ //#endregion
23
+ export { apply, inject, name };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Connection supervisor: owns the MCP client/transport generations for one
3
+ * plugin instance, keeps the harness tool registry in sync with the live
4
+ * generation, and — when the connection drops — restarts the configured
5
+ * server with bounded exponential backoff.
6
+ *
7
+ * One outage shares one attempt budget (`maxAttempts` consecutive failed
8
+ * attempts, delays doubling from `initialDelayMs` up to `maxDelayMs`). A
9
+ * connection that stays up past the stability window closes the outage, so
10
+ * the next disconnect starts a fresh budget while a crash-looping server —
11
+ * even one whose connects briefly succeed — still exhausts the cap instead of
12
+ * restarting forever. Exhaustion unregisters the server's tools and stops;
13
+ * disposal (including HMR) is the only way back from that state.
14
+ *
15
+ * @module
16
+ */
17
+ import type { Context } from '@hydraharness/cordis';
18
+ import type { Config } from './index.ts';
19
+ /** Automatic reconnect policy for one MCP server connection. */
20
+ export interface ReconnectConfig {
21
+ /** Reconnect automatically after a lost connection (default true). */
22
+ enabled?: boolean;
23
+ /** First reconnect delay in milliseconds; doubles per consecutive failed attempt (default 500). */
24
+ initialDelayMs?: number;
25
+ /** Backoff ceiling in milliseconds; also the uptime after which the attempt budget resets (default 30000). */
26
+ maxDelayMs?: number;
27
+ /** Consecutive failed attempts per outage before giving up for good (default 10). */
28
+ maxAttempts?: number;
29
+ }
30
+ /** Defaults shared by the Config schema and {@link resolveReconnectPolicy}. */
31
+ export declare const RECONNECT_DEFAULTS: Required<ReconnectConfig>;
32
+ /** Fully resolved reconnect policy captured at plugin load. */
33
+ export type ResolvedReconnectPolicy = Readonly<Required<ReconnectConfig>>;
34
+ /**
35
+ * The one explicit resolve step from raw reconnect config to the policy the
36
+ * supervisor runs. Programmatic construction may bypass Schemastery
37
+ * normalization, so every default and bound is re-judged here — misconfiguration
38
+ * fails the plugin instance at load.
39
+ *
40
+ * @param config - Raw `reconnect` config; omission uses the defaults.
41
+ * @param path - Diagnostic prefix naming the config location in thrown messages.
42
+ * @returns The frozen resolved policy.
43
+ */
44
+ export declare function resolveReconnectPolicy(config: ReconnectConfig | undefined, path: string): ResolvedReconnectPolicy;
45
+ /** Result from the initial connection attempt, for startup-await semantics. */
46
+ export interface ConnectionOutcome {
47
+ /** If the initial connection or tool sync failed, the error; otherwise absent. */
48
+ error?: unknown;
49
+ }
50
+ /** Handle for one plugin instance's supervised connection. */
51
+ export interface ConnectionHandle {
52
+ /**
53
+ * Settles when the first connection attempt completes (success or failure).
54
+ * The supervisor enters its reconnect loop regardless; the caller decides
55
+ * whether a failed startup is fatal via `failOnStartupError`.
56
+ */
57
+ ready: Promise<ConnectionOutcome>;
58
+ /**
59
+ * Stop reconnection, close the live client, wait for the in-flight attempt
60
+ * and queued tool syncs to quiesce, then unregister every tool this server
61
+ * still owns.
62
+ */
63
+ dispose(): Promise<void>;
64
+ }
65
+ /**
66
+ * Start the supervised connection for one MCP server and keep it alive per
67
+ * the reconnect policy.
68
+ *
69
+ * @param ctx - Cordis context providing the `tools` registry and logger.
70
+ * @param config - Resolved plugin config selecting the transport and server identity.
71
+ * @param policy - Resolved reconnect policy from {@link resolveReconnectPolicy}.
72
+ * @returns Handle with a `ready` promise for startup-await and a `dispose` for teardown.
73
+ */
74
+ export declare function startConnection(ctx: Context, config: Config, policy: ResolvedReconnectPolicy): ConnectionHandle;
75
+ //# sourceMappingURL=connection.d.ts.map
@@ -0,0 +1,85 @@
1
+ /**
2
+ * MCP client bridge plugin: connects to an external MCP server and registers
3
+ * its tools on `ctx.tools` under server-qualified public names
4
+ * (`mcp__<serverName>__<rawName>`). Each plugin instance connects to one MCP
5
+ * server; load multiple instances in `cordis.yml` for multiple servers.
6
+ *
7
+ * Namespace plugin (named exports, no default export). Lifecycle is
8
+ * effect-scoped: disposal disconnects from the server, unregisters all tools,
9
+ * and releases the `serverName` namespace reservation. HMR hot-swaps by
10
+ * disposing the old instance and creating a new one; identical `serverName`
11
+ * reproduces identical public tool names.
12
+ *
13
+ * @module @hydraharness/harness-mcp-client
14
+ */
15
+ import type { Context } from '@hydraharness/cordis';
16
+ import z from '@hydraharness/schemastery';
17
+ import type { ReconnectConfig } from './connection.ts';
18
+ export type { McpResult } from './tools.ts';
19
+ export { publicToolName } from './tools.ts';
20
+ export type { ReconnectConfig, ResolvedReconnectPolicy } from './connection.ts';
21
+ /** Cordis plugin name used by loader diagnostics. */
22
+ export declare const name = "mcp-client";
23
+ /** Services required by this plugin. */
24
+ export declare const inject: string[];
25
+ /** Config for connecting to an MCP server via a spawned child process over stdio. */
26
+ export interface StdioConfig {
27
+ /** Selects child-process stdio transport. */
28
+ transport: 'stdio';
29
+ /**
30
+ * Stable local namespace for this server's model-facing tool names
31
+ * (`mcp__<serverName>__<rawName>`). Must match `[A-Za-z0-9_-]{1,32}` and be
32
+ * unique across live mcp-client instances.
33
+ */
34
+ serverName: string;
35
+ /** Executable used to start the server. */
36
+ command: string;
37
+ /** Arguments passed directly, without shell interpolation. */
38
+ args: string[];
39
+ /** Extra env vars merged on top of scrubbed ambient env. */
40
+ env: Record<string, string>;
41
+ /** Working directory for the child process. */
42
+ cwd: string;
43
+ /** Per-tool-call timeout in milliseconds. */
44
+ toolCallTimeoutMs: number;
45
+ /** Fail plugin activation when the initial connection or tool synchronization fails. */
46
+ failOnStartupError: boolean;
47
+ /** Automatic reconnect policy after a lost connection; omission uses the defaults. */
48
+ reconnect?: ReconnectConfig;
49
+ }
50
+ /** Config for connecting to an MCP server over Streamable HTTP (SSE). */
51
+ export interface StreamableHttpConfig {
52
+ /** Selects Streamable HTTP transport. */
53
+ transport: 'streamable-http';
54
+ /**
55
+ * Stable local namespace for this server's model-facing tool names
56
+ * (`mcp__<serverName>__<rawName>`). Must match `[A-Za-z0-9_-]{1,32}` and be
57
+ * unique across live mcp-client instances.
58
+ */
59
+ serverName: string;
60
+ /** MCP endpoint URL. */
61
+ url: string;
62
+ /** Additional headers attached to MCP requests. */
63
+ headers: Record<string, string>;
64
+ /** Optional environment variable resolved to a bearer token at connection time. */
65
+ bearerTokenEnvVar?: string;
66
+ /** Per-tool-call timeout in milliseconds. */
67
+ toolCallTimeoutMs: number;
68
+ /** Fail plugin activation when the initial connection or tool synchronization fails. */
69
+ failOnStartupError: boolean;
70
+ /** Automatic reconnect policy after a lost connection; omission uses the defaults. */
71
+ reconnect?: ReconnectConfig;
72
+ }
73
+ /** Configuration for one stdio or Streamable HTTP MCP server. */
74
+ export type Config = StdioConfig | StreamableHttpConfig;
75
+ export declare const Config: z<Config>;
76
+ /**
77
+ * Connect one MCP server and publish its initial tool generation before activation.
78
+ * This entry remains explicitly `async`: Cordis treats a prototype-bearing
79
+ * ordinary function as a constructor, whose returned Promise is not startup work.
80
+ * @param ctx - plugin context carrying the tool registry.
81
+ * @param config - resolved transport and server namespace configuration.
82
+ * @returns startup readiness after connection and initial tool discovery settle.
83
+ */
84
+ export declare function apply(ctx: Context, config: Config): Promise<void>;
85
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Package-owned invariant companion for `@hydraharness/harness-mcp-client`.
3
+ * @module @hydraharness/harness-mcp-client/invariant
4
+ */
5
+ import type { Context } from '@hydraharness/cordis';
6
+ /** Cordis companion plugin name. */
7
+ export declare const name = "mcp-client-invariant";
8
+ /** Service required before the companion can reserve package ownership. */
9
+ export declare const inject: string[];
10
+ /**
11
+ * Register this package's invariant companion.
12
+ * @param ctx - Cordis context carrying the invariant service.
13
+ * @returns the installed registration's disposer after setup succeeds.
14
+ */
15
+ export declare const apply: (ctx: Context) => Promise<() => void>;
16
+ //# sourceMappingURL=invariant.d.ts.map
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Tool bridge: discovers MCP tools, registers them on the harness ToolRuntime
3
+ * under deterministic server-qualified public names, and handles re-sync when
4
+ * the server's tool list changes.
5
+ *
6
+ * Naming contract (see the mcp-client Agent Note "Naming invariants"): every MCP tool
7
+ * has the stable identity `(serverName, rawName)`; the model-facing public name
8
+ * is `mcp__<serverName>__<rawName>`, normalized to the DeepSeek function-name
9
+ * constraints. The raw name is only ever sent on the wire (`tools/call`); the
10
+ * public name is never parsed to recover it.
11
+ *
12
+ * @module
13
+ */
14
+ import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
15
+ import type { Context } from '@hydraharness/cordis';
16
+ import type { JsonValue } from '@hydraharness/harness-tools';
17
+ /** Resolved options relevant to tool bridging. */
18
+ export interface ToolBridgeOptions {
19
+ /** Whether a registry conflict is contained or rejects this synchronization. */
20
+ registrationFailure: 'contain' | 'throw';
21
+ serverName: string;
22
+ toolCallTimeoutMs: number;
23
+ }
24
+ /** State for one sync generation: the current set of disposers keyed by public name. */
25
+ export type ToolDisposers = Map<string, () => void>;
26
+ /** Canonical MCP result exposed to Code Mode without discarding protocol blocks. */
27
+ export type McpResult<Structured extends JsonValue = JsonValue> = {
28
+ content: JsonValue[];
29
+ structuredContent?: Structured;
30
+ };
31
+ /**
32
+ * Derive the model-facing public name for one MCP tool.
33
+ *
34
+ * Deterministic pure function of `(serverName, rawName)`: the clean case is
35
+ * `mcp__<serverName>__<rawName>` verbatim. When character replacement or
36
+ * truncation to the DeepSeek function-name contract (64 chars,
37
+ * `[A-Za-z0-9_-]`) changes the name, a 12-hex-char SHA-256 hash of the
38
+ * identity is appended so distinct MCP identities never collapse into the
39
+ * same public name.
40
+ *
41
+ * @param serverName - Stable local namespace from plugin config.
42
+ * @param rawName - The MCP server's own tool name.
43
+ * @returns The globally unique, model-facing ToolRuntime name.
44
+ */
45
+ export declare function publicToolName(serverName: string, rawName: string): string;
46
+ /**
47
+ * Sync the MCP server's tool list into the harness ToolRuntime.
48
+ *
49
+ * Two phases keep the swap safe:
50
+ *
51
+ * 1. Fetch: drain uncached `tools/list` pagination and build the full next
52
+ * generation of `ToolDefinition`s under public names. Any failure here
53
+ * (network error, duplicate raw name in the server's list) rejects and
54
+ * leaves the previous generation registered untouched.
55
+ * 2. Swap: dispose the previous generation, register the new one. A registry
56
+ * conflict here can only mean a foreign registration squats on this
57
+ * server's `mcp__<serverName>__` namespace — the partial generation is
58
+ * rolled back (zero tools from this server) and logged. Initial strict
59
+ * synchronization may propagate the conflict so its parent transaction
60
+ * rejects; ordinary clients and later re-syncs return an empty map.
61
+ *
62
+ * @param client - Connected MCP Client instance used to list and call tools.
63
+ * @param ctx - Cordis context providing the `tools` service for registration.
64
+ * @param opts - Bridge options: server namespace and per-call timeout.
65
+ * @param previous - Disposer map from the prior sync generation; disposed
66
+ * during the swap phase (only after the fetch phase succeeded).
67
+ * @returns A map of registered public tool names to their unregister
68
+ * disposers — the exact set of live registrations owned by this server.
69
+ */
70
+ export declare function syncTools(client: Client, ctx: Context, opts: ToolBridgeOptions, previous: ToolDisposers): Promise<ToolDisposers>;
71
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Transport factory: creates the appropriate MCP transport based on the
3
+ * plugin's resolved config. Stdio spawns a child process (with credential
4
+ * scrubbing); Streamable HTTP connects to a URL.
5
+ *
6
+ * @module
7
+ */
8
+ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
9
+ import type { Config } from './index.ts';
10
+ /**
11
+ * Create an MCP transport from the resolved plugin config.
12
+ *
13
+ * @param config - Resolved plugin config discriminated on `transport`.
14
+ * @returns A connected-ready MCP Transport (stdio or Streamable HTTP).
15
+ */
16
+ export declare function createTransport(config: Config): Transport;
17
+ //# sourceMappingURL=transport.d.ts.map
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@hydraharness/harness-mcp-client",
3
+ "description": "MCP client bridge: connects to MCP servers and registers their tools on ctx.tools",
4
+ "version": "0.1.1-rc.5",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/MaiHongPhong1902/Hydra-Harness.git",
11
+ "directory": "packages/mcp/mcp-client"
12
+ },
13
+ "type": "module",
14
+ "main": "lib/index.js",
15
+ "types": "lib/types/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/types/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./invariant": {
22
+ "types": "./lib/types/invariant.d.ts",
23
+ "default": "./lib/invariant.js"
24
+ },
25
+ "./src/*": "./src/*",
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "lib/index.js",
30
+ "lib/invariant.js",
31
+ "lib/types/**/*.d.ts"
32
+ ],
33
+ "license": "MIT",
34
+ "peerDependencies": {
35
+ "@hydraharness/harness-attachment": "^0.1.1-rc.5",
36
+ "@hydraharness/harness-subprocess": "^0.1.1-rc.5",
37
+ "@hydraharness/harness-llm": "^0.1.1-rc.5",
38
+ "@hydraharness/harness-invariants": "^0.1.1-rc.5",
39
+ "@hydraharness/harness-timeout": "^0.1.1-rc.5",
40
+ "@hydraharness/harness-tools": "^0.1.1-rc.5",
41
+ "@hydraharness/cordis": "^4.0.2"
42
+ },
43
+ "dependencies": {
44
+ "@modelcontextprotocol/sdk": "^1.12.0",
45
+ "zod": "^4.4.3",
46
+ "@hydraharness/schemastery": "^3.18.2"
47
+ },
48
+ "devDependencies": {
49
+ "@modelcontextprotocol/server-everything": "^2026.7.4",
50
+ "@modelcontextprotocol/server-filesystem": "^2026.7.4",
51
+ "@hydraharness/harness-attachment-local": "^0.1.1-rc.5",
52
+ "@hydraharness/harness-invariants": "^0.1.1-rc.5",
53
+ "@hydraharness/harness-attachment": "^0.1.1-rc.5",
54
+ "@hydraharness/harness-llm": "^0.1.1-rc.5",
55
+ "@hydraharness/harness-subprocess": "^0.1.1-rc.5",
56
+ "@hydraharness/harness-timeout": "^0.1.1-rc.5",
57
+ "@hydraharness/harness-tools": "^0.1.1-rc.5",
58
+ "@hydraharness/cordis": "^4.0.2"
59
+ }
60
+ }