@momeidejiyi/dsh-general-mcp 0.3.1 → 0.3.3
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 +312 -89
- 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 +230 -56
- 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.
|
|
@@ -409,8 +479,14 @@ function installRoutes(ctx: any): void {
|
|
|
409
479
|
if (origin === '') return true
|
|
410
480
|
if (origin.startsWith('dsh-app:') || origin.startsWith('file:')) return true
|
|
411
481
|
const loopback = /^(127\.0\.0\.1|localhost|\[::1\])(:|$)/
|
|
482
|
+
// A page opened from a local file (desktop shells, sandboxed webviews)
|
|
483
|
+
// reports the literal origin "null" on every POST, even though same-origin
|
|
484
|
+
// GETs carry no Origin at all.
|
|
485
|
+
if (origin === 'null') return loopback.test(host) || host === ''
|
|
412
486
|
try {
|
|
413
487
|
const originHost = new URL(origin).host
|
|
488
|
+
// Same-origin is the normal case for the settings page, including when
|
|
489
|
+
// DSH is opened over a LAN/Tailscale address instead of loopback.
|
|
414
490
|
if (host !== '' && originHost === host) return true
|
|
415
491
|
// A page served from loopback may talk to a differently-addressed loopback API.
|
|
416
492
|
if (loopback.test(originHost) && loopback.test(host)) return true
|
|
@@ -427,9 +503,12 @@ function installRoutes(ctx: any): void {
|
|
|
427
503
|
'access-control-max-age': '600',
|
|
428
504
|
vary: 'origin',
|
|
429
505
|
}
|
|
430
|
-
if (origin !== '') out['access-control-allow-origin'] = origin
|
|
506
|
+
if (origin !== '' && trusted({ headers })) out['access-control-allow-origin'] = origin
|
|
431
507
|
return out
|
|
432
508
|
}
|
|
509
|
+
const httpError = (status: number, message: string) => Object.assign(new Error(message), { status })
|
|
510
|
+
const statusOf = (error: unknown): number =>
|
|
511
|
+
typeof (error as any)?.status === 'number' ? (error as any).status : 500
|
|
433
512
|
const send = (res: any, status: number, payload: unknown, extra: Record<string, string> = {}) => {
|
|
434
513
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...extra })
|
|
435
514
|
res.end(JSON.stringify(payload))
|
|
@@ -438,14 +517,30 @@ function installRoutes(ctx: any): void {
|
|
|
438
517
|
new Promise((resolve, reject) => {
|
|
439
518
|
const chunks: Buffer[] = []
|
|
440
519
|
let size = 0
|
|
520
|
+
let settled = false
|
|
521
|
+
const fail = (error: Error, destroy = false) => {
|
|
522
|
+
if (settled) return
|
|
523
|
+
settled = true
|
|
524
|
+
// Stop reading: an oversized or aborted body must not keep buffering.
|
|
525
|
+
chunks.length = 0
|
|
526
|
+
if (destroy) { try { req.destroy() } catch {} }
|
|
527
|
+
reject(error)
|
|
528
|
+
}
|
|
441
529
|
req.on('data', (chunk: Buffer) => {
|
|
530
|
+
if (settled) return
|
|
442
531
|
size += chunk.length
|
|
443
|
-
if (size > limit)
|
|
444
|
-
|
|
532
|
+
if (size > limit) { fail(new Error('body too large'), true); return }
|
|
533
|
+
chunks.push(chunk)
|
|
445
534
|
})
|
|
446
535
|
req.on('end', () => {
|
|
536
|
+
if (settled) return
|
|
537
|
+
settled = true
|
|
447
538
|
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) } catch { reject(new Error('invalid JSON body')) }
|
|
448
539
|
})
|
|
540
|
+
// A client that hangs up mid-body would otherwise leave this promise
|
|
541
|
+
// pending (and the route closure alive) forever.
|
|
542
|
+
req.on('error', (error: Error) => fail(error))
|
|
543
|
+
req.on('aborted', () => fail(new Error('request aborted')))
|
|
449
544
|
})
|
|
450
545
|
const findEntry = () => {
|
|
451
546
|
const editor = ctx.get?.('configEditor')
|
|
@@ -456,21 +551,29 @@ function installRoutes(ctx: any): void {
|
|
|
456
551
|
}
|
|
457
552
|
|
|
458
553
|
try {
|
|
459
|
-
//
|
|
460
|
-
//
|
|
554
|
+
// Handler-only on purpose: when a route also declares "resource", the host
|
|
555
|
+
// dispatches that instead and answers OPTIONS with 405, which breaks the
|
|
556
|
+
// browser preflight for the Authorization header. Every DSH build
|
|
557
|
+
// dispatches "handler".
|
|
461
558
|
const catalogPayload = (method: string, rawUrl: string, headers: Record<string, string>) => {
|
|
462
559
|
const allowed = cors({ headers })
|
|
463
560
|
if (method === 'OPTIONS') return { status: 204, headers: { ...allowed }, body: undefined as string | undefined }
|
|
464
|
-
if (!trusted({ headers }))
|
|
561
|
+
if (!trusted({ headers })) {
|
|
562
|
+
// 401 carries a short text body, so say what it is. 304 stays
|
|
563
|
+
// body-less (a Content-Type there would describe nothing).
|
|
564
|
+
return { status: 401, headers: { ...allowed, 'content-type': 'text/plain; charset=utf-8' }, body: 'unauthorized' }
|
|
565
|
+
}
|
|
465
566
|
const url = new URL(rawUrl, 'http://localhost')
|
|
466
567
|
const raw = url.searchParams.get('since')
|
|
467
568
|
const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1
|
|
569
|
+
// RFC 9110: a 304 repeats validators/Cache-Control/Vary, never a body.
|
|
468
570
|
if (since === live.version) return { status: 304, headers: { ...allowed }, body: undefined }
|
|
469
571
|
return {
|
|
470
572
|
status: 200,
|
|
471
573
|
headers: { ...allowed, 'content-type': 'application/json; charset=utf-8' },
|
|
472
574
|
body: JSON.stringify({
|
|
473
575
|
version: live.version,
|
|
576
|
+
...(live.lastError === '' ? {} : { configError: live.lastError }),
|
|
474
577
|
timeoutMs: live.timeoutMs,
|
|
475
578
|
retryIntervalMs: live.retryIntervalMs,
|
|
476
579
|
maxRetries: live.maxRetries,
|
|
@@ -493,10 +596,15 @@ function installRoutes(ctx: any): void {
|
|
|
493
596
|
}
|
|
494
597
|
}
|
|
495
598
|
|
|
496
|
-
|
|
599
|
+
route({
|
|
497
600
|
kind: 'exact',
|
|
498
601
|
path: '/api/general-mcp/catalog',
|
|
499
602
|
handler: (req: any, res: any) => {
|
|
603
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS') {
|
|
604
|
+
res.writeHead(405, { allow: 'GET, HEAD, OPTIONS', ...cors(req) })
|
|
605
|
+
res.end()
|
|
606
|
+
return
|
|
607
|
+
}
|
|
500
608
|
const out = catalogPayload(
|
|
501
609
|
req.method ?? 'GET',
|
|
502
610
|
req.url ?? '/',
|
|
@@ -510,40 +618,40 @@ function installRoutes(ctx: any): void {
|
|
|
510
618
|
if (out.body === undefined) res.end()
|
|
511
619
|
else res.end(out.body)
|
|
512
620
|
},
|
|
513
|
-
resource: async (request: any) => {
|
|
514
|
-
const out = catalogPayload(
|
|
515
|
-
request.method,
|
|
516
|
-
request.url,
|
|
517
|
-
{
|
|
518
|
-
authorization: request.headers?.get?.('authorization') ?? '',
|
|
519
|
-
origin: request.headers?.get?.('origin') ?? '',
|
|
520
|
-
host: request.headers?.get?.('host') ?? '',
|
|
521
|
-
},
|
|
522
|
-
)
|
|
523
|
-
return new Response(out.body ?? null, { status: out.status, headers: { 'cache-control': 'no-store', ...out.headers } })
|
|
524
|
-
},
|
|
525
621
|
})
|
|
526
622
|
|
|
527
|
-
|
|
623
|
+
route({
|
|
528
624
|
kind: 'exact',
|
|
529
625
|
path: '/api/general-mcp/probe',
|
|
530
626
|
handler: (req: any, res: any) => {
|
|
531
627
|
const extra = cors(req)
|
|
532
628
|
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
|
|
533
629
|
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
630
|
+
if (req.method !== 'POST' && req.method !== 'OPTIONS') {
|
|
631
|
+
// A GET used to fall through and run a write (and a plugin reload).
|
|
632
|
+
res.writeHead(405, { allow: 'POST, OPTIONS', ...cors(req) })
|
|
633
|
+
res.end()
|
|
634
|
+
return
|
|
635
|
+
}
|
|
534
636
|
void (async () => {
|
|
637
|
+
let probe: McpConnection | undefined
|
|
535
638
|
try {
|
|
536
639
|
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
537
640
|
const body = await readBody(req)
|
|
538
641
|
const endpoint = typeof body.endpoint === 'string' ? body.endpoint.trim() : ''
|
|
539
|
-
if (!/^https?:\/\//i.test(endpoint))
|
|
642
|
+
if (!/^https?:\/\//i.test(endpoint)) {
|
|
643
|
+
// Invalid input is the caller's fault; connection failures below
|
|
644
|
+
// stay 200 {ok:false} because probing a dead host is a normal result.
|
|
645
|
+
send(res, 400, { ok: false, message: 'endpoint must be an http(s) URL' })
|
|
646
|
+
return
|
|
647
|
+
}
|
|
540
648
|
const headers: Record<string, string> = {}
|
|
541
649
|
if (body.headers !== null && typeof body.headers === 'object' && !Array.isArray(body.headers)) {
|
|
542
650
|
for (const [key, value] of Object.entries(body.headers as Record<string, unknown>)) {
|
|
543
651
|
if (typeof value === 'string') headers[key] = value
|
|
544
652
|
}
|
|
545
653
|
}
|
|
546
|
-
|
|
654
|
+
probe = await connectMcp(endpoint, headers, 15_000)
|
|
547
655
|
const tools = await probe.listTools()
|
|
548
656
|
send(res, 200, {
|
|
549
657
|
ok: true,
|
|
@@ -556,18 +664,27 @@ function installRoutes(ctx: any): void {
|
|
|
556
664
|
})
|
|
557
665
|
} catch (error) {
|
|
558
666
|
send(res, 200, { ok: false, message: String((error as Error)?.message ?? error) })
|
|
667
|
+
} finally {
|
|
668
|
+
// A probe must not leave a transport (and its stream) behind.
|
|
669
|
+
await probe?.close().catch(() => {})
|
|
559
670
|
}
|
|
560
671
|
})()
|
|
561
672
|
},
|
|
562
673
|
})
|
|
563
674
|
|
|
564
|
-
|
|
675
|
+
route({
|
|
565
676
|
kind: 'exact',
|
|
566
677
|
path: '/api/general-mcp/config',
|
|
567
678
|
handler: (req: any, res: any) => {
|
|
568
679
|
const extra = cors(req)
|
|
569
680
|
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
|
|
570
681
|
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
682
|
+
if (req.method !== 'POST' && req.method !== 'OPTIONS') {
|
|
683
|
+
// A GET used to fall through and run a write (and a plugin reload).
|
|
684
|
+
res.writeHead(405, { allow: 'POST, OPTIONS', ...cors(req) })
|
|
685
|
+
res.end()
|
|
686
|
+
return
|
|
687
|
+
}
|
|
571
688
|
void (async () => {
|
|
572
689
|
try {
|
|
573
690
|
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
@@ -578,11 +695,19 @@ function installRoutes(ctx: any): void {
|
|
|
578
695
|
const seen = new Set<string>()
|
|
579
696
|
for (const item of incoming as any[]) {
|
|
580
697
|
const name = String(item.name ?? 'general')
|
|
581
|
-
if (!/^[A-Za-z0-9_-]{1,32}$/.test(name)) throw
|
|
582
|
-
if (seen.has(name)) throw
|
|
698
|
+
if (!/^[A-Za-z0-9_-]{1,32}$/.test(name)) throw httpError(400, '网关名 "' + name + '" 非法')
|
|
699
|
+
if (seen.has(name)) throw httpError(400, '网关名 "' + name + '" 重复')
|
|
583
700
|
const endpoint = item.endpoint
|
|
584
701
|
if (endpoint !== undefined && endpoint !== null && endpoint !== '' && !/^https?:\/\//i.test(String(endpoint))) {
|
|
585
|
-
throw
|
|
702
|
+
throw httpError(400, '网关 "' + name + '" 的地址必须以 http(s):// 开头')
|
|
703
|
+
}
|
|
704
|
+
if (item.headers !== undefined && item.headers !== null) {
|
|
705
|
+
if (typeof item.headers !== 'object' || Array.isArray(item.headers)) throw httpError(400, '网关 "' + name + '" 的 headers 必须是对象')
|
|
706
|
+
for (const [key, value] of Object.entries(item.headers as Record<string, unknown>)) {
|
|
707
|
+
if (typeof key !== 'string' || key === '' || typeof value !== 'string') {
|
|
708
|
+
throw httpError(400, '网关 "' + name + '" 的 headers 值必须是字符串(' + key + ')')
|
|
709
|
+
}
|
|
710
|
+
}
|
|
586
711
|
}
|
|
587
712
|
seen.add(name)
|
|
588
713
|
}
|
|
@@ -602,20 +727,20 @@ function installRoutes(ctx: any): void {
|
|
|
602
727
|
const name = String(item.name ?? 'general')
|
|
603
728
|
if (removed.has(name)) continue
|
|
604
729
|
if (body.createOnly === true && byName.get(name) !== undefined) {
|
|
605
|
-
throw
|
|
730
|
+
throw httpError(409, '网关 ' + name + ' 已存在')
|
|
606
731
|
}
|
|
607
732
|
const previous = byName.get(name) ?? {}
|
|
608
733
|
// A partial payload (only enabled/timeout/headers) must keep the
|
|
609
734
|
// stored endpoint and tool settings.
|
|
610
735
|
const hasEndpoint = typeof item.endpoint === 'string'
|
|
611
736
|
if (!hasEndpoint && byName.get(name) === undefined) {
|
|
612
|
-
throw
|
|
737
|
+
throw httpError(404, '网关 ' + name + ' 不存在,改动未保存')
|
|
613
738
|
}
|
|
614
739
|
const endpoint = hasEndpoint ? item.endpoint.trim() : (previous.endpoint ?? '')
|
|
615
740
|
const sameEndpoint = (previous.endpoint ?? '') === endpoint
|
|
616
741
|
// Keep tool settings when only the endpoint changes: silently
|
|
617
|
-
// dropping
|
|
618
|
-
//
|
|
742
|
+
// dropping disabled/overrides was data loss. Entries for tools
|
|
743
|
+
// the new server does not expose are pruned on the next sync.
|
|
619
744
|
const next: any = { ...previous, ...item, name, endpoint }
|
|
620
745
|
void sameEndpoint
|
|
621
746
|
if (item.headersPatch !== null && typeof item.headersPatch === 'object' && !Array.isArray(item.headersPatch)) {
|
|
@@ -653,19 +778,25 @@ function installRoutes(ctx: any): void {
|
|
|
653
778
|
send(res, 200, { ok: true })
|
|
654
779
|
} catch (error) {
|
|
655
780
|
beacon('config-save-error ' + String(error))
|
|
656
|
-
send(res,
|
|
781
|
+
send(res, statusOf(error), { ok: false, message: String((error as Error)?.message ?? error) })
|
|
657
782
|
}
|
|
658
783
|
})()
|
|
659
784
|
},
|
|
660
785
|
})
|
|
661
786
|
|
|
662
|
-
|
|
787
|
+
route({
|
|
663
788
|
kind: 'exact',
|
|
664
789
|
path: '/api/general-mcp/tools',
|
|
665
790
|
handler: (req: any, res: any) => {
|
|
666
791
|
const extra = cors(req)
|
|
667
792
|
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
|
|
668
793
|
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
794
|
+
if (req.method !== 'POST' && req.method !== 'OPTIONS') {
|
|
795
|
+
// A GET used to fall through and run a write (and a plugin reload).
|
|
796
|
+
res.writeHead(405, { allow: 'POST, OPTIONS', ...cors(req) })
|
|
797
|
+
res.end()
|
|
798
|
+
return
|
|
799
|
+
}
|
|
669
800
|
void (async () => {
|
|
670
801
|
try {
|
|
671
802
|
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
@@ -681,15 +812,26 @@ function installRoutes(ctx: any): void {
|
|
|
681
812
|
const index = list.findIndex((item: any) => (item.name ?? 'general') === server)
|
|
682
813
|
// Never invent a gateway: that would resurrect a deleted one as an
|
|
683
814
|
// empty phantom and drag its old tool settings back with it.
|
|
684
|
-
if (index < 0) throw
|
|
815
|
+
if (index < 0) throw httpError(404, '网关 ' + server + ' 不存在,工具设置未保存')
|
|
685
816
|
// Merge per key: a partial request (or a stale page) must not wipe
|
|
686
817
|
// other lists such as removed/overrides.
|
|
687
818
|
const previous = list[index].tools ?? {}
|
|
688
819
|
const next: any = { ...previous }
|
|
689
820
|
if (Array.isArray(body.disabled)) next.disabled = body.disabled.filter((v: unknown) => typeof v === 'string')
|
|
690
|
-
if (Array.isArray(body.hidden))
|
|
821
|
+
if (Array.isArray(body.hidden)) {
|
|
822
|
+
// Legacy callers may still send "hidden": treat it as disabled.
|
|
823
|
+
const disabled = new Set(Array.isArray(next.disabled) ? next.disabled : [])
|
|
824
|
+
for (const name of body.hidden.filter((v: unknown) => typeof v === 'string')) disabled.add(name)
|
|
825
|
+
next.disabled = [...disabled]
|
|
826
|
+
delete next.hidden
|
|
827
|
+
}
|
|
691
828
|
if (Array.isArray(body.removed)) next.removed = body.removed.filter((v: unknown) => typeof v === 'string')
|
|
692
|
-
if (body.overrides !==
|
|
829
|
+
if (body.overrides !== undefined) {
|
|
830
|
+
if (body.overrides === null || typeof body.overrides !== 'object' || Array.isArray(body.overrides)) {
|
|
831
|
+
throw httpError(400, 'overrides 必须是以工具名为键的对象')
|
|
832
|
+
}
|
|
833
|
+
next.overrides = body.overrides
|
|
834
|
+
}
|
|
693
835
|
list[index] = { ...list[index], tools: next }
|
|
694
836
|
const { serverName, endpoint, headers, tools, ...rest } = current
|
|
695
837
|
return { ...rest, servers: list }
|
|
@@ -698,7 +840,7 @@ function installRoutes(ctx: any): void {
|
|
|
698
840
|
send(res, 200, { ok: true })
|
|
699
841
|
} catch (error) {
|
|
700
842
|
beacon('tools-save-error ' + String(error))
|
|
701
|
-
send(res,
|
|
843
|
+
send(res, statusOf(error), { ok: false, message: String((error as Error)?.message ?? error) })
|
|
702
844
|
}
|
|
703
845
|
})()
|
|
704
846
|
},
|
|
@@ -722,19 +864,44 @@ function installRoutes(ctx: any): void {
|
|
|
722
864
|
}
|
|
723
865
|
|
|
724
866
|
ctx.effect?.(() => () => {
|
|
725
|
-
|
|
867
|
+
const live = state()
|
|
868
|
+
for (const entry of live.servers.values()) {
|
|
869
|
+
entry.disposed = true
|
|
726
870
|
if (entry.retryTimer !== undefined) clearInterval(entry.retryTimer)
|
|
871
|
+
entry.retryTimer = undefined
|
|
727
872
|
for (const dispose of entry.tools.values()) {
|
|
728
873
|
try { dispose() } catch {}
|
|
729
874
|
}
|
|
730
875
|
entry.tools.clear()
|
|
876
|
+
// Without this the HTTP/SSE connections outlive the plugin: every reload
|
|
877
|
+
// would leak one stream (and one server-side session) per gateway.
|
|
878
|
+
void entry.client?.close().catch(() => {})
|
|
879
|
+
entry.client = undefined
|
|
880
|
+
entry.sync = undefined
|
|
881
|
+
entry.connected = false
|
|
882
|
+
entry.toolCount = 0
|
|
883
|
+
entry.catalog = []
|
|
731
884
|
}
|
|
885
|
+
live.servers.clear()
|
|
886
|
+
live.version += 1
|
|
887
|
+
const disposers = shared.__GENMCP_ROUTE_DISPOSERS__
|
|
888
|
+
if (Array.isArray(disposers)) {
|
|
889
|
+
for (const dispose of disposers.splice(0) as Array<() => void>) {
|
|
890
|
+
try { dispose() } catch {}
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
const webServer = shared.__GENMCP_WEBSERVER__
|
|
894
|
+
const installed = shared.__GENMCP_ROUTES__
|
|
895
|
+
if (webServer !== undefined && installed instanceof WeakMap) installed.delete(webServer as object)
|
|
732
896
|
})
|
|
733
897
|
|
|
734
898
|
shared.__GENMCP_STARTED__ = startedAt
|
|
735
899
|
}
|
|
736
900
|
|
|
737
901
|
function registerStatusTool(ctx: any): void {
|
|
902
|
+
// apply() runs on every config save; registering the status tool again would
|
|
903
|
+
// stack duplicates (the host may reject the second registration outright).
|
|
904
|
+
if (shared.__GENMCP_STATUS_CTX__ === ctx && typeof shared.__GENMCP_STATUS_DISPOSE__ === 'function') return
|
|
738
905
|
const live = state()
|
|
739
906
|
const startedAt = state() && ((shared.__GENMCP_STARTED__ as string) ?? new Date().toISOString())
|
|
740
907
|
const dispose = ctx.tools.register({
|
|
@@ -770,7 +937,6 @@ function registerStatusTool(ctx: any): void {
|
|
|
770
937
|
toolCount: entry.toolCount,
|
|
771
938
|
lastError: entry.lastError,
|
|
772
939
|
disabled: entry.settings.disabled ?? [],
|
|
773
|
-
hidden: entry.settings.hidden ?? [],
|
|
774
940
|
}))
|
|
775
941
|
return {
|
|
776
942
|
ok: servers.length > 0 && servers.every(item => item.connected || item.endpoint === ''),
|
|
@@ -779,5 +945,13 @@ function registerStatusTool(ctx: any): void {
|
|
|
779
945
|
}
|
|
780
946
|
},
|
|
781
947
|
})
|
|
782
|
-
|
|
948
|
+
shared.__GENMCP_STATUS_CTX__ = ctx
|
|
949
|
+
shared.__GENMCP_STATUS_DISPOSE__ = dispose
|
|
950
|
+
ctx.effect?.(() => () => {
|
|
951
|
+
dispose()
|
|
952
|
+
if (shared.__GENMCP_STATUS_DISPOSE__ === dispose) {
|
|
953
|
+
shared.__GENMCP_STATUS_DISPOSE__ = undefined
|
|
954
|
+
shared.__GENMCP_STATUS_CTX__ = undefined
|
|
955
|
+
}
|
|
956
|
+
})
|
|
783
957
|
}
|
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
|