@tachec/dsh-mcp-manage 0.0.0-stage → 1.2.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/CHANGELOG.md +51 -0
- package/LICENSE +21 -0
- package/README.en.md +194 -0
- package/README.md +242 -3
- package/client.js +2354 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +11 -0
- package/index.js +1033 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +61 -6
package/index.js
ADDED
|
@@ -0,0 +1,1033 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-mcp-manage — Host half.
|
|
3
|
+
*
|
|
4
|
+
* One authenticated same-origin JSON endpoint that the settings page drives:
|
|
5
|
+
*
|
|
6
|
+
* GET /dsh-mcp-manage/api → the complete management snapshot
|
|
7
|
+
* POST /dsh-mcp-manage/api → { action, ... } and the snapshot after the change
|
|
8
|
+
*
|
|
9
|
+
* Managed servers live in `@deepseek-ai/dsh-mcp-manager`'s volatile
|
|
10
|
+
* `config.servers`; writes go through the settings service, so they are
|
|
11
|
+
* validated, persisted by the profile's config editor, and reconciled into
|
|
12
|
+
* live mcp-client instances without restarting the Host. Statically composed
|
|
13
|
+
* `@deepseek-ai/dsh-mcp-client` rows are listed too: their configuration is
|
|
14
|
+
* edited through the config editor and their enablement through the plugin
|
|
15
|
+
* manager. MCP configuration files from other agent tools on this machine are
|
|
16
|
+
* read, never written.
|
|
17
|
+
*
|
|
18
|
+
* No model-facing tool is registered: the page is the only caller.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises'
|
|
22
|
+
import { homedir } from 'node:os'
|
|
23
|
+
import { dirname, join } from 'node:path'
|
|
24
|
+
|
|
25
|
+
const ROUTE = '/dsh-mcp-manage/api'
|
|
26
|
+
const MANAGER_PKG = '@deepseek-ai/dsh-mcp-manager'
|
|
27
|
+
const CLIENT_PKG = '@deepseek-ai/dsh-mcp-client'
|
|
28
|
+
const SERVER_NAME = /^[A-Za-z0-9_-]{1,32}$/
|
|
29
|
+
const MAX_BODY_BYTES = 256 * 1024
|
|
30
|
+
const MAX_CONFIG_BYTES = 2 * 1024 * 1024
|
|
31
|
+
const DISCOVERY_TTL_MS = 15_000
|
|
32
|
+
const PROBE_TIMEOUT_MS = 20_000
|
|
33
|
+
|
|
34
|
+
const MANAGER_FIELDS = [
|
|
35
|
+
'transport', 'command', 'args', 'env', 'cwd', 'url', 'headers',
|
|
36
|
+
'enabled', 'toolCallTimeoutMs', 'startupTimeoutMs', 'closeTimeoutMs', 'reconnect',
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
/** The last discovery scan, reused for a few seconds across page refreshes. */
|
|
40
|
+
let discoveryCache = { at: 0, value: [] }
|
|
41
|
+
|
|
42
|
+
/** Page preferences owned by this plugin, not by any MCP server. */
|
|
43
|
+
const DEFAULT_PREFERENCES = { sidebarShortcut: true }
|
|
44
|
+
let preferencesCache = null
|
|
45
|
+
let preferencesChain = Promise.resolve()
|
|
46
|
+
|
|
47
|
+
/** The preference document, beside the plugin's data under the Harness home. */
|
|
48
|
+
function preferencesFile() {
|
|
49
|
+
const home = typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME !== ''
|
|
50
|
+
? process.env.DSH_HOME
|
|
51
|
+
: join(homedir(), '.dsh')
|
|
52
|
+
return join(home, 'dsh-mcp-manage', 'preferences.json')
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Read the preference document once, tolerating a missing or broken file. */
|
|
56
|
+
async function readPreferences() {
|
|
57
|
+
if (preferencesCache !== null) return preferencesCache
|
|
58
|
+
try {
|
|
59
|
+
const text = await readFile(preferencesFile(), 'utf8')
|
|
60
|
+
const parsed = JSON.parse(text.replace(/^\uFEFF/, ''))
|
|
61
|
+
const sidebarShortcut = parsed !== null && typeof parsed === 'object' && parsed.sidebarShortcut === false ? false : true
|
|
62
|
+
preferencesCache = { ...DEFAULT_PREFERENCES, sidebarShortcut }
|
|
63
|
+
} catch {
|
|
64
|
+
preferencesCache = { ...DEFAULT_PREFERENCES }
|
|
65
|
+
}
|
|
66
|
+
return preferencesCache
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Persist one preference, serialized with later writes. */
|
|
70
|
+
async function writePreferences(patch) {
|
|
71
|
+
const current = await readPreferences()
|
|
72
|
+
const next = { ...current, ...patch }
|
|
73
|
+
const previous = preferencesCache
|
|
74
|
+
preferencesCache = next
|
|
75
|
+
const run = async () => {
|
|
76
|
+
const file = preferencesFile()
|
|
77
|
+
await mkdir(dirname(file), { recursive: true })
|
|
78
|
+
const temporary = `${file}.${process.pid}.${Date.now()}.tmp`
|
|
79
|
+
await writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
|
|
80
|
+
await rename(temporary, file)
|
|
81
|
+
}
|
|
82
|
+
const task = preferencesChain.then(run, run)
|
|
83
|
+
preferencesChain = task.catch(() => {})
|
|
84
|
+
try {
|
|
85
|
+
await task
|
|
86
|
+
} catch (error) {
|
|
87
|
+
preferencesCache = previous
|
|
88
|
+
throw fail('preferences-write-failed', `保存页面偏好失败:${messageOf(error)}`)
|
|
89
|
+
}
|
|
90
|
+
return next
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Create a refusal that the browser renders as a message instead of a crash. */
|
|
94
|
+
function fail(code, message, details) {
|
|
95
|
+
const error = new Error(message)
|
|
96
|
+
error.code = code
|
|
97
|
+
if (details !== undefined) error.details = details
|
|
98
|
+
return error
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Exact diagnostic text for a failure of unknown type. */
|
|
102
|
+
function messageOf(error) {
|
|
103
|
+
return error instanceof Error ? error.message : String(error)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A deep, JSON-shaped copy: server configuration is plain data only. */
|
|
107
|
+
function plain(value) {
|
|
108
|
+
if (value === null || typeof value !== 'object') return value
|
|
109
|
+
return JSON.parse(JSON.stringify(value))
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Send one JSON response; never writes over a response the auth layer already finished. */
|
|
113
|
+
function sendJson(response, status, value) {
|
|
114
|
+
if (response.headersSent || response.writableEnded) return
|
|
115
|
+
const body = JSON.stringify(value)
|
|
116
|
+
response.statusCode = status
|
|
117
|
+
response.setHeader('content-type', 'application/json; charset=utf-8')
|
|
118
|
+
response.setHeader('cache-control', 'no-store')
|
|
119
|
+
response.setHeader('x-content-type-options', 'nosniff')
|
|
120
|
+
response.end(body)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Read a bounded JSON request body. */
|
|
124
|
+
async function readJsonBody(request) {
|
|
125
|
+
const chunks = []
|
|
126
|
+
let size = 0
|
|
127
|
+
for await (const chunk of request) {
|
|
128
|
+
size += chunk.length
|
|
129
|
+
if (size > MAX_BODY_BYTES) throw fail('body-too-large', '请求体过大。')
|
|
130
|
+
chunks.push(chunk)
|
|
131
|
+
}
|
|
132
|
+
if (chunks.length === 0) return {}
|
|
133
|
+
let text = Buffer.concat(chunks).toString('utf8')
|
|
134
|
+
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1)
|
|
135
|
+
if (text.trim() === '') return {}
|
|
136
|
+
try {
|
|
137
|
+
const parsed = JSON.parse(text)
|
|
138
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
139
|
+
throw fail('invalid-body', '请求体必须是一个 JSON 对象。')
|
|
140
|
+
}
|
|
141
|
+
return parsed
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (error.code === 'invalid-body') throw error
|
|
144
|
+
throw fail('invalid-body', `请求体不是合法 JSON:${messageOf(error)}`)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The shell's own document origins; a shell may mint a document on one of these. */
|
|
149
|
+
const APP_SCHEMES = ['dsh-app:', 'dsh-desktop:']
|
|
150
|
+
|
|
151
|
+
function schemeOf(value) {
|
|
152
|
+
if (value === '' || value === 'null') return undefined
|
|
153
|
+
try {
|
|
154
|
+
return new URL(value).protocol
|
|
155
|
+
} catch {
|
|
156
|
+
return undefined
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* A second, browser-side boundary for writes. The host credential already
|
|
162
|
+
* authenticated the request; this refuses a document on another origin.
|
|
163
|
+
*/
|
|
164
|
+
function sameOrigin(request, writing) {
|
|
165
|
+
const origin = String(request.headers.origin ?? '').trim()
|
|
166
|
+
const site = String(request.headers['sec-fetch-site'] ?? '').toLowerCase()
|
|
167
|
+
if (APP_SCHEMES.includes(schemeOf(origin) ?? '')) return true
|
|
168
|
+
if (APP_SCHEMES.includes(schemeOf(String(request.headers.referer ?? '')) ?? '')) return true
|
|
169
|
+
if (origin === '') {
|
|
170
|
+
const agent = String(request.headers['user-agent'] ?? '')
|
|
171
|
+
const language = String(request.headers['accept-language'] ?? '')
|
|
172
|
+
if (/^Mozilla\/5\.0/.test(agent) && language !== '') return true
|
|
173
|
+
return !writing
|
|
174
|
+
}
|
|
175
|
+
if (site === 'cross-site' || site === 'same-site') return false
|
|
176
|
+
if (origin === 'null') return false
|
|
177
|
+
try {
|
|
178
|
+
return new URL(origin).host.toLowerCase() === String(request.headers.host ?? '').trim().toLowerCase()
|
|
179
|
+
} catch {
|
|
180
|
+
return false
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Bind the host's signed browser-session authentication to this route. */
|
|
185
|
+
function authorized(ctx, request, response) {
|
|
186
|
+
let connection
|
|
187
|
+
try {
|
|
188
|
+
connection = ctx.get('connection')
|
|
189
|
+
} catch {
|
|
190
|
+
connection = undefined
|
|
191
|
+
}
|
|
192
|
+
if (connection === undefined || typeof connection.authorizeIndex !== 'function') {
|
|
193
|
+
sendJson(response, 503, { ok: false, error: 'host-auth-unavailable' })
|
|
194
|
+
return false
|
|
195
|
+
}
|
|
196
|
+
return connection.authorizeIndex(request, response) !== false
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Read a string field, falling back when the value is not a string. */
|
|
200
|
+
function str(value, fallback = '') {
|
|
201
|
+
return typeof value === 'string' ? value : fallback
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Read a positive millisecond budget; undefined when absent or unusable. */
|
|
205
|
+
function positiveNumber(value) {
|
|
206
|
+
if (typeof value === 'number' && Number.isFinite(value) && value > 0) return Math.floor(value)
|
|
207
|
+
if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value)) && Number(value) > 0) {
|
|
208
|
+
return Math.floor(Number(value))
|
|
209
|
+
}
|
|
210
|
+
return undefined
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Read a string array, accepting a JSON string array for pasted configuration. */
|
|
214
|
+
function stringArray(value) {
|
|
215
|
+
if (value === undefined || value === null) return []
|
|
216
|
+
if (Array.isArray(value)) return value.map(item => (typeof item === 'string' ? item : String(item ?? '')))
|
|
217
|
+
if (typeof value === 'string' && value.trim() !== '') return [value]
|
|
218
|
+
return []
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Read a `Record<string, string>` from an object of scalar values. */
|
|
222
|
+
function stringMap(value) {
|
|
223
|
+
if (value === undefined || value === null) return {}
|
|
224
|
+
if (typeof value !== 'object' || Array.isArray(value)) return {}
|
|
225
|
+
const result = {}
|
|
226
|
+
for (const [key, item] of Object.entries(value)) {
|
|
227
|
+
if (item === undefined || item === null) continue
|
|
228
|
+
if (typeof item === 'object') continue
|
|
229
|
+
result[key] = String(item)
|
|
230
|
+
}
|
|
231
|
+
return result
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Read the reconnect policy, keeping only declared members. */
|
|
235
|
+
function reconnectOf(value) {
|
|
236
|
+
if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
|
|
237
|
+
const out = {}
|
|
238
|
+
if (typeof value.enabled === 'boolean') out.enabled = value.enabled
|
|
239
|
+
for (const key of ['initialDelayMs', 'maxDelayMs', 'maxAttempts']) {
|
|
240
|
+
const number = positiveNumber(value[key])
|
|
241
|
+
if (number !== undefined) out[key] = number
|
|
242
|
+
}
|
|
243
|
+
return Object.keys(out).length === 0 ? undefined : out
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The transport an entry asks for; `type` is accepted for pasted third-party JSON. */
|
|
247
|
+
function transportOf(input) {
|
|
248
|
+
if (input === null || typeof input !== 'object') return ''
|
|
249
|
+
let transport = String(input.transport ?? input.type ?? '').trim().toLowerCase()
|
|
250
|
+
if (transport === 'http') transport = 'streamable-http'
|
|
251
|
+
if (transport === 'sse') {
|
|
252
|
+
throw fail('sse-unsupported', '不支持旧的 SSE 传输;请使用 Streamable HTTP(把 type 改为 streamable-http 或 http)。')
|
|
253
|
+
}
|
|
254
|
+
if (transport === '') {
|
|
255
|
+
if (typeof input.url === 'string' && input.url.trim() !== '') transport = 'streamable-http'
|
|
256
|
+
else if (typeof input.command === 'string' && input.command.trim() !== '') transport = 'stdio'
|
|
257
|
+
}
|
|
258
|
+
return transport
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Refuse a server name the manager or the tool namespace cannot carry. */
|
|
262
|
+
function assertServerName(name) {
|
|
263
|
+
if (typeof name !== 'string' || !SERVER_NAME.test(name)) {
|
|
264
|
+
throw fail('invalid-name', `服务器名 “${String(name)}” 不合法:只能使用字母、数字、下划线或连字符,长度 1–32。`, { name: String(name) })
|
|
265
|
+
}
|
|
266
|
+
return name
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Validate and normalize one managed server entry. Only manager fields are
|
|
271
|
+
* kept; the per-transport rules mirror the manager's own write-time refusal so
|
|
272
|
+
* a mistake is named before the write.
|
|
273
|
+
*/
|
|
274
|
+
function normalizeManagerEntry(input) {
|
|
275
|
+
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
|
|
276
|
+
throw fail('invalid-server', '服务器配置必须是一个 JSON 对象。')
|
|
277
|
+
}
|
|
278
|
+
const transport = transportOf(input)
|
|
279
|
+
if (transport !== 'stdio' && transport !== 'streamable-http') {
|
|
280
|
+
throw fail('transport-required', '请选择传输方式:stdio 或 streamable-http。')
|
|
281
|
+
}
|
|
282
|
+
const out = { transport }
|
|
283
|
+
if (transport === 'stdio') {
|
|
284
|
+
const command = str(input.command).trim()
|
|
285
|
+
if (command === '') throw fail('command-required', 'stdio 服务器必须填写启动命令(command)。')
|
|
286
|
+
out.command = command
|
|
287
|
+
const args = stringArray(input.args)
|
|
288
|
+
if (args.length > 0) out.args = args
|
|
289
|
+
const env = stringMap(input.env)
|
|
290
|
+
if (Object.keys(env).length > 0) out.env = env
|
|
291
|
+
const cwd = str(input.cwd).trim()
|
|
292
|
+
if (cwd !== '') out.cwd = cwd
|
|
293
|
+
} else {
|
|
294
|
+
const url = str(input.url).trim()
|
|
295
|
+
if (!/^https?:\/\/\S+$/i.test(url)) {
|
|
296
|
+
throw fail('url-required', 'streamable-http 服务器必须填写以 http:// 或 https:// 开头的 URL。')
|
|
297
|
+
}
|
|
298
|
+
out.url = url
|
|
299
|
+
const headers = stringMap(input.headers)
|
|
300
|
+
if (Object.keys(headers).length > 0) out.headers = headers
|
|
301
|
+
}
|
|
302
|
+
const toolCallTimeoutMs = positiveNumber(input.toolCallTimeoutMs)
|
|
303
|
+
if (toolCallTimeoutMs !== undefined) out.toolCallTimeoutMs = toolCallTimeoutMs
|
|
304
|
+
const startupTimeoutMs = positiveNumber(input.startupTimeoutMs)
|
|
305
|
+
if (startupTimeoutMs !== undefined) out.startupTimeoutMs = startupTimeoutMs
|
|
306
|
+
const closeTimeoutMs = positiveNumber(input.closeTimeoutMs)
|
|
307
|
+
if (closeTimeoutMs !== undefined) out.closeTimeoutMs = closeTimeoutMs
|
|
308
|
+
const reconnect = reconnectOf(input.reconnect)
|
|
309
|
+
if (reconnect !== undefined) out.reconnect = reconnect
|
|
310
|
+
if (input.enabled === false || input.disabled === true) out.enabled = false
|
|
311
|
+
return out
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Keep only manager fields, so a pasted or copied document cannot smuggle junk into the profile. */
|
|
315
|
+
function cleanManagerConfig(input) {
|
|
316
|
+
const source = input !== null && typeof input === 'object' ? input : {}
|
|
317
|
+
const out = {}
|
|
318
|
+
for (const key of MANAGER_FIELDS) {
|
|
319
|
+
if (source[key] !== undefined) out[key] = plain(source[key])
|
|
320
|
+
}
|
|
321
|
+
if (out.transport !== 'stdio' && out.transport !== 'streamable-http') {
|
|
322
|
+
throw fail('invalid-server', '服务器配置缺少 transport。')
|
|
323
|
+
}
|
|
324
|
+
return out
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** A display summary plus the effective configuration the editor prefills. */
|
|
328
|
+
function summarizeServer(config) {
|
|
329
|
+
const source = config !== null && typeof config === 'object' ? config : {}
|
|
330
|
+
return {
|
|
331
|
+
transport: str(source.transport),
|
|
332
|
+
command: str(source.command),
|
|
333
|
+
args: stringArray(source.args),
|
|
334
|
+
cwd: str(source.cwd),
|
|
335
|
+
env: stringMap(source.env),
|
|
336
|
+
url: str(source.url),
|
|
337
|
+
headers: stringMap(source.headers),
|
|
338
|
+
toolCallTimeoutMs: positiveNumber(source.toolCallTimeoutMs),
|
|
339
|
+
startupTimeoutMs: positiveNumber(source.startupTimeoutMs),
|
|
340
|
+
closeTimeoutMs: positiveNumber(source.closeTimeoutMs),
|
|
341
|
+
reconnect: reconnectOf(source.reconnect),
|
|
342
|
+
config: plain(source),
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Parse pasted JSON into a `name → server` map, accepting common formats. */
|
|
347
|
+
function parseServerDocument(text, allowNameless = false) {
|
|
348
|
+
let document
|
|
349
|
+
try {
|
|
350
|
+
document = JSON.parse(String(text).replace(/^\uFEFF/, ''))
|
|
351
|
+
} catch (error) {
|
|
352
|
+
throw fail('invalid-json', `JSON 解析失败:${messageOf(error)}`)
|
|
353
|
+
}
|
|
354
|
+
if (document === null || typeof document !== 'object' || Array.isArray(document)) {
|
|
355
|
+
throw fail('invalid-json', '需要一个 JSON 对象。')
|
|
356
|
+
}
|
|
357
|
+
const isMap = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
358
|
+
if (isMap(document.mcpServers)) return document.mcpServers
|
|
359
|
+
if (isMap(document.servers)) return document.servers
|
|
360
|
+
if (isMap(document.mcp)) return document.mcp
|
|
361
|
+
const looksLikeOne =
|
|
362
|
+
typeof document.command === 'string' ||
|
|
363
|
+
typeof document.url === 'string' ||
|
|
364
|
+
document.transport !== undefined ||
|
|
365
|
+
document.type !== undefined
|
|
366
|
+
if (looksLikeOne) {
|
|
367
|
+
const name = document.name ?? document.serverName
|
|
368
|
+
if (typeof name !== 'string' || name.trim() === '') {
|
|
369
|
+
if (allowNameless) return { '': document }
|
|
370
|
+
throw fail('name-required', '单个服务器配置需要一个 name 或 serverName 字段。')
|
|
371
|
+
}
|
|
372
|
+
return { [name]: document }
|
|
373
|
+
}
|
|
374
|
+
const entries = Object.entries(document)
|
|
375
|
+
if (entries.length > 0 && entries.every(([, value]) => isMap(value))) return document
|
|
376
|
+
throw fail('invalid-json', '没有找到 mcpServers、servers,或 “名称 → 服务器” 映射。')
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Locate a Loader entry by its stable entry id. */
|
|
380
|
+
function entryById(ctx, entryId) {
|
|
381
|
+
if (typeof entryId !== 'string' || entryId === '') throw fail('not-found', '缺少 entryId。')
|
|
382
|
+
const entries = [...ctx.loader.entries()]
|
|
383
|
+
const entry = entries.find(item => item.id === entryId)
|
|
384
|
+
if (entry === undefined) throw fail('not-found', `找不到插件行 “${entryId}”。`)
|
|
385
|
+
return entry
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Read the live tools each MCP server registered, keyed by server name. */
|
|
389
|
+
function collectTools(ctx) {
|
|
390
|
+
const map = new Map()
|
|
391
|
+
try {
|
|
392
|
+
const tools = ctx.get('tools')
|
|
393
|
+
if (tools === undefined || typeof tools.definitions !== 'function') return map
|
|
394
|
+
for (const definition of tools.definitions()) {
|
|
395
|
+
const name = definition?.name
|
|
396
|
+
if (typeof name !== 'string' || !name.startsWith('mcp__')) continue
|
|
397
|
+
const rest = name.slice('mcp__'.length)
|
|
398
|
+
const separator = rest.indexOf('__')
|
|
399
|
+
if (separator <= 0) continue
|
|
400
|
+
const server = rest.slice(0, separator)
|
|
401
|
+
const tool = rest.slice(separator + 2)
|
|
402
|
+
if (!map.has(server)) map.set(server, [])
|
|
403
|
+
map.get(server).push(tool)
|
|
404
|
+
}
|
|
405
|
+
} catch {
|
|
406
|
+
// A missing tool registry merely hides the tool list.
|
|
407
|
+
}
|
|
408
|
+
for (const list of map.values()) list.sort()
|
|
409
|
+
return map
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Read the manager's live status registry, keyed by server name. */
|
|
413
|
+
function collectStatuses(ctx, warnings) {
|
|
414
|
+
const map = new Map()
|
|
415
|
+
let manager
|
|
416
|
+
try {
|
|
417
|
+
manager = ctx.get('mcpManager')
|
|
418
|
+
} catch {
|
|
419
|
+
manager = undefined
|
|
420
|
+
}
|
|
421
|
+
if (manager === undefined || typeof manager.list !== 'function') return map
|
|
422
|
+
try {
|
|
423
|
+
for (const view of manager.list()) {
|
|
424
|
+
if (view === null || typeof view !== 'object') continue
|
|
425
|
+
const status = view.status !== null && typeof view.status === 'object' ? view.status : { state: 'unknown' }
|
|
426
|
+
map.set(String(view.name), { configured: view.configured === true, ...status })
|
|
427
|
+
}
|
|
428
|
+
} catch (error) {
|
|
429
|
+
warnings.push(`读取 MCP 运行状态失败:${messageOf(error)}`)
|
|
430
|
+
}
|
|
431
|
+
return map
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Normalize a Cordis fiber state to a short phase name. */
|
|
435
|
+
function phaseOf(entry) {
|
|
436
|
+
let state
|
|
437
|
+
try {
|
|
438
|
+
state = entry.fiber?.state
|
|
439
|
+
} catch {
|
|
440
|
+
state = undefined
|
|
441
|
+
}
|
|
442
|
+
switch (state) {
|
|
443
|
+
case 0: return 'pending'
|
|
444
|
+
case 1: return 'loading'
|
|
445
|
+
case 2: return 'active'
|
|
446
|
+
case 3: return 'failed'
|
|
447
|
+
case 5: return 'unloading'
|
|
448
|
+
default: return null
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** The external MCP configuration files this platform is likely to have. */
|
|
453
|
+
function discoveryCandidates() {
|
|
454
|
+
const home = homedir()
|
|
455
|
+
const appData = process.env.APPDATA ?? join(home, 'AppData', 'Roaming')
|
|
456
|
+
const localAppData = process.env.LOCALAPPDATA ?? join(home, 'AppData', 'Local')
|
|
457
|
+
const list = []
|
|
458
|
+
if (process.platform === 'win32') {
|
|
459
|
+
list.push(
|
|
460
|
+
{ id: 'claude-desktop', label: 'Claude Desktop', path: join(appData, 'Claude', 'claude_desktop_config.json'), section: 'mcpServers' },
|
|
461
|
+
{ id: 'cursor', label: 'Cursor', path: join(home, '.cursor', 'mcp.json'), section: 'mcpServers' },
|
|
462
|
+
{ id: 'cursor-app', label: 'Cursor (app data)', path: join(appData, 'Cursor', 'User', 'mcp.json'), section: 'mcpServers' },
|
|
463
|
+
{ id: 'vscode', label: 'VS Code', path: join(appData, 'Code', 'User', 'mcp.json'), section: 'servers' },
|
|
464
|
+
{ id: 'vscode-insiders', label: 'VS Code Insiders', path: join(appData, 'Code - Insiders', 'User', 'mcp.json'), section: 'servers' },
|
|
465
|
+
{ id: 'windsurf', label: 'Windsurf', path: join(home, '.codeium', 'windsurf', 'mcp_config.json'), section: 'mcpServers' },
|
|
466
|
+
{ id: 'cline', label: 'Cline', path: join(appData, 'Code', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json'), section: 'mcpServers' },
|
|
467
|
+
{ id: 'roo-code', label: 'Roo Code', path: join(appData, 'Code', 'User', 'globalStorage', 'rooveterinaryinc.roo-cline', 'settings', 'mcp_settings.json'), section: 'mcpServers' },
|
|
468
|
+
{ id: 'trae', label: 'Trae', path: join(appData, 'Trae', 'User', 'mcp.json'), section: 'mcpServers' },
|
|
469
|
+
{ id: 'claude-code', label: 'Claude Code', path: join(home, '.claude.json'), section: 'mcpServers' },
|
|
470
|
+
{ id: 'dsh-local', label: 'DSH local data', path: join(localAppData, 'Programs', 'dsh', 'mcp.json'), section: 'mcpServers' },
|
|
471
|
+
)
|
|
472
|
+
} else if (process.platform === 'darwin') {
|
|
473
|
+
list.push(
|
|
474
|
+
{ id: 'claude-desktop', label: 'Claude Desktop', path: join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'), section: 'mcpServers' },
|
|
475
|
+
{ id: 'cursor', label: 'Cursor', path: join(home, '.cursor', 'mcp.json'), section: 'mcpServers' },
|
|
476
|
+
{ id: 'vscode', label: 'VS Code', path: join(home, 'Library', 'Application Support', 'Code', 'User', 'mcp.json'), section: 'servers' },
|
|
477
|
+
{ id: 'windsurf', label: 'Windsurf', path: join(home, '.codeium', 'windsurf', 'mcp_config.json'), section: 'mcpServers' },
|
|
478
|
+
{ id: 'claude-code', label: 'Claude Code', path: join(home, '.claude.json'), section: 'mcpServers' },
|
|
479
|
+
)
|
|
480
|
+
} else {
|
|
481
|
+
list.push(
|
|
482
|
+
{ id: 'claude-desktop', label: 'Claude Desktop', path: join(home, '.config', 'Claude', 'claude_desktop_config.json'), section: 'mcpServers' },
|
|
483
|
+
{ id: 'cursor', label: 'Cursor', path: join(home, '.cursor', 'mcp.json'), section: 'mcpServers' },
|
|
484
|
+
{ id: 'vscode', label: 'VS Code', path: join(home, '.config', 'Code', 'User', 'mcp.json'), section: 'servers' },
|
|
485
|
+
{ id: 'windsurf', label: 'Windsurf', path: join(home, '.codeium', 'windsurf', 'mcp_config.json'), section: 'mcpServers' },
|
|
486
|
+
{ id: 'cline', label: 'Cline', path: join(home, '.config', 'Code', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json'), section: 'mcpServers' },
|
|
487
|
+
{ id: 'claude-code', label: 'Claude Code', path: join(home, '.claude.json'), section: 'mcpServers' },
|
|
488
|
+
)
|
|
489
|
+
}
|
|
490
|
+
return list
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** The server map inside a third-party document, honoring its declared section. */
|
|
494
|
+
function extractSection(document, section) {
|
|
495
|
+
if (document === null || typeof document !== 'object' || Array.isArray(document)) return undefined
|
|
496
|
+
const isMap = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
497
|
+
if (typeof section === 'string' && isMap(document[section])) return document[section]
|
|
498
|
+
for (const key of ['mcpServers', 'servers', 'mcp']) {
|
|
499
|
+
if (isMap(document[key])) return document[key]
|
|
500
|
+
}
|
|
501
|
+
return undefined
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Read MCP servers from the other agent tools installed for this user. */
|
|
505
|
+
async function discover(ctx, refresh) {
|
|
506
|
+
const now = Date.now()
|
|
507
|
+
if (!refresh && now - discoveryCache.at < DISCOVERY_TTL_MS) return discoveryCache.value
|
|
508
|
+
const found = []
|
|
509
|
+
for (const candidate of discoveryCandidates()) {
|
|
510
|
+
let text
|
|
511
|
+
try {
|
|
512
|
+
const info = await stat(candidate.path)
|
|
513
|
+
if (!info.isFile()) continue
|
|
514
|
+
if (info.size > MAX_CONFIG_BYTES) {
|
|
515
|
+
found.push({ id: candidate.id, label: candidate.label, path: candidate.path, error: '文件超过 2 MB,已跳过。', servers: [] })
|
|
516
|
+
continue
|
|
517
|
+
}
|
|
518
|
+
text = await readFile(candidate.path, 'utf8')
|
|
519
|
+
} catch (error) {
|
|
520
|
+
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue
|
|
521
|
+
found.push({ id: candidate.id, label: candidate.label, path: candidate.path, error: messageOf(error), servers: [] })
|
|
522
|
+
continue
|
|
523
|
+
}
|
|
524
|
+
let document
|
|
525
|
+
try {
|
|
526
|
+
document = JSON.parse(text.replace(/^\uFEFF/, ''))
|
|
527
|
+
} catch (error) {
|
|
528
|
+
found.push({ id: candidate.id, label: candidate.label, path: candidate.path, error: `JSON 解析失败:${messageOf(error)}`, servers: [] })
|
|
529
|
+
continue
|
|
530
|
+
}
|
|
531
|
+
const section = extractSection(document, candidate.section)
|
|
532
|
+
if (section === undefined) continue
|
|
533
|
+
const servers = []
|
|
534
|
+
for (const [name, raw] of Object.entries(section)) {
|
|
535
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
536
|
+
servers.push({ name, error: '配置不是对象。' })
|
|
537
|
+
continue
|
|
538
|
+
}
|
|
539
|
+
try {
|
|
540
|
+
assertServerName(name)
|
|
541
|
+
const config = normalizeManagerEntry(raw)
|
|
542
|
+
servers.push({ name, transport: config.transport, config })
|
|
543
|
+
} catch (error) {
|
|
544
|
+
servers.push({ name, error: messageOf(error) })
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
if (servers.length > 0) {
|
|
548
|
+
found.push({ id: candidate.id, label: candidate.label, path: candidate.path, section: candidate.section, servers })
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
discoveryCache = { at: now, value: found }
|
|
552
|
+
return found
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Resolve the manager row, settings service, and its current form descriptor. */
|
|
556
|
+
function requireManager(ctx) {
|
|
557
|
+
let entries
|
|
558
|
+
try {
|
|
559
|
+
entries = [...ctx.loader.entries()]
|
|
560
|
+
} catch (error) {
|
|
561
|
+
throw fail('loader-unavailable', `读取插件清单失败:${messageOf(error)}`)
|
|
562
|
+
}
|
|
563
|
+
const entry = entries.find(item => item.options?.name === MANAGER_PKG)
|
|
564
|
+
if (entry === undefined) {
|
|
565
|
+
throw fail('manager-missing', '当前 profile 没有挂载 MCP 管理器(@deepseek-ai/dsh-mcp-manager),无法保存托管服务器。')
|
|
566
|
+
}
|
|
567
|
+
if (entry.disabled === true) {
|
|
568
|
+
throw fail('manager-disabled', 'MCP 管理器当前被停用,无法保存托管服务器。')
|
|
569
|
+
}
|
|
570
|
+
let settings
|
|
571
|
+
try {
|
|
572
|
+
settings = ctx.get('settings')
|
|
573
|
+
} catch {
|
|
574
|
+
settings = undefined
|
|
575
|
+
}
|
|
576
|
+
if (settings === undefined || typeof settings.describe !== 'function') {
|
|
577
|
+
throw fail('settings-missing', '设置服务未就绪,无法保存 MCP 配置。')
|
|
578
|
+
}
|
|
579
|
+
let descriptor
|
|
580
|
+
try {
|
|
581
|
+
descriptor = settings.describe().find(item => item.ns === entry.options.id)
|
|
582
|
+
} catch (error) {
|
|
583
|
+
throw fail('manager-unavailable', `读取 MCP 管理器配置失败:${messageOf(error)}`)
|
|
584
|
+
}
|
|
585
|
+
if (descriptor === undefined) {
|
|
586
|
+
throw fail('manager-unavailable', 'MCP 管理器还没有运行完成或当前不可配置,请稍后重试。')
|
|
587
|
+
}
|
|
588
|
+
return { entry, settings, descriptor }
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** Write the complete managed server map through the settings service. */
|
|
592
|
+
async function writeServers(manager, map) {
|
|
593
|
+
const cleaned = {}
|
|
594
|
+
for (const [name, config] of Object.entries(map)) {
|
|
595
|
+
cleaned[assertServerName(name)] = cleanManagerConfig(config)
|
|
596
|
+
}
|
|
597
|
+
await manager.settings.mutate(
|
|
598
|
+
manager.descriptor.ns,
|
|
599
|
+
[{ op: 'set', path: ['servers'], value: cleaned }],
|
|
600
|
+
manager.descriptor.revision,
|
|
601
|
+
)
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** Every MCP entry the current profile composes, managed or static. */
|
|
605
|
+
function relevantEntries(ctx) {
|
|
606
|
+
let entries
|
|
607
|
+
try {
|
|
608
|
+
entries = [...ctx.loader.entries()]
|
|
609
|
+
} catch {
|
|
610
|
+
return []
|
|
611
|
+
}
|
|
612
|
+
return entries
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/** Build the complete page snapshot. */
|
|
616
|
+
async function buildState(ctx, options = {}) {
|
|
617
|
+
const warnings = []
|
|
618
|
+
const capabilities = { managed: false, staticEditable: false, discovery: true }
|
|
619
|
+
const manager = { present: false, available: false, registered: [] }
|
|
620
|
+
const servers = []
|
|
621
|
+
const staticServers = []
|
|
622
|
+
const entries = relevantEntries(ctx)
|
|
623
|
+
const toolsByServer = collectTools(ctx)
|
|
624
|
+
const statuses = collectStatuses(ctx, warnings)
|
|
625
|
+
const managerEntry = entries.find(item => item.options?.name === MANAGER_PKG)
|
|
626
|
+
const settings = (() => {
|
|
627
|
+
try {
|
|
628
|
+
return ctx.get('settings')
|
|
629
|
+
} catch {
|
|
630
|
+
return undefined
|
|
631
|
+
}
|
|
632
|
+
})()
|
|
633
|
+
|
|
634
|
+
if (managerEntry !== undefined) {
|
|
635
|
+
manager.present = true
|
|
636
|
+
manager.entryId = managerEntry.id
|
|
637
|
+
manager.ns = managerEntry.options.id
|
|
638
|
+
manager.enabled = managerEntry.disabled !== true
|
|
639
|
+
let descriptor
|
|
640
|
+
if (settings !== undefined && typeof settings.describe === 'function') {
|
|
641
|
+
try {
|
|
642
|
+
descriptor = settings.describe().find(item => item.ns === managerEntry.options.id)
|
|
643
|
+
} catch (error) {
|
|
644
|
+
warnings.push(`读取 MCP 管理器配置失败:${messageOf(error)}`)
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
if (descriptor !== undefined && manager.enabled) {
|
|
648
|
+
capabilities.managed = true
|
|
649
|
+
manager.available = true
|
|
650
|
+
manager.revision = descriptor.revision
|
|
651
|
+
const effective = descriptor.value?.servers ?? {}
|
|
652
|
+
const user = descriptor.user?.servers ?? {}
|
|
653
|
+
const base = descriptor.base?.servers ?? {}
|
|
654
|
+
for (const [name, config] of Object.entries(effective)) {
|
|
655
|
+
const inUser = Object.prototype.hasOwnProperty.call(user, name)
|
|
656
|
+
const inBase = Object.prototype.hasOwnProperty.call(base, name)
|
|
657
|
+
servers.push({
|
|
658
|
+
name,
|
|
659
|
+
...summarizeServer(config),
|
|
660
|
+
enabled: config?.enabled !== false,
|
|
661
|
+
origin: inUser ? (inBase ? 'override' : 'profile') : 'base',
|
|
662
|
+
status: statuses.get(name) ?? null,
|
|
663
|
+
tools: toolsByServer.get(name) ?? [],
|
|
664
|
+
})
|
|
665
|
+
}
|
|
666
|
+
for (const [name, status] of statuses) {
|
|
667
|
+
if (status.configured !== true) manager.registered.push({ name, status })
|
|
668
|
+
}
|
|
669
|
+
} else if (!manager.enabled) {
|
|
670
|
+
manager.reason = 'manager-disabled'
|
|
671
|
+
} else {
|
|
672
|
+
manager.reason = settings === undefined ? 'settings-missing' : 'descriptor-missing'
|
|
673
|
+
}
|
|
674
|
+
} else {
|
|
675
|
+
manager.reason = 'manager-missing'
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const configEditor = (() => {
|
|
679
|
+
try {
|
|
680
|
+
return ctx.get('configEditor')
|
|
681
|
+
} catch {
|
|
682
|
+
return undefined
|
|
683
|
+
}
|
|
684
|
+
})()
|
|
685
|
+
const pluginManager = (() => {
|
|
686
|
+
try {
|
|
687
|
+
return ctx.get('pluginManager')
|
|
688
|
+
} catch {
|
|
689
|
+
return undefined
|
|
690
|
+
}
|
|
691
|
+
})()
|
|
692
|
+
if (configEditor === undefined || pluginManager === undefined) capabilities.staticEditable = false
|
|
693
|
+
else capabilities.staticEditable = true
|
|
694
|
+
|
|
695
|
+
for (const entry of entries) {
|
|
696
|
+
if (entry.options?.name !== CLIENT_PKG) continue
|
|
697
|
+
const config = entry.options.config ?? {}
|
|
698
|
+
const name = typeof config.serverName === 'string' ? config.serverName : ''
|
|
699
|
+
staticServers.push({
|
|
700
|
+
entryId: entry.id,
|
|
701
|
+
name,
|
|
702
|
+
...summarizeServer(config),
|
|
703
|
+
enabled: entry.disabled !== true,
|
|
704
|
+
phase: phaseOf(entry),
|
|
705
|
+
config: plain(config),
|
|
706
|
+
tools: toolsByServer.get(name) ?? [],
|
|
707
|
+
conflict: servers.some(server => server.name === name),
|
|
708
|
+
})
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
let discovered = []
|
|
712
|
+
try {
|
|
713
|
+
discovered = await discover(ctx, options.refreshDiscovery === true)
|
|
714
|
+
} catch (error) {
|
|
715
|
+
warnings.push(`扫描本机 MCP 配置失败:${messageOf(error)}`)
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
return {
|
|
719
|
+
ok: true,
|
|
720
|
+
generatedAt: Date.now(),
|
|
721
|
+
preferences: await readPreferences(),
|
|
722
|
+
manager,
|
|
723
|
+
capabilities,
|
|
724
|
+
servers,
|
|
725
|
+
staticServers,
|
|
726
|
+
discovered,
|
|
727
|
+
warnings,
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** The names of static rows that currently reserve a server namespace. */
|
|
732
|
+
function staticNames(ctx) {
|
|
733
|
+
const names = new Set()
|
|
734
|
+
for (const entry of relevantEntries(ctx)) {
|
|
735
|
+
if (entry.options?.name !== CLIENT_PKG) continue
|
|
736
|
+
if (entry.disabled === true) continue
|
|
737
|
+
const serverName = entry.options.config?.serverName
|
|
738
|
+
if (typeof serverName === 'string' && serverName !== '') names.add(serverName)
|
|
739
|
+
}
|
|
740
|
+
return names
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** Add one or more managed servers. */
|
|
744
|
+
async function createServers(ctx, body) {
|
|
745
|
+
const manager = requireManager(ctx)
|
|
746
|
+
let map
|
|
747
|
+
if (typeof body.json === 'string' && body.json.trim() !== '') {
|
|
748
|
+
map = parseServerDocument(body.json)
|
|
749
|
+
} else if (body.servers !== null && typeof body.servers === 'object' && !Array.isArray(body.servers)) {
|
|
750
|
+
map = body.servers
|
|
751
|
+
} else if (body.server !== null && typeof body.server === 'object') {
|
|
752
|
+
const name = body.name ?? body.server.name ?? body.server.serverName
|
|
753
|
+
if (typeof name !== 'string' || name.trim() === '') throw fail('name-required', '缺少服务器名称。')
|
|
754
|
+
map = { [name]: body.server }
|
|
755
|
+
} else {
|
|
756
|
+
throw fail('empty', '没有要添加的服务器。')
|
|
757
|
+
}
|
|
758
|
+
const names = Object.keys(map)
|
|
759
|
+
if (names.length === 0) throw fail('empty', '没有要添加的服务器。')
|
|
760
|
+
const effective = plain(manager.descriptor.value?.servers ?? {})
|
|
761
|
+
const reserved = staticNames(ctx)
|
|
762
|
+
const built = {}
|
|
763
|
+
for (const name of names) {
|
|
764
|
+
assertServerName(name)
|
|
765
|
+
if (effective[name] !== undefined) {
|
|
766
|
+
throw fail('duplicate', `服务器 “${name}” 已存在,请换一个名称或直接编辑它。`, { name })
|
|
767
|
+
}
|
|
768
|
+
if (reserved.has(name)) {
|
|
769
|
+
throw fail('static-collision', `服务器名 “${name}” 已被静态配置的 MCP 行占用;请换一个名称,或先停用那一行。`, { name })
|
|
770
|
+
}
|
|
771
|
+
built[name] = normalizeManagerEntry(map[name])
|
|
772
|
+
}
|
|
773
|
+
await writeServers(manager, { ...effective, ...built })
|
|
774
|
+
return { state: await buildState(ctx), added: names }
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** Replace one managed server's configuration. */
|
|
778
|
+
async function updateServer(ctx, body) {
|
|
779
|
+
const manager = requireManager(ctx)
|
|
780
|
+
const name = assertServerName(body.name)
|
|
781
|
+
const effective = plain(manager.descriptor.value?.servers ?? {})
|
|
782
|
+
if (effective[name] === undefined) throw fail('not-found', `找不到托管服务器 “${name}”。`, { name })
|
|
783
|
+
let raw = body.server ?? body.config
|
|
784
|
+
if (typeof body.json === 'string' && body.json.trim() !== '') {
|
|
785
|
+
const map = parseServerDocument(body.json, true)
|
|
786
|
+
raw = map[name] ?? map[''] ?? (Object.keys(map).length === 1 ? Object.values(map)[0] : undefined)
|
|
787
|
+
if (raw === undefined) {
|
|
788
|
+
throw fail('json-name-mismatch', `JSON 中没有名为 “${name}” 的服务器配置。`, { name })
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
if (raw === null || typeof raw !== 'object') throw fail('server-required', '缺少服务器配置。')
|
|
792
|
+
const normalized = normalizeManagerEntry(raw)
|
|
793
|
+
// An edit keeps the server's durable enabled intent unless the caller states it.
|
|
794
|
+
if (raw.enabled === undefined && raw.disabled === undefined) {
|
|
795
|
+
normalized.enabled = effective[name].enabled !== false
|
|
796
|
+
}
|
|
797
|
+
const next = { ...effective, [name]: normalized }
|
|
798
|
+
await writeServers(manager, next)
|
|
799
|
+
return { state: await buildState(ctx) }
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/** Delete one managed server. */
|
|
803
|
+
async function removeServer(ctx, body) {
|
|
804
|
+
const manager = requireManager(ctx)
|
|
805
|
+
const name = assertServerName(body.name)
|
|
806
|
+
const effective = plain(manager.descriptor.value?.servers ?? {})
|
|
807
|
+
const base = manager.descriptor.base?.servers ?? {}
|
|
808
|
+
if (effective[name] === undefined) throw fail('not-found', `找不到托管服务器 “${name}”。`, { name })
|
|
809
|
+
if (base[name] !== undefined) {
|
|
810
|
+
throw fail('inherited-readonly', `服务器 “${name}” 来自 profile 的基础配置,不能删除;可以停用它。`, { name })
|
|
811
|
+
}
|
|
812
|
+
const next = { ...effective }
|
|
813
|
+
delete next[name]
|
|
814
|
+
await writeServers(manager, next)
|
|
815
|
+
return { state: await buildState(ctx) }
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** Enable or disable one managed server without removing its configuration. */
|
|
819
|
+
async function toggleServer(ctx, body) {
|
|
820
|
+
const manager = requireManager(ctx)
|
|
821
|
+
const name = assertServerName(body.name)
|
|
822
|
+
const effective = plain(manager.descriptor.value?.servers ?? {})
|
|
823
|
+
if (effective[name] === undefined) throw fail('not-found', `找不到托管服务器 “${name}”。`, { name })
|
|
824
|
+
const enabled = body.enabled === undefined ? effective[name].enabled === false : body.enabled !== false
|
|
825
|
+
const next = { ...effective, [name]: { ...effective[name], enabled } }
|
|
826
|
+
await writeServers(manager, next)
|
|
827
|
+
return { state: await buildState(ctx), enabled }
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** Rebuild one managed server's live connection. */
|
|
831
|
+
async function restartServer(ctx, body) {
|
|
832
|
+
const manager = requireManager(ctx)
|
|
833
|
+
const name = assertServerName(body.name)
|
|
834
|
+
let live
|
|
835
|
+
try {
|
|
836
|
+
live = ctx.get('mcpManager')
|
|
837
|
+
} catch {
|
|
838
|
+
live = undefined
|
|
839
|
+
}
|
|
840
|
+
if (live === undefined || typeof live.restart !== 'function') {
|
|
841
|
+
throw fail('manager-missing', 'MCP 管理器服务不可用,无法重启。')
|
|
842
|
+
}
|
|
843
|
+
await live.restart(name)
|
|
844
|
+
return { state: await buildState(ctx) }
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/** Probe one managed server without touching its live instance. */
|
|
848
|
+
async function probeServer(ctx, body) {
|
|
849
|
+
const name = assertServerName(body.name)
|
|
850
|
+
let live
|
|
851
|
+
try {
|
|
852
|
+
live = ctx.get('mcpManager')
|
|
853
|
+
} catch {
|
|
854
|
+
live = undefined
|
|
855
|
+
}
|
|
856
|
+
if (live === undefined || typeof live.probe !== 'function') {
|
|
857
|
+
throw fail('manager-missing', 'MCP 管理器服务不可用,无法探测。')
|
|
858
|
+
}
|
|
859
|
+
const timeout = positiveNumber(body.timeoutMs) ?? PROBE_TIMEOUT_MS
|
|
860
|
+
const result = await live.probe(name, { timeoutMs: timeout })
|
|
861
|
+
return { probe: result }
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
/** Enable or disable one statically composed mcp-client row. */
|
|
865
|
+
async function staticToggle(ctx, body) {
|
|
866
|
+
const entry = entryById(ctx, body.entryId)
|
|
867
|
+
if (entry.options?.name !== CLIENT_PKG) throw fail('not-mcp-client', '这个插件行不是 MCP 客户端。')
|
|
868
|
+
let pluginManager
|
|
869
|
+
try {
|
|
870
|
+
pluginManager = ctx.get('pluginManager')
|
|
871
|
+
} catch {
|
|
872
|
+
pluginManager = undefined
|
|
873
|
+
}
|
|
874
|
+
if (pluginManager === undefined || typeof pluginManager.setPluginEnabled !== 'function') {
|
|
875
|
+
throw fail('plugin-manager-missing', '插件管理服务不可用,无法启停静态 MCP 行。')
|
|
876
|
+
}
|
|
877
|
+
const enabled = body.enabled !== false
|
|
878
|
+
const outcome = await pluginManager.setPluginEnabled(entry.id, enabled)
|
|
879
|
+
return { change: outcome, state: await buildState(ctx) }
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** Build the next static mcp-client config, clearing the other transport's fields. */
|
|
883
|
+
function staticNextConfig(current, input) {
|
|
884
|
+
if (input === null || typeof input !== 'object') throw fail('server-required', '缺少服务器配置。')
|
|
885
|
+
const transport = transportOf(input) || transportOf(current)
|
|
886
|
+
if (transport !== 'stdio' && transport !== 'streamable-http') {
|
|
887
|
+
throw fail('transport-required', '请选择传输方式:stdio 或 streamable-http。')
|
|
888
|
+
}
|
|
889
|
+
const out = {}
|
|
890
|
+
for (const key of ['serverName', 'expandTemplates', 'maxInstructionBytes', 'failOnStartupError']) {
|
|
891
|
+
if (current[key] !== undefined) out[key] = current[key]
|
|
892
|
+
}
|
|
893
|
+
out.serverName = typeof current.serverName === 'string' && current.serverName !== '' ? current.serverName : input.serverName
|
|
894
|
+
assertServerName(out.serverName)
|
|
895
|
+
out.transport = transport
|
|
896
|
+
if (transport === 'stdio') {
|
|
897
|
+
const command = str(input.command ?? current.command).trim()
|
|
898
|
+
if (command === '') throw fail('command-required', 'stdio 服务器必须填写启动命令(command)。')
|
|
899
|
+
out.command = command
|
|
900
|
+
const args = stringArray(input.args ?? current.args)
|
|
901
|
+
if (args.length > 0) out.args = args
|
|
902
|
+
const env = stringMap(input.env ?? current.env)
|
|
903
|
+
if (Object.keys(env).length > 0) out.env = env
|
|
904
|
+
const cwd = str(input.cwd ?? current.cwd).trim()
|
|
905
|
+
if (cwd !== '') out.cwd = cwd
|
|
906
|
+
} else {
|
|
907
|
+
const url = str(input.url ?? current.url).trim()
|
|
908
|
+
if (!/^https?:\/\/\S+$/i.test(url)) throw fail('url-required', 'streamable-http 服务器必须填写以 http:// 或 https:// 开头的 URL。')
|
|
909
|
+
out.url = url
|
|
910
|
+
const headers = stringMap(input.headers ?? current.headers)
|
|
911
|
+
if (Object.keys(headers).length > 0) out.headers = headers
|
|
912
|
+
}
|
|
913
|
+
for (const key of ['toolCallTimeoutMs', 'startupTimeoutMs', 'closeTimeoutMs']) {
|
|
914
|
+
const number = positiveNumber(input[key] ?? current[key])
|
|
915
|
+
if (number !== undefined) out[key] = number
|
|
916
|
+
}
|
|
917
|
+
const reconnect = reconnectOf(input.reconnect !== undefined ? input.reconnect : current.reconnect)
|
|
918
|
+
if (reconnect !== undefined) out.reconnect = reconnect
|
|
919
|
+
if (input.failOnStartupError !== undefined) out.failOnStartupError = input.failOnStartupError === true
|
|
920
|
+
return out
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/** Edit one statically composed mcp-client row. */
|
|
924
|
+
async function staticUpdate(ctx, body) {
|
|
925
|
+
const entry = entryById(ctx, body.entryId)
|
|
926
|
+
if (entry.options?.name !== CLIENT_PKG) throw fail('not-mcp-client', '这个插件行不是 MCP 客户端。')
|
|
927
|
+
if (entry.disabled === true) throw fail('disabled', '这个静态 MCP 行已停用,请先启用再编辑。')
|
|
928
|
+
let configEditor
|
|
929
|
+
try {
|
|
930
|
+
configEditor = ctx.get('configEditor')
|
|
931
|
+
} catch {
|
|
932
|
+
configEditor = undefined
|
|
933
|
+
}
|
|
934
|
+
if (configEditor === undefined || typeof configEditor.edit !== 'function') {
|
|
935
|
+
throw fail('config-editor-missing', '配置编辑服务不可用,无法保存静态 MCP 行。')
|
|
936
|
+
}
|
|
937
|
+
const current = entry.options.config ?? {}
|
|
938
|
+
let input = body.server ?? body.config
|
|
939
|
+
if (typeof body.json === 'string' && body.json.trim() !== '') {
|
|
940
|
+
const map = parseServerDocument(body.json, true)
|
|
941
|
+
input = map[current.serverName] ?? map[''] ?? (Object.keys(map).length === 1 ? Object.values(map)[0] : undefined)
|
|
942
|
+
if (input === undefined) throw fail('json-name-mismatch', `JSON 中没有名为 “${String(current.serverName)}” 的服务器配置。`)
|
|
943
|
+
}
|
|
944
|
+
const next = staticNextConfig(current, input)
|
|
945
|
+
await configEditor.edit(entry, () => next)
|
|
946
|
+
return { state: await buildState(ctx) }
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/** Dispatch one browser action and return its result. */
|
|
950
|
+
async function dispatch(ctx, body) {
|
|
951
|
+
const action = typeof body.action === 'string' ? body.action : ''
|
|
952
|
+
switch (action) {
|
|
953
|
+
case 'create':
|
|
954
|
+
case 'import':
|
|
955
|
+
return createServers(ctx, body)
|
|
956
|
+
case 'update':
|
|
957
|
+
return updateServer(ctx, body)
|
|
958
|
+
case 'remove':
|
|
959
|
+
return removeServer(ctx, body)
|
|
960
|
+
case 'toggle':
|
|
961
|
+
return toggleServer(ctx, body)
|
|
962
|
+
case 'restart':
|
|
963
|
+
return restartServer(ctx, body)
|
|
964
|
+
case 'probe':
|
|
965
|
+
return probeServer(ctx, body)
|
|
966
|
+
case 'static-toggle':
|
|
967
|
+
return staticToggle(ctx, body)
|
|
968
|
+
case 'static-update':
|
|
969
|
+
return staticUpdate(ctx, body)
|
|
970
|
+
case 'preferences': {
|
|
971
|
+
if (typeof body.sidebarShortcut !== 'boolean') {
|
|
972
|
+
throw fail('invalid-preference', 'sidebarShortcut 必须是布尔值。')
|
|
973
|
+
}
|
|
974
|
+
await writePreferences({ sidebarShortcut: body.sidebarShortcut })
|
|
975
|
+
return { state: await buildState(ctx) }
|
|
976
|
+
}
|
|
977
|
+
case 'refresh':
|
|
978
|
+
return { state: await buildState(ctx, { refreshDiscovery: true }) }
|
|
979
|
+
default:
|
|
980
|
+
throw fail('unknown-action', `未知操作 “${action}”。`)
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/** One management request. */
|
|
985
|
+
async function handle(ctx, request, response) {
|
|
986
|
+
try {
|
|
987
|
+
if (!authorized(ctx, request, response)) return
|
|
988
|
+
if (request.method === 'GET') {
|
|
989
|
+
const state = await buildState(ctx)
|
|
990
|
+
sendJson(response, 200, state)
|
|
991
|
+
return
|
|
992
|
+
}
|
|
993
|
+
if (request.method !== 'POST') {
|
|
994
|
+
sendJson(response, 405, { ok: false, error: 'method-not-allowed' })
|
|
995
|
+
return
|
|
996
|
+
}
|
|
997
|
+
if (!sameOrigin(request, true)) {
|
|
998
|
+
sendJson(response, 403, { ok: false, error: 'not-same-origin' })
|
|
999
|
+
return
|
|
1000
|
+
}
|
|
1001
|
+
let body
|
|
1002
|
+
try {
|
|
1003
|
+
body = await readJsonBody(request)
|
|
1004
|
+
} catch (error) {
|
|
1005
|
+
sendJson(response, 400, { ok: false, code: error?.code ?? 'invalid-body', error: messageOf(error) })
|
|
1006
|
+
return
|
|
1007
|
+
}
|
|
1008
|
+
const result = await dispatch(ctx, body)
|
|
1009
|
+
sendJson(response, 200, { ok: true, ...result })
|
|
1010
|
+
} catch (error) {
|
|
1011
|
+
const code = typeof error?.code === 'string' ? error.code : 'error'
|
|
1012
|
+
sendJson(response, 200, {
|
|
1013
|
+
ok: false,
|
|
1014
|
+
code,
|
|
1015
|
+
error: messageOf(error),
|
|
1016
|
+
...(error?.details !== undefined ? { details: error.details } : {}),
|
|
1017
|
+
})
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
export const name = 'dsh-mcp-manage'
|
|
1022
|
+
export const inject = ['webServer']
|
|
1023
|
+
|
|
1024
|
+
export function apply(ctx) {
|
|
1025
|
+
ctx.effect(
|
|
1026
|
+
() => ctx.webServer.register(
|
|
1027
|
+
{ kind: 'exact', path: ROUTE, handler: (request, response) => handle(ctx, request, response) },
|
|
1028
|
+
'dsh-mcp-manage: management api',
|
|
1029
|
+
),
|
|
1030
|
+
'dsh-mcp-manage: management api route',
|
|
1031
|
+
)
|
|
1032
|
+
ctx.logger?.info?.('dsh-mcp-manage: management api mounted at %s', ROUTE)
|
|
1033
|
+
}
|