@momeidejiyi/dsh-general-mcp 0.3.0 → 0.3.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 CHANGED
@@ -1,4 +1,4 @@
1
- // @momeidejiyi/dsh-general-mcp@0.3.0 (generated)
1
+ // @momeidejiyi/dsh-general-mcp@0.3.2 (generated)
2
2
 
3
3
  // packages/general-mcp/src/index.ts
4
4
  import { appendFileSync } from "node:fs";
@@ -108,14 +108,14 @@ function shortHash(value) {
108
108
  }
109
109
  function buildCatalog(serverName, tools, publicName, settings = {}) {
110
110
  const disabled = new Set(settings.disabled ?? []);
111
- const hidden = new Set(settings.hidden ?? []);
112
111
  const removed = new Set(settings.removed ?? []);
113
112
  return tools.map((tool) => {
114
113
  const override = settings.overrides?.[tool.name];
115
114
  const invalid = validateTool(tool);
116
115
  const warnings = toolWarnings(tool);
117
116
  const schema = inputSchemaOf(tool).schema;
118
- const folder = (override?.folder ?? folderFromMeta(tool) ?? folderFromName(tool.name)).map(slug).filter(Boolean);
117
+ const rawFolder = Array.isArray(override?.folder) ? override?.folder : folderFromMeta(tool) ?? folderFromName(tool.name);
118
+ const folder = (Array.isArray(rawFolder) ? rawFolder : []).map(slug).filter(Boolean);
119
119
  const leaf = slug(tool.name.split(/[./]/).pop() ?? tool.name) || "tool";
120
120
  const path = [...folder, leaf].join("/");
121
121
  const metaTitle = typeof tool._meta?.[CANONICAL_TITLE] === "string" ? String(tool._meta[CANONICAL_TITLE]).slice(0, MAX_TITLE) : void 0;
@@ -136,7 +136,6 @@ function buildCatalog(serverName, tools, publicName, settings = {}) {
136
136
  ...tool.outputSchema === void 0 ? {} : { outputSchema: tool.outputSchema },
137
137
  hash: shortHash(description + JSON.stringify(schema) + JSON.stringify(folder)),
138
138
  disabled: disabled.has(tool.name),
139
- hidden: hidden.has(tool.name),
140
139
  ...removed.has(tool.name) ? { removed: true } : {},
141
140
  ...invalid !== void 0 ? { invalid } : {},
142
141
  ...invalid === void 0 && warnings.length > 0 ? { warning: { code: warnings[0].code, message: warnings.map((item) => item.message).join("\uFF1B") } } : {}
@@ -235,7 +234,11 @@ var McpClient = class {
235
234
  const sessionId = this.sessionId;
236
235
  this.sessionId = void 0;
237
236
  try {
238
- await fetch(this.url, { method: "DELETE", headers: { "mcp-session-id": sessionId } });
237
+ await fetch(this.url, {
238
+ method: "DELETE",
239
+ headers: { "mcp-session-id": sessionId },
240
+ signal: AbortSignal.timeout(5e3)
241
+ });
239
242
  } catch {
240
243
  }
241
244
  }
@@ -368,7 +371,7 @@ function resolveMessageUrl(endpoint, sseUrl) {
368
371
  } catch {
369
372
  return endpoint;
370
373
  }
371
- if (target.origin !== sse.origin && isLocalHost(target.hostname)) {
374
+ if (target.origin !== sse.origin && isLocalHost(target.hostname) && !isLocalHost(sse.hostname)) {
372
375
  target.protocol = sse.protocol;
373
376
  target.hostname = sse.hostname;
374
377
  target.port = sse.port;
@@ -399,9 +402,17 @@ var SseClient = class {
399
402
  /** Open the stream and wait for the endpoint announcement. */
400
403
  connect() {
401
404
  if (this.connected !== void 0) return this.connected;
402
- this.connected = (async () => {
405
+ const attempt = (async () => {
403
406
  const headers = { accept: "text/event-stream", ...this.headers };
404
- const response = await fetch(this.url, { headers, signal: this.controller.signal });
407
+ const headerTimer = setTimeout(() => {
408
+ this.controller.abort(new Error("SSE connect timed out after " + this.timeoutMs + "ms (GET " + this.url + ")"));
409
+ }, this.timeoutMs);
410
+ let response;
411
+ try {
412
+ response = await fetch(this.url, { headers, signal: this.controller.signal });
413
+ } finally {
414
+ clearTimeout(headerTimer);
415
+ }
405
416
  if (!response.ok) throw new Error("SSE connect failed: HTTP " + response.status);
406
417
  if (response.body === null) throw new Error("SSE connect returned no body");
407
418
  this.reader = response.body.getReader();
@@ -413,6 +424,12 @@ var SseClient = class {
413
424
  await announced;
414
425
  if (this.messageUrl === void 0) throw new Error("SSE server did not announce an endpoint");
415
426
  })();
427
+ this.connected = attempt.catch(async (error) => {
428
+ this.connected = void 0;
429
+ await this.close().catch(() => {
430
+ });
431
+ throw error;
432
+ });
416
433
  return this.connected;
417
434
  }
418
435
  endpointWaiter;
@@ -494,10 +511,37 @@ var SseClient = class {
494
511
  waiter.reject(error);
495
512
  }
496
513
  }
497
- async request(method, params) {
514
+ /**
515
+ * POST one message. The POST itself needs its own deadline: a server that
516
+ * accepts the request and never answers would otherwise keep the caller (and
517
+ * the reply promise) pending forever, and the reply timer would reject with
518
+ * nobody listening.
519
+ */
520
+ async post(payload, signal) {
521
+ const controller = new AbortController();
522
+ const timer = setTimeout(() => {
523
+ controller.abort(new Error("SSE POST timed out after " + this.timeoutMs + "ms (POST " + this.messageUrl + ")"));
524
+ }, this.timeoutMs);
525
+ const forward = () => controller.abort(this.controller.signal.reason);
526
+ this.controller.signal.addEventListener("abort", forward, { once: true });
527
+ const forwardCaller = () => controller.abort(signal?.reason);
528
+ if (signal !== void 0) signal.addEventListener("abort", forwardCaller, { once: true });
529
+ try {
530
+ return await fetch(this.messageUrl, {
531
+ method: "POST",
532
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...this.headers },
533
+ body: JSON.stringify(payload),
534
+ signal: controller.signal
535
+ });
536
+ } finally {
537
+ clearTimeout(timer);
538
+ this.controller.signal.removeEventListener("abort", forward);
539
+ if (signal !== void 0) signal.removeEventListener("abort", forwardCaller);
540
+ }
541
+ }
542
+ async request(method, params, signal) {
498
543
  await this.connect();
499
544
  const id = this.nextId += 1;
500
- const body = JSON.stringify({ jsonrpc: "2.0", id, method, params });
501
545
  const reply = new Promise((resolve, reject) => {
502
546
  const timer = setTimeout(() => {
503
547
  this.pending.delete(id);
@@ -505,12 +549,19 @@ var SseClient = class {
505
549
  }, this.timeoutMs);
506
550
  this.pending.set(id, { resolve, reject, timer });
507
551
  });
508
- const response = await fetch(this.messageUrl, {
509
- method: "POST",
510
- headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...this.headers },
511
- body,
512
- signal: this.controller.signal
552
+ reply.catch(() => {
513
553
  });
554
+ let response;
555
+ try {
556
+ response = await this.post({ jsonrpc: "2.0", id, method, params }, signal);
557
+ } catch (error) {
558
+ const pending = this.pending.get(id);
559
+ if (pending !== void 0) {
560
+ clearTimeout(pending.timer);
561
+ this.pending.delete(id);
562
+ }
563
+ throw error;
564
+ }
514
565
  if (!response.ok) {
515
566
  const pending = this.pending.get(id);
516
567
  if (pending !== void 0) {
@@ -532,39 +583,47 @@ var SseClient = class {
532
583
  }
533
584
  async notify(method, params) {
534
585
  await this.connect();
535
- const response = await fetch(this.messageUrl, {
536
- method: "POST",
537
- headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...this.headers },
538
- body: JSON.stringify({ jsonrpc: "2.0", method, params }),
539
- signal: this.controller.signal
540
- });
586
+ const response = await this.post({ jsonrpc: "2.0", method, params });
541
587
  if (!response.ok) throw new Error("notify " + method + " failed: HTTP " + response.status);
542
588
  }
543
589
  async listTools() {
544
- const tools = [];
590
+ const collected = [];
591
+ const seenCursors = /* @__PURE__ */ new Set();
545
592
  let cursor;
546
593
  for (let page = 0; page < 100; page += 1) {
547
594
  const result = await this.request("tools/list", cursor === void 0 ? {} : { cursor });
548
595
  if (!Array.isArray(result?.tools)) throw new Error("tools/list returned no tools array");
549
- tools.push(...result.tools);
596
+ collected.push(...result.tools);
550
597
  const next = typeof result.nextCursor === "string" && result.nextCursor !== "" ? result.nextCursor : void 0;
551
- if (next === void 0 || tools.some((tool) => tool.name === "")) break;
598
+ if (next === void 0) {
599
+ cursor = void 0;
600
+ break;
601
+ }
602
+ if (seenCursors.has(next)) throw new Error("tools/list repeated cursor " + next);
603
+ seenCursors.add(next);
552
604
  cursor = next;
553
605
  }
554
- return tools;
606
+ if (cursor !== void 0) throw new Error("tools/list did not terminate within 100 pages");
607
+ const byName = /* @__PURE__ */ new Map();
608
+ for (const tool of collected) {
609
+ if (typeof tool?.name !== "string" || tool.name === "") continue;
610
+ byName.set(tool.name, tool);
611
+ }
612
+ return [...byName.values()];
555
613
  }
556
- async callTool(name2, args) {
557
- const result = await this.request("tools/call", { name: name2, arguments: args });
614
+ async callTool(name2, args, signal) {
615
+ const result = await this.request("tools/call", { name: name2, arguments: args }, signal);
558
616
  return result ?? {};
559
617
  }
560
618
  async close() {
619
+ if (this.closed === true) return;
561
620
  this.closed = true;
562
621
  this.failAll(new Error("SSE client closed"));
563
622
  this.controller.abort();
564
- try {
565
- await this.reader?.cancel();
566
- } catch {
567
- }
623
+ const reader = this.reader;
624
+ this.reader = void 0;
625
+ if (reader !== void 0) reader.cancel().catch(() => {
626
+ });
568
627
  }
569
628
  };
570
629
 
@@ -578,7 +637,14 @@ function looksLikeSse(url) {
578
637
  }
579
638
  async function viaStreamable(url, headers, timeoutMs) {
580
639
  const client = new McpClient(url, headers, timeoutMs);
581
- const info = await client.initialize();
640
+ let info;
641
+ try {
642
+ info = await client.initialize();
643
+ } catch (error) {
644
+ await client.close().catch(() => {
645
+ });
646
+ throw error;
647
+ }
582
648
  return {
583
649
  transport: "streamable",
584
650
  detail: "POST " + url,
@@ -593,7 +659,14 @@ async function viaStreamable(url, headers, timeoutMs) {
593
659
  }
594
660
  async function viaSse(url, headers, timeoutMs) {
595
661
  const client = new SseClient(url, headers, timeoutMs);
596
- const info = await client.initialize();
662
+ let info;
663
+ try {
664
+ info = await client.initialize();
665
+ } catch (error) {
666
+ await client.close().catch(() => {
667
+ });
668
+ throw error;
669
+ }
597
670
  return {
598
671
  transport: "sse",
599
672
  detail: "GET " + url + " \u2192 POST " + (client.messageEndpoint ?? "(pending)"),
@@ -602,7 +675,7 @@ async function viaSse(url, headers, timeoutMs) {
602
675
  async initialize() {
603
676
  },
604
677
  listTools: async () => await client.listTools(),
605
- callTool: (name2, args) => client.callTool(name2, args),
678
+ callTool: (name2, args, signal) => client.callTool(name2, args, signal),
606
679
  close: () => client.close()
607
680
  };
608
681
  }
@@ -633,6 +706,19 @@ function shortHash2(value) {
633
706
  }
634
707
  return hash.toString(16).padStart(8, "0");
635
708
  }
709
+ function uniqueToolName(base, rawName, used) {
710
+ if (!used.has(base)) return base;
711
+ const suffix = "_" + shortHash2(rawName + "\0" + base);
712
+ const trimmed = base.slice(0, MAX_LENGTH - suffix.length);
713
+ let candidate = trimmed + suffix;
714
+ let index = 1;
715
+ while (used.has(candidate)) {
716
+ const tail = suffix + String(index);
717
+ candidate = base.slice(0, MAX_LENGTH - tail.length) + tail;
718
+ index += 1;
719
+ }
720
+ return candidate;
721
+ }
636
722
  function publicToolName(serverName, rawName) {
637
723
  const base = "mcp__" + sanitize(serverName) + "__" + sanitize(rawName);
638
724
  if (base.length <= MAX_LENGTH) return base;
@@ -724,10 +810,13 @@ function state() {
724
810
  timeoutMs: 6e4,
725
811
  retryIntervalMs: 3e4,
726
812
  maxRetries: 20,
727
- pollIntervalMs: 15e3
813
+ pollIntervalMs: 15e3,
814
+ lastError: ""
728
815
  };
729
816
  }
730
- return shared.__GENMCP_STATE__;
817
+ const runtime = shared.__GENMCP_STATE__;
818
+ if (typeof runtime.lastError !== "string") runtime.lastError = "";
819
+ return runtime;
731
820
  }
732
821
  function serverState(name2) {
733
822
  const live = state();
@@ -763,12 +852,17 @@ function normalizeSettings(raw) {
763
852
  const overrides = {};
764
853
  if (tools.overrides !== null && typeof tools.overrides === "object" && !Array.isArray(tools.overrides)) {
765
854
  for (const [key, value] of Object.entries(tools.overrides)) {
766
- if (value !== null && typeof value === "object") overrides[key] = value;
855
+ if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
856
+ const cleaned = {};
857
+ if (typeof value.title === "string") cleaned.title = value.title;
858
+ if (Array.isArray(value.folder) && value.folder.every((item) => typeof item === "string")) cleaned.folder = value.folder;
859
+ if (Object.keys(cleaned).length > 0) overrides[key] = cleaned;
767
860
  }
768
861
  }
862
+ const disabled = Array.isArray(tools.disabled) ? tools.disabled.filter((item) => typeof item === "string") : [];
863
+ const legacyHidden = Array.isArray(tools.hidden) ? tools.hidden.filter((item) => typeof item === "string") : [];
769
864
  return {
770
- disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item) => typeof item === "string") : [],
771
- hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item) => typeof item === "string") : [],
865
+ disabled: [.../* @__PURE__ */ new Set([...disabled, ...legacyHidden])],
772
866
  removed: Array.isArray(tools.removed) ? tools.removed.filter((item) => typeof item === "string") : [],
773
867
  overrides
774
868
  };
@@ -802,8 +896,16 @@ function normalizeConfig(config) {
802
896
  }
803
897
  function apply(ctx, config) {
804
898
  const live = state();
805
- const servers = normalizeConfig(config);
806
- beacon("host-apply " + servers.map((item) => item.name).join(","));
899
+ let servers = [];
900
+ let configError = "";
901
+ try {
902
+ servers = normalizeConfig(config);
903
+ } catch (error) {
904
+ configError = String(error?.message ?? error);
905
+ servers = [];
906
+ }
907
+ live.lastError = configError;
908
+ beacon("host-apply " + servers.map((item) => item.name).join(",") + (configError === "" ? "" : " error=" + configError));
807
909
  const { disposeTools, registerTools, sync, scheduleRetry, stopRetry } = createRuntime(ctx);
808
910
  for (const [name2, entry] of live.servers) {
809
911
  if (servers.some((item) => item.name === name2)) continue;
@@ -832,7 +934,8 @@ function apply(ctx, config) {
832
934
  entry.enabled = enabled;
833
935
  entry.timeoutMs = serverTimeout;
834
936
  const nextSettings = normalizeSettings(item.tools);
835
- if (entry.sync !== void 0 && JSON.stringify(entry.settings) !== JSON.stringify(nextSettings)) entry.stale = true;
937
+ const settingsChanged = JSON.stringify(entry.settings) !== JSON.stringify(nextSettings);
938
+ if (entry.sync !== void 0 && settingsChanged) entry.stale = true;
836
939
  entry.settings = nextSettings;
837
940
  for (const raw of [...nextSettings.removed ?? [], ...nextSettings.disabled ?? []]) {
838
941
  const dispose = entry.tools.get(raw);
@@ -859,12 +962,28 @@ function apply(ctx, config) {
859
962
  live.version += 1;
860
963
  }
861
964
  if (entry.endpoint === "" || entry.enabled === false) {
965
+ const hadState = entry.connected || entry.catalog.length > 0;
862
966
  disposeTools(entry);
863
967
  stopRetry(entry);
968
+ entry.generation = (entry.generation ?? 0) + 1;
969
+ void entry.client?.close().catch(() => {
970
+ });
971
+ entry.client = void 0;
864
972
  entry.connected = false;
865
973
  entry.toolCount = 0;
866
974
  entry.catalog = [];
867
975
  entry.lastError = entry.enabled === false ? "" : entry.lastError;
976
+ if (hadState || settingsChanged) live.version += 1;
977
+ continue;
978
+ }
979
+ if (!changed && entry.connected && entry.client !== void 0 && entry.lastTools !== void 0) {
980
+ if (settingsChanged) {
981
+ disposeTools(entry);
982
+ entry.catalog = buildCatalog(entry.name, entry.lastTools, (raw) => entry.publicNames?.get(raw) ?? publicToolName(entry.name, raw), entry.settings);
983
+ registerTools(entry, entry.lastTools, entry.client);
984
+ entry.toolCount = entry.tools.size;
985
+ live.version += 1;
986
+ }
868
987
  continue;
869
988
  }
870
989
  void sync(entry).then((ok) => {
@@ -897,6 +1016,8 @@ function createRuntime(ctx) {
897
1016
  const invalid = validateTool(tool);
898
1017
  if (invalid !== void 0) continue;
899
1018
  const definition = createToolDefinition(entry.name, tool, client);
1019
+ const resolved = entry.publicNames?.get(tool.name);
1020
+ if (resolved !== void 0) definition.name = resolved;
900
1021
  try {
901
1022
  entry.tools.set(tool.name, ctx.tools.register(definition));
902
1023
  } catch (error) {
@@ -926,19 +1047,20 @@ function createRuntime(ctx) {
926
1047
  try {
927
1048
  const tools = await client.listTools();
928
1049
  if (!alive(entry) || (entry.generation ?? 0) !== generation) return false;
929
- const names = new Set(tools.map((tool) => tool.name));
930
- const keep = (list) => (list ?? []).filter((name2) => names.has(name2));
931
- entry.settings = {
932
- disabled: keep(entry.settings.disabled),
933
- hidden: keep(entry.settings.hidden),
934
- removed: keep(entry.settings.removed),
935
- overrides: Object.fromEntries(Object.entries(entry.settings.overrides ?? {}).filter(([name2]) => names.has(name2)))
936
- };
1050
+ const used = /* @__PURE__ */ new Set();
1051
+ const publicNames = /* @__PURE__ */ new Map();
1052
+ for (const tool of tools) {
1053
+ const resolved = uniqueToolName(publicToolName(entry.name, tool.name), tool.name, used);
1054
+ used.add(resolved);
1055
+ publicNames.set(tool.name, resolved);
1056
+ }
1057
+ entry.publicNames = publicNames;
1058
+ entry.lastTools = tools;
937
1059
  disposeTools(entry);
1060
+ entry.catalog = buildCatalog(entry.name, tools, (raw) => publicNames.get(raw) ?? publicToolName(entry.name, raw), entry.settings);
938
1061
  registerTools(entry, tools, client);
939
1062
  entry.connected = true;
940
1063
  entry.toolCount = entry.tools.size;
941
- entry.catalog = buildCatalog(entry.name, tools, (raw) => publicToolName(entry.name, raw), entry.settings);
942
1064
  entry.lastError = "";
943
1065
  entry.attempts = 0;
944
1066
  live.version += 1;
@@ -956,7 +1078,7 @@ function createRuntime(ctx) {
956
1078
  return false;
957
1079
  } finally {
958
1080
  entry.sync = void 0;
959
- if (entry.stale === true && alive(entry) && entry.endpoint !== "") {
1081
+ if (entry.stale === true && alive(entry) && entry.endpoint !== "" && entry.enabled !== false) {
960
1082
  entry.stale = false;
961
1083
  void sync(entry).then((ok) => {
962
1084
  if (!ok && alive(entry)) scheduleRetry(entry);
@@ -975,6 +1097,7 @@ function createRuntime(ctx) {
975
1097
  };
976
1098
  const scheduleRetry = (entry) => {
977
1099
  if (entry.retryTimer !== void 0) return;
1100
+ if (entry.disposed === true || entry.enabled === false || entry.endpoint === "") return;
978
1101
  entry.retryTimer = setInterval(() => {
979
1102
  entry.attempts += 1;
980
1103
  void sync(entry).then((ok) => {
@@ -996,6 +1119,12 @@ function installRoutes(ctx) {
996
1119
  const installed = shared.__GENMCP_ROUTES__ ??= /* @__PURE__ */ new WeakMap();
997
1120
  if (installed.get(webServer) === true) return;
998
1121
  installed.set(webServer, true);
1122
+ const routeDisposers = shared.__GENMCP_ROUTE_DISPOSERS__ ??= [];
1123
+ const route = (definition) => {
1124
+ const disposer = webServer.register(definition);
1125
+ if (typeof disposer === "function") routeDisposers.push(disposer);
1126
+ };
1127
+ shared.__GENMCP_WEBSERVER__ = webServer;
999
1128
  const trusted = (req) => {
1000
1129
  const headers = req.headers ?? {};
1001
1130
  if ((headers.authorization ?? "") === "Bearer " + live.token) return true;
@@ -1006,7 +1135,7 @@ function installRoutes(ctx) {
1006
1135
  const loopback = /^(127\.0\.0\.1|localhost|\[::1\])(:|$)/;
1007
1136
  try {
1008
1137
  const originHost = new URL(origin).host;
1009
- if (host !== "" && originHost === host) return true;
1138
+ if (host !== "" && originHost === host) return loopback.test(host);
1010
1139
  if (loopback.test(originHost) && loopback.test(host)) return true;
1011
1140
  } catch {
1012
1141
  }
@@ -1022,9 +1151,11 @@ function installRoutes(ctx) {
1022
1151
  "access-control-max-age": "600",
1023
1152
  vary: "origin"
1024
1153
  };
1025
- if (origin !== "") out["access-control-allow-origin"] = origin;
1154
+ if (origin !== "" && trusted({ headers })) out["access-control-allow-origin"] = origin;
1026
1155
  return out;
1027
1156
  };
1157
+ const httpError = (status, message) => Object.assign(new Error(message), { status });
1158
+ const statusOf = (error) => typeof error?.status === "number" ? error.status : 500;
1028
1159
  const send = (res, status, payload, extra = {}) => {
1029
1160
  res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...extra });
1030
1161
  res.end(JSON.stringify(payload));
@@ -1032,18 +1163,39 @@ function installRoutes(ctx) {
1032
1163
  const readBody = (req, limit = 256 * 1024) => new Promise((resolve, reject) => {
1033
1164
  const chunks = [];
1034
1165
  let size = 0;
1166
+ let settled = false;
1167
+ const fail = (error, destroy = false) => {
1168
+ if (settled) return;
1169
+ settled = true;
1170
+ chunks.length = 0;
1171
+ if (destroy) {
1172
+ try {
1173
+ req.destroy();
1174
+ } catch {
1175
+ }
1176
+ }
1177
+ reject(error);
1178
+ };
1035
1179
  req.on("data", (chunk) => {
1180
+ if (settled) return;
1036
1181
  size += chunk.length;
1037
- if (size > limit) reject(new Error("body too large"));
1038
- else chunks.push(chunk);
1182
+ if (size > limit) {
1183
+ fail(new Error("body too large"), true);
1184
+ return;
1185
+ }
1186
+ chunks.push(chunk);
1039
1187
  });
1040
1188
  req.on("end", () => {
1189
+ if (settled) return;
1190
+ settled = true;
1041
1191
  try {
1042
1192
  resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"));
1043
1193
  } catch {
1044
1194
  reject(new Error("invalid JSON body"));
1045
1195
  }
1046
1196
  });
1197
+ req.on("error", (error) => fail(error));
1198
+ req.on("aborted", () => fail(new Error("request aborted")));
1047
1199
  });
1048
1200
  const findEntry = () => {
1049
1201
  const editor = ctx.get?.("configEditor");
@@ -1053,28 +1205,20 @@ function installRoutes(ctx) {
1053
1205
  return { editor, entry };
1054
1206
  };
1055
1207
  try {
1056
- webServer.register({
1057
- kind: "exact",
1058
- path: "/api/general-mcp/catalog",
1059
- resource: async (request) => {
1060
- const hdr = {
1061
- authorization: request.headers?.get?.("authorization") ?? "",
1062
- origin: request.headers?.get?.("origin") ?? "",
1063
- host: request.headers?.get?.("host") ?? ""
1064
- };
1065
- const allowed = cors(hdr);
1066
- if (request.method === "OPTIONS") {
1067
- return new Response(null, { status: 204, headers: { ...allowed, "cache-control": "no-store" } });
1068
- }
1069
- if (!trusted(hdr)) {
1070
- return new Response("unauthorized", { status: 401, headers: { ...allowed, "cache-control": "no-store" } });
1071
- }
1072
- const url = new URL(request.url);
1073
- const raw = url.searchParams.get("since");
1074
- const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1;
1075
- if (since === live.version) return new Response(null, { status: 304, headers: { ...allowed, "cache-control": "no-store" } });
1076
- return new Response(JSON.stringify({
1208
+ const catalogPayload = (method, rawUrl, headers) => {
1209
+ const allowed = cors({ headers });
1210
+ if (method === "OPTIONS") return { status: 204, headers: { ...allowed }, body: void 0 };
1211
+ if (!trusted({ headers })) return { status: 401, headers: { ...allowed }, body: "unauthorized" };
1212
+ const url = new URL(rawUrl, "http://localhost");
1213
+ const raw = url.searchParams.get("since");
1214
+ const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1;
1215
+ if (since === live.version) return { status: 304, headers: { ...allowed }, body: void 0 };
1216
+ return {
1217
+ status: 200,
1218
+ headers: { ...allowed, "content-type": "application/json; charset=utf-8" },
1219
+ body: JSON.stringify({
1077
1220
  version: live.version,
1221
+ ...live.lastError === "" ? {} : { configError: live.lastError },
1078
1222
  timeoutMs: live.timeoutMs,
1079
1223
  retryIntervalMs: live.retryIntervalMs,
1080
1224
  maxRetries: live.maxRetries,
@@ -1093,10 +1237,33 @@ function installRoutes(ctx) {
1093
1237
  tools: entry.catalog,
1094
1238
  settings: entry.settings
1095
1239
  }))
1096
- }), { status: 200, headers: { ...allowed, "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
1240
+ })
1241
+ };
1242
+ };
1243
+ route({
1244
+ kind: "exact",
1245
+ path: "/api/general-mcp/catalog",
1246
+ handler: (req, res) => {
1247
+ if (req.method !== "GET" && req.method !== "HEAD" && req.method !== "OPTIONS") {
1248
+ res.writeHead(405, { allow: "GET, HEAD, OPTIONS", ...cors(req) });
1249
+ res.end();
1250
+ return;
1251
+ }
1252
+ const out = catalogPayload(
1253
+ req.method ?? "GET",
1254
+ req.url ?? "/",
1255
+ {
1256
+ authorization: String(req.headers?.authorization ?? ""),
1257
+ origin: String(req.headers?.origin ?? ""),
1258
+ host: String(req.headers?.host ?? "")
1259
+ }
1260
+ );
1261
+ res.writeHead(out.status, { "cache-control": "no-store", ...out.headers });
1262
+ if (out.body === void 0) res.end();
1263
+ else res.end(out.body);
1097
1264
  }
1098
1265
  });
1099
- webServer.register({
1266
+ route({
1100
1267
  kind: "exact",
1101
1268
  path: "/api/general-mcp/probe",
1102
1269
  handler: (req, res) => {
@@ -1107,7 +1274,13 @@ function installRoutes(ctx) {
1107
1274
  res.end();
1108
1275
  return;
1109
1276
  }
1277
+ if (req.method !== "POST" && req.method !== "OPTIONS") {
1278
+ res.writeHead(405, { allow: "POST, OPTIONS", ...cors(req) });
1279
+ res.end();
1280
+ return;
1281
+ }
1110
1282
  void (async () => {
1283
+ let probe;
1111
1284
  try {
1112
1285
  if (!authorized(req)) {
1113
1286
  send(res, 401, { ok: false, message: "unauthorized" });
@@ -1115,14 +1288,17 @@ function installRoutes(ctx) {
1115
1288
  }
1116
1289
  const body = await readBody(req);
1117
1290
  const endpoint = typeof body.endpoint === "string" ? body.endpoint.trim() : "";
1118
- if (!/^https?:\/\//i.test(endpoint)) throw new Error("endpoint must be an http(s) URL");
1291
+ if (!/^https?:\/\//i.test(endpoint)) {
1292
+ send(res, 400, { ok: false, message: "endpoint must be an http(s) URL" });
1293
+ return;
1294
+ }
1119
1295
  const headers = {};
1120
1296
  if (body.headers !== null && typeof body.headers === "object" && !Array.isArray(body.headers)) {
1121
1297
  for (const [key, value] of Object.entries(body.headers)) {
1122
1298
  if (typeof value === "string") headers[key] = value;
1123
1299
  }
1124
1300
  }
1125
- const probe = await connectMcp(endpoint, headers, 15e3);
1301
+ probe = await connectMcp(endpoint, headers, 15e3);
1126
1302
  const tools = await probe.listTools();
1127
1303
  send(res, 200, {
1128
1304
  ok: true,
@@ -1135,11 +1311,14 @@ function installRoutes(ctx) {
1135
1311
  });
1136
1312
  } catch (error) {
1137
1313
  send(res, 200, { ok: false, message: String(error?.message ?? error) });
1314
+ } finally {
1315
+ await probe?.close().catch(() => {
1316
+ });
1138
1317
  }
1139
1318
  })();
1140
1319
  }
1141
1320
  });
1142
- webServer.register({
1321
+ route({
1143
1322
  kind: "exact",
1144
1323
  path: "/api/general-mcp/config",
1145
1324
  handler: (req, res) => {
@@ -1150,6 +1329,11 @@ function installRoutes(ctx) {
1150
1329
  res.end();
1151
1330
  return;
1152
1331
  }
1332
+ if (req.method !== "POST" && req.method !== "OPTIONS") {
1333
+ res.writeHead(405, { allow: "POST, OPTIONS", ...cors(req) });
1334
+ res.end();
1335
+ return;
1336
+ }
1153
1337
  void (async () => {
1154
1338
  try {
1155
1339
  if (!authorized(req)) {
@@ -1163,11 +1347,19 @@ function installRoutes(ctx) {
1163
1347
  const seen = /* @__PURE__ */ new Set();
1164
1348
  for (const item of incoming) {
1165
1349
  const name2 = String(item.name ?? "general");
1166
- if (!/^[A-Za-z0-9_-]{1,32}$/.test(name2)) throw new Error('\u7F51\u5173\u540D "' + name2 + '" \u975E\u6CD5');
1167
- if (seen.has(name2)) throw new Error('\u7F51\u5173\u540D "' + name2 + '" \u91CD\u590D');
1350
+ if (!/^[A-Za-z0-9_-]{1,32}$/.test(name2)) throw httpError(400, '\u7F51\u5173\u540D "' + name2 + '" \u975E\u6CD5');
1351
+ if (seen.has(name2)) throw httpError(400, '\u7F51\u5173\u540D "' + name2 + '" \u91CD\u590D');
1168
1352
  const endpoint = item.endpoint;
1169
1353
  if (endpoint !== void 0 && endpoint !== null && endpoint !== "" && !/^https?:\/\//i.test(String(endpoint))) {
1170
- throw new Error('\u7F51\u5173 "' + name2 + '" \u7684\u5730\u5740\u5FC5\u987B\u4EE5 http(s):// \u5F00\u5934');
1354
+ throw httpError(400, '\u7F51\u5173 "' + name2 + '" \u7684\u5730\u5740\u5FC5\u987B\u4EE5 http(s):// \u5F00\u5934');
1355
+ }
1356
+ if (item.headers !== void 0 && item.headers !== null) {
1357
+ if (typeof item.headers !== "object" || Array.isArray(item.headers)) throw httpError(400, '\u7F51\u5173 "' + name2 + '" \u7684 headers \u5FC5\u987B\u662F\u5BF9\u8C61');
1358
+ for (const [key, value] of Object.entries(item.headers)) {
1359
+ if (typeof key !== "string" || key === "" || typeof value !== "string") {
1360
+ throw httpError(400, '\u7F51\u5173 "' + name2 + '" \u7684 headers \u503C\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\uFF08' + key + "\uFF09");
1361
+ }
1362
+ }
1171
1363
  }
1172
1364
  seen.add(name2);
1173
1365
  }
@@ -1180,12 +1372,12 @@ function installRoutes(ctx) {
1180
1372
  const name2 = String(item.name ?? "general");
1181
1373
  if (removed.has(name2)) continue;
1182
1374
  if (body.createOnly === true && byName.get(name2) !== void 0) {
1183
- throw new Error("\u7F51\u5173 " + name2 + " \u5DF2\u5B58\u5728");
1375
+ throw httpError(409, "\u7F51\u5173 " + name2 + " \u5DF2\u5B58\u5728");
1184
1376
  }
1185
1377
  const previous = byName.get(name2) ?? {};
1186
1378
  const hasEndpoint = typeof item.endpoint === "string";
1187
1379
  if (!hasEndpoint && byName.get(name2) === void 0) {
1188
- throw new Error("\u7F51\u5173 " + name2 + " \u4E0D\u5B58\u5728\uFF0C\u6539\u52A8\u672A\u4FDD\u5B58");
1380
+ throw httpError(404, "\u7F51\u5173 " + name2 + " \u4E0D\u5B58\u5728\uFF0C\u6539\u52A8\u672A\u4FDD\u5B58");
1189
1381
  }
1190
1382
  const endpoint2 = hasEndpoint ? item.endpoint.trim() : previous.endpoint ?? "";
1191
1383
  const sameEndpoint = (previous.endpoint ?? "") === endpoint2;
@@ -1225,12 +1417,12 @@ function installRoutes(ctx) {
1225
1417
  send(res, 200, { ok: true });
1226
1418
  } catch (error) {
1227
1419
  beacon("config-save-error " + String(error));
1228
- send(res, 500, { ok: false, message: String(error?.message ?? error) });
1420
+ send(res, statusOf(error), { ok: false, message: String(error?.message ?? error) });
1229
1421
  }
1230
1422
  })();
1231
1423
  }
1232
1424
  });
1233
- webServer.register({
1425
+ route({
1234
1426
  kind: "exact",
1235
1427
  path: "/api/general-mcp/tools",
1236
1428
  handler: (req, res) => {
@@ -1241,6 +1433,11 @@ function installRoutes(ctx) {
1241
1433
  res.end();
1242
1434
  return;
1243
1435
  }
1436
+ if (req.method !== "POST" && req.method !== "OPTIONS") {
1437
+ res.writeHead(405, { allow: "POST, OPTIONS", ...cors(req) });
1438
+ res.end();
1439
+ return;
1440
+ }
1244
1441
  void (async () => {
1245
1442
  try {
1246
1443
  if (!authorized(req)) {
@@ -1253,13 +1450,23 @@ function installRoutes(ctx) {
1253
1450
  await editor.edit(entry, (current) => {
1254
1451
  const list = Array.isArray(current.servers) ? current.servers.map((item) => ({ ...item })) : typeof current.endpoint === "string" && current.endpoint !== "" ? [{ name: current.serverName ?? "general", endpoint: current.endpoint, headers: current.headers ?? {}, tools: current.tools }] : [];
1255
1452
  const index = list.findIndex((item) => (item.name ?? "general") === server);
1256
- if (index < 0) throw new Error("\u7F51\u5173 " + server + " \u4E0D\u5B58\u5728\uFF0C\u5DE5\u5177\u8BBE\u7F6E\u672A\u4FDD\u5B58");
1453
+ if (index < 0) throw httpError(404, "\u7F51\u5173 " + server + " \u4E0D\u5B58\u5728\uFF0C\u5DE5\u5177\u8BBE\u7F6E\u672A\u4FDD\u5B58");
1257
1454
  const previous = list[index].tools ?? {};
1258
1455
  const next = { ...previous };
1259
1456
  if (Array.isArray(body.disabled)) next.disabled = body.disabled.filter((v) => typeof v === "string");
1260
- if (Array.isArray(body.hidden)) next.hidden = body.hidden.filter((v) => typeof v === "string");
1457
+ if (Array.isArray(body.hidden)) {
1458
+ const disabled = new Set(Array.isArray(next.disabled) ? next.disabled : []);
1459
+ for (const name2 of body.hidden.filter((v) => typeof v === "string")) disabled.add(name2);
1460
+ next.disabled = [...disabled];
1461
+ delete next.hidden;
1462
+ }
1261
1463
  if (Array.isArray(body.removed)) next.removed = body.removed.filter((v) => typeof v === "string");
1262
- if (body.overrides !== null && typeof body.overrides === "object" && !Array.isArray(body.overrides)) next.overrides = body.overrides;
1464
+ if (body.overrides !== void 0) {
1465
+ if (body.overrides === null || typeof body.overrides !== "object" || Array.isArray(body.overrides)) {
1466
+ throw httpError(400, "overrides \u5FC5\u987B\u662F\u4EE5\u5DE5\u5177\u540D\u4E3A\u952E\u7684\u5BF9\u8C61");
1467
+ }
1468
+ next.overrides = body.overrides;
1469
+ }
1263
1470
  list[index] = { ...list[index], tools: next };
1264
1471
  const { serverName, endpoint, headers, tools, ...rest } = current;
1265
1472
  return { ...rest, servers: list };
@@ -1268,7 +1475,7 @@ function installRoutes(ctx) {
1268
1475
  send(res, 200, { ok: true });
1269
1476
  } catch (error) {
1270
1477
  beacon("tools-save-error " + String(error));
1271
- send(res, 500, { ok: false, message: String(error?.message ?? error) });
1478
+ send(res, statusOf(error), { ok: false, message: String(error?.message ?? error) });
1272
1479
  }
1273
1480
  })();
1274
1481
  }
@@ -1292,8 +1499,11 @@ function installRoutes(ctx) {
1292
1499
  }
1293
1500
  }
1294
1501
  ctx.effect?.(() => () => {
1295
- for (const entry of state().servers.values()) {
1502
+ const live2 = state();
1503
+ for (const entry of live2.servers.values()) {
1504
+ entry.disposed = true;
1296
1505
  if (entry.retryTimer !== void 0) clearInterval(entry.retryTimer);
1506
+ entry.retryTimer = void 0;
1297
1507
  for (const dispose of entry.tools.values()) {
1298
1508
  try {
1299
1509
  dispose();
@@ -1301,11 +1511,33 @@ function installRoutes(ctx) {
1301
1511
  }
1302
1512
  }
1303
1513
  entry.tools.clear();
1514
+ void entry.client?.close().catch(() => {
1515
+ });
1516
+ entry.client = void 0;
1517
+ entry.sync = void 0;
1518
+ entry.connected = false;
1519
+ entry.toolCount = 0;
1520
+ entry.catalog = [];
1304
1521
  }
1522
+ live2.servers.clear();
1523
+ live2.version += 1;
1524
+ const disposers = shared.__GENMCP_ROUTE_DISPOSERS__;
1525
+ if (Array.isArray(disposers)) {
1526
+ for (const dispose of disposers.splice(0)) {
1527
+ try {
1528
+ dispose();
1529
+ } catch {
1530
+ }
1531
+ }
1532
+ }
1533
+ const webServer = shared.__GENMCP_WEBSERVER__;
1534
+ const installed = shared.__GENMCP_ROUTES__;
1535
+ if (webServer !== void 0 && installed instanceof WeakMap) installed.delete(webServer);
1305
1536
  });
1306
1537
  shared.__GENMCP_STARTED__ = startedAt;
1307
1538
  }
1308
1539
  function registerStatusTool(ctx) {
1540
+ if (shared.__GENMCP_STATUS_CTX__ === ctx && typeof shared.__GENMCP_STATUS_DISPOSE__ === "function") return;
1309
1541
  const live = state();
1310
1542
  const startedAt = state() && (shared.__GENMCP_STARTED__ ?? (/* @__PURE__ */ new Date()).toISOString());
1311
1543
  const dispose = ctx.tools.register({
@@ -1337,8 +1569,7 @@ function registerStatusTool(ctx) {
1337
1569
  timeoutMs: entry.timeoutMs,
1338
1570
  toolCount: entry.toolCount,
1339
1571
  lastError: entry.lastError,
1340
- disabled: entry.settings.disabled ?? [],
1341
- hidden: entry.settings.hidden ?? []
1572
+ disabled: entry.settings.disabled ?? []
1342
1573
  }));
1343
1574
  return {
1344
1575
  ok: servers.length > 0 && servers.every((item) => item.connected || item.endpoint === ""),
@@ -1347,10 +1578,20 @@ function registerStatusTool(ctx) {
1347
1578
  };
1348
1579
  }
1349
1580
  });
1350
- ctx.effect?.(() => () => dispose());
1581
+ shared.__GENMCP_STATUS_CTX__ = ctx;
1582
+ shared.__GENMCP_STATUS_DISPOSE__ = dispose;
1583
+ ctx.effect?.(() => () => {
1584
+ dispose();
1585
+ if (shared.__GENMCP_STATUS_DISPOSE__ === dispose) {
1586
+ shared.__GENMCP_STATUS_DISPOSE__ = void 0;
1587
+ shared.__GENMCP_STATUS_CTX__ = void 0;
1588
+ }
1589
+ });
1351
1590
  }
1352
1591
  export {
1592
+ SseClient,
1353
1593
  apply,
1354
1594
  inject,
1355
- name
1595
+ name,
1596
+ resolveMessageUrl
1356
1597
  };