@momeidejiyi/dsh-general-mcp 0.1.5 → 0.1.7
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/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @momeidejiyi/dsh-general-mcp@0.1.
|
|
1
|
+
// @momeidejiyi/dsh-general-mcp@0.1.7 (generated)
|
|
2
2
|
|
|
3
3
|
// packages/general-mcp/src/index.ts
|
|
4
4
|
import { appendFileSync } from "node:fs";
|
|
@@ -94,6 +94,7 @@ function buildCatalog(serverName, tools, publicName, settings = {}) {
|
|
|
94
94
|
const description = tool.description ?? tool.name;
|
|
95
95
|
return {
|
|
96
96
|
toolName: publicName(tool.name),
|
|
97
|
+
server: serverName,
|
|
97
98
|
rawName: tool.name,
|
|
98
99
|
path,
|
|
99
100
|
virtualPath: "dsh-mcp://" + serverName + "/" + path,
|
|
@@ -112,7 +113,7 @@ function buildCatalog(serverName, tools, publicName, settings = {}) {
|
|
|
112
113
|
}
|
|
113
114
|
|
|
114
115
|
// packages/general-mcp/src/client.ts
|
|
115
|
-
var CLIENT_VERSION = "0.1.
|
|
116
|
+
var CLIENT_VERSION = "0.1.7";
|
|
116
117
|
var MODERN = "2026-07-28";
|
|
117
118
|
var LEGACY = "2025-06-18";
|
|
118
119
|
var META_VERSION = "io.modelcontextprotocol/protocolVersion";
|
|
@@ -321,6 +322,248 @@ async function readSseResult(response, id) {
|
|
|
321
322
|
throw new Error("no JSON-RPC response with the request id in the SSE stream");
|
|
322
323
|
}
|
|
323
324
|
|
|
325
|
+
// packages/general-mcp/src/sse.ts
|
|
326
|
+
var SseClient = class {
|
|
327
|
+
constructor(url, headers = {}, timeoutMs = 6e4) {
|
|
328
|
+
this.url = url;
|
|
329
|
+
this.headers = headers;
|
|
330
|
+
this.timeoutMs = timeoutMs;
|
|
331
|
+
}
|
|
332
|
+
messageUrl;
|
|
333
|
+
pending = /* @__PURE__ */ new Map();
|
|
334
|
+
nextId = 0;
|
|
335
|
+
controller = new AbortController();
|
|
336
|
+
reader;
|
|
337
|
+
connected;
|
|
338
|
+
closed = false;
|
|
339
|
+
get protocolVersion() {
|
|
340
|
+
return "2024-11-05";
|
|
341
|
+
}
|
|
342
|
+
/** Open the stream and wait for the endpoint announcement. */
|
|
343
|
+
connect() {
|
|
344
|
+
if (this.connected !== void 0) return this.connected;
|
|
345
|
+
this.connected = (async () => {
|
|
346
|
+
const headers = { accept: "text/event-stream", ...this.headers };
|
|
347
|
+
const response = await fetch(this.url, { headers, signal: this.controller.signal });
|
|
348
|
+
if (!response.ok) throw new Error("SSE connect failed: HTTP " + response.status);
|
|
349
|
+
if (response.body === null) throw new Error("SSE connect returned no body");
|
|
350
|
+
this.reader = response.body.getReader();
|
|
351
|
+
const announced = new Promise((resolve, reject) => {
|
|
352
|
+
const timer = setTimeout(() => reject(new Error("SSE endpoint event timed out")), this.timeoutMs);
|
|
353
|
+
this.endpointWaiter = { resolve, reject, timer };
|
|
354
|
+
});
|
|
355
|
+
void this.pump();
|
|
356
|
+
await announced;
|
|
357
|
+
if (this.messageUrl === void 0) throw new Error("SSE server did not announce an endpoint");
|
|
358
|
+
})();
|
|
359
|
+
return this.connected;
|
|
360
|
+
}
|
|
361
|
+
endpointWaiter;
|
|
362
|
+
async pump() {
|
|
363
|
+
const decoder = new TextDecoder();
|
|
364
|
+
let buffer = "";
|
|
365
|
+
try {
|
|
366
|
+
while (true) {
|
|
367
|
+
const chunk = await this.reader?.read();
|
|
368
|
+
if (chunk === void 0 || chunk.done === true) break;
|
|
369
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
370
|
+
let index = buffer.indexOf("\n\n");
|
|
371
|
+
while (index >= 0) {
|
|
372
|
+
this.handleEvent(buffer.slice(0, index));
|
|
373
|
+
buffer = buffer.slice(index + 2);
|
|
374
|
+
index = buffer.indexOf("\n\n");
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
} catch (error) {
|
|
378
|
+
if (this.closed !== true) this.failAll(new Error("SSE stream failed: " + String(error?.message ?? error)));
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
handleEvent(raw) {
|
|
382
|
+
let event = "message";
|
|
383
|
+
const data = [];
|
|
384
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
385
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
386
|
+
else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
|
|
387
|
+
}
|
|
388
|
+
const payload = data.join("\n");
|
|
389
|
+
if (event === "endpoint") {
|
|
390
|
+
try {
|
|
391
|
+
this.messageUrl = new URL(payload, this.url).toString();
|
|
392
|
+
} catch {
|
|
393
|
+
this.messageUrl = payload;
|
|
394
|
+
}
|
|
395
|
+
const waiter = this.endpointWaiter;
|
|
396
|
+
this.endpointWaiter = void 0;
|
|
397
|
+
if (waiter !== void 0) {
|
|
398
|
+
clearTimeout(waiter.timer);
|
|
399
|
+
waiter.resolve(void 0);
|
|
400
|
+
}
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (event === "message" || event === "") {
|
|
404
|
+
let parsed;
|
|
405
|
+
try {
|
|
406
|
+
parsed = JSON.parse(payload);
|
|
407
|
+
} catch {
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
const id = parsed?.id;
|
|
411
|
+
if (typeof id === "number") {
|
|
412
|
+
const waiter = this.pending.get(id);
|
|
413
|
+
if (waiter !== void 0) {
|
|
414
|
+
this.pending.delete(id);
|
|
415
|
+
clearTimeout(waiter.timer);
|
|
416
|
+
if (parsed.error !== void 0) waiter.reject(new Error("MCP error " + parsed.error.code + ": " + parsed.error.message));
|
|
417
|
+
else waiter.resolve(parsed.result);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
if (event === "error") {
|
|
423
|
+
const waiter = this.endpointWaiter;
|
|
424
|
+
this.endpointWaiter = void 0;
|
|
425
|
+
if (waiter !== void 0) {
|
|
426
|
+
clearTimeout(waiter.timer);
|
|
427
|
+
waiter.reject(new Error("SSE error: " + payload));
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
failAll(error) {
|
|
432
|
+
for (const [id, waiter2] of this.pending) {
|
|
433
|
+
clearTimeout(waiter2.timer);
|
|
434
|
+
waiter2.reject(error);
|
|
435
|
+
this.pending.delete(id);
|
|
436
|
+
}
|
|
437
|
+
const waiter = this.endpointWaiter;
|
|
438
|
+
this.endpointWaiter = void 0;
|
|
439
|
+
if (waiter !== void 0) {
|
|
440
|
+
clearTimeout(waiter.timer);
|
|
441
|
+
waiter.reject(error);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
async request(method, params) {
|
|
445
|
+
await this.connect();
|
|
446
|
+
const id = this.nextId += 1;
|
|
447
|
+
const body = JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
448
|
+
const reply = new Promise((resolve, reject) => {
|
|
449
|
+
const timer = setTimeout(() => {
|
|
450
|
+
this.pending.delete(id);
|
|
451
|
+
reject(new Error("MCP " + method + " timed out after " + this.timeoutMs + "ms"));
|
|
452
|
+
}, this.timeoutMs);
|
|
453
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
454
|
+
});
|
|
455
|
+
const response = await fetch(this.messageUrl, {
|
|
456
|
+
method: "POST",
|
|
457
|
+
headers: { "content-type": "application/json", ...this.headers },
|
|
458
|
+
body,
|
|
459
|
+
signal: this.controller.signal
|
|
460
|
+
});
|
|
461
|
+
if (!response.ok) {
|
|
462
|
+
const pending = this.pending.get(id);
|
|
463
|
+
if (pending !== void 0) {
|
|
464
|
+
clearTimeout(pending.timer);
|
|
465
|
+
this.pending.delete(id);
|
|
466
|
+
}
|
|
467
|
+
throw new Error("MCP " + method + " POST failed: HTTP " + response.status);
|
|
468
|
+
}
|
|
469
|
+
return reply;
|
|
470
|
+
}
|
|
471
|
+
async initialize() {
|
|
472
|
+
const result = await this.request("initialize", {
|
|
473
|
+
protocolVersion: "2024-11-05",
|
|
474
|
+
capabilities: {},
|
|
475
|
+
clientInfo: { name: "dsh-general-mcp", version: "0.1.6" }
|
|
476
|
+
});
|
|
477
|
+
await this.notify("notifications/initialized", {});
|
|
478
|
+
return { ...result ?? {}, protocolVersion: result?.protocolVersion ?? "2024-11-05" };
|
|
479
|
+
}
|
|
480
|
+
async notify(method, params) {
|
|
481
|
+
await this.connect();
|
|
482
|
+
const response = await fetch(this.messageUrl, {
|
|
483
|
+
method: "POST",
|
|
484
|
+
headers: { "content-type": "application/json", ...this.headers },
|
|
485
|
+
body: JSON.stringify({ jsonrpc: "2.0", method, params }),
|
|
486
|
+
signal: this.controller.signal
|
|
487
|
+
});
|
|
488
|
+
if (!response.ok) throw new Error("notify " + method + " failed: HTTP " + response.status);
|
|
489
|
+
}
|
|
490
|
+
async listTools() {
|
|
491
|
+
const tools = [];
|
|
492
|
+
let cursor;
|
|
493
|
+
for (let page = 0; page < 100; page += 1) {
|
|
494
|
+
const result = await this.request("tools/list", cursor === void 0 ? {} : { cursor });
|
|
495
|
+
if (!Array.isArray(result?.tools)) throw new Error("tools/list returned no tools array");
|
|
496
|
+
tools.push(...result.tools);
|
|
497
|
+
const next = typeof result.nextCursor === "string" && result.nextCursor !== "" ? result.nextCursor : void 0;
|
|
498
|
+
if (next === void 0 || tools.some((tool) => tool.name === "")) break;
|
|
499
|
+
cursor = next;
|
|
500
|
+
}
|
|
501
|
+
return tools;
|
|
502
|
+
}
|
|
503
|
+
async callTool(name2, args) {
|
|
504
|
+
const result = await this.request("tools/call", { name: name2, arguments: args });
|
|
505
|
+
return result ?? {};
|
|
506
|
+
}
|
|
507
|
+
async close() {
|
|
508
|
+
this.closed = true;
|
|
509
|
+
this.failAll(new Error("SSE client closed"));
|
|
510
|
+
this.controller.abort();
|
|
511
|
+
try {
|
|
512
|
+
await this.reader?.cancel();
|
|
513
|
+
} catch {
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
// packages/general-mcp/src/connect.ts
|
|
519
|
+
function looksLikeSse(url) {
|
|
520
|
+
try {
|
|
521
|
+
return new URL(url).pathname.replace(/\/+$/, "").endsWith("/sse");
|
|
522
|
+
} catch {
|
|
523
|
+
return false;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
async function viaStreamable(url, headers, timeoutMs) {
|
|
527
|
+
const client = new McpClient(url, headers, timeoutMs);
|
|
528
|
+
const info = await client.initialize();
|
|
529
|
+
return {
|
|
530
|
+
transport: "streamable",
|
|
531
|
+
protocolVersion: info?.protocolVersion,
|
|
532
|
+
serverInfo: info?.serverInfo,
|
|
533
|
+
async initialize() {
|
|
534
|
+
},
|
|
535
|
+
listTools: () => client.listTools(),
|
|
536
|
+
callTool: (name2, args, signal) => client.callTool(name2, args, signal),
|
|
537
|
+
close: () => client.close()
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
async function viaSse(url, headers, timeoutMs) {
|
|
541
|
+
const client = new SseClient(url, headers, timeoutMs);
|
|
542
|
+
const info = await client.initialize();
|
|
543
|
+
return {
|
|
544
|
+
transport: "sse",
|
|
545
|
+
protocolVersion: info?.protocolVersion,
|
|
546
|
+
serverInfo: info?.serverInfo,
|
|
547
|
+
async initialize() {
|
|
548
|
+
},
|
|
549
|
+
listTools: async () => await client.listTools(),
|
|
550
|
+
callTool: (name2, args) => client.callTool(name2, args),
|
|
551
|
+
close: () => client.close()
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
async function connectMcp(url, headers, timeoutMs) {
|
|
555
|
+
const order = looksLikeSse(url) ? [() => viaSse(url, headers, timeoutMs), () => viaStreamable(url, headers, timeoutMs)] : [() => viaStreamable(url, headers, timeoutMs), () => viaSse(url, headers, timeoutMs)];
|
|
556
|
+
const errors = [];
|
|
557
|
+
for (const attempt of order) {
|
|
558
|
+
try {
|
|
559
|
+
return await attempt();
|
|
560
|
+
} catch (error) {
|
|
561
|
+
errors.push(String(error?.message ?? error));
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
throw new Error("\u65E0\u6CD5\u8FDE\u63A5\u7F51\u5173\uFF08\u4E24\u79CD\u4F20\u8F93\u90FD\u5931\u8D25\uFF09: " + errors.join(" | "));
|
|
565
|
+
}
|
|
566
|
+
|
|
324
567
|
// packages/general-mcp/src/naming.ts
|
|
325
568
|
var MAX_LENGTH = 64;
|
|
326
569
|
function sanitize(value) {
|
|
@@ -412,146 +655,214 @@ function createToolDefinition(serverName, tool, client) {
|
|
|
412
655
|
// packages/general-mcp/src/index.ts
|
|
413
656
|
var name = "general-mcp";
|
|
414
657
|
var inject = ["tools"];
|
|
658
|
+
var NAME_PATTERN2 = /^[A-Za-z0-9_-]{1,32}$/;
|
|
415
659
|
var shared = globalThis;
|
|
416
|
-
function
|
|
660
|
+
function state() {
|
|
661
|
+
const existing = shared.__GENMCP_STATE__;
|
|
662
|
+
if (existing === void 0 || !(existing.servers instanceof Map)) {
|
|
663
|
+
shared.__GENMCP_STATE__ = {
|
|
664
|
+
token: typeof existing?.token === "string" ? existing.token : Math.random().toString(36).slice(2) + Date.now().toString(36),
|
|
665
|
+
servers: /* @__PURE__ */ new Map(),
|
|
666
|
+
version: 0,
|
|
667
|
+
debug: false,
|
|
668
|
+
timeoutMs: 6e4
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
return shared.__GENMCP_STATE__;
|
|
672
|
+
}
|
|
673
|
+
function serverState(name2) {
|
|
417
674
|
const live = state();
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
675
|
+
let entry = live.servers.get(name2);
|
|
676
|
+
if (entry === void 0) {
|
|
677
|
+
entry = {
|
|
678
|
+
name: name2,
|
|
679
|
+
endpoint: "",
|
|
680
|
+
headers: {},
|
|
681
|
+
connected: false,
|
|
682
|
+
toolCount: 0,
|
|
683
|
+
lastError: "",
|
|
684
|
+
catalog: [],
|
|
685
|
+
tools: /* @__PURE__ */ new Map(),
|
|
686
|
+
settings: {},
|
|
687
|
+
attempts: 0
|
|
688
|
+
};
|
|
689
|
+
live.servers.set(name2, entry);
|
|
690
|
+
}
|
|
691
|
+
return entry;
|
|
692
|
+
}
|
|
693
|
+
function beacon(message) {
|
|
694
|
+
if (state().debug !== true) return;
|
|
695
|
+
try {
|
|
696
|
+
appendFileSync(join(tmpdir(), "dsh-general-mcp-debug.log"), (/* @__PURE__ */ new Date()).toISOString() + " " + message + "\n");
|
|
697
|
+
} catch {
|
|
422
698
|
}
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
const
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
699
|
+
}
|
|
700
|
+
function normalizeSettings(raw) {
|
|
701
|
+
const tools = raw ?? {};
|
|
702
|
+
const overrides = {};
|
|
703
|
+
if (tools.overrides !== null && typeof tools.overrides === "object" && !Array.isArray(tools.overrides)) {
|
|
704
|
+
for (const [key, value] of Object.entries(tools.overrides)) {
|
|
705
|
+
if (value !== null && typeof value === "object") overrides[key] = value;
|
|
429
706
|
}
|
|
430
707
|
}
|
|
431
|
-
|
|
432
|
-
const timeout = typeof raw.toolCallTimeoutMs === "number" && Number.isFinite(raw.toolCallTimeoutMs) ? Math.min(Math.max(Math.round(raw.toolCallTimeoutMs), 1e3), 6e5) : 6e4;
|
|
433
|
-
live.timeoutMs = timeout;
|
|
434
|
-
live.debug = raw.debug === true;
|
|
435
|
-
const tools = raw.tools ?? {};
|
|
436
|
-
live.toolSettings = {
|
|
708
|
+
return {
|
|
437
709
|
disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item) => typeof item === "string") : [],
|
|
438
710
|
hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item) => typeof item === "string") : [],
|
|
439
|
-
overrides
|
|
711
|
+
overrides
|
|
440
712
|
};
|
|
441
713
|
}
|
|
442
|
-
function
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
714
|
+
function normalizeConfig(config) {
|
|
715
|
+
const raw = config ?? {};
|
|
716
|
+
const live = state();
|
|
717
|
+
const timeout = typeof raw.toolCallTimeoutMs === "number" && Number.isFinite(raw.toolCallTimeoutMs) ? Math.min(Math.max(Math.round(raw.toolCallTimeoutMs), 1e3), 6e5) : 6e4;
|
|
718
|
+
live.timeoutMs = timeout;
|
|
719
|
+
live.debug = raw.debug === true;
|
|
720
|
+
const list = Array.isArray(raw.servers) && raw.servers.length > 0 ? raw.servers.map((item) => ({ ...item })) : [{ name: raw.serverName, endpoint: raw.endpoint, headers: raw.headers, tools: raw.tools }];
|
|
721
|
+
const seen = /* @__PURE__ */ new Set();
|
|
722
|
+
const out = [];
|
|
723
|
+
for (const item of list) {
|
|
724
|
+
const name2 = typeof item.name === "string" && item.name.trim() !== "" ? item.name.trim() : "general";
|
|
725
|
+
const endpoint = typeof item.endpoint === "string" ? item.endpoint.trim() : "";
|
|
726
|
+
if (endpoint !== "" && !/^https?:\/\//i.test(endpoint)) {
|
|
727
|
+
throw new Error("\u7F51\u5173 " + name2 + " \u7684\u5730\u5740\u5FC5\u987B\u4EE5 http(s):// \u5F00\u5934");
|
|
728
|
+
}
|
|
729
|
+
if (!NAME_PATTERN2.test(name2)) {
|
|
730
|
+
throw new Error('\u7F51\u5173\u540D "' + name2 + '" \u975E\u6CD5\uFF1A\u53EA\u80FD\u7528\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C1..32 \u5B57');
|
|
731
|
+
}
|
|
732
|
+
if (seen.has(name2)) throw new Error('\u7F51\u5173\u540D "' + name2 + '" \u91CD\u590D');
|
|
733
|
+
seen.add(name2);
|
|
734
|
+
out.push({ ...item, name: name2, endpoint });
|
|
735
|
+
}
|
|
736
|
+
return out;
|
|
460
737
|
}
|
|
461
|
-
|
|
462
|
-
normalizeConfig(config);
|
|
738
|
+
function apply(ctx, config) {
|
|
463
739
|
const live = state();
|
|
464
|
-
const
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
740
|
+
const servers = normalizeConfig(config);
|
|
741
|
+
beacon("host-apply " + servers.map((item) => item.name).join(","));
|
|
742
|
+
const { disposeTools, registerTools, sync, scheduleRetry, stopRetry } = createRuntime(ctx);
|
|
743
|
+
for (const [name2, entry] of live.servers) {
|
|
744
|
+
if (servers.some((item) => item.name === name2)) continue;
|
|
745
|
+
stopRetry(entry);
|
|
746
|
+
disposeTools(entry);
|
|
747
|
+
live.servers.delete(name2);
|
|
748
|
+
live.version += 1;
|
|
749
|
+
}
|
|
750
|
+
for (const item of servers) {
|
|
751
|
+
const entry = serverState(item.name);
|
|
752
|
+
const headers = {};
|
|
753
|
+
if (item.headers !== null && typeof item.headers === "object") {
|
|
754
|
+
for (const [key, value] of Object.entries(item.headers)) {
|
|
755
|
+
if (typeof value === "string") headers[key] = value;
|
|
756
|
+
}
|
|
470
757
|
}
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
758
|
+
const changed = entry.endpoint !== (item.endpoint ?? "") || JSON.stringify(entry.headers) !== JSON.stringify(headers);
|
|
759
|
+
entry.endpoint = item.endpoint ?? "";
|
|
760
|
+
entry.headers = headers;
|
|
761
|
+
entry.settings = normalizeSettings(item.tools);
|
|
762
|
+
if (changed) {
|
|
763
|
+
stopRetry(entry);
|
|
764
|
+
disposeTools(entry);
|
|
765
|
+
entry.connected = false;
|
|
766
|
+
entry.lastError = "";
|
|
767
|
+
entry.attempts = 0;
|
|
768
|
+
live.version += 1;
|
|
769
|
+
}
|
|
770
|
+
if (entry.endpoint === "") {
|
|
771
|
+
disposeTools(entry);
|
|
772
|
+
entry.connected = false;
|
|
773
|
+
entry.toolCount = 0;
|
|
774
|
+
entry.catalog = [];
|
|
775
|
+
entry.lastError = "";
|
|
776
|
+
continue;
|
|
777
|
+
}
|
|
778
|
+
void sync(entry).then((ok) => {
|
|
779
|
+
if (!ok) scheduleRetry(entry);
|
|
780
|
+
}).catch((error) => {
|
|
781
|
+
entry.lastError = String(error?.message ?? error);
|
|
782
|
+
live.version += 1;
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
installRoutes(ctx);
|
|
786
|
+
registerStatusTool(ctx);
|
|
787
|
+
}
|
|
788
|
+
function createRuntime(ctx) {
|
|
789
|
+
const live = state();
|
|
790
|
+
const disposeTools = (entry) => {
|
|
791
|
+
for (const dispose of entry.tools.values()) {
|
|
474
792
|
try {
|
|
475
793
|
dispose();
|
|
476
794
|
} catch {
|
|
477
795
|
}
|
|
478
|
-
live.tools.delete(key);
|
|
479
796
|
}
|
|
797
|
+
entry.tools.clear();
|
|
798
|
+
entry.toolCount = 0;
|
|
480
799
|
};
|
|
481
|
-
const
|
|
482
|
-
|
|
483
|
-
live.retryTimer = void 0;
|
|
484
|
-
};
|
|
485
|
-
const registerTools = (tools, client) => {
|
|
486
|
-
const disabled = new Set(live.toolSettings.disabled ?? []);
|
|
487
|
-
const hidden = new Set(live.toolSettings.hidden ?? []);
|
|
488
|
-
disposeTools();
|
|
800
|
+
const registerTools = (entry, tools, client) => {
|
|
801
|
+
const settings = entry.settings;
|
|
489
802
|
for (const tool of tools) {
|
|
490
|
-
if (
|
|
803
|
+
if (settings.disabled?.includes(tool.name) === true) continue;
|
|
491
804
|
const invalid = validateTool(tool);
|
|
492
|
-
if (invalid !== void 0)
|
|
493
|
-
|
|
494
|
-
|
|
805
|
+
if (invalid !== void 0) continue;
|
|
806
|
+
const definition = createToolDefinition(entry.name, tool, client);
|
|
807
|
+
try {
|
|
808
|
+
entry.tools.set(tool.name, ctx.tools.register(definition));
|
|
809
|
+
} catch (error) {
|
|
810
|
+
beacon("register-failed " + entry.name + "/" + tool.name + " " + String(error));
|
|
495
811
|
}
|
|
496
|
-
const definition = createToolDefinition(live.serverName, tool, client);
|
|
497
|
-
const dispose = ctx.tools.register(definition);
|
|
498
|
-
live.tools.set(definition.name, dispose);
|
|
499
812
|
}
|
|
500
813
|
};
|
|
501
|
-
const sync = () => {
|
|
502
|
-
if (
|
|
814
|
+
const sync = (entry) => {
|
|
815
|
+
if (entry.sync !== void 0) return entry.sync;
|
|
503
816
|
const run = (async () => {
|
|
504
|
-
if (
|
|
505
|
-
|
|
506
|
-
live.connected = false;
|
|
507
|
-
live.toolCount = 0;
|
|
508
|
-
live.catalog = [];
|
|
509
|
-
live.lastError = "";
|
|
510
|
-
live.version += 1;
|
|
511
|
-
return false;
|
|
512
|
-
}
|
|
513
|
-
const client = new McpClient(live.endpoint, live.headers, live.timeoutMs);
|
|
817
|
+
if (entry.endpoint === "") return false;
|
|
818
|
+
const client = await connectMcp(entry.endpoint, entry.headers, live.timeoutMs);
|
|
514
819
|
try {
|
|
515
|
-
await client.initialize();
|
|
516
820
|
const tools = await client.listTools();
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
821
|
+
disposeTools(entry);
|
|
822
|
+
registerTools(entry, tools, client);
|
|
823
|
+
entry.connected = true;
|
|
824
|
+
entry.toolCount = entry.tools.size;
|
|
825
|
+
entry.catalog = buildCatalog(entry.name, tools, (raw) => publicToolName(entry.name, raw), entry.settings);
|
|
826
|
+
entry.lastError = "";
|
|
827
|
+
entry.attempts = 0;
|
|
521
828
|
live.version += 1;
|
|
522
|
-
|
|
523
|
-
live.attempts = 0;
|
|
524
|
-
beacon("discovered " + tools.length + " version=" + live.version);
|
|
829
|
+
beacon("discovered " + entry.name + " tools=" + tools.length);
|
|
525
830
|
return true;
|
|
526
831
|
} catch (error) {
|
|
527
|
-
|
|
528
|
-
|
|
832
|
+
entry.connected = false;
|
|
833
|
+
entry.lastError = String(error?.message ?? error);
|
|
529
834
|
live.version += 1;
|
|
530
|
-
ctx.logger?.warn?.("general-mcp: " +
|
|
531
|
-
beacon("discover-error " +
|
|
835
|
+
ctx.logger?.warn?.("general-mcp(" + entry.name + "): " + entry.lastError);
|
|
836
|
+
beacon("discover-error " + entry.name + " " + entry.lastError);
|
|
532
837
|
return false;
|
|
533
838
|
} finally {
|
|
534
|
-
|
|
839
|
+
entry.sync = void 0;
|
|
535
840
|
}
|
|
536
841
|
})();
|
|
537
|
-
|
|
842
|
+
entry.sync = run;
|
|
538
843
|
return run;
|
|
539
844
|
};
|
|
540
|
-
const
|
|
541
|
-
if (
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
845
|
+
const stopRetry = (entry) => {
|
|
846
|
+
if (entry.retryTimer !== void 0) {
|
|
847
|
+
clearInterval(entry.retryTimer);
|
|
848
|
+
entry.retryTimer = void 0;
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
const scheduleRetry = (entry) => {
|
|
852
|
+
if (entry.retryTimer !== void 0) return;
|
|
853
|
+
entry.retryTimer = setInterval(() => {
|
|
854
|
+
entry.attempts += 1;
|
|
855
|
+
void sync(entry).then((ok) => {
|
|
856
|
+
if (ok || entry.attempts >= 20) stopRetry(entry);
|
|
546
857
|
});
|
|
547
858
|
}, 3e4);
|
|
548
859
|
};
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
const
|
|
860
|
+
return { disposeTools, registerTools, sync, scheduleRetry, stopRetry };
|
|
861
|
+
}
|
|
862
|
+
function installRoutes(ctx) {
|
|
863
|
+
const live = state();
|
|
864
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
865
|
+
const install = (webCtx) => {
|
|
555
866
|
const webServer = webCtx?.webServer ?? webCtx?.get?.("webServer");
|
|
556
867
|
if (webServer === void 0 || typeof webServer.register !== "function") {
|
|
557
868
|
beacon("host-no-webserver");
|
|
@@ -562,8 +873,7 @@ async function apply(ctx, config = {}) {
|
|
|
562
873
|
installed.set(webServer, true);
|
|
563
874
|
const sameOrigin = (req) => {
|
|
564
875
|
const headers = req.headers ?? {};
|
|
565
|
-
|
|
566
|
-
if (site === "same-origin") return true;
|
|
876
|
+
if (headers["sec-fetch-site"] === "same-origin") return true;
|
|
567
877
|
const origin = headers.origin;
|
|
568
878
|
const host = headers.host;
|
|
569
879
|
if (typeof origin !== "string" || typeof host !== "string" || origin === "") return false;
|
|
@@ -586,17 +896,13 @@ async function apply(ctx, config = {}) {
|
|
|
586
896
|
let size = 0;
|
|
587
897
|
req.on("data", (chunk) => {
|
|
588
898
|
size += chunk.length;
|
|
589
|
-
if (size > limit)
|
|
590
|
-
|
|
591
|
-
req.destroy();
|
|
592
|
-
return;
|
|
593
|
-
}
|
|
594
|
-
chunks.push(chunk);
|
|
899
|
+
if (size > limit) reject(new Error("body too large"));
|
|
900
|
+
else chunks.push(chunk);
|
|
595
901
|
});
|
|
596
902
|
req.on("end", () => {
|
|
597
903
|
try {
|
|
598
904
|
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"));
|
|
599
|
-
} catch
|
|
905
|
+
} catch {
|
|
600
906
|
reject(new Error("invalid JSON body"));
|
|
601
907
|
}
|
|
602
908
|
});
|
|
@@ -615,8 +921,8 @@ async function apply(ctx, config = {}) {
|
|
|
615
921
|
resource: async (request) => {
|
|
616
922
|
const headers = request.headers;
|
|
617
923
|
const bearer = headers?.get?.("authorization") === "Bearer " + live.token;
|
|
618
|
-
const
|
|
619
|
-
if (!bearer && !
|
|
924
|
+
const origin = headers?.get?.("sec-fetch-site") === "same-origin";
|
|
925
|
+
if (!bearer && !origin) {
|
|
620
926
|
return new Response("unauthorized", { status: 401, headers: { "cache-control": "no-store" } });
|
|
621
927
|
}
|
|
622
928
|
const url = new URL(request.url);
|
|
@@ -625,12 +931,15 @@ async function apply(ctx, config = {}) {
|
|
|
625
931
|
if (since === live.version) return new Response(null, { status: 304, headers: { "cache-control": "no-store" } });
|
|
626
932
|
return new Response(JSON.stringify({
|
|
627
933
|
version: live.version,
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
934
|
+
servers: [...live.servers.values()].map((entry) => ({
|
|
935
|
+
name: entry.name,
|
|
936
|
+
endpoint: entry.endpoint,
|
|
937
|
+
status: entry.connected ? "connected" : "idle",
|
|
938
|
+
lastError: entry.lastError,
|
|
939
|
+
toolCount: entry.toolCount,
|
|
940
|
+
tools: entry.catalog,
|
|
941
|
+
settings: entry.settings
|
|
942
|
+
}))
|
|
634
943
|
}), { status: 200, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
|
|
635
944
|
}
|
|
636
945
|
});
|
|
@@ -653,14 +962,14 @@ async function apply(ctx, config = {}) {
|
|
|
653
962
|
if (typeof value === "string") headers[key] = value;
|
|
654
963
|
}
|
|
655
964
|
}
|
|
656
|
-
const probe =
|
|
657
|
-
const info = await probe.initialize();
|
|
965
|
+
const probe = await connectMcp(endpoint, headers, 15e3);
|
|
658
966
|
const tools = await probe.listTools();
|
|
659
967
|
send(res, 200, {
|
|
660
968
|
ok: true,
|
|
661
|
-
protocolVersion:
|
|
662
|
-
|
|
663
|
-
|
|
969
|
+
protocolVersion: probe.protocolVersion ?? null,
|
|
970
|
+
transport: probe.transport,
|
|
971
|
+
server: probe.serverInfo?.name ?? null,
|
|
972
|
+
version: probe.serverInfo?.version ?? null,
|
|
664
973
|
tools: tools.map((tool) => ({ name: tool.name, description: tool.description ?? "", folder: tool._meta?.["dsh/folder"] ?? null }))
|
|
665
974
|
});
|
|
666
975
|
} catch (error) {
|
|
@@ -680,13 +989,11 @@ async function apply(ctx, config = {}) {
|
|
|
680
989
|
return;
|
|
681
990
|
}
|
|
682
991
|
const body = await readBody(req);
|
|
992
|
+
const servers = Array.isArray(body.servers) ? body.servers : void 0;
|
|
993
|
+
if (servers === void 0) throw new Error("body.servers must be an array");
|
|
683
994
|
const { editor, entry } = findEntry();
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
if (body.headers !== null && typeof body.headers === "object") next.headers = body.headers;
|
|
687
|
-
if (typeof body.toolCallTimeoutMs === "number") next.toolCallTimeoutMs = body.toolCallTimeoutMs;
|
|
688
|
-
await editor.edit(entry, (current) => ({ ...current, ...next }));
|
|
689
|
-
beacon("config-saved");
|
|
995
|
+
await editor.edit(entry, (current) => ({ ...current, servers }));
|
|
996
|
+
beacon("config-saved servers=" + servers.length);
|
|
690
997
|
send(res, 200, { ok: true });
|
|
691
998
|
} catch (error) {
|
|
692
999
|
beacon("config-save-error " + String(error));
|
|
@@ -706,14 +1013,21 @@ async function apply(ctx, config = {}) {
|
|
|
706
1013
|
return;
|
|
707
1014
|
}
|
|
708
1015
|
const body = await readBody(req);
|
|
709
|
-
const
|
|
1016
|
+
const server = typeof body.server === "string" && body.server !== "" ? body.server : "general";
|
|
710
1017
|
const tools = {
|
|
711
1018
|
disabled: Array.isArray(body.disabled) ? body.disabled.filter((v) => typeof v === "string") : [],
|
|
712
1019
|
hidden: Array.isArray(body.hidden) ? body.hidden.filter((v) => typeof v === "string") : [],
|
|
713
1020
|
overrides: body.overrides !== null && typeof body.overrides === "object" ? body.overrides : {}
|
|
714
1021
|
};
|
|
715
|
-
|
|
716
|
-
|
|
1022
|
+
const { editor, entry } = findEntry();
|
|
1023
|
+
await editor.edit(entry, (current) => {
|
|
1024
|
+
const list = Array.isArray(current.servers) && current.servers.length > 0 ? current.servers.map((item) => ({ ...item })) : [{ name: current.serverName ?? "general", endpoint: current.endpoint ?? "", headers: current.headers ?? {} }];
|
|
1025
|
+
const index = list.findIndex((item) => (item.name ?? "general") === server);
|
|
1026
|
+
if (index >= 0) list[index] = { ...list[index], tools };
|
|
1027
|
+
else list.push({ name: server, endpoint: "", tools });
|
|
1028
|
+
return { ...current, servers: list };
|
|
1029
|
+
});
|
|
1030
|
+
beacon("tools-saved " + server);
|
|
717
1031
|
send(res, 200, { ok: true });
|
|
718
1032
|
} catch (error) {
|
|
719
1033
|
beacon("tools-save-error " + String(error));
|
|
@@ -727,79 +1041,74 @@ async function apply(ctx, config = {}) {
|
|
|
727
1041
|
beacon("host-route-error " + String(error));
|
|
728
1042
|
}
|
|
729
1043
|
};
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
}
|
|
734
|
-
|
|
1044
|
+
try {
|
|
1045
|
+
if (typeof ctx.inject === "function") {
|
|
1046
|
+
ctx.inject(["webServer"], (sub) => install(sub));
|
|
1047
|
+
} else {
|
|
1048
|
+
install(ctx);
|
|
735
1049
|
}
|
|
736
|
-
}
|
|
737
|
-
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
beacon("host-inject-failed " + String(error));
|
|
738
1052
|
try {
|
|
739
|
-
ctx
|
|
740
|
-
} catch
|
|
741
|
-
beacon("host-inject-failed " + String(error));
|
|
742
|
-
startRoutes(ctx);
|
|
1053
|
+
install(ctx);
|
|
1054
|
+
} catch {
|
|
743
1055
|
}
|
|
744
|
-
} else {
|
|
745
|
-
startRoutes(ctx);
|
|
746
1056
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
}).catch((error) => {
|
|
759
|
-
const current = state();
|
|
760
|
-
current.lastError = String(error?.message ?? error);
|
|
761
|
-
current.version += 1;
|
|
1057
|
+
ctx.effect?.(() => () => {
|
|
1058
|
+
for (const entry of state().servers.values()) {
|
|
1059
|
+
if (entry.retryTimer !== void 0) clearInterval(entry.retryTimer);
|
|
1060
|
+
for (const dispose of entry.tools.values()) {
|
|
1061
|
+
try {
|
|
1062
|
+
dispose();
|
|
1063
|
+
} catch {
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
entry.tools.clear();
|
|
1067
|
+
}
|
|
762
1068
|
});
|
|
763
|
-
|
|
764
|
-
|
|
1069
|
+
shared.__GENMCP_STARTED__ = startedAt;
|
|
1070
|
+
}
|
|
1071
|
+
function registerStatusTool(ctx) {
|
|
1072
|
+
const live = state();
|
|
1073
|
+
const startedAt = state() && (shared.__GENMCP_STARTED__ ?? (/* @__PURE__ */ new Date()).toISOString());
|
|
1074
|
+
const dispose = ctx.tools.register({
|
|
765
1075
|
name: "general_mcp_status",
|
|
766
|
-
description: "Report
|
|
1076
|
+
description: "Report every configured MCP gateway and its connection status.",
|
|
767
1077
|
parameters: { type: "object", properties: {}, additionalProperties: false },
|
|
768
1078
|
output: {
|
|
769
1079
|
schema: {
|
|
770
1080
|
type: "object",
|
|
771
1081
|
properties: {
|
|
772
1082
|
ok: { type: "boolean" },
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
connected: { type: "boolean" },
|
|
776
|
-
toolCount: { type: "number" },
|
|
777
|
-
lastError: { type: "string" },
|
|
778
|
-
startedAt: { type: "string" }
|
|
1083
|
+
startedAt: { type: "string" },
|
|
1084
|
+
servers: { type: "array", items: { type: "object" } }
|
|
779
1085
|
},
|
|
780
|
-
required: ["ok", "
|
|
1086
|
+
required: ["ok", "startedAt", "servers"],
|
|
781
1087
|
additionalProperties: false
|
|
782
1088
|
},
|
|
783
1089
|
render(_args, value) {
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
text: "general-mcp: " + value.serverName + " endpoint=" + (value.endpoint === "" ? "(unset)" : value.endpoint) + " connected=" + value.connected + " tools=" + value.toolCount + (value.lastError === "" ? "" : " error=" + value.lastError)
|
|
787
|
-
}];
|
|
1090
|
+
const lines = (value.servers ?? []).map((item) => item.name + ": " + (item.connected ? "connected" : "idle") + " tools=" + item.toolCount + (item.lastError === "" ? "" : " error=" + item.lastError));
|
|
1091
|
+
return [{ type: "text", text: "general-mcp" + (lines.length === 0 ? " (no gateways)" : "\n" + lines.join("\n")) }];
|
|
788
1092
|
}
|
|
789
1093
|
},
|
|
790
1094
|
async execute() {
|
|
1095
|
+
const servers = [...live.servers.values()].map((entry) => ({
|
|
1096
|
+
name: entry.name,
|
|
1097
|
+
endpoint: entry.endpoint,
|
|
1098
|
+
connected: entry.connected,
|
|
1099
|
+
toolCount: entry.toolCount,
|
|
1100
|
+
lastError: entry.lastError,
|
|
1101
|
+
disabled: entry.settings.disabled ?? [],
|
|
1102
|
+
hidden: entry.settings.hidden ?? []
|
|
1103
|
+
}));
|
|
791
1104
|
return {
|
|
792
|
-
ok:
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
connected: live.connected,
|
|
796
|
-
toolCount: live.toolCount,
|
|
797
|
-
lastError: live.lastError,
|
|
798
|
-
startedAt
|
|
1105
|
+
ok: servers.length > 0 && servers.every((item) => item.connected || item.endpoint === ""),
|
|
1106
|
+
startedAt: shared.__GENMCP_STARTED__ ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1107
|
+
servers
|
|
799
1108
|
};
|
|
800
1109
|
}
|
|
801
1110
|
});
|
|
802
|
-
ctx.effect(() => () =>
|
|
1111
|
+
ctx.effect?.(() => () => dispose());
|
|
803
1112
|
}
|
|
804
1113
|
export {
|
|
805
1114
|
apply,
|