@momeidejiyi/dsh-general-mcp 0.3.1 → 0.3.2

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/src/index.ts CHANGED
@@ -12,7 +12,7 @@ import { join } from 'node:path'
12
12
  import { buildCatalog, validateTool, type CatalogEntry, type ToolSettings } from './catalog.ts'
13
13
  import type { McpTool } from './client.ts'
14
14
  import { connectMcp, type McpConnection } from './connect.ts'
15
- import { publicToolName } from './naming.ts'
15
+ import { publicToolName, uniqueToolName } from './naming.ts'
16
16
  import { createToolDefinition } from './register.ts'
17
17
 
18
18
  export const name = 'general-mcp'
@@ -63,6 +63,10 @@ interface ServerState {
63
63
  client?: McpConnection
64
64
  enabled: boolean
65
65
  timeoutMs: number
66
+ /** raw tool name -> public (uniquified) tool name for the current discovery. */
67
+ publicNames?: Map<string, string>
68
+ /** Last successful tools/list, so a settings change can re-publish without reconnecting. */
69
+ lastTools?: McpTool[]
66
70
  }
67
71
 
68
72
  interface RuntimeState {
@@ -74,6 +78,8 @@ interface RuntimeState {
74
78
  retryIntervalMs: number
75
79
  maxRetries: number
76
80
  pollIntervalMs: number
81
+ /** Set when the persisted config could not be read; keeps routes alive. */
82
+ lastError: string
77
83
  }
78
84
 
79
85
  const NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/
@@ -93,9 +99,12 @@ function state(): RuntimeState {
93
99
  retryIntervalMs: 30_000,
94
100
  maxRetries: 20,
95
101
  pollIntervalMs: 15_000,
102
+ lastError: '',
96
103
  }
97
104
  }
98
- return shared.__GENMCP_STATE__
105
+ const runtime = shared.__GENMCP_STATE__
106
+ if (typeof runtime.lastError !== 'string') runtime.lastError = ''
107
+ return runtime
99
108
  }
100
109
 
101
110
  function serverState(name: string): ServerState {
@@ -133,12 +142,22 @@ function normalizeSettings(raw: any): ToolSettings {
133
142
  const overrides: Record<string, any> = {}
134
143
  if (tools.overrides !== null && typeof tools.overrides === 'object' && !Array.isArray(tools.overrides)) {
135
144
  for (const [key, value] of Object.entries(tools.overrides as Record<string, any>)) {
136
- if (value !== null && typeof value === 'object') overrides[key] = value
145
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) continue
146
+ // Validate per field: a string "folder" used to survive into discovery and
147
+ // then crash buildCatalog (override.folder.map is not a function).
148
+ const cleaned: Record<string, unknown> = {}
149
+ if (typeof value.title === 'string') cleaned.title = value.title
150
+ if (Array.isArray(value.folder) && value.folder.every((item: unknown) => typeof item === 'string')) cleaned.folder = value.folder
151
+ if (Object.keys(cleaned).length > 0) overrides[key] = cleaned
137
152
  }
138
153
  }
154
+ const disabled = Array.isArray(tools.disabled) ? tools.disabled.filter((item: unknown) => typeof item === 'string') : []
155
+ // "hidden" only ever meant "not listed but still callable", which nobody can
156
+ // tell apart from "disabled" in the UI. Old configs keep working: the entries
157
+ // move to disabled, so the tool is no longer registered.
158
+ const legacyHidden = Array.isArray(tools.hidden) ? tools.hidden.filter((item: unknown) => typeof item === 'string') : []
139
159
  return {
140
- disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item: unknown) => typeof item === 'string') : [],
141
- hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item: unknown) => typeof item === 'string') : [],
160
+ disabled: [...new Set([...disabled, ...legacyHidden])],
142
161
  removed: Array.isArray(tools.removed) ? tools.removed.filter((item: unknown) => typeof item === 'string') : [],
143
162
  overrides,
144
163
  }
@@ -182,10 +201,23 @@ function normalizeConfig(config: Config | undefined): ServerConfig[] {
182
201
  return out
183
202
  }
184
203
 
