dsh-kjsjs-mcp 0.0.0-stage → 1.0.0

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/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # Custom MCP servers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Manage custom MCP servers over Streamable HTTP on top of the built-in
4
+ `dsh-mcp-manager`.
5
+
6
+ ## Usage
7
+
8
+ Open **Settings → MCP servers**. Add a server with a unique name (its tool
9
+ namespace, `[A-Za-z0-9_-]{1,32}`) and an MCP endpoint URL. Use the **Test**
10
+ button to connect, list tools, and close without enabling. Enable the server to
11
+ mount it; its tools then appear to the model as `mcp__<name>__<tool>`.
12
+
13
+ Headers are entered one per line as `Header: value`. Secret values can reference
14
+ the credentials provider instead of being stored in plain text, e.g.
15
+ `Authorization: Bearer ${credential:MY_TOKEN}`.
16
+
17
+ ## Scope and limitations
18
+
19
+ - Streamable HTTP transport only (the entry shape keeps a `transport` field for
20
+ future stdio support).
21
+ - Servers are stored in the global `dsh-mcp-manager` `servers` configuration,
22
+ so they also appear in the standard MCP settings form and persist in the
23
+ active profile.
24
+ - Connection, reconnect, timeout, and tool registration are handled entirely by
25
+ the built-in `dsh-mcp-client` / `dsh-mcp-manager`; this plugin only provides
26
+ the management surface and the configuration write path.
package/client.js ADDED
@@ -0,0 +1,707 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-kjsjs-mcp',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+ const { useState, useEffect, useCallback } = React;
7
+
8
+ const NS = 'custom-mcp';
9
+
10
+ const en = {
11
+ nav: 'MCP servers',
12
+ title: 'MCP servers',
13
+ intro: 'Manage the Streamable HTTP MCP servers. Their tools appear to the model as mcp__<name>__<tool>.',
14
+ add: 'Add server',
15
+ edit: 'Edit',
16
+ remove: 'Remove',
17
+ test: 'Test',
18
+ restart: 'Restart',
19
+ enable: 'Enable',
20
+ disable: 'Disable',
21
+ name: 'Name',
22
+ url: 'URL',
23
+ headers: 'Headers',
24
+ headersHint: 'One header per line: "Header: value". Secrets can use ${credential:NAME}.',
25
+ enabled: 'Enabled',
26
+ save: 'Save',
27
+ cancel: 'Cancel',
28
+ saving: 'Saving…',
29
+ testing: 'Testing…',
30
+ noServers: 'No MCP servers yet. Paste a config to add one.',
31
+ confirmRemove: 'Remove this server?',
32
+ statusConnected: 'Connected',
33
+ statusConnecting: 'Connecting',
34
+ statusReconnecting: 'Reconnecting',
35
+ statusDisabled: 'Disabled',
36
+ statusFailed: 'Failed',
37
+ statusClosed: 'Closed',
38
+ statusWaitingCredentials: 'Waiting for credentials',
39
+ tools: 'tools',
40
+ probeOk: 'Connected',
41
+ probeFail: 'Test failed',
42
+ loadError: 'Failed to load MCP settings',
43
+ invalidName: 'Name must be 1–32 characters of A–Z a–z 0–9 _ -',
44
+ invalidUrl: 'A URL is required',
45
+ jsonMode: 'Edit JSON',
46
+ formMode: 'Back to form',
47
+ jsonHint: 'Paste the full server entry as JSON. Extra fields such as startupTimeoutMs, toolCallTimeoutMs, and reconnect are supported.',
48
+ jsonInvalid: 'Invalid JSON',
49
+ importTitle: 'Manual configuration',
50
+ importHint: 'Paste MCP server config JSON from an MCP page (the "mcpServers" format). Multiple servers are imported at once.',
51
+ importWarn: 'Confirm the source before configuring.',
52
+ importEmpty: 'Paste a config first.',
53
+ importConfirm: 'Import',
54
+ importPlaceholder: '{\n "mcpServers": {\n "my-server": {\n "url": "http://127.0.0.1:3000/mcp",\n "headers": { "Authorization": "Bearer ..." }\n }\n }\n}',
55
+ editTitle: 'Edit server',
56
+ importInvalid: 'Invalid config: check the JSON and each server entry.',
57
+ imported: 'Imported',
58
+ };
59
+
60
+ const zh = {
61
+ nav: 'MCP 服务器',
62
+ title: 'MCP 服务器',
63
+ intro: '管理 Streamable HTTP MCP 服务器。其工具以 mcp__<名称>__<工具> 的形式提供给模型。',
64
+ add: '添加服务器',
65
+ edit: '编辑',
66
+ remove: '删除',
67
+ test: '测试',
68
+ restart: '重启',
69
+ enable: '启用',
70
+ disable: '停用',
71
+ name: '名称',
72
+ url: '地址',
73
+ headers: '请求头',
74
+ headersHint: '每行一个:"Header: value"。密钥可用 ${credential:名称} 引用。',
75
+ enabled: '启用',
76
+ save: '保存',
77
+ cancel: '取消',
78
+ saving: '保存中…',
79
+ testing: '测试中…',
80
+ noServers: '还没有 MCP 服务器。粘贴一段配置即可添加。',
81
+ confirmRemove: '删除这台服务器?',
82
+ statusConnected: '已连接',
83
+ statusConnecting: '连接中',
84
+ statusReconnecting: '重连中',
85
+ statusDisabled: '已停用',
86
+ statusFailed: '失败',
87
+ statusClosed: '已关闭',
88
+ statusWaitingCredentials: '等待凭据',
89
+ tools: '个工具',
90
+ probeOk: '连接成功',
91
+ probeFail: '测试失败',
92
+ loadError: '加载 MCP 设置失败',
93
+ invalidName: '名称需为 1–32 位 A–Z a–z 0–9 _ -',
94
+ invalidUrl: '需要填写地址',
95
+ jsonMode: '编辑 JSON',
96
+ formMode: '返回表单',
97
+ jsonHint: '粘贴完整服务器配置 JSON。支持额外字段(startupTimeoutMs、toolCallTimeoutMs、reconnect…)。',
98
+ jsonInvalid: 'JSON 无效',
99
+ importTitle: '手动配置',
100
+ importHint: '请从 MCP Servers 的介绍页面复制配置 JSON(mcpServers 格式,可一次导入多个),粘贴到输入框中。',
101
+ importWarn: '配置前请确认来源,甄别风险。',
102
+ importEmpty: '请先粘贴配置。',
103
+ importConfirm: '确认',
104
+ importPlaceholder: '{\n "mcpServers": {\n "my-server": {\n "url": "http://127.0.0.1:3000/mcp",\n "headers": { "Authorization": "Bearer ..." }\n }\n }\n}',
105
+ editTitle: '编辑服务器',
106
+ importInvalid: '配置无效:请检查 JSON 和每台服务器的字段。',
107
+ imported: '已导入',
108
+ };
109
+
110
+ const CSS = `
111
+ .cmm-section{max-width:720px;display:flex;flex-direction:column;gap:12px;color:var(--dsw-alias-label-primary)}
112
+ .cmm-title{margin:0;font-size:16px;font-weight:500;line-height:24px;color:var(--dsw-alias-label-primary)}
113
+ .cmm-intro{margin:0;font-size:14px;line-height:22px;color:var(--dsw-alias-label-tertiary)}
114
+ .cmm-msg{margin:0;font-size:12px;line-height:18px}
115
+ .cmm-msg--error{color:var(--dsw-alias-state-error-primary)}
116
+ .cmm-msg--ok{color:var(--dsw-alias-state-success-primary)}
117
+ .cmm-rows{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
118
+ .cmm-empty{border:1px dashed var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-lg);padding:16px;font-size:13px;line-height:20px;color:var(--dsw-alias-label-tertiary);text-align:center}
119
+ .cmm-row{border:.5px solid var(--dsw-alias-settings-card-stroke);background:var(--dsw-alias-settings-card-fill);border-radius:var(--dsw-radius-xl);padding:10px 14px;display:flex;align-items:center;gap:12px}
120
+ .cmm-avatar{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;flex:none;width:28px;height:28px;border-radius:var(--dsw-radius-sm);color:#fff;font-size:13px;font-weight:600;line-height:1}
121
+ .cmm-rowMain{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}
122
+ .cmm-rowTitle{display:flex;align-items:center;gap:8px;min-width:0;flex-wrap:wrap}
123
+ .cmm-name{font-size:14px;font-weight:500;line-height:22px;color:var(--dsw-alias-label-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
124
+ .cmm-rowUrl{font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
125
+ .cmm-pill{flex:none;padding:1px 7px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-xs);font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary)}
126
+ .cmm-pill--success{color:var(--dsw-alias-state-success-primary);border-color:var(--dsw-alias-state-success-primary)}
127
+ .cmm-pill--warn{color:var(--dsw-alias-state-warn-primary);border-color:var(--dsw-alias-state-warn-primary)}
128
+ .cmm-pill--error{color:var(--dsw-alias-state-error-primary);border-color:var(--dsw-alias-state-error-primary)}
129
+ .cmm-pill--idle{color:var(--dsw-alias-label-tertiary)}
130
+ .cmm-rowActions{display:inline-flex;align-items:center;gap:4px;flex:none}
131
+ .cmm-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;border:none;border-radius:var(--dsw-radius-sm);font:inherit;cursor:pointer;background:transparent;color:var(--dsw-alias-label-primary)}
132
+ .cmm-btn--secondary{height:28px;padding:0 10px;font-size:12px;line-height:18px;border:.5px solid var(--dsw-alias-border-l3)}
133
+ .cmm-btn--danger{height:28px;padding:0 10px;font-size:12px;line-height:18px;color:var(--dsw-alias-state-error-primary)}
134
+ .cmm-btn--primary{height:32px;padding:0 14px;font-size:13px;line-height:20px;background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-foreground)}
135
+ .cmm-btn--add{height:44px;width:100%;border:1px dashed var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-lg);color:var(--dsw-alias-label-primary);font-size:13px}
136
+ .cmm-btn:disabled{opacity:.4;cursor:default}
137
+ @media (hover:hover){
138
+ .cmm-btn--secondary:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover-solid)}
139
+ .cmm-btn--danger:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover-danger)}
140
+ .cmm-btn--primary:hover:not(:disabled){background:var(--dsw-alias-button-primary-hover)}
141
+ .cmm-btn--add:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}
142
+ }
143
+ .cmm-iconBtn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;flex:none;width:28px;height:28px;padding:0;border:none;border-radius:var(--dsw-radius-sm);background:transparent;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:16px;line-height:1;cursor:pointer}
144
+ @media (hover:hover){.cmm-iconBtn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}}
145
+ .cmm-switch{box-sizing:border-box;position:relative;flex:none;width:36px;height:20px;padding:0;border:none;border-radius:10px;background:var(--dsw-alias-state-idle-primary);cursor:pointer;transition:background .15s}
146
+ .cmm-switch--on{background:var(--dsw-alias-state-success-primary)}
147
+ .cmm-switchThumb{position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .15s}
148
+ .cmm-switch--on .cmm-switchThumb{transform:translateX(16px)}
149
+ .cmm-switch:disabled{opacity:.4;cursor:default}
150
+ .cmm-field{display:flex;flex-direction:column;gap:6px}
151
+ .cmm-label{font-size:12px;line-height:18px;font-weight:500;color:var(--dsw-alias-label-secondary)}
152
+ .cmm-input{box-sizing:border-box;width:100%;padding:0 10px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md);font:inherit;font-size:13px;line-height:20px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary)}
153
+ input.cmm-input{height:32px}
154
+ textarea.cmm-input{padding:8px 10px;resize:vertical;font-family:inherit}
155
+ textarea.cmm-code{font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Menlo,Consolas,monospace);font-size:12px;line-height:18px;tab-size:2}
156
+ .cmm-input:focus{outline:none;border-color:var(--dsw-alias-state-business-primary)}
157
+ .cmm-input:disabled{opacity:.6}
158
+ .cmm-hint{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary)}
159
+ .cmm-check{display:inline-flex;align-items:center;gap:6px;font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary)}
160
+ .cmm-overlay{position:fixed;inset:0;z-index:1000;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.32);padding:24px}
161
+ .cmm-modal{width:min(680px,100%);max-height:calc(100vh - 48px);display:flex;flex-direction:column;background:var(--dsw-alias-bg-overlay);border-radius:var(--dsw-radius-xl);box-shadow:0 12px 48px rgba(0,0,0,.24);overflow:hidden}
162
+ .cmm-modalHead{display:flex;align-items:center;gap:12px;padding:14px 18px;border-bottom:.5px solid var(--dsw-alias-border-l2)}
163
+ .cmm-modalTitle{flex:1;font-size:15px;font-weight:600;line-height:22px;color:var(--dsw-alias-label-primary)}
164
+ .cmm-modalBody{padding:18px;overflow:auto;display:flex;flex-direction:column;gap:14px}
165
+ .cmm-modalFooter{display:flex;align-items:center;gap:8px;padding:12px 18px;border-top:.5px solid var(--dsw-alias-border-l2)}
166
+ .cmm-spacer{flex:1}
167
+ .cmm-warn{font-size:12px;line-height:18px;color:var(--dsw-alias-state-warn-primary)}
168
+ @media (prefers-reduced-motion:reduce){.cmm-switch,.cmm-switchThumb{transition:none}}
169
+ `;
170
+
171
+ if (typeof document !== 'undefined') {
172
+ let tag = document.querySelector('style[data-cmm]');
173
+ if (!tag) {
174
+ tag = document.createElement('style');
175
+ tag.setAttribute('data-cmm', '');
176
+ document.head.appendChild(tag);
177
+ }
178
+ tag.textContent = CSS;
179
+ }
180
+
181
+ const NAME_RE = /^[A-Za-z0-9_-]{1,32}$/;
182
+ const AVATAR_COLORS = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae', '#1890ff', '#52c41a', '#eb2f96', '#722ed1', '#fa541c', '#13c2c2'];
183
+
184
+ function avatarColor(name) {
185
+ let hash = 0;
186
+ for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) | 0;
187
+ return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
188
+ }
189
+
190
+ function resultOf(res) {
191
+ if (res && typeof res === 'object' && 'ok' in res) return res;
192
+ return { ok: true, value: res };
193
+ }
194
+
195
+ function createOps(ctx) {
196
+ const settings = ctx.remote.settings;
197
+ const mcp = ctx.remote.mcpManager;
198
+
199
+ async function describe() {
200
+ const r = resultOf(await settings.describe());
201
+ if (!r.ok) throw new Error((r.error && r.error.message) || 'settings.describe failed');
202
+ return r.value;
203
+ }
204
+
205
+ function findManager(namespaces) {
206
+ const list = namespaces || [];
207
+ // This plugin's own servers config (its profile entry id).
208
+ const own = list.find(ns => ns.ns === 'custom-mcp-manager');
209
+ if (own !== undefined) return own;
210
+ // Fallback: any namespace whose schema exposes a volatile servers map.
211
+ for (const ns of list) {
212
+ const s = ns.schema;
213
+ if (s && typeof s === 'object' && s.properties && s.properties.servers) return ns;
214
+ }
215
+ return null;
216
+ }
217
+
218
+ async function loadConfig() {
219
+ const d = await describe();
220
+ const ns = findManager(d.namespaces);
221
+ if (!ns) return { ns: null, revision: undefined, servers: {} };
222
+ const servers = (ns.value && ns.value.servers) || {};
223
+ return { ns: ns.ns, revision: ns.revision, servers };
224
+ }
225
+
226
+ async function write(ops, revision) {
227
+ const cfg = await loadConfig();
228
+ if (!cfg.ns) throw new Error('MCP servers config not found in settings');
229
+ const r = resultOf(await settings.mutate(cfg.ns, ops, revision));
230
+ if (!r.ok) {
231
+ const err = new Error((r.error && r.error.message) || 'settings write failed');
232
+ err.code = r.error && r.error.code;
233
+ throw err;
234
+ }
235
+ return r.value;
236
+ }
237
+
238
+ return {
239
+ loadConfig,
240
+ save(name, entry, revision) {
241
+ return write([{ op: 'set', path: ['servers', name], value: entry }], revision);
242
+ },
243
+ remove(name, revision) {
244
+ return write([{ op: 'unset', path: ['servers', name] }], revision);
245
+ },
246
+ setEnabled(name, enabled, revision) {
247
+ return write([{ op: 'set', path: ['servers', name, 'enabled'], value: enabled }], revision);
248
+ },
249
+ saveMany(map, revision) {
250
+ const ops = Object.keys(map).map(name => ({ op: 'set', path: ['servers', name], value: map[name] }));
251
+ return write(ops, revision);
252
+ },
253
+ async probe(name) {
254
+ const r = resultOf(await mcp.probe(name));
255
+ return r.ok ? r.value
256
+ : { ok: false, stage: 'connect', message: (r.error && r.error.message) || 'probe failed', closeConfirmed: false };
257
+ },
258
+ async restart(name) {
259
+ const r = resultOf(await mcp.restart(name));
260
+ if (!r.ok) throw new Error((r.error && r.error.message) || 'restart failed');
261
+ },
262
+ watch(onList, onError) {
263
+ const ac = new AbortController();
264
+ (async () => {
265
+ try {
266
+ for await (const chunk of mcp.watch(ac.signal)) {
267
+ onList(Array.isArray(chunk) ? chunk : []);
268
+ }
269
+ } catch (e) {
270
+ if (!ac.signal.aborted) onError(e);
271
+ }
272
+ })();
273
+ return () => ac.abort();
274
+ },
275
+ };
276
+ }
277
+
278
+ function buildEntry(d, t) {
279
+ if (d.mode === 'json') {
280
+ let parsed;
281
+ try {
282
+ parsed = JSON.parse(d.jsonText || '{}');
283
+ } catch (e) {
284
+ throw new Error(t('jsonInvalid') + ': ' + (e && e.message || e));
285
+ }
286
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(t('jsonInvalid'));
287
+ const url = (parsed.url || '').toString().trim();
288
+ if (!url) throw new Error(t('invalidUrl'));
289
+ return { transport: 'streamable-http', ...parsed, url };
290
+ }
291
+ const url = (d.url || '').trim();
292
+ if (!url) throw new Error(t('invalidUrl'));
293
+ return { transport: 'streamable-http', url, headers: parseHeaders(d.headersText), enabled: !!d.enabled };
294
+ }
295
+
296
+ function parseImport(text, t) {
297
+ let parsed;
298
+ try {
299
+ parsed = JSON.parse(text);
300
+ } catch (e) {
301
+ throw new Error(t('jsonInvalid') + ': ' + (e && e.message || e));
302
+ }
303
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(t('jsonInvalid'));
304
+ const map = parsed.mcpServers && typeof parsed.mcpServers === 'object' && !Array.isArray(parsed.mcpServers)
305
+ ? parsed.mcpServers
306
+ : parsed;
307
+ const out = {};
308
+ for (const name of Object.keys(map)) {
309
+ if (!NAME_RE.test(name)) throw new Error(t('invalidName') + ': ' + name);
310
+ const entry = map[name];
311
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) throw new Error(t('importInvalid'));
312
+ const url = (entry.url || '').toString().trim();
313
+ const command = (entry.command || '').toString().trim();
314
+ if (!url && !command) throw new Error(t('importInvalid') + ': ' + name);
315
+ out[name] = url
316
+ ? { transport: 'streamable-http', ...entry, url }
317
+ : { transport: 'stdio', ...entry };
318
+ }
319
+ if (Object.keys(out).length === 0) throw new Error(t('importInvalid'));
320
+ return out;
321
+ }
322
+
323
+ function parseHeaders(text) {
324
+ const out = {};
325
+ if (!text) return out;
326
+ for (const line of String(text).split('\n')) {
327
+ const s = line.trim();
328
+ if (!s) continue;
329
+ const idx = s.indexOf(':');
330
+ if (idx <= 0) continue;
331
+ const key = s.slice(0, idx).trim();
332
+ const val = s.slice(idx + 1).trim();
333
+ if (key) out[key] = val;
334
+ }
335
+ return out;
336
+ }
337
+
338
+ function headersToText(headers) {
339
+ if (!headers) return '';
340
+ return Object.keys(headers).map(k => k + ': ' + headers[k]).join('\n');
341
+ }
342
+
343
+ function statusInfo(status, t) {
344
+ if (!status) return { text: '', tone: 'idle' };
345
+ switch (status.state) {
346
+ case 'connected': return { text: t('statusConnected'), tone: 'success' };
347
+ case 'connecting': return { text: t('statusConnecting'), tone: 'warn' };
348
+ case 'reconnecting': return { text: t('statusReconnecting'), tone: 'warn' };
349
+ case 'disabled': return { text: t('statusDisabled'), tone: 'idle' };
350
+ case 'failed': return { text: t('statusFailed'), tone: 'error' };
351
+ case 'closed': return { text: t('statusClosed'), tone: 'idle' };
352
+ case 'waiting-credentials': return { text: t('statusWaitingCredentials'), tone: 'warn' };
353
+ default: return { text: status.state, tone: 'idle' };
354
+ }
355
+ }
356
+
357
+ function Modal(props) {
358
+ const { title, onClose, children, footer } = props;
359
+ useEffect(() => {
360
+ const onKey = e => { if (e.key === 'Escape') onClose(); };
361
+ document.addEventListener('keydown', onKey);
362
+ return () => document.removeEventListener('keydown', onKey);
363
+ }, [onClose]);
364
+ return h('div', {
365
+ className: 'cmm-overlay',
366
+ onMouseDown: e => { if (e.target === e.currentTarget) onClose(); },
367
+ },
368
+ h('div', { className: 'cmm-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': title },
369
+ h('div', { className: 'cmm-modalHead' },
370
+ h('span', { className: 'cmm-modalTitle' }, title),
371
+ h('button', { type: 'button', className: 'cmm-iconBtn', onClick: onClose, 'aria-label': 'Close' }, '×'),
372
+ ),
373
+ h('div', { className: 'cmm-modalBody' }, children),
374
+ footer ? h('div', { className: 'cmm-modalFooter' }, footer) : null,
375
+ ),
376
+ );
377
+ }
378
+
379
+ function Toggle(props) {
380
+ return h('button', {
381
+ type: 'button',
382
+ role: 'switch',
383
+ 'aria-checked': props.checked,
384
+ className: 'cmm-switch' + (props.checked ? ' cmm-switch--on' : ''),
385
+ disabled: props.disabled,
386
+ onClick: () => props.onChange(!props.checked),
387
+ }, h('span', { className: 'cmm-switchThumb' }));
388
+ }
389
+
390
+ function Section(props) {
391
+ const ops = props.ops;
392
+ const t = props.t;
393
+
394
+ const [config, setConfig] = useState({ ns: null, revision: undefined, servers: {} });
395
+ const [views, setViews] = useState([]);
396
+ const [probes, setProbes] = useState({});
397
+ const [busy, setBusy] = useState(null);
398
+ const [message, setMessage] = useState(null);
399
+ const [modal, setModal] = useState(null);
400
+ const [importText, setImportText] = useState('');
401
+ const [draft, setDraft] = useState(null);
402
+
403
+ const load = useCallback(async () => {
404
+ try {
405
+ const c = await ops.loadConfig();
406
+ setConfig(c);
407
+ } catch (e) {
408
+ setMessage({ kind: 'error', text: t('loadError') + ': ' + (e && e.message || e) });
409
+ }
410
+ }, [ops, t]);
411
+
412
+ useEffect(() => {
413
+ load();
414
+ const dispose = ops.watch(setViews, e => setMessage({ kind: 'error', text: String(e && e.message || e) }));
415
+ return dispose;
416
+ }, [ops, load]);
417
+
418
+ const refetch = useCallback(async () => {
419
+ const c = await ops.loadConfig();
420
+ setConfig(c);
421
+ return c;
422
+ }, [ops]);
423
+
424
+ const viewOf = name => views.find(v => v.name === name) || null;
425
+
426
+ function showError(e) {
427
+ if (e && e.code === 'settings/conflict') {
428
+ refetch();
429
+ setMessage({ kind: 'error', text: (e.message || 'configuration changed, retry') });
430
+ } else {
431
+ setMessage({ kind: 'error', text: (e && e.message) || String(e) });
432
+ }
433
+ }
434
+
435
+ function closeModal() {
436
+ setModal(null);
437
+ setDraft(null);
438
+ setImportText('');
439
+ }
440
+
441
+ async function doToggle(name, enabled) {
442
+ setBusy('toggle:' + name);
443
+ try {
444
+ await ops.setEnabled(name, enabled, config.revision);
445
+ await refetch();
446
+ } catch (e) {
447
+ showError(e);
448
+ } finally { setBusy(null); }
449
+ }
450
+
451
+ async function doProbe(name) {
452
+ setBusy('probe:' + name);
453
+ try {
454
+ const res = await ops.probe(name);
455
+ setProbes(p => ({ ...p, [name]: res }));
456
+ setMessage(null);
457
+ } catch (e) {
458
+ showError(e);
459
+ } finally { setBusy(null); }
460
+ }
461
+
462
+ async function doImport() {
463
+ const text = (importText || '').trim();
464
+ if (!text) {
465
+ setMessage({ kind: 'error', text: t('importEmpty') });
466
+ return;
467
+ }
468
+ let map;
469
+ try {
470
+ map = parseImport(text, t);
471
+ } catch (e) {
472
+ setMessage({ kind: 'error', text: (e && e.message) || String(e) });
473
+ return;
474
+ }
475
+ setBusy('import');
476
+ try {
477
+ await ops.saveMany(map, config.revision);
478
+ await refetch();
479
+ closeModal();
480
+ setMessage({ kind: 'ok', text: t('imported') + ' · ' + Object.keys(map).length });
481
+ } catch (e) {
482
+ showError(e);
483
+ } finally { setBusy(null); }
484
+ }
485
+
486
+ async function doSave() {
487
+ if (!draft) return;
488
+ const name = (draft.name || '').trim();
489
+ if (!NAME_RE.test(name)) { setMessage({ kind: 'error', text: t('invalidName') }); return; }
490
+ let entry;
491
+ try {
492
+ entry = buildEntry(draft, t);
493
+ } catch (e) {
494
+ setMessage({ kind: 'error', text: (e && e.message) || String(e) });
495
+ return;
496
+ }
497
+ setBusy('save');
498
+ try {
499
+ await ops.save(name, entry, config.revision);
500
+ await refetch();
501
+ closeModal();
502
+ setMessage(null);
503
+ } catch (e) {
504
+ showError(e);
505
+ } finally { setBusy(null); }
506
+ }
507
+
508
+ async function doSaveAndTest() {
509
+ if (!draft) return;
510
+ const name = (draft.name || '').trim();
511
+ if (!NAME_RE.test(name)) { setMessage({ kind: 'error', text: t('invalidName') }); return; }
512
+ let entry;
513
+ try {
514
+ entry = buildEntry(draft, t);
515
+ } catch (e) {
516
+ setMessage({ kind: 'error', text: (e && e.message) || String(e) });
517
+ return;
518
+ }
519
+ setBusy('test');
520
+ try {
521
+ await ops.save(name, entry, config.revision);
522
+ await refetch();
523
+ const res = await ops.probe(name);
524
+ setProbes(p => ({ ...p, [name]: res }));
525
+ } catch (e) {
526
+ showError(e);
527
+ } finally { setBusy(null); }
528
+ }
529
+
530
+ async function doRemove(name) {
531
+ if (!window.confirm(t('confirmRemove'))) return;
532
+ setBusy('remove:' + name);
533
+ try {
534
+ await ops.remove(name, config.revision);
535
+ await refetch();
536
+ closeModal();
537
+ } catch (e) {
538
+ showError(e);
539
+ } finally { setBusy(null); }
540
+ }
541
+
542
+ function openEdit(name) {
543
+ const entry = config.servers[name] || {};
544
+ setDraft({
545
+ name,
546
+ url: entry.url || '',
547
+ headersText: headersToText(entry.headers),
548
+ enabled: entry.enabled !== false,
549
+ isNew: false,
550
+ mode: 'form',
551
+ jsonText: JSON.stringify(entry, null, 2),
552
+ });
553
+ setMessage(null);
554
+ setModal({ kind: 'edit', name });
555
+ }
556
+
557
+ function openAdd() {
558
+ setImportText('');
559
+ setMessage(null);
560
+ setModal({ kind: 'add' });
561
+ }
562
+
563
+ function toggleMode() {
564
+ if (!draft) return;
565
+ if (draft.mode === 'json') {
566
+ let parsed;
567
+ try {
568
+ parsed = JSON.parse(draft.jsonText || '{}');
569
+ } catch (e) {
570
+ setMessage({ kind: 'error', text: t('jsonInvalid') + ': ' + (e && e.message || e) });
571
+ return;
572
+ }
573
+ setDraft({ ...draft, mode: 'form', url: parsed.url || '', headersText: headersToText(parsed.headers), enabled: parsed.enabled !== false });
574
+ } else {
575
+ const entry = { transport: 'streamable-http', url: draft.url || '', headers: parseHeaders(draft.headersText || ''), enabled: !!draft.enabled };
576
+ setDraft({ ...draft, mode: 'json', jsonText: JSON.stringify(entry, null, 2) });
577
+ }
578
+ }
579
+
580
+ const names = Object.keys(config.servers || {});
581
+
582
+ const rows = names.map(name => {
583
+ const entry = config.servers[name] || {};
584
+ const view = viewOf(name);
585
+ const enabled = entry.enabled !== false;
586
+ const status = view ? view.status : (enabled ? { state: 'connecting' } : { state: 'disabled' });
587
+ const info = statusInfo(status, t);
588
+ return h('li', { key: name, className: 'cmm-row' },
589
+ h('span', { className: 'cmm-avatar', style: { background: avatarColor(name) } }, (name[0] || '?').toUpperCase()),
590
+ h('span', { className: 'cmm-rowMain' },
591
+ h('span', { className: 'cmm-rowTitle' },
592
+ h('span', { className: 'cmm-name' }, name),
593
+ h('span', { className: 'cmm-pill cmm-pill--' + info.tone }, info.text),
594
+ status.state === 'connected' ? h('span', { className: 'cmm-pill cmm-pill--idle' }, status.toolCount + ' ' + t('tools')) : null,
595
+ ),
596
+ h('span', { className: 'cmm-rowUrl' }, entry.url || ''),
597
+ ),
598
+ h('span', { className: 'cmm-rowActions' },
599
+ h('button', { type: 'button', className: 'cmm-btn cmm-btn--secondary', disabled: busy === ('probe:' + name), onClick: () => doProbe(name) }, busy === ('probe:' + name) ? t('testing') : t('test')),
600
+ h('button', { type: 'button', className: 'cmm-btn cmm-btn--secondary', onClick: () => openEdit(name) }, t('edit')),
601
+ h(Toggle, { checked: enabled, disabled: busy === ('toggle:' + name), onChange: v => doToggle(name, v) }),
602
+ ),
603
+ );
604
+ });
605
+
606
+ function editorFields(d) {
607
+ const isJson = d.mode === 'json';
608
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 14 } },
609
+ h('div', { className: 'cmm-field' },
610
+ h('span', { className: 'cmm-label' }, t('name')),
611
+ h('input', { className: 'cmm-input', value: d.name, disabled: !d.isNew, placeholder: 'my-server', onChange: e => setDraft({ ...d, name: e.target.value }) }),
612
+ ),
613
+ isJson
614
+ ? h('div', { className: 'cmm-field' },
615
+ h('span', { className: 'cmm-label' }, 'JSON'),
616
+ h('textarea', { className: 'cmm-input cmm-code', value: d.jsonText, rows: 10, spellCheck: false, onChange: e => setDraft({ ...d, jsonText: e.target.value }) }),
617
+ h('span', { className: 'cmm-hint' }, t('jsonHint')),
618
+ )
619
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: 14 } },
620
+ h('div', { className: 'cmm-field' },
621
+ h('span', { className: 'cmm-label' }, t('url')),
622
+ h('input', { className: 'cmm-input', value: d.url, placeholder: 'http://127.0.0.1:3000/mcp', onChange: e => setDraft({ ...d, url: e.target.value }) }),
623
+ ),
624
+ h('div', { className: 'cmm-field' },
625
+ h('span', { className: 'cmm-label' }, t('headers')),
626
+ h('textarea', { className: 'cmm-input', value: d.headersText, rows: 4, spellCheck: false, placeholder: 'Authorization: Bearer ...', onChange: e => setDraft({ ...d, headersText: e.target.value }) }),
627
+ h('span', { className: 'cmm-hint' }, t('headersHint')),
628
+ ),
629
+ h('label', { className: 'cmm-check' },
630
+ h('input', { type: 'checkbox', checked: !!d.enabled, onChange: e => setDraft({ ...d, enabled: e.target.checked }) }),
631
+ t('enabled'),
632
+ ),
633
+ ),
634
+ h('div', null,
635
+ h('button', { type: 'button', className: 'cmm-btn cmm-btn--secondary', onClick: toggleMode }, isJson ? t('formMode') : t('jsonMode')),
636
+ ),
637
+ );
638
+ }
639
+
640
+ return h('div', { className: 'cmm-section' },
641
+ h('h2', { className: 'cmm-title' }, t('title')),
642
+ h('p', { className: 'cmm-intro' }, t('intro')),
643
+ message && !modal ? h('p', { className: 'cmm-msg ' + (message.kind === 'ok' ? 'cmm-msg--ok' : 'cmm-msg--error'), role: 'alert' }, message.text) : null,
644
+ names.length > 0
645
+ ? h('ul', { className: 'cmm-rows' }, rows)
646
+ : h('div', { className: 'cmm-empty' }, t('noServers')),
647
+ h('button', { type: 'button', className: 'cmm-btn cmm-btn--add', onClick: openAdd }, t('add')),
648
+
649
+ modal && modal.kind === 'add'
650
+ ? h(Modal, {
651
+ title: t('importTitle'),
652
+ onClose: closeModal,
653
+ footer: [
654
+ h('span', { key: 'warn', className: 'cmm-warn' }, '⚠ ' + t('importWarn')),
655
+ h('span', { key: 'spacer', className: 'cmm-spacer' }),
656
+ h('button', { key: 'cancel', type: 'button', className: 'cmm-btn cmm-btn--secondary', onClick: closeModal }, t('cancel')),
657
+ h('button', { key: 'ok', type: 'button', className: 'cmm-btn cmm-btn--primary', disabled: !importText.trim() || busy === 'import', onClick: doImport }, busy === 'import' ? t('saving') : t('importConfirm')),
658
+ ],
659
+ },
660
+ message && message.kind === 'error' ? h('p', { className: 'cmm-msg cmm-msg--error', role: 'alert' }, message.text) : null,
661
+ h('p', { className: 'cmm-hint' }, t('importHint')),
662
+ h('textarea', {
663
+ className: 'cmm-input cmm-code',
664
+ style: { minHeight: 320, resize: 'vertical' },
665
+ value: importText,
666
+ spellCheck: false,
667
+ placeholder: t('importPlaceholder'),
668
+ onChange: e => { setImportText(e.target.value); if (message) setMessage(null); },
669
+ }),
670
+ )
671
+ : null,
672
+
673
+ modal && modal.kind === 'edit'
674
+ ? h(Modal, {
675
+ title: t('editTitle') + ' · ' + modal.name,
676
+ onClose: closeModal,
677
+ footer: [
678
+ h('button', { key: 'remove', type: 'button', className: 'cmm-btn cmm-btn--danger', disabled: busy === ('remove:' + modal.name), onClick: () => doRemove(modal.name) }, t('remove')),
679
+ h('span', { key: 'spacer', className: 'cmm-spacer' }),
680
+ h('button', { key: 'test', type: 'button', className: 'cmm-btn cmm-btn--secondary', disabled: busy === 'test', onClick: doSaveAndTest }, busy === 'test' ? t('testing') : t('test')),
681
+ h('button', { key: 'save', type: 'button', className: 'cmm-btn cmm-btn--primary', disabled: busy === 'save', onClick: doSave }, busy === 'save' ? t('saving') : t('save')),
682
+ ],
683
+ },
684
+ message && message.kind === 'error' ? h('p', { className: 'cmm-msg cmm-msg--error', role: 'alert' }, message.text) : null,
685
+ draft ? editorFields(draft) : null,
686
+ )
687
+ : null,
688
+ );
689
+ }
690
+
691
+ return {
692
+ inject: ['slots', 'locale', 'remote', 'remote.settings', 'remote.mcpManager'],
693
+ apply(ctx) {
694
+ ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'custom-mcp: locale dictionaries');
695
+ const t = ctx.locale.bind(NS);
696
+ const ops = createOps(ctx);
697
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
698
+ name: 'settings.section',
699
+ id: 'custom-mcp',
700
+ order: 60,
701
+ label: () => t('nav'),
702
+ inject: () => ({ ops, t }),
703
+ }, Section));
704
+ },
705
+ };
706
+ },
707
+ });
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: custom-mcp-manager
3
+ name: 'dsh-kjsjs-mcp'
package/icon.svg ADDED
@@ -0,0 +1,9 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
2
+ <rect x="10" y="8" width="16" height="20" rx="3" fill="#247bbf"/>
3
+ <circle cx="18" cy="14" r="2" fill="#ffffff"/>
4
+ <circle cx="18" cy="22" r="2" fill="#ffffff"/>
5
+ <circle cx="18" cy="4" r="2.5" fill="#3da86a"/>
6
+ <line x1="18" y1="6.5" x2="18" y2="8" stroke="#3da86a" stroke-width="1.5"/>
7
+ <circle cx="18" cy="32" r="2.5" fill="#3da86a"/>
8
+ <line x1="18" y1="28" x2="18" y2="29.5" stroke="#3da86a" stroke-width="1.5"/>
9
+ </svg>
package/index.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Host half of the custom MCP manager bundle.
3
+ *
4
+ * The plugin owns one `servers` config (a profile user-patch entry, so Settings
5
+ * can edit it). On every config change it reconciles the fleet by registering
6
+ * each enabled server with the built-in `ctx.mcpManager`, which mounts the
7
+ * `dsh-mcp-client` instance, connects, and publishes the tools. The client
8
+ * half only writes that config and reads manager status/probe/restart.
9
+ */
10
+ import z from '@deepseek-ai/schemastery'
11
+
12
+ /** One managed server entry; flat like the manager's, validated cross-field by the manager. */
13
+ const ServerEntrySchema = z.object({
14
+ transport: z.union(['stdio', 'streamable-http']).default('streamable-http'),
15
+ url: z.string().default(''),
16
+ headers: z.dict(String).default({}),
17
+ command: z.string().default(''),
18
+ args: z.array(String).default([]),
19
+ env: z.dict(String).default({}),
20
+ cwd: z.string().default(''),
21
+ enabled: z.boolean().default(true),
22
+ startupTimeoutMs: z.number().min(1).default(30000),
23
+ })
24
+
25
+ export const Config = z.object({
26
+ servers: z.dict(ServerEntrySchema).default({}).volatile(),
27
+ })
28
+
29
+ export const inject = ['mcpManager']
30
+
31
+ /**
32
+ * Detach one entry from its frozen config snapshot. The manager's `register`
33
+ * parses the entry through its own schema, which assigns defaults into nested
34
+ * objects; a frozen `headers` map from the volatile snapshot would throw
35
+ * "Cannot assign to read only property". A JSON round-trip also drops
36
+ * `undefined` members so the manager's defaults apply.
37
+ * @param entry - one server config entry.
38
+ * @returns a plain, writable copy.
39
+ */
40
+ function detach(entry) {
41
+ return JSON.parse(JSON.stringify(entry))
42
+ }
43
+
44
+ export function apply(ctx, config) {
45
+ /** name → { dispose, snapshot } for every server registered on this plugin's life. */
46
+ const registered = new Map()
47
+ let reconciling = false
48
+
49
+ const reconcile = (reason) => {
50
+ if (reconciling) return
51
+ reconciling = true
52
+ try {
53
+ const servers = config.servers.get() || {}
54
+ // Drop entries that disappeared or were disabled.
55
+ for (const [name, record] of [...registered]) {
56
+ const entry = servers[name]
57
+ if (!entry || entry.enabled === false) {
58
+ try { record.dispose() } catch (error) { ctx.logger.warn('custom-mcp: dispose "%s" failed: %s', name, error && error.message) }
59
+ registered.delete(name)
60
+ ctx.logger.info('custom-mcp: unregistered "%s" (%s)', name, reason)
61
+ }
62
+ }
63
+ // Register new entries and rebuild changed ones (whole-entry identity).
64
+ for (const [name, entry] of Object.entries(servers)) {
65
+ if (!entry || entry.enabled === false) continue
66
+ const snapshot = JSON.stringify(entry)
67
+ const record = registered.get(name)
68
+ if (record && record.snapshot === snapshot) continue
69
+ if (record) {
70
+ try { record.dispose() } catch (error) { ctx.logger.warn('custom-mcp: dispose "%s" failed: %s', name, error && error.message) }
71
+ registered.delete(name)
72
+ }
73
+ try {
74
+ const { enabled, ...registration } = detach(entry)
75
+ registered.set(name, { dispose: ctx.mcpManager.register(name, registration), snapshot })
76
+ ctx.logger.info('custom-mcp: registered "%s" (%s)', name, reason)
77
+ } catch (error) {
78
+ ctx.logger.warn('custom-mcp: register "%s" failed: %s', name, error && error.message)
79
+ }
80
+ }
81
+ } finally {
82
+ reconciling = false
83
+ }
84
+ }
85
+
86
+ ctx.effect(() => () => {
87
+ for (const record of registered.values()) {
88
+ try { record.dispose() } catch { /* disposal is best effort */ }
89
+ }
90
+ registered.clear()
91
+ }, 'custom-mcp: server registrations')
92
+
93
+ reconcile('initial')
94
+
95
+ // A Settings write updates the volatile config in place; reconcile on that,
96
+ // and once more on the ordinary reload path.
97
+ ctx.on('loader/volatile-update', () => { reconcile('volatile update') })
98
+ ctx.on('internal/config', (fiber, next) => {
99
+ const raw = next()
100
+ if (fiber === ctx.fiber) reconcile('config change')
101
+ return raw
102
+ })
103
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Custom MCP servers",
4
+ "description": "Manage custom MCP servers over Streamable HTTP. Add, edit, test, enable, disable, restart, and remove servers from Settings; their tools appear to the model as mcp__<name>__<tool>. Credentials can be referenced as ${credential:NAME} header templates."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "自定义 MCP 服务器",
4
+ "description": "管理自定义 MCP 服务器(Streamable HTTP)。在设置中新增、编辑、测试、启用、停用、重启、删除服务器;其工具以 mcp__<名称>__<工具> 的形式提供给模型。请求头可用 ${credential:名称} 引用凭据。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "dsh-kjsjs-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Manage custom MCP servers over Streamable HTTP: add, edit, test, enable, disable, restart, and remove servers from Settings.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./client": "./client.js",
9
+ "./locale/*.json": "./locale/*.json",
10
+ "./icon": "./icon.svg",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "index.js",
15
+ "client.js",
16
+ "cordis.patch.yml",
17
+ "locale/*.json",
18
+ "icon.svg",
19
+ "README.md"
20
+ ],
21
+ "keywords": [
22
+ "dsh",
23
+ "dsh-plugin",
24
+ "deepseek-harness",
25
+ "mcp",
26
+ "model-context-protocol",
27
+ "streamable-http"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dsh": {
33
+ "bundle": {
34
+ "patch": "./cordis.patch.yml"
35
+ },
36
+ "client": {
37
+ "platform": "web",
38
+ "immediately": true,
39
+ "inject": [
40
+ "@deepseek-ai/dsh-client-ui-settings",
41
+ "@deepseek-ai/dsh-client-locale",
42
+ "@deepseek-ai/dsh-api-remotes"
43
+ ]
44
+ }
45
+ },
46
+ "dependencies": {
47
+ "@deepseek-ai/schemastery": "^3.19.0"
48
+ }
49
+ }