@momeidejiyi/dsh-general-mcp 0.1.7 → 0.1.9
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 +280 -77
- package/package.json +1 -1
- package/src/catalog.ts +5 -0
- package/src/client.ts +10 -6
- package/src/connect.ts +9 -2
- package/src/index.ts +277 -61
- package/src/sse.ts +45 -6
package/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @momeidejiyi/dsh-general-mcp@0.1.
|
|
1
|
+
// @momeidejiyi/dsh-general-mcp@0.1.9 (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);
|
|
@@ -323,6 +325,27 @@ async function readSseResult(response, id) {
|
|
|
323
325
|
}
|
|
324
326
|
|
|
325
327
|
// packages/general-mcp/src/sse.ts
|
|
328
|
+
function isLocalHost(hostname) {
|
|
329
|
+
const host = hostname.toLowerCase();
|
|
330
|
+
return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]" || host === "0.0.0.0" || /^10\./.test(host) || /^192\.168\./.test(host) || /^172\.(1[6-9]|2\d|3[01])\./.test(host);
|
|
331
|
+
}
|
|
332
|
+
function resolveMessageUrl(endpoint, sseUrl) {
|
|
333
|
+
let target;
|
|
334
|
+
let sse;
|
|
335
|
+
try {
|
|
336
|
+
sse = new URL(sseUrl);
|
|
337
|
+
target = new URL(endpoint, sseUrl);
|
|
338
|
+
} catch {
|
|
339
|
+
return endpoint;
|
|
340
|
+
}
|
|
341
|
+
if (target.origin !== sse.origin && isLocalHost(target.hostname)) {
|
|
342
|
+
target.protocol = sse.protocol;
|
|
343
|
+
target.hostname = sse.hostname;
|
|
344
|
+
target.port = sse.port;
|
|
345
|
+
return target.toString();
|
|
346
|
+
}
|
|
347
|
+
return target.toString();
|
|
348
|
+
}
|
|
326
349
|
var SseClient = class {
|
|
327
350
|
constructor(url, headers = {}, timeoutMs = 6e4) {
|
|
328
351
|
this.url = url;
|
|
@@ -339,6 +362,10 @@ var SseClient = class {
|
|
|
339
362
|
get protocolVersion() {
|
|
340
363
|
return "2024-11-05";
|
|
341
364
|
}
|
|
365
|
+
/** Where requests are POSTed; useful in diagnostics. */
|
|
366
|
+
get messageEndpoint() {
|
|
367
|
+
return this.messageUrl;
|
|
368
|
+
}
|
|
342
369
|
/** Open the stream and wait for the endpoint announcement. */
|
|
343
370
|
connect() {
|
|
344
371
|
if (this.connected !== void 0) return this.connected;
|
|
@@ -349,7 +376,7 @@ var SseClient = class {
|
|
|
349
376
|
if (response.body === null) throw new Error("SSE connect returned no body");
|
|
350
377
|
this.reader = response.body.getReader();
|
|
351
378
|
const announced = new Promise((resolve, reject) => {
|
|
352
|
-
const timer = setTimeout(() => reject(new Error("SSE endpoint event timed out")), this.timeoutMs);
|
|
379
|
+
const timer = setTimeout(() => reject(new Error("SSE endpoint event timed out after " + this.timeoutMs + "ms (GET " + this.url + ")")), this.timeoutMs);
|
|
353
380
|
this.endpointWaiter = { resolve, reject, timer };
|
|
354
381
|
});
|
|
355
382
|
void this.pump();
|
|
@@ -366,7 +393,7 @@ var SseClient = class {
|
|
|
366
393
|
while (true) {
|
|
367
394
|
const chunk = await this.reader?.read();
|
|
368
395
|
if (chunk === void 0 || chunk.done === true) break;
|
|
369
|
-
buffer
|
|
396
|
+
buffer = (buffer + decoder.decode(chunk.value, { stream: true })).replace(/\r\n/g, "\n");
|
|
370
397
|
let index = buffer.indexOf("\n\n");
|
|
371
398
|
while (index >= 0) {
|
|
372
399
|
this.handleEvent(buffer.slice(0, index));
|
|
@@ -387,11 +414,7 @@ var SseClient = class {
|
|
|
387
414
|
}
|
|
388
415
|
const payload = data.join("\n");
|
|
389
416
|
if (event === "endpoint") {
|
|
390
|
-
|
|
391
|
-
this.messageUrl = new URL(payload, this.url).toString();
|
|
392
|
-
} catch {
|
|
393
|
-
this.messageUrl = payload;
|
|
394
|
-
}
|
|
417
|
+
this.messageUrl = resolveMessageUrl(payload, this.url);
|
|
395
418
|
const waiter = this.endpointWaiter;
|
|
396
419
|
this.endpointWaiter = void 0;
|
|
397
420
|
if (waiter !== void 0) {
|
|
@@ -448,13 +471,13 @@ var SseClient = class {
|
|
|
448
471
|
const reply = new Promise((resolve, reject) => {
|
|
449
472
|
const timer = setTimeout(() => {
|
|
450
473
|
this.pending.delete(id);
|
|
451
|
-
reject(new Error("MCP " + method + " timed out after " + this.timeoutMs + "ms"));
|
|
474
|
+
reject(new Error("MCP " + method + " timed out after " + this.timeoutMs + "ms (POST " + this.messageUrl + ")"));
|
|
452
475
|
}, this.timeoutMs);
|
|
453
476
|
this.pending.set(id, { resolve, reject, timer });
|
|
454
477
|
});
|
|
455
478
|
const response = await fetch(this.messageUrl, {
|
|
456
479
|
method: "POST",
|
|
457
|
-
headers: { "content-type": "application/json", ...this.headers },
|
|
480
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...this.headers },
|
|
458
481
|
body,
|
|
459
482
|
signal: this.controller.signal
|
|
460
483
|
});
|
|
@@ -481,7 +504,7 @@ var SseClient = class {
|
|
|
481
504
|
await this.connect();
|
|
482
505
|
const response = await fetch(this.messageUrl, {
|
|
483
506
|
method: "POST",
|
|
484
|
-
headers: { "content-type": "application/json", ...this.headers },
|
|
507
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...this.headers },
|
|
485
508
|
body: JSON.stringify({ jsonrpc: "2.0", method, params }),
|
|
486
509
|
signal: this.controller.signal
|
|
487
510
|
});
|
|
@@ -528,6 +551,7 @@ async function viaStreamable(url, headers, timeoutMs) {
|
|
|
528
551
|
const info = await client.initialize();
|
|
529
552
|
return {
|
|
530
553
|
transport: "streamable",
|
|
554
|
+
detail: "POST " + url,
|
|
531
555
|
protocolVersion: info?.protocolVersion,
|
|
532
556
|
serverInfo: info?.serverInfo,
|
|
533
557
|
async initialize() {
|
|
@@ -542,6 +566,7 @@ async function viaSse(url, headers, timeoutMs) {
|
|
|
542
566
|
const info = await client.initialize();
|
|
543
567
|
return {
|
|
544
568
|
transport: "sse",
|
|
569
|
+
detail: "GET " + url + " \u2192 POST " + (client.messageEndpoint ?? "(pending)"),
|
|
545
570
|
protocolVersion: info?.protocolVersion,
|
|
546
571
|
serverInfo: info?.serverInfo,
|
|
547
572
|
async initialize() {
|
|
@@ -552,7 +577,8 @@ async function viaSse(url, headers, timeoutMs) {
|
|
|
552
577
|
};
|
|
553
578
|
}
|
|
554
579
|
async function connectMcp(url, headers, timeoutMs) {
|
|
555
|
-
const
|
|
580
|
+
const probeMs = Math.min(timeoutMs, 8e3);
|
|
581
|
+
const order = looksLikeSse(url) ? [() => viaSse(url, headers, timeoutMs), () => viaStreamable(url, headers, probeMs)] : [() => viaStreamable(url, headers, probeMs), () => viaSse(url, headers, timeoutMs)];
|
|
556
582
|
const errors = [];
|
|
557
583
|
for (const attempt of order) {
|
|
558
584
|
try {
|
|
@@ -665,7 +691,10 @@ function state() {
|
|
|
665
691
|
servers: /* @__PURE__ */ new Map(),
|
|
666
692
|
version: 0,
|
|
667
693
|
debug: false,
|
|
668
|
-
timeoutMs: 6e4
|
|
694
|
+
timeoutMs: 6e4,
|
|
695
|
+
retryIntervalMs: 3e4,
|
|
696
|
+
maxRetries: 20,
|
|
697
|
+
pollIntervalMs: 15e3
|
|
669
698
|
};
|
|
670
699
|
}
|
|
671
700
|
return shared.__GENMCP_STATE__;
|
|
@@ -684,7 +713,9 @@ function serverState(name2) {
|
|
|
684
713
|
catalog: [],
|
|
685
714
|
tools: /* @__PURE__ */ new Map(),
|
|
686
715
|
settings: {},
|
|
687
|
-
attempts: 0
|
|
716
|
+
attempts: 0,
|
|
717
|
+
enabled: true,
|
|
718
|
+
timeoutMs: 0
|
|
688
719
|
};
|
|
689
720
|
live.servers.set(name2, entry);
|
|
690
721
|
}
|
|
@@ -708,16 +739,20 @@ function normalizeSettings(raw) {
|
|
|
708
739
|
return {
|
|
709
740
|
disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item) => typeof item === "string") : [],
|
|
710
741
|
hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item) => typeof item === "string") : [],
|
|
742
|
+
removed: Array.isArray(tools.removed) ? tools.removed.filter((item) => typeof item === "string") : [],
|
|
711
743
|
overrides
|
|
712
744
|
};
|
|
713
745
|
}
|
|
714
746
|
function normalizeConfig(config) {
|
|
715
747
|
const raw = config ?? {};
|
|
716
748
|
const live = state();
|
|
717
|
-
const
|
|
718
|
-
live.timeoutMs =
|
|
749
|
+
const clamp = (value, fallback, min, max) => typeof value === "number" && Number.isFinite(value) ? Math.min(Math.max(Math.round(value), min), max) : fallback;
|
|
750
|
+
live.timeoutMs = clamp(raw.toolCallTimeoutMs, 6e4, 1e3, 6e5);
|
|
751
|
+
live.retryIntervalMs = clamp(raw.retryIntervalMs, 3e4, 5e3, 6e5);
|
|
752
|
+
live.maxRetries = clamp(raw.maxRetries, 20, 0, 1e3);
|
|
753
|
+
live.pollIntervalMs = clamp(raw.pollIntervalMs, 15e3, 2e3, 6e5);
|
|
719
754
|
live.debug = raw.debug === true;
|
|
720
|
-
const list = Array.isArray(raw.servers)
|
|
755
|
+
const list = Array.isArray(raw.servers) ? raw.servers.map((item) => ({ ...item })) : [{ name: raw.serverName, endpoint: raw.endpoint, headers: raw.headers, tools: raw.tools }];
|
|
721
756
|
const seen = /* @__PURE__ */ new Set();
|
|
722
757
|
const out = [];
|
|
723
758
|
for (const item of list) {
|
|
@@ -742,8 +777,12 @@ function apply(ctx, config) {
|
|
|
742
777
|
const { disposeTools, registerTools, sync, scheduleRetry, stopRetry } = createRuntime(ctx);
|
|
743
778
|
for (const [name2, entry] of live.servers) {
|
|
744
779
|
if (servers.some((item) => item.name === name2)) continue;
|
|
780
|
+
entry.disposed = true;
|
|
745
781
|
stopRetry(entry);
|
|
746
782
|
disposeTools(entry);
|
|
783
|
+
void entry.client?.close().catch(() => {
|
|
784
|
+
});
|
|
785
|
+
entry.client = void 0;
|
|
747
786
|
live.servers.delete(name2);
|
|
748
787
|
live.version += 1;
|
|
749
788
|
}
|
|
@@ -755,28 +794,51 @@ function apply(ctx, config) {
|
|
|
755
794
|
if (typeof value === "string") headers[key] = value;
|
|
756
795
|
}
|
|
757
796
|
}
|
|
758
|
-
const
|
|
797
|
+
const enabled = item.enabled !== false;
|
|
798
|
+
const serverTimeout = typeof item.timeoutMs === "number" && Number.isFinite(item.timeoutMs) ? Math.min(Math.max(Math.round(item.timeoutMs), 1e3), 6e5) : 0;
|
|
799
|
+
const changed = entry.endpoint !== (item.endpoint ?? "") || JSON.stringify(entry.headers) !== JSON.stringify(headers) || entry.enabled !== enabled || entry.timeoutMs !== serverTimeout;
|
|
759
800
|
entry.endpoint = item.endpoint ?? "";
|
|
760
801
|
entry.headers = headers;
|
|
761
|
-
entry.
|
|
802
|
+
entry.enabled = enabled;
|
|
803
|
+
entry.timeoutMs = serverTimeout;
|
|
804
|
+
const nextSettings = normalizeSettings(item.tools);
|
|
805
|
+
if (entry.sync !== void 0 && JSON.stringify(entry.settings) !== JSON.stringify(nextSettings)) entry.stale = true;
|
|
806
|
+
entry.settings = nextSettings;
|
|
807
|
+
for (const raw of [...nextSettings.removed ?? [], ...nextSettings.disabled ?? []]) {
|
|
808
|
+
const dispose = entry.tools.get(raw);
|
|
809
|
+
if (dispose === void 0) continue;
|
|
810
|
+
try {
|
|
811
|
+
dispose();
|
|
812
|
+
} catch {
|
|
813
|
+
}
|
|
814
|
+
entry.tools.delete(raw);
|
|
815
|
+
}
|
|
816
|
+
entry.toolCount = entry.tools.size;
|
|
762
817
|
if (changed) {
|
|
818
|
+
entry.generation = (entry.generation ?? 0) + 1;
|
|
819
|
+
if (entry.sync !== void 0) entry.stale = true;
|
|
763
820
|
stopRetry(entry);
|
|
764
821
|
disposeTools(entry);
|
|
822
|
+
void entry.client?.close().catch(() => {
|
|
823
|
+
});
|
|
824
|
+
entry.client = void 0;
|
|
765
825
|
entry.connected = false;
|
|
826
|
+
entry.catalog = [];
|
|
766
827
|
entry.lastError = "";
|
|
767
828
|
entry.attempts = 0;
|
|
768
829
|
live.version += 1;
|
|
769
830
|
}
|
|
770
|
-
if (entry.endpoint === "") {
|
|
831
|
+
if (entry.endpoint === "" || entry.enabled === false) {
|
|
771
832
|
disposeTools(entry);
|
|
833
|
+
stopRetry(entry);
|
|
772
834
|
entry.connected = false;
|
|
773
835
|
entry.toolCount = 0;
|
|
774
836
|
entry.catalog = [];
|
|
775
|
-
entry.lastError = "";
|
|
837
|
+
entry.lastError = entry.enabled === false ? "" : entry.lastError;
|
|
776
838
|
continue;
|
|
777
839
|
}
|
|
778
840
|
void sync(entry).then((ok) => {
|
|
779
|
-
if (!ok) scheduleRetry(entry);
|
|
841
|
+
if (!ok && entry.disposed !== true && live.servers.get(entry.name) === entry) scheduleRetry(entry);
|
|
780
842
|
}).catch((error) => {
|
|
781
843
|
entry.lastError = String(error?.message ?? error);
|
|
782
844
|
live.version += 1;
|
|
@@ -801,6 +863,7 @@ function createRuntime(ctx) {
|
|
|
801
863
|
const settings = entry.settings;
|
|
802
864
|
for (const tool of tools) {
|
|
803
865
|
if (settings.disabled?.includes(tool.name) === true) continue;
|
|
866
|
+
if (settings.removed?.includes(tool.name) === true) continue;
|
|
804
867
|
const invalid = validateTool(tool);
|
|
805
868
|
if (invalid !== void 0) continue;
|
|
806
869
|
const definition = createToolDefinition(entry.name, tool, client);
|
|
@@ -811,23 +874,49 @@ function createRuntime(ctx) {
|
|
|
811
874
|
}
|
|
812
875
|
}
|
|
813
876
|
};
|
|
877
|
+
const alive = (entry) => entry.disposed !== true && live.servers.get(entry.name) === entry;
|
|
814
878
|
const sync = (entry) => {
|
|
815
879
|
if (entry.sync !== void 0) return entry.sync;
|
|
880
|
+
if (entry.endpoint === "" || entry.enabled === false) return Promise.resolve(false);
|
|
816
881
|
const run = (async () => {
|
|
817
|
-
|
|
818
|
-
const client = await connectMcp(entry.endpoint, entry.headers, live.timeoutMs);
|
|
882
|
+
const generation = entry.generation ?? 0;
|
|
819
883
|
try {
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
entry.
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
884
|
+
if (entry.endpoint === "" || entry.enabled === false) return false;
|
|
885
|
+
const timeout = entry.timeoutMs > 0 ? entry.timeoutMs : live.timeoutMs;
|
|
886
|
+
const client = await connectMcp(entry.endpoint, entry.headers, timeout);
|
|
887
|
+
if (!alive(entry) || (entry.generation ?? 0) !== generation) {
|
|
888
|
+
await client.close().catch(() => {
|
|
889
|
+
});
|
|
890
|
+
return false;
|
|
891
|
+
}
|
|
892
|
+
const previous = entry.client;
|
|
893
|
+
entry.client = client;
|
|
894
|
+
if (previous !== void 0 && previous !== client) void previous.close().catch(() => {
|
|
895
|
+
});
|
|
896
|
+
try {
|
|
897
|
+
const tools = await client.listTools();
|
|
898
|
+
if (!alive(entry) || (entry.generation ?? 0) !== generation) return false;
|
|
899
|
+
const names = new Set(tools.map((tool) => tool.name));
|
|
900
|
+
const keep = (list) => (list ?? []).filter((name2) => names.has(name2));
|
|
901
|
+
entry.settings = {
|
|
902
|
+
disabled: keep(entry.settings.disabled),
|
|
903
|
+
hidden: keep(entry.settings.hidden),
|
|
904
|
+
removed: keep(entry.settings.removed),
|
|
905
|
+
overrides: Object.fromEntries(Object.entries(entry.settings.overrides ?? {}).filter(([name2]) => names.has(name2)))
|
|
906
|
+
};
|
|
907
|
+
disposeTools(entry);
|
|
908
|
+
registerTools(entry, tools, client);
|
|
909
|
+
entry.connected = true;
|
|
910
|
+
entry.toolCount = entry.tools.size;
|
|
911
|
+
entry.catalog = buildCatalog(entry.name, tools, (raw) => publicToolName(entry.name, raw), entry.settings);
|
|
912
|
+
entry.lastError = "";
|
|
913
|
+
entry.attempts = 0;
|
|
914
|
+
live.version += 1;
|
|
915
|
+
beacon("discovered " + entry.name + " tools=" + tools.length);
|
|
916
|
+
return true;
|
|
917
|
+
} catch (error) {
|
|
918
|
+
throw error;
|
|
919
|
+
}
|
|
831
920
|
} catch (error) {
|
|
832
921
|
entry.connected = false;
|
|
833
922
|
entry.lastError = String(error?.message ?? error);
|
|
@@ -837,6 +926,12 @@ function createRuntime(ctx) {
|
|
|
837
926
|
return false;
|
|
838
927
|
} finally {
|
|
839
928
|
entry.sync = void 0;
|
|
929
|
+
if (entry.stale === true && alive(entry) && entry.endpoint !== "") {
|
|
930
|
+
entry.stale = false;
|
|
931
|
+
void sync(entry).then((ok) => {
|
|
932
|
+
if (!ok && alive(entry)) scheduleRetry(entry);
|
|
933
|
+
});
|
|
934
|
+
}
|
|
840
935
|
}
|
|
841
936
|
})();
|
|
842
937
|
entry.sync = run;
|
|
@@ -853,9 +948,9 @@ function createRuntime(ctx) {
|
|
|
853
948
|
entry.retryTimer = setInterval(() => {
|
|
854
949
|
entry.attempts += 1;
|
|
855
950
|
void sync(entry).then((ok) => {
|
|
856
|
-
if (ok || entry.attempts >=
|
|
951
|
+
if (ok || entry.attempts >= live.maxRetries) stopRetry(entry);
|
|
857
952
|
});
|
|
858
|
-
},
|
|
953
|
+
}, live.retryIntervalMs);
|
|
859
954
|
};
|
|
860
955
|
return { disposeTools, registerTools, sync, scheduleRetry, stopRetry };
|
|
861
956
|
}
|
|
@@ -871,24 +966,37 @@ function installRoutes(ctx) {
|
|
|
871
966
|
const installed = shared.__GENMCP_ROUTES__ ??= /* @__PURE__ */ new WeakMap();
|
|
872
967
|
if (installed.get(webServer) === true) return;
|
|
873
968
|
installed.set(webServer, true);
|
|
874
|
-
const
|
|
969
|
+
const trusted = (req) => {
|
|
875
970
|
const headers = req.headers ?? {};
|
|
876
|
-
if (headers
|
|
877
|
-
const origin = headers.origin;
|
|
878
|
-
const host = headers.host;
|
|
879
|
-
if (
|
|
971
|
+
if ((headers.authorization ?? "") === "Bearer " + live.token) return true;
|
|
972
|
+
const origin = typeof headers.origin === "string" ? headers.origin : "";
|
|
973
|
+
const host = typeof headers.host === "string" ? headers.host : "";
|
|
974
|
+
if (origin === "") return true;
|
|
975
|
+
if (origin.startsWith("dsh-app:") || origin.startsWith("file:")) return true;
|
|
976
|
+
const loopback = /^(127\.0\.0\.1|localhost|\[::1\])(:|$)/;
|
|
880
977
|
try {
|
|
881
|
-
|
|
978
|
+
const originHost = new URL(origin).host;
|
|
979
|
+
if (host !== "" && originHost === host) return true;
|
|
980
|
+
if (loopback.test(originHost) && loopback.test(host)) return true;
|
|
882
981
|
} catch {
|
|
883
|
-
return false;
|
|
884
982
|
}
|
|
983
|
+
return false;
|
|
885
984
|
};
|
|
886
|
-
const authorized = (req) =>
|
|
887
|
-
|
|
888
|
-
|
|
985
|
+
const authorized = (req) => trusted(req);
|
|
986
|
+
const cors = (req) => {
|
|
987
|
+
const headers = req.headers ?? {};
|
|
988
|
+
const origin = typeof headers.origin === "string" ? headers.origin : "";
|
|
989
|
+
const out = {
|
|
990
|
+
"access-control-allow-methods": "GET, POST, OPTIONS",
|
|
991
|
+
"access-control-allow-headers": "content-type, authorization",
|
|
992
|
+
"access-control-max-age": "600",
|
|
993
|
+
vary: "origin"
|
|
994
|
+
};
|
|
995
|
+
if (origin !== "") out["access-control-allow-origin"] = origin;
|
|
996
|
+
return out;
|
|
889
997
|
};
|
|
890
|
-
const send = (res, status, payload) => {
|
|
891
|
-
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
998
|
+
const send = (res, status, payload, extra = {}) => {
|
|
999
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...extra });
|
|
892
1000
|
res.end(JSON.stringify(payload));
|
|
893
1001
|
};
|
|
894
1002
|
const readBody = (req, limit = 256 * 1024) => new Promise((resolve, reject) => {
|
|
@@ -919,34 +1027,56 @@ function installRoutes(ctx) {
|
|
|
919
1027
|
kind: "exact",
|
|
920
1028
|
path: "/api/general-mcp/catalog",
|
|
921
1029
|
resource: async (request) => {
|
|
922
|
-
const
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
1030
|
+
const hdr = {
|
|
1031
|
+
authorization: request.headers?.get?.("authorization") ?? "",
|
|
1032
|
+
origin: request.headers?.get?.("origin") ?? "",
|
|
1033
|
+
host: request.headers?.get?.("host") ?? ""
|
|
1034
|
+
};
|
|
1035
|
+
const allowed = cors(hdr);
|
|
1036
|
+
if (request.method === "OPTIONS") {
|
|
1037
|
+
return new Response(null, { status: 204, headers: { ...allowed, "cache-control": "no-store" } });
|
|
1038
|
+
}
|
|
1039
|
+
if (!trusted(hdr)) {
|
|
1040
|
+
return new Response("unauthorized", { status: 401, headers: { ...allowed, "cache-control": "no-store" } });
|
|
927
1041
|
}
|
|
928
1042
|
const url = new URL(request.url);
|
|
929
1043
|
const raw = url.searchParams.get("since");
|
|
930
1044
|
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" } });
|
|
1045
|
+
if (since === live.version) return new Response(null, { status: 304, headers: { ...allowed, "cache-control": "no-store" } });
|
|
932
1046
|
return new Response(JSON.stringify({
|
|
933
1047
|
version: live.version,
|
|
1048
|
+
timeoutMs: live.timeoutMs,
|
|
1049
|
+
retryIntervalMs: live.retryIntervalMs,
|
|
1050
|
+
maxRetries: live.maxRetries,
|
|
1051
|
+
pollIntervalMs: live.pollIntervalMs,
|
|
1052
|
+
debug: live.debug,
|
|
934
1053
|
servers: [...live.servers.values()].map((entry) => ({
|
|
935
1054
|
name: entry.name,
|
|
936
1055
|
endpoint: entry.endpoint,
|
|
937
|
-
status: entry.connected ? "connected" : "idle",
|
|
1056
|
+
status: entry.connected ? "connected" : entry.enabled === false ? "disabled" : "idle",
|
|
1057
|
+
enabled: entry.enabled,
|
|
1058
|
+
timeoutMs: entry.timeoutMs,
|
|
1059
|
+
// Never ship header values to the page; names are enough to edit them.
|
|
1060
|
+
headerNames: Object.keys(entry.headers),
|
|
938
1061
|
lastError: entry.lastError,
|
|
939
1062
|
toolCount: entry.toolCount,
|
|
940
1063
|
tools: entry.catalog,
|
|
941
1064
|
settings: entry.settings
|
|
942
1065
|
}))
|
|
943
|
-
}), { status: 200, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
|
|
1066
|
+
}), { status: 200, headers: { ...allowed, "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
|
|
944
1067
|
}
|
|
945
1068
|
});
|
|
946
1069
|
webServer.register({
|
|
947
1070
|
kind: "exact",
|
|
948
1071
|
path: "/api/general-mcp/probe",
|
|
949
1072
|
handler: (req, res) => {
|
|
1073
|
+
const extra = cors(req);
|
|
1074
|
+
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value);
|
|
1075
|
+
if (req.method === "OPTIONS") {
|
|
1076
|
+
res.writeHead(204);
|
|
1077
|
+
res.end();
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
950
1080
|
void (async () => {
|
|
951
1081
|
try {
|
|
952
1082
|
if (!authorized(req)) {
|
|
@@ -968,6 +1098,7 @@ function installRoutes(ctx) {
|
|
|
968
1098
|
ok: true,
|
|
969
1099
|
protocolVersion: probe.protocolVersion ?? null,
|
|
970
1100
|
transport: probe.transport,
|
|
1101
|
+
detail: probe.detail ?? null,
|
|
971
1102
|
server: probe.serverInfo?.name ?? null,
|
|
972
1103
|
version: probe.serverInfo?.version ?? null,
|
|
973
1104
|
tools: tools.map((tool) => ({ name: tool.name, description: tool.description ?? "", folder: tool._meta?.["dsh/folder"] ?? null }))
|
|
@@ -982,6 +1113,13 @@ function installRoutes(ctx) {
|
|
|
982
1113
|
kind: "exact",
|
|
983
1114
|
path: "/api/general-mcp/config",
|
|
984
1115
|
handler: (req, res) => {
|
|
1116
|
+
const extra = cors(req);
|
|
1117
|
+
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value);
|
|
1118
|
+
if (req.method === "OPTIONS") {
|
|
1119
|
+
res.writeHead(204);
|
|
1120
|
+
res.end();
|
|
1121
|
+
return;
|
|
1122
|
+
}
|
|
985
1123
|
void (async () => {
|
|
986
1124
|
try {
|
|
987
1125
|
if (!authorized(req)) {
|
|
@@ -989,11 +1127,65 @@ function installRoutes(ctx) {
|
|
|
989
1127
|
return;
|
|
990
1128
|
}
|
|
991
1129
|
const body = await readBody(req);
|
|
992
|
-
const
|
|
993
|
-
if (
|
|
1130
|
+
const incoming = Array.isArray(body.servers) ? body.servers : void 0;
|
|
1131
|
+
if (incoming === void 0) throw new Error("body.servers must be an array");
|
|
1132
|
+
const removed = new Set(Array.isArray(body.removed) ? body.removed.filter((n) => typeof n === "string") : []);
|
|
1133
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1134
|
+
for (const item of incoming) {
|
|
1135
|
+
const name2 = String(item.name ?? "general");
|
|
1136
|
+
if (!/^[A-Za-z0-9_-]{1,32}$/.test(name2)) throw new Error('\u7F51\u5173\u540D "' + name2 + '" \u975E\u6CD5');
|
|
1137
|
+
if (seen.has(name2)) throw new Error('\u7F51\u5173\u540D "' + name2 + '" \u91CD\u590D');
|
|
1138
|
+
const endpoint = item.endpoint;
|
|
1139
|
+
if (endpoint !== void 0 && endpoint !== null && endpoint !== "" && !/^https?:\/\//i.test(String(endpoint))) {
|
|
1140
|
+
throw new Error('\u7F51\u5173 "' + name2 + '" \u7684\u5730\u5740\u5FC5\u987B\u4EE5 http(s):// \u5F00\u5934');
|
|
1141
|
+
}
|
|
1142
|
+
seen.add(name2);
|
|
1143
|
+
}
|
|
994
1144
|
const { editor, entry } = findEntry();
|
|
995
|
-
await editor.edit(entry, (current) =>
|
|
996
|
-
|
|
1145
|
+
await editor.edit(entry, (current) => {
|
|
1146
|
+
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 }] : [];
|
|
1147
|
+
const byName = /* @__PURE__ */ new Map();
|
|
1148
|
+
for (const item of existing) byName.set(String(item.name ?? "general"), item);
|
|
1149
|
+
for (const item of incoming) {
|
|
1150
|
+
const name2 = String(item.name ?? "general");
|
|
1151
|
+
if (removed.has(name2)) continue;
|
|
1152
|
+
const previous = byName.get(name2) ?? {};
|
|
1153
|
+
const hasEndpoint = typeof item.endpoint === "string";
|
|
1154
|
+
const endpoint2 = hasEndpoint ? item.endpoint.trim() : previous.endpoint ?? "";
|
|
1155
|
+
const sameEndpoint = (previous.endpoint ?? "") === endpoint2;
|
|
1156
|
+
const next2 = { ...previous, ...item, name: name2, endpoint: endpoint2 };
|
|
1157
|
+
if (!sameEndpoint) delete next2.tools;
|
|
1158
|
+
if (item.headersPatch !== null && typeof item.headersPatch === "object" && !Array.isArray(item.headersPatch)) {
|
|
1159
|
+
const headers2 = { ...previous.headers ?? {} };
|
|
1160
|
+
for (const [key, value] of Object.entries(item.headersPatch)) {
|
|
1161
|
+
if (value === null) delete headers2[key];
|
|
1162
|
+
else if (typeof value === "string") headers2[key] = value;
|
|
1163
|
+
}
|
|
1164
|
+
next2.headers = headers2;
|
|
1165
|
+
}
|
|
1166
|
+
delete next2.headersPatch;
|
|
1167
|
+
byName.set(name2, next2);
|
|
1168
|
+
}
|
|
1169
|
+
for (const name2 of removed) byName.delete(name2);
|
|
1170
|
+
const servers = [...byName.values()];
|
|
1171
|
+
const { serverName, endpoint, headers, tools, ...rest } = current;
|
|
1172
|
+
const next = { ...rest, servers };
|
|
1173
|
+
const knobs = [
|
|
1174
|
+
["toolCallTimeoutMs", 1e3, 6e5],
|
|
1175
|
+
["retryIntervalMs", 5e3, 6e5],
|
|
1176
|
+
["pollIntervalMs", 2e3, 6e5],
|
|
1177
|
+
["maxRetries", 0, 1e3]
|
|
1178
|
+
];
|
|
1179
|
+
for (const [key, min, max] of knobs) {
|
|
1180
|
+
const value = body[key];
|
|
1181
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
1182
|
+
next[key] = Math.min(Math.max(Math.round(value), min), max);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
if (typeof body.debug === "boolean") next.debug = body.debug;
|
|
1186
|
+
return next;
|
|
1187
|
+
});
|
|
1188
|
+
beacon("config-saved servers=" + incoming.length + " removed=" + removed.size);
|
|
997
1189
|
send(res, 200, { ok: true });
|
|
998
1190
|
} catch (error) {
|
|
999
1191
|
beacon("config-save-error " + String(error));
|
|
@@ -1006,6 +1198,13 @@ function installRoutes(ctx) {
|
|
|
1006
1198
|
kind: "exact",
|
|
1007
1199
|
path: "/api/general-mcp/tools",
|
|
1008
1200
|
handler: (req, res) => {
|
|
1201
|
+
const extra = cors(req);
|
|
1202
|
+
for (const [key, value] of Object.entries(extra)) res.setHeader(key, value);
|
|
1203
|
+
if (req.method === "OPTIONS") {
|
|
1204
|
+
res.writeHead(204);
|
|
1205
|
+
res.end();
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1009
1208
|
void (async () => {
|
|
1010
1209
|
try {
|
|
1011
1210
|
if (!authorized(req)) {
|
|
@@ -1014,18 +1213,20 @@ function installRoutes(ctx) {
|
|
|
1014
1213
|
}
|
|
1015
1214
|
const body = await readBody(req);
|
|
1016
1215
|
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
1216
|
const { editor, entry } = findEntry();
|
|
1023
1217
|
await editor.edit(entry, (current) => {
|
|
1024
|
-
const list = Array.isArray(current.servers)
|
|
1218
|
+
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
1219
|
const index = list.findIndex((item) => (item.name ?? "general") === server);
|
|
1026
|
-
if (index
|
|
1027
|
-
|
|
1028
|
-
|
|
1220
|
+
if (index < 0) throw new Error("\u7F51\u5173 " + server + " \u4E0D\u5B58\u5728\uFF0C\u5DE5\u5177\u8BBE\u7F6E\u672A\u4FDD\u5B58");
|
|
1221
|
+
const previous = list[index].tools ?? {};
|
|
1222
|
+
const next = { ...previous };
|
|
1223
|
+
if (Array.isArray(body.disabled)) next.disabled = body.disabled.filter((v) => typeof v === "string");
|
|
1224
|
+
if (Array.isArray(body.hidden)) next.hidden = body.hidden.filter((v) => typeof v === "string");
|
|
1225
|
+
if (Array.isArray(body.removed)) next.removed = body.removed.filter((v) => typeof v === "string");
|
|
1226
|
+
if (body.overrides !== null && typeof body.overrides === "object" && !Array.isArray(body.overrides)) next.overrides = body.overrides;
|
|
1227
|
+
list[index] = { ...list[index], tools: next };
|
|
1228
|
+
const { serverName, endpoint, headers, tools, ...rest } = current;
|
|
1229
|
+
return { ...rest, servers: list };
|
|
1029
1230
|
});
|
|
1030
1231
|
beacon("tools-saved " + server);
|
|
1031
1232
|
send(res, 200, { ok: true });
|
|
@@ -1087,7 +1288,7 @@ function registerStatusTool(ctx) {
|
|
|
1087
1288
|
additionalProperties: false
|
|
1088
1289
|
},
|
|
1089
1290
|
render(_args, value) {
|
|
1090
|
-
const lines = (value.servers ?? []).map((item) => item.name + ": " + (item.connected ? "connected" : "idle") + " tools=" + item.toolCount + (item.lastError === "" ? "" : " error=" + item.lastError));
|
|
1291
|
+
const lines = (value.servers ?? []).map((item) => item.name + ": " + (item.connected ? "connected" : item.enabled === false ? "disabled" : "idle") + " tools=" + item.toolCount + (item.timeoutMs > 0 ? " timeout=" + item.timeoutMs + "ms" : "") + (item.lastError === "" ? "" : " error=" + item.lastError));
|
|
1091
1292
|
return [{ type: "text", text: "general-mcp" + (lines.length === 0 ? " (no gateways)" : "\n" + lines.join("\n")) }];
|
|
1092
1293
|
}
|
|
1093
1294
|
},
|
|
@@ -1096,6 +1297,8 @@ function registerStatusTool(ctx) {
|
|
|
1096
1297
|
name: entry.name,
|
|
1097
1298
|
endpoint: entry.endpoint,
|
|
1098
1299
|
connected: entry.connected,
|
|
1300
|
+
enabled: entry.enabled,
|
|
1301
|
+
timeoutMs: entry.timeoutMs,
|
|
1099
1302
|
toolCount: entry.toolCount,
|
|
1100
1303
|
lastError: entry.lastError,
|
|
1101
1304
|
disabled: entry.settings.disabled ?? [],
|