universal-plugin-hub 1.0.25 → 1.0.35

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/package.json CHANGED
@@ -2,8 +2,8 @@
2
2
  "name": "universal-plugin-hub",
3
3
  "title": "Universal Plugin Hub",
4
4
  "displayName": "Universal Plugin Hub",
5
- "description": "在 DSH 中使用 Claude Code、Codex 等软件生态的插件,一站式管理插件、Skills 与 MCP。支持添加自己的 Git 插件源、上传插件和 Skills、添加 MCP 服务器,自动扫描并开关本地 Skills,接入插件提供的子代理、MCP、Hooks 与 LSP。",
6
- "version": "1.0.25",
5
+ "description": "在 DSH 中使用 Claude Code、Codex 等软件生态的插件,一站式管理插件、Skills 与 MCP。支持添加 Git 插件源和 marketplace、上传插件和 Skills、添加 MCP 服务器,自动扫描并开关本地 Skills,接入插件提供的子代理、MCP、Hooks 与 LSP。",
6
+ "version": "1.0.35",
7
7
  "engines": {
8
8
  "dsh": ">=0.1.5-rc.1"
9
9
  },
package/src/index.js CHANGED
@@ -10,12 +10,45 @@ import { mountRoutes } from './routes.js'
10
10
  import { cancelAllOAuthVerifications } from './oauth.js'
