@crazx/dsh-mcp-client 0.1.0-rc.7.zw.2

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/lib/index.js ADDED
@@ -0,0 +1,829 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { MAX_TIMER_DELAY_MS } from "@deepseek-ai/dsh-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 "@deepseek-ai/dsh-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 "@deepseek-ai/dsh-attachment";
12
+ import { assertSupportedJsonSchema } from "@deepseek-ai/dsh-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
+ * `DSH_*` 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
+ /**
34
+ * Create an MCP transport from the resolved plugin config.
35
+ *
36
+ * @param config - Resolved plugin config discriminated on `transport`.
37
+ * @returns A connected-ready MCP Transport (stdio or Streamable HTTP).
38
+ */
39
+ function createTransport(config) {
40
+ switch (config.transport) {
41
+ case "stdio": return new StdioClientTransport({
42
+ command: config.command,
43
+ args: config.args,
44
+ env: buildChildEnv(config.env),
45
+ cwd: config.cwd
46
+ });
47
+ case "streamable-http": return new StreamableHTTPClientTransport(new URL(config.url), { requestInit: { headers: config.headers } });
48
+ }
49
+ }
50
+ //#endregion
51
+ //#region lib/types/tools.js
52
+ /**
53
+ * Tool bridge: discovers MCP tools, registers them on the harness ToolRuntime
54
+ * under deterministic server-qualified public names, and handles re-sync when
55
+ * the server's tool list changes.
56
+ *
57
+ * Naming contract (see the mcp-client Agent Note "Naming invariants"): every MCP tool
58
+ * has the stable identity `(serverName, rawName)`; the model-facing public name
59
+ * is `mcp__<serverName>__<rawName>`, normalized to the DeepSeek function-name
60
+ * constraints. The raw name is only ever sent on the wire (`tools/call`); the
61
+ * public name is never parsed to recover it.
62
+ *
63
+ * @module
64
+ */
65
+ /**
66
+ * DeepSeek function-name contract: at most 64 characters. Wire-protocol
67
+ * constant, not configuration.
68
+ */
69
+ const MAX_PUBLIC_NAME_LENGTH = 64;
70
+ /** DeepSeek function-name contract: only `[A-Za-z0-9_-]` is allowed. */
71
+ const INVALID_NAME_CHARS = /[^A-Za-z0-9_-]/g;
72
+ /** Hex chars of the SHA-256 identity hash appended on lossy normalization. */
73
+ const HASH_LENGTH = 12;
74
+ /** Raw result record: the bridge owns JSON-value validation after transport. */
75
+ const RawCallToolResultSchema = z$1.record(z$1.string(), z$1.unknown());
76
+ /** Raster formats supported by the durable attachment vocabulary. */
77
+ const IMAGE_MEDIA_TYPES = [
78
+ "image/png",
79
+ "image/jpeg",
80
+ "image/webp",
81
+ "image/gif"
82
+ ];
83
+ /** Canonical RFC 4648 base64, excluding whitespace and URL-safe aliases. */
84
+ const CANONICAL_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
85
+ /** List without mutating the SDK's per-page output-validator cache. */
86
+ function listToolsUncached(client, cursor) {
87
+ return client.request({
88
+ method: "tools/list",
89
+ ...cursor === void 0 ? {} : { params: { cursor } }
90
+ }, ListToolsResultSchema);
91
+ }
92
+ /** Call without the SDK pre-validating an output schema the bridge may not support. */
93
+ function callToolUncached(client, rawName, args, exec, opts) {
94
+ return client.request({
95
+ method: "tools/call",
96
+ params: {
97
+ name: rawName,
98
+ arguments: args
99
+ }
100
+ }, RawCallToolResultSchema, {
101
+ signal: exec.signal,
102
+ timeout: opts.toolCallTimeoutMs
103
+ });
104
+ }
105
+ /**
106
+ * Derive the model-facing public name for one MCP tool.
107
+ *
108
+ * Deterministic pure function of `(serverName, rawName)`: the clean case is
109
+ * `mcp__<serverName>__<rawName>` verbatim. When character replacement or
110
+ * truncation to the DeepSeek function-name contract (64 chars,
111
+ * `[A-Za-z0-9_-]`) changes the name, a 12-hex-char SHA-256 hash of the
112
+ * identity is appended so distinct MCP identities never collapse into the
113
+ * same public name.
114
+ *
115
+ * @param serverName - Stable local namespace from plugin config.
116
+ * @param rawName - The MCP server's own tool name.
117
+ * @returns The globally unique, model-facing ToolRuntime name.
118
+ */
119
+ function publicToolName(serverName, rawName) {
120
+ const joined = `mcp__${serverName}__${rawName}`;
121
+ const normalized = joined.replace(INVALID_NAME_CHARS, "_");
122
+ if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH) return normalized;
123
+ const hash = createHash("sha256").update(`${serverName}\0${rawName}`).digest("hex").slice(0, HASH_LENGTH);
124
+ return `${normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1)}_${hash}`;
125
+ }
126
+ /**
127
+ * Sync the MCP server's tool list into the harness ToolRuntime.
128
+ *
129
+ * Two phases keep the swap safe:
130
+ *
131
+ * 1. Fetch: drain uncached `tools/list` pagination and build the full next
132
+ * generation of `ToolDefinition`s under public names. Any failure here
133
+ * (network error, duplicate raw name in the server's list) rejects and
134
+ * leaves the previous generation registered untouched.
135
+ * 2. Swap: dispose the previous generation, register the new one. A registry
136
+ * conflict here can only mean a foreign registration squats on this
137
+ * server's `mcp__<serverName>__` namespace — the partial generation is
138
+ * rolled back (zero tools from this server) and logged. Initial strict
139
+ * synchronization may propagate the conflict so its parent transaction
140
+ * rejects; ordinary clients and later re-syncs return an empty map.
141
+ *
142
+ * @param client - Connected MCP Client instance used to list and call tools.
143
+ * @param ctx - Cordis context providing the `tools` service for registration.
144
+ * @param opts - Bridge options: server namespace and per-call timeout.
145
+ * @param previous - Disposer map from the prior sync generation; disposed
146
+ * during the swap phase (only after the fetch phase succeeded).
147
+ * @returns A map of registered public tool names to their unregister
148
+ * disposers — the exact set of live registrations owned by this server.
149
+ */
150
+ async function syncTools(client, ctx, opts, previous) {
151
+ const definitions = /* @__PURE__ */ new Map();
152
+ let cursor;
153
+ do {
154
+ const response = await listToolsUncached(client, cursor);
155
+ for (const tool of response.tools) {
156
+ const publicName = publicToolName(opts.serverName, tool.name);
157
+ if (definitions.has(publicName)) throw new Error(`mcp-client(${opts.serverName}): server listed tool "${tool.name}" more than once — invalid tool list`);
158
+ definitions.set(publicName, createDefinition(client, ctx, publicName, tool.name, tool.description ?? "", tool.inputSchema, supportedOutputSchema(tool.outputSchema), tool.execution?.taskSupport === "required", opts));
159
+ }
160
+ cursor = response.nextCursor;
161
+ } while (cursor);
162
+ for (const dispose of previous.values()) dispose();
163
+ const disposers = /* @__PURE__ */ new Map();
164
+ try {
165
+ for (const [publicName, definition] of definitions) disposers.set(publicName, ctx.tools.register(definition));
166
+ } catch (error) {
167
+ for (const dispose of disposers.values()) dispose();
168
+ ctx.logger.error(`mcp-client(${opts.serverName}): tool registration failed, no tools registered: ${String(error)}`);
169
+ if (opts.registrationFailure === "throw") throw error;
170
+ return /* @__PURE__ */ new Map();
171
+ }
172
+ return disposers;
173
+ }
174
+ /** Keep a supported advertised schema; unsupported MCP vocabulary falls back to JsonValue. */
175
+ function supportedOutputSchema(candidate) {
176
+ if (candidate === void 0) return void 0;
177
+ try {
178
+ assertSupportedJsonSchema(candidate);
179
+ return candidate;
180
+ } catch {
181
+ return;
182
+ }
183
+ }
184
+ /**
185
+ * Build one generation-local tool definition and its execution-local rich projections.
186
+ * @param client - connected MCP client used for calls.
187
+ * @param ctx - plugin context carrying optional attachment and model services.
188
+ * @param publicName - registry-qualified public tool name.
189
+ * @param rawName - MCP wire tool name.
190
+ * @param description - model-facing tool description.
191
+ * @param parameters - MCP input schema.
192
+ * @param structuredSchema - supported structured-output schema, when advertised.
193
+ * @param taskRequired - whether this MCP tool requires unsupported task execution.
194
+ * @param opts - bridge timeout and namespace options.
195
+ * @returns a complete ToolRuntime definition.
196
+ */
197
+ function createDefinition(client, ctx, publicName, rawName, description, parameters, structuredSchema, taskRequired, opts) {
198
+ const projections = /* @__PURE__ */ new WeakMap();
199
+ return {
200
+ name: publicName,
201
+ description,
202
+ parameters,
203
+ output: createOutput(rawName, structuredSchema),
204
+ execute: createExecutor(client, ctx, rawName, taskRequired, opts, projections),
205
+ finalizeContent(exec, result) {
206
+ const projection = projections.get(exec);
207
+ if (projection === void 0) return void 0;
208
+ projections.delete(exec);
209
+ if (result.isError) return void 0;
210
+ if (!isDeepStrictEqual(result.value, projection.value)) return void 0;
211
+ if (!isDeepStrictEqual(result.content, projection.fallback)) return void 0;
212
+ return projection.content;
213
+ }
214
+ };
215
+ }
216
+ /** Build the canonical result schema and existing Native text projection. */
217
+ function createOutput(rawName, structuredSchema) {
218
+ return {
219
+ schema: {
220
+ type: "object",
221
+ properties: {
222
+ content: {
223
+ type: "array",
224
+ items: {}
225
+ },
226
+ structuredContent: structuredSchema ?? {}
227
+ },
228
+ required: structuredSchema === void 0 ? ["content"] : ["content", "structuredContent"],
229
+ additionalProperties: false
230
+ },
231
+ render(_args, value) {
232
+ return [{
233
+ type: "text",
234
+ text: extractText(value.content, rawName)
235
+ }];
236
+ }
237
+ };
238
+ }
239
+ /**
240
+ * Create an execute function for one MCP tool. The executor closes over the
241
+ * raw MCP tool name and sends an uncached `tools/call` request with it (never
242
+ * the public name), with abort signal and timeout, then maps the result to
243
+ * harness ContentBlocks. Owning the raw request prevents the SDK's internal
244
+ * per-page schema cache from pre-validating a different contract.
245
+ *
246
+ * When the MCP server returns `isError: true`, the executor throws so that
247
+ * the ToolRuntime's catch path produces an `isError` result for the model.
248
+ */
249
+ function createExecutor(client, ctx, rawName, taskRequired, opts, projections) {
250
+ return async (args, exec) => {
251
+ if (taskRequired) throw new Error(`Tool "${rawName}" requires task-based execution, which this bridge does not support`);
252
+ const result = await callToolUncached(client, rawName, typeof args === "object" && args !== null ? args : {}, exec, opts);
253
+ if (!Array.isArray(result.content)) {
254
+ const rendered = "toolResult" in result ? JSON.stringify(result.toolResult) : "(no output)";
255
+ const text = typeof rendered === "string" ? rendered : "(no output)";
256
+ if (result.isError === true) throw new Error(text);
257
+ return {
258
+ content: [{
259
+ type: "text",
260
+ text
261
+ }],
262
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}
263
+ };
264
+ }
265
+ const content = result.content;
266
+ const text = extractText(content, rawName);
267
+ if (result.isError === true) throw new Error(text);
268
+ const value = {
269
+ content,
270
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}
271
+ };
272
+ if (containsImage(content)) {
273
+ const fallback = [{
274
+ type: "text",
275
+ text: extractText(content, rawName)
276
+ }];
277
+ const projected = await prepareImageProjection(ctx, exec, content, rawName);
278
+ projections.set(exec, {
279
+ value,
280
+ fallback,
281
+ content: projected
282
+ });
283
+ }
284
+ return value;
285
+ };
286
+ }
287
+ /** Whether an untrusted MCP content array contains a declared image block. */
288
+ function containsImage(content) {
289
+ return content.some((value) => isRecord(value) && value.type === "image");
290
+ }
291
+ /** Narrow one JSON value to a string-keyed object. */
292
+ function isRecord(value) {
293
+ return typeof value === "object" && value !== null && !Array.isArray(value);
294
+ }
295
+ /** Narrow a declared MIME string to the durable image vocabulary. */
296
+ function isImageMediaType(value) {
297
+ return IMAGE_MEDIA_TYPES.includes(value);
298
+ }
299
+ /** Decode one untrusted MCP image block without accepting base64 aliases. */
300
+ function decodeImage(block) {
301
+ if (block.mimeType === void 0 || !isImageMediaType(block.mimeType)) throw new Error("the declared media type is not PNG, JPEG, WebP, or GIF");
302
+ if (block.data === void 0 || !CANONICAL_BASE64.test(block.data)) throw new Error("the image data is not canonical base64");
303
+ const data = Buffer.from(block.data, "base64");
304
+ if (data.toString("base64") !== block.data) throw new Error("the image data is not canonical base64");
305
+ return {
306
+ data,
307
+ mediaType: block.mimeType
308
+ };
309
+ }
310
+ /**
311
+ * Resolve the active model route and durable store for an image-bearing result.
312
+ * @param ctx - plugin context with optional services.
313
+ * @param exec - exact tool execution whose agent supplies the latest route.
314
+ * @returns the attachment store after exact positive image-capability proof.
315
+ */
316
+ async function resolveImageAdmission(ctx, exec) {
317
+ const attachments = ctx.get("attachments");
318
+ if (attachments === void 0) throw new Error("no attachment store is mounted");
319
+ const routed = exec.agent?.session.requestHeader()?.config;
320
+ const provider = routed?.provider ?? exec.agent?.options.provider;
321
+ const model = routed?.model ?? exec.agent?.options.model;
322
+ const llm = ctx.get("llm");
323
+ if (provider === void 0 || model === void 0 || llm === void 0) throw new Error("the current model route could not be resolved");
324
+ let info;
325
+ try {
326
+ info = await llm.resolveModelInfo(provider, model, exec.signal);
327
+ } catch {
328
+ throw new Error("the current model route could not be verified");
329
+ }
330
+ if (info.inputModalities === void 0 || !info.inputModalities.includes("image")) throw new Error(`model "${model}" does not declare image input`);
331
+ if (exec.signal.aborted) throw new Error("the tool call was canceled before image storage");
332
+ return attachments;
333
+ }
334
+ /** Stable diagnostic text for an image block that was not admitted. */
335
+ function imageDiagnostic(block, reason) {
336
+ return `[image unavailable: ${block.mimeType ?? "unknown media type"}; ${reason}; raw image data remains available to programmatic callers]`;
337
+ }
338
+ /**
339
+ * Decode, preflight, and durably save one MCP result's ordered image batch.
340
+ * Any refusal projects every image as text while retaining the canonical raw
341
+ * value for programmatic callers.
342
+ */
343
+ async function prepareImageProjection(ctx, exec, content, toolName) {
344
+ const decoded = [];
345
+ const validationErrors = /* @__PURE__ */ new Map();
346
+ const imageIndexes = [];
347
+ for (const [index, value] of content.entries()) {
348
+ if (!isRecord(value) || value.type !== "image") continue;
349
+ imageIndexes.push(index);
350
+ try {
351
+ decoded.push(decodeImage(value));
352
+ } catch (error) {
353
+ validationErrors.set(index, error.message);
354
+ }
355
+ }
356
+ if (validationErrors.size > 0) return projectContent(content, toolName, (block, index) => ({
357
+ type: "text",
358
+ text: imageDiagnostic(block, validationErrors.get(index) ?? "another image in the same result was invalid")
359
+ }));
360
+ let attachments;
361
+ try {
362
+ attachments = await resolveImageAdmission(ctx, exec);
363
+ } catch (error) {
364
+ const reason = error.message;
365
+ return projectContent(content, toolName, (block) => ({
366
+ type: "text",
367
+ text: imageDiagnostic(block, reason)
368
+ }));
369
+ }
370
+ try {
371
+ const refs = await attachments.saveImages(decoded);
372
+ const byIndex = new Map(imageIndexes.map((index, offset) => [index, refs[offset]]));
373
+ return projectContent(content, toolName, (_block, index) => ({
374
+ type: "image",
375
+ attachment: byIndex.get(index)
376
+ }));
377
+ } catch (error) {
378
+ const reason = isImageAdmissionError(error) ? `image admission rejected the result: ${error.message}` : "durable image storage rejected the result";
379
+ return projectContent(content, toolName, (block) => ({
380
+ type: "text",
381
+ text: imageDiagnostic(block, reason)
382
+ }));
383
+ }
384
+ }
385
+ /**
386
+ * Extract text from an MCP content array into a single string.
387
+ * - text blocks: join with '\n'
388
+ * - image/audio/resource blocks: replaced with a placeholder
389
+ *
390
+ * Defensive: fields that the MCP spec declares required (mimeType, text) are
391
+ * guarded with fallbacks because this is a network trust boundary.
392
+ */
393
+ function extractText(mcpContent, toolName) {
394
+ return projectContent(mcpContent, toolName).map((block) => block.text).join("\n");
395
+ }
396
+ /**
397
+ * Project ordered MCP blocks into the core content vocabulary.
398
+ * Text-like runs are newline-coalesced; admitted images split those runs at
399
+ * their original position.
400
+ */
401
+ function projectContent(mcpContent, toolName, image = (block) => ({
402
+ type: "text",
403
+ text: imageDiagnostic(block, "this result was not admitted to durable model context")
404
+ })) {
405
+ const projected = [];
406
+ const text = [];
407
+ const flushText = () => {
408
+ if (text.length === 0) return;
409
+ projected.push({
410
+ type: "text",
411
+ text: text.splice(0).join("\n")
412
+ });
413
+ };
414
+ for (const [index, value] of mcpContent.entries()) {
415
+ if (!isRecord(value)) {
416
+ text.push("[unsupported MCP content block: expected an object]");
417
+ continue;
418
+ }
419
+ const block = value;
420
+ switch (block.type) {
421
+ case "text":
422
+ if (block.text !== void 0) text.push(block.text);
423
+ break;
424
+ case "image":
425
+ flushText();
426
+ projected.push(image(block, index));
427
+ break;
428
+ case "resource_link":
429
+ if (block.name === void 0 || block.uri === void 0) text.push("[resource link unavailable: the MCP block is missing its name or URI]");
430
+ else text.push(`Resource link: ${block.name} (${block.uri})`);
431
+ break;
432
+ case "audio":
433
+ text.push(`[audio result unsupported: ${block.mimeType ?? "unknown media type"}; raw audio data remains available to programmatic callers]`);
434
+ break;
435
+ case "resource":
436
+ text.push("[embedded resource unsupported; raw resource data remains available to programmatic callers]");
437
+ break;
438
+ default: text.push(`[unsupported MCP content type: ${block.type}]`);
439
+ }
440
+ }
441
+ flushText();
442
+ return projected.length > 0 ? projected : [{
443
+ type: "text",
444
+ text: `(${toolName} returned no model-visible content)`
445
+ }];
446
+ }
447
+ //#endregion
448
+ //#region lib/types/connection.js
449
+ /**
450
+ * Connection supervisor: owns the MCP client/transport generations for one
451
+ * plugin instance, keeps the harness tool registry in sync with the live
452
+ * generation, and — when the connection drops — restarts the configured
453
+ * server with bounded exponential backoff.
454
+ *
455
+ * One outage shares one attempt budget (`maxAttempts` consecutive failed
456
+ * attempts, delays doubling from `initialDelayMs` up to `maxDelayMs`). A
457
+ * connection that stays up past the stability window closes the outage, so
458
+ * the next disconnect starts a fresh budget while a crash-looping server —
459
+ * even one whose connects briefly succeed — still exhausts the cap instead of
460
+ * restarting forever. Exhaustion unregisters the server's tools and stops;
461
+ * disposal (including HMR) is the only way back from that state.
462
+ *
463
+ * @module
464
+ */
465
+ /** Defaults shared by the Config schema and {@link resolveReconnectPolicy}. */
466
+ const RECONNECT_DEFAULTS = Object.freeze({
467
+ enabled: true,
468
+ initialDelayMs: 500,
469
+ maxDelayMs: 3e4,
470
+ maxAttempts: 10
471
+ });
472
+ const GENERATION_CLOSE_TIMEOUT_MS = 5e3;
473
+ /**
474
+ * The one explicit resolve step from raw reconnect config to the policy the
475
+ * supervisor runs. Programmatic construction may bypass Schemastery
476
+ * normalization, so every default and bound is re-judged here — misconfiguration
477
+ * fails the plugin instance at load.
478
+ *
479
+ * @param config - Raw `reconnect` config; omission uses the defaults.
480
+ * @param path - Diagnostic prefix naming the config location in thrown messages.
481
+ * @returns The frozen resolved policy.
482
+ */
483
+ function resolveReconnectPolicy(config, path) {
484
+ if (config !== void 0) {
485
+ for (const key of Object.keys(config)) if (!Object.hasOwn(RECONNECT_DEFAULTS, key)) throw new Error(`${path}.${key} is not a reconnect option`);
486
+ }
487
+ const enabled = config?.enabled ?? RECONNECT_DEFAULTS.enabled;
488
+ const initialDelayMs = config?.initialDelayMs ?? RECONNECT_DEFAULTS.initialDelayMs;
489
+ const maxDelayMs = config?.maxDelayMs ?? RECONNECT_DEFAULTS.maxDelayMs;
490
+ const maxAttempts = config?.maxAttempts ?? RECONNECT_DEFAULTS.maxAttempts;
491
+ 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}`);
492
+ 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}`);
493
+ if (initialDelayMs > maxDelayMs) throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);
494
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) throw new Error(`${path}.maxAttempts must be a positive integer`);
495
+ return Object.freeze({
496
+ enabled,
497
+ initialDelayMs,
498
+ maxDelayMs,
499
+ maxAttempts
500
+ });
501
+ }
502
+ /**
503
+ * Derive the observable connection status from supervisor state facts.
504
+ *
505
+ * Evaluation order is load-bearing: `failed` is judged before `reconnecting`
506
+ * because a give-up leaves `failedAttempts` above zero with no client and no
507
+ * timer, and `connected` is judged before the in-flight branches because the
508
+ * outage budget resets from that mark.
509
+ *
510
+ * @param facts - the supervisor's current state facts.
511
+ * @returns the committed status those facts represent.
512
+ */
513
+ function computeMcpClientStatus(facts) {
514
+ if (facts.disposed) return "disposed";
515
+ if (!facts.hasClient && !facts.hasTimer) return "failed";
516
+ if (facts.connected) return "connected";
517
+ if (facts.hasTimer) return "reconnecting";
518
+ return facts.failedAttempts === 0 ? "connecting" : "reconnecting";
519
+ }
520
+ /**
521
+ * Start the supervised connection for one MCP server and keep it alive per
522
+ * the reconnect policy.
523
+ *
524
+ * @param ctx - Cordis context providing the `tools` registry and logger.
525
+ * @param config - Resolved plugin config selecting the transport and server identity.
526
+ * @param policy - Resolved reconnect policy from {@link resolveReconnectPolicy}.
527
+ * @returns Handle with a `ready` promise for startup-await and a `dispose` for teardown.
528
+ */
529
+ function startConnection(ctx, config, policy) {
530
+ const label = `mcp-client(${config.serverName})`;
531
+ const opts = {
532
+ registrationFailure: "contain",
533
+ serverName: config.serverName,
534
+ toolCallTimeoutMs: config.toolCallTimeoutMs
535
+ };
536
+ const startupOpts = config.failOnStartupError ? {
537
+ ...opts,
538
+ registrationFailure: "throw"
539
+ } : opts;
540
+ let disposed = false;
541
+ /** Current generation: the connecting or connected client; undefined during backoff waits and after final failure. */
542
+ let client;
543
+ /** Close signal paired with {@link client}; captured by dispose before current ownership is cleared. */
544
+ let clientClosed;
545
+ /** Live tool registrations owned by this server; only {@link enqueueSync} and dispose swap it. */
546
+ let disposers = /* @__PURE__ */ new Map();
547
+ let reconnectTimer;
548
+ /** Consecutive failed connection attempts within the current outage. */
549
+ let failedAttempts = 0;
550
+ /** When the current generation finished connect + initial sync; undefined while down. */
551
+ let connectedAt;
552
+ /** The real error from the first connection attempt, for startup-await diagnostics. */
553
+ let firstAttemptError;
554
+ /** Snapshot the supervisor facts the status projection reads. */
555
+ const facts = () => ({
556
+ disposed,
557
+ hasClient: client !== void 0,
558
+ hasTimer: reconnectTimer !== void 0,
559
+ connected: connectedAt !== void 0,
560
+ failedAttempts
561
+ });
562
+ /** Publish the current committed status; an observer throw cannot disrupt the supervisor. */
563
+ const publish = () => {
564
+ try {
565
+ ctx.emit("mcp-client/status", config.serverName, computeMcpClientStatus(facts()), disposers.size);
566
+ } catch (error) {
567
+ ctx.logger.error(`${label}: status listener failed: ${String(error)}`);
568
+ }
569
+ };
570
+ /** A generation may act only while it is the current one on a live plugin. */
571
+ const isCurrent = (generation) => !disposed && client === generation;
572
+ /**
573
+ * Serializes every syncTools call — initial syncs and notification re-syncs
574
+ * across all generations — so two syncs can never interleave their
575
+ * dispose-previous/register-next swap (which would double-dispose one
576
+ * generation and leak another).
577
+ */
578
+ let syncChain = Promise.resolve();
579
+ function enqueueSync(generation, syncOpts = opts) {
580
+ const run = syncChain.then(async () => {
581
+ if (!isCurrent(generation)) return;
582
+ disposers = await syncTools(generation, ctx, syncOpts, disposers);
583
+ publish();
584
+ });
585
+ syncChain = run.catch(() => {});
586
+ return run;
587
+ }
588
+ /** One disconnect decision per generation: the isCurrent guard makes racing close/error signals idempotent. */
589
+ function generationDown(generation) {
590
+ if (!isCurrent(generation)) return;
591
+ client = void 0;
592
+ clientClosed = void 0;
593
+ scheduleReconnect();
594
+ }
595
+ /** Wait for the transport-owned close signal without letting a broken transport wedge teardown forever. */
596
+ function waitForClose(closed) {
597
+ return new Promise((resolve) => {
598
+ const timeout = setTimeout(() => {
599
+ resolve(false);
600
+ }, GENERATION_CLOSE_TIMEOUT_MS);
601
+ timeout.unref();
602
+ closed.then(() => {
603
+ clearTimeout(timeout);
604
+ resolve(true);
605
+ });
606
+ });
607
+ }
608
+ function scheduleReconnect() {
609
+ const lostEstablishedConnection = connectedAt !== void 0;
610
+ if (!policy.enabled) {
611
+ 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";
612
+ ctx.logger.error(`${label}: ${message}`);
613
+ publish();
614
+ return;
615
+ }
616
+ if (connectedAt !== void 0 && Date.now() - connectedAt >= policy.maxDelayMs) failedAttempts = 0;
617
+ connectedAt = void 0;
618
+ failedAttempts += 1;
619
+ if (failedAttempts > policy.maxAttempts) {
620
+ syncChain = syncChain.then(() => {
621
+ for (const dispose of disposers.values()) dispose();
622
+ disposers = /* @__PURE__ */ new Map();
623
+ publish();
624
+ });
625
+ ctx.logger.error(`${label}: giving up after ${policy.maxAttempts} consecutive failed reconnect attempts — tools unregistered; reload the plugin or restart the Host to reconnect`);
626
+ publish();
627
+ return;
628
+ }
629
+ const delayMs = Math.min(policy.maxDelayMs, policy.initialDelayMs * 2 ** (failedAttempts - 1));
630
+ const action = lostEstablishedConnection ? "connection lost; reconnecting" : "connection failed; retrying";
631
+ ctx.logger.warn(`${label}: ${action} in ${delayMs}ms (attempt ${failedAttempts}/${policy.maxAttempts})`);
632
+ reconnectTimer = setTimeout(() => {
633
+ reconnectTimer = void 0;
634
+ settling = connectGeneration(false);
635
+ }, delayMs);
636
+ reconnectTimer.unref();
637
+ publish();
638
+ }
639
+ /**
640
+ * One connection attempt: fresh transport + client (the MCP SDK binds a
641
+ * Protocol to one transport for life), connect, then queue the initial tool
642
+ * sync. The startup flag belongs to the attempt rather than the shared sync
643
+ * queue, so an early notification cannot consume strict startup semantics.
644
+ * Every failure funnels through {@link generationDown}; success arms the
645
+ * onclose-driven disconnect path. Never rejects.
646
+ *
647
+ * @param startup - Whether this is the plugin's activation attempt.
648
+ */
649
+ async function connectGeneration(startup) {
650
+ const generation = new Client({
651
+ name: "dsh-mcp-client",
652
+ version: "0.0.1"
653
+ }, { capabilities: {} });
654
+ const closed = Promise.withResolvers();
655
+ let attemptSettled = false;
656
+ let closeObserved = false;
657
+ const hasClosed = () => closeObserved;
658
+ client = generation;
659
+ clientClosed = closed.promise;
660
+ generation.onclose = () => {
661
+ closeObserved = true;
662
+ closed.resolve();
663
+ if (attemptSettled) generationDown(generation);
664
+ };
665
+ generation.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
666
+ if (!isCurrent(generation)) return;
667
+ ctx.logger.info(`${label}: tool list changed, re-syncing`);
668
+ try {
669
+ await enqueueSync(generation);
670
+ } catch (error) {
671
+ if (!disposed) ctx.logger.error(`${label}: tool re-sync failed: ${String(error)}`);
672
+ }
673
+ });
674
+ try {
675
+ await generation.connect(createTransport(config));
676
+ if (hasClosed()) {
677
+ attemptSettled = true;
678
+ generationDown(generation);
679
+ return;
680
+ }
681
+ await enqueueSync(generation, startup ? startupOpts : opts);
682
+ } catch (error) {
683
+ if (firstAttemptError === void 0) firstAttemptError = error;
684
+ if (isCurrent(generation)) ctx.logger.warn(`${label}: connection attempt failed: ${String(error)}`);
685
+ try {
686
+ await generation.close();
687
+ } catch {}
688
+ const quiesced = hasClosed() || await waitForClose(closed.promise);
689
+ attemptSettled = true;
690
+ if (!isCurrent(generation)) return;
691
+ if (!quiesced) {
692
+ client = void 0;
693
+ clientClosed = void 0;
694
+ 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`);
695
+ publish();
696
+ return;
697
+ }
698
+ generationDown(generation);
699
+ return;
700
+ }
701
+ attemptSettled = true;
702
+ if (hasClosed()) {
703
+ generationDown(generation);
704
+ return;
705
+ }
706
+ if (!isCurrent(generation)) return;
707
+ connectedAt = Date.now();
708
+ publish();
709
+ if (failedAttempts > 0) ctx.logger.info(`${label}: reconnected and re-synced tools (attempt ${failedAttempts}/${policy.maxAttempts})`);
710
+ }
711
+ /** The in-flight (or last settled) connection attempt; dispose awaits it for quiescence. */
712
+ let settling = connectGeneration(true);
713
+ publish();
714
+ return {
715
+ ready: settling.then(() => {
716
+ if (client !== void 0) return {};
717
+ /* v8 ignore next -- defensive: firstAttemptError is always set when connect/sync fails */
718
+ return { error: firstAttemptError ?? /* @__PURE__ */ new Error(`${label}: initial connection failed`) };
719
+ }),
720
+ async dispose() {
721
+ disposed = true;
722
+ if (reconnectTimer !== void 0) {
723
+ clearTimeout(reconnectTimer);
724
+ reconnectTimer = void 0;
725
+ }
726
+ publish();
727
+ const current = client;
728
+ const currentClosed = clientClosed;
729
+ client = void 0;
730
+ clientClosed = void 0;
731
+ if (current !== void 0) {
732
+ try {
733
+ await current.close();
734
+ } catch {}
735
+ 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`);
736
+ }
737
+ await settling;
738
+ await syncChain;
739
+ for (const dispose of disposers.values()) dispose();
740
+ disposers = /* @__PURE__ */ new Map();
741
+ publish();
742
+ }
743
+ };
744
+ }
745
+ //#endregion
746
+ //#region lib/types/index.js
747
+ /**
748
+ * MCP client bridge plugin: connects to an external MCP server and registers
749
+ * its tools on `ctx.tools` under server-qualified public names
750
+ * (`mcp__<serverName>__<rawName>`). Each plugin instance connects to one MCP
751
+ * server; load multiple instances in `cordis.yml` for multiple servers.
752
+ *
753
+ * Namespace plugin (named exports, no default export). Lifecycle is
754
+ * effect-scoped: disposal disconnects from the server, unregisters all tools,
755
+ * and releases the `serverName` namespace reservation. HMR hot-swaps by
756
+ * disposing the old instance and creating a new one; identical `serverName`
757
+ * reproduces identical public tool names.
758
+ *
759
+ * @module @deepseek-ai/dsh-mcp-client
760
+ */
761
+ /** Cordis plugin name used by loader diagnostics. */
762
+ const name = "mcp-client";
763
+ /** Services required by this plugin. */
764
+ const inject = ["tools"];
765
+ /** Default timeout for individual MCP tool calls (ms). */
766
+ const DEFAULT_TOOL_CALL_TIMEOUT_MS = 6e4;
767
+ /** Valid `serverName`, kept below the public tool-name budget. */
768
+ const SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
769
+ /**
770
+ * Live `serverName` reservations per app, keyed off `ctx.root` (multiple apps
771
+ * in one process — tests — must not see each other's names). A duplicate
772
+ * namespace is a configuration error surfaced at plugin load, never silent
773
+ * shadowing.
774
+ */
775
+ const activeServerNames = /* @__PURE__ */ new WeakMap();
776
+ const Reconnect = z.object({
777
+ enabled: z.boolean().default(RECONNECT_DEFAULTS.enabled),
778
+ initialDelayMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(RECONNECT_DEFAULTS.initialDelayMs),
779
+ maxDelayMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(RECONNECT_DEFAULTS.maxDelayMs),
780
+ maxAttempts: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(RECONNECT_DEFAULTS.maxAttempts)
781
+ });
782
+ const Config = z.union([z.object({
783
+ transport: z.const("stdio"),
784
+ serverName: z.string().required().pattern(SERVER_NAME_PATTERN),
785
+ command: z.string().required(),
786
+ args: z.array(String).default([]),
787
+ env: z.dict(String).default({}),
788
+ cwd: z.string().default(""),
789
+ toolCallTimeoutMs: z.number().default(DEFAULT_TOOL_CALL_TIMEOUT_MS),
790
+ failOnStartupError: z.boolean().default(false),
791
+ reconnect: Reconnect
792
+ }), z.object({
793
+ transport: z.const("streamable-http"),
794
+ serverName: z.string().required().pattern(SERVER_NAME_PATTERN),
795
+ url: z.string().required(),
796
+ headers: z.dict(String).default({}),
797
+ toolCallTimeoutMs: z.number().default(DEFAULT_TOOL_CALL_TIMEOUT_MS),
798
+ failOnStartupError: z.boolean().default(false),
799
+ reconnect: Reconnect
800
+ })]);
801
+ /**
802
+ * Connect one MCP server and publish its initial tool generation before activation.
803
+ * This entry remains explicitly `async`: Cordis treats a prototype-bearing
804
+ * ordinary function as a constructor, whose returned Promise is not startup work.
805
+ * @param ctx - plugin context carrying the tool registry.
806
+ * @param config - resolved transport and server namespace configuration.
807
+ * @returns startup readiness after connection and initial tool discovery settle.
808
+ */
809
+ async function apply(ctx, config) {
810
+ const reconnect = resolveReconnectPolicy(config.reconnect, `mcp-client(${config.serverName}): reconnect`);
811
+ ctx.effect(() => {
812
+ let names = activeServerNames.get(ctx.root);
813
+ if (!names) {
814
+ names = /* @__PURE__ */ new Set();
815
+ activeServerNames.set(ctx.root, names);
816
+ }
817
+ 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`);
818
+ names.add(config.serverName);
819
+ return () => void names.delete(config.serverName);
820
+ }, "mcp-client.serverName");
821
+ const connection = startConnection(ctx, config, reconnect);
822
+ ctx.effect(() => {
823
+ return () => connection.dispose();
824
+ }, "mcp-client.connection");
825
+ const outcome = await connection.ready;
826
+ if (outcome.error !== void 0 && config.failOnStartupError) throw new Error(`mcp-client(${config.serverName}): initial connection or tool synchronization failed`, { cause: outcome.error });
827
+ }
828
+ //#endregion
829
+ export { Config, apply, inject, name };