@momeidejiyi/dsh-general-mcp 0.1.7 → 0.1.8
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 +187 -59
- package/package.json +1 -1
- package/src/catalog.ts +5 -0
- package/src/client.ts +10 -6
- package/src/connect.ts +5 -2
- package/src/index.ts +189 -50
- package/src/sse.ts +5 -3
package/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @momeidejiyi/dsh-general-mcp@0.1.
|
|
1
|
+
// @momeidejiyi/dsh-general-mcp@0.1.8 (generated)
|
|
2
2
|
|
|
3
3
|
// packages/general-mcp/src/index.ts
|
|
4
4
|
import { appendFileSync } from "node:fs";
|
|
@@ -81,6 +81,7 @@ function shortHash(value) {
|
|
|
81
81
|
function buildCatalog(serverName, tools, publicName, settings = {}) {
|
|
82
82
|
const disabled = new Set(settings.disabled ?? []);
|
|
83
83
|
const hidden = new Set(settings.hidden ?? []);
|
|
84
|
+
const removed = new Set(settings.removed ?? []);
|
|
84
85
|
return tools.map((tool) => {
|
|
85
86
|
const override = settings.overrides?.[tool.name];
|
|
86
87
|
const invalid = validateTool(tool);
|
|
@@ -106,6 +107,7 @@ function buildCatalog(serverName, tools, publicName, settings = {}) {
|
|
|
106
107
|
hash: shortHash(description + JSON.stringify(tool.inputSchema ?? null) + JSON.stringify(folder)),
|
|
107
108
|
disabled: disabled.has(tool.name),
|
|
108
109
|
hidden: hidden.has(tool.name),
|
|
110
|
+
...removed.has(tool.name) ? { removed: true } : {},
|
|
109
111
|
...invalid !== void 0 ? { invalid } : {},
|
|
110
112
|
...invalid === void 0 && alias !== void 0 ? { warning: alias } : {}
|
|
111
113
|
};
|
|
@@ -155,7 +157,8 @@ var McpClient = class {
|
|
|
155
157
|
const result = await this.request("server/discover", {}, void 0, MODERN);
|
|
156
158
|
if (result === void 0 || result === null) return void 0;
|
|
157
159
|
return result;
|
|
158
|
-
} catch {
|
|
160
|
+
} catch (error) {
|
|
161
|
+
if (/timed out/i.test(String(error?.message ?? ""))) throw error;
|
|
159
162
|
return void 0;
|
|
160
163
|
}
|
|
161
164
|
}
|
|
@@ -179,13 +182,12 @@ var McpClient = class {
|
|
|
179
182
|
cursor = next;
|
|
180
183
|
}
|
|
181
184
|
if (cursor !== void 0) throw new Error("tools/list did not terminate within 100 pages");
|
|
182
|
-
const
|
|
185
|
+
const byName = /* @__PURE__ */ new Map();
|
|
183
186
|
for (const tool of tools) {
|
|
184
|
-
if (typeof tool.name !== "string" || tool.name === "")
|
|
185
|
-
|
|
186
|
-
seen.add(tool.name);
|
|
187
|
+
if (typeof tool.name !== "string" || tool.name === "") continue;
|
|
188
|
+
byName.set(tool.name, tool);
|
|
187
189
|
}
|
|
188
|
-
return
|
|
190
|
+
return [...byName.values()];
|
|
189
191
|
}
|
|
190
192
|
async callTool(name2, args, signal) {
|
|
191
193
|
const result = await this.request("tools/call", { name: name2, arguments: args }, signal, void 0, name2);
|
|
@@ -366,7 +368,7 @@ var SseClient = class {
|
|
|
366
368
|
while (true) {
|
|
367
369
|
const chunk = await this.reader?.read();
|
|
368
370
|
if (chunk === void 0 || chunk.done === true) break;
|
|
369
|
-
buffer
|
|
371
|
+
buffer = (buffer + decoder.decode(chunk.value, { stream: true })).replace(/\r\n/g, "\n");
|
|
370
372
|
let index = buffer.indexOf("\n\n");
|
|
371
373
|
while (index >= 0) {
|
|
372
374
|
this.handleEvent(buffer.slice(0, index));
|
|
@@ -454,7 +456,7 @@ var SseClient = class {
|
|
|
454
456
|
});
|
|
455
457
|
const response = await fetch(this.messageUrl, {
|
|
456
458
|
method: "POST",
|
|
457
|
-
headers: { "content-type": "application/json", ...this.headers },
|
|
459
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...this.headers },
|
|
458
460
|
body,
|
|
459
461
|
signal: this.controller.signal
|
|
460
462
|
});
|
|
@@ -481,7 +483,7 @@ var SseClient = class {
|
|
|
481
483
|
await this.connect();
|
|
482
484
|
const response = await fetch(this.messageUrl, {
|
|
483
485
|
method: "POST",
|
|
484
|
-
headers: { "content-type": "application/json", ...this.headers },
|
|
486
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...this.headers },
|
|
485
487
|
body: JSON.stringify({ jsonrpc: "2.0", method, params }),
|
|
486
488
|
signal: this.controller.signal
|
|
487
489
|
});
|
|
@@ -552,7 +554,8 @@ async function viaSse(url, headers, timeoutMs) {
|
|
|
552
554
|
};
|
|
553
555
|
}
|
|
554
556
|
async function connectMcp(url, headers, timeoutMs) {
|
|
555
|
-
const
|
|
557
|
+
const probeMs = Math.min(timeoutMs, 8e3);
|
|
558
|
+
const order = looksLikeSse(url) ? [() => viaSse(url, headers, timeoutMs), () => viaStreamable(url, headers, probeMs)] : [() => viaStreamable(url, headers, probeMs), () => viaSse(url, headers, timeoutMs)];
|
|
556
559
|
const errors = [];
|
|
557
560
|
for (const attempt of order) {
|
|
558
561
|
try {
|
|
@@ -708,6 +711,7 @@ function normalizeSettings(raw) {
|
|
|
708
711
|
return {
|
|
709
712
|
disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item) => typeof item === "string") : [],
|
|
710
713
|
hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item) => typeof item === "string") : [],
|
|
714
|
+
removed: Array.isArray(tools.removed) ? tools.removed.filter((item) => typeof item === "string") : [],
|
|
711
715
|
overrides
|
|
712
716
|
};
|
|
713
717
|
}
|
|
@@ -717,7 +721,7 @@ function normalizeConfig(config) {
|
|
|
717
721
|
const timeout = typeof raw.toolCallTimeoutMs === "number" && Number.isFinite(raw.toolCallTimeoutMs) ? Math.min(Math.max(Math.round(raw.toolCallTimeoutMs), 1e3), 6e5) : 6e4;
|
|
718
722
|
live.timeoutMs = timeout;
|
|
719
723
|
live.debug = raw.debug === true;
|
|
720
|
-
const list = Array.isArray(raw.servers)
|
|
724
|
+
const list = Array.isArray(raw.servers) ? raw.servers.map((item) => ({ ...item })) : [{ name: raw.serverName, endpoint: raw.endpoint, headers: raw.headers, tools: raw.tools }];
|
|
721
725
|
const seen = /* @__PURE__ */ new Set();
|
|
722
726
|
const out = [];
|
|
723
727
|
for (const item of list) {
|
|
@@ -742,8 +746,12 @@ function apply(ctx, config) {
|
|
|
742
746
|
const { disposeTools, registerTools, sync, scheduleRetry, stopRetry } = createRuntime(ctx);
|
|
743
747
|
for (const [name2, entry] of live.servers) {
|
|
744
748
|
if (servers.some((item) => item.name === name2)) continue;
|
|
749
|
+
entry.disposed = true;
|
|
745
750
|
stopRetry(entry);
|
|
746
751
|
disposeTools(entry);
|
|
752
|
+
void entry.client?.close().catch(() => {
|
|
753
|
+
});
|
|
754
|
+
entry.client = void 0;
|
|
747
755
|
live.servers.delete(name2);
|
|
748
756
|
live.version += 1;
|
|
749
757
|
}
|
|
@@ -758,11 +766,29 @@ function apply(ctx, config) {
|
|
|
758
766
|
const changed = entry.endpoint !== (item.endpoint ?? "") || JSON.stringify(entry.headers) !== JSON.stringify(headers);
|
|
759
767
|
entry.endpoint = item.endpoint ?? "";
|
|
760
768
|
entry.headers = headers;
|
|
761
|
-
|
|
769
|
+
const nextSettings = normalizeSettings(item.tools);
|
|
770
|
+
if (entry.sync !== void 0 && JSON.stringify(entry.settings) !== JSON.stringify(nextSettings)) entry.stale = true;
|
|
771
|
+
entry.settings = nextSettings;
|
|
772
|
+
for (const raw of [...nextSettings.removed ?? [], ...nextSettings.disabled ?? []]) {
|
|
773
|
+
const dispose = entry.tools.get(raw);
|
|
774
|
+
if (dispose === void 0) continue;
|
|
775
|
+
try {
|
|
776
|
+
dispose();
|
|
777
|
+
} catch {
|
|
778
|
+
}
|
|
779
|
+
entry.tools.delete(raw);
|
|
780
|
+
}
|
|
781
|
+
entry.toolCount = entry.tools.size;
|
|
762
782
|
if (changed) {
|
|
783
|
+
entry.generation = (entry.generation ?? 0) + 1;
|
|
784
|
+
if (entry.sync !== void 0) entry.stale = true;
|
|
763
785
|
stopRetry(entry);
|
|
764
786
|
disposeTools(entry);
|
|
787
|
+
void entry.client?.close().catch(() => {
|
|
788
|
+
});
|
|
789
|
+
entry.client = void 0;
|
|
765
790
|
entry.connected = false;
|
|
791
|
+
entry.catalog = [];
|
|
766
792
|
entry.lastError = "";
|
|
767
793
|
entry.attempts = 0;
|
|
768
794
|
live.version += 1;
|
|
@@ -776,7 +802,7 @@ function apply(ctx, config) {
|
|
|
776
802
|
continue;
|
|
777
803
|
}
|
|
778
804
|
void sync(entry).then((ok) => {
|
|
779
|
-
if (!ok) scheduleRetry(entry);
|
|
805
|
+
if (!ok && entry.disposed !== true && live.servers.get(entry.name) === entry) scheduleRetry(entry);
|
|
780
806
|
}).catch((error) => {
|
|
781
807
|
entry.lastError = String(error?.message ?? error);
|
|
782
808
|
live.version += 1;
|
|
@@ -801,6 +827,7 @@ function createRuntime(ctx) {
|
|
|
801
827
|
const settings = entry.settings;
|
|
802
828
|
for (const tool of tools) {
|
|
803
829
|
if (settings.disabled?.includes(tool.name) === true) continue;
|
|
830
|
+
if (settings.removed?.includes(tool.name) === true) continue;
|
|
804
831
|
const invalid = validateTool(tool);
|
|
805
832
|
if (invalid !== void 0) continue;
|
|
806
833
|
const definition = createToolDefinition(entry.name, tool, client);
|
|
@@ -811,23 +838,47 @@ function createRuntime(ctx) {
|
|
|
811
838
|
}
|
|
812
839
|
}
|
|
813
840
|
};
|
|
841
|
+
const alive = (entry) => entry.disposed !== true && live.servers.get(entry.name) === entry;
|
|
814
842
|
const sync = (entry) => {
|
|
815
843
|
if (entry.sync !== void 0) return entry.sync;
|
|
816
844
|
const run = (async () => {
|
|
817
|
-
|
|
818
|
-
const client = await connectMcp(entry.endpoint, entry.headers, live.timeoutMs);
|
|
845
|
+
const generation = entry.generation ?? 0;
|
|
819
846
|
try {
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
847
|
+
if (entry.endpoint === "") return false;
|
|
848
|
+
const client = await connectMcp(entry.endpoint, entry.headers, live.timeoutMs);
|
|
849
|
+
if (!alive(entry) || (entry.generation ?? 0) !== generation) {
|
|
850
|
+
await client.close().catch(() => {
|
|
851
|
+
});
|
|
852
|
+
return false;
|
|
853
|
+
}
|
|
854
|
+
const previous = entry.client;
|
|
855
|
+
entry.client = client;
|
|
856
|
+
if (previous !== void 0 && previous !== client) void previous.close().catch(() => {
|
|
857
|
+
});
|
|
858
|
+
try {
|
|
859
|
+
const tools = await client.listTools();
|
|
860
|
+
if (!alive(entry) || (entry.generation ?? 0) !== generation) return false;
|
|
861
|
+
const names = new Set(tools.map((tool) => tool.name));
|
|
862
|
+
const keep = (list) => (list ?? []).filter((name2) => names.has(name2));
|
|
863
|
+
entry.settings = {
|
|
864
|
+
disabled: keep(entry.settings.disabled),
|
|
865
|
+
hidden: keep(entry.settings.hidden),
|
|
866
|
+
removed: keep(entry.settings.removed),
|
|
867
|
+
overrides: Object.fromEntries(Object.entries(entry.settings.overrides ?? {}).filter(([name2]) => names.has(name2)))
|
|
868
|
+
};
|
|
869
|
+
disposeTools(entry);
|
|
870
|
+
registerTools(entry, tools, client);
|
|
871
|
+
entry.connected = true;
|
|
872
|
+
entry.toolCount = entry.tools.size;
|
|
873
|
+
entry.catalog = buildCatalog(entry.name, tools, (raw) => publicToolName(entry.name, raw), entry.settings);
|
|
874
|
+
entry.lastError = "";
|
|
875
|
+
entry.attempts = 0;
|
|
876
|
+
live.version += 1;
|
|
877
|
+
beacon("discovered " + entry.name + " tools=" + tools.length);
|
|
878
|
+
return true;
|
|
879
|
+
} catch (error) {
|
|
880
|
+
throw error;
|
|
881
|
+
}
|
|
831
882
|
} catch (error) {
|
|
832
883
|
entry.connected = false;
|
|
833
884
|
entry.lastError = String(error?.message ?? error);
|
|
@@ -837,6 +888,12 @@ function createRuntime(ctx) {
|
|
|
837
888
|
return false;
|
|
838
889
|
} finally {
|
|
839
890
|
entry.sync = void 0;
|
|
891
|
+
if (entry.stale === true && alive(entry) && entry.endpoint !== "") {
|
|
892
|
+
entry.stale = false;
|
|
893
|
+
void sync(entry).then((ok) => {
|
|
894
|
+
if (!ok && alive(entry)) scheduleRetry(entry);
|
|
895
|
+
});
|
|
896
|
+
}
|
|
840
897
|
}
|
|
841
898
|
})();
|
|
842
899
|
entry.sync = run;
|
|
@@ -871,24 +928,37 @@ function installRoutes(ctx) {
|
|
|
871
928
|
const installed = shared.__GENMCP_ROUTES__ ??= /* @__PURE__ */ new WeakMap();
|
|
872
929
|
if (installed.get(webServer) === true) return;
|
|
873
930
|
installed.set(webServer, true);
|
|
874
|
-
const
|
|
931
|
+
const trusted = (req) => {
|
|
875
932
|
const headers = req.headers ?? {};
|
|
876
|
-
if (headers
|
|
877
|
-
const origin = headers.origin;
|
|
878
|
-
const host = headers.host;
|
|
879
|
-
if (
|
|
933
|
+
if ((headers.authorization ?? "") === "Bearer " + live.token) return true;
|
|
934
|
+
const origin = typeof headers.origin === "string" ? headers.origin : "";
|
|
935
|
+
const host = typeof headers.host === "string" ? headers.host : "";
|
|
936
|
+
if (origin === "") return true;
|
|
937
|
+
if (origin.startsWith("dsh-app:") || origin.startsWith("file:")) return true;
|
|
938
|
+
const loopback = /^(127\.0\.0\.1|localhost|\[::1\])(:|$)/;
|
|
880
939
|
try {
|
|
881
|
-
|
|
940
|
+
const originHost = new URL(origin).host;
|
|
941
|
+
if (host !== "" && originHost === host) return true;
|
|
942
|
+
if (loopback.test(originHost) && loopback.test(host)) return true;
|
|
882
943
|
} catch {
|
|
883
|
-
return false;
|
|
884
944
|
}
|
|
945
|
+
return false;
|
|
885
946
|
};
|
|
886
|
-
const authorized = (req) =>
|
|
887
|
-
|
|
888
|
-
|
|
947
|
+
const authorized = (req) => trusted(req);
|
|
948
|
+
const cors = (req) => {
|
|
949
|
+
const headers = req.headers ?? {};
|
|
950
|
+
const origin = typeof headers.origin === "string" ? headers.origin : "";
|
|
951
|
+
const out = {
|
|
952
|
+
"access-control-allow-methods": "GET, POST, OPTIONS",
|
|
953
|
+
"access-control-allow-headers": "content-type, authorization",
|
|
954
|
+
"access-control-max-age": "600",
|
|
955
|
+
vary: "origin"
|
|
956
|
+
};
|
|
957
|
+
if (origin !== "") out["access-control-allow-origin"] = origin;
|
|
958
|
+
return out;
|
|
889
959
|
};
|
|
890
|
-
const send = (res, status, payload) => {
|
|
891
|
-
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
960
|
+
const send = (res, status, payload, extra = {}) => {
|
|
961
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...extra });
|
|
892
962
|
res.end(JSON.stringify(payload));
|
|
893
963
|
};
|
|
894
964
|
const readBody = (req, limit = 256 * 1024) => new Promise((resolve, reject) => {
|
|
@@ -919,16 +989,22 @@ function installRoutes(ctx) {
|
|
|
919
989
|
kind: "exact",
|
|
920
990
|
path: "/api/general-mcp/catalog",
|
|
921
991
|
resource: async (request) => {
|
|
922
|
-
const
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
992
|
+
const hdr = {
|
|
993
|
+
authorization: request.headers?.get?.("authorization") ?? "",
|
|
994
|
+
origin: request.headers?.get?.("origin") ?? "",
|
|
995
|
+
host: request.headers?.get?.("host") ?? ""
|
|
996
|
+
};
|
|
997
|
+
const allowed = cors(hdr);
|
|
998
|
+
if (request.method === "OPTIONS") {
|
|
999
|
+
return new Response(null, { status: 204, headers: { ...allowed, "cache-control": "no-store" } });
|
|
1000
|
+
}
|
|
1001
|
+
if (!trusted(hdr)) {
|
|
1002
|
+
return new Response("unauthorized", { status: 401, headers: { ...allowed, "cache-control": "no-store" } });
|
|
927
1003
|
}
|
|
928
1004
|
const url = new URL(request.url);
|
|
929
1005
|
const raw = url.searchParams.get("since");
|
|
930
1006
|
const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1;
|
|
931
|
-
if (since === live.version) return new Response(null, { status: 304, headers: { "cache-control": "no-store" } });
|
|
1007
|
+
if (since === live.version) return new Response(null, { status: 304, headers: { ...allowed, "cache-control": "no-store" } });
|
|
932
1008
|
return new Response(JSON.stringify({
|
|
933
1009
|
version: live.version,
|
|
934
1010
|
servers: [...live.servers.values()].map((entry) => ({
|
|
@@ -940,13 +1016,20 @@ function installRoutes(ctx) {
|
|
|
940
1016
|
tools: entry.catalog,
|
|
941
1017
|
settings: entry.settings
|
|
942
1018
|
}))
|
|
943
|
-
}), { status: 200, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
|
|
1019
|
+
}), { status: 200, headers: { ...allowed, "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
|
|
944
1020
|
}
|
|
945
1021
|
});
|
|
946
1022
|
webServer.register({
|
|
947
1023
|
kind: "exact",
|
|
948
1024
|
path: "/api/general-mcp/probe",
|
|
949
1025
|
handler: (req, res) => {
|
|
1026
|
+
const extra = cors(req);
|
|
1027
|
+
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value);
|
|
1028
|
+
if (req.method === "OPTIONS") {
|
|
1029
|
+
res.writeHead(204);
|
|
1030
|
+
res.end();
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
950
1033
|
void (async () => {
|
|
951
1034
|
try {
|
|
952
1035
|
if (!authorized(req)) {
|
|
@@ -982,6 +1065,13 @@ function installRoutes(ctx) {
|
|
|
982
1065
|
kind: "exact",
|
|
983
1066
|
path: "/api/general-mcp/config",
|
|
984
1067
|
handler: (req, res) => {
|
|
1068
|
+
const extra = cors(req);
|
|
1069
|
+
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value);
|
|
1070
|
+
if (req.method === "OPTIONS") {
|
|
1071
|
+
res.writeHead(204);
|
|
1072
|
+
res.end();
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
985
1075
|
void (async () => {
|
|
986
1076
|
try {
|
|
987
1077
|
if (!authorized(req)) {
|
|
@@ -989,11 +1079,40 @@ function installRoutes(ctx) {
|
|
|
989
1079
|
return;
|
|
990
1080
|
}
|
|
991
1081
|
const body = await readBody(req);
|
|
992
|
-
const
|
|
993
|
-
if (
|
|
1082
|
+
const incoming = Array.isArray(body.servers) ? body.servers : void 0;
|
|
1083
|
+
if (incoming === void 0) throw new Error("body.servers must be an array");
|
|
1084
|
+
const removed = new Set(Array.isArray(body.removed) ? body.removed.filter((n) => typeof n === "string") : []);
|
|
1085
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1086
|
+
for (const item of incoming) {
|
|
1087
|
+
const name2 = String(item.name ?? "general");
|
|
1088
|
+
if (!/^[A-Za-z0-9_-]{1,32}$/.test(name2)) throw new Error('\u7F51\u5173\u540D "' + name2 + '" \u975E\u6CD5');
|
|
1089
|
+
if (seen.has(name2)) throw new Error('\u7F51\u5173\u540D "' + name2 + '" \u91CD\u590D');
|
|
1090
|
+
const endpoint = item.endpoint;
|
|
1091
|
+
if (endpoint !== void 0 && endpoint !== null && endpoint !== "" && !/^https?:\/\//i.test(String(endpoint))) {
|
|
1092
|
+
throw new Error('\u7F51\u5173 "' + name2 + '" \u7684\u5730\u5740\u5FC5\u987B\u4EE5 http(s):// \u5F00\u5934');
|
|
1093
|
+
}
|
|
1094
|
+
seen.add(name2);
|
|
1095
|
+
}
|
|
994
1096
|
const { editor, entry } = findEntry();
|
|
995
|
-
await editor.edit(entry, (current) =>
|
|
996
|
-
|
|
1097
|
+
await editor.edit(entry, (current) => {
|
|
1098
|
+
const existing = 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 }] : [];
|
|
1099
|
+
const byName = /* @__PURE__ */ new Map();
|
|
1100
|
+
for (const item of existing) byName.set(String(item.name ?? "general"), item);
|
|
1101
|
+
for (const item of incoming) {
|
|
1102
|
+
const name2 = String(item.name ?? "general");
|
|
1103
|
+
if (removed.has(name2)) continue;
|
|
1104
|
+
const previous = byName.get(name2) ?? {};
|
|
1105
|
+
const sameEndpoint = (previous.endpoint ?? "") === (item.endpoint ?? "");
|
|
1106
|
+
const next = { ...sameEndpoint ? previous : {}, ...item, name: name2 };
|
|
1107
|
+
if (!sameEndpoint) delete next.tools;
|
|
1108
|
+
byName.set(name2, next);
|
|
1109
|
+
}
|
|
1110
|
+
for (const name2 of removed) byName.delete(name2);
|
|
1111
|
+
const servers = [...byName.values()];
|
|
1112
|
+
const { serverName, endpoint, headers, tools, ...rest } = current;
|
|
1113
|
+
return { ...rest, servers };
|
|
1114
|
+
});
|
|
1115
|
+
beacon("config-saved servers=" + incoming.length + " removed=" + removed.size);
|
|
997
1116
|
send(res, 200, { ok: true });
|
|
998
1117
|
} catch (error) {
|
|
999
1118
|
beacon("config-save-error " + String(error));
|
|
@@ -1006,6 +1125,13 @@ function installRoutes(ctx) {
|
|
|
1006
1125
|
kind: "exact",
|
|
1007
1126
|
path: "/api/general-mcp/tools",
|
|
1008
1127
|
handler: (req, res) => {
|
|
1128
|
+
const extra = cors(req);
|
|
1129
|
+
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value);
|
|
1130
|
+
if (req.method === "OPTIONS") {
|
|
1131
|
+
res.writeHead(204);
|
|
1132
|
+
res.end();
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1009
1135
|
void (async () => {
|
|
1010
1136
|
try {
|
|
1011
1137
|
if (!authorized(req)) {
|
|
@@ -1014,18 +1140,20 @@ function installRoutes(ctx) {
|
|
|
1014
1140
|
}
|
|
1015
1141
|
const body = await readBody(req);
|
|
1016
1142
|
const server = typeof body.server === "string" && body.server !== "" ? body.server : "general";
|
|
1017
|
-
const tools = {
|
|
1018
|
-
disabled: Array.isArray(body.disabled) ? body.disabled.filter((v) => typeof v === "string") : [],
|
|
1019
|
-
hidden: Array.isArray(body.hidden) ? body.hidden.filter((v) => typeof v === "string") : [],
|
|
1020
|
-
overrides: body.overrides !== null && typeof body.overrides === "object" ? body.overrides : {}
|
|
1021
|
-
};
|
|
1022
1143
|
const { editor, entry } = findEntry();
|
|
1023
1144
|
await editor.edit(entry, (current) => {
|
|
1024
|
-
const list = Array.isArray(current.servers)
|
|
1145
|
+
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 }] : [];
|
|
1025
1146
|
const index = list.findIndex((item) => (item.name ?? "general") === server);
|
|
1026
|
-
if (index
|
|
1027
|
-
|
|
1028
|
-
|
|
1147
|
+
if (index < 0) throw new Error("\u7F51\u5173 " + server + " \u4E0D\u5B58\u5728\uFF0C\u5DE5\u5177\u8BBE\u7F6E\u672A\u4FDD\u5B58");
|
|
1148
|
+
const previous = list[index].tools ?? {};
|
|
1149
|
+
const next = { ...previous };
|
|
1150
|
+
if (Array.isArray(body.disabled)) next.disabled = body.disabled.filter((v) => typeof v === "string");
|
|
1151
|
+
if (Array.isArray(body.hidden)) next.hidden = body.hidden.filter((v) => typeof v === "string");
|
|
1152
|
+
if (Array.isArray(body.removed)) next.removed = body.removed.filter((v) => typeof v === "string");
|
|
1153
|
+
if (body.overrides !== null && typeof body.overrides === "object" && !Array.isArray(body.overrides)) next.overrides = body.overrides;
|
|
1154
|
+
list[index] = { ...list[index], tools: next };
|
|
1155
|
+
const { serverName, endpoint, headers, tools, ...rest } = current;
|
|
1156
|
+
return { ...rest, servers: list };
|
|
1029
1157
|
});
|
|
1030
1158
|
beacon("tools-saved " + server);
|
|
1031
1159
|
send(res, 200, { ok: true });
|
package/package.json
CHANGED
package/src/catalog.ts
CHANGED
|
@@ -9,6 +9,8 @@ export interface ToolOverride {
|
|
|
9
9
|
export interface ToolSettings {
|
|
10
10
|
disabled?: string[]
|
|
11
11
|
hidden?: string[]
|
|
12
|
+
/** Removed from the tree entirely; separate from "disabled". */
|
|
13
|
+
removed?: string[]
|
|
12
14
|
overrides?: Record<string, ToolOverride>
|
|
13
15
|
}
|
|
14
16
|
|
|
@@ -31,6 +33,7 @@ export interface CatalogEntry {
|
|
|
31
33
|
hash: string
|
|
32
34
|
disabled: boolean
|
|
33
35
|
hidden: boolean
|
|
36
|
+
removed?: boolean
|
|
34
37
|
invalid?: ToolDiagnostic
|
|
35
38
|
warning?: ToolDiagnostic
|
|
36
39
|
}
|
|
@@ -130,6 +133,7 @@ export function buildCatalog(
|
|
|
130
133
|
): CatalogEntry[] {
|
|
131
134
|
const disabled = new Set(settings.disabled ?? [])
|
|
132
135
|
const hidden = new Set(settings.hidden ?? [])
|
|
136
|
+
const removed = new Set(settings.removed ?? [])
|
|
133
137
|
return tools.map(tool => {
|
|
134
138
|
const override = settings.overrides?.[tool.name]
|
|
135
139
|
const invalid = validateTool(tool)
|
|
@@ -157,6 +161,7 @@ export function buildCatalog(
|
|
|
157
161
|
hash: shortHash(description + JSON.stringify(tool.inputSchema ?? null) + JSON.stringify(folder)),
|
|
158
162
|
disabled: disabled.has(tool.name),
|
|
159
163
|
hidden: hidden.has(tool.name),
|
|
164
|
+
...(removed.has(tool.name) ? { removed: true } : {}),
|
|
160
165
|
...(invalid !== undefined ? { invalid } : {}),
|
|
161
166
|
...(invalid === undefined && alias !== undefined ? { warning: alias } : {}),
|
|
162
167
|
}
|
package/src/client.ts
CHANGED
|
@@ -72,7 +72,10 @@ export class McpClient {
|
|
|
72
72
|
const result = await this.request('server/discover', {}, undefined, MODERN)
|
|
73
73
|
if (result === undefined || result === null) return undefined
|
|
74
74
|
return result as Record<string, unknown>
|
|
75
|
-
} catch {
|
|
75
|
+
} catch (error) {
|
|
76
|
+
// A timeout means the endpoint accepted the request and stalled; falling
|
|
77
|
+
// back to the legacy handshake would burn the same budget again.
|
|
78
|
+
if (/timed out/i.test(String((error as Error)?.message ?? ''))) throw error
|
|
76
79
|
return undefined
|
|
77
80
|
}
|
|
78
81
|
}
|
|
@@ -94,13 +97,14 @@ export class McpClient {
|
|
|
94
97
|
cursor = next
|
|
95
98
|
}
|
|
96
99
|
if (cursor !== undefined) throw new Error('tools/list did not terminate within 100 pages')
|
|
97
|
-
|
|
100
|
+
// Duplicate names are tolerated: the last definition wins, so a server can
|
|
101
|
+
// refine a tool without the whole catalogue failing to load.
|
|
102
|
+
const byName = new Map<string, McpTool>()
|
|
98
103
|
for (const tool of tools) {
|
|
99
|
-
if (typeof tool.name !== 'string' || tool.name === '')
|
|
100
|
-
|
|
101
|
-
seen.add(tool.name)
|
|
104
|
+
if (typeof tool.name !== 'string' || tool.name === '') continue
|
|
105
|
+
byName.set(tool.name, tool)
|
|
102
106
|
}
|
|
103
|
-
return
|
|
107
|
+
return [...byName.values()]
|
|
104
108
|
}
|
|
105
109
|
|
|
106
110
|
async callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<McpCallResult> {
|
package/src/connect.ts
CHANGED
|
@@ -49,9 +49,12 @@ export async function connectMcp(
|
|
|
49
49
|
headers: Record<string, string>,
|
|
50
50
|
timeoutMs: number,
|
|
51
51
|
): Promise<McpConnection> {
|
|
52
|
+
// Cap the first attempt: a server that accepts the connection but never
|
|
53
|
+
// answers must not burn the full timeout before the fallback transport runs.
|
|
54
|
+
const probeMs = Math.min(timeoutMs, 8_000)
|
|
52
55
|
const order: Array<() => Promise<McpConnection>> = looksLikeSse(url)
|
|
53
|
-
? [() => viaSse(url, headers, timeoutMs), () => viaStreamable(url, headers,
|
|
54
|
-
: [() => viaStreamable(url, headers,
|
|
56
|
+
? [() => viaSse(url, headers, timeoutMs), () => viaStreamable(url, headers, probeMs)]
|
|
57
|
+
: [() => viaStreamable(url, headers, probeMs), () => viaSse(url, headers, timeoutMs)]
|
|
55
58
|
const errors: string[] = []
|
|
56
59
|
for (const attempt of order) {
|
|
57
60
|
try {
|
package/src/index.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { tmpdir } from 'node:os'
|
|
|
11
11
|
import { join } from 'node:path'
|
|
12
12
|
import { buildCatalog, validateTool, type CatalogEntry, type ToolSettings } from './catalog.ts'
|
|
13
13
|
import type { McpTool } from './client.ts'
|
|
14
|
-
import { connectMcp } from './connect.ts'
|
|
14
|
+
import { connectMcp, type McpConnection } from './connect.ts'
|
|
15
15
|
import { publicToolName } from './naming.ts'
|
|
16
16
|
import { createToolDefinition } from './register.ts'
|
|
17
17
|
|
|
@@ -48,6 +48,10 @@ interface ServerState {
|
|
|
48
48
|
attempts: number
|
|
49
49
|
retryTimer?: any
|
|
50
50
|
sync?: Promise<boolean>
|
|
51
|
+
stale?: boolean
|
|
52
|
+
disposed?: boolean
|
|
53
|
+
generation?: number
|
|
54
|
+
client?: McpConnection
|
|
51
55
|
}
|
|
52
56
|
|
|
53
57
|
interface RuntimeState {
|
|
@@ -116,6 +120,7 @@ function normalizeSettings(raw: any): ToolSettings {
|
|
|
116
120
|
return {
|
|
117
121
|
disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item: unknown) => typeof item === 'string') : [],
|
|
118
122
|
hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item: unknown) => typeof item === 'string') : [],
|
|
123
|
+
removed: Array.isArray(tools.removed) ? tools.removed.filter((item: unknown) => typeof item === 'string') : [],
|
|
119
124
|
overrides,
|
|
120
125
|
}
|
|
121
126
|
}
|
|
@@ -130,7 +135,9 @@ function normalizeConfig(config: Config | undefined): ServerConfig[] {
|
|
|
130
135
|
live.timeoutMs = timeout
|
|
131
136
|
live.debug = raw.debug === true
|
|
132
137
|
|
|
133
|
-
|
|
138
|
+
// An explicit empty array means "no gateways"; only a missing key falls back
|
|
139
|
+
// to the legacy single-endpoint shape.
|
|
140
|
+
const list: ServerConfig[] = Array.isArray(raw.servers)
|
|
134
141
|
? raw.servers.map(item => ({ ...item }))
|
|
135
142
|
: [{ name: raw.serverName, endpoint: raw.endpoint, headers: raw.headers, tools: raw.tools }]
|
|
136
143
|
|
|
@@ -162,8 +169,11 @@ export function apply(ctx: any, config?: Config): void {
|
|
|
162
169
|
// Drop servers that are no longer configured.
|
|
163
170
|
for (const [name, entry] of live.servers) {
|
|
164
171
|
if (servers.some(item => item.name === name)) continue
|
|
172
|
+
entry.disposed = true
|
|
165
173
|
stopRetry(entry)
|
|
166
174
|
disposeTools(entry)
|
|
175
|
+
void entry.client?.close().catch(() => {})
|
|
176
|
+
entry.client = undefined
|
|
167
177
|
live.servers.delete(name)
|
|
168
178
|
live.version += 1
|
|
169
179
|
}
|
|
@@ -180,12 +190,32 @@ export function apply(ctx: any, config?: Config): void {
|
|
|
180
190
|
JSON.stringify(entry.headers) !== JSON.stringify(headers)
|
|
181
191
|
entry.endpoint = item.endpoint ?? ''
|
|
182
192
|
entry.headers = headers
|
|
183
|
-
|
|
193
|
+
const nextSettings = normalizeSettings(item.tools)
|
|
194
|
+
// Display settings live outside the connection; a sync already in flight
|
|
195
|
+
// read the old ones, so ask for one more pass once it settles.
|
|
196
|
+
// Only a settings change that lands *while* a discovery is in flight needs a
|
|
197
|
+
// second pass; otherwise sync() below already runs once.
|
|
198
|
+
if (entry.sync !== undefined && JSON.stringify(entry.settings) !== JSON.stringify(nextSettings)) entry.stale = true
|
|
199
|
+
entry.settings = nextSettings
|
|
200
|
+
// Applying a settings change must not wait for a successful reconnect:
|
|
201
|
+
// a removed/disabled tool has to stop being callable right away.
|
|
202
|
+
for (const raw of [...(nextSettings.removed ?? []), ...(nextSettings.disabled ?? [])]) {
|
|
203
|
+
const dispose = entry.tools.get(raw)
|
|
204
|
+
if (dispose === undefined) continue
|
|
205
|
+
try { dispose() } catch {}
|
|
206
|
+
entry.tools.delete(raw)
|
|
207
|
+
}
|
|
208
|
+
entry.toolCount = entry.tools.size
|
|
184
209
|
|
|
185
210
|
if (changed) {
|
|
211
|
+
entry.generation = (entry.generation ?? 0) + 1
|
|
212
|
+
if (entry.sync !== undefined) entry.stale = true
|
|
186
213
|
stopRetry(entry)
|
|
187
214
|
disposeTools(entry)
|
|
215
|
+
void entry.client?.close().catch(() => {})
|
|
216
|
+
entry.client = undefined
|
|
188
217
|
entry.connected = false
|
|
218
|
+
entry.catalog = []
|
|
189
219
|
entry.lastError = ''
|
|
190
220
|
entry.attempts = 0
|
|
191
221
|
live.version += 1
|
|
@@ -199,7 +229,7 @@ export function apply(ctx: any, config?: Config): void {
|
|
|
199
229
|
continue
|
|
200
230
|
}
|
|
201
231
|
void sync(entry).then(ok => {
|
|
202
|
-
if (!ok) scheduleRetry(entry)
|
|
232
|
+
if (!ok && entry.disposed !== true && live.servers.get(entry.name) === entry) scheduleRetry(entry)
|
|
203
233
|
}).catch(error => {
|
|
204
234
|
entry.lastError = String((error as Error)?.message ?? error)
|
|
205
235
|
live.version += 1
|
|
@@ -225,6 +255,7 @@ function createRuntime(ctx: any) {
|
|
|
225
255
|
const settings = entry.settings
|
|
226
256
|
for (const tool of tools) {
|
|
227
257
|
if (settings.disabled?.includes(tool.name) === true) continue
|
|
258
|
+
if (settings.removed?.includes(tool.name) === true) continue
|
|
228
259
|
const invalid = validateTool(tool)
|
|
229
260
|
if (invalid !== undefined) continue
|
|
230
261
|
const definition: any = createToolDefinition(entry.name, tool, client)
|
|
@@ -236,23 +267,47 @@ function createRuntime(ctx: any) {
|
|
|
236
267
|
}
|
|
237
268
|
}
|
|
238
269
|
|
|
270
|
+
const alive = (entry: ServerState): boolean =>
|
|
271
|
+
entry.disposed !== true && live.servers.get(entry.name) === entry
|
|
272
|
+
|
|
239
273
|
const sync = (entry: ServerState): Promise<boolean> => {
|
|
240
274
|
if (entry.sync !== undefined) return entry.sync
|
|
241
275
|
const run = (async () => {
|
|
242
|
-
|
|
243
|
-
const client = await connectMcp(entry.endpoint, entry.headers, live.timeoutMs)
|
|
276
|
+
const generation = entry.generation ?? 0
|
|
244
277
|
try {
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
entry.
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
278
|
+
if (entry.endpoint === '') return false
|
|
279
|
+
const client = await connectMcp(entry.endpoint, entry.headers, live.timeoutMs)
|
|
280
|
+
if (!alive(entry) || (entry.generation ?? 0) !== generation) {
|
|
281
|
+
await client.close().catch(() => {})
|
|
282
|
+
return false
|
|
283
|
+
}
|
|
284
|
+
const previous = entry.client
|
|
285
|
+
entry.client = client
|
|
286
|
+
if (previous !== undefined && previous !== client) void previous.close().catch(() => {})
|
|
287
|
+
try {
|
|
288
|
+
const tools = await client.listTools()
|
|
289
|
+
if (!alive(entry) || (entry.generation ?? 0) !== generation) return false
|
|
290
|
+
const names = new Set(tools.map(tool => tool.name))
|
|
291
|
+
const keep = (list: string[] | undefined) => (list ?? []).filter(name => names.has(name))
|
|
292
|
+
entry.settings = {
|
|
293
|
+
disabled: keep(entry.settings.disabled),
|
|
294
|
+
hidden: keep(entry.settings.hidden),
|
|
295
|
+
removed: keep(entry.settings.removed),
|
|
296
|
+
overrides: Object.fromEntries(Object.entries(entry.settings.overrides ?? {}).filter(([name]) => names.has(name))),
|
|
297
|
+
}
|
|
298
|
+
disposeTools(entry)
|
|
299
|
+
registerTools(entry, tools as McpTool[], client)
|
|
300
|
+
entry.connected = true
|
|
301
|
+
entry.toolCount = entry.tools.size
|
|
302
|
+
entry.catalog = buildCatalog(entry.name, tools as McpTool[], raw => publicToolName(entry.name, raw), entry.settings)
|
|
303
|
+
entry.lastError = ''
|
|
304
|
+
entry.attempts = 0
|
|
305
|
+
live.version += 1
|
|
306
|
+
beacon('discovered ' + entry.name + ' tools=' + tools.length)
|
|
307
|
+
return true
|
|
308
|
+
} catch (error) {
|
|
309
|
+
throw error
|
|
310
|
+
}
|
|
256
311
|
} catch (error) {
|
|
257
312
|
entry.connected = false
|
|
258
313
|
entry.lastError = String((error as Error)?.message ?? error)
|
|
@@ -262,6 +317,10 @@ function createRuntime(ctx: any) {
|
|
|
262
317
|
return false
|
|
263
318
|
} finally {
|
|
264
319
|
entry.sync = undefined
|
|
320
|
+
if (entry.stale === true && alive(entry) && entry.endpoint !== '') {
|
|
321
|
+
entry.stale = false
|
|
322
|
+
void sync(entry).then(ok => { if (!ok && alive(entry)) scheduleRetry(entry) })
|
|
323
|
+
}
|
|
265
324
|
}
|
|
266
325
|
})()
|
|
267
326
|
entry.sync = run
|
|
@@ -302,20 +361,41 @@ function installRoutes(ctx: any): void {
|
|
|
302
361
|
if (installed.get(webServer) === true) return
|
|
303
362
|
installed.set(webServer, true)
|
|
304
363
|
|
|
305
|
-
|
|
364
|
+
// The desktop shell renders the page from dsh-app:// and forwards /api to
|
|
365
|
+
// this server, so sec-fetch-site is cross-site and Origin is an app scheme.
|
|
366
|
+
// Accept: boot token, no Origin (non-browser), desktop/file origins, the
|
|
367
|
+
// server's own host, or any loopback host.
|
|
368
|
+
const trusted = (req: any): boolean => {
|
|
306
369
|
const headers = req.headers ?? {}
|
|
307
|
-
if (headers
|
|
308
|
-
const origin = headers.origin
|
|
309
|
-
const host = headers.host
|
|
310
|
-
if (
|
|
311
|
-
|
|
370
|
+
if ((headers.authorization ?? '') === 'Bearer ' + live.token) return true
|
|
371
|
+
const origin = typeof headers.origin === 'string' ? headers.origin : ''
|
|
372
|
+
const host = typeof headers.host === 'string' ? headers.host : ''
|
|
373
|
+
if (origin === '') return true
|
|
374
|
+
if (origin.startsWith('dsh-app:') || origin.startsWith('file:')) return true
|
|
375
|
+
const loopback = /^(127\.0\.0\.1|localhost|\[::1\])(:|$)/
|
|
376
|
+
try {
|
|
377
|
+
const originHost = new URL(origin).host
|
|
378
|
+
if (host !== '' && originHost === host) return true
|
|
379
|
+
// A page served from loopback may talk to a differently-addressed loopback API.
|
|
380
|
+
if (loopback.test(originHost) && loopback.test(host)) return true
|
|
381
|
+
} catch {}
|
|
382
|
+
return false
|
|
312
383
|
}
|
|
313
|
-
const authorized = (req: any): boolean =>
|
|
314
|
-
|
|
315
|
-
|
|
384
|
+
const authorized = (req: any): boolean => trusted(req)
|
|
385
|
+
const cors = (req: any): Record<string, string> => {
|
|
386
|
+
const headers = req.headers ?? {}
|
|
387
|
+
const origin = typeof headers.origin === 'string' ? headers.origin : ''
|
|
388
|
+
const out: Record<string, string> = {
|
|
389
|
+
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
|
390
|
+
'access-control-allow-headers': 'content-type, authorization',
|
|
391
|
+
'access-control-max-age': '600',
|
|
392
|
+
vary: 'origin',
|
|
393
|
+
}
|
|
394
|
+
if (origin !== '') out['access-control-allow-origin'] = origin
|
|
395
|
+
return out
|
|
316
396
|
}
|
|
317
|
-
const send = (res: any, status: number, payload: unknown) => {
|
|
318
|
-
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
397
|
+
const send = (res: any, status: number, payload: unknown, extra: Record<string, string> = {}) => {
|
|
398
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...extra })
|
|
319
399
|
res.end(JSON.stringify(payload))
|
|
320
400
|
}
|
|
321
401
|
const readBody = (req: any, limit = 256 * 1024): Promise<Record<string, unknown>> =>
|
|
@@ -344,16 +424,22 @@ function installRoutes(ctx: any): void {
|
|
|
344
424
|
kind: 'exact',
|
|
345
425
|
path: '/api/general-mcp/catalog',
|
|
346
426
|
resource: async (request: any) => {
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
427
|
+
const hdr = {
|
|
428
|
+
authorization: request.headers?.get?.('authorization') ?? '',
|
|
429
|
+
origin: request.headers?.get?.('origin') ?? '',
|
|
430
|
+
host: request.headers?.get?.('host') ?? '',
|
|
431
|
+
}
|
|
432
|
+
const allowed = cors(hdr)
|
|
433
|
+
if (request.method === 'OPTIONS') {
|
|
434
|
+
return new Response(null, { status: 204, headers: { ...allowed, 'cache-control': 'no-store' } })
|
|
435
|
+
}
|
|
436
|
+
if (!trusted(hdr)) {
|
|
437
|
+
return new Response('unauthorized', { status: 401, headers: { ...allowed, 'cache-control': 'no-store' } })
|
|
352
438
|
}
|
|
353
439
|
const url = new URL(request.url)
|
|
354
440
|
const raw = url.searchParams.get('since')
|
|
355
441
|
const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1
|
|
356
|
-
if (since === live.version) return new Response(null, { status: 304, headers: { 'cache-control': 'no-store' } })
|
|
442
|
+
if (since === live.version) return new Response(null, { status: 304, headers: { ...allowed, 'cache-control': 'no-store' } })
|
|
357
443
|
return new Response(JSON.stringify({
|
|
358
444
|
version: live.version,
|
|
359
445
|
servers: [...live.servers.values()].map(entry => ({
|
|
@@ -365,7 +451,7 @@ function installRoutes(ctx: any): void {
|
|
|
365
451
|
tools: entry.catalog,
|
|
366
452
|
settings: entry.settings,
|
|
367
453
|
})),
|
|
368
|
-
}), { status: 200, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } })
|
|
454
|
+
}), { status: 200, headers: { ...allowed, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } })
|
|
369
455
|
},
|
|
370
456
|
})
|
|
371
457
|
|
|
@@ -373,6 +459,9 @@ function installRoutes(ctx: any): void {
|
|
|
373
459
|
kind: 'exact',
|
|
374
460
|
path: '/api/general-mcp/probe',
|
|
375
461
|
handler: (req: any, res: any) => {
|
|
462
|
+
const extra = cors(req)
|
|
463
|
+
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
|
|
464
|
+
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
376
465
|
void (async () => {
|
|
377
466
|
try {
|
|
378
467
|
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
@@ -406,15 +495,54 @@ function installRoutes(ctx: any): void {
|
|
|
406
495
|
kind: 'exact',
|
|
407
496
|
path: '/api/general-mcp/config',
|
|
408
497
|
handler: (req: any, res: any) => {
|
|
498
|
+
const extra = cors(req)
|
|
499
|
+
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
|
|
500
|
+
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
409
501
|
void (async () => {
|
|
410
502
|
try {
|
|
411
503
|
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
412
504
|
const body = await readBody(req)
|
|
413
|
-
const
|
|
414
|
-
if (
|
|
505
|
+
const incoming = Array.isArray(body.servers) ? body.servers : undefined
|
|
506
|
+
if (incoming === undefined) throw new Error('body.servers must be an array')
|
|
507
|
+
const removed = new Set(Array.isArray(body.removed) ? body.removed.filter((n: unknown) => typeof n === 'string') : [])
|
|
508
|
+
const seen = new Set<string>()
|
|
509
|
+
for (const item of incoming as any[]) {
|
|
510
|
+
const name = String(item.name ?? 'general')
|
|
511
|
+
if (!/^[A-Za-z0-9_-]{1,32}$/.test(name)) throw new Error('网关名 "' + name + '" 非法')
|
|
512
|
+
if (seen.has(name)) throw new Error('网关名 "' + name + '" 重复')
|
|
513
|
+
const endpoint = item.endpoint
|
|
514
|
+
if (endpoint !== undefined && endpoint !== null && endpoint !== '' && !/^https?:\/\//i.test(String(endpoint))) {
|
|
515
|
+
throw new Error('网关 "' + name + '" 的地址必须以 http(s):// 开头')
|
|
516
|
+
}
|
|
517
|
+
seen.add(name)
|
|
518
|
+
}
|
|
415
519
|
const { editor, entry } = findEntry()
|
|
416
|
-
await editor.edit(entry, (current: any) =>
|
|
417
|
-
|
|
520
|
+
await editor.edit(entry, (current: any) => {
|
|
521
|
+
// Merge instead of replacing: a stale page or a race must never
|
|
522
|
+
// delete gateways it did not explicitly ask to remove. An explicit
|
|
523
|
+
// empty array still means "no gateways" (never fall back to legacy).
|
|
524
|
+
const existing: any[] = Array.isArray(current.servers)
|
|
525
|
+
? current.servers.map((item: any) => ({ ...item }))
|
|
526
|
+
: (typeof current.endpoint === 'string' && current.endpoint !== ''
|
|
527
|
+
? [{ name: current.serverName ?? 'general', endpoint: current.endpoint, headers: current.headers ?? {}, tools: current.tools }]
|
|
528
|
+
: [])
|
|
529
|
+
const byName = new Map<string, any>()
|
|
530
|
+
for (const item of existing) byName.set(String(item.name ?? 'general'), item)
|
|
531
|
+
for (const item of incoming as any[]) {
|
|
532
|
+
const name = String(item.name ?? 'general')
|
|
533
|
+
if (removed.has(name)) continue
|
|
534
|
+
const previous = byName.get(name) ?? {}
|
|
535
|
+
const sameEndpoint = (previous.endpoint ?? '') === (item.endpoint ?? '')
|
|
536
|
+
const next = { ...(sameEndpoint ? previous : {}), ...item, name }
|
|
537
|
+
if (!sameEndpoint) delete next.tools
|
|
538
|
+
byName.set(name, next)
|
|
539
|
+
}
|
|
540
|
+
for (const name of removed) byName.delete(name)
|
|
541
|
+
const servers = [...byName.values()]
|
|
542
|
+
const { serverName, endpoint, headers, tools, ...rest } = current
|
|
543
|
+
return { ...rest, servers }
|
|
544
|
+
})
|
|
545
|
+
beacon('config-saved servers=' + (incoming as any[]).length + ' removed=' + removed.size)
|
|
418
546
|
send(res, 200, { ok: true })
|
|
419
547
|
} catch (error) {
|
|
420
548
|
beacon('config-save-error ' + String(error))
|
|
@@ -428,25 +556,36 @@ function installRoutes(ctx: any): void {
|
|
|
428
556
|
kind: 'exact',
|
|
429
557
|
path: '/api/general-mcp/tools',
|
|
430
558
|
handler: (req: any, res: any) => {
|
|
559
|
+
const extra = cors(req)
|
|
560
|
+
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value)
|
|
561
|
+
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
431
562
|
void (async () => {
|
|
432
563
|
try {
|
|
433
564
|
if (!authorized(req)) { send(res, 401, { ok: false, message: 'unauthorized' }); return }
|
|
434
565
|
const body = await readBody(req)
|
|
435
566
|
const server = typeof body.server === 'string' && body.server !== '' ? body.server : 'general'
|
|
436
|
-
const tools = {
|
|
437
|
-
disabled: Array.isArray(body.disabled) ? body.disabled.filter((v: unknown) => typeof v === 'string') : [],
|
|
438
|
-
hidden: Array.isArray(body.hidden) ? body.hidden.filter((v: unknown) => typeof v === 'string') : [],
|
|
439
|
-
overrides: body.overrides !== null && typeof body.overrides === 'object' ? body.overrides : {},
|
|
440
|
-
}
|
|
441
567
|
const { editor, entry } = findEntry()
|
|
442
568
|
await editor.edit(entry, (current: any) => {
|
|
443
|
-
const list = Array.isArray(current.servers)
|
|
569
|
+
const list: any[] = Array.isArray(current.servers)
|
|
444
570
|
? current.servers.map((item: any) => ({ ...item }))
|
|
445
|
-
:
|
|
571
|
+
: (typeof current.endpoint === 'string' && current.endpoint !== ''
|
|
572
|
+
? [{ name: current.serverName ?? 'general', endpoint: current.endpoint, headers: current.headers ?? {}, tools: current.tools }]
|
|
573
|
+
: [])
|
|
446
574
|
const index = list.findIndex((item: any) => (item.name ?? 'general') === server)
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
575
|
+
// Never invent a gateway: that would resurrect a deleted one as an
|
|
576
|
+
// empty phantom and drag its old tool settings back with it.
|
|
577
|
+
if (index < 0) throw new Error('网关 ' + server + ' 不存在,工具设置未保存')
|
|
578
|
+
// Merge per key: a partial request (or a stale page) must not wipe
|
|
579
|
+
// other lists such as removed/overrides.
|
|
580
|
+
const previous = list[index].tools ?? {}
|
|
581
|
+
const next: any = { ...previous }
|
|
582
|
+
if (Array.isArray(body.disabled)) next.disabled = body.disabled.filter((v: unknown) => typeof v === 'string')
|
|
583
|
+
if (Array.isArray(body.hidden)) next.hidden = body.hidden.filter((v: unknown) => typeof v === 'string')
|
|
584
|
+
if (Array.isArray(body.removed)) next.removed = body.removed.filter((v: unknown) => typeof v === 'string')
|
|
585
|
+
if (body.overrides !== null && typeof body.overrides === 'object' && !Array.isArray(body.overrides)) next.overrides = body.overrides
|
|
586
|
+
list[index] = { ...list[index], tools: next }
|
|
587
|
+
const { serverName, endpoint, headers, tools, ...rest } = current
|
|
588
|
+
return { ...rest, servers: list }
|
|
450
589
|
})
|
|
451
590
|
beacon('tools-saved ' + server)
|
|
452
591
|
send(res, 200, { ok: true })
|
|
@@ -531,4 +670,4 @@ function registerStatusTool(ctx: any): void {
|
|
|
531
670
|
},
|
|
532
671
|
})
|
|
533
672
|
ctx.effect?.(() => () => dispose())
|
|
534
|
-
}
|
|
673
|
+
}
|
package/src/sse.ts
CHANGED
|
@@ -75,7 +75,9 @@ export class SseClient {
|
|
|
75
75
|
while (true) {
|
|
76
76
|
const chunk = await this.reader?.read()
|
|
77
77
|
if (chunk === undefined || chunk.done === true) break
|
|
78
|
-
|
|
78
|
+
// Normalise CRLF here (not per line) so a \r\n split across two chunks
|
|
79
|
+
// still collapses into one event boundary.
|
|
80
|
+
buffer = (buffer + decoder.decode(chunk.value, { stream: true })).replace(/\r\n/g, '\n')
|
|
79
81
|
let index = buffer.indexOf('\n\n')
|
|
80
82
|
while (index >= 0) {
|
|
81
83
|
this.handleEvent(buffer.slice(0, index))
|
|
@@ -149,7 +151,7 @@ export class SseClient {
|
|
|
149
151
|
})
|
|
150
152
|
const response = await fetch(this.messageUrl as string, {
|
|
151
153
|
method: 'POST',
|
|
152
|
-
headers: { 'content-type': 'application/json', ...this.headers },
|
|
154
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...this.headers },
|
|
153
155
|
body,
|
|
154
156
|
signal: this.controller.signal,
|
|
155
157
|
})
|
|
@@ -175,7 +177,7 @@ export class SseClient {
|
|
|
175
177
|
await this.connect()
|
|
176
178
|
const response = await fetch(this.messageUrl as string, {
|
|
177
179
|
method: 'POST',
|
|
178
|
-
headers: { 'content-type': 'application/json', ...this.headers },
|
|
180
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...this.headers },
|
|
179
181
|
body: JSON.stringify({ jsonrpc: '2.0', method, params }),
|
|
180
182
|
signal: this.controller.signal,
|
|
181
183
|
})
|