@momeidejiyi/dsh-general-mcp 0.0.0-stage → 0.1.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 +807 -0
- package/package.json +23 -3
- package/src/catalog.ts +162 -0
- package/src/client.ts +254 -0
- package/src/index.ts +463 -0
- package/src/naming.ts +21 -0
- package/src/register.ts +91 -0
- package/README.md +0 -3
package/src/index.ts
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @momeidejiyi/dsh-general-mcp - host half.
|
|
3
|
+
*
|
|
4
|
+
* Connects one MCP gateway over Streamable HTTP, discovers its tools, registers
|
|
5
|
+
* them on ctx.tools, and (when the web surface exists) serves the catalog and
|
|
6
|
+
* config routes used by the Settings section.
|
|
7
|
+
*/
|
|
8
|
+
import { appendFileSync } from 'node:fs'
|
|
9
|
+
import { tmpdir } from 'node:os'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
import { buildCatalog, validateTool, type CatalogEntry, type ToolSettings } from './catalog.ts'
|
|
12
|
+
import { McpClient, type McpTool } from './client.ts'
|
|
13
|
+
import { publicToolName } from './naming.ts'
|
|
14
|
+
import { createToolDefinition } from './register.ts'
|
|
15
|
+
|
|
16
|
+
export const name = 'general-mcp'
|
|
17
|
+
export const inject = ['tools']
|
|
18
|
+
|
|
19
|
+
export interface Config {
|
|
20
|
+
serverName?: string
|
|
21
|
+
endpoint?: string
|
|
22
|
+
headers?: Record<string, string>
|
|
23
|
+
toolCallTimeoutMs?: number
|
|
24
|
+
debug?: boolean
|
|
25
|
+
tools?: ToolSettings
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface RuntimeState {
|
|
29
|
+
serverName: string
|
|
30
|
+
endpoint: string
|
|
31
|
+
headers: Record<string, string>
|
|
32
|
+
timeoutMs: number
|
|
33
|
+
debug: boolean
|
|
34
|
+
connected: boolean
|
|
35
|
+
toolCount: number
|
|
36
|
+
lastError: string
|
|
37
|
+
catalog: CatalogEntry[]
|
|
38
|
+
toolSettings: ToolSettings
|
|
39
|
+
version: number
|
|
40
|
+
token: string
|
|
41
|
+
sync?: Promise<boolean>
|
|
42
|
+
tools: Map<string, () => void>
|
|
43
|
+
retryTimer?: any
|
|
44
|
+
attempts: number
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const shared = globalThis as unknown as {
|
|
48
|
+
__GENMCP_STATE__?: RuntimeState
|
|
49
|
+
__GENMCP_ROUTES__?: WeakMap<object, boolean>
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Coerce untrusted config into the shape the runtime expects. */
|
|
53
|
+
function normalizeConfig(config: Config): void {
|
|
54
|
+
const live = state()
|
|
55
|
+
const raw = (config ?? {}) as Record<string, unknown>
|
|
56
|
+
const endpoint = typeof raw.endpoint === 'string' ? raw.endpoint.trim() : ''
|
|
57
|
+
if (endpoint !== '' && !/^https?:\/\//i.test(endpoint)) {
|
|
58
|
+
throw new Error('endpoint must be an http(s) URL')
|
|
59
|
+
}
|
|
60
|
+
live.endpoint = endpoint
|
|
61
|
+
live.serverName = typeof raw.serverName === 'string' && raw.serverName !== '' ? raw.serverName : 'general'
|
|
62
|
+
const headers: Record<string, string> = {}
|
|
63
|
+
if (raw.headers !== null && typeof raw.headers === 'object' && !Array.isArray(raw.headers)) {
|
|
64
|
+
for (const [key, value] of Object.entries(raw.headers as Record<string, unknown>)) {
|
|
65
|
+
if (typeof value === 'string') headers[key] = value
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
live.headers = headers
|
|
69
|
+
const timeout = typeof raw.toolCallTimeoutMs === 'number' && Number.isFinite(raw.toolCallTimeoutMs)
|
|
70
|
+
? Math.min(Math.max(Math.round(raw.toolCallTimeoutMs), 1000), 600_000)
|
|
71
|
+
: 60_000
|
|
72
|
+
live.timeoutMs = timeout
|
|
73
|
+
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
|
+
|
|
82
|
+
function state(): RuntimeState {
|
|
83
|
+
shared.__GENMCP_STATE__ ??= {
|
|
84
|
+
serverName: 'general',
|
|
85
|
+
endpoint: '',
|
|
86
|
+
headers: {},
|
|
87
|
+
timeoutMs: 60_000,
|
|
88
|
+
debug: false,
|
|
89
|
+
connected: false,
|
|
90
|
+
toolCount: 0,
|
|
91
|
+
lastError: '',
|
|
92
|
+
catalog: [],
|
|
93
|
+
toolSettings: {},
|
|
94
|
+
version: 0,
|
|
95
|
+
token: crypto.randomUUID(),
|
|
96
|
+
tools: new Map(),
|
|
97
|
+
attempts: 0,
|
|
98
|
+
}
|
|
99
|
+
return shared.__GENMCP_STATE__
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function apply(ctx: any, config: Config = {}) {
|
|
103
|
+
normalizeConfig(config)
|
|
104
|
+
const live = state()
|
|
105
|
+
const startedAt = new Date().toISOString()
|
|
106
|
+
|
|
107
|
+
const beacon = (stage: string) => {
|
|
108
|
+
if (live.debug !== true) return
|
|
109
|
+
try {
|
|
110
|
+
appendFileSync(join(tmpdir(), 'dsh-general-mcp-debug.log'), new Date().toISOString() + ' ' + stage + '\n')
|
|
111
|
+
} catch {}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const disposeTools = () => {
|
|
115
|
+
for (const [key, dispose] of live.tools) {
|
|
116
|
+
try { dispose() } catch {}
|
|
117
|
+
live.tools.delete(key)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const stopRetry = () => {
|
|
122
|
+
if (live.retryTimer !== undefined) clearInterval(live.retryTimer)
|
|
123
|
+
live.retryTimer = undefined
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Register one generation of tools, replacing the previous one atomically. */
|
|
127
|
+
const registerTools = (tools: McpTool[], client: McpClient) => {
|
|
128
|
+
const disabled = new Set(live.toolSettings.disabled ?? [])
|
|
129
|
+
const hidden = new Set(live.toolSettings.hidden ?? [])
|
|
130
|
+
disposeTools()
|
|
131
|
+
for (const tool of tools) {
|
|
132
|
+
if (hidden.has(tool.name) || disabled.has(tool.name)) continue
|
|
133
|
+
const invalid = validateTool(tool)
|
|
134
|
+
if (invalid !== undefined) {
|
|
135
|
+
ctx.logger?.warn?.('general-mcp: rejected tool ' + tool.name + ' (' + invalid.code + '): ' + invalid.message)
|
|
136
|
+
continue
|
|
137
|
+
}
|
|
138
|
+
const definition: any = createToolDefinition(live.serverName, tool, client)
|
|
139
|
+
const dispose = ctx.tools.register(definition)
|
|
140
|
+
live.tools.set(definition.name, dispose)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** One discovery pass; serialized so overlapping generations cannot interleave. */
|
|
145
|
+
const sync = (): Promise<boolean> => {
|
|
146
|
+
if (live.sync !== undefined) return live.sync
|
|
147
|
+
const run = (async () => {
|
|
148
|
+
if (live.endpoint === '') {
|
|
149
|
+
// Clearing the endpoint must also clear the previous generation's state,
|
|
150
|
+
// otherwise a disabled plugin still reports the old tools as connected.
|
|
151
|
+
disposeTools()
|
|
152
|
+
live.connected = false
|
|
153
|
+
live.toolCount = 0
|
|
154
|
+
live.catalog = []
|
|
155
|
+
live.lastError = ''
|
|
156
|
+
live.version += 1
|
|
157
|
+
return false
|
|
158
|
+
}
|
|
159
|
+
const client = new McpClient(live.endpoint, live.headers, live.timeoutMs)
|
|
160
|
+
try {
|
|
161
|
+
await client.initialize()
|
|
162
|
+
const tools = await client.listTools()
|
|
163
|
+
registerTools(tools as McpTool[], client)
|
|
164
|
+
live.connected = true
|
|
165
|
+
live.toolCount = live.tools.size
|
|
166
|
+
live.catalog = buildCatalog(live.serverName, tools as McpTool[], raw => publicToolName(live.serverName, raw), live.toolSettings)
|
|
167
|
+
live.version += 1
|
|
168
|
+
live.lastError = ''
|
|
169
|
+
live.attempts = 0
|
|
170
|
+
beacon('discovered ' + tools.length + ' version=' + live.version)
|
|
171
|
+
return true
|
|
172
|
+
} catch (error) {
|
|
173
|
+
live.connected = false
|
|
174
|
+
live.lastError = String((error as Error)?.message ?? error)
|
|
175
|
+
live.version += 1
|
|
176
|
+
ctx.logger?.warn?.('general-mcp: ' + live.lastError)
|
|
177
|
+
beacon('discover-error ' + live.lastError)
|
|
178
|
+
return false
|
|
179
|
+
} finally {
|
|
180
|
+
live.sync = undefined
|
|
181
|
+
}
|
|
182
|
+
})()
|
|
183
|
+
live.sync = run
|
|
184
|
+
return run
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const scheduleRetry = () => {
|
|
188
|
+
if (live.retryTimer !== undefined) return
|
|
189
|
+
live.retryTimer = setInterval(() => {
|
|
190
|
+
live.attempts += 1
|
|
191
|
+
void sync().then(ok => {
|
|
192
|
+
if (ok || live.attempts >= 20) stopRetry()
|
|
193
|
+
})
|
|
194
|
+
}, 30_000)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Cordis has no "dispose" event; effects run their disposer at fiber teardown.
|
|
198
|
+
ctx.effect(() => () => {
|
|
199
|
+
stopRetry()
|
|
200
|
+
disposeTools()
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
beacon('host-apply ' + live.serverName)
|
|
204
|
+
|
|
205
|
+
// ---- optional web surface -------------------------------------------------
|
|
206
|
+
const installRoutes = (webCtx: any) => {
|
|
207
|
+
const webServer = webCtx?.webServer ?? webCtx?.get?.('webServer')
|
|
208
|
+
if (webServer === undefined || typeof webServer.register !== 'function') {
|
|
209
|
+
beacon('host-no-webserver')
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
const installed = (shared.__GENMCP_ROUTES__ ??= new WeakMap<object, boolean>())
|
|
213
|
+
if (installed.get(webServer) === true) return
|
|
214
|
+
installed.set(webServer, true)
|
|
215
|
+
|
|
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
|
+
const sameOrigin = (req: any): boolean => {
|
|
220
|
+
const headers = req.headers ?? {}
|
|
221
|
+
const site = headers['sec-fetch-site']
|
|
222
|
+
if (site === 'same-origin') return true
|
|
223
|
+
const origin = headers.origin
|
|
224
|
+
const host = headers.host
|
|
225
|
+
if (typeof origin !== 'string' || typeof host !== 'string' || origin === '') return false
|
|
226
|
+
try { return new URL(origin).host === host } catch { return false }
|
|
227
|
+
}
|
|
228
|
+
const authorized = (req: any): boolean => {
|
|
229
|
+
const authorization = req.headers?.authorization ?? ''
|
|
230
|
+
return authorization === 'Bearer ' + live.token || sameOrigin(req)
|
|
231
|
+
}
|
|
232
|
+
const send = (res: any, status: number, payload: unknown) => {
|
|
233
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
234
|
+
res.end(JSON.stringify(payload))
|
|
235
|
+
}
|
|
236
|
+
const readBody = (req: any, limit = 256 * 1024): Promise<Record<string, unknown>> =>
|
|
237
|
+
new Promise((resolve, reject) => {
|
|
238
|
+
const chunks: Buffer[] = []
|
|
239
|
+
let size = 0
|
|
240
|
+
req.on('data', (chunk: Buffer) => {
|
|
241
|
+
size += chunk.length
|
|
242
|
+
if (size > limit) { reject(new Error('request body too large')); req.destroy(); return }
|
|
243
|
+
chunks.push(chunk)
|
|
244
|
+
})
|
|
245
|
+
req.on('end', () => {
|
|
246
|
+
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) }
|
|
247
|
+
catch (error) { reject(new Error('invalid JSON body')) }
|
|
248
|
+
})
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
const findEntry = () => {
|
|
252
|
+
const editor = ctx.get?.('configEditor')
|
|
253
|
+
if (editor === undefined) throw new Error('config editor is unavailable')
|
|
254
|
+
const entry = editor.entries().find((item: any) => item.options?.id === 'general-mcp')
|
|
255
|
+
if (entry === undefined) throw new Error('loader entry general-mcp not found')
|
|
256
|
+
return { editor, entry }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
try {
|
|
260
|
+
webServer.register({
|
|
261
|
+
kind: 'exact',
|
|
262
|
+
path: '/api/general-mcp/catalog',
|
|
263
|
+
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
|
+
const headers = request.headers
|
|
267
|
+
const bearer = headers?.get?.('authorization') === 'Bearer ' + live.token
|
|
268
|
+
const sameOrigin = headers?.get?.('sec-fetch-site') === 'same-origin'
|
|
269
|
+
if (!bearer && !sameOrigin) {
|
|
270
|
+
return new Response('unauthorized', { status: 401, headers: { 'cache-control': 'no-store' } })
|
|
271
|
+
}
|
|
272
|
+
const url = new URL(request.url)
|
|
273
|
+
const raw = url.searchParams.get('since')
|
|
274
|
+
const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1
|
|
275
|
+
if (since === live.version) return new Response(null, { status: 304, headers: { 'cache-control': 'no-store' } })
|
|
276
|
+
return new Response(JSON.stringify({
|
|
277
|
+
version: live.version,
|
|
278
|
+
server: live.serverName,
|
|
279
|
+
status: live.connected ? 'connected' : 'idle',
|
|
280
|
+
endpoint: live.endpoint,
|
|
281
|
+
lastError: live.lastError,
|
|
282
|
+
tools: live.catalog,
|
|
283
|
+
overrides: live.toolSettings,
|
|
284
|
+
}), { status: 200, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } })
|
|
285
|
+
},
|
|
286
|
+
})
|
|
287
|
+
|
|
288
|
+
webServer.register({
|
|
289
|
+
kind: 'exact',
|
|
290
|
+
path: '/api/general-mcp/probe',
|
|
291
|
+
handler: (req: any, res: any) => {
|
|
292
|
+
void (async () => {
|
|
293
|
+
try {
|
|
294
|
+
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
295
|
+
const body = await readBody(req)
|
|
296
|
+
const endpoint = typeof body.endpoint === 'string' ? body.endpoint.trim() : ''
|
|
297
|
+
if (!/^https?:\/\//i.test(endpoint)) throw new Error('endpoint must be an http(s) URL')
|
|
298
|
+
const headers: Record<string, string> = {}
|
|
299
|
+
if (body.headers !== null && typeof body.headers === 'object' && !Array.isArray(body.headers)) {
|
|
300
|
+
for (const [key, value] of Object.entries(body.headers as Record<string, unknown>)) {
|
|
301
|
+
if (typeof value === 'string') headers[key] = value
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const probe = new McpClient(endpoint, headers, 15_000)
|
|
305
|
+
const info: any = await probe.initialize()
|
|
306
|
+
const tools = await probe.listTools()
|
|
307
|
+
send(res, 200, {
|
|
308
|
+
ok: true,
|
|
309
|
+
protocolVersion: info?.protocolVersion ?? null,
|
|
310
|
+
server: info?.serverInfo?.name ?? null,
|
|
311
|
+
version: info?.serverInfo?.version ?? null,
|
|
312
|
+
tools: tools.map(tool => ({ name: tool.name, description: tool.description ?? '', folder: (tool._meta as any)?.['dsh/folder'] ?? null })),
|
|
313
|
+
})
|
|
314
|
+
} catch (error) {
|
|
315
|
+
send(res, 200, { ok: false, message: String((error as Error)?.message ?? error) })
|
|
316
|
+
}
|
|
317
|
+
})()
|
|
318
|
+
},
|
|
319
|
+
})
|
|
320
|
+
|
|
321
|
+
webServer.register({
|
|
322
|
+
kind: 'exact',
|
|
323
|
+
path: '/api/general-mcp/config',
|
|
324
|
+
handler: (req: any, res: any) => {
|
|
325
|
+
void (async () => {
|
|
326
|
+
try {
|
|
327
|
+
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
328
|
+
const body = await readBody(req)
|
|
329
|
+
const { editor, entry } = findEntry()
|
|
330
|
+
const next: Record<string, unknown> = {}
|
|
331
|
+
if (typeof body.endpoint === 'string') next.endpoint = body.endpoint.trim()
|
|
332
|
+
if (body.headers !== null && typeof body.headers === 'object') next.headers = body.headers
|
|
333
|
+
if (typeof body.toolCallTimeoutMs === 'number') next.toolCallTimeoutMs = body.toolCallTimeoutMs
|
|
334
|
+
await editor.edit(entry, (current: Record<string, unknown>) => ({ ...current, ...next }))
|
|
335
|
+
beacon('config-saved')
|
|
336
|
+
send(res, 200, { ok: true })
|
|
337
|
+
} catch (error) {
|
|
338
|
+
beacon('config-save-error ' + String(error))
|
|
339
|
+
send(res, 500, { ok: false, message: String((error as Error)?.message ?? error) })
|
|
340
|
+
}
|
|
341
|
+
})()
|
|
342
|
+
},
|
|
343
|
+
})
|
|
344
|
+
|
|
345
|
+
webServer.register({
|
|
346
|
+
kind: 'exact',
|
|
347
|
+
path: '/api/general-mcp/tools',
|
|
348
|
+
handler: (req: any, res: any) => {
|
|
349
|
+
void (async () => {
|
|
350
|
+
try {
|
|
351
|
+
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
352
|
+
const body = await readBody(req)
|
|
353
|
+
const { editor, entry } = findEntry()
|
|
354
|
+
const tools: ToolSettings = {
|
|
355
|
+
disabled: Array.isArray(body.disabled) ? (body.disabled as unknown[]).filter(v => typeof v === 'string') as string[] : [],
|
|
356
|
+
hidden: Array.isArray(body.hidden) ? (body.hidden as unknown[]).filter(v => typeof v === 'string') as string[] : [],
|
|
357
|
+
overrides: body.overrides !== null && typeof body.overrides === 'object' ? body.overrides as Record<string, any> : {},
|
|
358
|
+
}
|
|
359
|
+
await editor.edit(entry, (current: Record<string, unknown>) => ({ ...current, tools }))
|
|
360
|
+
beacon('tools-saved')
|
|
361
|
+
send(res, 200, { ok: true })
|
|
362
|
+
} catch (error) {
|
|
363
|
+
beacon('tools-save-error ' + String(error))
|
|
364
|
+
send(res, 500, { ok: false, message: String((error as Error)?.message ?? error) })
|
|
365
|
+
}
|
|
366
|
+
})()
|
|
367
|
+
},
|
|
368
|
+
})
|
|
369
|
+
|
|
370
|
+
beacon('routes-installed')
|
|
371
|
+
} catch (error) {
|
|
372
|
+
beacon('host-route-error ' + String(error))
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// The web carrier may mount after this plugin: wait for the service instead of
|
|
377
|
+
// reading it once (a one-shot read silently produced 404s for the whole process).
|
|
378
|
+
const startRoutes = (webCtx: any) => {
|
|
379
|
+
try {
|
|
380
|
+
installRoutes(webCtx)
|
|
381
|
+
} catch (error) {
|
|
382
|
+
beacon('host-route-failed ' + String(error))
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
if (typeof ctx.inject === 'function') {
|
|
386
|
+
try {
|
|
387
|
+
ctx.inject(['webServer'], (sub: any) => startRoutes(sub))
|
|
388
|
+
} catch (error) {
|
|
389
|
+
beacon('host-inject-failed ' + String(error))
|
|
390
|
+
startRoutes(ctx)
|
|
391
|
+
}
|
|
392
|
+
} else {
|
|
393
|
+
startRoutes(ctx)
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// Inject the catalog token into the boot payload for the page.
|
|
397
|
+
const onInject = (table: any[]) => {
|
|
398
|
+
table.push({
|
|
399
|
+
kind: 'global',
|
|
400
|
+
name: '__GENMCP__',
|
|
401
|
+
value: { token: live.token, server: live.serverName, catalogPath: '/api/general-mcp/catalog' },
|
|
402
|
+
})
|
|
403
|
+
}
|
|
404
|
+
ctx.effect(() => ctx.on('webserver/index-inject', onInject))
|
|
405
|
+
|
|
406
|
+
// ---- discovery (never blocks or fails activation) --------------------------
|
|
407
|
+
stopRetry()
|
|
408
|
+
void sync().then(ok => {
|
|
409
|
+
if (!ok && state().endpoint !== '') scheduleRetry()
|
|
410
|
+
}).catch(error => {
|
|
411
|
+
const current = state()
|
|
412
|
+
current.lastError = String((error as Error)?.message ?? error)
|
|
413
|
+
current.version += 1
|
|
414
|
+
})
|
|
415
|
+
|
|
416
|
+
ctx.effect(() => () => stopRetry())
|
|
417
|
+
|
|
418
|
+
// ---- status tool ----------------------------------------------------------
|
|
419
|
+
const statusDispose = ctx.tools.register({
|
|
420
|
+
name: 'general_mcp_status',
|
|
421
|
+
description: 'Report the general-mcp gateway connection status.',
|
|
422
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
423
|
+
output: {
|
|
424
|
+
schema: {
|
|
425
|
+
type: 'object',
|
|
426
|
+
properties: {
|
|
427
|
+
ok: { type: 'boolean' },
|
|
428
|
+
serverName: { type: 'string' },
|
|
429
|
+
endpoint: { type: 'string' },
|
|
430
|
+
connected: { type: 'boolean' },
|
|
431
|
+
toolCount: { type: 'number' },
|
|
432
|
+
lastError: { type: 'string' },
|
|
433
|
+
startedAt: { type: 'string' },
|
|
434
|
+
},
|
|
435
|
+
required: ['ok', 'serverName', 'endpoint', 'connected', 'toolCount', 'lastError', 'startedAt'],
|
|
436
|
+
additionalProperties: false,
|
|
437
|
+
},
|
|
438
|
+
render(_args: unknown, value: any) {
|
|
439
|
+
return [{
|
|
440
|
+
type: 'text',
|
|
441
|
+
text: 'general-mcp: ' + value.serverName +
|
|
442
|
+
' endpoint=' + (value.endpoint === '' ? '(unset)' : value.endpoint) +
|
|
443
|
+
' connected=' + value.connected +
|
|
444
|
+
' tools=' + value.toolCount +
|
|
445
|
+
(value.lastError === '' ? '' : ' error=' + value.lastError),
|
|
446
|
+
}]
|
|
447
|
+
},
|
|
448
|
+
},
|
|
449
|
+
async execute() {
|
|
450
|
+
return {
|
|
451
|
+
ok: live.endpoint !== '' && live.lastError === '' && live.connected,
|
|
452
|
+
serverName: live.serverName,
|
|
453
|
+
endpoint: live.endpoint,
|
|
454
|
+
connected: live.connected,
|
|
455
|
+
toolCount: live.toolCount,
|
|
456
|
+
lastError: live.lastError,
|
|
457
|
+
startedAt,
|
|
458
|
+
}
|
|
459
|
+
},
|
|
460
|
+
})
|
|
461
|
+
ctx.effect(() => () => statusDispose())
|
|
462
|
+
}
|
|
463
|
+
|
package/src/naming.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Public tool name: mcp__<server>__<raw>, normalized to the function-name contract. */
|
|
2
|
+
const MAX_LENGTH = 64
|
|
3
|
+
|
|
4
|
+
function sanitize(value: string): string {
|
|
5
|
+
return value.replace(/[^A-Za-z0-9_-]/g, '_')
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function shortHash(value: string): string {
|
|
9
|
+
let hash = 0x811c9dc5
|
|
10
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
11
|
+
hash ^= value.charCodeAt(index)
|
|
12
|
+
hash = Math.imul(hash, 0x01000193) >>> 0
|
|
13
|
+
}
|
|
14
|
+
return hash.toString(16).padStart(8, '0')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function publicToolName(serverName: string, rawName: string): string {
|
|
18
|
+
const base = 'mcp__' + sanitize(serverName) + '__' + sanitize(rawName)
|
|
19
|
+
if (base.length <= MAX_LENGTH) return base
|
|
20
|
+
return base.slice(0, MAX_LENGTH - 9) + '_' + shortHash(base)
|
|
21
|
+
}
|
package/src/register.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/** Adapt one MCP tool to a DSH ToolDefinition, projecting MCP blocks safely. */
|
|
2
|
+
import type { McpClient, McpTool } from './client.ts'
|
|
3
|
+
import { publicToolName } from './naming.ts'
|
|
4
|
+
|
|
5
|
+
interface DshBlock {
|
|
6
|
+
type: 'text'
|
|
7
|
+
text: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function placeholder(kind: string, detail: string): string {
|
|
11
|
+
return '[' + kind + (detail === '' ? '' : ': ' + detail) + ']'
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* MCP content is richer than DSH's model-facing vocabulary. Text passes
|
|
16
|
+
* through; binary and structured blocks become short placeholders so base64
|
|
17
|
+
* never reaches the transcript or the provider.
|
|
18
|
+
*/
|
|
19
|
+
export function projectBlocks(blocks: unknown): DshBlock[] {
|
|
20
|
+
if (!Array.isArray(blocks)) return []
|
|
21
|
+
const out: DshBlock[] = []
|
|
22
|
+
for (const raw of blocks) {
|
|
23
|
+
const block = raw as any
|
|
24
|
+
switch (block?.type) {
|
|
25
|
+
case 'text':
|
|
26
|
+
out.push({ type: 'text', text: String(block.text ?? '') })
|
|
27
|
+
break
|
|
28
|
+
case 'image':
|
|
29
|
+
out.push({ type: 'text', text: placeholder('image', String(block.mimeType ?? 'unknown')) })
|
|
30
|
+
break
|
|
31
|
+
case 'audio':
|
|
32
|
+
out.push({ type: 'text', text: placeholder('audio', String(block.mimeType ?? 'unknown')) })
|
|
33
|
+
break
|
|
34
|
+
case 'resource_link':
|
|
35
|
+
out.push({ type: 'text', text: placeholder('resource', String(block.uri ?? '')) })
|
|
36
|
+
break
|
|
37
|
+
case 'resource':
|
|
38
|
+
out.push({ type: 'text', text: placeholder('resource', String(block.resource?.uri ?? '')) })
|
|
39
|
+
break
|
|
40
|
+
default:
|
|
41
|
+
out.push({ type: 'text', text: placeholder('block', String(block?.type ?? 'unknown')) })
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return out
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function textOf(blocks: DshBlock[]): string {
|
|
48
|
+
return blocks.map(block => block.text).join('\n')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function createToolDefinition(
|
|
52
|
+
serverName: string,
|
|
53
|
+
tool: McpTool,
|
|
54
|
+
client: McpClient,
|
|
55
|
+
): Record<string, unknown> {
|
|
56
|
+
const parameters = tool.inputSchema && typeof tool.inputSchema === 'object'
|
|
57
|
+
? tool.inputSchema
|
|
58
|
+
: { type: 'object', properties: {} }
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
name: publicToolName(serverName, tool.name),
|
|
62
|
+
description: tool.description ?? tool.name,
|
|
63
|
+
parameters,
|
|
64
|
+
output: {
|
|
65
|
+
schema: {
|
|
66
|
+
type: 'object',
|
|
67
|
+
properties: {
|
|
68
|
+
content: { type: 'array', items: {} },
|
|
69
|
+
structuredContent: {},
|
|
70
|
+
},
|
|
71
|
+
required: ['content'],
|
|
72
|
+
additionalProperties: true,
|
|
73
|
+
},
|
|
74
|
+
render(_args: unknown, value: any) {
|
|
75
|
+
return [{ type: 'text', text: textOf(projectBlocks(value?.content)) }]
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
isConcurrencySafe() {
|
|
79
|
+
return true
|
|
80
|
+
},
|
|
81
|
+
async execute(args: Record<string, unknown>, exec: any) {
|
|
82
|
+
const result = await client.callTool(tool.name, args ?? {}, exec?.signal)
|
|
83
|
+
const content = projectBlocks(result.content)
|
|
84
|
+
if (result.isError) throw new Error(textOf(content))
|
|
85
|
+
return {
|
|
86
|
+
content,
|
|
87
|
+
...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
}
|
package/README.md
DELETED