@momeidejiyi/dsh-general-mcp 0.1.4 → 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 CHANGED
@@ -1,4 +1,4 @@
1
- // @momeidejiyi/dsh-general-mcp@0.1.4 (generated)
1
+ // @momeidejiyi/dsh-general-mcp@0.1.6 (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,6 +113,7 @@ function buildCatalog(serverName, tools, publicName, settings = {}) {
112
113
  }
113
114
 
114
115
  // packages/general-mcp/src/client.ts
116
+ var CLIENT_VERSION = "0.1.6";
115
117
  var MODERN = "2026-07-28";
116
118
  var LEGACY = "2025-06-18";
117
119
  var META_VERSION = "io.modelcontextprotocol/protocolVersion";
@@ -141,7 +143,7 @@ var McpClient = class {
141
143
  const result = await this.request("initialize", {
142
144
  protocolVersion: LEGACY,
143
145
  capabilities: {},
144
- clientInfo: { name: "dsh-general-mcp", version: "0.1.1" }
146
+ clientInfo: { name: "dsh-general-mcp", version: CLIENT_VERSION }
145
147
  });
146
148
  if (typeof result?.protocolVersion === "string") this.protocolVersion = result.protocolVersion;
147
149
  await this.notify("notifications/initialized", {});
@@ -213,7 +215,7 @@ var McpClient = class {
213
215
  jsonrpc: "2.0",
214
216
  id,
215
217
  method,
216
- params: era === "modern" ? { ...params, _meta: { ...params?._meta, [META_VERSION]: MODERN, [META_CLIENT]: { name: "dsh-general-mcp", version: "0.1.1" }, [META_CAPS]: {} } } : params
218
+ params: era === "modern" ? { ...params, _meta: { ...params?._meta, [META_VERSION]: MODERN, [META_CLIENT]: { name: "dsh-general-mcp", version: CLIENT_VERSION }, [META_CAPS]: {} } } : params
217
219
  };
218
220
  let response = await this.send(body, signal, method, era, toolName);
219
221
  if (response.status === 404 && this.sessionId !== void 0 && method !== "initialize") {
@@ -320,6 +322,248 @@ async function readSseResult(response, id) {
320
322
  throw new Error("no JSON-RPC response with the request id in the SSE stream");
321
323
  }
322
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
+
323
567
  // packages/general-mcp/src/naming.ts
324
568
  var MAX_LENGTH = 64;
325
569
  function sanitize(value) {
@@ -411,146 +655,214 @@ function createToolDefinition(serverName, tool, client) {
411
655
  // packages/general-mcp/src/index.ts
412
656
  var name = "general-mcp";
413
657
  var inject = ["tools"];
658
+ var NAME_PATTERN2 = /^[A-Za-z0-9_-]{1,32}$/;
414
659
  var shared = globalThis;
415
- function normalizeConfig(config) {
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) {
416
674
  const live = state();
417
- const raw = config ?? {};
418
- const endpoint = typeof raw.endpoint === "string" ? raw.endpoint.trim() : "";
419
- if (endpoint !== "" && !/^https?:\/\//i.test(endpoint)) {
420
- throw new Error("endpoint must be an http(s) URL");
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 {
421
698
  }
422
- live.endpoint = endpoint;
423
- live.serverName = typeof raw.serverName === "string" && raw.serverName !== "" ? raw.serverName : "general";
424
- const headers = {};
425
- if (raw.headers !== null && typeof raw.headers === "object" && !Array.isArray(raw.headers)) {
426
- for (const [key, value] of Object.entries(raw.headers)) {
427
- if (typeof value === "string") headers[key] = value;
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;
428
706
  }
429
707
  }
430
- live.headers = headers;
431
- const timeout = typeof raw.toolCallTimeoutMs === "number" && Number.isFinite(raw.toolCallTimeoutMs) ? Math.min(Math.max(Math.round(raw.toolCallTimeoutMs), 1e3), 6e5) : 6e4;
432
- live.timeoutMs = timeout;
433
- live.debug = raw.debug === true;
434
- const tools = raw.tools ?? {};
435
- live.toolSettings = {
708
+ return {
436
709
  disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item) => typeof item === "string") : [],
437
710
  hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item) => typeof item === "string") : [],
438
- overrides: tools.overrides !== null && typeof tools.overrides === "object" ? tools.overrides : {}
711
+ overrides
439
712
  };
440
713
  }
441
- function state() {
442
- shared.__GENMCP_STATE__ ??= {
443
- serverName: "general",
444
- endpoint: "",
445
- headers: {},
446
- timeoutMs: 6e4,
447
- debug: false,
448
- connected: false,
449
- toolCount: 0,
450
- lastError: "",
451
- catalog: [],
452
- toolSettings: {},
453
- version: 0,
454
- token: crypto.randomUUID(),
455
- tools: /* @__PURE__ */ new Map(),
456
- attempts: 0
457
- };
458
- return shared.__GENMCP_STATE__;
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;
459
737
  }
460
- async function apply(ctx, config = {}) {
461
- normalizeConfig(config);
738
+ function apply(ctx, config) {
462
739
  const live = state();
463
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
464
- const beacon = (stage) => {
465
- if (live.debug !== true) return;
466
- try {
467
- appendFileSync(join(tmpdir(), "dsh-general-mcp-debug.log"), (/* @__PURE__ */ new Date()).toISOString() + " " + stage + "\n");
468
- } catch {
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
+ }
469
757
  }
470
- };
471
- const disposeTools = () => {
472
- for (const [key, dispose] of live.tools) {
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()) {
473
792
  try {
474
793
  dispose();
475
794
  } catch {
476
795
  }
477
- live.tools.delete(key);
478
796
  }
797
+ entry.tools.clear();
798
+ entry.toolCount = 0;
479
799
  };
480
- const stopRetry = () => {
481
- if (live.retryTimer !== void 0) clearInterval(live.retryTimer);
482
- live.retryTimer = void 0;
483
- };
484
- const registerTools = (tools, client) => {
485
- const disabled = new Set(live.toolSettings.disabled ?? []);
486
- const hidden = new Set(live.toolSettings.hidden ?? []);
487
- disposeTools();
800
+ const registerTools = (entry, tools, client) => {
801
+ const settings = entry.settings;
488
802
  for (const tool of tools) {
489
- if (hidden.has(tool.name) || disabled.has(tool.name)) continue;
803
+ if (settings.disabled?.includes(tool.name) === true) continue;
490
804
  const invalid = validateTool(tool);
491
- if (invalid !== void 0) {
492
- ctx.logger?.warn?.("general-mcp: rejected tool " + tool.name + " (" + invalid.code + "): " + invalid.message);
493
- continue;
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));
494
811
  }
495
- const definition = createToolDefinition(live.serverName, tool, client);
496
- const dispose = ctx.tools.register(definition);
497
- live.tools.set(definition.name, dispose);
498
812
  }
499
813
  };
500
- const sync = () => {
501
- if (live.sync !== void 0) return live.sync;
814
+ const sync = (entry) => {
815
+ if (entry.sync !== void 0) return entry.sync;
502
816
  const run = (async () => {
503
- if (live.endpoint === "") {
504
- disposeTools();
505
- live.connected = false;
506
- live.toolCount = 0;
507
- live.catalog = [];
508
- live.lastError = "";
509
- live.version += 1;
510
- return false;
511
- }
512
- 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);
513
819
  try {
514
- await client.initialize();
515
820
  const tools = await client.listTools();
516
- registerTools(tools, client);
517
- live.connected = true;
518
- live.toolCount = live.tools.size;
519
- live.catalog = buildCatalog(live.serverName, tools, (raw) => publicToolName(live.serverName, raw), live.toolSettings);
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;
520
828
  live.version += 1;
521
- live.lastError = "";
522
- live.attempts = 0;
523
- beacon("discovered " + tools.length + " version=" + live.version);
829
+ beacon("discovered " + entry.name + " tools=" + tools.length);
524
830
  return true;
525
831
  } catch (error) {
526
- live.connected = false;
527
- live.lastError = String(error?.message ?? error);
832
+ entry.connected = false;
833
+ entry.lastError = String(error?.message ?? error);
528
834
  live.version += 1;
529
- ctx.logger?.warn?.("general-mcp: " + live.lastError);
530
- beacon("discover-error " + live.lastError);
835
+ ctx.logger?.warn?.("general-mcp(" + entry.name + "): " + entry.lastError);
836
+ beacon("discover-error " + entry.name + " " + entry.lastError);
531
837
  return false;
532
838
  } finally {
533
- live.sync = void 0;
839
+ entry.sync = void 0;
534
840
  }
535
841
  })();
536
- live.sync = run;
842
+ entry.sync = run;
537
843
  return run;
538
844
  };
539
- const scheduleRetry = () => {
540
- if (live.retryTimer !== void 0) return;
541
- live.retryTimer = setInterval(() => {
542
- live.attempts += 1;
543
- void sync().then((ok) => {
544
- if (ok || live.attempts >= 20) stopRetry();
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);
545
857
  });
546
858
  }, 3e4);
547
859
  };
548
- ctx.effect(() => () => {
549
- stopRetry();
550
- disposeTools();
551
- });
552
- beacon("host-apply " + live.serverName);
553
- const installRoutes = (webCtx) => {
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) => {
554
866
  const webServer = webCtx?.webServer ?? webCtx?.get?.("webServer");
555
867
  if (webServer === void 0 || typeof webServer.register !== "function") {
556
868
  beacon("host-no-webserver");
@@ -561,8 +873,7 @@ async function apply(ctx, config = {}) {
561
873
  installed.set(webServer, true);
562
874
  const sameOrigin = (req) => {
563
875
  const headers = req.headers ?? {};
564
- const site = headers["sec-fetch-site"];
565
- if (site === "same-origin") return true;
876
+ if (headers["sec-fetch-site"] === "same-origin") return true;
566
877
  const origin = headers.origin;
567
878
  const host = headers.host;
568
879
  if (typeof origin !== "string" || typeof host !== "string" || origin === "") return false;
@@ -585,17 +896,13 @@ async function apply(ctx, config = {}) {
585
896
  let size = 0;
586
897
  req.on("data", (chunk) => {
587
898
  size += chunk.length;
588
- if (size > limit) {
589
- reject(new Error("request body too large"));
590
- req.destroy();
591
- return;
592
- }
593
- chunks.push(chunk);
899
+ if (size > limit) reject(new Error("body too large"));
900
+ else chunks.push(chunk);
594
901
  });
595
902
  req.on("end", () => {
596
903
  try {
597
904
  resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"));
598
- } catch (error) {
905
+ } catch {
599
906
  reject(new Error("invalid JSON body"));
600
907
  }
601
908
  });
@@ -614,8 +921,8 @@ async function apply(ctx, config = {}) {
614
921
  resource: async (request) => {
615
922
  const headers = request.headers;
616
923
  const bearer = headers?.get?.("authorization") === "Bearer " + live.token;
617
- const sameOrigin2 = headers?.get?.("sec-fetch-site") === "same-origin";
618
- if (!bearer && !sameOrigin2) {
924
+ const origin = headers?.get?.("sec-fetch-site") === "same-origin";
925
+ if (!bearer && !origin) {
619
926
  return new Response("unauthorized", { status: 401, headers: { "cache-control": "no-store" } });
620
927
  }
621
928
  const url = new URL(request.url);
@@ -624,12 +931,15 @@ async function apply(ctx, config = {}) {
624
931
  if (since === live.version) return new Response(null, { status: 304, headers: { "cache-control": "no-store" } });
625
932
  return new Response(JSON.stringify({
626
933
  version: live.version,
627
- server: live.serverName,
628
- status: live.connected ? "connected" : "idle",
629
- endpoint: live.endpoint,
630
- lastError: live.lastError,
631
- tools: live.catalog,
632
- overrides: live.toolSettings
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
+ }))
633
943
  }), { status: 200, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
634
944
  }
635
945
  });
@@ -652,14 +962,14 @@ async function apply(ctx, config = {}) {
652
962
  if (typeof value === "string") headers[key] = value;
653
963
  }
654
964
  }
655
- const probe = new McpClient(endpoint, headers, 15e3);
656
- const info = await probe.initialize();
965
+ const probe = await connectMcp(endpoint, headers, 15e3);
657
966
  const tools = await probe.listTools();
658
967
  send(res, 200, {
659
968
  ok: true,
660
- protocolVersion: info?.protocolVersion ?? null,
661
- server: info?.serverInfo?.name ?? null,
662
- version: info?.serverInfo?.version ?? null,
969
+ protocolVersion: probe.protocolVersion ?? null,
970
+ transport: probe.transport,
971
+ server: probe.serverInfo?.name ?? null,
972
+ version: probe.serverInfo?.version ?? null,
663
973
  tools: tools.map((tool) => ({ name: tool.name, description: tool.description ?? "", folder: tool._meta?.["dsh/folder"] ?? null }))
664
974
  });
665
975
  } catch (error) {
@@ -679,13 +989,11 @@ async function apply(ctx, config = {}) {
679
989
  return;
680
990
  }
681
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");
682
994
  const { editor, entry } = findEntry();
683
- const next = {};
684
- if (typeof body.endpoint === "string") next.endpoint = body.endpoint.trim();
685
- if (body.headers !== null && typeof body.headers === "object") next.headers = body.headers;
686
- if (typeof body.toolCallTimeoutMs === "number") next.toolCallTimeoutMs = body.toolCallTimeoutMs;
687
- await editor.edit(entry, (current) => ({ ...current, ...next }));
688
- beacon("config-saved");
995
+ await editor.edit(entry, (current) => ({ ...current, servers }));
996
+ beacon("config-saved servers=" + servers.length);
689
997
  send(res, 200, { ok: true });
690
998
  } catch (error) {
691
999
  beacon("config-save-error " + String(error));
@@ -705,14 +1013,21 @@ async function apply(ctx, config = {}) {
705
1013
  return;
706
1014
  }
707
1015
  const body = await readBody(req);
708
- const { editor, entry } = findEntry();
1016
+ const server = typeof body.server === "string" && body.server !== "" ? body.server : "general";
709
1017
  const tools = {
710
1018
  disabled: Array.isArray(body.disabled) ? body.disabled.filter((v) => typeof v === "string") : [],
711
1019
  hidden: Array.isArray(body.hidden) ? body.hidden.filter((v) => typeof v === "string") : [],
712
1020
  overrides: body.overrides !== null && typeof body.overrides === "object" ? body.overrides : {}
713
1021
  };
714
- await editor.edit(entry, (current) => ({ ...current, tools }));
715
- beacon("tools-saved");
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);
716
1031
  send(res, 200, { ok: true });
717
1032
  } catch (error) {
718
1033
  beacon("tools-save-error " + String(error));
@@ -726,79 +1041,74 @@ async function apply(ctx, config = {}) {
726
1041
  beacon("host-route-error " + String(error));
727
1042
  }
728
1043
  };
729
- const startRoutes = (webCtx) => {
730
- try {
731
- installRoutes(webCtx);
732
- } catch (error) {
733
- beacon("host-route-failed " + String(error));
1044
+ try {
1045
+ if (typeof ctx.inject === "function") {
1046
+ ctx.inject(["webServer"], (sub) => install(sub));
1047
+ } else {
1048
+ install(ctx);
734
1049
  }
735
- };
736
- if (typeof ctx.inject === "function") {
1050
+ } catch (error) {
1051
+ beacon("host-inject-failed " + String(error));
737
1052
  try {
738
- ctx.inject(["webServer"], (sub) => startRoutes(sub));
739
- } catch (error) {
740
- beacon("host-inject-failed " + String(error));
741
- startRoutes(ctx);
1053
+ install(ctx);
1054
+ } catch {
742
1055
  }
743
- } else {
744
- startRoutes(ctx);
745
1056
  }
746
- const onInject = (table) => {
747
- table.push({
748
- kind: "global",
749
- name: "__GENMCP__",
750
- value: { token: live.token, server: live.serverName, catalogPath: "/api/general-mcp/catalog" }
751
- });
752
- };
753
- ctx.effect(() => ctx.on("webserver/index-inject", onInject));
754
- stopRetry();
755
- void sync().then((ok) => {
756
- if (!ok && state().endpoint !== "") scheduleRetry();
757
- }).catch((error) => {
758
- const current = state();
759
- current.lastError = String(error?.message ?? error);
760
- 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
+ }
761
1068
  });
762
- ctx.effect(() => () => stopRetry());
763
- const statusDispose = ctx.tools.register({
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({
764
1075
  name: "general_mcp_status",
765
- description: "Report the general-mcp gateway connection status.",
1076
+ description: "Report every configured MCP gateway and its connection status.",
766
1077
  parameters: { type: "object", properties: {}, additionalProperties: false },
767
1078
  output: {
768
1079
  schema: {
769
1080
  type: "object",
770
1081
  properties: {
771
1082
  ok: { type: "boolean" },
772
- serverName: { type: "string" },
773
- endpoint: { type: "string" },
774
- connected: { type: "boolean" },
775
- toolCount: { type: "number" },
776
- lastError: { type: "string" },
777
- startedAt: { type: "string" }
1083
+ startedAt: { type: "string" },
1084
+ servers: { type: "array", items: { type: "object" } }
778
1085
  },
779
- required: ["ok", "serverName", "endpoint", "connected", "toolCount", "lastError", "startedAt"],
1086
+ required: ["ok", "startedAt", "servers"],
780
1087
  additionalProperties: false
781
1088
  },
782
1089
  render(_args, value) {
783
- return [{
784
- type: "text",
785
- text: "general-mcp: " + value.serverName + " endpoint=" + (value.endpoint === "" ? "(unset)" : value.endpoint) + " connected=" + value.connected + " tools=" + value.toolCount + (value.lastError === "" ? "" : " error=" + value.lastError)
786
- }];
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")) }];
787
1092
  }
788
1093
  },
789
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
+ }));
790
1104
  return {
791
- ok: live.endpoint !== "" && live.lastError === "" && live.connected,
792
- serverName: live.serverName,
793
- endpoint: live.endpoint,
794
- connected: live.connected,
795
- toolCount: live.toolCount,
796
- lastError: live.lastError,
797
- startedAt
1105
+ ok: servers.length > 0 && servers.every((item) => item.connected || item.endpoint === ""),
1106
+ startedAt: shared.__GENMCP_STARTED__ ?? (/* @__PURE__ */ new Date()).toISOString(),
1107
+ servers
798
1108
  };
799
1109
  }
800
1110
  });
801
- ctx.effect(() => () => statusDispose());
1111
+ ctx.effect?.(() => () => dispose());
802
1112
  }
803
1113
  export {
804
1114
  apply,