@momeidejiyi/dsh-general-mcp 0.1.4 → 0.1.6

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
@@ -1,22 +1,32 @@
1
1
  /**
2
- * @momeidejiyi/dsh-general-mcp - host half.
2
+ * general-mcp - host half.
3
3
  *
4
- * Connects one MCP gateway over Streamable HTTP, discovers its tools, registers
5
- * them on ctx.tools, and (when the web surface exists) serves the catalog and
6
- * config routes used by the Settings section.
4
+ * Connects one or more MCP gateways over Streamable HTTP, discovers their tools,
5
+ * registers them on ctx.tools, and serves the catalog/config routes used by the
6
+ * Settings section. Each configured gateway is an independent instance: its own
7
+ * name, endpoint, headers, tool settings, connection state and retry loop.
7
8
  */
8
9
  import { appendFileSync } from 'node:fs'
9
10
  import { tmpdir } from 'node:os'
10
11
  import { join } from 'node:path'
11
12
  import { buildCatalog, validateTool, type CatalogEntry, type ToolSettings } from './catalog.ts'
12
- import { McpClient, type McpTool } from './client.ts'
13
+ import type { McpTool } from './client.ts'
14
+ import { connectMcp } from './connect.ts'
13
15
  import { publicToolName } from './naming.ts'
14
16
  import { createToolDefinition } from './register.ts'
15
17
 
16
18
  export const name = 'general-mcp'
17
19
  export const inject = ['tools']
18
20
 