11
11
  import { syncAllInstalledSkillsToDsh, installProfilePackages, findDshMainNodeModules, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from './install.js'
12
12
  import { createSkillsManager } from './skills.js'
13
+ import { createProfileApplicator } from './runtime.js'
13
14
  import { createRequire } from 'node:module'
14
15
  import { join } from 'node:path'
15
16
 
16
17
  export const name = 'universal-plugin-hub'
17
18
 
18
19
  export function apply(ctx) {
20
+ // The running host knows which profile it booted. Guessing from the
21
+ // filesystem writes patches into the wrong profile (e.g. a custom profile
22
+ // name would land in `web`), and the change then never loads.
23
+ // `profileContext` is provided asynchronously, so it must be injected —
24
+ // reading it eagerly here returns undefined on a real host.
25
+ // Everything below that resolves a profile path has to run *after* this, so
26
+ // it lives inside the injection rather than beside it.
27
+ let provisioned = Promise.resolve()
28
+ ctx.inject(['profileContext'], (hostCtx) => {
29
+ const name = hostCtx.profileContext?.name
30
+ if (typeof name === 'string' && name.trim()) process.env.DSH_PROFILE = name.trim()
31
+
32
+ // Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
33
+ try {
34
+ syncAllInstalledSkillsToDsh()
35
+ } catch (err) {
36
+ ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)
37
+ }
38
+
39
+ // Host packages disappear when a package manager re-resolves the profile
40
+ // (pnpm moves unrecognized packages to node_modules/.ignored), so repair
41
+ // them on every start instead of trusting a one-time install step.
42
+ // Detached on purpose: Cordis awaits whatever apply returns, and this does
43
+ // network probes and tarball extraction — the hub fiber must not wait on it.
44
+ // Exposed on the callback for tests that need to await it.
45
+ const provisioning = installProfilePackages([...LSP_HOST_PACKAGES, ...HOOK_HOST_PACKAGES]).catch((err) => {
46
+ ctx.logger?.warn?.(`[universal-plugin-hub] host package provisioning skipped: ${err.message}`)
47
+ })
48
+ provisioned = provisioning
49
+ })
50
+ // Exposed only so a test can await the detached provisioning.
51
+ apply.provisioned = () => provisioned
19
52
  const skills = createSkillsManager()
20
53
  ctx.inject(['skills'], (hostCtx) => {
21
54
  hostCtx.effect(() => skills.attach(hostCtx.skills, () => {
@@ -37,23 +70,9 @@ export function apply(ctx) {
37
70
  }
38
71
  hostCtx.effect(() => skills.attachAgents(hostCtx, createScope), 'universal-plugin-hub: scoped skill switches')
39
72
  })
40
- // Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
41
- try {
42
- syncAllInstalledSkillsToDsh()
43
- } catch (err) {
44
- ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)
45
- }
46
-
47
- // Host packages disappear when a package manager re-resolves the profile
48
- // (pnpm moves unrecognized packages to node_modules/.ignored), so repair
49
- // them on every start instead of trusting a one-time install step.
50
- installProfilePackages([...LSP_HOST_PACKAGES, ...HOOK_HOST_PACKAGES]).catch((err) => {
51
- ctx.logger?.warn?.(`[universal-plugin-hub] host package provisioning skipped: ${err.message}`)
52
- })
53
-
54
73
  ctx.inject(['webServer'], (hostCtx) => {
55
74
  hostCtx.effect(() => {
56
- const unmount = mountRoutes(hostCtx.webServer, skills)
75
+ const unmount = mountRoutes(hostCtx.webServer, skills, createProfileApplicator(ctx))
57
76
  return () => { unmount(); cancelAllOAuthVerifications() }
58
77
  }, 'universal-plugin-hub: http routes')
59
78
  })
package/src/install.js CHANGED
@@ -22,7 +22,7 @@ import { parseAgentDefinition, compileSubagentsHubSkill, cleanupLegacyPresets }
22
22
  import { buildPluginIcons } from './icons.js'
23
23
  import { beginOAuthVerification, completeOAuthVerification, saveCustomOAuthClient, readSavedOAuthClient } from './oauth.js'
24
24
  import { encodeOAuthConfig, isOAuthMode, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
25
- import { oauthStoreDir } from './oauth-store.js'
25
+ import { oauthStoreDir, readOAuthRecord, writeOAuthRecord, deleteOAuthRecord } from './oauth-store.js'
26
26
 
27
27
  const OAUTH_BRIDGE_PATH = fileURLToPath(new URL('./oauth-bridge.js', import.meta.url))
28
28
 
@@ -310,6 +310,183 @@ export function unregisterConnector(pluginName, connectorName) {
310
310
  return { ok: true, connected: false }
311
311
  }
312
312
 
313
+ /**
314
+ * Delete a user-added MCP server completely: registration, saved definition,
315
+ * per-tool state and any OAuth credentials. `unregisterConnector` alone is the
316
+ * "turn it off" path and deliberately keeps the saved remote config so the
317
+ * server can be switched back on; a delete must leave nothing behind, or
318
+ * re-adding the same name would silently inherit the old sign-in.
319
+ */
320
+ export function removeUserMcp(connectorName) {
321
+ const state = readState()
322
+ const saved = (Array.isArray(state.userMcps) ? state.userMcps : []).find((x) => x && x.name === connectorName)
323
+ if (!saved) throw new Error(`MCP 不存在:${connectorName}`)
324
+
325
+ // Credential keys cover both OAuth modes; the mode the server was saved with
326
+ // decides which file exists, and deleting a missing one is a no-op.
327
+ const remote = remoteConfigFromEntry(getConnectorEntry('user-mcp', connectorName)?.config) || saved
328
+ // A server can have been edited to a new URL since it signed in, so clear the
329
+ // record for every URL it is known to have used — the live one and the stored
330
+ // one — or the old sign-in survives the delete and is inherited on re-add.
331
+ const urls = new Set([remote?.url, saved.url, ...(Array.isArray(saved.usedUrls) ? saved.usedUrls : [])]
332
+ .filter((u) => typeof u === 'string' && u.trim()))
333
+ const credentialKeys = [...urls].flatMap((u) =>
334
+ ['auto_register', 'custom'].map((mode) => oauthCredentialKey('user-mcp', connectorName, u, mode)))
335
+ const url = remote?.url || saved.url || null
336
+
337
+ unregisterConnector('user-mcp', connectorName)
338
+
339
+ const toolsKey = `user-mcp::${connectorName}`
340
+ const toolsState = readMcpToolsState()
341
+ if (Object.prototype.hasOwnProperty.call(toolsState, toolsKey)) {
342
+ delete toolsState[toolsKey]
343
+ writeMcpToolsState(toolsState)
344
+ }
345
+ MEMORY_TOOLS_CACHE.delete(toolsKey)
346
+ for (const key of credentialKeys) {
347
+ try { deleteOAuthRecord(key) } catch {}
348
+ }
349
+
350
+ state.userMcps = (Array.isArray(state.userMcps) ? state.userMcps : []).filter((x) => x && x.name !== connectorName)
351
+ writeState(state)
352
+ return { ok: true, name: connectorName }
353
+ }
354
+
355
+ /**
356
+ * Normalize one saved user MCP definition. `fallback` supplies the previous
357
+ * record, so a body that omits a field inherits the stored value instead of
358
+ * resetting it.
359
+ */
360
+ export function userMcpConfig(name, body = {}, fallback = {}) {
361
+ // Only a *missing* field inherits the stored value. An explicit empty string
362
+ // is the user clearing the field; treating it as "keep previous" would make
363
+ // the editor unable to remove a callback port, scope or client id.
364
+ const pick = (value, previous) => (value === undefined ? previous : value)
365
+ // Remember every URL this server has used. A credential file is named by a
366
+ // hash of its URL, so once a server is edited to a new URL the old sign-in is
367
+ // unreachable unless its URL was recorded here.
368
+ const usedUrls = new Set(Array.isArray(fallback.usedUrls) ? fallback.usedUrls : [])
369
+ for (const candidate of [fallback.url, body.url]) {
370
+ if (typeof candidate === 'string' && candidate.trim()) usedUrls.add(candidate)
371
+ }
372
+ return {
373
+ name,
374
+ usedUrls: [...usedUrls],
375
+ transport: (body.transport || fallback.transport) === 'http' ? 'http' : 'stdio',
376
+ url: pick(body.url, fallback.url ?? null),
377
+ command: pick(body.command, fallback.command ?? null),
378
+ args: Array.isArray(body.args) ? body.args : (fallback.args || []),
379
+ env: body.env && typeof body.env === 'object' ? body.env : (fallback.env || {}),
380
+ headers: body.headers && typeof body.headers === 'object' ? body.headers : (fallback.headers || {}),
381
+ oauth: body.oauth || fallback.oauth || 'none',
382
+ oauthClientId: pick(body.oauthClientId, fallback.oauthClientId || ''),
383
+ oauthCallbackPort: pick(body.oauthCallbackPort, fallback.oauthCallbackPort ?? null),
384
+ oauthScope: pick(body.oauthScope, fallback.oauthScope || ''),
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Rename a user-added MCP. Everything that is keyed by the server name has to
390
+ * move with it: the cordis registration id, the saved OAuth record (its file
391
+ * name is a hash of the name, so a rename without this copy would look like a
392
+ * fresh, unauthenticated server), and per-tool state. OAuth records are copied
393
+ * before the re-registration so the new registration reuses the existing
394
+ * sign-in instead of starting a new browser handshake.
395
+ */
396
+ export function renameUserMcp(oldName, newName, payload) {
397
+ if (oldName === newName) {
398
+ return saveConnectorAuth('user-mcp', newName, payload)
399
+ }
400
+ const state = readState()
401
+ if (!Array.isArray(state.userMcps)) state.userMcps = []
402
+ const idx = state.userMcps.findIndex((x) => x && x.name === oldName)
403
+ if (idx < 0) throw new Error(`MCP 不存在:${oldName}`)
404
+ if (state.userMcps.some((x) => x && x.name === newName)) throw new Error(`已存在同名 MCP:${newName}`)
405
+
406
+ const saved = state.userMcps[idx]
407
+ // One lookup for both facts: `readCordisPatch` re-reads and re-parses the
408
+ // patch file on every call, and this runs inside a user-visible action.
409
+ const entry = getConnectorEntry('user-mcp', oldName)
410
+ const wasEnabled = !!entry
411
+ const remote = remoteConfigFromEntry(entry?.config)
412
+ const url = remote?.url || saved.url || payload?.url || null
413
+ const modes = ['auto_register', 'custom']
414
+ // Carry every URL this server has used, exactly as `removeUserMcp` clears
415
+ // them: the sign-in may belong to a URL the server has since been edited
416
+ // away from, and copying only the current one would strand it.
417
+ const urls = [...new Set([url, saved.url, ...(Array.isArray(saved.usedUrls) ? saved.usedUrls : [])]
418
+ .filter((u) => typeof u === 'string' && u.trim()))]
419
+
420
+ for (const source of urls) {
421
+ for (const mode of modes) {
422
+ const from = oauthCredentialKey('user-mcp', oldName, source, mode)
423
+ const to = oauthCredentialKey('user-mcp', newName, source, mode)
424
+ const record = readOAuthRecord(from)
425
+ if (record && Object.keys(record).length > 0) writeOAuthRecord(to, record)
426
+ }
427
+ }
428
+
429
+ if (wasEnabled) {
430
+ const clientId = url ? readSavedOAuthClient('user-mcp', newName, url, 'custom').clientId : ''
431
+ // `saveConnectorAuth` reports failure both by returning `{ok:false}` and by
432
+ // throwing (e.g. a missing OAuth client id), so the rollback lives in one
433
+ // place that both paths reach.
434
+ const rollback = () => {
435
+ for (const source of urls) for (const mode of modes) deleteOAuthRecord(oauthCredentialKey('user-mcp', newName, source, mode))
436
+ }
437
+ let result
438
+ try {
439
+ result = saveConnectorAuth('user-mcp', newName, {
440
+ ...payload,
441
+ // A cleared field stays cleared: falling back to the stored id would put
442
+ // the old client back into the live registration while the definition
443
+ // says empty, and the next toggle would fail on the mismatch.
444
+ oauthClientId: payload?.oauthClientId !== undefined ? payload.oauthClientId : (clientId || ''),
445
+ })
446
+ } catch (error) {
447
+ // Leave the old server untouched: a failed rename must not strand the
448
+ // user with neither name registered.
449
+ rollback()
450
+ throw error
451
+ }
452
+ if (!result || !result.ok) {
453
+ rollback()
454
+ return result
455
+ }
456
+ // Only drop the old registration when it is a different entry. Names are
457
+ // normalized but ids are slugified, so `a.dot` and `a-dot` share one id —
458
+ // unregistering by the old name would delete the entry just written and
459
+ // leave the server silently disabled.
460
+ if (getConnectorId('user-mcp', oldName) !== getConnectorId('user-mcp', newName)) {
461
+ unregisterConnector('user-mcp', oldName)
462
+ }
463
+ }
464
+
465
+ const toolsState = readMcpToolsState()
466
+ const oldKey = `user-mcp::${oldName}`
467
+ const newKey = `user-mcp::${newName}`
468
+ if (toolsState[oldKey] || toolsState[newKey]) {
469
+ const merged = { ...(toolsState[oldKey] || {}), ...(toolsState[newKey] || {}) }
470
+ if (Array.isArray(toolsState[oldKey]?.disabledTools)) merged.disabledTools = toolsState[oldKey].disabledTools
471
+ delete merged.cachedTools
472
+ toolsState[newKey] = merged
473
+ delete toolsState[oldKey]
474
+ writeMcpToolsState(toolsState)
475
+ }
476
+ MEMORY_TOOLS_CACHE.delete(oldKey)
477
+ MEMORY_TOOLS_CACHE.delete(newKey)
478
+ for (const source of urls) for (const mode of modes) deleteOAuthRecord(oauthCredentialKey('user-mcp', oldName, source, mode))
479
+
480
+ // Keep the whole edited form, not just the name: `/mcps/update` routes a
481
+ // rename here with the same body a plain save sends, so a rename that also
482
+ // edits command/url/args/env/headers must persist those edits — and on an
483
+ // enabled server the patch was already written from them, so storing the old
484
+ // record would silently revert the edit on the next toggle.
485
+ state.userMcps[idx] = userMcpConfig(newName, payload, saved)
486
+ writeState(state)
487
+ return { ok: true, name: newName, previousName: oldName }
488
+ }
489
+
313
490
  // ── LSP server registration (cordis.patch.yml → @deepseek-ai/dsh-lsp-stdio) ──
314
491
  //
315
492
  // DSH exposes LSP as a capability seam with three packages:
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
2
2
  import { dirname, join } from 'node:path'
3
3
  import { execFileSync } from 'node:child_process'
4
4
  import { randomBytes } from 'node:crypto'
@@ -84,3 +84,14 @@ export function saveOAuthClientCredentials(key, client) {
84
84
  }
85
85
  writeOAuthRecord(key, record)
86
86
  }
87
+
88
+ /**
89
+ * Delete a credential record outright. Used when the connector it belongs to is
90
+ * removed: leaving the file behind would resurrect a stale sign-in if a server
91
+ * of the same name were added again with the same URL and OAuth mode.
92
+ */
93
+ export function deleteOAuthRecord(key) {
94
+ const file = oauthCredentialPath(key)
95
+ RECORD_CACHE.delete(file)
96
+ try { rmSync(file, { force: true }) } catch {}
97
+ }
package/src/routes.js CHANGED
@@ -15,19 +15,20 @@ import { getOrFetchIcon, readLocalIcon } from './icons.js'
15
15
  import {
16
16
  installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered,
17
17
  toggleConnector, isConnectorActive, verifyConnectorAuth, saveConnectorAuth,
18
- fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, getConnectorEntry, readMcpToolsState,
18
+ fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, removeUserMcp, renameUserMcp, getConnectorEntry, getConnectorId, readMcpToolsState, userMcpConfig,
19
19
  } from './install.js'
20
20
  import { inspectLocalPlugin, importLocalPlugin, saveUploadedZip } from './local.js'
21
21
  import { getOAuthVerification, cancelOAuthVerification, readSavedOAuthClient } from './oauth.js'
22
22
  import { remoteConfigFromEntry } from './oauth-config.js'
23
+ import { scheduledResult } from './runtime.js'
23
24
 
24
25
  const API_PREFIX = '/universal-plugin-hub/api'
25
26
 
26
- export function mountRoutes(webServer, skills = null) {
27
+ export function mountRoutes(webServer, skills = null, applyProfile = null) {
27
28
  const r = webServer.register({
28
29
  kind: 'prefix',
29
30
  path: API_PREFIX,
30
- handler: (req, res) => handle(req, res, API_PREFIX, skills),
31
+ handler: (req, res) => handle(req, res, API_PREFIX, skills, applyProfile),
31
32
  })
32
33
  return () => {
33
34
  try { if (typeof r === 'function') r() } catch {}
@@ -38,23 +39,8 @@ function normalizeMcpName(value) {
38
39
  return String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '') || 'mcp'
39
40
  }
40
41
 
41
- function userMcpConfig(name, body) {
42
- return {
43
- name,
44
- transport: body.transport === 'http' ? 'http' : 'stdio',
45
- url: body.url || null,
46
- command: body.command || null,
47
- args: Array.isArray(body.args) ? body.args : [],
48
- env: body.env && typeof body.env === 'object' ? body.env : {},
49
- headers: body.headers && typeof body.headers === 'object' ? body.headers : {},
50
- oauth: body.oauth || 'none',
51
- oauthClientId: body.oauthClientId || '',
52
- oauthCallbackPort: body.oauthCallbackPort || null,
53
- oauthScope: body.oauthScope || '',
54
- }
55
- }
56
42
 
57
- async function handle(req, res, prefix = API_PREFIX, skills = null) {
43
+ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile = null) {
58
44
  const url = new URL(req.url, 'http://localhost')
59
45
  const path = url.pathname.slice(prefix.length).replace(/\/+$/, '') || '/'
60
46
  const method = req.method ?? 'GET'
@@ -119,6 +105,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
119
105
  })
120
106
  }
121
107
 
108
+ // The runtime outcome of the last saved change. It is intentionally a
109
+ // separate read: applying a change can restart this plugin, so the write
110
+ // answers immediately and the result arrives here.
111
+ if (method === 'GET' && path === '/apply-status') {
112
+ const token = Number(url.searchParams.get('token'))
113
+ return sendJson(res, 200, {
114
+ ok: true,
115
+ ...(typeof applyProfile?.status === 'function'
116
+ ? applyProfile.status(Number.isFinite(token) ? token : undefined)
117
+ : { application: 'unknown' }),
118
+ })
119
+ }
120
+
122
121
  if (path === '/skills' && method === 'GET' && skills) return sendJson(res, 200, { skills: await skills.list() })
123
122
  if (path === '/skills/refresh' && method === 'POST' && skills) {
124
123
  requireSameOrigin(req); skills.refresh()
@@ -323,7 +322,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
323
322
  for (const block of patch) {
324
323
  if (!block || !Array.isArray(block.insert)) continue
325
324
  for (const item of block.insert) {
326
- if (!item || typeof item.id !== 'string' || !item.id.startsWith('mcp-user-mcp-')) continue
325
+ if (!item || typeof item.id !== 'string' || !item.id.startsWith(getConnectorId('user-mcp', ''))) continue
327
326
  const cfg = item.config || {}
328
327
  if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
329
328
  state.userMcps.push(userMcpConfig(cfg.serverName, {
@@ -342,15 +341,22 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
342
341
  const entry = getConnectorEntry('user-mcp', x.name)
343
342
  const remote = remoteConfigFromEntry(entry?.config) || readMcpToolsState()[`user-mcp::${x.name}`]?.savedOAuthRemoteConfig
344
343
  const client = remote?.oauth === 'custom' ? readSavedOAuthClient('user-mcp', x.name, remote.url, remote.oauth) : null
344
+ // The live registration says what is *running*; the saved definition
345
+ // says what the editor should show. The client id comes from the
346
+ // credential record, since the definition never stores the secret.
345
347
  return {
346
348
  ...x,
347
349
  ...(remote ? {
348
350
  transport: 'http', url: remote.url, headers: remote.headers,
349
- oauth: remote.oauth, oauthClientId: client?.clientId || remote.oauthClientId,
351
+ oauth: remote.oauth,
352
+ oauthClientId: client?.clientId || x.oauthClientId || remote.oauthClientId,
350
353
  oauthHasClientSecret: client?.hasClientSecret || false,
351
- oauthCallbackPort: remote.oauthCallbackPort || null, oauthScope: remote.oauthScope || '',
354
+ // Fall back to the live config only when the definition has no
355
+ // opinion, so a cleared field stays cleared.
356
+ oauthCallbackPort: x.oauthCallbackPort ?? remote.oauthCallbackPort ?? null,
357
+ oauthScope: x.oauthScope ?? remote.oauthScope ?? '',
352
358
  } : {}),
353
- enabled: enabledIds.has('mcp-user-mcp-' + x.name),
359
+ enabled: enabledIds.has(getConnectorId('user-mcp', x.name)),
354
360
  }
355
361
  })
356
362
  return sendJson(res, 200, { ok: true, mcps })
@@ -383,26 +389,63 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
383
389
  state.userMcps.push(userMcpConfig(name, body))
384
390
  writeState(state)
385
391
  }
386
- return sendJson(res, 200, result)
392
+ // A rejected create registered nothing, so there is nothing to apply.
393
+ if (!result || !result.ok) return sendJson(res, 200, result)
394
+ return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]))
387
395
  }
388
396
 
389
397
  if (method === 'POST' && path === '/mcps/update') {
390
398
  requireSameOrigin(req)
391
399
  const body = await readJsonBody(req)
400
+ // `previousName` is only sent when the user renamed the server in the
401
+ // editor; without it the name in the body is also the stored one.
402
+ const previousName = body.previousName
403
+ ? safeSegment(normalizeMcpName(body.previousName), 'MCP 名称')
404
+ : null
392
405
  const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
393
406
  const state = readState()
394
407
  if (!Array.isArray(state.userMcps)) state.userMcps = []
395
- const idx = state.userMcps.findIndex((x) => x && x.name === name)
396
- if (idx < 0) throw new Error(`MCP 不存在:${name}`)
408
+ const idx = state.userMcps.findIndex((x) => x && x.name === (previousName || name))
409
+ if (idx < 0) throw new Error(`MCP 不存在:${previousName || name}`)
410
+ if (previousName && previousName !== name) {
411
+ // Capture enablement before the rename: a disabled server registers
412
+ // nothing, so asking HMR to start its id would target an entry that
413
+ // does not exist.
414
+ const renamingEnabled = !!getConnectorEntry('user-mcp', previousName)
415
+ const renamed = renameUserMcp(previousName, name, body)
416
+ // A rename that failed registered nothing, so there is nothing to apply.
417
+ if (!renamed || !renamed.ok) return sendJson(res, 200, renamed)
418
+ return sendJson(res, 200, scheduledResult(
419
+ renamed, applyProfile, renamingEnabled ? [getConnectorId('user-mcp', name)] : []))
420
+ }
397
421
  const wasEnabled = !!getConnectorEntry('user-mcp', name)
398
422
  let result = { ok: true }
399
423
  if (wasEnabled) {
400
424
  result = saveConnectorAuth('user-mcp', name, body)
401
425
  if (!result || !result.ok) return sendJson(res, 200, result)
402
426
  }
403
- state.userMcps[idx] = userMcpConfig(name, body)
427
+ // Pass the stored record so an edit keeps the URL history a later delete
428
+ // needs to find every credential this server ever issued.
429
+ state.userMcps[idx] = userMcpConfig(name, body, state.userMcps[idx])
404
430
  writeState(state)
405
- return sendJson(res, 200, result)
431
+ return sendJson(res, 200, scheduledResult(result, applyProfile, wasEnabled ? [getConnectorId('user-mcp', name)] : []))
432
+ }
433
+
434
+ // One segment only: `/mcps/<name>/tools` belongs to the tool routes below.
435
+ // Decode and validate before the single-segment test, or an encoded slash
436
+ // slips past it; and reject a name that normalizes to nothing rather than
437
+ // falling back to the literal "mcp", which could match a real server.
438
+ if (method === 'DELETE' && path.startsWith('/mcps/')) {
439
+ // Check segments *after* decoding: `prod%2Fdb` decodes to a two-segment
440
+ // path and must not fall through to the server named `prod-db`.
441
+ const decoded = decodeURIComponent(path.slice('/mcps/'.length))
442
+ if (decoded.includes('/')) return sendJson(res, 404, { error: 'not found' })
443
+ requireSameOrigin(req)
444
+ const normalized = String(decoded || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '')
445
+ if (!normalized) throw new Error('无效的 MCP 名称')
446
+ const name = safeSegment(normalized, 'MCP 名称')
447
+ const result = removeUserMcp(name)
448
+ return sendJson(res, 200, scheduledResult(result, applyProfile))
406
449
  }
407
450
 
408
451
  if (method === 'POST' && path === '/mcps/toggle') {
@@ -414,10 +457,12 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
414
457
  if (!cfg) throw new Error(`MCP 不存在:${name}`)
415
458
  if (body.enabled !== false) {
416
459
  const result = saveConnectorAuth('user-mcp', name, cfg)
417
- return sendJson(res, 200, result)
460
+ // A rejected enable registered nothing: do not schedule a reconcile.
461
+ if (!result || !result.ok) return sendJson(res, 200, result)
462
+ return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]))
418
463
  }
419
464
  unregisterConnector('user-mcp', name)
420
- return sendJson(res, 200, { ok: true })
465
+ return sendJson(res, 200, scheduledResult({ ok: true }, applyProfile))
421
466
  }
422
467
 
423
468
  // ── user MCP tool list / per-tool toggle (same shape as plugin connectors) ──
@@ -476,7 +521,9 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
476
521
  const connectorName = safeSegment(parts[2], 'connector name')
477
522
  const body = await readJsonBody(req)
478
523
  const result = toggleConnector(pluginName, connectorName, body.enabled !== false)
479
- return sendJson(res, 200, result)
524
+ // A rejected toggle registered nothing: do not schedule a reconcile.
525
+ if (!result || !result.ok) return sendJson(res, 200, result)
526
+ return sendJson(res, 200, scheduledResult(result, applyProfile, body.enabled !== false ? [getConnectorId(pluginName, connectorName)] : []))
480
527
  }
