@momeidejiyi/dsh-general-mcp 0.1.5 → 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/lib/index.js +493 -184
- package/package.json +1 -1
- package/src/catalog.ts +2 -0
- package/src/client.ts +1 -1
- package/src/connect.ts +64 -0
- package/src/index.ts +296 -225
- package/src/sse.ts +210 -0
package/src/index.ts
CHANGED
|
@@ -1,22 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* general-mcp - host half.
|
|
3
3
|
*
|
|
4
|
-
* Connects one MCP
|
|
5
|
-
* them on ctx.tools, and
|
|
6
|
-
*
|
|
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 {
|
|
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
|
|
29
|
-
|
|
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
|
-
|
|
47
|
+
settings: ToolSettings
|
|
44
48
|
attempts: number
|
|
49
|
+
retryTimer?: any
|
|
50
|
+
sync?: Promise<boolean>
|
|
45
51
|
}
|
|
46
52
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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
|
-
|
|
53
|
-
|
|
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
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
-
|
|
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),
|
|
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
|
-
|
|
83
|
-
|
|
84
|
-
serverName:
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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
|
|
152
|
+
return out
|
|
100
153
|
}
|
|
101
154
|
|
|
102
|
-
export
|
|
103
|
-
normalizeConfig(config)
|
|
155
|
+
export function apply(ctx: any, config?: Config): void {
|
|
104
156
|
const live = state()
|
|
105
|
-
const
|
|
157
|
+
const servers = normalizeConfig(config)
|
|
158
|
+
beacon('host-apply ' + servers.map(item => item.name).join(','))
|
|
106
159
|
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
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
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
-
|
|
127
|
-
|
|
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 (
|
|
227
|
+
if (settings.disabled?.includes(tool.name) === true) continue
|
|
133
228
|
const invalid = validateTool(tool)
|
|
134
|
-
if (invalid !== undefined)
|
|
135
|
-
|
|
136
|
-
|
|
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
|
-
|
|
145
|
-
|
|
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 (
|
|
149
|
-
|
|
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
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
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
|
-
|
|
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
|
-
|
|
174
|
-
|
|
257
|
+
entry.connected = false
|
|
258
|
+
entry.lastError = String((error as Error)?.message ?? error)
|
|
175
259
|
live.version += 1
|
|
176
|
-
ctx.logger?.warn?.('general-mcp: ' +
|
|
177
|
-
beacon('discover-error ' +
|
|
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
|
-
|
|
264
|
+
entry.sync = undefined
|
|
181
265
|
}
|
|
182
266
|
})()
|
|
183
|
-
|
|
267
|
+
entry.sync = run
|
|
184
268
|
return run
|
|
185
269
|
}
|
|
186
270
|
|
|
187
|
-
const
|
|
188
|
-
if (
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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
|
-
|
|
198
|
-
|
|
199
|
-
stopRetry()
|
|
200
|
-
disposeTools()
|
|
201
|
-
})
|
|
288
|
+
return { disposeTools, registerTools, sync, scheduleRetry, stopRetry }
|
|
289
|
+
}
|
|
202
290
|
|
|
203
|
-
|
|
291
|
+
function installRoutes(ctx: any): void {
|
|
292
|
+
const live = state()
|
|
293
|
+
const startedAt = new Date().toISOString()
|
|
204
294
|
|
|
205
|
-
|
|
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
|
-
|
|
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)
|
|
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
|
|
269
|
-
if (!bearer && !
|
|
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
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
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 =
|
|
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:
|
|
310
|
-
|
|
311
|
-
|
|
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
|
-
|
|
331
|
-
|
|
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
|
|
354
|
-
const tools
|
|
355
|
-
disabled: Array.isArray(body.disabled) ?
|
|
356
|
-
hidden: Array.isArray(body.hidden) ?
|
|
357
|
-
overrides: body.overrides !== null && typeof body.overrides === 'object' ? body.overrides
|
|
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
|
-
|
|
360
|
-
|
|
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
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
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
|
-
|
|
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
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
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
|
-
|
|
488
|
+
shared.__GENMCP_STARTED__ = startedAt
|
|
489
|
+
}
|
|
417
490
|
|
|
418
|
-
|
|
419
|
-
const
|
|
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
|
|
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', '
|
|
506
|
+
required: ['ok', 'startedAt', 'servers'],
|
|
436
507
|
additionalProperties: false,
|
|
437
508
|
},
|
|
438
509
|
render(_args: unknown, value: any) {
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
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:
|
|
452
|
-
|
|
453
|
-
|
|
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(() => () =>
|
|
533
|
+
ctx.effect?.(() => () => dispose())
|
|
462
534
|
}
|
|
463
|
-
|