@momeidejiyi/dsh-general-mcp 0.1.7 → 0.1.9

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/catalog.ts CHANGED
@@ -9,6 +9,8 @@ export interface ToolOverride {
9
9
  export interface ToolSettings {
10
10
  disabled?: string[]
11
11
  hidden?: string[]
12
+ /** Removed from the tree entirely; separate from "disabled". */
13
+ removed?: string[]
12
14
  overrides?: Record<string, ToolOverride>
13
15
  }
14
16
 
@@ -31,6 +33,7 @@ export interface CatalogEntry {
31
33
  hash: string
32
34
  disabled: boolean
33
35
  hidden: boolean
36
+ removed?: boolean
34
37
  invalid?: ToolDiagnostic
35
38
  warning?: ToolDiagnostic
36
39
  }
@@ -130,6 +133,7 @@ export function buildCatalog(
130
133
  ): CatalogEntry[] {
131
134
  const disabled = new Set(settings.disabled ?? [])
132
135
  const hidden = new Set(settings.hidden ?? [])
136
+ const removed = new Set(settings.removed ?? [])
133
137
  return tools.map(tool => {
134
138
  const override = settings.overrides?.[tool.name]
135
139
  const invalid = validateTool(tool)
@@ -157,6 +161,7 @@ export function buildCatalog(
157
161
  hash: shortHash(description + JSON.stringify(tool.inputSchema ?? null) + JSON.stringify(folder)),
158
162
  disabled: disabled.has(tool.name),
159
163
  hidden: hidden.has(tool.name),
164
+ ...(removed.has(tool.name) ? { removed: true } : {}),
160
165
  ...(invalid !== undefined ? { invalid } : {}),
161
166
  ...(invalid === undefined && alias !== undefined ? { warning: alias } : {}),
162
167
  }
package/src/client.ts CHANGED
@@ -72,7 +72,10 @@ export class McpClient {
72
72
  const result = await this.request('server/discover', {}, undefined, MODERN)
73
73
  if (result === undefined || result === null) return undefined
74
74
  return result as Record<string, unknown>
75
- } catch {
75
+ } catch (error) {
76
+ // A timeout means the endpoint accepted the request and stalled; falling
77
+ // back to the legacy handshake would burn the same budget again.
78
+ if (/timed out/i.test(String((error as Error)?.message ?? ''))) throw error
76
79
  return undefined
77
80
  }
78
81
  }
@@ -94,13 +97,14 @@ export class McpClient {
94
97
  cursor = next
95
98
  }
96
99
  if (cursor !== undefined) throw new Error('tools/list did not terminate within 100 pages')
97
- const seen = new Set<string>()
100
+ // Duplicate names are tolerated: the last definition wins, so a server can
101
+ // refine a tool without the whole catalogue failing to load.
102
+ const byName = new Map<string, McpTool>()
98
103
  for (const tool of tools) {
99
- if (typeof tool.name !== 'string' || tool.name === '') throw new Error('tool without a name')
100
- if (seen.has(tool.name)) throw new Error('duplicate tool: ' + tool.name)
101
- seen.add(tool.name)
104
+ if (typeof tool.name !== 'string' || tool.name === '') continue
105
+ byName.set(tool.name, tool)
102
106
  }
103
- return tools
107
+ return [...byName.values()]
104
108
  }
105
109
 
106
110
  async callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<McpCallResult> {
package/src/connect.ts CHANGED
@@ -4,6 +4,8 @@ import { SseClient } from './sse.ts'
4
4
 
5
5
  export interface McpConnection {
6
6
  transport: 'streamable' | 'sse'
7
+ /** Human-readable transport detail, e.g. the SSE message endpoint. */
8
+ detail?: string
7
9
  protocolVersion: string | undefined
8
10
  serverInfo: unknown
9
11
  initialize(): Promise<void>
@@ -21,6 +23,7 @@ async function viaStreamable(url: string, headers: Record<string, string>, timeo
21
23
  const info: any = await client.initialize()
22
24
  return {
23
25
  transport: 'streamable',
26
+ detail: 'POST ' + url,
24
27
  protocolVersion: info?.protocolVersion,
25
28
  serverInfo: info?.serverInfo,
26
29
  async initialize() {},
@@ -35,6 +38,7 @@ async function viaSse(url: string, headers: Record<string, string>, timeoutMs: n
35
38
  const info: any = await client.initialize()
36
39
  return {
37
40
  transport: 'sse',
41
+ detail: 'GET ' + url + ' → POST ' + (client.messageEndpoint ?? '(pending)'),
38
42
  protocolVersion: info?.protocolVersion,
39
43
  serverInfo: info?.serverInfo,
40
44
  async initialize() {},
@@ -49,9 +53,12 @@ export async function connectMcp(
49
53
  headers: Record<string, string>,
50
54
  timeoutMs: number,
51
55
  ): Promise<McpConnection> {
56
+ // Cap the first attempt: a server that accepts the connection but never
57
+ // answers must not burn the full timeout before the fallback transport runs.
58
+ const probeMs = Math.min(timeoutMs, 8_000)
52
59
  const order: Array<() => Promise<McpConnection>> = looksLikeSse(url)
53
- ? [() => viaSse(url, headers, timeoutMs), () => viaStreamable(url, headers, timeoutMs)]
54
- : [() => viaStreamable(url, headers, timeoutMs), () => viaSse(url, headers, timeoutMs)]
60
+ ? [() => viaSse(url, headers, timeoutMs), () => viaStreamable(url, headers, probeMs)]
61
+ : [() => viaStreamable(url, headers, probeMs), () => viaSse(url, headers, timeoutMs)]
55
62
  const errors: string[] = []
56
63
  for (const attempt of order) {
57
64
  try {
package/src/index.ts CHANGED
@@ -11,7 +11,7 @@ import { tmpdir } from 'node:os'
11
11
  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
- import { connectMcp } from './connect.ts'
14
+ import { connectMcp, type McpConnection } from './connect.ts'
15
15
  import { publicToolName } from './naming.ts'
16
16
  import { createToolDefinition } from './register.ts'
17
17
 
@@ -23,6 +23,10 @@ export interface ServerConfig {
23
23
  endpoint?: string
24
24
  headers?: Record<string, string>
25
25
  tools?: ToolSettings
26
+ /** false keeps the gateway configured but disconnected. */
27
+ enabled?: boolean
28
+ /** Per-gateway override of the global request timeout. */
29
+ timeoutMs?: number
26
30
  }
27
31
 
28
32
  export interface Config {
@@ -31,6 +35,11 @@ export interface Config {
31
35
  endpoint?: string
32
36
  headers?: Record<string, string>
33
37
  toolCallTimeoutMs?: number
38
+ /** Reconnect cadence for a gateway that failed to connect. */
39
+ retryIntervalMs?: number
40
+ maxRetries?: number
41
+ /** How often the settings page re-reads the catalogue. */
42
+ pollIntervalMs?: number
34
43
  debug?: boolean
35
44
  tools?: ToolSettings
36
45
  }
@@ -48,6 +57,12 @@ interface ServerState {
48
57
  attempts: number
49
58
  retryTimer?: any
50
59
  sync?: Promise<boolean>
60
+ stale?: boolean
61
+ disposed?: boolean
62
+ generation?: number
63
+ client?: McpConnection
64
+ enabled: boolean
65
+ timeoutMs: number
51
66
  }
52
67
 
53
68
  interface RuntimeState {
@@ -56,6 +71,9 @@ interface RuntimeState {
56
71
  version: number
57
72
  debug: boolean
58
73
  timeoutMs: number
74
+ retryIntervalMs: number
75
+ maxRetries: number
76
+ pollIntervalMs: number
59
77
  }
60
78
 
61
79
  const NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/
@@ -72,6 +90,9 @@ function state(): RuntimeState {
72
90
  version: 0,
73
91
  debug: false,
74
92
  timeoutMs: 60_000,
93
+ retryIntervalMs: 30_000,
94
+ maxRetries: 20,
95
+ pollIntervalMs: 15_000,
75
96
  }
76
97
  }
77
98
  return shared.__GENMCP_STATE__
@@ -92,6 +113,8 @@ function serverState(name: string): ServerState {
92
113
  tools: new Map(),
93
114
  settings: {},
94
115
  attempts: 0,
116
+ enabled: true,
117
+ timeoutMs: 0,
95
118
  }
96
119
  live.servers.set(name, entry)
97
120
  }
@@ -116,6 +139,7 @@ function normalizeSettings(raw: any): ToolSettings {
116
139
  return {
117
140
  disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item: unknown) => typeof item === 'string') : [],
118
141
  hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item: unknown) => typeof item === 'string') : [],
142
+ removed: Array.isArray(tools.removed) ? tools.removed.filter((item: unknown) => typeof item === 'string') : [],
119
143
  overrides,
120
144
  }
121
145
  }
@@ -124,13 +148,19 @@ function normalizeSettings(raw: any): ToolSettings {
124
148
  function normalizeConfig(config: Config | undefined): ServerConfig[] {
125
149
  const raw = config ?? {}
126
150
  const live = state()
127
- const timeout = typeof raw.toolCallTimeoutMs === 'number' && Number.isFinite(raw.toolCallTimeoutMs)
128
- ? Math.min(Math.max(Math.round(raw.toolCallTimeoutMs), 1_000), 600_000)
129
- : 60_000
130
- live.timeoutMs = timeout
151
+ const clamp = (value: unknown, fallback: number, min: number, max: number): number =>
152
+ typeof value === 'number' && Number.isFinite(value)
153
+ ? Math.min(Math.max(Math.round(value), min), max)
154
+ : fallback
155
+ live.timeoutMs = clamp(raw.toolCallTimeoutMs, 60_000, 1_000, 600_000)
156
+ live.retryIntervalMs = clamp(raw.retryIntervalMs, 30_000, 5_000, 600_000)
157
+ live.maxRetries = clamp(raw.maxRetries, 20, 0, 1_000)
158
+ live.pollIntervalMs = clamp(raw.pollIntervalMs, 15_000, 2_000, 600_000)
131
159
  live.debug = raw.debug === true
132
160
 
133
- const list: ServerConfig[] = Array.isArray(raw.servers) && raw.servers.length > 0
161
+ // An explicit empty array means "no gateways"; only a missing key falls back
162
+ // to the legacy single-endpoint shape.
163
+ const list: ServerConfig[] = Array.isArray(raw.servers)
134
164
  ? raw.servers.map(item => ({ ...item }))
135
165
  : [{ name: raw.serverName, endpoint: raw.endpoint, headers: raw.headers, tools: raw.tools }]
136
166
 
@@ -162,8 +192,11 @@ export function apply(ctx: any, config?: Config): void {
162
192
  // Drop servers that are no longer configured.
163
193
  for (const [name, entry] of live.servers) {
164
194
  if (servers.some(item => item.name === name)) continue
195
+ entry.disposed = true
165
196
  stopRetry(entry)
166
197
  disposeTools(entry)
198
+ void entry.client?.close().catch(() => {})
199
+ entry.client = undefined
167
200
  live.servers.delete(name)
168
201
  live.version += 1
169
202
  }
@@ -176,30 +209,59 @@ export function apply(ctx: any, config?: Config): void {
176
209
  if (typeof value === 'string') headers[key] = value
177
210
  }
178
211
  }
212
+ const enabled = item.enabled !== false
213
+ const serverTimeout = typeof item.timeoutMs === 'number' && Number.isFinite(item.timeoutMs)
214
+ ? Math.min(Math.max(Math.round(item.timeoutMs), 1_000), 600_000)
215
+ : 0
179
216
  const changed = entry.endpoint !== (item.endpoint ?? '') ||
180
- JSON.stringify(entry.headers) !== JSON.stringify(headers)
217
+ JSON.stringify(entry.headers) !== JSON.stringify(headers) ||
218
+ entry.enabled !== enabled ||
219
+ entry.timeoutMs !== serverTimeout
181
220
  entry.endpoint = item.endpoint ?? ''
182
221
  entry.headers = headers
183
- entry.settings = normalizeSettings(item.tools)
222
+ entry.enabled = enabled
223
+ entry.timeoutMs = serverTimeout
224
+ const nextSettings = normalizeSettings(item.tools)
225
+ // Display settings live outside the connection; a sync already in flight
226
+ // read the old ones, so ask for one more pass once it settles.
227
+ // Only a settings change that lands *while* a discovery is in flight needs a
228
+ // second pass; otherwise sync() below already runs once.
229
+ if (entry.sync !== undefined && JSON.stringify(entry.settings) !== JSON.stringify(nextSettings)) entry.stale = true
230
+ entry.settings = nextSettings
231
+ // Applying a settings change must not wait for a successful reconnect:
232
+ // a removed/disabled tool has to stop being callable right away.
233
+ for (const raw of [...(nextSettings.removed ?? []), ...(nextSettings.disabled ?? [])]) {
234
+ const dispose = entry.tools.get(raw)
235
+ if (dispose === undefined) continue
236
+ try { dispose() } catch {}
237
+ entry.tools.delete(raw)
238
+ }
239
+ entry.toolCount = entry.tools.size
184
240
 
185
241
  if (changed) {
242
+ entry.generation = (entry.generation ?? 0) + 1
243
+ if (entry.sync !== undefined) entry.stale = true
186
244
  stopRetry(entry)
187
245
  disposeTools(entry)
246
+ void entry.client?.close().catch(() => {})
247
+ entry.client = undefined
188
248
  entry.connected = false
249
+ entry.catalog = []
189
250
  entry.lastError = ''
190
251
  entry.attempts = 0
191
252
  live.version += 1
192
253
  }
193
- if (entry.endpoint === '') {
254
+ if (entry.endpoint === '' || entry.enabled === false) {
194
255
  disposeTools(entry)
256
+ stopRetry(entry)
195
257
  entry.connected = false
196
258
  entry.toolCount = 0
197
259
  entry.catalog = []
198
- entry.lastError = ''
260
+ entry.lastError = entry.enabled === false ? '' : entry.lastError
199
261
  continue
200
262
  }
201
263
  void sync(entry).then(ok => {
202
- if (!ok) scheduleRetry(entry)
264
+ if (!ok && entry.disposed !== true && live.servers.get(entry.name) === entry) scheduleRetry(entry)
203
265
  }).catch(error => {
204
266
  entry.lastError = String((error as Error)?.message ?? error)
205
267
  live.version += 1
@@ -225,6 +287,7 @@ function createRuntime(ctx: any) {
225
287
  const settings = entry.settings
226
288
  for (const tool of tools) {
227
289
  if (settings.disabled?.includes(tool.name) === true) continue
290
+ if (settings.removed?.includes(tool.name) === true) continue
228
291
  const invalid = validateTool(tool)
229
292
  if (invalid !== undefined) continue
230
293
  const definition: any = createToolDefinition(entry.name, tool, client)
@@ -236,23 +299,51 @@ function createRuntime(ctx: any) {
236
299
  }
237
300
  }
238
301
 
302
+ const alive = (entry: ServerState): boolean =>
303
+ entry.disposed !== true && live.servers.get(entry.name) === entry
304
+
239
305
  const sync = (entry: ServerState): Promise<boolean> => {
240
306
  if (entry.sync !== undefined) return entry.sync
307
+ // Must be checked before the promise is stored: an early return would run
308
+ // the finally block before "entry.sync = run", leaving it permanently set.
309
+ if (entry.endpoint === '' || entry.enabled === false) return Promise.resolve(false)
241
310
  const run = (async () => {
242
- if (entry.endpoint === '') return false
243
- const client = await connectMcp(entry.endpoint, entry.headers, live.timeoutMs)
311
+ const generation = entry.generation ?? 0
244
312
  try {
245
- const tools = await client.listTools()
246
- disposeTools(entry)
247
- registerTools(entry, tools as McpTool[], client)
248
- entry.connected = true
249
- entry.toolCount = entry.tools.size
250
- entry.catalog = buildCatalog(entry.name, tools as McpTool[], raw => publicToolName(entry.name, raw), entry.settings)
251
- entry.lastError = ''
252
- entry.attempts = 0
253
- live.version += 1
254
- beacon('discovered ' + entry.name + ' tools=' + tools.length)
255
- return true
313
+ if (entry.endpoint === '' || entry.enabled === false) return false
314
+ const timeout = entry.timeoutMs > 0 ? entry.timeoutMs : live.timeoutMs
315
+ const client = await connectMcp(entry.endpoint, entry.headers, timeout)
316
+ if (!alive(entry) || (entry.generation ?? 0) !== generation) {
317
+ await client.close().catch(() => {})
318
+ return false
319
+ }
320
+ const previous = entry.client
321
+ entry.client = client
322
+ if (previous !== undefined && previous !== client) void previous.close().catch(() => {})
323
+ try {
324
+ const tools = await client.listTools()
325
+ 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))),
333
+ }
334
+ disposeTools(entry)
335
+ registerTools(entry, tools as McpTool[], client)
336
+ entry.connected = true
337
+ entry.toolCount = entry.tools.size
338
+ entry.catalog = buildCatalog(entry.name, tools as McpTool[], raw => publicToolName(entry.name, raw), entry.settings)
339
+ entry.lastError = ''
340
+ entry.attempts = 0
341
+ live.version += 1
342
+ beacon('discovered ' + entry.name + ' tools=' + tools.length)
343
+ return true
344
+ } catch (error) {
345
+ throw error
346
+ }
256
347
  } catch (error) {
257
348
  entry.connected = false
258
349
  entry.lastError = String((error as Error)?.message ?? error)
@@ -262,6 +353,10 @@ function createRuntime(ctx: any) {
262
353
  return false
263
354
  } finally {
264
355
  entry.sync = undefined
356
+ if (entry.stale === true && alive(entry) && entry.endpoint !== '') {
357
+ entry.stale = false
358
+ void sync(entry).then(ok => { if (!ok && alive(entry)) scheduleRetry(entry) })
359
+ }
265
360
  }
266
361
  })()
267
362
  entry.sync = run
@@ -280,9 +375,9 @@ function createRuntime(ctx: any) {
280
375
  entry.retryTimer = setInterval(() => {
281
376
  entry.attempts += 1
282
377
  void sync(entry).then(ok => {
283
- if (ok || entry.attempts >= 20) stopRetry(entry)
378
+ if (ok || entry.attempts >= live.maxRetries) stopRetry(entry)
284
379
  })
285
- }, 30_000)
380
+ }, live.retryIntervalMs)
286
381
  }
287
382
 
288
383
  return { disposeTools, registerTools, sync, scheduleRetry, stopRetry }
@@ -302,20 +397,41 @@ function installRoutes(ctx: any): void {
302
397
  if (installed.get(webServer) === true) return
303
398
  installed.set(webServer, true)
304
399
 
305
- const sameOrigin = (req: any): boolean => {
400
+ // The desktop shell renders the page from dsh-app:// and forwards /api to
401
+ // this server, so sec-fetch-site is cross-site and Origin is an app scheme.
402
+ // Accept: boot token, no Origin (non-browser), desktop/file origins, the
403
+ // server's own host, or any loopback host.
404
+ const trusted = (req: any): boolean => {
306
405
  const headers = req.headers ?? {}
307
- if (headers['sec-fetch-site'] === 'same-origin') return true
308
- const origin = headers.origin
309
- const host = headers.host
310
- if (typeof origin !== 'string' || typeof host !== 'string' || origin === '') return false
311
- try { return new URL(origin).host === host } catch { return false }
406
+ if ((headers.authorization ?? '') === 'Bearer ' + live.token) return true
407
+ const origin = typeof headers.origin === 'string' ? headers.origin : ''
408
+ const host = typeof headers.host === 'string' ? headers.host : ''
409
+ if (origin === '') return true
410
+ if (origin.startsWith('dsh-app:') || origin.startsWith('file:')) return true
411
+ const loopback = /^(127\.0\.0\.1|localhost|\[::1\])(:|$)/
412
+ try {
413
+ const originHost = new URL(origin).host
414
+ if (host !== '' && originHost === host) return true
415
+ // A page served from loopback may talk to a differently-addressed loopback API.
416
+ if (loopback.test(originHost) && loopback.test(host)) return true
417
+ } catch {}
418
+ return false
312
419
  }
313
- const authorized = (req: any): boolean => {
314
- const authorization = req.headers?.authorization ?? ''
315
- return authorization === 'Bearer ' + live.token || sameOrigin(req)
420
+ const authorized = (req: any): boolean => trusted(req)
421
+ const cors = (req: any): Record<string, string> => {
422
+ const headers = req.headers ?? {}
423
+ const origin = typeof headers.origin === 'string' ? headers.origin : ''
424
+ const out: Record<string, string> = {
425
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
426
+ 'access-control-allow-headers': 'content-type, authorization',
427
+ 'access-control-max-age': '600',
428
+ vary: 'origin',
429
+ }
430
+ if (origin !== '') out['access-control-allow-origin'] = origin
431
+ return out
316
432
  }
317
- const send = (res: any, status: number, payload: unknown) => {
318
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
433
+ const send = (res: any, status: number, payload: unknown, extra: Record<string, string> = {}) => {
434
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...extra })
319
435
  res.end(JSON.stringify(payload))
320
436
  }
321
437
  const readBody = (req: any, limit = 256 * 1024): Promise<Record<string, unknown>> =>
@@ -344,28 +460,43 @@ function installRoutes(ctx: any): void {
344
460
  kind: 'exact',
345
461
  path: '/api/general-mcp/catalog',
346
462
  resource: async (request: any) => {
347
- const headers = request.headers
348
- const bearer = headers?.get?.('authorization') === 'Bearer ' + live.token
349
- const origin = headers?.get?.('sec-fetch-site') === 'same-origin'
350
- if (!bearer && !origin) {
351
- return new Response('unauthorized', { status: 401, headers: { 'cache-control': 'no-store' } })
463
+ const hdr = {
464
+ authorization: request.headers?.get?.('authorization') ?? '',
465
+ origin: request.headers?.get?.('origin') ?? '',
466
+ host: request.headers?.get?.('host') ?? '',
467
+ }
468
+ const allowed = cors(hdr)
469
+ if (request.method === 'OPTIONS') {
470
+ return new Response(null, { status: 204, headers: { ...allowed, 'cache-control': 'no-store' } })
471
+ }
472
+ if (!trusted(hdr)) {
473
+ return new Response('unauthorized', { status: 401, headers: { ...allowed, 'cache-control': 'no-store' } })
352
474
  }
353
475
  const url = new URL(request.url)
354
476
  const raw = url.searchParams.get('since')
355
477
  const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1
356
- if (since === live.version) return new Response(null, { status: 304, headers: { 'cache-control': 'no-store' } })
478
+ if (since === live.version) return new Response(null, { status: 304, headers: { ...allowed, 'cache-control': 'no-store' } })
357
479
  return new Response(JSON.stringify({
358
480
  version: live.version,
481
+ timeoutMs: live.timeoutMs,
482
+ retryIntervalMs: live.retryIntervalMs,
483
+ maxRetries: live.maxRetries,
484
+ pollIntervalMs: live.pollIntervalMs,
485
+ debug: live.debug,
359
486
  servers: [...live.servers.values()].map(entry => ({
360
487
  name: entry.name,
361
488
  endpoint: entry.endpoint,
362
- status: entry.connected ? 'connected' : 'idle',
489
+ status: entry.connected ? 'connected' : entry.enabled === false ? 'disabled' : 'idle',
490
+ enabled: entry.enabled,
491
+ timeoutMs: entry.timeoutMs,
492
+ // Never ship header values to the page; names are enough to edit them.
493
+ headerNames: Object.keys(entry.headers),
363
494
  lastError: entry.lastError,
364
495
  toolCount: entry.toolCount,
365
496
  tools: entry.catalog,
366
497
  settings: entry.settings,
367
498
  })),
368
- }), { status: 200, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } })
499
+ }), { status: 200, headers: { ...allowed, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } })
369
500
  },
370
501
  })
371
502
 
@@ -373,6 +504,9 @@ function installRoutes(ctx: any): void {
373
504
  kind: 'exact',
374
505
  path: '/api/general-mcp/probe',
375
506
  handler: (req: any, res: any) => {
507
+ const extra = cors(req)
508
+ for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
509
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
376
510
  void (async () => {
377
511
  try {
378
512
  if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
@@ -391,6 +525,7 @@ function installRoutes(ctx: any): void {
391
525
  ok: true,
392
526
  protocolVersion: probe.protocolVersion ?? null,
393
527
  transport: probe.transport,
528
+ detail: probe.detail ?? null,
394
529
  server: (probe.serverInfo as any)?.name ?? null,
395
530
  version: (probe.serverInfo as any)?.version ?? null,
396
531
  tools: tools.map(tool => ({ name: tool.name, description: tool.description ?? '', folder: (tool._meta as any)?.['dsh/folder'] ?? null })),
@@ -406,15 +541,82 @@ function installRoutes(ctx: any): void {
406
541
  kind: 'exact',
407
542
  path: '/api/general-mcp/config',
408
543
  handler: (req: any, res: any) => {
544
+ const extra = cors(req)
545
+ for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
546
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
409
547
  void (async () => {
410
548
  try {
411
549
  if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
412
550
  const body = await readBody(req)
413
- const servers = Array.isArray(body.servers) ? body.servers : undefined
414
- if (servers === undefined) throw new Error('body.servers must be an array')
551
+ const incoming = Array.isArray(body.servers) ? body.servers : undefined
552
+ if (incoming === undefined) throw new Error('body.servers must be an array')
553
+ const removed = new Set(Array.isArray(body.removed) ? body.removed.filter((n: unknown) => typeof n === 'string') : [])
554
+ const seen = new Set<string>()
555
+ for (const item of incoming as any[]) {
556
+ const name = String(item.name ?? 'general')
557
+ if (!/^[A-Za-z0-9_-]{1,32}$/.test(name)) throw new Error('网关名 "' + name + '" 非法')
558
+ if (seen.has(name)) throw new Error('网关名 "' + name + '" 重复')
559
+ const endpoint = item.endpoint
560
+ if (endpoint !== undefined && endpoint !== null && endpoint !== '' && !/^https?:\/\//i.test(String(endpoint))) {
561
+ throw new Error('网关 "' + name + '" 的地址必须以 http(s):// 开头')
562
+ }
563
+ seen.add(name)
564
+ }
415
565
  const { editor, entry } = findEntry()
416
- await editor.edit(entry, (current: any) => ({ ...current, servers }))
417
- beacon('config-saved servers=' + servers.length)
566
+ await editor.edit(entry, (current: any) => {
567
+ // Merge instead of replacing: a stale page or a race must never
568
+ // delete gateways it did not explicitly ask to remove. An explicit
569
+ // empty array still means "no gateways" (never fall back to legacy).
570
+ const existing: any[] = Array.isArray(current.servers)
571
+ ? current.servers.map((item: any) => ({ ...item }))
572
+ : (typeof current.endpoint === 'string' && current.endpoint !== ''
573
+ ? [{ name: current.serverName ?? 'general', endpoint: current.endpoint, headers: current.headers ?? {}, tools: current.tools }]
574
+ : [])
575
+ const byName = new Map<string, any>()
576
+ for (const item of existing) byName.set(String(item.name ?? 'general'), item)
577
+ for (const item of incoming as any[]) {
578
+ const name = String(item.name ?? 'general')
579
+ if (removed.has(name)) continue
580
+ const previous = byName.get(name) ?? {}
581
+ // A partial payload (only enabled/timeout/headers) must keep the
582
+ // stored endpoint and tool settings.
583
+ const hasEndpoint = typeof item.endpoint === 'string'
584
+ const endpoint = hasEndpoint ? item.endpoint.trim() : (previous.endpoint ?? '')
585
+ const sameEndpoint = (previous.endpoint ?? '') === endpoint
586
+ const next: any = { ...previous, ...item, name, endpoint }
587
+ if (!sameEndpoint) delete next.tools
588
+ if (item.headersPatch !== null && typeof item.headersPatch === 'object' && !Array.isArray(item.headersPatch)) {
589
+ const headers: Record<string, string> = { ...(previous.headers ?? {}) }
590
+ for (const [key, value] of Object.entries(item.headersPatch as Record<string, unknown>)) {
591
+ if (value === null) delete headers[key]
592
+ else if (typeof value === 'string') headers[key] = value
593
+ }
594
+ next.headers = headers
595
+ }
596
+ delete next.headersPatch
597
+ byName.set(name, next)
598
+ }
599
+ for (const name of removed) byName.delete(name)
600
+ const servers = [...byName.values()]
601
+ const { serverName, endpoint, headers, tools, ...rest } = current
602
+ const next: any = { ...rest, servers }
603
+ // Display/behaviour knobs live next to the gateway list.
604
+ const knobs: Array<[string, number, number]> = [
605
+ ['toolCallTimeoutMs', 1_000, 600_000],
606
+ ['retryIntervalMs', 5_000, 600_000],
607
+ ['pollIntervalMs', 2_000, 600_000],
608
+ ['maxRetries', 0, 1_000],
609
+ ]
610
+ for (const [key, min, max] of knobs) {
611
+ const value = body[key]
612
+ if (typeof value === 'number' && Number.isFinite(value)) {
613
+ next[key] = Math.min(Math.max(Math.round(value), min), max)
614
+ }
615
+ }
616
+ if (typeof body.debug === 'boolean') next.debug = body.debug
617
+ return next
618
+ })
619
+ beacon('config-saved servers=' + (incoming as any[]).length + ' removed=' + removed.size)
418
620
  send(res, 200, { ok: true })
419
621
  } catch (error) {
420
622
  beacon('config-save-error ' + String(error))
@@ -428,25 +630,36 @@ function installRoutes(ctx: any): void {
428
630
  kind: 'exact',
429
631
  path: '/api/general-mcp/tools',
430
632
  handler: (req: any, res: any) => {
633
+ const extra = cors(req)
634
+ for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
635
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
431
636
  void (async () => {
432
637
  try {
433
638
  if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
434
639
  const body = await readBody(req)
435
640
  const server = typeof body.server === 'string' && body.server !== '' ? body.server : 'general'
436
- const tools = {
437
- disabled: Array.isArray(body.disabled) ? body.disabled.filter((v: unknown) => typeof v === 'string') : [],
438
- hidden: Array.isArray(body.hidden) ? body.hidden.filter((v: unknown) => typeof v === 'string') : [],
439
- overrides: body.overrides !== null && typeof body.overrides === 'object' ? body.overrides : {},
440
- }
441
641
  const { editor, entry } = findEntry()
442
642
  await editor.edit(entry, (current: any) => {
443
- const list = Array.isArray(current.servers) && current.servers.length > 0
643
+ const list: any[] = Array.isArray(current.servers)
444
644
  ? current.servers.map((item: any) => ({ ...item }))
445
- : [{ name: current.serverName ?? 'general', endpoint: current.endpoint ?? '', headers: current.headers ?? {} }]
645
+ : (typeof current.endpoint === 'string' && current.endpoint !== ''
646
+ ? [{ name: current.serverName ?? 'general', endpoint: current.endpoint, headers: current.headers ?? {}, tools: current.tools }]
647
+ : [])
446
648
  const index = list.findIndex((item: any) => (item.name ?? 'general') === server)
447
- if (index >= 0) list[index] = { ...list[index], tools }
448
- else list.push({ name: server, endpoint: '', tools })
449
- return { ...current, servers: list }
649
+ // Never invent a gateway: that would resurrect a deleted one as an
650
+ // empty phantom and drag its old tool settings back with it.
651
+ if (index < 0) throw new Error('网关 ' + server + ' 不存在,工具设置未保存')
652
+ // Merge per key: a partial request (or a stale page) must not wipe
653
+ // other lists such as removed/overrides.
654
+ const previous = list[index].tools ?? {}
655
+ const next: any = { ...previous }
656
+ if (Array.isArray(body.disabled)) next.disabled = body.disabled.filter((v: unknown) => typeof v === 'string')
657
+ if (Array.isArray(body.hidden)) next.hidden = body.hidden.filter((v: unknown) => typeof v === 'string')
658
+ if (Array.isArray(body.removed)) next.removed = body.removed.filter((v: unknown) => typeof v === 'string')
659
+ if (body.overrides !== null && typeof body.overrides === 'object' && !Array.isArray(body.overrides)) next.overrides = body.overrides
660
+ list[index] = { ...list[index], tools: next }
661
+ const { serverName, endpoint, headers, tools, ...rest } = current
662
+ return { ...rest, servers: list }
450
663
  })
451
664
  beacon('tools-saved ' + server)
452
665
  send(res, 200, { ok: true })
@@ -508,7 +721,8 @@ function registerStatusTool(ctx: any): void {
508
721
  },
509
722
  render(_args: unknown, value: any) {
510
723
  const lines = (value.servers ?? []).map((item: any) =>
511
- item.name + ': ' + (item.connected ? 'connected' : 'idle') + ' tools=' + item.toolCount +
724
+ item.name + ': ' + (item.connected ? 'connected' : item.enabled === false ? 'disabled' : 'idle') +
725
+ ' tools=' + item.toolCount + (item.timeoutMs > 0 ? ' timeout=' + item.timeoutMs + 'ms' : '') +
512
726
  (item.lastError === '' ? '' : ' error=' + item.lastError))
513
727
  return [{ type: 'text', text: 'general-mcp' + (lines.length === 0 ? ' (no gateways)' : '\n' + lines.join('\n')) }]
514
728
  },
@@ -518,6 +732,8 @@ function registerStatusTool(ctx: any): void {
518
732
  name: entry.name,
519
733
  endpoint: entry.endpoint,
520
734
  connected: entry.connected,
735
+ enabled: entry.enabled,
736
+ timeoutMs: entry.timeoutMs,
521
737
  toolCount: entry.toolCount,
522
738
  lastError: entry.lastError,
523
739
  disabled: entry.settings.disabled ?? [],
@@ -531,4 +747,4 @@ function registerStatusTool(ctx: any): void {
531
747
  },
532
748
  })
533
749
  ctx.effect?.(() => () => dispose())
534
- }
750
+ }