@sparkelf/dsh-plugin-mcp-credentials 0.1.0-rc.10

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.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/plus/mcp-credentials/README.md
5
+ README.md: c074ff8dc4ec6e093d36f1ec300eb9009fee7674
6
+ README.zh.md: a07457971bd284f4d7e95eda795c0afd60b00a5d
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ ---
2
+ description: "The official MCP client behavior with per-request credential-backed Bearer authentication for Streamable HTTP."
3
+ kind: "package-reference"
4
+ ---
5
+
6
+ # @sparkelf/dsh-plugin-mcp-credentials
7
+
8
+ English | [中文](README.zh.md)
9
+
10
+ ## Summary
11
+
12
+ This Host plugin preserves official MCP connection, reconnect, tool publication, image-result, and lifecycle behavior while adding one Streamable HTTP option: `bearerTokenRef`. The transport resolves that DSH credential immediately before every network request and sends the current value as the Bearer token.
13
+
14
+ ## Table of Contents
15
+
16
+ - [Use this package](#use-this-package)
17
+ - [Model Experience](#model-experience)
18
+ - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
19
+ - [Dev Note](#dev-note)
20
+
21
+ -----
22
+
23
+ <a id="use-this-package"></a>
24
+ ## Use this package
25
+
26
+ Use the same stdio or `streamable-http` configuration as the official MCP client. For credential-backed HTTP, set `bearerTokenRef` and compose Credentials; literal `headers.Authorization` and `bearerTokenRef` are mutually exclusive. DataOps mounts this plugin internally so token rotation reaches the next MCP request without a profile remount.
27
+
28
+ -----
29
+
30
+ <a id="model-experience"></a>
31
+ ## Model Experience
32
+
33
+ ### Credential-backed MCP transport
34
+
35
+ #### What the model sees
36
+
37
+ The model sees only current namespaced MCP tool schemas authenticated through `bearerTokenRef` and their results. Credential references and values never appear in tool arguments, results, prompts, Session events, manifests, or deployment locks.
38
+
39
+ #### Token effect
40
+
41
+ Authentication adds zero tokens. MCP tool schemas and calls retain the token effects owned by the upstream MCP client.
42
+
43
+ #### KV Cache effect
44
+
45
+ Credential rotation does not alter model-visible schemas. Tool discovery or connection loss may add or remove schemas and therefore change the tool prefix.
46
+
47
+ ## Known Limitations and Deferred Work
48
+
49
+ <a id="known-limitations-and-deferred-work"></a>
50
+
51
+ - **Bearer authentication only**: other HTTP authorization schemes require a proven provider extension point; profile files must not carry literal secret headers.
52
+
53
+ <a id="dev-note"></a>
54
+ ### Dev Note
55
+
56
+ <details>
57
+ <summary>Working context for maintainers, click to expand</summary>
58
+
59
+ This Dev Note is working context for maintainers; shipped behavior, limits, and rationale live in the sections above, the package code, and the linked Agent Note.
60
+
61
+ - `src/index.ts` owns credential resolution and MCP transport composition. The [distribution Agent Note](../../../.agents/notes/proposed/architecture/2026-08-29-ranged-plus-patchset-distribution.md) records why this is a complete internal DataOps dependency.
62
+
63
+ </details>
package/README.zh.md ADDED
@@ -0,0 +1,63 @@
1
+ ---
2
+ description: "为Streamable HTTP加入per-request credential-backed Bearer authentication的official MCP client behavior。"
3
+ kind: "package-reference"
4
+ ---
5
+
6
+ # @sparkelf/dsh-plugin-mcp-credentials
7
+
8
+ [English](README.md) | 中文
9
+
10
+ ## 概述
11
+
12
+ 该Host plugin保留official MCP connection、reconnect、tool publication、image-result及lifecycle behavior,同时增加一个Streamable HTTP option:`bearerTokenRef`。Transport会在每次network request前立即resolve该DSH credential,并把current value作为Bearer token发送。
13
+
14
+ ## 目录
15
+
16
+ - [使用此软件包](#use-this-package)
17
+ - [模型体验](#model-experience)
18
+ - [已知限制和延期工作](#known-limitations-and-deferred-work)
19
+ - [开发备注](#dev-note)
20
+
21
+ -----
22
+
23
+ <a id="use-this-package"></a>
24
+ ## 使用此软件包
25
+
26
+ 使用与official MCP client相同的stdio或`streamable-http` configuration。对于credential-backed HTTP,设置`bearerTokenRef`并compose Credentials;literal `headers.Authorization`与`bearerTokenRef`互斥。DataOps会在内部mount该plugin,因此token rotation无需profile remount即可到达下一次MCP request。
27
+
28
+ -----
29
+
30
+ <a id="model-experience"></a>
31
+ ## 模型体验
32
+
33
+ ### Credential-backed MCP transport
34
+
35
+ #### 模型看到什么
36
+
37
+ 模型只看到通过`bearerTokenRef`认证的当前namespaced MCP tool schemas及其results。Credential references及values不会出现在tool arguments、results、prompts、Session events、manifests或deployment locks中。
38
+
39
+ #### Token 影响
40
+
41
+ Authentication增加零token。MCP tool schemas及calls保留upstream MCP client持有的token effects。
42
+
43
+ #### KV Cache 影响
44
+
45
+ Credential rotation不改变model-visible schemas。Tool discovery或connection loss可能增加或移除schemas,从而改变tool prefix。
46
+
47
+ ## 已知限制和延期工作
48
+
49
+ <a id="known-limitations-and-deferred-work"></a>
50
+
51
+ - **仅Bearer authentication**:其他HTTP authorization schemes需要proven provider extension point;profile files不得携带literal secret headers。
52
+
53
+ <a id="dev-note"></a>
54
+ ### 开发备注
55
+
56
+ <details>
57
+ <summary>维护者工作上下文,点击展开</summary>
58
+
59
+ 该开发备注是maintainer working context;shipped behavior、limits及rationale以以上sections、package code及linked Agent Note为准。
60
+
61
+ - `src/index.ts`持有credential resolution及MCP transport composition。[Distribution Agent Note](../../../.agents/notes/proposed/architecture/2026-08-29-ranged-plus-patchset-distribution.zh.md)记录它作为complete internal DataOps dependency的原因。
62
+
63
+ </details>
package/lib/index.js ADDED
@@ -0,0 +1,818 @@
1
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
2
+ import z from "@deepseek-ai/schemastery";
3
+ import { scopeOf } from "@deepseek-ai/dsh-scope";
4
+ import { MAX_TIMER_DELAY_MS } from "@deepseek-ai/dsh-timeout";
5
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
6
+ import { ListToolsResultSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
7
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
8
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
9
+ import { scrubbedParentEnv } from "@deepseek-ai/dsh-subprocess";
10
+ import { createHash } from "node:crypto";
11
+ import { isDeepStrictEqual } from "node:util";
12
+ import { z as z$1 } from "zod";
13
+ import { isImageAdmissionError } from "@deepseek-ai/dsh-attachment";
14
+ import { assertSupportedJsonSchema } from "@deepseek-ai/dsh-tools";
15
+ //#region lib/types/transport.js
16
+ /**
17
+ * Transport factory: creates the appropriate MCP transport based on the
18
+ * plugin's resolved config. Stdio spawns a child process (with credential
19
+ * scrubbing); Streamable HTTP connects to a URL.
20
+ *
21
+ * @module
22
+ */
23
+ /**
24
+ * The subprocess seam's scrubbed parent env (credential-shaped and stale
25
+ * `DSH_*` names dropped), plus the spec's explicit env. The MCP SDK owns the
26
+ * actual spawn, so this transport shares the scrub definition rather than the
27
+ * spawn path.
28
+ */
29
+ function buildChildEnv(extra) {
30
+ return {
31
+ ...scrubbedParentEnv(),
32
+ ...extra
33
+ };
34
+ }
35
+ /** Resolve the current bearer credential immediately before each network request. */
36
+ function credentialFetch(ctx, rawRef) {
37
+ const ref = credentialRef(rawRef);
38
+ return async (input, init) => {
39
+ const provider = ctx.get("credentials");
40
+ if (provider === void 0) throw new Error(`mcp-client: credential service unavailable while resolving "${ref}"`);
41
+ const resolved = await provider.resolve(ref);
42
+ if (resolved === void 0) throw new Error(`mcp-client: credential "${ref}" is not configured`);
43
+ const headers = new Headers(init?.headers);
44
+ headers.set("Authorization", `Bearer ${resolved.value}`);
45
+ return globalThis.fetch(input, {
46
+ ...init,
47
+ headers
48
+ });
49
+ };
50
+ }
51
+ /**
52
+ * Create an MCP transport from the resolved plugin config.
53
+ *
54
+ * @param config - Resolved plugin config discriminated on `transport`.
55
+ * @param ctx - Cordis context required only for credential-backed HTTP auth.
56
+ * @returns A connected-ready MCP Transport (stdio or Streamable HTTP).
57
+ */
58
+ function createTransport(config, ctx) {
59
+ switch (config.transport) {
60
+ case "stdio": return new StdioClientTransport({
61
+ command: config.command,
62
+ args: config.args,
63
+ env: buildChildEnv(config.env),
64
+ cwd: config.cwd
65
+ });
66
+ case "streamable-http": {
67
+ const authenticatedFetch = config.bearerTokenRef === void 0 ? void 0 : credentialFetch(ctx, config.bearerTokenRef);
68
+ return new StreamableHTTPClientTransport(new URL(config.url), {
69
+ requestInit: { headers: config.headers },
70
+ ...authenticatedFetch === void 0 ? {} : { fetch: authenticatedFetch }
71
+ });
72
+ }
73
+ }
74
+ }
75
+ //#endregion
76
+ //#region lib/types/tools.js
77
+ /**
78
+ * Tool bridge: discovers MCP tools, registers them on the harness ToolRuntime
79
+ * under deterministic server-qualified public names, and handles re-sync when
80
+ * the server's tool list changes.
81
+ *
82
+ * Naming contract (see the mcp-client Agent Note "Naming invariants"): every MCP tool
83
+ * has the stable identity `(serverName, rawName)`; the model-facing public name
84
+ * is `mcp__<serverName>__<rawName>`, normalized to the DeepSeek function-name
85
+ * constraints. The raw name is only ever sent on the wire (`tools/call`); the
86
+ * public name is never parsed to recover it.
87
+ *
88
+ * @module
89
+ */
90
+ /**
91
+ * DeepSeek function-name contract: at most 64 characters. Wire-protocol
92
+ * constant, not configuration.
93
+ */
94
+ const MAX_PUBLIC_NAME_LENGTH = 64;
95
+ /** DeepSeek function-name contract: only `[A-Za-z0-9_-]` is allowed. */
96
+ const INVALID_NAME_CHARS = /[^A-Za-z0-9_-]/g;
97
+ /** Hex chars of the SHA-256 identity hash appended on lossy normalization. */
98
+ const HASH_LENGTH = 12;
99
+ /** Raw result record: the bridge owns JSON-value validation after transport. */
100
+ const RawCallToolResultSchema = z$1.record(z$1.string(), z$1.unknown());
101
+ /** Raster formats supported by the durable attachment vocabulary. */
102
+ const IMAGE_MEDIA_TYPES = [
103
+ "image/png",
104
+ "image/jpeg",
105
+ "image/webp",
106
+ "image/gif"
107
+ ];
108
+ /** Canonical RFC 4648 base64, excluding whitespace and URL-safe aliases. */
109
+ const CANONICAL_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
110
+ /** List without mutating the SDK's per-page output-validator cache. */
111
+ function listToolsUncached(client, cursor) {
112
+ return client.request({
113
+ method: "tools/list",
114
+ ...cursor === void 0 ? {} : { params: { cursor } }
115
+ }, ListToolsResultSchema);
116
+ }
117
+ /** Call without the SDK pre-validating an output schema the bridge may not support. */
118
+ function callToolUncached(client, rawName, args, exec, opts) {
119
+ return client.request({
120
+ method: "tools/call",
121
+ params: {
122
+ name: rawName,
123
+ arguments: args
124
+ }
125
+ }, RawCallToolResultSchema, {
126
+ signal: exec.signal,
127
+ timeout: opts.toolCallTimeoutMs
128
+ });
129
+ }
130
+ /**
131
+ * Derive the model-facing public name for one MCP tool.
132
+ *
133
+ * Deterministic pure function of `(serverName, rawName)`: the clean case is
134
+ * `mcp__<serverName>__<rawName>` verbatim. When character replacement or
135
+ * truncation to the DeepSeek function-name contract (64 chars,
136
+ * `[A-Za-z0-9_-]`) changes the name, a 12-hex-char SHA-256 hash of the
137
+ * identity is appended so distinct MCP identities never collapse into the
138
+ * same public name.
139
+ *
140
+ * @param serverName - Stable local namespace from plugin config.
141
+ * @param rawName - The MCP server's own tool name.
142
+ * @returns The globally unique, model-facing ToolRuntime name.
143
+ */
144
+ function publicToolName(serverName, rawName) {
145
+ const joined = `mcp__${serverName}__${rawName}`;
146
+ const normalized = joined.replace(INVALID_NAME_CHARS, "_");
147
+ if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH) return normalized;
148
+ const hash = createHash("sha256").update(`${serverName}\0${rawName}`).digest("hex").slice(0, HASH_LENGTH);
149
+ return `${normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1)}_${hash}`;
150
+ }
151
+ /**
152
+ * Sync the MCP server's tool list into the harness ToolRuntime.
153
+ *
154
+ * Two phases keep the swap safe:
155
+ *
156
+ * 1. Fetch: drain uncached `tools/list` pagination and build the full next
157
+ * generation of `ToolDefinition`s under public names. Any failure here
158
+ * (network error, duplicate raw name in the server's list) rejects and
159
+ * leaves the previous generation registered untouched.
160
+ * 2. Swap: dispose the previous generation, register the new one. A registry
161
+ * conflict here can only mean a foreign registration squats on this
162
+ * server's `mcp__<serverName>__` namespace — the partial generation is
163
+ * rolled back (zero tools from this server) and logged. Initial strict
164
+ * synchronization may propagate the conflict so its parent transaction
165
+ * rejects; ordinary clients and later re-syncs return an empty map.
166
+ *
167
+ * @param client - Connected MCP Client instance used to list and call tools.
168
+ * @param ctx - Cordis context providing the `tools` service for registration.
169
+ * @param opts - Bridge options: server namespace and per-call timeout.
170
+ * @param previous - Disposer map from the prior sync generation; disposed
171
+ * during the swap phase (only after the fetch phase succeeded).
172
+ * @returns A map of registered public tool names to their unregister
173
+ * disposers — the exact set of live registrations owned by this server.
174
+ */
175
+ async function syncTools(client, ctx, opts, previous) {
176
+ const definitions = /* @__PURE__ */ new Map();
177
+ let cursor;
178
+ do {
179
+ const response = await listToolsUncached(client, cursor);
180
+ for (const tool of response.tools) {
181
+ const publicName = publicToolName(opts.serverName, tool.name);
182
+ if (definitions.has(publicName)) throw new Error(`mcp-client(${opts.serverName}): server listed tool "${tool.name}" more than once — invalid tool list`);
183
+ definitions.set(publicName, createDefinition(client, ctx, publicName, tool.name, tool.description ?? "", tool.inputSchema, supportedOutputSchema(tool.outputSchema), tool.execution?.taskSupport === "required", opts));
184
+ }
185
+ cursor = response.nextCursor;
186
+ } while (cursor);
187
+ for (const dispose of previous.values()) dispose();
188
+ const disposers = /* @__PURE__ */ new Map();
189
+ try {
190
+ for (const [publicName, definition] of definitions) disposers.set(publicName, ctx.tools.register(definition));
191
+ } catch (error) {
192
+ for (const dispose of disposers.values()) dispose();
193
+ ctx.logger.error(`mcp-client(${opts.serverName}): tool registration failed, no tools registered: ${String(error)}`);
194
+ if (opts.registrationFailure === "throw") throw error;
195
+ return /* @__PURE__ */ new Map();
196
+ }
197
+ return disposers;
198
+ }
199
+ /** Keep a supported advertised schema; unsupported MCP vocabulary falls back to JsonValue. */
200
+ function supportedOutputSchema(candidate) {
201
+ if (candidate === void 0) return void 0;
202
+ try {
203
+ assertSupportedJsonSchema(candidate);
204
+ return candidate;
205
+ } catch {
206
+ return;
207
+ }
208
+ }
209
+ /**
210
+ * Build one generation-local tool definition and its execution-local rich projections.
211
+ * @param client - connected MCP client used for calls.
212
+ * @param ctx - plugin context carrying optional attachment and model services.
213
+ * @param publicName - registry-qualified public tool name.
214
+ * @param rawName - MCP wire tool name.
215
+ * @param description - model-facing tool description.
216
+ * @param parameters - MCP input schema.
217
+ * @param structuredSchema - supported structured-output schema, when advertised.
218
+ * @param taskRequired - whether this MCP tool requires unsupported task execution.
219
+ * @param opts - bridge timeout and namespace options.
220
+ * @returns a complete ToolRuntime definition.
221
+ */
222
+ function createDefinition(client, ctx, publicName, rawName, description, parameters, structuredSchema, taskRequired, opts) {
223
+ const projections = /* @__PURE__ */ new WeakMap();
224
+ return {
225
+ name: publicName,
226
+ description,
227
+ parameters,
228
+ output: createOutput(rawName, structuredSchema),
229
+ execute: createExecutor(client, ctx, rawName, taskRequired, opts, projections),
230
+ finalizeContent(exec, result) {
231
+ const projection = projections.get(exec);
232
+ if (projection === void 0) return void 0;
233
+ projections.delete(exec);
234
+ if (result.isError) return void 0;
235
+ if (!isDeepStrictEqual(result.value, projection.value)) return void 0;
236
+ if (!isDeepStrictEqual(result.content, projection.fallback)) return void 0;
237
+ return projection.content;
238
+ }
239
+ };
240
+ }
241
+ /** Build the canonical result schema and existing Native text projection. */
242
+ function createOutput(rawName, structuredSchema) {
243
+ return {
244
+ schema: {
245
+ type: "object",
246
+ properties: {
247
+ content: {
248
+ type: "array",
249
+ items: {}
250
+ },
251
+ structuredContent: structuredSchema ?? {}
252
+ },
253
+ required: structuredSchema === void 0 ? ["content"] : ["content", "structuredContent"],
254
+ additionalProperties: false
255
+ },
256
+ render(_args, value) {
257
+ return [{
258
+ type: "text",
259
+ text: extractText(value.content, rawName)
260
+ }];
261
+ }
262
+ };
263
+ }
264
+ /**
265
+ * Create an execute function for one MCP tool. The executor closes over the
266
+ * raw MCP tool name and sends an uncached `tools/call` request with it (never
267
+ * the public name), with abort signal and timeout, then maps the result to
268
+ * harness ContentBlocks. Owning the raw request prevents the SDK's internal
269
+ * per-page schema cache from pre-validating a different contract.
270
+ *
271
+ * When the MCP server returns `isError: true`, the executor throws so that
272
+ * the ToolRuntime's catch path produces an `isError` result for the model.
273
+ */
274
+ function createExecutor(client, ctx, rawName, taskRequired, opts, projections) {
275
+ return async (args, exec) => {
276
+ if (taskRequired) throw new Error(`Tool "${rawName}" requires task-based execution, which this bridge does not support`);
277
+ const result = await callToolUncached(client, rawName, typeof args === "object" && args !== null ? args : {}, exec, opts);
278
+ if (!Array.isArray(result.content)) {
279
+ const rendered = "toolResult" in result ? JSON.stringify(result.toolResult) : "(no output)";
280
+ const text = typeof rendered === "string" ? rendered : "(no output)";
281
+ if (result.isError === true) throw new Error(text);
282
+ return {
283
+ content: [{
284
+ type: "text",
285
+ text
286
+ }],
287
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}
288
+ };
289
+ }
290
+ const content = result.content;
291
+ const text = extractText(content, rawName);
292
+ if (result.isError === true) throw new Error(text);
293
+ const value = {
294
+ content,
295
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}
296
+ };
297
+ if (containsImage(content)) {
298
+ const fallback = [{
299
+ type: "text",
300
+ text: extractText(content, rawName)
301
+ }];
302
+ const projected = await prepareImageProjection(ctx, exec, content, rawName);
303
+ projections.set(exec, {
304
+ value,
305
+ fallback,
306
+ content: projected
307
+ });
308
+ }
309
+ return value;
310
+ };
311
+ }
312
+ /** Whether an untrusted MCP content array contains a declared image block. */
313
+ function containsImage(content) {
314
+ return content.some((value) => isRecord(value) && value.type === "image");
315
+ }
316
+ /** Narrow one JSON value to a string-keyed object. */
317
+ function isRecord(value) {
318
+ return typeof value === "object" && value !== null && !Array.isArray(value);
319
+ }
320
+ /** Narrow a declared MIME string to the durable image vocabulary. */
321
+ function isImageMediaType(value) {
322
+ return IMAGE_MEDIA_TYPES.includes(value);
323
+ }
324
+ /** Decode one untrusted MCP image block without accepting base64 aliases. */
325
+ function decodeImage(block) {
326
+ if (block.mimeType === void 0 || !isImageMediaType(block.mimeType)) throw new Error("the declared media type is not PNG, JPEG, WebP, or GIF");
327
+ if (block.data === void 0 || !CANONICAL_BASE64.test(block.data)) throw new Error("the image data is not canonical base64");
328
+ const data = Buffer.from(block.data, "base64");
329
+ if (data.toString("base64") !== block.data) throw new Error("the image data is not canonical base64");
330
+ return {
331
+ data,
332
+ mediaType: block.mimeType
333
+ };
334
+ }
335
+ /**
336
+ * Resolve the active model route and durable store for an image-bearing result.
337
+ * @param ctx - plugin context with optional services.
338
+ * @param exec - exact tool execution whose agent supplies the latest route.
339
+ * @returns the attachment store after exact positive image-capability proof.
340
+ */
341
+ async function resolveImageAdmission(ctx, exec) {
342
+ const attachments = ctx.get("attachments");
343
+ if (attachments === void 0) throw new Error("no attachment store is mounted");
344
+ const routed = exec.agent?.session.requestHeader()?.config;
345
+ const provider = routed?.provider ?? exec.agent?.options.provider;
346
+ const model = routed?.model ?? exec.agent?.options.model;
347
+ const llm = ctx.get("llm");
348
+ if (provider === void 0 || model === void 0 || llm === void 0) throw new Error("the current model route could not be resolved");
349
+ let info;
350
+ try {
351
+ info = await llm.resolveModelInfo(provider, model, exec.signal);
352
+ } catch {
353
+ throw new Error("the current model route could not be verified");
354
+ }
355
+ if (info.inputModalities === void 0 || !info.inputModalities.includes("image")) throw new Error(`model "${model}" does not declare image input`);
356
+ if (exec.signal.aborted) throw new Error("the tool call was canceled before image storage");
357
+ return attachments;
358
+ }
359
+ /** Stable diagnostic text for an image block that was not admitted. */
360
+ function imageDiagnostic(block, reason) {
361
+ return `[image unavailable: ${block.mimeType ?? "unknown media type"}; ${reason}; raw image data remains available to programmatic callers]`;
362
+ }
363
+ /**
364
+ * Decode, preflight, and durably save one MCP result's ordered image batch.
365
+ * Any refusal projects every image as text while retaining the canonical raw
366
+ * value for programmatic callers.
367
+ */
368
+ async function prepareImageProjection(ctx, exec, content, toolName) {
369
+ const decoded = [];
370
+ const validationErrors = /* @__PURE__ */ new Map();
371
+ const imageIndexes = [];
372
+ for (const [index, value] of content.entries()) {
373
+ if (!isRecord(value) || value.type !== "image") continue;
374
+ imageIndexes.push(index);
375
+ try {
376
+ decoded.push(decodeImage(value));
377
+ } catch (error) {
378
+ validationErrors.set(index, error.message);
379
+ }
380
+ }
381
+ if (validationErrors.size > 0) return projectContent(content, toolName, (block, index) => ({
382
+ type: "text",
383
+ text: imageDiagnostic(block, validationErrors.get(index) ?? "another image in the same result was invalid")
384
+ }));
385
+ let attachments;
386
+ try {
387
+ attachments = await resolveImageAdmission(ctx, exec);
388
+ } catch (error) {
389
+ const reason = error.message;
390
+ return projectContent(content, toolName, (block) => ({
391
+ type: "text",
392
+ text: imageDiagnostic(block, reason)
393
+ }));
394
+ }
395
+ try {
396
+ const refs = await attachments.saveImages(decoded);
397
+ const byIndex = new Map(imageIndexes.map((index, offset) => [index, refs[offset]]));
398
+ return projectContent(content, toolName, (_block, index) => ({
399
+ type: "image",
400
+ attachment: byIndex.get(index)
401
+ }));
402
+ } catch (error) {
403
+ const reason = isImageAdmissionError(error) ? `image admission rejected the result: ${error.message}` : "durable image storage rejected the result";
404
+ return projectContent(content, toolName, (block) => ({
405
+ type: "text",
406
+ text: imageDiagnostic(block, reason)
407
+ }));
408
+ }
409
+ }
410
+ /**
411
+ * Extract text from an MCP content array into a single string.
412
+ * - text blocks: join with '\n'
413
+ * - image/audio/resource blocks: replaced with a placeholder
414
+ *
415
+ * Defensive: fields that the MCP spec declares required (mimeType, text) are
416
+ * guarded with fallbacks because this is a network trust boundary.
417
+ */
418
+ function extractText(mcpContent, toolName) {
419
+ return projectContent(mcpContent, toolName).map((block) => block.text).join("\n");
420
+ }
421
+ /**
422
+ * Project ordered MCP blocks into the core content vocabulary.
423
+ * Text-like runs are newline-coalesced; admitted images split those runs at
424
+ * their original position.
425
+ */
426
+ function projectContent(mcpContent, toolName, image = (block) => ({
427
+ type: "text",
428
+ text: imageDiagnostic(block, "this result was not admitted to durable model context")
429
+ })) {
430
+ const projected = [];
431
+ const text = [];
432
+ const flushText = () => {
433
+ if (text.length === 0) return;
434
+ projected.push({
435
+ type: "text",
436
+ text: text.splice(0).join("\n")
437
+ });
438
+ };
439
+ for (const [index, value] of mcpContent.entries()) {
440
+ if (!isRecord(value)) {
441
+ text.push("[unsupported MCP content block: expected an object]");
442
+ continue;
443
+ }
444
+ const block = value;
445
+ switch (block.type) {
446
+ case "text":
447
+ if (block.text !== void 0) text.push(block.text);
448
+ break;
449
+ case "image":
450
+ flushText();
451
+ projected.push(image(block, index));
452
+ break;
453
+ case "resource_link":
454
+ if (block.name === void 0 || block.uri === void 0) text.push("[resource link unavailable: the MCP block is missing its name or URI]");
455
+ else text.push(`Resource link: ${block.name} (${block.uri})`);
456
+ break;
457
+ case "audio":
458
+ text.push(`[audio result unsupported: ${block.mimeType ?? "unknown media type"}; raw audio data remains available to programmatic callers]`);
459
+ break;
460
+ case "resource":
461
+ text.push("[embedded resource unsupported; raw resource data remains available to programmatic callers]");
462
+ break;
463
+ default: text.push(`[unsupported MCP content type: ${block.type}]`);
464
+ }
465
+ }
466
+ flushText();
467
+ return projected.length > 0 ? projected : [{
468
+ type: "text",
469
+ text: `(${toolName} returned no model-visible content)`
470
+ }];
471
+ }
472
+ //#endregion
473
+ //#region lib/types/connection.js
474
+ /**
475
+ * Connection supervisor: owns the MCP client/transport generations for one
476
+ * plugin instance, keeps the harness tool registry in sync with the live
477
+ * generation, and — when the connection drops — restarts the configured
478
+ * server with bounded exponential backoff.
479
+ *
480
+ * One outage shares one attempt budget (`maxAttempts` consecutive failed
481
+ * attempts, delays doubling from `initialDelayMs` up to `maxDelayMs`). A
482
+ * connection that stays up past the stability window closes the outage, so
483
+ * the next disconnect starts a fresh budget while a crash-looping server —
484
+ * even one whose connects briefly succeed — still exhausts the cap instead of
485
+ * restarting forever. Exhaustion unregisters the server's tools and stops;
486
+ * disposal (including HMR) is the only way back from that state.
487
+ *
488
+ * @module
489
+ */
490
+ /** Defaults shared by the Config schema and {@link resolveReconnectPolicy}. */
491
+ const RECONNECT_DEFAULTS = Object.freeze({
492
+ enabled: true,
493
+ initialDelayMs: 500,
494
+ maxDelayMs: 3e4,
495
+ maxAttempts: 10
496
+ });
497
+ const GENERATION_CLOSE_TIMEOUT_MS = 5e3;
498
+ /**
499
+ * The one explicit resolve step from raw reconnect config to the policy the
500
+ * supervisor runs. Programmatic construction may bypass Schemastery
501
+ * normalization, so every default and bound is re-judged here — misconfiguration
502
+ * fails the plugin instance at load.
503
+ *
504
+ * @param config - Raw `reconnect` config; omission uses the defaults.
505
+ * @param path - Diagnostic prefix naming the config location in thrown messages.
506
+ * @returns The frozen resolved policy.
507
+ */
508
+ function resolveReconnectPolicy(config, path) {
509
+ if (config !== void 0) {
510
+ for (const key of Object.keys(config)) if (!Object.hasOwn(RECONNECT_DEFAULTS, key)) throw new Error(`${path}.${key} is not a reconnect option`);
511
+ }
512
+ const enabled = config?.enabled ?? RECONNECT_DEFAULTS.enabled;
513
+ const initialDelayMs = config?.initialDelayMs ?? RECONNECT_DEFAULTS.initialDelayMs;
514
+ const maxDelayMs = config?.maxDelayMs ?? RECONNECT_DEFAULTS.maxDelayMs;
515
+ const maxAttempts = config?.maxAttempts ?? RECONNECT_DEFAULTS.maxAttempts;
516
+ 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}`);
517
+ 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}`);
518
+ if (initialDelayMs > maxDelayMs) throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);
519
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) throw new Error(`${path}.maxAttempts must be a positive integer`);
520
+ return Object.freeze({
521
+ enabled,
522
+ initialDelayMs,
523
+ maxDelayMs,
524
+ maxAttempts
525
+ });
526
+ }
527
+ /**
528
+ * Start the supervised connection for one MCP server and keep it alive per
529
+ * the reconnect policy.
530
+ *
531
+ * @param ctx - Cordis context providing the `tools` registry and logger.
532
+ * @param config - Resolved plugin config selecting the transport and server identity.
533
+ * @param policy - Resolved reconnect policy from {@link resolveReconnectPolicy}.
534
+ * @returns Handle with a `ready` promise for startup-await and a `dispose` for teardown.
535
+ */
536
+ function startConnection(ctx, config, policy) {
537
+ const label = `mcp-client(${config.serverName})`;
538
+ const opts = {
539
+ registrationFailure: "contain",
540
+ serverName: config.serverName,
541
+ toolCallTimeoutMs: config.toolCallTimeoutMs
542
+ };
543
+ const startupOpts = config.failOnStartupError ? {
544
+ ...opts,
545
+ registrationFailure: "throw"
546
+ } : opts;
547
+ let disposed = false;
548
+ /** Current generation: the connecting or connected client; undefined during backoff waits and after final failure. */
549
+ let client;
550
+ /** Close signal paired with {@link client}; captured by dispose before current ownership is cleared. */
551
+ let clientClosed;
552
+ /** Live tool registrations owned by this server; only {@link enqueueSync} and dispose swap it. */
553
+ let disposers = /* @__PURE__ */ new Map();
554
+ let reconnectTimer;
555
+ /** Consecutive failed connection attempts within the current outage. */
556
+ let failedAttempts = 0;
557
+ /** When the current generation finished connect + initial sync; undefined while down. */
558
+ let connectedAt;
559
+ /** The real error from the first connection attempt, for startup-await diagnostics. */
560
+ let firstAttemptError;
561
+ /** A generation may act only while it is the current one on a live plugin. */
562
+ const isCurrent = (generation) => !disposed && client === generation;
563
+ /**
564
+ * Serializes every syncTools call — initial syncs and notification re-syncs
565
+ * across all generations — so two syncs can never interleave their
566
+ * dispose-previous/register-next swap (which would double-dispose one
567
+ * generation and leak another).
568
+ */
569
+ let syncChain = Promise.resolve();
570
+ function enqueueSync(generation, syncOpts = opts) {
571
+ const run = syncChain.then(async () => {
572
+ if (!isCurrent(generation)) return;
573
+ disposers = await syncTools(generation, ctx, syncOpts, disposers);
574
+ });
575
+ syncChain = run.catch(() => {});
576
+ return run;
577
+ }
578
+ /** One disconnect decision per generation: the isCurrent guard makes racing close/error signals idempotent. */
579
+ function generationDown(generation) {
580
+ if (!isCurrent(generation)) return;
581
+ client = void 0;
582
+ clientClosed = void 0;
583
+ scheduleReconnect();
584
+ }
585
+ /** Wait for the transport-owned close signal without letting a broken transport wedge teardown forever. */
586
+ function waitForClose(closed) {
587
+ return new Promise((resolve) => {
588
+ const timeout = setTimeout(() => {
589
+ resolve(false);
590
+ }, GENERATION_CLOSE_TIMEOUT_MS);
591
+ timeout.unref();
592
+ closed.then(() => {
593
+ clearTimeout(timeout);
594
+ resolve(true);
595
+ });
596
+ });
597
+ }
598
+ function scheduleReconnect() {
599
+ const lostEstablishedConnection = connectedAt !== void 0;
600
+ if (!policy.enabled) {
601
+ 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";
602
+ ctx.logger.error(`${label}: ${message}`);
603
+ return;
604
+ }
605
+ if (connectedAt !== void 0 && Date.now() - connectedAt >= policy.maxDelayMs) failedAttempts = 0;
606
+ connectedAt = void 0;
607
+ failedAttempts += 1;
608
+ if (failedAttempts > policy.maxAttempts) {
609
+ syncChain = syncChain.then(() => {
610
+ for (const dispose of disposers.values()) dispose();
611
+ disposers = /* @__PURE__ */ new Map();
612
+ });
613
+ ctx.logger.error(`${label}: giving up after ${policy.maxAttempts} consecutive failed reconnect attempts — tools unregistered; reload the plugin or restart the Host to reconnect`);
614
+ return;
615
+ }
616
+ const delayMs = Math.min(policy.maxDelayMs, policy.initialDelayMs * 2 ** (failedAttempts - 1));
617
+ const action = lostEstablishedConnection ? "connection lost; reconnecting" : "connection failed; retrying";
618
+ ctx.logger.warn(`${label}: ${action} in ${delayMs}ms (attempt ${failedAttempts}/${policy.maxAttempts})`);
619
+ reconnectTimer = setTimeout(() => {
620
+ reconnectTimer = void 0;
621
+ settling = connectGeneration(false);
622
+ }, delayMs);
623
+ reconnectTimer.unref();
624
+ }
625
+ /**
626
+ * One connection attempt: fresh transport + client (the MCP SDK binds a
627
+ * Protocol to one transport for life), connect, then queue the initial tool
628
+ * sync. The startup flag belongs to the attempt rather than the shared sync
629
+ * queue, so an early notification cannot consume strict startup semantics.
630
+ * Every failure funnels through {@link generationDown}; success arms the
631
+ * onclose-driven disconnect path. Never rejects.
632
+ *
633
+ * @param startup - Whether this is the plugin's activation attempt.
634
+ */
635
+ async function connectGeneration(startup) {
636
+ const generation = new Client({
637
+ name: "dsh-mcp-client",
638
+ version: "0.0.1"
639
+ }, { capabilities: {} });
640
+ const closed = Promise.withResolvers();
641
+ let attemptSettled = false;
642
+ let closeObserved = false;
643
+ const hasClosed = () => closeObserved;
644
+ client = generation;
645
+ clientClosed = closed.promise;
646
+ generation.onclose = () => {
647
+ closeObserved = true;
648
+ closed.resolve();
649
+ if (attemptSettled) generationDown(generation);
650
+ };
651
+ generation.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
652
+ if (!isCurrent(generation)) return;
653
+ ctx.logger.info(`${label}: tool list changed, re-syncing`);
654
+ try {
655
+ await enqueueSync(generation);
656
+ } catch (error) {
657
+ if (!disposed) ctx.logger.error(`${label}: tool re-sync failed: ${String(error)}`);
658
+ }
659
+ });
660
+ try {
661
+ await generation.connect(createTransport(config, ctx));
662
+ if (hasClosed()) {
663
+ attemptSettled = true;
664
+ generationDown(generation);
665
+ return;
666
+ }
667
+ await enqueueSync(generation, startup ? startupOpts : opts);
668
+ } catch (error) {
669
+ if (firstAttemptError === void 0) firstAttemptError = error;
670
+ if (isCurrent(generation)) ctx.logger.warn(`${label}: connection attempt failed: ${String(error)}`);
671
+ try {
672
+ await generation.close();
673
+ } catch {}
674
+ const quiesced = hasClosed() || await waitForClose(closed.promise);
675
+ attemptSettled = true;
676
+ if (!isCurrent(generation)) return;
677
+ if (!quiesced) {
678
+ client = void 0;
679
+ clientClosed = void 0;
680
+ 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`);
681
+ return;
682
+ }
683
+ generationDown(generation);
684
+ return;
685
+ }
686
+ attemptSettled = true;
687
+ if (hasClosed()) {
688
+ generationDown(generation);
689
+ return;
690
+ }
691
+ if (!isCurrent(generation)) return;
692
+ connectedAt = Date.now();
693
+ if (failedAttempts > 0) ctx.logger.info(`${label}: reconnected and re-synced tools (attempt ${failedAttempts}/${policy.maxAttempts})`);
694
+ }
695
+ /** The in-flight (or last settled) connection attempt; dispose awaits it for quiescence. */
696
+ let settling = connectGeneration(true);
697
+ return {
698
+ ready: settling.then(() => {
699
+ if (client !== void 0) return {};
700
+ /* v8 ignore next -- defensive: firstAttemptError is always set when connect/sync fails */
701
+ return { error: firstAttemptError ?? /* @__PURE__ */ new Error(`${label}: initial connection failed`) };
702
+ }),
703
+ async dispose() {
704
+ disposed = true;
705
+ if (reconnectTimer !== void 0) {
706
+ clearTimeout(reconnectTimer);
707
+ reconnectTimer = void 0;
708
+ }
709
+ const current = client;
710
+ const currentClosed = clientClosed;
711
+ client = void 0;
712
+ clientClosed = void 0;
713
+ if (current !== void 0) {
714
+ try {
715
+ await current.close();
716
+ } catch {}
717
+ 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`);
718
+ }
719
+ await settling;
720
+ await syncChain;
721
+ for (const dispose of disposers.values()) dispose();
722
+ disposers = /* @__PURE__ */ new Map();
723
+ }
724
+ };
725
+ }
726
+ //#endregion
727
+ //#region lib/types/index.js
728
+ /**
729
+ * MCP client bridge plugin: connects to an external MCP server and registers
730
+ * its tools on `ctx.tools` under server-qualified public names
731
+ * (`mcp__<serverName>__<rawName>`). Each plugin instance connects to one MCP
732
+ * server; load multiple instances in `cordis.yml` for multiple servers.
733
+ *
734
+ * Namespace plugin (named exports, no default export). Lifecycle is
735
+ * effect-scoped: disposal disconnects from the server, unregisters all tools,
736
+ * and releases the `serverName` namespace reservation. HMR hot-swaps by
737
+ * disposing the old instance and creating a new one; identical `serverName`
738
+ * reproduces identical public tool names.
739
+ *
740
+ * @module @sparkelf/dsh-plugin-mcp-credentials
741
+ */
742
+ /** Cordis plugin name used by loader diagnostics. */
743
+ const name = "mcp-client";
744
+ /** Services required by this plugin. */
745
+ const inject = ["tools"];
746
+ /** Default timeout for individual MCP tool calls (ms). */
747
+ const DEFAULT_TOOL_CALL_TIMEOUT_MS = 6e4;
748
+ /** Valid `serverName`, kept below the public tool-name budget. */
749
+ const SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
750
+ /**
751
+ * Live `serverName` reservations per registration scope. Agent-scoped MCP
752
+ * servers may reuse a namespace in another Agent, while global instances and
753
+ * duplicates inside one Agent remain mutually exclusive.
754
+ */
755
+ const activeServerNames = /* @__PURE__ */ new WeakMap();
756
+ const Reconnect = z.object({
757
+ enabled: z.boolean().default(RECONNECT_DEFAULTS.enabled),
758
+ initialDelayMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(RECONNECT_DEFAULTS.initialDelayMs),
759
+ maxDelayMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(RECONNECT_DEFAULTS.maxDelayMs),
760
+ maxAttempts: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(RECONNECT_DEFAULTS.maxAttempts)
761
+ });
762
+ const Config = z.union([z.object({
763
+ transport: z.const("stdio"),
764
+ serverName: z.string().required().pattern(SERVER_NAME_PATTERN),
765
+ command: z.string().required(),
766
+ args: z.array(String).default([]),
767
+ env: z.dict(String).default({}),
768
+ cwd: z.string().default(""),
769
+ toolCallTimeoutMs: z.number().default(DEFAULT_TOOL_CALL_TIMEOUT_MS),
770
+ failOnStartupError: z.boolean().default(false),
771
+ reconnect: Reconnect
772
+ }), z.object({
773
+ transport: z.const("streamable-http"),
774
+ serverName: z.string().required().pattern(SERVER_NAME_PATTERN),
775
+ url: z.string().required(),
776
+ headers: z.dict(String).default({}),
777
+ bearerTokenRef: z.string().role("credential-ref"),
778
+ toolCallTimeoutMs: z.number().default(DEFAULT_TOOL_CALL_TIMEOUT_MS),
779
+ failOnStartupError: z.boolean().default(false),
780
+ reconnect: Reconnect
781
+ })]);
782
+ function validateCredentialAuth(ctx, config) {
783
+ if (config.transport !== "streamable-http" || config.bearerTokenRef === void 0) return;
784
+ const ref = credentialRef(config.bearerTokenRef);
785
+ if (Object.keys(config.headers).some((header) => header.toLowerCase() === "authorization")) throw new Error(`mcp-client(${config.serverName}): bearerTokenRef and headers.Authorization cannot be configured together`);
786
+ if (ctx.get("credentials") === void 0) throw new Error(`mcp-client(${config.serverName}): bearerTokenRef "${ref}" requires the credentials service`);
787
+ }
788
+ /**
789
+ * Connect one MCP server and publish its initial tool generation before activation.
790
+ * This entry remains explicitly `async`: Cordis treats a prototype-bearing
791
+ * ordinary function as a constructor, whose returned Promise is not startup work.
792
+ * @param ctx - plugin context carrying the tool registry.
793
+ * @param config - resolved transport and server namespace configuration.
794
+ * @returns startup readiness after connection and initial tool discovery settle.
795
+ */
796
+ async function apply(ctx, config) {
797
+ validateCredentialAuth(ctx, config);
798
+ const reconnect = resolveReconnectPolicy(config.reconnect, `mcp-client(${config.serverName}): reconnect`);
799
+ ctx.effect(() => {
800
+ const owner = scopeOf(ctx) ?? ctx.root;
801
+ let names = activeServerNames.get(owner);
802
+ if (!names) {
803
+ names = /* @__PURE__ */ new Set();
804
+ activeServerNames.set(owner, names);
805
+ }
806
+ 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`);
807
+ names.add(config.serverName);
808
+ return () => void names.delete(config.serverName);
809
+ }, "mcp-client.serverName");
810
+ const connection = startConnection(ctx, config, reconnect);
811
+ ctx.effect(() => {
812
+ return () => connection.dispose();
813
+ }, "mcp-client.connection");
814
+ const outcome = await connection.ready;
815
+ if (outcome.error !== void 0 && config.failOnStartupError) throw new Error(`mcp-client(${config.serverName}): initial connection or tool synchronization failed`, { cause: outcome.error });
816
+ }
817
+ //#endregion
818
+ export { Config, apply, inject, name };
@@ -0,0 +1,23 @@
1
+ //#region lib/types/invariant.js
2
+ /**
3
+ * Package-owned invariant companion for `@sparkelf/dsh-plugin-mcp-credentials`.
4
+ * @module @sparkelf/dsh-plugin-mcp-credentials/invariant
5
+ */
6
+ const PACKAGE_NAME = "@sparkelf/dsh-plugin-mcp-credentials";
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,76 @@
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 '@deepseek-ai/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
+ 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
+ export {};
76
+ //# sourceMappingURL=connection.d.ts.map
@@ -0,0 +1,87 @@
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 @sparkelf/dsh-plugin-mcp-credentials
14
+ */
15
+ import type { Context } from '@deepseek-ai/cordis';
16
+ import z from '@deepseek-ai/schemastery';
17
+ import type { ReconnectConfig } from './connection.ts';
18
+ export type { McpResult } from './tools.ts';
19
+ export type { ReconnectConfig, ResolvedReconnectPolicy } from './connection.ts';
20
+ /** Cordis plugin name used by loader diagnostics. */
21
+ export declare const name = "mcp-client";
22
+ /** Services required by this plugin. */
23
+ export declare const inject: string[];
24
+ /** Config for connecting to an MCP server via a spawned child process over stdio. */
25
+ export interface StdioConfig {
26
+ /** Selects child-process stdio transport. */
27
+ transport: 'stdio';
28
+ /**
29
+ * Stable local namespace for this server's model-facing tool names
30
+ * (`mcp__<serverName>__<rawName>`). Must match `[A-Za-z0-9_-]{1,32}` and be
31
+ * unique across live mcp-client instances.
32
+ */
33
+ serverName: string;
34
+ /** Executable used to start the server. */
35
+ command: string;
36
+ /** Arguments passed directly, without shell interpolation. */
37
+ args: string[];
38
+ /** Extra env vars merged on top of scrubbed ambient env. */
39
+ env: Record<string, string>;
40
+ /** Working directory for the child process. */
41
+ cwd: string;
42
+ /** Per-tool-call timeout in milliseconds. */
43
+ toolCallTimeoutMs: number;
44
+ /** Fail plugin activation when the initial connection or tool synchronization fails. */
45
+ failOnStartupError: boolean;
46
+ /** Automatic reconnect policy after a lost connection; omission uses the defaults. */
47
+ reconnect?: ReconnectConfig;
48
+ }
49
+ /** Config for connecting to an MCP server over Streamable HTTP (SSE). */
50
+ export interface StreamableHttpConfig {
51
+ /** Selects Streamable HTTP transport. */
52
+ transport: 'streamable-http';
53
+ /**
54
+ * Stable local namespace for this server's model-facing tool names
55
+ * (`mcp__<serverName>__<rawName>`). Must match `[A-Za-z0-9_-]{1,32}` and be
56
+ * unique across live mcp-client instances.
57
+ */
58
+ serverName: string;
59
+ /** MCP endpoint URL. */
60
+ url: string;
61
+ /** Additional non-credential headers attached to MCP requests. */
62
+ headers: Record<string, string>;
63
+ /** Credential reference resolved immediately before each HTTP request and sent as a Bearer token. */
64
+ bearerTokenRef?: string;
65
+ /** Per-tool-call timeout in milliseconds. */
66
+ toolCallTimeoutMs: number;
67
+ /** Fail plugin activation when the initial connection or tool synchronization fails. */
68
+ failOnStartupError: boolean;
69
+ /** Automatic reconnect policy after a lost connection; omission uses the defaults. */
70
+ reconnect?: ReconnectConfig;
71
+ }
72
+ /** Configuration for one stdio or Streamable HTTP MCP server. */
73
+ export type Config = StdioConfig | StreamableHttpConfig;
74
+ type StdioConfigInput = Omit<StdioConfig, 'args' | 'env' | 'cwd' | 'toolCallTimeoutMs' | 'failOnStartupError'> & Partial<Pick<StdioConfig, 'args' | 'env' | 'cwd' | 'toolCallTimeoutMs' | 'failOnStartupError'>>;
75
+ type StreamableHttpConfigInput = Omit<StreamableHttpConfig, 'headers' | 'toolCallTimeoutMs' | 'failOnStartupError'> & Partial<Pick<StreamableHttpConfig, 'headers' | 'toolCallTimeoutMs' | 'failOnStartupError'>>;
76
+ type ConfigInput = StdioConfigInput | StreamableHttpConfigInput;
77
+ export declare const Config: z<ConfigInput, Config>;
78
+ /**
79
+ * Connect one MCP server and publish its initial tool generation before activation.
80
+ * This entry remains explicitly `async`: Cordis treats a prototype-bearing
81
+ * ordinary function as a constructor, whose returned Promise is not startup work.
82
+ * @param ctx - plugin context carrying the tool registry.
83
+ * @param config - resolved transport and server namespace configuration.
84
+ * @returns startup readiness after connection and initial tool discovery settle.
85
+ */
86
+ export declare function apply(ctx: Context, config: Config): Promise<void>;
87
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Package-owned invariant companion for `@sparkelf/dsh-plugin-mcp-credentials`.
3
+ * @module @sparkelf/dsh-plugin-mcp-credentials/invariant
4
+ */
5
+ import type { Context } from '@deepseek-ai/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,56 @@
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 '@deepseek-ai/cordis';
16
+ import type { JsonValue } from '@deepseek-ai/dsh-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 PTC mode without discarding protocol blocks. */
27
+ export type McpResult<Structured extends JsonValue = JsonValue> = {
28
+ content: JsonValue[];
29
+ structuredContent?: Structured;
30
+ };
31
+ /**
32
+ * Sync the MCP server's tool list into the harness ToolRuntime.
33
+ *
34
+ * Two phases keep the swap safe:
35
+ *
36
+ * 1. Fetch: drain uncached `tools/list` pagination and build the full next
37
+ * generation of `ToolDefinition`s under public names. Any failure here
38
+ * (network error, duplicate raw name in the server's list) rejects and
39
+ * leaves the previous generation registered untouched.
40
+ * 2. Swap: dispose the previous generation, register the new one. A registry
41
+ * conflict here can only mean a foreign registration squats on this
42
+ * server's `mcp__<serverName>__` namespace — the partial generation is
43
+ * rolled back (zero tools from this server) and logged. Initial strict
44
+ * synchronization may propagate the conflict so its parent transaction
45
+ * rejects; ordinary clients and later re-syncs return an empty map.
46
+ *
47
+ * @param client - Connected MCP Client instance used to list and call tools.
48
+ * @param ctx - Cordis context providing the `tools` service for registration.
49
+ * @param opts - Bridge options: server namespace and per-call timeout.
50
+ * @param previous - Disposer map from the prior sync generation; disposed
51
+ * during the swap phase (only after the fetch phase succeeded).
52
+ * @returns A map of registered public tool names to their unregister
53
+ * disposers — the exact set of live registrations owned by this server.
54
+ */
55
+ export declare function syncTools(client: Client, ctx: Context, opts: ToolBridgeOptions, previous: ToolDisposers): Promise<ToolDisposers>;
56
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1,19 @@
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 { Context } from '@deepseek-ai/cordis';
10
+ import type { Config } from './index.ts';
11
+ /**
12
+ * Create an MCP transport from the resolved plugin config.
13
+ *
14
+ * @param config - Resolved plugin config discriminated on `transport`.
15
+ * @param ctx - Cordis context required only for credential-backed HTTP auth.
16
+ * @returns A connected-ready MCP Transport (stdio or Streamable HTTP).
17
+ */
18
+ export declare function createTransport(config: Config, ctx: Context): Transport;
19
+ //# sourceMappingURL=transport.d.ts.map
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "dependencies": {
3
+ "@deepseek-ai/schemastery": ">=3.18.1",
4
+ "@modelcontextprotocol/sdk": "^1.12.0",
5
+ "zod": "^4.4.3"
6
+ },
7
+ "description": "Official MCP client replacement with credential-backed Streamable HTTP Bearer authentication",
8
+ "devDependencies": {
9
+ "@deepseek-ai/cordis": "^4.0.1",
10
+ "@deepseek-ai/dsh-attachment": "^0.1.2-alpha.1",
11
+ "@deepseek-ai/dsh-credentials": "^0.1.2-alpha.1",
12
+ "@deepseek-ai/dsh-invariants": "^0.1.2-alpha.1",
13
+ "@deepseek-ai/dsh-llm": "^0.1.2-alpha.1",
14
+ "@deepseek-ai/dsh-scope": "^0.1.2-alpha.1",
15
+ "@deepseek-ai/dsh-subprocess": "^0.1.2-alpha.1",
16
+ "@deepseek-ai/dsh-timeout": "^0.1.2-alpha.1",
17
+ "@deepseek-ai/dsh-tools": "^0.1.2-alpha.1"
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "default": "./lib/index.js",
22
+ "types": "./lib/types/index.d.ts"
23
+ },
24
+ "./invariant": {
25
+ "default": "./lib/invariant.js",
26
+ "types": "./lib/types/invariant.d.ts"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "lib/index.js",
32
+ "lib/invariant.js",
33
+ "lib/types/**/*.d.ts"
34
+ ],
35
+ "license": "MIT",
36
+ "main": "lib/index.js",
37
+ "name": "@sparkelf/dsh-plugin-mcp-credentials",
38
+ "peerDependencies": {
39
+ "@deepseek-ai/cordis": ">=4.0.1",
40
+ "@deepseek-ai/dsh-attachment": ">=0.1.2-alpha.1",
41
+ "@deepseek-ai/dsh-credentials": ">=0.1.2-alpha.1",
42
+ "@deepseek-ai/dsh-invariants": ">=0.1.2-alpha.1",
43
+ "@deepseek-ai/dsh-llm": ">=0.1.2-alpha.1",
44
+ "@deepseek-ai/dsh-scope": ">=0.1.2-alpha.1",
45
+ "@deepseek-ai/dsh-subprocess": ">=0.1.2-alpha.1",
46
+ "@deepseek-ai/dsh-timeout": ">=0.1.2-alpha.1",
47
+ "@deepseek-ai/dsh-tools": ">=0.1.2-alpha.1"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "repository": {
53
+ "directory": "packages/plus/mcp-credentials",
54
+ "type": "git",
55
+ "url": "git+https://github.com/SparkElf/deepseek-harness-plus.git"
56
+ },
57
+ "type": "module",
58
+ "types": "lib/types/index.d.ts",
59
+ "version": "0.1.0-rc.10"
60
+ }