204
+ export { SseClient, resolveMessageUrl } from './sse.ts'
205
+
185
206
  export function apply(ctx: any, config?: Config): void {
186
207
  const live = state()
187
- const servers = normalizeConfig(config)
188
- beacon('host-apply ' + servers.map(item => item.name).join(','))
208
+ let servers: ServerConfig[] = []
209
+ let configError = ''
210
+ try {
211
+ servers = normalizeConfig(config)
212
+ } catch (error) {
213
+ // Rejecting the whole plugin would leave the settings page without routes
214
+ // (and the user without a way to fix the config in the UI), so degrade to
215
+ // "no gateways" and surface the reason instead.
216
+ configError = String((error as Error)?.message ?? error)
217
+ servers = []
218
+ }
219
+ live.lastError = configError
220
+ beacon('host-apply ' + servers.map(item => item.name).join(',') + (configError === '' ? '' : ' error=' + configError))
189
221
 
190
222
  const { disposeTools, registerTools, sync, scheduleRetry, stopRetry } = createRuntime(ctx)
191
223
 
@@ -222,11 +254,12 @@ export function apply(ctx: any, config?: Config): void {
222
254
  entry.enabled = enabled
223
255
  entry.timeoutMs = serverTimeout
224
256
  const nextSettings = normalizeSettings(item.tools)
257
+ const settingsChanged = JSON.stringify(entry.settings) !== JSON.stringify(nextSettings)
225
258
  // Display settings live outside the connection; a sync already in flight
226
259
  // read the old ones, so ask for one more pass once it settles.
227
260
  // Only a settings change that lands *while* a discovery is in flight needs a
228
261
  // second pass; otherwise sync() below already runs once.
229
- if (entry.sync !== undefined && JSON.stringify(entry.settings) !== JSON.stringify(nextSettings)) entry.stale = true
262
+ if (entry.sync !== undefined && settingsChanged) entry.stale = true
230
263
  entry.settings = nextSettings
231
264
  // Applying a settings change must not wait for a successful reconnect:
232
265
  // a removed/disabled tool has to stop being callable right away.
@@ -252,12 +285,34 @@ export function apply(ctx: any, config?: Config): void {
252
285
  live.version += 1
253
286
  }
254
287
  if (entry.endpoint === '' || entry.enabled === false) {
288
+ const hadState = entry.connected || entry.catalog.length > 0
255
289
  disposeTools(entry)
256
290
  stopRetry(entry)
291
+ // A disabled gateway must not keep a socket (or an SSE stream/server
292
+ // session) open: only the tools were being dropped before.
293
+ entry.generation = (entry.generation ?? 0) + 1
294
+ void entry.client?.close().catch(() => {})
295
+ entry.client = undefined
257
296
  entry.connected = false
258
297
  entry.toolCount = 0
259
298
  entry.catalog = []
260
299
  entry.lastError = entry.enabled === false ? '' : entry.lastError
300
+ // The page polls with ?since=<version>; a settings change on a disabled
301
+ // gateway still has to invalidate that snapshot or it stays 304 forever.
302
+ if (hadState || settingsChanged) live.version += 1
303
+ continue
304
+ }
305
+ if (!changed && entry.connected && entry.client !== undefined && entry.lastTools !== undefined) {
306
+ // Same endpoint and still connected: never reconnect here. Only a real
307
+ // settings change needs the catalogue republished from the last discovery
308
+ // (a debug/poll-interval save must not touch the gateways at all).
309
+ if (settingsChanged) {
310
+ disposeTools(entry)
311
+ entry.catalog = buildCatalog(entry.name, entry.lastTools, raw => entry.publicNames?.get(raw) ?? publicToolName(entry.name, raw), entry.settings)
312
+ registerTools(entry, entry.lastTools, entry.client)
313
+ entry.toolCount = entry.tools.size
314
+ live.version += 1
315
+ }
261
316
  continue
262
317
  }
263
318
  void sync(entry).then(ok => {
@@ -291,6 +346,8 @@ function createRuntime(ctx: any) {
291
346
  const invalid = validateTool(tool)
292
347
  if (invalid !== undefined) continue
293
348
  const definition: any = createToolDefinition(entry.name, tool, client)
349
+ const resolved = entry.publicNames?.get(tool.name)
350
+ if (resolved !== undefined) definition.name = resolved
294
351
  try {
295
352
  entry.tools.set(tool.name, ctx.tools.register(definition))
296
353
  } catch (error) {
@@ -323,19 +380,24 @@ function createRuntime(ctx: any) {
323
380
  try {
324
381
  const tools = await client.listTools()
325
382
  if (!alive(entry) || (entry.generation ?? 0) !== generation) return false
326
- const names = new Set(tools.map(tool => tool.name))
327
- const keep = (list: string[] | undefined) => (list ?? []).filter(name => names.has(name))
328
- entry.settings = {
329
- disabled: keep(entry.settings.disabled),
330
- hidden: keep(entry.settings.hidden),
331
- removed: keep(entry.settings.removed),
332
- overrides: Object.fromEntries(Object.entries(entry.settings.overrides ?? {}).filter(([name]) => names.has(name))),
383
+ // Two raw names can normalize to the same public name (a.b vs a_b).
384
+ // Give the second one a stable suffix instead of silently replacing it.
385
+ const used = new Set<string>()
386
+ const publicNames = new Map<string, string>()
387
+ for (const tool of tools as McpTool[]) {
388
+ const resolved = uniqueToolName(publicToolName(entry.name, tool.name), tool.name, used)
389
+ used.add(resolved)
390
+ publicNames.set(tool.name, resolved)
333
391
  }
392
+ entry.publicNames = publicNames
393
+ entry.lastTools = tools as McpTool[]
394
+ // Settings for tools that are momentarily absent stay: pruning them
395
+ // here would silently lose a user's disabled/override on next save.
334
396
  disposeTools(entry)
397
+ entry.catalog = buildCatalog(entry.name, tools as McpTool[], raw => publicNames.get(raw) ?? publicToolName(entry.name, raw), entry.settings)
335
398
  registerTools(entry, tools as McpTool[], client)
336
399
  entry.connected = true
337
400
  entry.toolCount = entry.tools.size
338
- entry.catalog = buildCatalog(entry.name, tools as McpTool[], raw => publicToolName(entry.name, raw), entry.settings)
339
401
  entry.lastError = ''
340
402
  entry.attempts = 0
341
403
  live.version += 1
@@ -353,7 +415,7 @@ function createRuntime(ctx: any) {
353
415
  return false
354
416
  } finally {
355
417
  entry.sync = undefined
356
- if (entry.stale === true && alive(entry) && entry.endpoint !== '') {
418
+ if (entry.stale === true && alive(entry) && entry.endpoint !== '' && entry.enabled !== false) {
357
419
  entry.stale = false
358
420
  void sync(entry).then(ok => { if (!ok && alive(entry)) scheduleRetry(entry) })
359
421
  }
@@ -372,6 +434,8 @@ function createRuntime(ctx: any) {
372
434
 
373
435
  const scheduleRetry = (entry: ServerState) => {
374
436
  if (entry.retryTimer !== undefined) return
437
+ // A disabled/removed gateway must not keep an interval alive.
438
+ if (entry.disposed === true || entry.enabled === false || entry.endpoint === '') return
375
439
  entry.retryTimer = setInterval(() => {
376
440
  entry.attempts += 1
377
441
  void sync(entry).then(ok => {
@@ -396,6 +460,12 @@ function installRoutes(ctx: any): void {
396
460
  const installed = (shared.__GENMCP_ROUTES__ ??= new WeakMap<object, boolean>())
397
461
  if (installed.get(webServer) === true) return
398
462
  installed.set(webServer, true)
463
+ const routeDisposers = (shared.__GENMCP_ROUTE_DISPOSERS__ ??= [] as Array<() => void>)
464
+ const route = (definition: any) => {
465
+ const disposer = webServer.register(definition)
466
+ if (typeof disposer === 'function') (routeDisposers as Array<() => void>).push(disposer)
467
+ }
468
+ shared.__GENMCP_WEBSERVER__ = webServer
399
469
 
400
470
  // The desktop shell renders the page from dsh-app:// and forwards /api to
401
471
  // this server, so sec-fetch-site is cross-site and Origin is an app scheme.
@@ -411,7 +481,9 @@ function installRoutes(ctx: any): void {
411
481
  const loopback = /^(127\.0\.0\.1|localhost|\[::1\])(:|$)/
412
482
  try {
413
483
  const originHost = new URL(origin).host
414
- if (host !== '' && originHost === host) return true
484
+ // origin===host alone is not proof of locality: a hostile domain can
485
+ // resolve to 127.0.0.1 (DNS rebinding) and present a matching pair.
486
+ if (host !== '' && originHost === host) return loopback.test(host)
415
487
  // A page served from loopback may talk to a differently-addressed loopback API.
416
488
  if (loopback.test(originHost) && loopback.test(host)) return true
417
489
  } catch {}
@@ -427,9 +499,12 @@ function installRoutes(ctx: any): void {
427
499
  'access-control-max-age': '600',
428
500
  vary: 'origin',
429
501
  }
430
- if (origin !== '') out['access-control-allow-origin'] = origin
502
+ if (origin !== '' && trusted({ headers })) out['access-control-allow-origin'] = origin
431
503
  return out
432
504
  }
505
+ const httpError = (status: number, message: string) => Object.assign(new Error(message), { status })
506
+ const statusOf = (error: unknown): number =>
507
+ typeof (error as any)?.status === 'number' ? (error as any).status : 500
433
508
  const send = (res: any, status: number, payload: unknown, extra: Record<string, string> = {}) => {
434
509
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...extra })
435
510
  res.end(JSON.stringify(payload))
@@ -438,14 +513,30 @@ function installRoutes(ctx: any): void {
438
513
  new Promise((resolve, reject) => {
439
514
  const chunks: Buffer[] = []
440
515
  let size = 0
516
+ let settled = false
517
+ const fail = (error: Error, destroy = false) => {
518
+ if (settled) return
519
+ settled = true
520
+ // Stop reading: an oversized or aborted body must not keep buffering.
521
+ chunks.length = 0
522
+ if (destroy) { try { req.destroy() } catch {} }
523
+ reject(error)
524
+ }
441
525
  req.on('data', (chunk: Buffer) => {
526
+ if (settled) return
442
527
  size += chunk.length
443
- if (size > limit) reject(new Error('body too large'))
444
- else chunks.push(chunk)
528
+ if (size > limit) { fail(new Error('body too large'), true); return }
529
+ chunks.push(chunk)
445
530
  })
446
531
  req.on('end', () => {
532
+ if (settled) return
533
+ settled = true
447
534
  try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) } catch { reject(new Error('invalid JSON body')) }
448
535
  })
536
+ // A client that hangs up mid-body would otherwise leave this promise
537
+ // pending (and the route closure alive) forever.
538
+ req.on('error', (error: Error) => fail(error))
539
+ req.on('aborted', () => fail(new Error('request aborted')))
449
540
  })
450
541
  const findEntry = () => {
451
542
  const editor = ctx.get?.('configEditor')
@@ -456,8 +547,10 @@ function installRoutes(ctx: any): void {
456
547
  }
457
548
 
458
549
  try {
459
- // Older DSH builds only dispatch "handler" routes; newer ones prefer the
460
- // Fetch-style "resource". Register both so the catalog works either way.
550
+ // Handler-only on purpose: when a route also declares "resource", the host
551
+ // dispatches that instead and answers OPTIONS with 405, which breaks the
552
+ // browser preflight for the Authorization header. Every DSH build
553
+ // dispatches "handler".
461
554
  const catalogPayload = (method: string, rawUrl: string, headers: Record<string, string>) => {
462
555
  const allowed = cors({ headers })
463
556
  if (method === 'OPTIONS') return { status: 204, headers: { ...allowed }, body: undefined as string | undefined }
@@ -471,6 +564,7 @@ function installRoutes(ctx: any): void {
471
564
  headers: { ...allowed, 'content-type': 'application/json; charset=utf-8' },
472
565
  body: JSON.stringify({
473
566
  version: live.version,
567
+ ...(live.lastError === '' ? {} : { configError: live.lastError }),
474
568
  timeoutMs: live.timeoutMs,
475
569
  retryIntervalMs: live.retryIntervalMs,
476
570
  maxRetries: live.maxRetries,
@@ -493,10 +587,15 @@ function installRoutes(ctx: any): void {
493
587
  }
494
588
  }
495
589
 
496
- webServer.register({
590
+ route({
497
591
  kind: 'exact',
498
592
  path: '/api/general-mcp/catalog',
499
593
  handler: (req: any, res: any) => {
594
+ if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS') {
595
+ res.writeHead(405, { allow: 'GET, HEAD, OPTIONS', ...cors(req) })
596
+ res.end()
597
+ return
598
+ }
500
599
  const out = catalogPayload(
501
600
  req.method ?? 'GET',
502
601
  req.url ?? '/',
@@ -510,40 +609,40 @@ function installRoutes(ctx: any): void {
510
609
  if (out.body === undefined) res.end()
511
610
  else res.end(out.body)
512
611
  },
513
- resource: async (request: any) => {
514
- const out = catalogPayload(
515
- request.method,
516
- request.url,
517
- {
518
- authorization: request.headers?.get?.('authorization') ?? '',
519
- origin: request.headers?.get?.('origin') ?? '',
520
- host: request.headers?.get?.('host') ?? '',
521
- },
522
- )
523
- return new Response(out.body ?? null, { status: out.status, headers: { 'cache-control': 'no-store', ...out.headers } })
524
- },
525
612
  })
526
613
 
527
- webServer.register({
614
+ route({
528
615
  kind: 'exact',
529
616
  path: '/api/general-mcp/probe',
530
617
  handler: (req: any, res: any) => {
531
618
  const extra = cors(req)
532
619
  for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
533
620
  if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
621
+ if (req.method !== 'POST' && req.method !== 'OPTIONS') {
622
+ // A GET used to fall through and run a write (and a plugin reload).
623
+ res.writeHead(405, { allow: 'POST, OPTIONS', ...cors(req) })
624
+ res.end()
625
+ return
626
+ }
534
627
  void (async () => {
628
+ let probe: McpConnection | undefined
535
629
  try {
536
630
  if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
537
631
  const body = await readBody(req)
538
632
  const endpoint = typeof body.endpoint === 'string' ? body.endpoint.trim() : ''
539
- if (!/^https?:\/\//i.test(endpoint)) throw new Error('endpoint must be an http(s) URL')
633
+ if (!/^https?:\/\//i.test(endpoint)) {
634
+ // Invalid input is the caller's fault; connection failures below
635
+ // stay 200 {ok:false} because probing a dead host is a normal result.
636
+ send(res, 400, { ok: false, message: 'endpoint must be an http(s) URL' })
637
+ return
638
+ }
540
639
  const headers: Record<string, string> = {}
541
640
  if (body.headers !== null && typeof body.headers === 'object' && !Array.isArray(body.headers)) {
542
641
  for (const [key, value] of Object.entries(body.headers as Record<string, unknown>)) {
543
642
  if (typeof value === 'string') headers[key] = value
544
643
  }
545
644
  }
546
- const probe = await connectMcp(endpoint, headers, 15_000)
645
+ probe = await connectMcp(endpoint, headers, 15_000)
547
646
  const tools = await probe.listTools()
548
647
  send(res, 200, {
549
648
  ok: true,
@@ -556,18 +655,27 @@ function installRoutes(ctx: any): void {
556
655
  })
557
656
  } catch (error) {
558
657
  send(res, 200, { ok: false, message: String((error as Error)?.message ?? error) })
658
+ } finally {
659
+ // A probe must not leave a transport (and its stream) behind.
660
+ await probe?.close().catch(() => {})
559
661
  }
560
662
  })()
561
663
  },
562
664
  })
563
665
 
564
- webServer.register({
666
+ route({
565
667
  kind: 'exact',
566
668
  path: '/api/general-mcp/config',
567
669
  handler: (req: any, res: any) => {
568
670
  const extra = cors(req)
569
671
  for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
570
672
  if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
673
+ if (req.method !== 'POST' && req.method !== 'OPTIONS') {
674
+ // A GET used to fall through and run a write (and a plugin reload).
675
+ res.writeHead(405, { allow: 'POST, OPTIONS', ...cors(req) })
676
+ res.end()
677
+ return
678
+ }
571
679
  void (async () => {
572
680
  try {
573
681
  if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
@@ -578,11 +686,19 @@ function installRoutes(ctx: any): void {
578
686
  const seen = new Set<string>()
579
687
  for (const item of incoming as any[]) {
580
688
  const name = String(item.name ?? 'general')
581
- if (!/^[A-Za-z0-9_-]{1,32}$/.test(name)) throw new Error('网关名 "' + name + '" 非法')
582
- if (seen.has(name)) throw new Error('网关名 "' + name + '" 重复')
689
+ if (!/^[A-Za-z0-9_-]{1,32}$/.test(name)) throw httpError(400, '网关名 "' + name + '" 非法')
690
+ if (seen.has(name)) throw httpError(400, '网关名 "' + name + '" 重复')
583
691
  const endpoint = item.endpoint
584
692
  if (endpoint !== undefined && endpoint !== null && endpoint !== '' && !/^https?:\/\//i.test(String(endpoint))) {
585
- throw new Error('网关 "' + name + '" 的地址必须以 http(s):// 开头')
693
+ throw httpError(400, '网关 "' + name + '" 的地址必须以 http(s):// 开头')
694
+ }
695
+ if (item.headers !== undefined && item.headers !== null) {
696
+ if (typeof item.headers !== 'object' || Array.isArray(item.headers)) throw httpError(400, '网关 "' + name + '" 的 headers 必须是对象')
697
+ for (const [key, value] of Object.entries(item.headers as Record<string, unknown>)) {
698
+ if (typeof key !== 'string' || key === '' || typeof value !== 'string') {
699
+ throw httpError(400, '网关 "' + name + '" 的 headers 值必须是字符串(' + key + ')')
700
+ }
701
+ }
586
702
  }
587
703
  seen.add(name)
588
704
  }
@@ -602,20 +718,20 @@ function installRoutes(ctx: any): void {
602
718
  const name = String(item.name ?? 'general')
603
719
  if (removed.has(name)) continue
604
720
  if (body.createOnly === true && byName.get(name) !== undefined) {
605
- throw new Error('网关 ' + name + ' 已存在')
721
+ throw httpError(409, '网关 ' + name + ' 已存在')
606
722
  }
607
723
  const previous = byName.get(name) ?? {}
608
724
  // A partial payload (only enabled/timeout/headers) must keep the
609
725
  // stored endpoint and tool settings.
610
726
  const hasEndpoint = typeof item.endpoint === 'string'
611
727
  if (!hasEndpoint && byName.get(name) === undefined) {
612
- throw new Error('网关 ' + name + ' 不存在,改动未保存')
728
+ throw httpError(404, '网关 ' + name + ' 不存在,改动未保存')
613
729
  }
614
730
  const endpoint = hasEndpoint ? item.endpoint.trim() : (previous.endpoint ?? '')
615
731
  const sameEndpoint = (previous.endpoint ?? '') === endpoint
616
732
  // Keep tool settings when only the endpoint changes: silently
617
- // dropping hidden/disabled/overrides was data loss. Entries for
618
- // tools the new server does not expose are pruned on the next sync.
733
+ // dropping disabled/overrides was data loss. Entries for tools
734
+ // the new server does not expose are pruned on the next sync.
619
735
  const next: any = { ...previous, ...item, name, endpoint }
620
736
  void sameEndpoint
621
737
  if (item.headersPatch !== null && typeof item.headersPatch === 'object' && !Array.isArray(item.headersPatch)) {
@@ -653,19 +769,25 @@ function installRoutes(ctx: any): void {
653
769
  send(res, 200, { ok: true })
654
770
  } catch (error) {
655
771
  beacon('config-save-error ' + String(error))
656
- send(res, 500, { ok: false, message: String((error as Error)?.message ?? error) })
772
+ send(res, statusOf(error), { ok: false, message: String((error as Error)?.message ?? error) })
657
773
  }
658
774
  })()
659
775
  },
660
776
  })
661
777
 
662
- webServer.register({
778
+ route({
663
779
  kind: 'exact',
664
780
  path: '/api/general-mcp/tools',
665
781
  handler: (req: any, res: any) => {
666
782
  const extra = cors(req)
667
783
  for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
668
784
  if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
785
+ if (req.method !== 'POST' && req.method !== 'OPTIONS') {
786
+ // A GET used to fall through and run a write (and a plugin reload).
787
+ res.writeHead(405, { allow: 'POST, OPTIONS', ...cors(req) })
788
+ res.end()
789
+ return
790
+ }
669
791
  void (async () => {
670
792
  try {
671
793
  if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
@@ -681,15 +803,26 @@ function installRoutes(ctx: any): void {
681
803
  const index = list.findIndex((item: any) => (item.name ?? 'general') === server)
682
804
  // Never invent a gateway: that would resurrect a deleted one as an
683
805
  // empty phantom and drag its old tool settings back with it.
684
- if (index < 0) throw new Error('网关 ' + server + ' 不存在,工具设置未保存')
806
+ if (index < 0) throw httpError(404, '网关 ' + server + ' 不存在,工具设置未保存')
685
807
  // Merge per key: a partial request (or a stale page) must not wipe
686
808
  // other lists such as removed/overrides.
687
809
  const previous = list[index].tools ?? {}
688
810
  const next: any = { ...previous }
689
811
  if (Array.isArray(body.disabled)) next.disabled = body.disabled.filter((v: unknown) => typeof v === 'string')
690
- if (Array.isArray(body.hidden)) next.hidden = body.hidden.filter((v: unknown) => typeof v === 'string')
812
+ if (Array.isArray(body.hidden)) {
813
+ // Legacy callers may still send "hidden": treat it as disabled.
814
+ const disabled = new Set(Array.isArray(next.disabled) ? next.disabled : [])
815
+ for (const name of body.hidden.filter((v: unknown) => typeof v === 'string')) disabled.add(name)
816
+ next.disabled = [...disabled]
817
+ delete next.hidden
818
+ }
691
819
  if (Array.isArray(body.removed)) next.removed = body.removed.filter((v: unknown) => typeof v === 'string')
692
- if (body.overrides !== null && typeof body.overrides === 'object' && !Array.isArray(body.overrides)) next.overrides = body.overrides
820
+ if (body.overrides !== undefined) {
821
+ if (body.overrides === null || typeof body.overrides !== 'object' || Array.isArray(body.overrides)) {
822
+ throw httpError(400, 'overrides 必须是以工具名为键的对象')
823
+ }
824
+ next.overrides = body.overrides
825
+ }
693
826
  list[index] = { ...list[index], tools: next }
694
827
  const { serverName, endpoint, headers, tools, ...rest } = current
695
828
  return { ...rest, servers: list }
@@ -698,7 +831,7 @@ function installRoutes(ctx: any): void {
698
831
  send(res, 200, { ok: true })
699
832
  } catch (error) {
700
833
  beacon('tools-save-error ' + String(error))
701
- send(res, 500, { ok: false, message: String((error as Error)?.message ?? error) })
834
+ send(res, statusOf(error), { ok: false, message: String((error as Error)?.message ?? error) })
702
835
  }
703
836
  })()
704
837
  },
@@ -722,19 +855,44 @@ function installRoutes(ctx: any): void {
722
855
  }
723
856
 
724
857
  ctx.effect?.(() => () => {
725
- for (const entry of state().servers.values()) {
858
+ const live = state()
859
+ for (const entry of live.servers.values()) {
860
+ entry.disposed = true
726
861
  if (entry.retryTimer !== undefined) clearInterval(entry.retryTimer)
862
+ entry.retryTimer = undefined
727
863
  for (const dispose of entry.tools.values()) {
728
864
  try { dispose() } catch {}
729
865
  }
730
866
  entry.tools.clear()
867
+ // Without this the HTTP/SSE connections outlive the plugin: every reload
868
+ // would leak one stream (and one server-side session) per gateway.
869
+ void entry.client?.close().catch(() => {})
870
+ entry.client = undefined
871
+ entry.sync = undefined
872
+ entry.connected = false
873
+ entry.toolCount = 0
874
+ entry.catalog = []
731
875
  }
876
+ live.servers.clear()
877
+ live.version += 1
878
+ const disposers = shared.__GENMCP_ROUTE_DISPOSERS__
879
+ if (Array.isArray(disposers)) {
880
+ for (const dispose of disposers.splice(0) as Array<() => void>) {
881
+ try { dispose() } catch {}
882
+ }
883
+ }
884
+ const webServer = shared.__GENMCP_WEBSERVER__
885
+ const installed = shared.__GENMCP_ROUTES__
886
+ if (webServer !== undefined && installed instanceof WeakMap) installed.delete(webServer as object)
732
887
  })
733
888
 
734
889
  shared.__GENMCP_STARTED__ = startedAt
735
890
  }
736
891
 
737
892
  function registerStatusTool(ctx: any): void {
893
+ // apply() runs on every config save; registering the status tool again would
894
+ // stack duplicates (the host may reject the second registration outright).
895
+ if (shared.__GENMCP_STATUS_CTX__ === ctx && typeof shared.__GENMCP_STATUS_DISPOSE__ === 'function') return
738
896
  const live = state()
739
897
  const startedAt = state() && ((shared.__GENMCP_STARTED__ as string) ?? new Date().toISOString())
740
898
  const dispose = ctx.tools.register({
@@ -770,7 +928,6 @@ function registerStatusTool(ctx: any): void {
770
928
  toolCount: entry.toolCount,
771
929
  lastError: entry.lastError,
772
930
  disabled: entry.settings.disabled ?? [],
773
- hidden: entry.settings.hidden ?? [],
774
931
  }))
775
932
  return {
776
933
  ok: servers.length > 0 && servers.every(item => item.connected || item.endpoint === ''),
@@ -779,5 +936,13 @@ function registerStatusTool(ctx: any): void {
779
936
  }
780
937
  },
781
938
  })
782
- ctx.effect?.(() => () => dispose())
939
+ shared.__GENMCP_STATUS_CTX__ = ctx
940
+ shared.__GENMCP_STATUS_DISPOSE__ = dispose
941
+ ctx.effect?.(() => () => {
942
+ dispose()
943
+ if (shared.__GENMCP_STATUS_DISPOSE__ === dispose) {
944
+ shared.__GENMCP_STATUS_DISPOSE__ = undefined
945
+ shared.__GENMCP_STATUS_CTX__ = undefined
946
+ }
947
+ })
783
948
  }
package/src/naming.ts CHANGED
@@ -14,6 +14,25 @@ function shortHash(value: string): string {
14
14
  return hash.toString(16).padStart(8, '0')
15
15
  }
16
16
 
17
+ /**
18
+ * Two raw names can normalize to the same public name ("a.b" and "a_b" both
19
+ * become "a_b"). Colliding names get a stable suffix derived from the raw name,
20
+ * so both tools stay callable and the catalogue stays key-unique.
21
+ */
22
+ export function uniqueToolName(base: string, rawName: string, used: Set<string>): string {
23
+ if (!used.has(base)) return base
24
+ const suffix = '_' + shortHash(rawName + '\u0000' + base)
25
+ const trimmed = base.slice(0, MAX_LENGTH - suffix.length)
26
+ let candidate = trimmed + suffix
27
+ let index = 1
28
+ while (used.has(candidate)) {
29
+ const tail = suffix + String(index)
30
+ candidate = base.slice(0, MAX_LENGTH - tail.length) + tail
31
+ index += 1
32
+ }
33
+ return candidate
34
+ }
35
+
17
36
  export function publicToolName(serverName: string, rawName: string): string {
18
37
  const base = 'mcp__' + sanitize(serverName) + '__' + sanitize(rawName)
19
38
  if (base.length <= MAX_LENGTH) return base