@momeidejiyi/dsh-general-mcp 0.3.1 → 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.1 (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");
@@ -1066,6 +1218,7 @@ function installRoutes(ctx) {
1066
1218
  headers: { ...allowed, "content-type": "application/json; charset=utf-8" },
1067
1219
  body: JSON.stringify({
1068
1220
  version: live.version,
1221
+ ...live.lastError === "" ? {} : { configError: live.lastError },
1069
1222
  timeoutMs: live.timeoutMs,
1070
1223
  retryIntervalMs: live.retryIntervalMs,
1071
1224
  maxRetries: live.maxRetries,
@@ -1087,10 +1240,15 @@ function installRoutes(ctx) {
1087
1240
  })
1088
1241
  };
1089
1242
  };
1090
- webServer.register({
1243
+ route({
1091
1244
  kind: "exact",
1092
1245
  path: "/api/general-mcp/catalog",
1093
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
+ }
1094
1252
  const out = catalogPayload(
1095
1253
  req.method ?? "GET",
1096
1254
  req.url ?? "/",
@@ -1103,21 +1261,9 @@ function installRoutes(ctx) {
1103
1261
  res.writeHead(out.status, { "cache-control": "no-store", ...out.headers });
1104
1262
  if (out.body === void 0) res.end();
1105
1263
  else res.end(out.body);
1106
- },
1107
- resource: async (request) => {
1108
- const out = catalogPayload(
1109
- request.method,
1110
- request.url,
1111
- {
1112
- authorization: request.headers?.get?.("authorization") ?? "",
1113
- origin: request.headers?.get?.("origin") ?? "",
1114
- host: request.headers?.get?.("host") ?? ""
1115
- }
1116
- );
1117
- return new Response(out.body ?? null, { status: out.status, headers: { "cache-control": "no-store", ...out.headers } });
1118
1264
  }
1119
1265
  });
1120
- webServer.register({
1266
+ route({
1121
1267
  kind: "exact",
1122
1268
  path: "/api/general-mcp/probe",
1123
1269
  handler: (req, res) => {
@@ -1128,7 +1274,13 @@ function installRoutes(ctx) {
1128
1274
  res.end();
1129
1275
  return;
1130
1276
  }
1277
+ if (req.method !== "POST" && req.method !== "OPTIONS") {
1278
+ res.writeHead(405, { allow: "POST, OPTIONS", ...cors(req) });
1279
+ res.end();
1280
+ return;
1281
+ }
1131
1282
  void (async () => {
1283
+ let probe;
1132
1284
  try {
1133
1285
  if (!authorized(req)) {
1134
1286
  send(res, 401, { ok: false, message: "unauthorized" });
@@ -1136,14 +1288,17 @@ function installRoutes(ctx) {
1136
1288
  }
1137
1289
  const body = await readBody(req);
1138
1290
  const endpoint = typeof body.endpoint === "string" ? body.endpoint.trim() : "";
1139
- 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
+ }
1140
1295
  const headers = {};
1141
1296
  if (body.headers !== null && typeof body.headers === "object" && !Array.isArray(body.headers)) {
1142
1297
  for (const [key, value] of Object.entries(body.headers)) {
1143
1298
  if (typeof value === "string") headers[key] = value;
1144
1299
  }
1145
1300
  }
1146
- const probe = await connectMcp(endpoint, headers, 15e3);
1301
+ probe = await connectMcp(endpoint, headers, 15e3);
1147
1302
  const tools = await probe.listTools();
1148
1303
  send(res, 200, {
1149
1304
  ok: true,
@@ -1156,11 +1311,14 @@ function installRoutes(ctx) {
1156
1311
  });
1157
1312
  } catch (error) {
1158
1313
  send(res, 200, { ok: false, message: String(error?.message ?? error) });
1314
+ } finally {
1315
+ await probe?.close().catch(() => {
1316
+ });
1159
1317
  }
1160
1318
  })();
1161
1319
  }
1162
1320
  });
1163
- webServer.register({
1321
+ route({
1164
1322
  kind: "exact",
1165
1323
  path: "/api/general-mcp/config",
1166
1324
  handler: (req, res) => {
@@ -1171,6 +1329,11 @@ function installRoutes(ctx) {
1171
1329
  res.end();
1172
1330
  return;
1173
1331
  }
1332
+ if (req.method !== "POST" && req.method !== "OPTIONS") {
1333
+ res.writeHead(405, { allow: "POST, OPTIONS", ...cors(req) });
1334
+ res.end();
1335
+ return;
1336
+ }
1174
1337
  void (async () => {
1175
1338
  try {
1176
1339
  if (!authorized(req)) {
@@ -1184,11 +1347,19 @@ function installRoutes(ctx) {
1184
1347
  const seen = /* @__PURE__ */ new Set();
1185
1348
  for (const item of incoming) {
1186
1349
  const name2 = String(item.name ?? "general");
1187
- if (!/^[A-Za-z0-9_-]{1,32}$/.test(name2)) throw new Error('\u7F51\u5173\u540D "' + name2 + '" \u975E\u6CD5');
1188
- 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');
1189
1352
  const endpoint = item.endpoint;
1190
1353
  if (endpoint !== void 0 && endpoint !== null && endpoint !== "" && !/^https?:\/\//i.test(String(endpoint))) {
1191
- 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
+ }
1192
1363
  }
1193
1364
  seen.add(name2);
1194
1365
  }
@@ -1201,12 +1372,12 @@ function installRoutes(ctx) {
1201
1372
  const name2 = String(item.name ?? "general");
1202
1373
  if (removed.has(name2)) continue;
1203
1374
  if (body.createOnly === true && byName.get(name2) !== void 0) {
1204
- throw new Error("\u7F51\u5173 " + name2 + " \u5DF2\u5B58\u5728");
1375
+ throw httpError(409, "\u7F51\u5173 " + name2 + " \u5DF2\u5B58\u5728");
1205
1376
  }
1206
1377
  const previous = byName.get(name2) ?? {};
1207
1378
  const hasEndpoint = typeof item.endpoint === "string";
1208
1379
  if (!hasEndpoint && byName.get(name2) === void 0) {
1209
- 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");
1210
1381
  }
1211
1382
  const endpoint2 = hasEndpoint ? item.endpoint.trim() : previous.endpoint ?? "";
1212
1383
  const sameEndpoint = (previous.endpoint ?? "") === endpoint2;
@@ -1246,12 +1417,12 @@ function installRoutes(ctx) {
1246
1417
  send(res, 200, { ok: true });
1247
1418
  } catch (error) {
1248
1419
  beacon("config-save-error " + String(error));
1249
- send(res, 500, { ok: false, message: String(error?.message ?? error) });
1420
+ send(res, statusOf(error), { ok: false, message: String(error?.message ?? error) });
1250
1421
  }
1251
1422
  })();
1252
1423
  }
1253
1424
  });
1254
- webServer.register({
1425
+ route({
1255
1426
  kind: "exact",
1256
1427
  path: "/api/general-mcp/tools",
1257
1428
  handler: (req, res) => {
@@ -1262,6 +1433,11 @@ function installRoutes(ctx) {
1262
1433
  res.end();
1263
1434
  return;
1264
1435
  }
1436
+ if (req.method !== "POST" && req.method !== "OPTIONS") {
1437
+ res.writeHead(405, { allow: "POST, OPTIONS", ...cors(req) });
1438
+ res.end();
1439
+ return;
1440
+ }
1265
1441
  void (async () => {
1266
1442
  try {
1267
1443
  if (!authorized(req)) {
@@ -1274,13 +1450,23 @@ function installRoutes(ctx) {
1274
1450
  await editor.edit(entry, (current) => {
1275
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 }] : [];
1276
1452
  const index = list.findIndex((item) => (item.name ?? "general") === server);
1277
- 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");
1278
1454
  const previous = list[index].tools ?? {};
1279
1455
  const next = { ...previous };
1280
1456
  if (Array.isArray(body.disabled)) next.disabled = body.disabled.filter((v) => typeof v === "string");
1281
- 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
+ }
1282
1463
  if (Array.isArray(body.removed)) next.removed = body.removed.filter((v) => typeof v === "string");
1283
- 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
+ }
1284
1470
  list[index] = { ...list[index], tools: next };
1285
1471
  const { serverName, endpoint, headers, tools, ...rest } = current;
1286
1472
  return { ...rest, servers: list };
@@ -1289,7 +1475,7 @@ function installRoutes(ctx) {
1289
1475
  send(res, 200, { ok: true });
1290
1476
  } catch (error) {
1291
1477
  beacon("tools-save-error " + String(error));
1292
- send(res, 500, { ok: false, message: String(error?.message ?? error) });
1478
+ send(res, statusOf(error), { ok: false, message: String(error?.message ?? error) });
1293
1479
  }
1294
1480
  })();
1295
1481
  }
@@ -1313,8 +1499,11 @@ function installRoutes(ctx) {
1313
1499
  }
1314
1500
  }
1315
1501
  ctx.effect?.(() => () => {
1316
- for (const entry of state().servers.values()) {
1502
+ const live2 = state();
1503
+ for (const entry of live2.servers.values()) {
1504
+ entry.disposed = true;
1317
1505
  if (entry.retryTimer !== void 0) clearInterval(entry.retryTimer);
1506
+ entry.retryTimer = void 0;
1318
1507
  for (const dispose of entry.tools.values()) {
1319
1508
  try {
1320
1509
  dispose();
@@ -1322,11 +1511,33 @@ function installRoutes(ctx) {
1322
1511
  }
1323
1512
  }
1324
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 = [];
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
+ }
1325
1532
  }
1533
+ const webServer = shared.__GENMCP_WEBSERVER__;
1534
+ const installed = shared.__GENMCP_ROUTES__;
1535
+ if (webServer !== void 0 && installed instanceof WeakMap) installed.delete(webServer);
1326
1536
  });
1327
1537
  shared.__GENMCP_STARTED__ = startedAt;
1328
1538
  }
1329
1539
  function registerStatusTool(ctx) {
1540
+ if (shared.__GENMCP_STATUS_CTX__ === ctx && typeof shared.__GENMCP_STATUS_DISPOSE__ === "function") return;
1330
1541
  const live = state();
1331
1542
  const startedAt = state() && (shared.__GENMCP_STARTED__ ?? (/* @__PURE__ */ new Date()).toISOString());
1332
1543
  const dispose = ctx.tools.register({
@@ -1358,8 +1569,7 @@ function registerStatusTool(ctx) {
1358
1569
  timeoutMs: entry.timeoutMs,
1359
1570
  toolCount: entry.toolCount,
1360
1571
  lastError: entry.lastError,
1361
- disabled: entry.settings.disabled ?? [],
1362
- hidden: entry.settings.hidden ?? []
1572
+ disabled: entry.settings.disabled ?? []
1363
1573
  }));
1364
1574
  return {
1365
1575
  ok: servers.length > 0 && servers.every((item) => item.connected || item.endpoint === ""),
@@ -1368,10 +1578,20 @@ function registerStatusTool(ctx) {
1368
1578
  };
1369
1579
  }
1370
1580
  });
1371
- 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
+ });
1372
1590
  }
1373
1591
  export {
1592
+ SseClient,
1374
1593
  apply,
1375
1594
  inject,
1376
- name
1595
+ name,
1596
+ resolveMessageUrl
1377
1597
  };