481
528
 
482
529
  if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/verify')) {
@@ -496,7 +543,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
496
543
  const connectorName = safeSegment(parts[2], 'connector name')
497
544
  const body = await readJsonBody(req)
498
545
  const result = saveConnectorAuth(pluginName, connectorName, body)
499
- return sendJson(res, 200, result)
546
+ return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId(pluginName, connectorName)]))
500
547
  }
501
548
 
502
549
  // ── plugin detail ────────────────────────────────────────────────────
@@ -572,14 +619,14 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
572
619
  pluginName,
573
620
  })
574
621
  invalidateMarketplaceCache(sourceId)
575
- return sendJson(res, 200, result)
622
+ return sendJson(res, 200, scheduledResult(result, applyProfile))
576
623
  }
577
624
 
578
625
  if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/toggle')) {
579
626
  requireSameOrigin(req)
580
627
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/toggle'.length), 'plugin name')
581
628
  const body = await readJsonBody(req)
582
- return sendJson(res, 200, await togglePlugin(pluginName, body.enabled === true))
629
+ return sendJson(res, 200, scheduledResult(await togglePlugin(pluginName, body.enabled === true), applyProfile))
583
630
  }
584
631
 
585
632
  if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/update')) {
@@ -587,7 +634,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
587
634
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/update'.length), 'plugin name')
588
635
  const result = await updatePlugin(pluginName)
589
636
  invalidateMarketplaceCache()
590
- return sendJson(res, 200, result)
637
+ return sendJson(res, 200, scheduledResult(result, applyProfile))
591
638
  }
592
639
 
593
640
  if (method === 'POST' && path === '/restart') {
@@ -630,7 +677,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
630
677
  const pluginName = safeSegment(path.slice('/plugins/'.length), 'plugin name')
631
678
  const result = uninstallPlugin(pluginName)
632
679
  invalidateMarketplaceCache()
633
- return sendJson(res, 200, result)
680
+ return sendJson(res, 200, scheduledResult(result, applyProfile))
634
681
  }
635
682
 
636
683
  return sendJson(res, 404, { error: 'not found' })