21
+ export interface ServerConfig {
22
+ name?: string
23
+ endpoint?: string
24
+ headers?: Record<string, string>
25
+ tools?: ToolSettings
26
+ }
27
+
19
28
  export interface Config {
29
+ servers?: ServerConfig[]
20
30
  serverName?: string
21
31
  endpoint?: string
22
32
  headers?: Record<string, string>
@@ -25,185 +35,264 @@ export interface Config {
25
35
  tools?: ToolSettings
26
36
  }
27
37
 
28
- interface RuntimeState {
29
- serverName: string
38
+ interface ServerState {
39
+ name: string
30
40
  endpoint: string
31
41
  headers: Record<string, string>
32
- timeoutMs: number
33
- debug: boolean
34
42
  connected: boolean
35
43
  toolCount: number
36
44
  lastError: string
37
45
  catalog: CatalogEntry[]
38
- toolSettings: ToolSettings
39
- version: number
40
- token: string
41
- sync?: Promise<boolean>
42
46
  tools: Map<string, () => void>
43
- retryTimer?: any
47
+ settings: ToolSettings
44
48
  attempts: number
49
+ retryTimer?: any
50
+ sync?: Promise<boolean>
45
51
  }
46
52
 
47
- const shared = globalThis as unknown as {
48
- __GENMCP_STATE__?: RuntimeState
49
- __GENMCP_ROUTES__?: WeakMap<object, boolean>
53
+ interface RuntimeState {
54
+ token: string
55
+ servers: Map<string, ServerState>
56
+ version: number
57
+ debug: boolean
58
+ timeoutMs: number
50
59
  }
51
60
 
52
- /** Coerce untrusted config into the shape the runtime expects. */
53
- function normalizeConfig(config: Config): void {
61
+ const NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/
62
+ const shared = globalThis as any
63
+
64
+ function state(): RuntimeState {
65
+ // Hot reload keeps globalThis: a state object written by an older version has
66
+ // no servers map, so migrate instead of trusting the existing shape.
67
+ const existing = shared.__GENMCP_STATE__
68
+ if (existing === undefined || !(existing.servers instanceof Map)) {
69
+ shared.__GENMCP_STATE__ = {
70
+ token: typeof existing?.token === 'string' ? existing.token : Math.random().toString(36).slice(2) + Date.now().toString(36),
71
+ servers: new Map<string, ServerState>(),
72
+ version: 0,
73
+ debug: false,
74
+ timeoutMs: 60_000,
75
+ }
76
+ }
77
+ return shared.__GENMCP_STATE__
78
+ }
79
+
80
+ function serverState(name: string): ServerState {
54
81
  const live = state()
55
- const raw = (config ?? {}) as Record<string, unknown>
56
- const endpoint = typeof raw.endpoint === 'string' ? raw.endpoint.trim() : ''
57
- if (endpoint !== '' && !/^https?:\/\//i.test(endpoint)) {
58
- throw new Error('endpoint must be an http(s) URL')
82
+ let entry = live.servers.get(name)
83
+ if (entry === undefined) {
84
+ entry = {
85
+ name,
86
+ endpoint: '',
87
+ headers: {},
88
+ connected: false,
89
+ toolCount: 0,
90
+ lastError: '',
91
+ catalog: [],
92
+ tools: new Map(),
93
+ settings: {},
94
+ attempts: 0,
95
+ }
96
+ live.servers.set(name, entry)
59
97
  }
60
- live.endpoint = endpoint
61
- live.serverName = typeof raw.serverName === 'string' && raw.serverName !== '' ? raw.serverName : 'general'
62
- const headers: Record<string, string> = {}
63
- if (raw.headers !== null && typeof raw.headers === 'object' && !Array.isArray(raw.headers)) {
64
- for (const [key, value] of Object.entries(raw.headers as Record<string, unknown>)) {
65
- if (typeof value === 'string') headers[key] = value
98
+ return entry
99
+ }
100
+
101
+ function beacon(message: string): void {
102
+ if (state().debug !== true) return
103
+ try {
104
+ appendFileSync(join(tmpdir(), 'dsh-general-mcp-debug.log'), new Date().toISOString() + ' ' + message + '\n')
105
+ } catch {}
106
+ }
107
+
108
+ function normalizeSettings(raw: any): ToolSettings {
109
+ const tools = raw ?? {}
110
+ const overrides: Record<string, any> = {}
111
+ if (tools.overrides !== null && typeof tools.overrides === 'object' && !Array.isArray(tools.overrides)) {
112
+ for (const [key, value] of Object.entries(tools.overrides as Record<string, any>)) {
113
+ if (value !== null && typeof value === 'object') overrides[key] = value
66
114
  }
67
115
  }
68
- live.headers = headers
116
+ return {
117
+ disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item: unknown) => typeof item === 'string') : [],
118
+ hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item: unknown) => typeof item === 'string') : [],
119
+ overrides,
120
+ }
121
+ }
122
+
123
+ /** Turn any historical config shape into a validated server list. */
124
+ function normalizeConfig(config: Config | undefined): ServerConfig[] {
125
+ const raw = config ?? {}
126
+ const live = state()
69
127
  const timeout = typeof raw.toolCallTimeoutMs === 'number' && Number.isFinite(raw.toolCallTimeoutMs)
70
- ? Math.min(Math.max(Math.round(raw.toolCallTimeoutMs), 1000), 600_000)
128
+ ? Math.min(Math.max(Math.round(raw.toolCallTimeoutMs), 1_000), 600_000)
71
129
  : 60_000
72
130
  live.timeoutMs = timeout
73
131
  live.debug = raw.debug === true
74
- const tools = (raw.tools ?? {}) as ToolSettings
75
- live.toolSettings = {
76
- disabled: Array.isArray(tools.disabled) ? tools.disabled.filter(item => typeof item === 'string') : [],
77
- hidden: Array.isArray(tools.hidden) ? tools.hidden.filter(item => typeof item === 'string') : [],
78
- overrides: tools.overrides !== null && typeof tools.overrides === 'object' ? tools.overrides : {},
79
- }
80
- }
81
132
 
82
- function state(): RuntimeState {
83
- shared.__GENMCP_STATE__ ??= {
84
- serverName: 'general',
85
- endpoint: '',
86
- headers: {},
87
- timeoutMs: 60_000,
88
- debug: false,
89
- connected: false,
90
- toolCount: 0,
91
- lastError: '',
92
- catalog: [],
93
- toolSettings: {},
94
- version: 0,
95
- token: crypto.randomUUID(),
96
- tools: new Map(),
97
- attempts: 0,
133
+ const list: ServerConfig[] = Array.isArray(raw.servers) && raw.servers.length > 0
134
+ ? raw.servers.map(item => ({ ...item }))
135
+ : [{ name: raw.serverName, endpoint: raw.endpoint, headers: raw.headers, tools: raw.tools }]
136
+
137
+ const seen = new Set<string>()
138
+ const out: ServerConfig[] = []
139
+ for (const item of list) {
140
+ const name = typeof item.name === 'string' && item.name.trim() !== '' ? item.name.trim() : 'general'
141
+ const endpoint = typeof item.endpoint === 'string' ? item.endpoint.trim() : ''
142
+ if (endpoint !== '' && !/^https?:\/\//i.test(endpoint)) {
143
+ throw new Error('网关 ' + name + ' 的地址必须以 http(s):// 开头')
144
+ }
145
+ if (!NAME_PATTERN.test(name)) {
146
+ throw new Error('网关名 "' + name + '" 非法:只能用字母、数字、下划线、短横线,1..32 字')
147
+ }
148
+ if (seen.has(name)) throw new Error('网关名 "' + name + '" 重复')
149
+ seen.add(name)
150
+ out.push({ ...item, name, endpoint })
98
151
  }
99
- return shared.__GENMCP_STATE__
152
+ return out
100
153
  }
101
154
 
102
- export async function apply(ctx: any, config: Config = {}) {
103
- normalizeConfig(config)
155
+ export function apply(ctx: any, config?: Config): void {
104
156
  const live = state()
105
- const startedAt = new Date().toISOString()
157
+ const servers = normalizeConfig(config)
158
+ beacon('host-apply ' + servers.map(item => item.name).join(','))
106
159
 
107
- const beacon = (stage: string) => {
108
- if (live.debug !== true) return
109
- try {
110
- appendFileSync(join(tmpdir(), 'dsh-general-mcp-debug.log'), new Date().toISOString() + ' ' + stage + '\n')
111
- } catch {}
160
+ const { disposeTools, registerTools, sync, scheduleRetry, stopRetry } = createRuntime(ctx)
161
+
162
+ // Drop servers that are no longer configured.
163
+ for (const [name, entry] of live.servers) {
164
+ if (servers.some(item => item.name === name)) continue
165
+ stopRetry(entry)
166
+ disposeTools(entry)
167
+ live.servers.delete(name)
168
+ live.version += 1
112
169
  }
113
170
 
114
- const disposeTools = () => {
115
- for (const [key, dispose] of live.tools) {
116
- try { dispose() } catch {}
117
- live.tools.delete(key)
171
+ for (const item of servers) {
172
+ const entry = serverState(item.name as string)
173
+ const headers: Record<string, string> = {}
174
+ if (item.headers !== null && typeof item.headers === 'object') {
175
+ for (const [key, value] of Object.entries(item.headers)) {
176
+ if (typeof value === 'string') headers[key] = value
177
+ }
178
+ }
179
+ const changed = entry.endpoint !== (item.endpoint ?? '') ||
180
+ JSON.stringify(entry.headers) !== JSON.stringify(headers)
181
+ entry.endpoint = item.endpoint ?? ''
182
+ entry.headers = headers
183
+ entry.settings = normalizeSettings(item.tools)
184
+
185
+ if (changed) {
186
+ stopRetry(entry)
187
+ disposeTools(entry)
188
+ entry.connected = false
189
+ entry.lastError = ''
190
+ entry.attempts = 0
191
+ live.version += 1
118
192
  }
193
+ if (entry.endpoint === '') {
194
+ disposeTools(entry)
195
+ entry.connected = false
196
+ entry.toolCount = 0
197
+ entry.catalog = []
198
+ entry.lastError = ''
199
+ continue
200
+ }
201
+ void sync(entry).then(ok => {
202
+ if (!ok) scheduleRetry(entry)
203
+ }).catch(error => {
204
+ entry.lastError = String((error as Error)?.message ?? error)
205
+ live.version += 1
206
+ })
119
207
  }
120
208
 
121
- const stopRetry = () => {
122
- if (live.retryTimer !== undefined) clearInterval(live.retryTimer)
123
- live.retryTimer = undefined
209
+ installRoutes(ctx)
210
+ registerStatusTool(ctx)
211
+ }
212
+
213
+ function createRuntime(ctx: any) {
214
+ const live = state()
215
+
216
+ const disposeTools = (entry: ServerState) => {
217
+ for (const dispose of entry.tools.values()) {
218
+ try { dispose() } catch {}
219
+ }
220
+ entry.tools.clear()
221
+ entry.toolCount = 0
124
222
  }
125
223
 
126
- /** Register one generation of tools, replacing the previous one atomically. */
127
- const registerTools = (tools: McpTool[], client: McpClient) => {
128
- const disabled = new Set(live.toolSettings.disabled ?? [])
129
- const hidden = new Set(live.toolSettings.hidden ?? [])
130
- disposeTools()
224
+ const registerTools = (entry: ServerState, tools: McpTool[], client: McpClient) => {
225
+ const settings = entry.settings
131
226
  for (const tool of tools) {
132
- if (hidden.has(tool.name) || disabled.has(tool.name)) continue
227
+ if (settings.disabled?.includes(tool.name) === true) continue
133
228
  const invalid = validateTool(tool)
134
- if (invalid !== undefined) {
135
- ctx.logger?.warn?.('general-mcp: rejected tool ' + tool.name + ' (' + invalid.code + '): ' + invalid.message)
136
- continue
229
+ if (invalid !== undefined) continue
230
+ const definition: any = createToolDefinition(entry.name, tool, client)
231
+ try {
232
+ entry.tools.set(tool.name, ctx.tools.register(definition))
233
+ } catch (error) {
234
+ beacon('register-failed ' + entry.name + '/' + tool.name + ' ' + String(error))
137
235
  }
138
- const definition: any = createToolDefinition(live.serverName, tool, client)
139
- const dispose = ctx.tools.register(definition)
140
- live.tools.set(definition.name, dispose)
141
236
  }
142
237
  }
143
238
 
144
- /** One discovery pass; serialized so overlapping generations cannot interleave. */
145
- const sync = (): Promise<boolean> => {
146
- if (live.sync !== undefined) return live.sync
239
+ const sync = (entry: ServerState): Promise<boolean> => {
240
+ if (entry.sync !== undefined) return entry.sync
147
241
  const run = (async () => {
148
- if (live.endpoint === '') {
149
- // Clearing the endpoint must also clear the previous generation's state,
150
- // otherwise a disabled plugin still reports the old tools as connected.
151
- disposeTools()
152
- live.connected = false
153
- live.toolCount = 0
154
- live.catalog = []
155
- live.lastError = ''
156
- live.version += 1
157
- return false
158
- }
159
- const client = new McpClient(live.endpoint, live.headers, live.timeoutMs)
242
+ if (entry.endpoint === '') return false
243
+ const client = await connectMcp(entry.endpoint, entry.headers, live.timeoutMs)
160
244
  try {
161
- await client.initialize()
162
245
  const tools = await client.listTools()
163
- registerTools(tools as McpTool[], client)
164
- live.connected = true
165
- live.toolCount = live.tools.size
166
- live.catalog = buildCatalog(live.serverName, tools as McpTool[], raw => publicToolName(live.serverName, raw), live.toolSettings)
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
167
253
  live.version += 1
168
- live.lastError = ''
169
- live.attempts = 0
170
- beacon('discovered ' + tools.length + ' version=' + live.version)
254
+ beacon('discovered ' + entry.name + ' tools=' + tools.length)
171
255
  return true
172
256
  } catch (error) {
173
- live.connected = false
174
- live.lastError = String((error as Error)?.message ?? error)
257
+ entry.connected = false
258
+ entry.lastError = String((error as Error)?.message ?? error)
175
259
  live.version += 1
176
- ctx.logger?.warn?.('general-mcp: ' + live.lastError)
177
- beacon('discover-error ' + live.lastError)
260
+ ctx.logger?.warn?.('general-mcp(' + entry.name + '): ' + entry.lastError)
261
+ beacon('discover-error ' + entry.name + ' ' + entry.lastError)
178
262
  return false
179
263
  } finally {
180
- live.sync = undefined
264
+ entry.sync = undefined
181
265
  }
182
266
  })()
183
- live.sync = run
267
+ entry.sync = run
184
268
  return run
185
269
  }
186
270
 
187
- const scheduleRetry = () => {
188
- if (live.retryTimer !== undefined) return
189
- live.retryTimer = setInterval(() => {
190
- live.attempts += 1
191
- void sync().then(ok => {
192
- if (ok || live.attempts >= 20) stopRetry()
271
+ const stopRetry = (entry: ServerState) => {
272
+ if (entry.retryTimer !== undefined) {
273
+ clearInterval(entry.retryTimer)
274
+ entry.retryTimer = undefined
275
+ }
276
+ }
277
+
278
+ const scheduleRetry = (entry: ServerState) => {
279
+ if (entry.retryTimer !== undefined) return
280
+ entry.retryTimer = setInterval(() => {
281
+ entry.attempts += 1
282
+ void sync(entry).then(ok => {
283
+ if (ok || entry.attempts >= 20) stopRetry(entry)
193
284
  })
194
285
  }, 30_000)
195
286
  }
196
287
 
197
- // Cordis has no "dispose" event; effects run their disposer at fiber teardown.
198
- ctx.effect(() => () => {
199
- stopRetry()
200
- disposeTools()
201
- })
288
+ return { disposeTools, registerTools, sync, scheduleRetry, stopRetry }
289
+ }
202
290
 
203
- beacon('host-apply ' + live.serverName)
291
+ function installRoutes(ctx: any): void {
292
+ const live = state()
293
+ const startedAt = new Date().toISOString()
204
294
 
205
- // ---- optional web surface -------------------------------------------------
206
- const installRoutes = (webCtx: any) => {
295
+ const install = (webCtx: any) => {
207
296
  const webServer = webCtx?.webServer ?? webCtx?.get?.('webServer')
208
297
  if (webServer === undefined || typeof webServer.register !== 'function') {
209
298
  beacon('host-no-webserver')
@@ -213,13 +302,9 @@ export async function apply(ctx: any, config: Config = {}) {
213
302
  if (installed.get(webServer) === true) return
214
303
  installed.set(webServer, true)
215
304
 
216
- // Writes accept either the boot token or a same-origin browser request.
217
- // The token alone made the UI unusable whenever index-inject did not fire
218
- // (older DSH builds, or a page loaded before the plugin registered).
219
305
  const sameOrigin = (req: any): boolean => {
220
306
  const headers = req.headers ?? {}
221
- const site = headers['sec-fetch-site']
222
- if (site === 'same-origin') return true
307
+ if (headers['sec-fetch-site'] === 'same-origin') return true
223
308
  const origin = headers.origin
224
309
  const host = headers.host
225
310
  if (typeof origin !== 'string' || typeof host !== 'string' || origin === '') return false
@@ -239,15 +324,13 @@ export async function apply(ctx: any, config: Config = {}) {
239
324
  let size = 0
240
325
  req.on('data', (chunk: Buffer) => {
241
326
  size += chunk.length
242
- if (size > limit) { reject(new Error('request body too large')); req.destroy(); return }
243
- chunks.push(chunk)
327
+ if (size > limit) reject(new Error('body too large'))
328
+ else chunks.push(chunk)
244
329
  })
245
330
  req.on('end', () => {
246
- try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) }
247
- catch (error) { reject(new Error('invalid JSON body')) }
331
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) } catch { reject(new Error('invalid JSON body')) }
248
332
  })
249
333
  })
250
-
251
334
  const findEntry = () => {
252
335
  const editor = ctx.get?.('configEditor')
253
336
  if (editor === undefined) throw new Error('config editor is unavailable')
@@ -261,12 +344,10 @@ export async function apply(ctx: any, config: Config = {}) {
261
344
  kind: 'exact',
262
345
  path: '/api/general-mcp/catalog',
263
346
  resource: async (request: any) => {
264
- // Read-only catalog: a same-origin GET is allowed so a stale injected
265
- // token cannot brick the page. Writes stay token-only.
266
347
  const headers = request.headers
267
348
  const bearer = headers?.get?.('authorization') === 'Bearer ' + live.token
268
- const sameOrigin = headers?.get?.('sec-fetch-site') === 'same-origin'
269
- if (!bearer && !sameOrigin) {
349
+ const origin = headers?.get?.('sec-fetch-site') === 'same-origin'
350
+ if (!bearer && !origin) {
270
351
  return new Response('unauthorized', { status: 401, headers: { 'cache-control': 'no-store' } })
271
352
  }
272
353
  const url = new URL(request.url)
@@ -275,12 +356,15 @@ export async function apply(ctx: any, config: Config = {}) {
275
356
  if (since === live.version) return new Response(null, { status: 304, headers: { 'cache-control': 'no-store' } })
276
357
  return new Response(JSON.stringify({
277
358
  version: live.version,
278
- server: live.serverName,
279
- status: live.connected ? 'connected' : 'idle',
280
- endpoint: live.endpoint,
281
- lastError: live.lastError,
282
- tools: live.catalog,
283
- overrides: live.toolSettings,
359
+ servers: [...live.servers.values()].map(entry => ({
360
+ name: entry.name,
361
+ endpoint: entry.endpoint,
362
+ status: entry.connected ? 'connected' : 'idle',
363
+ lastError: entry.lastError,
364
+ toolCount: entry.toolCount,
365
+ tools: entry.catalog,
366
+ settings: entry.settings,
367
+ })),
284
368
  }), { status: 200, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } })
285
369
  },
286
370
  })
@@ -301,14 +385,14 @@ export async function apply(ctx: any, config: Config = {}) {
301
385
  if (typeof value === 'string') headers[key] = value
302
386
  }
303
387
  }
304
- const probe = new McpClient(endpoint, headers, 15_000)
305
- const info: any = await probe.initialize()
388
+ const probe = await connectMcp(endpoint, headers, 15_000)
306
389
  const tools = await probe.listTools()
307
390
  send(res, 200, {
308
391
  ok: true,
309
- protocolVersion: info?.protocolVersion ?? null,
310
- server: info?.serverInfo?.name ?? null,
311
- version: info?.serverInfo?.version ?? null,
392
+ protocolVersion: probe.protocolVersion ?? null,
393
+ transport: probe.transport,
394
+ server: (probe.serverInfo as any)?.name ?? null,
395
+ version: (probe.serverInfo as any)?.version ?? null,
312
396
  tools: tools.map(tool => ({ name: tool.name, description: tool.description ?? '', folder: (tool._meta as any)?.['dsh/folder'] ?? null })),
313
397
  })
314
398
  } catch (error) {
@@ -326,13 +410,11 @@ export async function apply(ctx: any, config: Config = {}) {
326
410
  try {
327
411
  if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
328
412
  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')
329
415
  const { editor, entry } = findEntry()
330
- const next: Record<string, unknown> = {}
331
- if (typeof body.endpoint === 'string') next.endpoint = body.endpoint.trim()
332
- if (body.headers !== null && typeof body.headers === 'object') next.headers = body.headers
333
- if (typeof body.toolCallTimeoutMs === 'number') next.toolCallTimeoutMs = body.toolCallTimeoutMs
334
- await editor.edit(entry, (current: Record<string, unknown>) => ({ ...current, ...next }))
335
- beacon('config-saved')
416
+ await editor.edit(entry, (current: any) => ({ ...current, servers }))
417
+ beacon('config-saved servers=' + servers.length)
336
418
  send(res, 200, { ok: true })
337
419
  } catch (error) {
338
420
  beacon('config-save-error ' + String(error))
@@ -350,14 +432,23 @@ export async function apply(ctx: any, config: Config = {}) {
350
432
  try {
351
433
  if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
352
434
  const body = await readBody(req)
353
- const { editor, entry } = findEntry()
354
- const tools: ToolSettings = {
355
- disabled: Array.isArray(body.disabled) ? (body.disabled as unknown[]).filter(v => typeof v === 'string') as string[] : [],
356
- hidden: Array.isArray(body.hidden) ? (body.hidden as unknown[]).filter(v => typeof v === 'string') as string[] : [],
357
- overrides: body.overrides !== null && typeof body.overrides === 'object' ? body.overrides as Record<string, any> : {},
435
+ 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 : {},
358
440
  }
359
- await editor.edit(entry, (current: Record<string, unknown>) => ({ ...current, tools }))
360
- beacon('tools-saved')
441
+ const { editor, entry } = findEntry()
442
+ await editor.edit(entry, (current: any) => {
443
+ const list = Array.isArray(current.servers) && current.servers.length > 0
444
+ ? current.servers.map((item: any) => ({ ...item }))
445
+ : [{ name: current.serverName ?? 'general', endpoint: current.endpoint ?? '', headers: current.headers ?? {} }]
446
+ 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 }
450
+ })
451
+ beacon('tools-saved ' + server)
361
452
  send(res, 200, { ok: true })
362
453
  } catch (error) {
363
454
  beacon('tools-save-error ' + String(error))
@@ -373,91 +464,71 @@ export async function apply(ctx: any, config: Config = {}) {
373
464
  }
374
465
  }
375
466
 
376
- // The web carrier may mount after this plugin: wait for the service instead of
377
- // reading it once (a one-shot read silently produced 404s for the whole process).
378
- const startRoutes = (webCtx: any) => {
379
- try {
380
- installRoutes(webCtx)
381
- } catch (error) {
382
- beacon('host-route-failed ' + String(error))
467
+ try {
468
+ if (typeof ctx.inject === 'function') {
469
+ ctx.inject(['webServer'], (sub: any) => install(sub))
470
+ } else {
471
+ install(ctx)
383
472
  }
384
- }
385
- if (typeof ctx.inject === 'function') {
386
- try {
387
- ctx.inject(['webServer'], (sub: any) => startRoutes(sub))
388
- } catch (error) {
389
- beacon('host-inject-failed ' + String(error))
390
- startRoutes(ctx)
391
- }
392
- } else {
393
- startRoutes(ctx)
473
+ } catch (error) {
474
+ beacon('host-inject-failed ' + String(error))
475
+ try { install(ctx) } catch {}
394
476
  }
395
477
 
396
- // Inject the catalog token into the boot payload for the page.
397
- const onInject = (table: any[]) => {
398
- table.push({
399
- kind: 'global',
400
- name: '__GENMCP__',
401
- value: { token: live.token, server: live.serverName, catalogPath: '/api/general-mcp/catalog' },
402
- })
403
- }
404
- ctx.effect(() => ctx.on('webserver/index-inject', onInject))
405
-
406
- // ---- discovery (never blocks or fails activation) --------------------------
407
- stopRetry()
408
- void sync().then(ok => {
409
- if (!ok && state().endpoint !== '') scheduleRetry()
410
- }).catch(error => {
411
- const current = state()
412
- current.lastError = String((error as Error)?.message ?? error)
413
- current.version += 1
478
+ ctx.effect?.(() => () => {
479
+ for (const entry of state().servers.values()) {
480
+ if (entry.retryTimer !== undefined) clearInterval(entry.retryTimer)
481
+ for (const dispose of entry.tools.values()) {
482
+ try { dispose() } catch {}
483
+ }
484
+ entry.tools.clear()
485
+ }
414
486
  })
415
487
 
416
- ctx.effect(() => () => stopRetry())
488
+ shared.__GENMCP_STARTED__ = startedAt
489
+ }
417
490
 
418
- // ---- status tool ----------------------------------------------------------
419
- const statusDispose = ctx.tools.register({
491
+ function registerStatusTool(ctx: any): void {
492
+ const live = state()
493
+ const startedAt = state() && ((shared.__GENMCP_STARTED__ as string) ?? new Date().toISOString())
494
+ const dispose = ctx.tools.register({
420
495
  name: 'general_mcp_status',
421
- description: 'Report the general-mcp gateway connection status.',
496
+ description: 'Report every configured MCP gateway and its connection status.',
422
497
  parameters: { type: 'object', properties: {}, additionalProperties: false },
423
498
  output: {
424
499
  schema: {
425
500
  type: 'object',
426
501
  properties: {
427
502
  ok: { type: 'boolean' },
428
- serverName: { type: 'string' },
429
- endpoint: { type: 'string' },
430
- connected: { type: 'boolean' },
431
- toolCount: { type: 'number' },
432
- lastError: { type: 'string' },
433
503
  startedAt: { type: 'string' },
504
+ servers: { type: 'array', items: { type: 'object' } },
434
505
  },
435
- required: ['ok', 'serverName', 'endpoint', 'connected', 'toolCount', 'lastError', 'startedAt'],
506
+ required: ['ok', 'startedAt', 'servers'],
436
507
  additionalProperties: false,
437
508
  },
438
509
  render(_args: unknown, value: any) {
439
- return [{
440
- type: 'text',
441
- text: 'general-mcp: ' + value.serverName +
442
- ' endpoint=' + (value.endpoint === '' ? '(unset)' : value.endpoint) +
443
- ' connected=' + value.connected +
444
- ' tools=' + value.toolCount +
445
- (value.lastError === '' ? '' : ' error=' + value.lastError),
446
- }]
510
+ const lines = (value.servers ?? []).map((item: any) =>
511
+ item.name + ': ' + (item.connected ? 'connected' : 'idle') + ' tools=' + item.toolCount +
512
+ (item.lastError === '' ? '' : ' error=' + item.lastError))
513
+ return [{ type: 'text', text: 'general-mcp' + (lines.length === 0 ? ' (no gateways)' : '\n' + lines.join('\n')) }]
447
514
  },
448
515
  },
449
516
  async execute() {
517
+ const servers = [...live.servers.values()].map(entry => ({
518
+ name: entry.name,
519
+ endpoint: entry.endpoint,
520
+ connected: entry.connected,
521
+ toolCount: entry.toolCount,
522
+ lastError: entry.lastError,
523
+ disabled: entry.settings.disabled ?? [],
524
+ hidden: entry.settings.hidden ?? [],
525
+ }))
450
526
  return {
451
- ok: live.endpoint !== '' && live.lastError === '' && live.connected,
452
- serverName: live.serverName,
453
- endpoint: live.endpoint,
454
- connected: live.connected,
455
- toolCount: live.toolCount,
456
- lastError: live.lastError,
457
- startedAt,
527
+ ok: servers.length > 0 && servers.every(item => item.connected || item.endpoint === ''),
528
+ startedAt: (shared.__GENMCP_STARTED__ as string) ?? new Date().toISOString(),
529
+ servers,
458
530
  }
459
531
  },
460
532
  })
461
- ctx.effect(() => () => statusDispose())
533
+ ctx.effect?.(() => () => dispose())
462
534
  }
463
-