@momeidejiyi/dsh-general-mcp 0.3.0 → 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/lib/index.js +339 -98
- package/package.json +1 -1
- package/src/catalog.ts +5 -8
- package/src/client.ts +7 -1
- package/src/connect.ts +19 -4
- package/src/index.ts +252 -63
- package/src/naming.ts +19 -0
- package/src/sse.ts +89 -25
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
|
-
|
|
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
|
|
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:
|
|
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
|
-
|
|
188
|
-
|
|
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 &&
|
|
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
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
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
|
-
|
|
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)
|
|
444
|
-
|
|
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,28 +547,24 @@ function installRoutes(ctx: any): void {
|
|
|
456
547
|
}
|
|
457
548
|
|
|
458
549
|
try {
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
const url = new URL(request.url)
|
|
476
|
-
const raw = url.searchParams.get('since')
|
|
477
|
-
const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1
|
|
478
|
-
if (since === live.version) return new Response(null, { status: 304, headers: { ...allowed, 'cache-control': 'no-store' } })
|
|
479
|
-
return new Response(JSON.stringify({
|
|
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".
|
|
554
|
+
const catalogPayload = (method: string, rawUrl: string, headers: Record<string, string>) => {
|
|
555
|
+
const allowed = cors({ headers })
|
|
556
|
+
if (method === 'OPTIONS') return { status: 204, headers: { ...allowed }, body: undefined as string | undefined }
|
|
557
|
+
if (!trusted({ headers })) return { status: 401, headers: { ...allowed }, body: 'unauthorized' }
|
|
558
|
+
const url = new URL(rawUrl, 'http://localhost')
|
|
559
|
+
const raw = url.searchParams.get('since')
|
|
560
|
+
const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1
|
|
561
|
+
if (since === live.version) return { status: 304, headers: { ...allowed }, body: undefined }
|
|
562
|
+
return {
|
|
563
|
+
status: 200,
|
|
564
|
+
headers: { ...allowed, 'content-type': 'application/json; charset=utf-8' },
|
|
565
|
+
body: JSON.stringify({
|
|
480
566
|
version: live.version,
|
|
567
|
+
...(live.lastError === '' ? {} : { configError: live.lastError }),
|
|
481
568
|
timeoutMs: live.timeoutMs,
|
|
482
569
|
retryIntervalMs: live.retryIntervalMs,
|
|
483
570
|
maxRetries: live.maxRetries,
|
|
@@ -496,30 +583,66 @@ function installRoutes(ctx: any): void {
|
|
|
496
583
|
tools: entry.catalog,
|
|
497
584
|
settings: entry.settings,
|
|
498
585
|
})),
|
|
499
|
-
}),
|
|
586
|
+
}),
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
route({
|
|
591
|
+
kind: 'exact',
|
|
592
|
+
path: '/api/general-mcp/catalog',
|
|
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
|
+
}
|
|
599
|
+
const out = catalogPayload(
|
|
600
|
+
req.method ?? 'GET',
|
|
601
|
+
req.url ?? '/',
|
|
602
|
+
{
|
|
603
|
+
authorization: String(req.headers?.authorization ?? ''),
|
|
604
|
+
origin: String(req.headers?.origin ?? ''),
|
|
605
|
+
host: String(req.headers?.host ?? ''),
|
|
606
|
+
},
|
|
607
|
+
)
|
|
608
|
+
res.writeHead(out.status, { 'cache-control': 'no-store', ...out.headers })
|
|
609
|
+
if (out.body === undefined) res.end()
|
|
610
|
+
else res.end(out.body)
|
|
500
611
|
},
|
|
501
612
|
})
|
|
502
613
|
|
|
503
|
-
|
|
614
|
+
route({
|
|
504
615
|
kind: 'exact',
|
|
505
616
|
path: '/api/general-mcp/probe',
|
|
506
617
|
handler: (req: any, res: any) => {
|
|
507
618
|
const extra = cors(req)
|
|
508
619
|
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
|
|
509
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
|
+
}
|
|
510
627
|
void (async () => {
|
|
628
|
+
let probe: McpConnection | undefined
|
|
511
629
|
try {
|
|
512
630
|
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
513
631
|
const body = await readBody(req)
|
|
514
632
|
const endpoint = typeof body.endpoint === 'string' ? body.endpoint.trim() : ''
|
|
515
|
-
if (!/^https?:\/\//i.test(endpoint))
|
|
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
|
+
}
|
|
516
639
|
const headers: Record<string, string> = {}
|
|
517
640
|
if (body.headers !== null && typeof body.headers === 'object' && !Array.isArray(body.headers)) {
|
|
518
641
|
for (const [key, value] of Object.entries(body.headers as Record<string, unknown>)) {
|
|
519
642
|
if (typeof value === 'string') headers[key] = value
|
|
520
643
|
}
|
|
521
644
|
}
|
|
522
|
-
|
|
645
|
+
probe = await connectMcp(endpoint, headers, 15_000)
|
|
523
646
|
const tools = await probe.listTools()
|
|
524
647
|
send(res, 200, {
|
|
525
648
|
ok: true,
|
|
@@ -532,18 +655,27 @@ function installRoutes(ctx: any): void {
|
|
|
532
655
|
})
|
|
533
656
|
} catch (error) {
|
|
534
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(() => {})
|
|
535
661
|
}
|
|
536
662
|
})()
|
|
537
663
|
},
|
|
538
664
|
})
|
|
539
665
|
|
|
540
|
-
|
|
666
|
+
route({
|
|
541
667
|
kind: 'exact',
|
|
542
668
|
path: '/api/general-mcp/config',
|
|
543
669
|
handler: (req: any, res: any) => {
|
|
544
670
|
const extra = cors(req)
|
|
545
671
|
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
|
|
546
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
|
+
}
|
|
547
679
|
void (async () => {
|
|
548
680
|
try {
|
|
549
681
|
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
@@ -554,11 +686,19 @@ function installRoutes(ctx: any): void {
|
|
|
554
686
|
const seen = new Set<string>()
|
|
555
687
|
for (const item of incoming as any[]) {
|
|
556
688
|
const name = String(item.name ?? 'general')
|
|
557
|
-
if (!/^[A-Za-z0-9_-]{1,32}$/.test(name)) throw
|
|
558
|
-
if (seen.has(name)) throw
|
|
689
|
+
if (!/^[A-Za-z0-9_-]{1,32}$/.test(name)) throw httpError(400, '网关名 "' + name + '" 非法')
|
|
690
|
+
if (seen.has(name)) throw httpError(400, '网关名 "' + name + '" 重复')
|
|
559
691
|
const endpoint = item.endpoint
|
|
560
692
|
if (endpoint !== undefined && endpoint !== null && endpoint !== '' && !/^https?:\/\//i.test(String(endpoint))) {
|
|
561
|
-
throw
|
|
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
|
+
}
|
|
562
702
|
}
|
|
563
703
|
seen.add(name)
|
|
564
704
|
}
|
|
@@ -578,20 +718,20 @@ function installRoutes(ctx: any): void {
|
|
|
578
718
|
const name = String(item.name ?? 'general')
|
|
579
719
|
if (removed.has(name)) continue
|
|
580
720
|
if (body.createOnly === true && byName.get(name) !== undefined) {
|
|
581
|
-
throw
|
|
721
|
+
throw httpError(409, '网关 ' + name + ' 已存在')
|
|
582
722
|
}
|
|
583
723
|
const previous = byName.get(name) ?? {}
|
|
584
724
|
// A partial payload (only enabled/timeout/headers) must keep the
|
|
585
725
|
// stored endpoint and tool settings.
|
|
586
726
|
const hasEndpoint = typeof item.endpoint === 'string'
|
|
587
727
|
if (!hasEndpoint && byName.get(name) === undefined) {
|
|
588
|
-
throw
|
|
728
|
+
throw httpError(404, '网关 ' + name + ' 不存在,改动未保存')
|
|
589
729
|
}
|
|
590
730
|
const endpoint = hasEndpoint ? item.endpoint.trim() : (previous.endpoint ?? '')
|
|
591
731
|
const sameEndpoint = (previous.endpoint ?? '') === endpoint
|
|
592
732
|
// Keep tool settings when only the endpoint changes: silently
|
|
593
|
-
// dropping
|
|
594
|
-
//
|
|
733
|
+
// dropping disabled/overrides was data loss. Entries for tools
|
|
734
|
+
// the new server does not expose are pruned on the next sync.
|
|
595
735
|
const next: any = { ...previous, ...item, name, endpoint }
|
|
596
736
|
void sameEndpoint
|
|
597
737
|
if (item.headersPatch !== null && typeof item.headersPatch === 'object' && !Array.isArray(item.headersPatch)) {
|
|
@@ -629,19 +769,25 @@ function installRoutes(ctx: any): void {
|
|
|
629
769
|
send(res, 200, { ok: true })
|
|
630
770
|
} catch (error) {
|
|
631
771
|
beacon('config-save-error ' + String(error))
|
|
632
|
-
send(res,
|
|
772
|
+
send(res, statusOf(error), { ok: false, message: String((error as Error)?.message ?? error) })
|
|
633
773
|
}
|
|
634
774
|
})()
|
|
635
775
|
},
|
|
636
776
|
})
|
|
637
777
|
|
|
638
|
-
|
|
778
|
+
route({
|
|
639
779
|
kind: 'exact',
|
|
640
780
|
path: '/api/general-mcp/tools',
|
|
641
781
|
handler: (req: any, res: any) => {
|
|
642
782
|
const extra = cors(req)
|
|
643
783
|
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
|
|
644
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
|
+
}
|
|
645
791
|
void (async () => {
|
|
646
792
|
try {
|
|
647
793
|
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
@@ -657,15 +803,26 @@ function installRoutes(ctx: any): void {
|
|
|
657
803
|
const index = list.findIndex((item: any) => (item.name ?? 'general') === server)
|
|
658
804
|
// Never invent a gateway: that would resurrect a deleted one as an
|
|
659
805
|
// empty phantom and drag its old tool settings back with it.
|
|
660
|
-
if (index < 0) throw
|
|
806
|
+
if (index < 0) throw httpError(404, '网关 ' + server + ' 不存在,工具设置未保存')
|
|
661
807
|
// Merge per key: a partial request (or a stale page) must not wipe
|
|
662
808
|
// other lists such as removed/overrides.
|
|
663
809
|
const previous = list[index].tools ?? {}
|
|
664
810
|
const next: any = { ...previous }
|
|
665
811
|
if (Array.isArray(body.disabled)) next.disabled = body.disabled.filter((v: unknown) => typeof v === 'string')
|
|
666
|
-
if (Array.isArray(body.hidden))
|
|
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
|
+
}
|
|
667
819
|
if (Array.isArray(body.removed)) next.removed = body.removed.filter((v: unknown) => typeof v === 'string')
|
|
668
|
-
if (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
|
+
}
|
|
669
826
|
list[index] = { ...list[index], tools: next }
|
|
670
827
|
const { serverName, endpoint, headers, tools, ...rest } = current
|
|
671
828
|
return { ...rest, servers: list }
|
|
@@ -674,7 +831,7 @@ function installRoutes(ctx: any): void {
|
|
|
674
831
|
send(res, 200, { ok: true })
|
|
675
832
|
} catch (error) {
|
|
676
833
|
beacon('tools-save-error ' + String(error))
|
|
677
|
-
send(res,
|
|
834
|
+
send(res, statusOf(error), { ok: false, message: String((error as Error)?.message ?? error) })
|
|
678
835
|
}
|
|
679
836
|
})()
|
|
680
837
|
},
|
|
@@ -698,19 +855,44 @@ function installRoutes(ctx: any): void {
|
|
|
698
855
|
}
|
|
699
856
|
|
|
700
857
|
ctx.effect?.(() => () => {
|
|
701
|
-
|
|
858
|
+
const live = state()
|
|
859
|
+
for (const entry of live.servers.values()) {
|
|
860
|
+
entry.disposed = true
|
|
702
861
|
if (entry.retryTimer !== undefined) clearInterval(entry.retryTimer)
|
|
862
|
+
entry.retryTimer = undefined
|
|
703
863
|
for (const dispose of entry.tools.values()) {
|
|
704
864
|
try { dispose() } catch {}
|
|
705
865
|
}
|
|
706
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 = []
|
|
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
|
+
}
|
|
707
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)
|
|
708
887
|
})
|
|
709
888
|
|
|
710
889
|
shared.__GENMCP_STARTED__ = startedAt
|
|
711
890
|
}
|
|
712
891
|
|
|
713
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
|
|
714
896
|
const live = state()
|
|
715
897
|
const startedAt = state() && ((shared.__GENMCP_STARTED__ as string) ?? new Date().toISOString())
|
|
716
898
|
const dispose = ctx.tools.register({
|
|
@@ -746,7 +928,6 @@ function registerStatusTool(ctx: any): void {
|
|
|
746
928
|
toolCount: entry.toolCount,
|
|
747
929
|
lastError: entry.lastError,
|
|
748
930
|
disabled: entry.settings.disabled ?? [],
|
|
749
|
-
hidden: entry.settings.hidden ?? [],
|
|
750
931
|
}))
|
|
751
932
|
return {
|
|
752
933
|
ok: servers.length > 0 && servers.every(item => item.connected || item.endpoint === ''),
|
|
@@ -755,5 +936,13 @@ function registerStatusTool(ctx: any): void {
|
|
|
755
936
|
}
|
|
756
937
|
},
|
|
757
938
|
})
|
|
758
|
-
|
|
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
|
+
})
|
|
759
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
|