@momeidejiyi/dsh-general-mcp 0.1.8 → 0.2.0
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 +154 -49
- package/package.json +1 -1
- package/src/catalog.ts +62 -23
- package/src/connect.ts +4 -0
- package/src/index.ts +93 -16
- package/src/register.ts +2 -3
- package/src/sse.ts +40 -3
package/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @momeidejiyi/dsh-general-mcp@0.
|
|
1
|
+
// @momeidejiyi/dsh-general-mcp@0.2.0 (generated)
|
|
2
2
|
|
|
3
3
|
// packages/general-mcp/src/index.ts
|
|
4
4
|
import { appendFileSync } from "node:fs";
|
|
@@ -23,29 +23,53 @@ function validateTool(tool) {
|
|
|
23
23
|
if (typeof tool.name !== "string" || !NAME_PATTERN.test(tool.name)) {
|
|
24
24
|
return { code: "name", message: "name \u5FC5\u987B\u5339\u914D " + NAME_PATTERN.source };
|
|
25
25
|
}
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
function inputSchemaOf(tool) {
|
|
29
|
+
let value = tool.inputSchema;
|
|
30
|
+
if (typeof value === "string") {
|
|
31
|
+
try {
|
|
32
|
+
value = JSON.parse(value);
|
|
33
|
+
} catch {
|
|
34
|
+
value = void 0;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (value === void 0 || value === null) {
|
|
38
|
+
return { schema: { type: "object", properties: {} }, warning: { code: "input-schema", message: "\u7F3A\u5C11 inputSchema\uFF0C\u6309\u65E0\u53C2\u6570\u5DE5\u5177\u5904\u7406" } };
|
|
39
|
+
}
|
|
40
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
41
|
+
return { schema: { type: "object", properties: {} }, warning: { code: "input-schema", message: "inputSchema \u4E0D\u662F\u5BF9\u8C61\uFF0C\u6309\u65E0\u53C2\u6570\u5DE5\u5177\u5904\u7406" } };
|
|
28
42
|
}
|
|
29
|
-
const
|
|
30
|
-
if (
|
|
31
|
-
return { code: "input-schema", message:
|
|
43
|
+
const type = value.type;
|
|
44
|
+
if (type !== void 0 && type !== "object") {
|
|
45
|
+
return { schema: { type: "object", properties: {} }, warning: { code: "input-schema", message: "inputSchema.type \u4E0D\u662F object\uFF0C\u6309\u65E0\u53C2\u6570\u5DE5\u5177\u5904\u7406" } };
|
|
32
46
|
}
|
|
47
|
+
return { schema: { type: "object", properties: {}, ...value } };
|
|
48
|
+
}
|
|
49
|
+
function toolWarnings(tool) {
|
|
50
|
+
const out = [];
|
|
51
|
+
if (typeof tool.description !== "string" || tool.description.trim() === "") {
|
|
52
|
+
out.push({ code: "description", message: "\u7F3A\u5C11 description\uFF0C\u7528\u5DE5\u5177\u540D\u4EE3\u66FF" });
|
|
53
|
+
}
|
|
54
|
+
const schema = inputSchemaOf(tool).warning;
|
|
55
|
+
if (schema !== void 0) out.push(schema);
|
|
33
56
|
const meta = tool._meta ?? {};
|
|
34
57
|
const folder = meta[CANONICAL_FOLDER];
|
|
35
58
|
if (folder !== void 0) {
|
|
36
59
|
if (!isStringArray(folder) || folder.length === 0 || folder.length > MAX_FOLDER_DEPTH) {
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
return { code: "folder", message: '_meta["dsh/folder"] \u6BB5 "' + bad + '" \u975E\u6CD5\uFF08\u4E0D\u80FD\u542B / \u6216 .\uFF0C\u957F\u5EA6 1..64\uFF09' };
|
|
60
|
+
out.push({ code: "folder", message: '_meta["dsh/folder"] \u5FC5\u987B\u662F 1..8 \u4E2A\u5B57\u7B26\u4E32\u7684\u6570\u7EC4\uFF0C\u5DF2\u5FFD\u7565' });
|
|
61
|
+
} else {
|
|
62
|
+
const bad = folder.find((segment) => !SEGMENT_PATTERN.test(segment));
|
|
63
|
+
if (bad !== void 0) out.push({ code: "folder", message: '_meta["dsh/folder"] \u6BB5 "' + bad + '" \u975E\u6CD5\uFF0C\u5DF2\u5FFD\u7565' });
|
|
42
64
|
}
|
|
43
65
|
}
|
|
44
66
|
const title = meta[CANONICAL_TITLE];
|
|
45
67
|
if (title !== void 0 && (typeof title !== "string" || title.length > MAX_TITLE)) {
|
|
46
|
-
|
|
68
|
+
out.push({ code: "title", message: '_meta["dsh/title"] \u5FC5\u987B\u662F\u4E0D\u8D85\u8FC7 ' + MAX_TITLE + " \u5B57\u7684\u5B57\u7B26\u4E32\uFF0C\u5DF2\u622A\u65AD" });
|
|
47
69
|
}
|
|
48
|
-
|
|
70
|
+
const alias = aliasWarning(tool);
|
|
71
|
+
if (alias !== void 0) out.push(alias);
|
|
72
|
+
return out;
|
|
49
73
|
}
|
|
50
74
|
function aliasWarning(tool) {
|
|
51
75
|
const meta = tool._meta ?? {};
|
|
@@ -54,15 +78,19 @@ function aliasWarning(tool) {
|
|
|
54
78
|
if (used.length === 0) return void 0;
|
|
55
79
|
return { code: "alias", message: "\u4F7F\u7528\u4E86\u975E\u89C4\u8303\u5B57\u6BB5 " + used.join(", ") + '\uFF0C\u8BF7\u6539\u7528 _meta["dsh/folder"] / _meta["dsh/title"]' };
|
|
56
80
|
}
|
|
81
|
+
function usableFolder(value) {
|
|
82
|
+
if (!isStringArray(value) || value.length === 0 || value.length > MAX_FOLDER_DEPTH) return void 0;
|
|
83
|
+
return value.every((segment) => SEGMENT_PATTERN.test(segment)) ? value : void 0;
|
|
84
|
+
}
|
|
57
85
|
function folderFromMeta(tool) {
|
|
58
86
|
const meta = tool._meta ?? {};
|
|
59
|
-
const canonical = meta[CANONICAL_FOLDER];
|
|
60
|
-
if (
|
|
87
|
+
const canonical = usableFolder(meta[CANONICAL_FOLDER]);
|
|
88
|
+
if (canonical !== void 0) return canonical;
|
|
61
89
|
for (const key of ALIAS_NAMESPACES) {
|
|
62
90
|
const nested = meta[key];
|
|
63
91
|
if (nested === null || typeof nested !== "object") continue;
|
|
64
|
-
const inner = nested.folder;
|
|
65
|
-
if (
|
|
92
|
+
const inner = usableFolder(nested.folder);
|
|
93
|
+
if (inner !== void 0) return inner;
|
|
66
94
|
}
|
|
67
95
|
return void 0;
|
|
68
96
|
}
|
|
@@ -85,14 +113,16 @@ function buildCatalog(serverName, tools, publicName, settings = {}) {
|
|
|
85
113
|
return tools.map((tool) => {
|
|
86
114
|
const override = settings.overrides?.[tool.name];
|
|
87
115
|
const invalid = validateTool(tool);
|
|
88
|
-
const
|
|
116
|
+
const warnings = toolWarnings(tool);
|
|
117
|
+
const schema = inputSchemaOf(tool).schema;
|
|
89
118
|
const folder = (override?.folder ?? folderFromMeta(tool) ?? folderFromName(tool.name)).map(slug).filter(Boolean);
|
|
90
119
|
const leaf = slug(tool.name.split(/[./]/).pop() ?? tool.name) || "tool";
|
|
91
120
|
const path = [...folder, leaf].join("/");
|
|
92
|
-
const metaTitle = typeof tool._meta?.[CANONICAL_TITLE] === "string" ? String(tool._meta[CANONICAL_TITLE]) : void 0;
|
|
121
|
+
const metaTitle = typeof tool._meta?.[CANONICAL_TITLE] === "string" ? String(tool._meta[CANONICAL_TITLE]).slice(0, MAX_TITLE) : void 0;
|
|
93
122
|
const annotationTitle = typeof tool.annotations?.title === "string" ? tool.annotations.title : void 0;
|
|
94
123
|
const title = override?.title ?? tool.title ?? annotationTitle ?? metaTitle;
|
|
95
|
-
const
|
|
124
|
+
const described = typeof tool.description === "string" && tool.description.trim() !== "";
|
|
125
|
+
const description = described ? tool.description : tool.name;
|
|
96
126
|
return {
|
|
97
127
|
toolName: publicName(tool.name),
|
|
98
128
|
server: serverName,
|
|
@@ -102,14 +132,14 @@ function buildCatalog(serverName, tools, publicName, settings = {}) {
|
|
|
102
132
|
folder,
|
|
103
133
|
...title === void 0 ? {} : { title },
|
|
104
134
|
description,
|
|
105
|
-
inputSchema:
|
|
135
|
+
inputSchema: schema,
|
|
106
136
|
...tool.outputSchema === void 0 ? {} : { outputSchema: tool.outputSchema },
|
|
107
|
-
hash: shortHash(description + JSON.stringify(
|
|
137
|
+
hash: shortHash(description + JSON.stringify(schema) + JSON.stringify(folder)),
|
|
108
138
|
disabled: disabled.has(tool.name),
|
|
109
139
|
hidden: hidden.has(tool.name),
|
|
110
140
|
...removed.has(tool.name) ? { removed: true } : {},
|
|
111
141
|
...invalid !== void 0 ? { invalid } : {},
|
|
112
|
-
...invalid === void 0 &&
|
|
142
|
+
...invalid === void 0 && warnings.length > 0 ? { warning: { code: warnings[0].code, message: warnings.map((item) => item.message).join("\uFF1B") } } : {}
|
|
113
143
|
};
|
|
114
144
|
});
|
|
115
145
|
}
|
|
@@ -325,6 +355,27 @@ async function readSseResult(response, id) {
|
|
|
325
355
|
}
|
|
326
356
|
|
|
327
357
|
// packages/general-mcp/src/sse.ts
|
|
358
|
+
function isLocalHost(hostname) {
|
|
359
|
+
const host = hostname.toLowerCase();
|
|
360
|
+
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);
|
|
361
|
+
}
|
|
362
|
+
function resolveMessageUrl(endpoint, sseUrl) {
|
|
363
|
+
let target;
|
|
364
|
+
let sse;
|
|
365
|
+
try {
|
|
366
|
+
sse = new URL(sseUrl);
|
|
367
|
+
target = new URL(endpoint, sseUrl);
|
|
368
|
+
} catch {
|
|
369
|
+
return endpoint;
|
|
370
|
+
}
|
|
371
|
+
if (target.origin !== sse.origin && isLocalHost(target.hostname)) {
|
|
372
|
+
target.protocol = sse.protocol;
|
|
373
|
+
target.hostname = sse.hostname;
|
|
374
|
+
target.port = sse.port;
|
|
375
|
+
return target.toString();
|
|
376
|
+
}
|
|
377
|
+
return target.toString();
|
|
378
|
+
}
|
|
328
379
|
var SseClient = class {
|
|
329
380
|
constructor(url, headers = {}, timeoutMs = 6e4) {
|
|
330
381
|
this.url = url;
|
|
@@ -341,6 +392,10 @@ var SseClient = class {
|
|
|
341
392
|
get protocolVersion() {
|
|
342
393
|
return "2024-11-05";
|
|
343
394
|
}
|
|
395
|
+
/** Where requests are POSTed; useful in diagnostics. */
|
|
396
|
+
get messageEndpoint() {
|
|
397
|
+
return this.messageUrl;
|
|
398
|
+
}
|
|
344
399
|
/** Open the stream and wait for the endpoint announcement. */
|
|
345
400
|
connect() {
|
|
346
401
|
if (this.connected !== void 0) return this.connected;
|
|
@@ -351,7 +406,7 @@ var SseClient = class {
|
|
|
351
406
|
if (response.body === null) throw new Error("SSE connect returned no body");
|
|
352
407
|
this.reader = response.body.getReader();
|
|
353
408
|
const announced = new Promise((resolve, reject) => {
|
|
354
|
-
const timer = setTimeout(() => reject(new Error("SSE endpoint event timed out")), this.timeoutMs);
|
|
409
|
+
const timer = setTimeout(() => reject(new Error("SSE endpoint event timed out after " + this.timeoutMs + "ms (GET " + this.url + ")")), this.timeoutMs);
|
|
355
410
|
this.endpointWaiter = { resolve, reject, timer };
|
|
356
411
|
});
|
|
357
412
|
void this.pump();
|
|
@@ -389,11 +444,7 @@ var SseClient = class {
|
|
|
389
444
|
}
|
|
390
445
|
const payload = data.join("\n");
|
|
391
446
|
if (event === "endpoint") {
|
|
392
|
-
|
|
393
|
-
this.messageUrl = new URL(payload, this.url).toString();
|
|
394
|
-
} catch {
|
|
395
|
-
this.messageUrl = payload;
|
|
396
|
-
}
|
|
447
|
+
this.messageUrl = resolveMessageUrl(payload, this.url);
|
|
397
448
|
const waiter = this.endpointWaiter;
|
|
398
449
|
this.endpointWaiter = void 0;
|
|
399
450
|
if (waiter !== void 0) {
|
|
@@ -450,7 +501,7 @@ var SseClient = class {
|
|
|
450
501
|
const reply = new Promise((resolve, reject) => {
|
|
451
502
|
const timer = setTimeout(() => {
|
|
452
503
|
this.pending.delete(id);
|
|
453
|
-
reject(new Error("MCP " + method + " timed out after " + this.timeoutMs + "ms"));
|
|
504
|
+
reject(new Error("MCP " + method + " timed out after " + this.timeoutMs + "ms (POST " + this.messageUrl + ")"));
|
|
454
505
|
}, this.timeoutMs);
|
|
455
506
|
this.pending.set(id, { resolve, reject, timer });
|
|
456
507
|
});
|
|
@@ -530,6 +581,7 @@ async function viaStreamable(url, headers, timeoutMs) {
|
|
|
530
581
|
const info = await client.initialize();
|
|
531
582
|
return {
|
|
532
583
|
transport: "streamable",
|
|
584
|
+
detail: "POST " + url,
|
|
533
585
|
protocolVersion: info?.protocolVersion,
|
|
534
586
|
serverInfo: info?.serverInfo,
|
|
535
587
|
async initialize() {
|
|
@@ -544,6 +596,7 @@ async function viaSse(url, headers, timeoutMs) {
|
|
|
544
596
|
const info = await client.initialize();
|
|
545
597
|
return {
|
|
546
598
|
transport: "sse",
|
|
599
|
+
detail: "GET " + url + " \u2192 POST " + (client.messageEndpoint ?? "(pending)"),
|
|
547
600
|
protocolVersion: info?.protocolVersion,
|
|
548
601
|
serverInfo: info?.serverInfo,
|
|
549
602
|
async initialize() {
|
|
@@ -621,7 +674,7 @@ function textOf(blocks) {
|
|
|
621
674
|
return blocks.map((block) => block.text).join("\n");
|
|
622
675
|
}
|
|
623
676
|
function createToolDefinition(serverName, tool, client) {
|
|
624
|
-
const parameters = tool.
|
|
677
|
+
const parameters = inputSchemaOf(tool).schema;
|
|
625
678
|
return {
|
|
626
679
|
name: publicToolName(serverName, tool.name),
|
|
627
680
|
description: tool.description ?? tool.name,
|
|
@@ -668,7 +721,10 @@ function state() {
|
|
|
668
721
|
servers: /* @__PURE__ */ new Map(),
|
|
669
722
|
version: 0,
|
|
670
723
|
debug: false,
|
|
671
|
-
timeoutMs: 6e4
|
|
724
|
+
timeoutMs: 6e4,
|
|
725
|
+
retryIntervalMs: 3e4,
|
|
726
|
+
maxRetries: 20,
|
|
727
|
+
pollIntervalMs: 15e3
|
|
672
728
|
};
|
|
673
729
|
}
|
|
674
730
|
return shared.__GENMCP_STATE__;
|
|
@@ -687,7 +743,9 @@ function serverState(name2) {
|
|
|
687
743
|
catalog: [],
|
|
688
744
|
tools: /* @__PURE__ */ new Map(),
|
|
689
745
|
settings: {},
|
|
690
|
-
attempts: 0
|
|
746
|
+
attempts: 0,
|
|
747
|
+
enabled: true,
|
|
748
|
+
timeoutMs: 0
|
|
691
749
|
};
|
|
692
750
|
live.servers.set(name2, entry);
|
|
693
751
|
}
|
|
@@ -718,8 +776,11 @@ function normalizeSettings(raw) {
|
|
|
718
776
|
function normalizeConfig(config) {
|
|
719
777
|
const raw = config ?? {};
|
|
720
778
|
const live = state();
|
|
721
|
-
const
|
|
722
|
-
live.timeoutMs =
|
|
779
|
+
const clamp = (value, fallback, min, max) => typeof value === "number" && Number.isFinite(value) ? Math.min(Math.max(Math.round(value), min), max) : fallback;
|
|
780
|
+
live.timeoutMs = clamp(raw.toolCallTimeoutMs, 6e4, 1e3, 6e5);
|
|
781
|
+
live.retryIntervalMs = clamp(raw.retryIntervalMs, 3e4, 5e3, 6e5);
|
|
782
|
+
live.maxRetries = clamp(raw.maxRetries, 20, 0, 1e3);
|
|
783
|
+
live.pollIntervalMs = clamp(raw.pollIntervalMs, 15e3, 2e3, 6e5);
|
|
723
784
|
live.debug = raw.debug === true;
|
|
724
785
|
const list = Array.isArray(raw.servers) ? raw.servers.map((item) => ({ ...item })) : [{ name: raw.serverName, endpoint: raw.endpoint, headers: raw.headers, tools: raw.tools }];
|
|
725
786
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -763,9 +824,13 @@ function apply(ctx, config) {
|
|
|
763
824
|
if (typeof value === "string") headers[key] = value;
|
|
764
825
|
}
|
|
765
826
|
}
|
|
766
|
-
const
|
|
827
|
+
const enabled = item.enabled !== false;
|
|
828
|
+
const serverTimeout = typeof item.timeoutMs === "number" && Number.isFinite(item.timeoutMs) ? Math.min(Math.max(Math.round(item.timeoutMs), 1e3), 6e5) : 0;
|
|
829
|
+
const changed = entry.endpoint !== (item.endpoint ?? "") || JSON.stringify(entry.headers) !== JSON.stringify(headers) || entry.enabled !== enabled || entry.timeoutMs !== serverTimeout;
|
|
767
830
|
entry.endpoint = item.endpoint ?? "";
|
|
768
831
|
entry.headers = headers;
|
|
832
|
+
entry.enabled = enabled;
|
|
833
|
+
entry.timeoutMs = serverTimeout;
|
|
769
834
|
const nextSettings = normalizeSettings(item.tools);
|
|
770
835
|
if (entry.sync !== void 0 && JSON.stringify(entry.settings) !== JSON.stringify(nextSettings)) entry.stale = true;
|
|
771
836
|
entry.settings = nextSettings;
|
|
@@ -793,12 +858,13 @@ function apply(ctx, config) {
|
|
|
793
858
|
entry.attempts = 0;
|
|
794
859
|
live.version += 1;
|
|
795
860
|
}
|
|
796
|
-
if (entry.endpoint === "") {
|
|
861
|
+
if (entry.endpoint === "" || entry.enabled === false) {
|
|
797
862
|
disposeTools(entry);
|
|
863
|
+
stopRetry(entry);
|
|
798
864
|
entry.connected = false;
|
|
799
865
|
entry.toolCount = 0;
|
|
800
866
|
entry.catalog = [];
|
|
801
|
-
entry.lastError = "";
|
|
867
|
+
entry.lastError = entry.enabled === false ? "" : entry.lastError;
|
|
802
868
|
continue;
|
|
803
869
|
}
|
|
804
870
|
void sync(entry).then((ok) => {
|
|
@@ -841,11 +907,13 @@ function createRuntime(ctx) {
|
|
|
841
907
|
const alive = (entry) => entry.disposed !== true && live.servers.get(entry.name) === entry;
|
|
842
908
|
const sync = (entry) => {
|
|
843
909
|
if (entry.sync !== void 0) return entry.sync;
|
|
910
|
+
if (entry.endpoint === "" || entry.enabled === false) return Promise.resolve(false);
|
|
844
911
|
const run = (async () => {
|
|
845
912
|
const generation = entry.generation ?? 0;
|
|
846
913
|
try {
|
|
847
|
-
if (entry.endpoint === "") return false;
|
|
848
|
-
const
|
|
914
|
+
if (entry.endpoint === "" || entry.enabled === false) return false;
|
|
915
|
+
const timeout = entry.timeoutMs > 0 ? entry.timeoutMs : live.timeoutMs;
|
|
916
|
+
const client = await connectMcp(entry.endpoint, entry.headers, timeout);
|
|
849
917
|
if (!alive(entry) || (entry.generation ?? 0) !== generation) {
|
|
850
918
|
await client.close().catch(() => {
|
|
851
919
|
});
|
|
@@ -910,9 +978,9 @@ function createRuntime(ctx) {
|
|
|
910
978
|
entry.retryTimer = setInterval(() => {
|
|
911
979
|
entry.attempts += 1;
|
|
912
980
|
void sync(entry).then((ok) => {
|
|
913
|
-
if (ok || entry.attempts >=
|
|
981
|
+
if (ok || entry.attempts >= live.maxRetries) stopRetry(entry);
|
|
914
982
|
});
|
|
915
|
-
},
|
|
983
|
+
}, live.retryIntervalMs);
|
|
916
984
|
};
|
|
917
985
|
return { disposeTools, registerTools, sync, scheduleRetry, stopRetry };
|
|
918
986
|
}
|
|
@@ -1007,10 +1075,19 @@ function installRoutes(ctx) {
|
|
|
1007
1075
|
if (since === live.version) return new Response(null, { status: 304, headers: { ...allowed, "cache-control": "no-store" } });
|
|
1008
1076
|
return new Response(JSON.stringify({
|
|
1009
1077
|
version: live.version,
|
|
1078
|
+
timeoutMs: live.timeoutMs,
|
|
1079
|
+
retryIntervalMs: live.retryIntervalMs,
|
|
1080
|
+
maxRetries: live.maxRetries,
|
|
1081
|
+
pollIntervalMs: live.pollIntervalMs,
|
|
1082
|
+
debug: live.debug,
|
|
1010
1083
|
servers: [...live.servers.values()].map((entry) => ({
|
|
1011
1084
|
name: entry.name,
|
|
1012
1085
|
endpoint: entry.endpoint,
|
|
1013
|
-
status: entry.connected ? "connected" : "idle",
|
|
1086
|
+
status: entry.connected ? "connected" : entry.enabled === false ? "disabled" : "idle",
|
|
1087
|
+
enabled: entry.enabled,
|
|
1088
|
+
timeoutMs: entry.timeoutMs,
|
|
1089
|
+
// Never ship header values to the page; names are enough to edit them.
|
|
1090
|
+
headerNames: Object.keys(entry.headers),
|
|
1014
1091
|
lastError: entry.lastError,
|
|
1015
1092
|
toolCount: entry.toolCount,
|
|
1016
1093
|
tools: entry.catalog,
|
|
@@ -1051,6 +1128,7 @@ function installRoutes(ctx) {
|
|
|
1051
1128
|
ok: true,
|
|
1052
1129
|
protocolVersion: probe.protocolVersion ?? null,
|
|
1053
1130
|
transport: probe.transport,
|
|
1131
|
+
detail: probe.detail ?? null,
|
|
1054
1132
|
server: probe.serverInfo?.name ?? null,
|
|
1055
1133
|
version: probe.serverInfo?.version ?? null,
|
|
1056
1134
|
tools: tools.map((tool) => ({ name: tool.name, description: tool.description ?? "", folder: tool._meta?.["dsh/folder"] ?? null }))
|
|
@@ -1102,15 +1180,40 @@ function installRoutes(ctx) {
|
|
|
1102
1180
|
const name2 = String(item.name ?? "general");
|
|
1103
1181
|
if (removed.has(name2)) continue;
|
|
1104
1182
|
const previous = byName.get(name2) ?? {};
|
|
1105
|
-
const
|
|
1106
|
-
const
|
|
1107
|
-
|
|
1108
|
-
|
|
1183
|
+
const hasEndpoint = typeof item.endpoint === "string";
|
|
1184
|
+
const endpoint2 = hasEndpoint ? item.endpoint.trim() : previous.endpoint ?? "";
|
|
1185
|
+
const sameEndpoint = (previous.endpoint ?? "") === endpoint2;
|
|
1186
|
+
const next2 = { ...previous, ...item, name: name2, endpoint: endpoint2 };
|
|
1187
|
+
if (!sameEndpoint) delete next2.tools;
|
|
1188
|
+
if (item.headersPatch !== null && typeof item.headersPatch === "object" && !Array.isArray(item.headersPatch)) {
|
|
1189
|
+
const headers2 = { ...previous.headers ?? {} };
|
|
1190
|
+
for (const [key, value] of Object.entries(item.headersPatch)) {
|
|
1191
|
+
if (value === null) delete headers2[key];
|
|
1192
|
+
else if (typeof value === "string") headers2[key] = value;
|
|
1193
|
+
}
|
|
1194
|
+
next2.headers = headers2;
|
|
1195
|
+
}
|
|
1196
|
+
delete next2.headersPatch;
|
|
1197
|
+
byName.set(name2, next2);
|
|
1109
1198
|
}
|
|
1110
1199
|
for (const name2 of removed) byName.delete(name2);
|
|
1111
1200
|
const servers = [...byName.values()];
|
|
1112
1201
|
const { serverName, endpoint, headers, tools, ...rest } = current;
|
|
1113
|
-
|
|
1202
|
+
const next = { ...rest, servers };
|
|
1203
|
+
const knobs = [
|
|
1204
|
+
["toolCallTimeoutMs", 1e3, 6e5],
|
|
1205
|
+
["retryIntervalMs", 5e3, 6e5],
|
|
1206
|
+
["pollIntervalMs", 2e3, 6e5],
|
|
1207
|
+
["maxRetries", 0, 1e3]
|
|
1208
|
+
];
|
|
1209
|
+
for (const [key, min, max] of knobs) {
|
|
1210
|
+
const value = body[key];
|
|
1211
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
1212
|
+
next[key] = Math.min(Math.max(Math.round(value), min), max);
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
if (typeof body.debug === "boolean") next.debug = body.debug;
|
|
1216
|
+
return next;
|
|
1114
1217
|
});
|
|
1115
1218
|
beacon("config-saved servers=" + incoming.length + " removed=" + removed.size);
|
|
1116
1219
|
send(res, 200, { ok: true });
|
|
@@ -1215,7 +1318,7 @@ function registerStatusTool(ctx) {
|
|
|
1215
1318
|
additionalProperties: false
|
|
1216
1319
|
},
|
|
1217
1320
|
render(_args, value) {
|
|
1218
|
-
const lines = (value.servers ?? []).map((item) => item.name + ": " + (item.connected ? "connected" : "idle") + " tools=" + item.toolCount + (item.lastError === "" ? "" : " error=" + item.lastError));
|
|
1321
|
+
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));
|
|
1219
1322
|
return [{ type: "text", text: "general-mcp" + (lines.length === 0 ? " (no gateways)" : "\n" + lines.join("\n")) }];
|
|
1220
1323
|
}
|
|
1221
1324
|
},
|
|
@@ -1224,6 +1327,8 @@ function registerStatusTool(ctx) {
|
|
|
1224
1327
|
name: entry.name,
|
|
1225
1328
|
endpoint: entry.endpoint,
|
|
1226
1329
|
connected: entry.connected,
|
|
1330
|
+
enabled: entry.enabled,
|
|
1331
|
+
timeoutMs: entry.timeoutMs,
|
|
1227
1332
|
toolCount: entry.toolCount,
|
|
1228
1333
|
lastError: entry.lastError,
|
|
1229
1334
|
disabled: entry.settings.disabled ?? [],
|
package/package.json
CHANGED
package/src/catalog.ts
CHANGED
|
@@ -59,34 +59,64 @@ function isStringArray(value: unknown): value is string[] {
|
|
|
59
59
|
return Array.isArray(value) && value.every(item => typeof item === 'string')
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* Only an unusable name is fatal: many servers (Spring AI's @Tool for one)
|
|
64
|
+
* omit description or inputSchema, and hiding those tools helps nobody.
|
|
65
|
+
*/
|
|
63
66
|
export function validateTool(tool: McpTool): ToolDiagnostic | undefined {
|
|
64
67
|
if (typeof tool.name !== 'string' || !NAME_PATTERN.test(tool.name)) {
|
|
65
68
|
return { code: 'name', message: 'name 必须匹配 ' + NAME_PATTERN.source }
|
|
66
69
|
}
|
|
67
|
-
|
|
68
|
-
|
|
70
|
+
return undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Coerce whatever the server sent into a usable object schema. Strings are
|
|
75
|
+
* parsed (some servers double-encode), everything else falls back to "no args".
|
|
76
|
+
*/
|
|
77
|
+
export function inputSchemaOf(tool: McpTool): { schema: Record<string, unknown>; warning?: ToolDiagnostic } {
|
|
78
|
+
let value: any = (tool as any).inputSchema
|
|
79
|
+
if (typeof value === 'string') {
|
|
80
|
+
try { value = JSON.parse(value) } catch { value = undefined }
|
|
81
|
+
}
|
|
82
|
+
if (value === undefined || value === null) {
|
|
83
|
+
return { schema: { type: 'object', properties: {} }, warning: { code: 'input-schema', message: '缺少 inputSchema,按无参数工具处理' } }
|
|
84
|
+
}
|
|
85
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
86
|
+
return { schema: { type: 'object', properties: {} }, warning: { code: 'input-schema', message: 'inputSchema 不是对象,按无参数工具处理' } }
|
|
87
|
+
}
|
|
88
|
+
const type = (value as any).type
|
|
89
|
+
if (type !== undefined && type !== 'object') {
|
|
90
|
+
return { schema: { type: 'object', properties: {} }, warning: { code: 'input-schema', message: 'inputSchema.type 不是 object,按无参数工具处理' } }
|
|
69
91
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
92
|
+
return { schema: { type: 'object', properties: {}, ...value } }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Non-fatal diagnostics: the tool still registers, the UI just flags it. */
|
|
96
|
+
export function toolWarnings(tool: McpTool): ToolDiagnostic[] {
|
|
97
|
+
const out: ToolDiagnostic[] = []
|
|
98
|
+
if (typeof tool.description !== 'string' || tool.description.trim() === '') {
|
|
99
|
+
out.push({ code: 'description', message: '缺少 description,用工具名代替' })
|
|
73
100
|
}
|
|
101
|
+
const schema = inputSchemaOf(tool).warning
|
|
102
|
+
if (schema !== undefined) out.push(schema)
|
|
74
103
|
const meta = (tool._meta ?? {}) as Record<string, unknown>
|
|
75
104
|
const folder = meta[CANONICAL_FOLDER]
|
|
76
105
|
if (folder !== undefined) {
|
|
77
106
|
if (!isStringArray(folder) || folder.length === 0 || folder.length > MAX_FOLDER_DEPTH) {
|
|
78
|
-
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
return { code: 'folder', message: '_meta["dsh/folder"] 段 "' + bad + '" 非法(不能含 / 或 .,长度 1..64)' }
|
|
107
|
+
out.push({ code: 'folder', message: '_meta["dsh/folder"] 必须是 1..8 个字符串的数组,已忽略' })
|
|
108
|
+
} else {
|
|
109
|
+
const bad = folder.find(segment => !SEGMENT_PATTERN.test(segment))
|
|
110
|
+
if (bad !== undefined) out.push({ code: 'folder', message: '_meta["dsh/folder"] 段 "' + bad + '" 非法,已忽略' })
|
|
83
111
|
}
|
|
84
112
|
}
|
|
85
113
|
const title = meta[CANONICAL_TITLE]
|
|
86
114
|
if (title !== undefined && (typeof title !== 'string' || title.length > MAX_TITLE)) {
|
|
87
|
-
|
|
115
|
+
out.push({ code: 'title', message: '_meta["dsh/title"] 必须是不超过 ' + MAX_TITLE + ' 字的字符串,已截断' })
|
|
88
116
|
}
|
|
89
|
-
|
|
117
|
+
const alias = aliasWarning(tool)
|
|
118
|
+
if (alias !== undefined) out.push(alias)
|
|
119
|
+
return out
|
|
90
120
|
}
|
|
91
121
|
|
|
92
122
|
/** Non-fatal: the tool uses a legacy alias instead of the canonical keys. */
|
|
@@ -98,15 +128,20 @@ export function aliasWarning(tool: McpTool): ToolDiagnostic | undefined {
|
|
|
98
128
|
return { code: 'alias', message: '使用了非规范字段 ' + used.join(', ') + ',请改用 _meta["dsh/folder"] / _meta["dsh/title"]' }
|
|
99
129
|
}
|
|
100
130
|
|
|
131
|
+
function usableFolder(value: unknown): string[] | undefined {
|
|
132
|
+
if (!isStringArray(value) || value.length === 0 || value.length > MAX_FOLDER_DEPTH) return undefined
|
|
133
|
+
return value.every(segment => SEGMENT_PATTERN.test(segment)) ? value : undefined
|
|
134
|
+
}
|
|
135
|
+
|
|
101
136
|
function folderFromMeta(tool: McpTool): string[] | undefined {
|
|
102
137
|
const meta = (tool._meta ?? {}) as Record<string, unknown>
|
|
103
|
-
const canonical = meta[CANONICAL_FOLDER]
|
|
104
|
-
if (
|
|
138
|
+
const canonical = usableFolder(meta[CANONICAL_FOLDER])
|
|
139
|
+
if (canonical !== undefined) return canonical
|
|
105
140
|
for (const key of ALIAS_NAMESPACES) {
|
|
106
141
|
const nested = meta[key]
|
|
107
142
|
if (nested === null || typeof nested !== 'object') continue
|
|
108
|
-
const inner = (nested as any).folder
|
|
109
|
-
if (
|
|
143
|
+
const inner = usableFolder((nested as any).folder)
|
|
144
|
+
if (inner !== undefined) return inner
|
|
110
145
|
}
|
|
111
146
|
return undefined
|
|
112
147
|
}
|
|
@@ -137,16 +172,18 @@ export function buildCatalog(
|
|
|
137
172
|
return tools.map(tool => {
|
|
138
173
|
const override = settings.overrides?.[tool.name]
|
|
139
174
|
const invalid = validateTool(tool)
|
|
140
|
-
const
|
|
175
|
+
const warnings = toolWarnings(tool)
|
|
176
|
+
const schema = inputSchemaOf(tool).schema
|
|
141
177
|
const folder = (override?.folder ?? folderFromMeta(tool) ?? folderFromName(tool.name))
|
|
142
178
|
.map(slug)
|
|
143
179
|
.filter(Boolean)
|
|
144
180
|
const leaf = slug(tool.name.split(/[./]/).pop() ?? tool.name) || 'tool'
|
|
145
181
|
const path = [...folder, leaf].join('/')
|
|
146
|
-
const metaTitle = typeof tool._meta?.[CANONICAL_TITLE] === 'string' ? String(tool._meta[CANONICAL_TITLE]) : undefined
|
|
182
|
+
const metaTitle = typeof tool._meta?.[CANONICAL_TITLE] === 'string' ? String(tool._meta[CANONICAL_TITLE]).slice(0, MAX_TITLE) : undefined
|
|
147
183
|
const annotationTitle = typeof tool.annotations?.title === 'string' ? tool.annotations.title : undefined
|
|
148
184
|
const title = override?.title ?? tool.title ?? annotationTitle ?? metaTitle
|
|
149
|
-
const
|
|
185
|
+
const described = typeof tool.description === 'string' && tool.description.trim() !== ''
|
|
186
|
+
const description = described ? tool.description as string : tool.name
|
|
150
187
|
return {
|
|
151
188
|
toolName: publicName(tool.name),
|
|
152
189
|
server: serverName,
|
|
@@ -156,14 +193,16 @@ export function buildCatalog(
|
|
|
156
193
|
folder,
|
|
157
194
|
...(title === undefined ? {} : { title }),
|
|
158
195
|
description,
|
|
159
|
-
inputSchema:
|
|
196
|
+
inputSchema: schema,
|
|
160
197
|
...(tool.outputSchema === undefined ? {} : { outputSchema: tool.outputSchema }),
|
|
161
|
-
hash: shortHash(description + JSON.stringify(
|
|
198
|
+
hash: shortHash(description + JSON.stringify(schema) + JSON.stringify(folder)),
|
|
162
199
|
disabled: disabled.has(tool.name),
|
|
163
200
|
hidden: hidden.has(tool.name),
|
|
164
201
|
...(removed.has(tool.name) ? { removed: true } : {}),
|
|
165
202
|
...(invalid !== undefined ? { invalid } : {}),
|
|
166
|
-
...(invalid === undefined &&
|
|
203
|
+
...(invalid === undefined && warnings.length > 0
|
|
204
|
+
? { warning: { code: warnings[0].code, message: warnings.map(item => item.message).join(';') } }
|
|
205
|
+
: {}),
|
|
167
206
|
}
|
|
168
207
|
})
|
|
169
208
|
}
|
package/src/connect.ts
CHANGED
|
@@ -4,6 +4,8 @@ import { SseClient } from './sse.ts'
|
|
|
4
4
|
|
|
5
5
|
export interface McpConnection {
|
|
6
6
|
transport: 'streamable' | 'sse'
|
|
7
|
+
/** Human-readable transport detail, e.g. the SSE message endpoint. */
|
|
8
|
+
detail?: string
|
|
7
9
|
protocolVersion: string | undefined
|
|
8
10
|
serverInfo: unknown
|
|
9
11
|
initialize(): Promise<void>
|
|
@@ -21,6 +23,7 @@ async function viaStreamable(url: string, headers: Record<string, string>, timeo
|
|
|
21
23
|
const info: any = await client.initialize()
|
|
22
24
|
return {
|
|
23
25
|
transport: 'streamable',
|
|
26
|
+
detail: 'POST ' + url,
|
|
24
27
|
protocolVersion: info?.protocolVersion,
|
|
25
28
|
serverInfo: info?.serverInfo,
|
|
26
29
|
async initialize() {},
|
|
@@ -35,6 +38,7 @@ async function viaSse(url: string, headers: Record<string, string>, timeoutMs: n
|
|
|
35
38
|
const info: any = await client.initialize()
|
|
36
39
|
return {
|
|
37
40
|
transport: 'sse',
|
|
41
|
+
detail: 'GET ' + url + ' → POST ' + (client.messageEndpoint ?? '(pending)'),
|
|
38
42
|
protocolVersion: info?.protocolVersion,
|
|
39
43
|
serverInfo: info?.serverInfo,
|
|
40
44
|
async initialize() {},
|
package/src/index.ts
CHANGED
|
@@ -23,6 +23,10 @@ export interface ServerConfig {
|
|
|
23
23
|
endpoint?: string
|
|
24
24
|
headers?: Record<string, string>
|
|
25
25
|
tools?: ToolSettings
|
|
26
|
+
/** false keeps the gateway configured but disconnected. */
|
|
27
|
+
enabled?: boolean
|
|
28
|
+
/** Per-gateway override of the global request timeout. */
|
|
29
|
+
timeoutMs?: number
|
|
26
30
|
}
|
|
27
31
|
|
|
28
32
|
export interface Config {
|
|
@@ -31,6 +35,11 @@ export interface Config {
|
|
|
31
35
|
endpoint?: string
|
|
32
36
|
headers?: Record<string, string>
|
|
33
37
|
toolCallTimeoutMs?: number
|
|
38
|
+
/** Reconnect cadence for a gateway that failed to connect. */
|
|
39
|
+
retryIntervalMs?: number
|
|
40
|
+
maxRetries?: number
|
|
41
|
+
/** How often the settings page re-reads the catalogue. */
|
|
42
|
+
pollIntervalMs?: number
|
|
34
43
|
debug?: boolean
|
|
35
44
|
tools?: ToolSettings
|
|
36
45
|
}
|
|
@@ -52,6 +61,8 @@ interface ServerState {
|
|
|
52
61
|
disposed?: boolean
|
|
53
62
|
generation?: number
|
|
54
63
|
client?: McpConnection
|
|
64
|
+
enabled: boolean
|
|
65
|
+
timeoutMs: number
|
|
55
66
|
}
|
|
56
67
|
|
|
57
68
|
interface RuntimeState {
|
|
@@ -60,6 +71,9 @@ interface RuntimeState {
|
|
|
60
71
|
version: number
|
|
61
72
|
debug: boolean
|
|
62
73
|
timeoutMs: number
|
|
74
|
+
retryIntervalMs: number
|
|
75
|
+
maxRetries: number
|
|
76
|
+
pollIntervalMs: number
|
|
63
77
|
}
|
|
64
78
|
|
|
65
79
|
const NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/
|
|
@@ -76,6 +90,9 @@ function state(): RuntimeState {
|
|
|
76
90
|
version: 0,
|
|
77
91
|
debug: false,
|
|
78
92
|
timeoutMs: 60_000,
|
|
93
|
+
retryIntervalMs: 30_000,
|
|
94
|
+
maxRetries: 20,
|
|
95
|
+
pollIntervalMs: 15_000,
|
|
79
96
|
}
|
|
80
97
|
}
|
|
81
98
|
return shared.__GENMCP_STATE__
|
|
@@ -96,6 +113,8 @@ function serverState(name: string): ServerState {
|
|
|
96
113
|
tools: new Map(),
|
|
97
114
|
settings: {},
|
|
98
115
|
attempts: 0,
|
|
116
|
+
enabled: true,
|
|
117
|
+
timeoutMs: 0,
|
|
99
118
|
}
|
|
100
119
|
live.servers.set(name, entry)
|
|
101
120
|
}
|
|
@@ -129,10 +148,14 @@ function normalizeSettings(raw: any): ToolSettings {
|
|
|
129
148
|
function normalizeConfig(config: Config | undefined): ServerConfig[] {
|
|
130
149
|
const raw = config ?? {}
|
|
131
150
|
const live = state()
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
151
|
+
const clamp = (value: unknown, fallback: number, min: number, max: number): number =>
|
|
152
|
+
typeof value === 'number' && Number.isFinite(value)
|
|
153
|
+
? Math.min(Math.max(Math.round(value), min), max)
|
|
154
|
+
: fallback
|
|
155
|
+
live.timeoutMs = clamp(raw.toolCallTimeoutMs, 60_000, 1_000, 600_000)
|
|
156
|
+
live.retryIntervalMs = clamp(raw.retryIntervalMs, 30_000, 5_000, 600_000)
|
|
157
|
+
live.maxRetries = clamp(raw.maxRetries, 20, 0, 1_000)
|
|
158
|
+
live.pollIntervalMs = clamp(raw.pollIntervalMs, 15_000, 2_000, 600_000)
|
|
136
159
|
live.debug = raw.debug === true
|
|
137
160
|
|
|
138
161
|
// An explicit empty array means "no gateways"; only a missing key falls back
|
|
@@ -186,10 +209,18 @@ export function apply(ctx: any, config?: Config): void {
|
|
|
186
209
|
if (typeof value === 'string') headers[key] = value
|
|
187
210
|
}
|
|
188
211
|
}
|
|
212
|
+
const enabled = item.enabled !== false
|
|
213
|
+
const serverTimeout = typeof item.timeoutMs === 'number' && Number.isFinite(item.timeoutMs)
|
|
214
|
+
? Math.min(Math.max(Math.round(item.timeoutMs), 1_000), 600_000)
|
|
215
|
+
: 0
|
|
189
216
|
const changed = entry.endpoint !== (item.endpoint ?? '') ||
|
|
190
|
-
JSON.stringify(entry.headers) !== JSON.stringify(headers)
|
|
217
|
+
JSON.stringify(entry.headers) !== JSON.stringify(headers) ||
|
|
218
|
+
entry.enabled !== enabled ||
|
|
219
|
+
entry.timeoutMs !== serverTimeout
|
|
191
220
|
entry.endpoint = item.endpoint ?? ''
|
|
192
221
|
entry.headers = headers
|
|
222
|
+
entry.enabled = enabled
|
|
223
|
+
entry.timeoutMs = serverTimeout
|
|
193
224
|
const nextSettings = normalizeSettings(item.tools)
|
|
194
225
|
// Display settings live outside the connection; a sync already in flight
|
|
195
226
|
// read the old ones, so ask for one more pass once it settles.
|
|
@@ -220,12 +251,13 @@ export function apply(ctx: any, config?: Config): void {
|
|
|
220
251
|
entry.attempts = 0
|
|
221
252
|
live.version += 1
|
|
222
253
|
}
|
|
223
|
-
if (entry.endpoint === '') {
|
|
254
|
+
if (entry.endpoint === '' || entry.enabled === false) {
|
|
224
255
|
disposeTools(entry)
|
|
256
|
+
stopRetry(entry)
|
|
225
257
|
entry.connected = false
|
|
226
258
|
entry.toolCount = 0
|
|
227
259
|
entry.catalog = []
|
|
228
|
-
entry.lastError = ''
|
|
260
|
+
entry.lastError = entry.enabled === false ? '' : entry.lastError
|
|
229
261
|
continue
|
|
230
262
|
}
|
|
231
263
|
void sync(entry).then(ok => {
|
|
@@ -272,11 +304,15 @@ function createRuntime(ctx: any) {
|
|
|
272
304
|
|
|
273
305
|
const sync = (entry: ServerState): Promise<boolean> => {
|
|
274
306
|
if (entry.sync !== undefined) return entry.sync
|
|
307
|
+
// Must be checked before the promise is stored: an early return would run
|
|
308
|
+
// the finally block before "entry.sync = run", leaving it permanently set.
|
|
309
|
+
if (entry.endpoint === '' || entry.enabled === false) return Promise.resolve(false)
|
|
275
310
|
const run = (async () => {
|
|
276
311
|
const generation = entry.generation ?? 0
|
|
277
312
|
try {
|
|
278
|
-
if (entry.endpoint === '') return false
|
|
279
|
-
const
|
|
313
|
+
if (entry.endpoint === '' || entry.enabled === false) return false
|
|
314
|
+
const timeout = entry.timeoutMs > 0 ? entry.timeoutMs : live.timeoutMs
|
|
315
|
+
const client = await connectMcp(entry.endpoint, entry.headers, timeout)
|
|
280
316
|
if (!alive(entry) || (entry.generation ?? 0) !== generation) {
|
|
281
317
|
await client.close().catch(() => {})
|
|
282
318
|
return false
|
|
@@ -339,9 +375,9 @@ function createRuntime(ctx: any) {
|
|
|
339
375
|
entry.retryTimer = setInterval(() => {
|
|
340
376
|
entry.attempts += 1
|
|
341
377
|
void sync(entry).then(ok => {
|
|
342
|
-
if (ok || entry.attempts >=
|
|
378
|
+
if (ok || entry.attempts >= live.maxRetries) stopRetry(entry)
|
|
343
379
|
})
|
|
344
|
-
},
|
|
380
|
+
}, live.retryIntervalMs)
|
|
345
381
|
}
|
|
346
382
|
|
|
347
383
|
return { disposeTools, registerTools, sync, scheduleRetry, stopRetry }
|
|
@@ -442,10 +478,19 @@ function installRoutes(ctx: any): void {
|
|
|
442
478
|
if (since === live.version) return new Response(null, { status: 304, headers: { ...allowed, 'cache-control': 'no-store' } })
|
|
443
479
|
return new Response(JSON.stringify({
|
|
444
480
|
version: live.version,
|
|
481
|
+
timeoutMs: live.timeoutMs,
|
|
482
|
+
retryIntervalMs: live.retryIntervalMs,
|
|
483
|
+
maxRetries: live.maxRetries,
|
|
484
|
+
pollIntervalMs: live.pollIntervalMs,
|
|
485
|
+
debug: live.debug,
|
|
445
486
|
servers: [...live.servers.values()].map(entry => ({
|
|
446
487
|
name: entry.name,
|
|
447
488
|
endpoint: entry.endpoint,
|
|
448
|
-
status: entry.connected ? 'connected' : 'idle',
|
|
489
|
+
status: entry.connected ? 'connected' : entry.enabled === false ? 'disabled' : 'idle',
|
|
490
|
+
enabled: entry.enabled,
|
|
491
|
+
timeoutMs: entry.timeoutMs,
|
|
492
|
+
// Never ship header values to the page; names are enough to edit them.
|
|
493
|
+
headerNames: Object.keys(entry.headers),
|
|
449
494
|
lastError: entry.lastError,
|
|
450
495
|
toolCount: entry.toolCount,
|
|
451
496
|
tools: entry.catalog,
|
|
@@ -480,6 +525,7 @@ function installRoutes(ctx: any): void {
|
|
|
480
525
|
ok: true,
|
|
481
526
|
protocolVersion: probe.protocolVersion ?? null,
|
|
482
527
|
transport: probe.transport,
|
|
528
|
+
detail: probe.detail ?? null,
|
|
483
529
|
server: (probe.serverInfo as any)?.name ?? null,
|
|
484
530
|
version: (probe.serverInfo as any)?.version ?? null,
|
|
485
531
|
tools: tools.map(tool => ({ name: tool.name, description: tool.description ?? '', folder: (tool._meta as any)?.['dsh/folder'] ?? null })),
|
|
@@ -532,15 +578,43 @@ function installRoutes(ctx: any): void {
|
|
|
532
578
|
const name = String(item.name ?? 'general')
|
|
533
579
|
if (removed.has(name)) continue
|
|
534
580
|
const previous = byName.get(name) ?? {}
|
|
535
|
-
|
|
536
|
-
|
|
581
|
+
// A partial payload (only enabled/timeout/headers) must keep the
|
|
582
|
+
// stored endpoint and tool settings.
|
|
583
|
+
const hasEndpoint = typeof item.endpoint === 'string'
|
|
584
|
+
const endpoint = hasEndpoint ? item.endpoint.trim() : (previous.endpoint ?? '')
|
|
585
|
+
const sameEndpoint = (previous.endpoint ?? '') === endpoint
|
|
586
|
+
const next: any = { ...previous, ...item, name, endpoint }
|
|
537
587
|
if (!sameEndpoint) delete next.tools
|
|
588
|
+
if (item.headersPatch !== null && typeof item.headersPatch === 'object' && !Array.isArray(item.headersPatch)) {
|
|
589
|
+
const headers: Record<string, string> = { ...(previous.headers ?? {}) }
|
|
590
|
+
for (const [key, value] of Object.entries(item.headersPatch as Record<string, unknown>)) {
|
|
591
|
+
if (value === null) delete headers[key]
|
|
592
|
+
else if (typeof value === 'string') headers[key] = value
|
|
593
|
+
}
|
|
594
|
+
next.headers = headers
|
|
595
|
+
}
|
|
596
|
+
delete next.headersPatch
|
|
538
597
|
byName.set(name, next)
|
|
539
598
|
}
|
|
540
599
|
for (const name of removed) byName.delete(name)
|
|
541
600
|
const servers = [...byName.values()]
|
|
542
601
|
const { serverName, endpoint, headers, tools, ...rest } = current
|
|
543
|
-
|
|
602
|
+
const next: any = { ...rest, servers }
|
|
603
|
+
// Display/behaviour knobs live next to the gateway list.
|
|
604
|
+
const knobs: Array<[string, number, number]> = [
|
|
605
|
+
['toolCallTimeoutMs', 1_000, 600_000],
|
|
606
|
+
['retryIntervalMs', 5_000, 600_000],
|
|
607
|
+
['pollIntervalMs', 2_000, 600_000],
|
|
608
|
+
['maxRetries', 0, 1_000],
|
|
609
|
+
]
|
|
610
|
+
for (const [key, min, max] of knobs) {
|
|
611
|
+
const value = body[key]
|
|
612
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
613
|
+
next[key] = Math.min(Math.max(Math.round(value), min), max)
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (typeof body.debug === 'boolean') next.debug = body.debug
|
|
617
|
+
return next
|
|
544
618
|
})
|
|
545
619
|
beacon('config-saved servers=' + (incoming as any[]).length + ' removed=' + removed.size)
|
|
546
620
|
send(res, 200, { ok: true })
|
|
@@ -647,7 +721,8 @@ function registerStatusTool(ctx: any): void {
|
|
|
647
721
|
},
|
|
648
722
|
render(_args: unknown, value: any) {
|
|
649
723
|
const lines = (value.servers ?? []).map((item: any) =>
|
|
650
|
-
item.name + ': ' + (item.connected ? 'connected' : '
|
|
724
|
+
item.name + ': ' + (item.connected ? 'connected' : item.enabled === false ? 'disabled' : 'idle') +
|
|
725
|
+
' tools=' + item.toolCount + (item.timeoutMs > 0 ? ' timeout=' + item.timeoutMs + 'ms' : '') +
|
|
651
726
|
(item.lastError === '' ? '' : ' error=' + item.lastError))
|
|
652
727
|
return [{ type: 'text', text: 'general-mcp' + (lines.length === 0 ? ' (no gateways)' : '\n' + lines.join('\n')) }]
|
|
653
728
|
},
|
|
@@ -657,6 +732,8 @@ function registerStatusTool(ctx: any): void {
|
|
|
657
732
|
name: entry.name,
|
|
658
733
|
endpoint: entry.endpoint,
|
|
659
734
|
connected: entry.connected,
|
|
735
|
+
enabled: entry.enabled,
|
|
736
|
+
timeoutMs: entry.timeoutMs,
|
|
660
737
|
toolCount: entry.toolCount,
|
|
661
738
|
lastError: entry.lastError,
|
|
662
739
|
disabled: entry.settings.disabled ?? [],
|
package/src/register.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Adapt one MCP tool to a DSH ToolDefinition, projecting MCP blocks safely. */
|
|
2
2
|
import type { McpClient, McpTool } from './client.ts'
|
|
3
3
|
import { publicToolName } from './naming.ts'
|
|
4
|
+
import { inputSchemaOf } from './catalog.ts'
|
|
4
5
|
|
|
5
6
|
interface DshBlock {
|
|
6
7
|
type: 'text'
|
|
@@ -53,9 +54,7 @@ export function createToolDefinition(
|
|
|
53
54
|
tool: McpTool,
|
|
54
55
|
client: McpClient,
|
|
55
56
|
): Record<string, unknown> {
|
|
56
|
-
const parameters = tool.
|
|
57
|
-
? tool.inputSchema
|
|
58
|
-
: { type: 'object', properties: {} }
|
|
57
|
+
const parameters = inputSchemaOf(tool).schema
|
|
59
58
|
|
|
60
59
|
return {
|
|
61
60
|
name: publicToolName(serverName, tool.name),
|
package/src/sse.ts
CHANGED
|
@@ -27,6 +27,38 @@ interface Pending {
|
|
|
27
27
|
timer: any
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
/** Hosts that only make sense on the server itself. */
|
|
31
|
+
function isLocalHost(hostname: string): boolean {
|
|
32
|
+
const host = hostname.toLowerCase()
|
|
33
|
+
return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]' ||
|
|
34
|
+
host === '0.0.0.0' || /^10\./.test(host) || /^192\.168\./.test(host) ||
|
|
35
|
+
/^172\.(1[6-9]|2\d|3[01])\./.test(host)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Spring AI builds the message endpoint from the server's own request URL, so
|
|
40
|
+
* behind a NAT/port-forward it often announces http://localhost:PORT/... That
|
|
41
|
+
* address is unreachable from the client; keep the path and take the origin
|
|
42
|
+
* from the SSE URL we actually connected to.
|
|
43
|
+
*/
|
|
44
|
+
export function resolveMessageUrl(endpoint: string, sseUrl: string): string {
|
|
45
|
+
let target: URL
|
|
46
|
+
let sse: URL
|
|
47
|
+
try {
|
|
48
|
+
sse = new URL(sseUrl)
|
|
49
|
+
target = new URL(endpoint, sseUrl)
|
|
50
|
+
} catch {
|
|
51
|
+
return endpoint
|
|
52
|
+
}
|
|
53
|
+
if (target.origin !== sse.origin && isLocalHost(target.hostname)) {
|
|
54
|
+
target.protocol = sse.protocol
|
|
55
|
+
target.hostname = sse.hostname
|
|
56
|
+
target.port = sse.port
|
|
57
|
+
return target.toString()
|
|
58
|
+
}
|
|
59
|
+
return target.toString()
|
|
60
|
+
}
|
|
61
|
+
|
|
30
62
|
export class SseClient {
|
|
31
63
|
private messageUrl: string | undefined
|
|
32
64
|
private pending = new Map<number, Pending>()
|
|
@@ -46,6 +78,11 @@ export class SseClient {
|
|
|
46
78
|
return '2024-11-05'
|
|
47
79
|
}
|
|
48
80
|
|
|
81
|
+
/** Where requests are POSTed; useful in diagnostics. */
|
|
82
|
+
get messageEndpoint(): string | undefined {
|
|
83
|
+
return this.messageUrl
|
|
84
|
+
}
|
|
85
|
+
|
|
49
86
|
/** Open the stream and wait for the endpoint announcement. */
|
|
50
87
|
connect(): Promise<void> {
|
|
51
88
|
if (this.connected !== undefined) return this.connected
|
|
@@ -56,7 +93,7 @@ export class SseClient {
|
|
|
56
93
|
if (response.body === null) throw new Error('SSE connect returned no body')
|
|
57
94
|
this.reader = response.body.getReader()
|
|
58
95
|
const announced = new Promise<void>((resolve, reject) => {
|
|
59
|
-
const timer = setTimeout(() => reject(new Error('SSE endpoint event timed out')), this.timeoutMs)
|
|
96
|
+
const timer = setTimeout(() => reject(new Error('SSE endpoint event timed out after ' + this.timeoutMs + 'ms (GET ' + this.url + ')')), this.timeoutMs)
|
|
60
97
|
this.endpointWaiter = { resolve, reject, timer }
|
|
61
98
|
})
|
|
62
99
|
void this.pump()
|
|
@@ -99,7 +136,7 @@ export class SseClient {
|
|
|
99
136
|
}
|
|
100
137
|
const payload = data.join('\n')
|
|
101
138
|
if (event === 'endpoint') {
|
|
102
|
-
|
|
139
|
+
this.messageUrl = resolveMessageUrl(payload, this.url)
|
|
103
140
|
const waiter = this.endpointWaiter
|
|
104
141
|
this.endpointWaiter = undefined
|
|
105
142
|
if (waiter !== undefined) { clearTimeout(waiter.timer); waiter.resolve(undefined) }
|
|
@@ -145,7 +182,7 @@ export class SseClient {
|
|
|
145
182
|
const reply = new Promise<any>((resolve, reject) => {
|
|
146
183
|
const timer = setTimeout(() => {
|
|
147
184
|
this.pending.delete(id)
|
|
148
|
-
reject(new Error('MCP ' + method + ' timed out after ' + this.timeoutMs + 'ms'))
|
|
185
|
+
reject(new Error('MCP ' + method + ' timed out after ' + this.timeoutMs + 'ms (POST ' + this.messageUrl + ')'))
|
|
149
186
|
}, this.timeoutMs)
|
|
150
187
|
this.pending.set(id, { resolve, reject, timer })
|
|
151
188
|
})
|