dsh-dock 0.21.1 → 0.23.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 +28 -31
- package/client.js +1511 -751
- package/features/balance/view.js +6 -1
- package/features/mcpconfig/host.js +402 -0
- package/features/mcpconfig/view.js +658 -0
- package/features/modelconfig/host.js +1 -1
- package/features/modelconfig/view.js +2 -2
- package/features/notify/host.js +8 -3
- package/features/notify/view.jsx +40 -12
- package/features/providerconfig/host.js +1 -1
- package/features/providerconfig/view.js +4 -4
- package/features/tokenlog/host.js +207 -10
- package/features/tokenlog/view.jsx +101 -20
- package/index.js +5 -3
- package/package.json +3 -3
- package/src/client.jsx +11 -7
- package/src/host-core.js +3 -0
- package/src/shared.js +5 -0
- package/src/task-track.js +64 -0
- package/features/heartbeat/view.js +0 -35
- package/features/theme/view.js +0 -61
package/features/balance/view.js
CHANGED
|
@@ -302,10 +302,15 @@ function BalanceChip(props) {
|
|
|
302
302
|
"aria-label": "模型余额",
|
|
303
303
|
onClick: () => openPanel("balance", def ? { provider: def } : null),
|
|
304
304
|
},
|
|
305
|
+
// 窄屏只显示这枚小图标:点它进功能坞看余额详情(title 里是完整数值)
|
|
306
|
+
react.createElement("span", { className: "dockchip-svg", "aria-hidden": "true" },
|
|
307
|
+
react.createElement("svg", { viewBox: "0 0 16 16", width: 13, height: 13, fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" },
|
|
308
|
+
react.createElement("path", { d: "M2.8 6.2h10.4v6.3a1 1 0 0 1-1 1H3.8a1 1 0 0 1-1-1z" }),
|
|
309
|
+
react.createElement("path", { d: "M5.4 6.2V4.6a2.6 2.6 0 0 1 5.2 0v1.6" }))),
|
|
305
310
|
react.createElement("span", { className: "dockchip-dot", style: { background: accent } }),
|
|
306
311
|
mm ? react.createElement("span", { className: "dockchip-pre" }, mm[1]) : null,
|
|
307
312
|
mm ? react.createElement("span", { className: "dockchip-pre-s" }, "余额 ") : null,
|
|
308
|
-
react.createElement("span",
|
|
313
|
+
react.createElement("span", { className: "dockchip-val" }, mm ? mm[2] : text));
|
|
309
314
|
}
|
|
310
315
|
|
|
311
316
|
export const feature = {
|
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
// dsh-dock · 功能模块【MCP 管理】· 宿主半部
|
|
2
|
+
//
|
|
3
|
+
// GET /dsh-dock/mcpconfig —— 列出本模块托管的 MCP 服务器(含实时状态与已注册工具)
|
|
4
|
+
// POST /dsh-dock/mcpconfig —— action=save:全量写回 profile patch 的机器托管块并热应用
|
|
5
|
+
//
|
|
6
|
+
// 背景:DSH 的 MCP 服务器是 cordis 插件行(每台服务器一行
|
|
7
|
+
// `name: '@deepseek-ai/dsh-mcp-client'` + 一份 config),真相源是当前 profile 的
|
|
8
|
+
// `cordis.patch.yml`。DSH 自身没有 MCP 管理界面,所以本模块接管其中**一段带标记的
|
|
9
|
+
// 机器托管块**:只改 `# >>> dsh-dock MCP manager` 与 `# <<< dsh-dock MCP manager`
|
|
10
|
+
// 之间的内容,用户手写的其它行/注释/!!js 表达式一律不动。
|
|
11
|
+
//
|
|
12
|
+
// 生效链路(实测可用):写盘 → `ctx.hmr.reconcileProfile(ids)` 原地重组合
|
|
13
|
+
// (dsh-hmr 精确监听 profile patch 文件)→ 新增行 import 并启动、改动行只重启该行、
|
|
14
|
+
// 删除行 dispose 工具并杀掉子进程。无需重启 dsh。失败则把旧文本写回并再 reconcile 一次。
|
|
15
|
+
//
|
|
16
|
+
// 为什么不用 settings/configEditor 写:config-editor 只能改「已存在的条目」,
|
|
17
|
+
// 不能新增/删除插件行;MCP 服务器数量是动态的,必须自己维护 insert 行。
|
|
18
|
+
import { readFile } from 'node:fs/promises'
|
|
19
|
+
import { writeFile, rename, unlink } from 'node:fs/promises'
|
|
20
|
+
import { join } from 'node:path'
|
|
21
|
+
import yaml from 'js-yaml'
|
|
22
|
+
import { sendJson, readBody, rejectUntrustedRequest } from '../../src/host-core.js'
|
|
23
|
+
|
|
24
|
+
/** 托管块的 MCP 插件包名(与 DSH 内置 MCP 客户端一致)。 */
|
|
25
|
+
const MCP_ROW_NAME = '@deepseek-ai/dsh-mcp-client'
|
|
26
|
+
/** 本模块写入的行 id 前缀:id = dock-mcp-<serverName>。 */
|
|
27
|
+
const ROW_ID_PREFIX = 'dock-mcp-'
|
|
28
|
+
const BEGIN = '# >>> dsh-dock MCP manager (machine-managed; do not edit by hand)'
|
|
29
|
+
const END = '# <<< dsh-dock MCP manager'
|
|
30
|
+
/** mcp-client 的 serverName 约束(packages/mcp/mcp-client/src/index.ts)。 */
|
|
31
|
+
const SERVER_NAME_RE = /^[A-Za-z0-9_-]{1,32}$/
|
|
32
|
+
/** 默认单次工具调用超时(与 mcp-client 一致)。 */
|
|
33
|
+
const DEFAULT_TOOL_TIMEOUT_MS = 60000
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 与 DSH 自己的 patch 方言一致的 YAML schema:保住 profile patch 里已有的
|
|
37
|
+
* `!!js` 表达式(值为 {__jsExpr} 占位,dump 时还原),否则整份文件解析失败就没法改。
|
|
38
|
+
*/
|
|
39
|
+
const JsExpr = new yaml.Type('tag:yaml.org,2002:js', {
|
|
40
|
+
kind: 'scalar',
|
|
41
|
+
resolve: (d) => typeof d === 'string',
|
|
42
|
+
construct: (d) => ({ __jsExpr: d }),
|
|
43
|
+
predicate: (v) => v instanceof Object && '__jsExpr' in v,
|
|
44
|
+
represent: (v) => v.__jsExpr,
|
|
45
|
+
})
|
|
46
|
+
const PATCH_SCHEMA = yaml.JSON_SCHEMA.extend(JsExpr)
|
|
47
|
+
|
|
48
|
+
/** 同一进程内的写串行(config-editor / settings / plugin-manager 都写同一文件)。 */
|
|
49
|
+
let writeChain = Promise.resolve()
|
|
50
|
+
function serialWrite(fn) {
|
|
51
|
+
const run = writeChain.then(fn, fn)
|
|
52
|
+
writeChain = run.catch(() => {})
|
|
53
|
+
return run
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function patchPathOf(ctx) {
|
|
57
|
+
const pc = (typeof ctx.get === 'function' ? ctx.get('profileContext') : null) || ctx.profileContext
|
|
58
|
+
if (!pc || typeof pc.patchPath !== 'string' || !pc.patchPath) {
|
|
59
|
+
throw Object.assign(new Error('当前不是 profile 启动,读不到 cordis.patch.yml;MCP 管理不可用'), { statusCode: 400 })
|
|
60
|
+
}
|
|
61
|
+
return pc.patchPath
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function hmrOf(ctx) {
|
|
65
|
+
const hmr = typeof ctx.get === 'function' ? ctx.get('hmr') : null
|
|
66
|
+
if (!hmr || typeof hmr.runExclusive !== 'function' || typeof hmr.reconcileProfile !== 'function') return null
|
|
67
|
+
return hmr
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 读 patch 文件;不存在时按空数组处理(与 DSH 的 loadOptionalPatches 一致)。 */
|
|
71
|
+
async function readPatchText(path) {
|
|
72
|
+
try {
|
|
73
|
+
return await readFile(path, 'utf8')
|
|
74
|
+
} catch (e) {
|
|
75
|
+
if (e && e.code === 'ENOENT') return '[]\n'
|
|
76
|
+
throw e
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 解析成 patch 数组;解析失败直接抛(绝不覆盖用户文件)。 */
|
|
81
|
+
function parsePatchList(text) {
|
|
82
|
+
const parsed = yaml.load(text, { schema: PATCH_SCHEMA })
|
|
83
|
+
if (parsed === null || parsed === undefined) return []
|
|
84
|
+
if (!Array.isArray(parsed)) throw new Error('cordis.patch.yml 顶层不是数组,拒绝写入')
|
|
85
|
+
return parsed
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 把文件拆成「托管块之前 / 托管块 / 托管块之后」三段。 */
|
|
89
|
+
function splitManagedBlock(text) {
|
|
90
|
+
const start = text.indexOf(BEGIN)
|
|
91
|
+
const end = text.indexOf(END)
|
|
92
|
+
if (start < 0 || end < 0 || end < start) return { head: text, block: null, tail: '' }
|
|
93
|
+
return {
|
|
94
|
+
head: text.slice(0, start),
|
|
95
|
+
block: text.slice(start, end + END.length),
|
|
96
|
+
tail: text.slice(end + END.length),
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 从托管块里取服务器定义(只认本模块的行)。 */
|
|
101
|
+
function serversFromBlock(patchList) {
|
|
102
|
+
const servers = []
|
|
103
|
+
for (const patch of patchList) {
|
|
104
|
+
const rows = Array.isArray(patch && patch.insert) ? patch.insert : []
|
|
105
|
+
for (const row of rows) {
|
|
106
|
+
if (!row || row.name !== MCP_ROW_NAME) continue
|
|
107
|
+
const cfg = row.config && typeof row.config === 'object' ? row.config : {}
|
|
108
|
+
if (typeof cfg.serverName !== 'string') continue
|
|
109
|
+
servers.push({
|
|
110
|
+
serverName: cfg.serverName,
|
|
111
|
+
transport: cfg.transport === 'streamable-http' ? 'streamable-http' : 'stdio',
|
|
112
|
+
command: typeof cfg.command === 'string' ? cfg.command : '',
|
|
113
|
+
args: Array.isArray(cfg.args) ? cfg.args.filter((x) => typeof x === 'string') : [],
|
|
114
|
+
env: cfg.env && typeof cfg.env === 'object' && !Array.isArray(cfg.env) ? cfg.env : {},
|
|
115
|
+
cwd: typeof cfg.cwd === 'string' ? cfg.cwd : '',
|
|
116
|
+
url: typeof cfg.url === 'string' ? cfg.url : '',
|
|
117
|
+
headers: cfg.headers && typeof cfg.headers === 'object' && !Array.isArray(cfg.headers) ? cfg.headers : {},
|
|
118
|
+
enabled: row.disabled !== true,
|
|
119
|
+
failOnStartupError: cfg.failOnStartupError === true,
|
|
120
|
+
toolCallTimeoutMs: Number.isFinite(cfg.toolCallTimeoutMs) ? cfg.toolCallTimeoutMs : DEFAULT_TOOL_TIMEOUT_MS,
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return servers
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 由服务器定义生成托管块文本(与读回逻辑严格对称)。 */
|
|
128
|
+
function renderBlock(servers) {
|
|
129
|
+
if (servers.length === 0) return ''
|
|
130
|
+
const rows = servers.map((s) => {
|
|
131
|
+
const config = s.transport === 'streamable-http'
|
|
132
|
+
? {
|
|
133
|
+
serverName: s.serverName,
|
|
134
|
+
transport: 'streamable-http',
|
|
135
|
+
url: s.url,
|
|
136
|
+
headers: s.headers || {},
|
|
137
|
+
failOnStartupError: !!s.failOnStartupError,
|
|
138
|
+
toolCallTimeoutMs: s.toolCallTimeoutMs || DEFAULT_TOOL_TIMEOUT_MS,
|
|
139
|
+
}
|
|
140
|
+
: {
|
|
141
|
+
serverName: s.serverName,
|
|
142
|
+
transport: 'stdio',
|
|
143
|
+
command: s.command,
|
|
144
|
+
args: s.args || [],
|
|
145
|
+
env: s.env || {},
|
|
146
|
+
...(s.cwd ? { cwd: s.cwd } : {}),
|
|
147
|
+
failOnStartupError: !!s.failOnStartupError,
|
|
148
|
+
toolCallTimeoutMs: s.toolCallTimeoutMs || DEFAULT_TOOL_TIMEOUT_MS,
|
|
149
|
+
}
|
|
150
|
+
const row = { id: ROW_ID_PREFIX + s.serverName, name: MCP_ROW_NAME, config }
|
|
151
|
+
if (!s.enabled) row.disabled = true
|
|
152
|
+
return row
|
|
153
|
+
})
|
|
154
|
+
const body = yaml.dump([{ insert: rows }], { schema: PATCH_SCHEMA, lineWidth: -1 }).trimEnd()
|
|
155
|
+
return `${BEGIN}\n${body}\n${END}\n`
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 校验整份服务器列表(写盘前;错误信息直接展示给用户)。 */
|
|
159
|
+
function validateServers(list, existingPatchList) {
|
|
160
|
+
const bad = (msg) => { throw Object.assign(new Error(msg), { statusCode: 400 }) }
|
|
161
|
+
if (!Array.isArray(list)) bad('servers 必须是数组')
|
|
162
|
+
if (list.length > 64) bad('最多管理 64 台 MCP 服务器')
|
|
163
|
+
const seen = new Set()
|
|
164
|
+
const out = []
|
|
165
|
+
for (const raw of list) {
|
|
166
|
+
if (!raw || typeof raw !== 'object') bad('服务器条目必须是对象')
|
|
167
|
+
const serverName = typeof raw.serverName === 'string' ? raw.serverName.trim() : ''
|
|
168
|
+
if (!SERVER_NAME_RE.test(serverName)) bad(`serverName 非法:「${serverName}」须匹配 ${SERVER_NAME_RE}`)
|
|
169
|
+
if (seen.has(serverName)) bad(`serverName 重复:${serverName}`)
|
|
170
|
+
seen.add(serverName)
|
|
171
|
+
const transport = raw.transport === 'streamable-http' ? 'streamable-http' : 'stdio'
|
|
172
|
+
const common = {
|
|
173
|
+
serverName,
|
|
174
|
+
transport,
|
|
175
|
+
enabled: raw.enabled !== false,
|
|
176
|
+
failOnStartupError: raw.failOnStartupError === true,
|
|
177
|
+
toolCallTimeoutMs: Number.isFinite(raw.toolCallTimeoutMs) && raw.toolCallTimeoutMs > 0
|
|
178
|
+
? Math.floor(raw.toolCallTimeoutMs)
|
|
179
|
+
: DEFAULT_TOOL_TIMEOUT_MS,
|
|
180
|
+
}
|
|
181
|
+
if (transport === 'stdio') {
|
|
182
|
+
const command = typeof raw.command === 'string' ? raw.command.trim() : ''
|
|
183
|
+
if (!command) bad(`「${serverName}」是 stdio 传输,command 必填`)
|
|
184
|
+
const args = Array.isArray(raw.args) ? raw.args.map((x) => String(x)) : []
|
|
185
|
+
if (args.length > 64) bad(`「${serverName}」args 过多`)
|
|
186
|
+
const env = {}
|
|
187
|
+
const srcEnv = raw.env && typeof raw.env === 'object' && !Array.isArray(raw.env) ? raw.env : {}
|
|
188
|
+
for (const [k, v] of Object.entries(srcEnv)) {
|
|
189
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) bad(`「${serverName}」环境变量名非法:${k}`)
|
|
190
|
+
env[k] = String(v)
|
|
191
|
+
}
|
|
192
|
+
out.push({ ...common, command, args, env, cwd: typeof raw.cwd === 'string' ? raw.cwd.trim() : '' })
|
|
193
|
+
} else {
|
|
194
|
+
const url = typeof raw.url === 'string' ? raw.url.trim() : ''
|
|
195
|
+
if (!/^https?:\/\//i.test(url)) bad(`「${serverName}」是 HTTP 传输,url 须以 http:// 或 https:// 开头`)
|
|
196
|
+
const headers = {}
|
|
197
|
+
const srcHeaders = raw.headers && typeof raw.headers === 'object' && !Array.isArray(raw.headers) ? raw.headers : {}
|
|
198
|
+
for (const [k, v] of Object.entries(srcHeaders)) headers[String(k)] = String(v)
|
|
199
|
+
out.push({ ...common, url, headers })
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
// 与文件里**其它**区段(用户手写、非本托管块)的 serverName / id 冲突检查。
|
|
203
|
+
const foreignServers = new Set()
|
|
204
|
+
const foreignIds = new Set()
|
|
205
|
+
for (const patch of existingPatchList) {
|
|
206
|
+
if (!patch || typeof patch !== 'object') continue
|
|
207
|
+
if (typeof patch.id === 'string') foreignIds.add(patch.id)
|
|
208
|
+
const rows = Array.isArray(patch.insert) ? patch.insert : []
|
|
209
|
+
for (const row of rows) {
|
|
210
|
+
if (!row || typeof row !== 'object') continue
|
|
211
|
+
if (typeof row.id === 'string') foreignIds.add(row.id)
|
|
212
|
+
if (row.name === MCP_ROW_NAME) {
|
|
213
|
+
const n = row.config && row.config.serverName
|
|
214
|
+
if (typeof n === 'string') foreignServers.add(n)
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
for (const s of out) {
|
|
219
|
+
if (foreignServers.has(s.serverName)) {
|
|
220
|
+
bad(`serverName「${s.serverName}」已被 cordis.patch.yml 里手写的 mcp-client 行占用,请换一个名字`)
|
|
221
|
+
}
|
|
222
|
+
if (foreignIds.has(ROW_ID_PREFIX + s.serverName)) {
|
|
223
|
+
bad(`行 id「${ROW_ID_PREFIX}${s.serverName}」与该文件其它区段的 id 冲突,请换一个 serverName`)
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return out
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** 原子写:同目录临时文件 + rename(保留 0600,profile patch 原权限)。 */
|
|
230
|
+
async function writeTextAtomic(path, text) {
|
|
231
|
+
const tmp = join(join(path, '..'), `.cordis.patch.yml.dsh-dock-${process.pid}-${Date.now()}.tmp`)
|
|
232
|
+
await writeFile(tmp, text, { mode: 0o600 })
|
|
233
|
+
try {
|
|
234
|
+
await rename(tmp, path)
|
|
235
|
+
} catch (e) {
|
|
236
|
+
try { await unlink(tmp) } catch { /* 清理失败忽略 */ }
|
|
237
|
+
throw e
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** 写托管块并热应用;失败回滚文件。返回 { changed, applied, restartRequired, warnings }。 */
|
|
242
|
+
async function applyServers(ctx, servers) {
|
|
243
|
+
const path = patchPathOf(ctx)
|
|
244
|
+
return serialWrite(async () => {
|
|
245
|
+
const before = await readPatchText(path)
|
|
246
|
+
const parsed = parsePatchList(before) // 不可解析就抛,绝不覆盖
|
|
247
|
+
const { head, tail } = splitManagedBlock(before)
|
|
248
|
+
const block = renderBlock(servers)
|
|
249
|
+
const next = servers.length === 0
|
|
250
|
+
? `${head}${tail}`.replace(/\n{3,}$/, '\n')
|
|
251
|
+
: `${head}${block}${tail}`
|
|
252
|
+
if (next === before) return { changed: false, applied: true, warnings: [] }
|
|
253
|
+
|
|
254
|
+
// 写后自检:解析必须仍然成功、托管块行数正确(防止把用户文件写坏)。
|
|
255
|
+
const check = parsePatchList(next)
|
|
256
|
+
const written = serversFromBlock(check)
|
|
257
|
+
if (written.length !== servers.length) throw new Error('写后自检失败:托管块行数与请求不一致,未落盘')
|
|
258
|
+
|
|
259
|
+
const hmr = hmrOf(ctx)
|
|
260
|
+
if (!hmr) {
|
|
261
|
+
await writeTextAtomic(path, next)
|
|
262
|
+
return { changed: true, applied: false, restartRequired: true, warnings: ['当前 profile 未启用 HMR:已保存到 cordis.patch.yml,重启 DSH 后生效'] }
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
await writeTextAtomic(path, next)
|
|
266
|
+
const ids = servers.map((s) => ROW_ID_PREFIX + s.serverName)
|
|
267
|
+
try {
|
|
268
|
+
await hmr.runExclusive(() => hmr.reconcileProfile(ids))
|
|
269
|
+
return { changed: true, applied: true, warnings: [] }
|
|
270
|
+
} catch (error) {
|
|
271
|
+
// 回滚文件 + 再 reconcile 一次(HMR 自己不会回滚)
|
|
272
|
+
let rolledBack = true
|
|
273
|
+
try {
|
|
274
|
+
await writeTextAtomic(path, before)
|
|
275
|
+
await hmr.runExclusive(() => hmr.reconcileProfile([]))
|
|
276
|
+
} catch {
|
|
277
|
+
rolledBack = false
|
|
278
|
+
}
|
|
279
|
+
const err = new Error(`应用失败${rolledBack ? ',已回滚' : ',且回滚失败(请手动检查 cordis.patch.yml)'}:${(error && error.message) || error}`)
|
|
280
|
+
err.statusCode = 400
|
|
281
|
+
err.rolledBack = rolledBack
|
|
282
|
+
err.needsRestart = !rolledBack
|
|
283
|
+
throw err
|
|
284
|
+
}
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 实时状态:Loader 行(disabled / fiber 状态)+ 已注册工具名。 */
|
|
289
|
+
function liveStatus(ctx, servers) {
|
|
290
|
+
const status = new Map(servers.map((s) => [s.serverName, { state: 'unknown', error: null, tools: [] }]))
|
|
291
|
+
let entries = []
|
|
292
|
+
try {
|
|
293
|
+
const loader = typeof ctx.get === 'function' ? ctx.get('loader') : null
|
|
294
|
+
if (loader && typeof loader.entries === 'function') entries = Array.from(loader.entries())
|
|
295
|
+
} catch { /* loader 不可用:保持 unknown */ }
|
|
296
|
+
const byId = new Map()
|
|
297
|
+
for (const entry of entries) {
|
|
298
|
+
const opts = entry && entry.options ? entry.options : {}
|
|
299
|
+
const id = typeof opts.id === 'string' ? opts.id : ''
|
|
300
|
+
if (!id.startsWith(ROW_ID_PREFIX)) continue
|
|
301
|
+
if (opts.name !== MCP_ROW_NAME) continue
|
|
302
|
+
const cfg = opts.config && typeof opts.config === 'object' ? opts.config : {}
|
|
303
|
+
const serverName = typeof cfg.serverName === 'string' ? cfg.serverName : ''
|
|
304
|
+
if (!serverName) continue
|
|
305
|
+
byId.set(id, { entry, serverName })
|
|
306
|
+
}
|
|
307
|
+
let toolNames = []
|
|
308
|
+
try {
|
|
309
|
+
const tools = typeof ctx.get === 'function' ? ctx.get('tools') : null
|
|
310
|
+
if (tools && typeof tools.definitions === 'function') toolNames = tools.definitions().map((d) => d && d.name).filter(Boolean)
|
|
311
|
+
} catch { /* tools 不可用 */ }
|
|
312
|
+
for (const [id, { entry, serverName }] of byId) {
|
|
313
|
+
const slot = status.get(serverName) || { state: 'unknown', error: null, tools: [] }
|
|
314
|
+
let disabled = false
|
|
315
|
+
try { disabled = entry.disabled === true } catch { disabled = false }
|
|
316
|
+
let fiberState = ''
|
|
317
|
+
try { fiberState = String((entry.fiber && entry.fiber.state) || '') } catch { fiberState = '' }
|
|
318
|
+
const st = disabled ? 'disabled'
|
|
319
|
+
: /fail/i.test(fiberState) ? 'failed'
|
|
320
|
+
: /active|run/i.test(fiberState) ? 'active'
|
|
321
|
+
: 'inactive'
|
|
322
|
+
slot.state = st
|
|
323
|
+
slot.error = (entry.fiber && entry.fiber.error && String(entry.fiber.error.message || entry.fiber.error)) || null
|
|
324
|
+
slot.tools = toolNames.filter((n) => n.startsWith(`mcp__${serverName}__`))
|
|
325
|
+
status.set(serverName, slot)
|
|
326
|
+
}
|
|
327
|
+
return status
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function listPayload(ctx, patchText, patchList) {
|
|
331
|
+
const { block } = splitManagedBlock(patchText)
|
|
332
|
+
const servers = block ? serversFromBlock(parsePatchList(block)) : []
|
|
333
|
+
const live = liveStatus(ctx, servers)
|
|
334
|
+
const warnings = []
|
|
335
|
+
const hmr = hmrOf(ctx)
|
|
336
|
+
if (!hmr) warnings.push('当前 profile 未启用 HMR:修改会写入 cordis.patch.yml,但需要重启 DSH 才生效')
|
|
337
|
+
return {
|
|
338
|
+
ok: true,
|
|
339
|
+
patchPath: (() => { try { return patchPathOf(ctx) } catch { return '' } })(),
|
|
340
|
+
hmrAvailable: !!hmr,
|
|
341
|
+
servers: servers.map((s) => {
|
|
342
|
+
const st = live.get(s.serverName) || { state: 'unknown', error: null, tools: [] }
|
|
343
|
+
return { ...s, state: st.state, error: st.error, tools: st.tools, toolCount: st.tools.length }
|
|
344
|
+
}),
|
|
345
|
+
warnings,
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** 功能注册表条目:index.js 组装 FEATURES 时使用。 */
|
|
350
|
+
export const feature = {
|
|
351
|
+
id: 'mcpconfig',
|
|
352
|
+
name: 'MCP管理',
|
|
353
|
+
description: '管理 DSH 使用的 MCP 服务器(增删改 / 启停 / 工具状态),写回 cordis.patch.yml 并热应用',
|
|
354
|
+
defaultEnabled: false,
|
|
355
|
+
setup(ctx) {
|
|
356
|
+
const webServer = ctx.get('webServer')
|
|
357
|
+
if (webServer === undefined) throw new Error('webServer 服务不可用,无法提供 MCP 管理路由')
|
|
358
|
+
const handler = async (req, res) => {
|
|
359
|
+
if (rejectUntrustedRequest(ctx, req, res)) return
|
|
360
|
+
try {
|
|
361
|
+
if (req.method === 'GET') {
|
|
362
|
+
const path = patchPathOf(ctx)
|
|
363
|
+
const text = await readPatchText(path)
|
|
364
|
+
parsePatchList(text) // 不可解析时直接报错给面板,避免面板把文件写坏
|
|
365
|
+
sendJson(res, 200, listPayload(ctx, text))
|
|
366
|
+
return
|
|
367
|
+
}
|
|
368
|
+
if (req.method === 'POST') {
|
|
369
|
+
const body = await readBody(req)
|
|
370
|
+
if (!body || typeof body !== 'object') {
|
|
371
|
+
sendJson(res, 400, { ok: false, error: '请求体不是 JSON 对象' })
|
|
372
|
+
return
|
|
373
|
+
}
|
|
374
|
+
const action = body.action || 'save'
|
|
375
|
+
if (action !== 'save') {
|
|
376
|
+
sendJson(res, 400, { ok: false, error: `不支持的 action:${action}` })
|
|
377
|
+
return
|
|
378
|
+
}
|
|
379
|
+
const path = patchPathOf(ctx)
|
|
380
|
+
const before = await readPatchText(path)
|
|
381
|
+
const parsedBefore = parsePatchList(before)
|
|
382
|
+
const { head: outerHead, tail: outerTail } = splitManagedBlock(before)
|
|
383
|
+
const outerList = parsePatchList(`${outerHead}${outerTail}`.trim() || '[]')
|
|
384
|
+
const servers = validateServers(body.servers, outerList)
|
|
385
|
+
const result = await applyServers(ctx, servers)
|
|
386
|
+
sendJson(res, 200, { ok: true, ...result })
|
|
387
|
+
return
|
|
388
|
+
}
|
|
389
|
+
sendJson(res, 405, { ok: false, error: `不支持的请求方法:${req.method}` })
|
|
390
|
+
} catch (e) {
|
|
391
|
+
const status = e && e.statusCode ? e.statusCode : 500
|
|
392
|
+
sendJson(res, status, {
|
|
393
|
+
ok: false,
|
|
394
|
+
error: e instanceof Error ? e.message : String(e),
|
|
395
|
+
...(e && e.rolledBack !== undefined ? { rolledBack: e.rolledBack } : {}),
|
|
396
|
+
...(e && e.needsRestart ? { needsRestart: true } : {}),
|
|
397
|
+
})
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
return webServer.register({ kind: 'exact', path: '/dsh-dock/mcpconfig', handler })
|
|
401
|
+
},
|
|
402
|
+
}
|