@momeidejiyi/dsh-general-mcp 0.0.0-stage → 0.1.1
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 +794 -0
- package/package.json +23 -3
- package/src/catalog.ts +162 -0
- package/src/client.ts +254 -0
- package/src/index.ts +451 -0
- package/src/naming.ts +21 -0
- package/src/register.ts +91 -0
- package/README.md +0 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,794 @@
|
|
|
1
|
+
// @momeidejiyi/dsh-general-mcp@0.1.1 (generated)
|
|
2
|
+
|
|
3
|
+
// packages/general-mcp/src/index.ts
|
|
4
|
+
import { appendFileSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
|
|
8
|
+
// packages/general-mcp/src/catalog.ts
|
|
9
|
+
var NAME_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
10
|
+
var SEGMENT_PATTERN = /^[^/.]{1,64}$/;
|
|
11
|
+
var MAX_TITLE = 80;
|
|
12
|
+
var MAX_FOLDER_DEPTH = 8;
|
|
13
|
+
var CANONICAL_FOLDER = "dsh/folder";
|
|
14
|
+
var CANONICAL_TITLE = "dsh/title";
|
|
15
|
+
var ALIAS_NAMESPACES = ["dev.dsh/tool", "io.deepseek/tool", "dsh/tool"];
|
|
16
|
+
function slug(value) {
|
|
17
|
+
return value.trim().toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5._-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
18
|
+
}
|
|
19
|
+
function isStringArray(value) {
|
|
20
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
21
|
+
}
|
|
22
|
+
function validateTool(tool) {
|
|
23
|
+
if (typeof tool.name !== "string" || !NAME_PATTERN.test(tool.name)) {
|
|
24
|
+
return { code: "name", message: "name \u5FC5\u987B\u5339\u914D " + NAME_PATTERN.source };
|
|
25
|
+
}
|
|
26
|
+
if (typeof tool.description !== "string" || tool.description.trim() === "") {
|
|
27
|
+
return { code: "description", message: "description \u4E0D\u80FD\u4E3A\u7A7A" };
|
|
28
|
+
}
|
|
29
|
+
const schema = tool.inputSchema;
|
|
30
|
+
if (schema === null || typeof schema !== "object" || Array.isArray(schema) || schema.type !== "object") {
|
|
31
|
+
return { code: "input-schema", message: 'inputSchema \u5FC5\u987B\u662F type:"object" \u7684 JSON Schema' };
|
|
32
|
+
}
|
|
33
|
+
const meta = tool._meta ?? {};
|
|
34
|
+
const folder = meta[CANONICAL_FOLDER];
|
|
35
|
+
if (folder !== void 0) {
|
|
36
|
+
if (!isStringArray(folder) || folder.length === 0 || folder.length > MAX_FOLDER_DEPTH) {
|
|
37
|
+
return { code: "folder", message: '_meta["dsh/folder"] \u5FC5\u987B\u662F 1..8 \u4E2A\u5B57\u7B26\u4E32\u7684\u6570\u7EC4' };
|
|
38
|
+
}
|
|
39
|
+
const bad = folder.find((segment) => !SEGMENT_PATTERN.test(segment));
|
|
40
|
+
if (bad !== void 0) {
|
|
41
|
+
return { code: "folder", message: '_meta["dsh/folder"] \u6BB5 "' + bad + '" \u975E\u6CD5\uFF08\u4E0D\u80FD\u542B / \u6216 .\uFF0C\u957F\u5EA6 1..64\uFF09' };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const title = meta[CANONICAL_TITLE];
|
|
45
|
+
if (title !== void 0 && (typeof title !== "string" || title.length > MAX_TITLE)) {
|
|
46
|
+
return { code: "title", message: '_meta["dsh/title"] \u5FC5\u987B\u662F\u4E0D\u8D85\u8FC7 ' + MAX_TITLE + " \u5B57\u7684\u5B57\u7B26\u4E32" };
|
|
47
|
+
}
|
|
48
|
+
return void 0;
|
|
49
|
+
}
|
|
50
|
+
function aliasWarning(tool) {
|
|
51
|
+
const meta = tool._meta ?? {};
|
|
52
|
+
if (meta[CANONICAL_FOLDER] !== void 0 || meta[CANONICAL_TITLE] !== void 0) return void 0;
|
|
53
|
+
const used = ALIAS_NAMESPACES.filter((key) => meta[key] !== void 0 || key === "dsh/tool" && meta[key] !== void 0);
|
|
54
|
+
if (used.length === 0) return void 0;
|
|
55
|
+
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
|
+
}
|
|
57
|
+
function folderFromMeta(tool) {
|
|
58
|
+
const meta = tool._meta ?? {};
|
|
59
|
+
const canonical = meta[CANONICAL_FOLDER];
|
|
60
|
+
if (isStringArray(canonical) && canonical.length > 0) return canonical;
|
|
61
|
+
for (const key of ALIAS_NAMESPACES) {
|
|
62
|
+
const nested = meta[key];
|
|
63
|
+
if (nested === null || typeof nested !== "object") continue;
|
|
64
|
+
const inner = nested.folder;
|
|
65
|
+
if (isStringArray(inner) && inner.length > 0) return inner;
|
|
66
|
+
}
|
|
67
|
+
return void 0;
|
|
68
|
+
}
|
|
69
|
+
function folderFromName(rawName) {
|
|
70
|
+
const parts = rawName.split(/[./]/).filter(Boolean);
|
|
71
|
+
return parts.length > 1 ? parts.slice(0, -1) : ["uncategorized"];
|
|
72
|
+
}
|
|
73
|
+
function shortHash(value) {
|
|
74
|
+
let hash = 2166136261;
|
|
75
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
76
|
+
hash ^= value.charCodeAt(index);
|
|
77
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
78
|
+
}
|
|
79
|
+
return hash.toString(16).padStart(8, "0");
|
|
80
|
+
}
|
|
81
|
+
function buildCatalog(serverName, tools, publicName, settings = {}) {
|
|
82
|
+
const disabled = new Set(settings.disabled ?? []);
|
|
83
|
+
const hidden = new Set(settings.hidden ?? []);
|
|
84
|
+
return tools.map((tool) => {
|
|
85
|
+
const override = settings.overrides?.[tool.name];
|
|
86
|
+
const invalid = validateTool(tool);
|
|
87
|
+
const alias = aliasWarning(tool);
|
|
88
|
+
const folder = (override?.folder ?? folderFromMeta(tool) ?? folderFromName(tool.name)).map(slug).filter(Boolean);
|
|
89
|
+
const leaf = slug(tool.name.split(/[./]/).pop() ?? tool.name) || "tool";
|
|
90
|
+
const path = [...folder, leaf].join("/");
|
|
91
|
+
const metaTitle = typeof tool._meta?.[CANONICAL_TITLE] === "string" ? String(tool._meta[CANONICAL_TITLE]) : void 0;
|
|
92
|
+
const annotationTitle = typeof tool.annotations?.title === "string" ? tool.annotations.title : void 0;
|
|
93
|
+
const title = override?.title ?? tool.title ?? annotationTitle ?? metaTitle;
|
|
94
|
+
const description = tool.description ?? tool.name;
|
|
95
|
+
return {
|
|
96
|
+
toolName: publicName(tool.name),
|
|
97
|
+
rawName: tool.name,
|
|
98
|
+
path,
|
|
99
|
+
virtualPath: "dsh-mcp://" + serverName + "/" + path,
|
|
100
|
+
folder,
|
|
101
|
+
...title === void 0 ? {} : { title },
|
|
102
|
+
description,
|
|
103
|
+
inputSchema: tool.inputSchema ?? { type: "object", properties: {} },
|
|
104
|
+
...tool.outputSchema === void 0 ? {} : { outputSchema: tool.outputSchema },
|
|
105
|
+
hash: shortHash(description + JSON.stringify(tool.inputSchema ?? null) + JSON.stringify(folder)),
|
|
106
|
+
disabled: disabled.has(tool.name),
|
|
107
|
+
hidden: hidden.has(tool.name),
|
|
108
|
+
...invalid !== void 0 ? { invalid } : {},
|
|
109
|
+
...invalid === void 0 && alias !== void 0 ? { warning: alias } : {}
|
|
110
|
+
};
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// packages/general-mcp/src/client.ts
|
|
115
|
+
var MODERN = "2026-07-28";
|
|
116
|
+
var LEGACY = "2025-06-18";
|
|
117
|
+
var META_VERSION = "io.modelcontextprotocol/protocolVersion";
|
|
118
|
+
var META_CLIENT = "io.modelcontextprotocol/clientInfo";
|
|
119
|
+
var META_CAPS = "io.modelcontextprotocol/clientCapabilities";
|
|
120
|
+
var McpClient = class {
|
|
121
|
+
constructor(url, headers = {}, timeoutMs = 6e4) {
|
|
122
|
+
this.url = url;
|
|
123
|
+
this.headers = headers;
|
|
124
|
+
this.timeoutMs = timeoutMs;
|
|
125
|
+
}
|
|
126
|
+
nextId = 0;
|
|
127
|
+
sessionId;
|
|
128
|
+
protocolVersion;
|
|
129
|
+
era;
|
|
130
|
+
get protocol() {
|
|
131
|
+
return { era: this.era, version: this.protocolVersion };
|
|
132
|
+
}
|
|
133
|
+
async initialize() {
|
|
134
|
+
const modern = await this.tryModern();
|
|
135
|
+
if (modern !== void 0) {
|
|
136
|
+
this.era = "modern";
|
|
137
|
+
this.protocolVersion = MODERN;
|
|
138
|
+
return { ...modern, era: "modern" };
|
|
139
|
+
}
|
|
140
|
+
this.era = "legacy";
|
|
141
|
+
const result = await this.request("initialize", {
|
|
142
|
+
protocolVersion: LEGACY,
|
|
143
|
+
capabilities: {},
|
|
144
|
+
clientInfo: { name: "dsh-general-mcp", version: "0.1.1" }
|
|
145
|
+
});
|
|
146
|
+
if (typeof result?.protocolVersion === "string") this.protocolVersion = result.protocolVersion;
|
|
147
|
+
await this.notify("notifications/initialized", {});
|
|
148
|
+
return { ...result ?? {}, era: "legacy" };
|
|
149
|
+
}
|
|
150
|
+
/** The modern revision has no initialize: server/discover is the handshake. */
|
|
151
|
+
async tryModern() {
|
|
152
|
+
try {
|
|
153
|
+
const result = await this.request("server/discover", {}, void 0, MODERN);
|
|
154
|
+
if (result === void 0 || result === null) return void 0;
|
|
155
|
+
return result;
|
|
156
|
+
} catch {
|
|
157
|
+
return void 0;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async listTools() {
|
|
161
|
+
const tools = [];
|
|
162
|
+
const seenCursors = /* @__PURE__ */ new Set();
|
|
163
|
+
let cursor;
|
|
164
|
+
let pages = 0;
|
|
165
|
+
while (pages < 100) {
|
|
166
|
+
pages += 1;
|
|
167
|
+
const result = await this.request("tools/list", cursor === void 0 ? {} : { cursor });
|
|
168
|
+
if (!Array.isArray(result?.tools)) throw new Error("tools/list returned no tools array");
|
|
169
|
+
tools.push(...result.tools);
|
|
170
|
+
const next = typeof result.nextCursor === "string" && result.nextCursor !== "" ? result.nextCursor : void 0;
|
|
171
|
+
if (next === void 0) {
|
|
172
|
+
cursor = void 0;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
if (seenCursors.has(next)) throw new Error("tools/list repeated cursor " + next);
|
|
176
|
+
seenCursors.add(next);
|
|
177
|
+
cursor = next;
|
|
178
|
+
}
|
|
179
|
+
if (cursor !== void 0) throw new Error("tools/list did not terminate within 100 pages");
|
|
180
|
+
const seen = /* @__PURE__ */ new Set();
|
|
181
|
+
for (const tool of tools) {
|
|
182
|
+
if (typeof tool.name !== "string" || tool.name === "") throw new Error("tool without a name");
|
|
183
|
+
if (seen.has(tool.name)) throw new Error("duplicate tool: " + tool.name);
|
|
184
|
+
seen.add(tool.name);
|
|
185
|
+
}
|
|
186
|
+
return tools;
|
|
187
|
+
}
|
|
188
|
+
async callTool(name2, args, signal) {
|
|
189
|
+
const result = await this.request("tools/call", { name: name2, arguments: args }, signal, void 0, name2);
|
|
190
|
+
return result ?? {};
|
|
191
|
+
}
|
|
192
|
+
async notify(method, params) {
|
|
193
|
+
const response = await this.send({ jsonrpc: "2.0", method, params }, void 0, method);
|
|
194
|
+
if (response.status !== 202 && response.status !== 200 && response.status !== 204) {
|
|
195
|
+
throw new Error("notify " + method + " failed: HTTP " + response.status);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Terminate the session so a reconnect starts clean. */
|
|
199
|
+
async close() {
|
|
200
|
+
if (this.sessionId === void 0) return;
|
|
201
|
+
const sessionId = this.sessionId;
|
|
202
|
+
this.sessionId = void 0;
|
|
203
|
+
try {
|
|
204
|
+
await fetch(this.url, { method: "DELETE", headers: { "mcp-session-id": sessionId } });
|
|
205
|
+
} catch {
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
async request(method, params, signal, eraOverride, toolName) {
|
|
209
|
+
if (signal?.aborted === true) throw signal.reason ?? new Error("aborted");
|
|
210
|
+
const era = eraOverride ?? this.era;
|
|
211
|
+
const id = this.nextId += 1;
|
|
212
|
+
const body = {
|
|
213
|
+
jsonrpc: "2.0",
|
|
214
|
+
id,
|
|
215
|
+
method,
|
|
216
|
+
params: era === "modern" ? { ...params, _meta: { ...params?._meta, [META_VERSION]: MODERN, [META_CLIENT]: { name: "dsh-general-mcp", version: "0.1.1" }, [META_CAPS]: {} } } : params
|
|
217
|
+
};
|
|
218
|
+
let response = await this.send(body, signal, method, era, toolName);
|
|
219
|
+
if (response.status === 404 && this.sessionId !== void 0 && method !== "initialize") {
|
|
220
|
+
this.sessionId = void 0;
|
|
221
|
+
await this.initialize();
|
|
222
|
+
response = await this.send(body, signal, method, this.era, toolName);
|
|
223
|
+
}
|
|
224
|
+
if (response.status === 401 || response.status === 403) {
|
|
225
|
+
throw new Error(method + " failed: HTTP " + response.status + " (authentication rejected)");
|
|
226
|
+
}
|
|
227
|
+
const payload = response.payload;
|
|
228
|
+
if (payload?.error) {
|
|
229
|
+
throw new Error("MCP " + method + " error " + payload.error.code + ": " + payload.error.message);
|
|
230
|
+
}
|
|
231
|
+
if (payload === void 0) {
|
|
232
|
+
throw new Error(method + " returned no JSON-RPC payload (HTTP " + response.status + ")");
|
|
233
|
+
}
|
|
234
|
+
return payload.result;
|
|
235
|
+
}
|
|
236
|
+
async send(body, signal, method, eraOverride, toolName) {
|
|
237
|
+
const era = eraOverride ?? this.era;
|
|
238
|
+
const controller = new AbortController();
|
|
239
|
+
const timer = setTimeout(() => {
|
|
240
|
+
controller.abort(new Error("MCP request timed out after " + this.timeoutMs + "ms"));
|
|
241
|
+
}, this.timeoutMs);
|
|
242
|
+
const forward = () => controller.abort(signal?.reason);
|
|
243
|
+
signal?.addEventListener("abort", forward, { once: true });
|
|
244
|
+
try {
|
|
245
|
+
const headers = {
|
|
246
|
+
"content-type": "application/json",
|
|
247
|
+
accept: "application/json, text/event-stream",
|
|
248
|
+
...this.headers
|
|
249
|
+
};
|
|
250
|
+
if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId;
|
|
251
|
+
if (era === "modern") {
|
|
252
|
+
headers["mcp-protocol-version"] = this.protocolVersion ?? MODERN;
|
|
253
|
+
if (method !== void 0) headers["mcp-method"] = method;
|
|
254
|
+
if (toolName !== void 0) headers["mcp-name"] = toolName;
|
|
255
|
+
} else if (this.protocolVersion !== void 0) {
|
|
256
|
+
headers["mcp-protocol-version"] = this.protocolVersion;
|
|
257
|
+
}
|
|
258
|
+
const response = await fetch(this.url, { method: "POST", headers, body: JSON.stringify(body), signal: controller.signal });
|
|
259
|
+
const sessionId = response.headers.get("mcp-session-id");
|
|
260
|
+
if (sessionId !== null && sessionId !== "") this.sessionId = sessionId;
|
|
261
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
262
|
+
let payload;
|
|
263
|
+
if (response.status === 202 || response.status === 204) {
|
|
264
|
+
payload = void 0;
|
|
265
|
+
} else if (contentType.includes("text/event-stream")) {
|
|
266
|
+
payload = await readSseResult(response, body?.id);
|
|
267
|
+
} else if (response.ok) {
|
|
268
|
+
payload = await response.json();
|
|
269
|
+
} else {
|
|
270
|
+
const detail = await response.text().catch(() => "");
|
|
271
|
+
if (detail !== "") throw new Error("HTTP " + response.status + ": " + detail.slice(0, 300));
|
|
272
|
+
payload = void 0;
|
|
273
|
+
}
|
|
274
|
+
return { status: response.status, payload, headers: response.headers };
|
|
275
|
+
} catch (error) {
|
|
276
|
+
const cause = error?.cause;
|
|
277
|
+
if (controller.signal.aborted) {
|
|
278
|
+
const reason = controller.signal.reason;
|
|
279
|
+
throw new Error(String(reason?.message ?? reason ?? "MCP request aborted"));
|
|
280
|
+
}
|
|
281
|
+
if (cause !== void 0 && typeof cause?.code === "string") {
|
|
282
|
+
throw new Error("MCP transport failed: " + cause.code + (cause.message ? " - " + cause.message : ""));
|
|
283
|
+
}
|
|
284
|
+
throw error;
|
|
285
|
+
} finally {
|
|
286
|
+
clearTimeout(timer);
|
|
287
|
+
signal?.removeEventListener("abort", forward);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
async function readSseResult(response, id) {
|
|
292
|
+
const text = await response.text();
|
|
293
|
+
const events = [];
|
|
294
|
+
let data = [];
|
|
295
|
+
const flush = () => {
|
|
296
|
+
if (data.length > 0) events.push(data.join("\n"));
|
|
297
|
+
data = [];
|
|
298
|
+
};
|
|
299
|
+
for (const line of text.split(/\r?\n/)) {
|
|
300
|
+
if (line === "") {
|
|
301
|
+
flush();
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
|
|
305
|
+
}
|
|
306
|
+
flush();
|
|
307
|
+
for (const event of events) {
|
|
308
|
+
if (event === "" || event === "[DONE]") continue;
|
|
309
|
+
let parsed;
|
|
310
|
+
try {
|
|
311
|
+
parsed = JSON.parse(event);
|
|
312
|
+
} catch {
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
const candidates = Array.isArray(parsed) ? parsed : [parsed];
|
|
316
|
+
for (const candidate of candidates) {
|
|
317
|
+
if (candidate?.id === id) return candidate;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
throw new Error("no JSON-RPC response with the request id in the SSE stream");
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// packages/general-mcp/src/naming.ts
|
|
324
|
+
var MAX_LENGTH = 64;
|
|
325
|
+
function sanitize(value) {
|
|
326
|
+
return value.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
327
|
+
}
|
|
328
|
+
function shortHash2(value) {
|
|
329
|
+
let hash = 2166136261;
|
|
330
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
331
|
+
hash ^= value.charCodeAt(index);
|
|
332
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
333
|
+
}
|
|
334
|
+
return hash.toString(16).padStart(8, "0");
|
|
335
|
+
}
|
|
336
|
+
function publicToolName(serverName, rawName) {
|
|
337
|
+
const base = "mcp__" + sanitize(serverName) + "__" + sanitize(rawName);
|
|
338
|
+
if (base.length <= MAX_LENGTH) return base;
|
|
339
|
+
return base.slice(0, MAX_LENGTH - 9) + "_" + shortHash2(base);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// packages/general-mcp/src/register.ts
|
|
343
|
+
function placeholder(kind, detail) {
|
|
344
|
+
return "[" + kind + (detail === "" ? "" : ": " + detail) + "]";
|
|
345
|
+
}
|
|
346
|
+
function projectBlocks(blocks) {
|
|
347
|
+
if (!Array.isArray(blocks)) return [];
|
|
348
|
+
const out = [];
|
|
349
|
+
for (const raw of blocks) {
|
|
350
|
+
const block = raw;
|
|
351
|
+
switch (block?.type) {
|
|
352
|
+
case "text":
|
|
353
|
+
out.push({ type: "text", text: String(block.text ?? "") });
|
|
354
|
+
break;
|
|
355
|
+
case "image":
|
|
356
|
+
out.push({ type: "text", text: placeholder("image", String(block.mimeType ?? "unknown")) });
|
|
357
|
+
break;
|
|
358
|
+
case "audio":
|
|
359
|
+
out.push({ type: "text", text: placeholder("audio", String(block.mimeType ?? "unknown")) });
|
|
360
|
+
break;
|
|
361
|
+
case "resource_link":
|
|
362
|
+
out.push({ type: "text", text: placeholder("resource", String(block.uri ?? "")) });
|
|
363
|
+
break;
|
|
364
|
+
case "resource":
|
|
365
|
+
out.push({ type: "text", text: placeholder("resource", String(block.resource?.uri ?? "")) });
|
|
366
|
+
break;
|
|
367
|
+
default:
|
|
368
|
+
out.push({ type: "text", text: placeholder("block", String(block?.type ?? "unknown")) });
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return out;
|
|
372
|
+
}
|
|
373
|
+
function textOf(blocks) {
|
|
374
|
+
return blocks.map((block) => block.text).join("\n");
|
|
375
|
+
}
|
|
376
|
+
function createToolDefinition(serverName, tool, client) {
|
|
377
|
+
const parameters = tool.inputSchema && typeof tool.inputSchema === "object" ? tool.inputSchema : { type: "object", properties: {} };
|
|
378
|
+
return {
|
|
379
|
+
name: publicToolName(serverName, tool.name),
|
|
380
|
+
description: tool.description ?? tool.name,
|
|
381
|
+
parameters,
|
|
382
|
+
output: {
|
|
383
|
+
schema: {
|
|
384
|
+
type: "object",
|
|
385
|
+
properties: {
|
|
386
|
+
content: { type: "array", items: {} },
|
|
387
|
+
structuredContent: {}
|
|
388
|
+
},
|
|
389
|
+
required: ["content"],
|
|
390
|
+
additionalProperties: true
|
|
391
|
+
},
|
|
392
|
+
render(_args, value) {
|
|
393
|
+
return [{ type: "text", text: textOf(projectBlocks(value?.content)) }];
|
|
394
|
+
}
|
|
395
|
+
},
|
|
396
|
+
isConcurrencySafe() {
|
|
397
|
+
return true;
|
|
398
|
+
},
|
|
399
|
+
async execute(args, exec) {
|
|
400
|
+
const result = await client.callTool(tool.name, args ?? {}, exec?.signal);
|
|
401
|
+
const content = projectBlocks(result.content);
|
|
402
|
+
if (result.isError) throw new Error(textOf(content));
|
|
403
|
+
return {
|
|
404
|
+
content,
|
|
405
|
+
...result.structuredContent === void 0 ? {} : { structuredContent: result.structuredContent }
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// packages/general-mcp/src/index.ts
|
|
412
|
+
var name = "general-mcp";
|
|
413
|
+
var inject = ["tools"];
|
|
414
|
+
var shared = globalThis;
|
|
415
|
+
function normalizeConfig(config) {
|
|
416
|
+
const live = state();
|
|
417
|
+
const raw = config ?? {};
|
|
418
|
+
const endpoint = typeof raw.endpoint === "string" ? raw.endpoint.trim() : "";
|
|
419
|
+
if (endpoint !== "" && !/^https?:\/\//i.test(endpoint)) {
|
|
420
|
+
throw new Error("endpoint must be an http(s) URL");
|
|
421
|
+
}
|
|
422
|
+
live.endpoint = endpoint;
|
|
423
|
+
live.serverName = typeof raw.serverName === "string" && raw.serverName !== "" ? raw.serverName : "general";
|
|
424
|
+
const headers = {};
|
|
425
|
+
if (raw.headers !== null && typeof raw.headers === "object" && !Array.isArray(raw.headers)) {
|
|
426
|
+
for (const [key, value] of Object.entries(raw.headers)) {
|
|
427
|
+
if (typeof value === "string") headers[key] = value;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
live.headers = headers;
|
|
431
|
+
const timeout = typeof raw.toolCallTimeoutMs === "number" && Number.isFinite(raw.toolCallTimeoutMs) ? Math.min(Math.max(Math.round(raw.toolCallTimeoutMs), 1e3), 6e5) : 6e4;
|
|
432
|
+
live.timeoutMs = timeout;
|
|
433
|
+
live.debug = raw.debug === true;
|
|
434
|
+
const tools = raw.tools ?? {};
|
|
435
|
+
live.toolSettings = {
|
|
436
|
+
disabled: Array.isArray(tools.disabled) ? tools.disabled.filter((item) => typeof item === "string") : [],
|
|
437
|
+
hidden: Array.isArray(tools.hidden) ? tools.hidden.filter((item) => typeof item === "string") : [],
|
|
438
|
+
overrides: tools.overrides !== null && typeof tools.overrides === "object" ? tools.overrides : {}
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
function state() {
|
|
442
|
+
shared.__GENMCP_STATE__ ??= {
|
|
443
|
+
serverName: "general",
|
|
444
|
+
endpoint: "",
|
|
445
|
+
headers: {},
|
|
446
|
+
timeoutMs: 6e4,
|
|
447
|
+
debug: false,
|
|
448
|
+
connected: false,
|
|
449
|
+
toolCount: 0,
|
|
450
|
+
lastError: "",
|
|
451
|
+
catalog: [],
|
|
452
|
+
toolSettings: {},
|
|
453
|
+
version: 0,
|
|
454
|
+
token: crypto.randomUUID(),
|
|
455
|
+
tools: /* @__PURE__ */ new Map(),
|
|
456
|
+
attempts: 0
|
|
457
|
+
};
|
|
458
|
+
return shared.__GENMCP_STATE__;
|
|
459
|
+
}
|
|
460
|
+
async function apply(ctx, config = {}) {
|
|
461
|
+
normalizeConfig(config);
|
|
462
|
+
const live = state();
|
|
463
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
464
|
+
const beacon = (stage) => {
|
|
465
|
+
if (live.debug !== true) return;
|
|
466
|
+
try {
|
|
467
|
+
appendFileSync(join(tmpdir(), "dsh-general-mcp-debug.log"), (/* @__PURE__ */ new Date()).toISOString() + " " + stage + "\n");
|
|
468
|
+
} catch {
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
const disposeTools = () => {
|
|
472
|
+
for (const [key, dispose] of live.tools) {
|
|
473
|
+
try {
|
|
474
|
+
dispose();
|
|
475
|
+
} catch {
|
|
476
|
+
}
|
|
477
|
+
live.tools.delete(key);
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
const stopRetry = () => {
|
|
481
|
+
if (live.retryTimer !== void 0) clearInterval(live.retryTimer);
|
|
482
|
+
live.retryTimer = void 0;
|
|
483
|
+
};
|
|
484
|
+
const registerTools = (tools, client) => {
|
|
485
|
+
const disabled = new Set(live.toolSettings.disabled ?? []);
|
|
486
|
+
const hidden = new Set(live.toolSettings.hidden ?? []);
|
|
487
|
+
disposeTools();
|
|
488
|
+
for (const tool of tools) {
|
|
489
|
+
if (hidden.has(tool.name) || disabled.has(tool.name)) continue;
|
|
490
|
+
const invalid = validateTool(tool);
|
|
491
|
+
if (invalid !== void 0) {
|
|
492
|
+
ctx.logger?.warn?.("general-mcp: rejected tool " + tool.name + " (" + invalid.code + "): " + invalid.message);
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
const definition = createToolDefinition(live.serverName, tool, client);
|
|
496
|
+
const dispose = ctx.tools.register(definition);
|
|
497
|
+
live.tools.set(definition.name, dispose);
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
const sync = () => {
|
|
501
|
+
if (live.sync !== void 0) return live.sync;
|
|
502
|
+
const run = (async () => {
|
|
503
|
+
if (live.endpoint === "") {
|
|
504
|
+
disposeTools();
|
|
505
|
+
live.connected = false;
|
|
506
|
+
live.toolCount = 0;
|
|
507
|
+
live.catalog = [];
|
|
508
|
+
live.lastError = "";
|
|
509
|
+
live.version += 1;
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
const client = new McpClient(live.endpoint, live.headers, live.timeoutMs);
|
|
513
|
+
try {
|
|
514
|
+
await client.initialize();
|
|
515
|
+
const tools = await client.listTools();
|
|
516
|
+
registerTools(tools, client);
|
|
517
|
+
live.connected = true;
|
|
518
|
+
live.toolCount = live.tools.size;
|
|
519
|
+
live.catalog = buildCatalog(live.serverName, tools, (raw) => publicToolName(live.serverName, raw), live.toolSettings);
|
|
520
|
+
live.version += 1;
|
|
521
|
+
live.lastError = "";
|
|
522
|
+
live.attempts = 0;
|
|
523
|
+
beacon("discovered " + tools.length + " version=" + live.version);
|
|
524
|
+
return true;
|
|
525
|
+
} catch (error) {
|
|
526
|
+
live.connected = false;
|
|
527
|
+
live.lastError = String(error?.message ?? error);
|
|
528
|
+
live.version += 1;
|
|
529
|
+
ctx.logger?.warn?.("general-mcp: " + live.lastError);
|
|
530
|
+
beacon("discover-error " + live.lastError);
|
|
531
|
+
return false;
|
|
532
|
+
} finally {
|
|
533
|
+
live.sync = void 0;
|
|
534
|
+
}
|
|
535
|
+
})();
|
|
536
|
+
live.sync = run;
|
|
537
|
+
return run;
|
|
538
|
+
};
|
|
539
|
+
const scheduleRetry = () => {
|
|
540
|
+
if (live.retryTimer !== void 0) return;
|
|
541
|
+
live.retryTimer = setInterval(() => {
|
|
542
|
+
live.attempts += 1;
|
|
543
|
+
void sync().then((ok) => {
|
|
544
|
+
if (ok || live.attempts >= 20) stopRetry();
|
|
545
|
+
});
|
|
546
|
+
}, 3e4);
|
|
547
|
+
};
|
|
548
|
+
ctx.effect(() => () => {
|
|
549
|
+
stopRetry();
|
|
550
|
+
disposeTools();
|
|
551
|
+
});
|
|
552
|
+
beacon("host-apply " + live.serverName);
|
|
553
|
+
const installRoutes = (webCtx) => {
|
|
554
|
+
const webServer = webCtx?.webServer ?? webCtx?.get?.("webServer");
|
|
555
|
+
if (webServer === void 0 || typeof webServer.register !== "function") {
|
|
556
|
+
beacon("host-no-webserver");
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
const installed = shared.__GENMCP_ROUTES__ ??= /* @__PURE__ */ new WeakMap();
|
|
560
|
+
if (installed.get(webServer) === true) return;
|
|
561
|
+
installed.set(webServer, true);
|
|
562
|
+
const authorized = (req) => {
|
|
563
|
+
const authorization = req.headers?.authorization ?? "";
|
|
564
|
+
return authorization === "Bearer " + live.token;
|
|
565
|
+
};
|
|
566
|
+
const send = (res, status, payload) => {
|
|
567
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
568
|
+
res.end(JSON.stringify(payload));
|
|
569
|
+
};
|
|
570
|
+
const readBody = (req, limit = 256 * 1024) => new Promise((resolve, reject) => {
|
|
571
|
+
const chunks = [];
|
|
572
|
+
let size = 0;
|
|
573
|
+
req.on("data", (chunk) => {
|
|
574
|
+
size += chunk.length;
|
|
575
|
+
if (size > limit) {
|
|
576
|
+
reject(new Error("request body too large"));
|
|
577
|
+
req.destroy();
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
chunks.push(chunk);
|
|
581
|
+
});
|
|
582
|
+
req.on("end", () => {
|
|
583
|
+
try {
|
|
584
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"));
|
|
585
|
+
} catch (error) {
|
|
586
|
+
reject(new Error("invalid JSON body"));
|
|
587
|
+
}
|
|
588
|
+
});
|
|
589
|
+
});
|
|
590
|
+
const findEntry = () => {
|
|
591
|
+
const editor = ctx.get?.("configEditor");
|
|
592
|
+
if (editor === void 0) throw new Error("config editor is unavailable");
|
|
593
|
+
const entry = editor.entries().find((item) => item.options?.id === "general-mcp");
|
|
594
|
+
if (entry === void 0) throw new Error("loader entry general-mcp not found");
|
|
595
|
+
return { editor, entry };
|
|
596
|
+
};
|
|
597
|
+
try {
|
|
598
|
+
webServer.register({
|
|
599
|
+
kind: "exact",
|
|
600
|
+
path: "/api/general-mcp/catalog",
|
|
601
|
+
resource: async (request) => {
|
|
602
|
+
const headers = request.headers;
|
|
603
|
+
const bearer = headers?.get?.("authorization") === "Bearer " + live.token;
|
|
604
|
+
const sameOrigin = headers?.get?.("sec-fetch-site") === "same-origin";
|
|
605
|
+
if (!bearer && !sameOrigin) {
|
|
606
|
+
return new Response("unauthorized", { status: 401, headers: { "cache-control": "no-store" } });
|
|
607
|
+
}
|
|
608
|
+
const url = new URL(request.url);
|
|
609
|
+
const raw = url.searchParams.get("since");
|
|
610
|
+
const since = raw !== null && /^\d+$/.test(raw) ? Number(raw) : -1;
|
|
611
|
+
if (since === live.version) return new Response(null, { status: 304, headers: { "cache-control": "no-store" } });
|
|
612
|
+
return new Response(JSON.stringify({
|
|
613
|
+
version: live.version,
|
|
614
|
+
server: live.serverName,
|
|
615
|
+
status: live.connected ? "connected" : "idle",
|
|
616
|
+
endpoint: live.endpoint,
|
|
617
|
+
lastError: live.lastError,
|
|
618
|
+
tools: live.catalog,
|
|
619
|
+
overrides: live.toolSettings
|
|
620
|
+
}), { status: 200, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });
|
|
621
|
+
}
|
|
622
|
+
});
|
|
623
|
+
webServer.register({
|
|
624
|
+
kind: "exact",
|
|
625
|
+
path: "/api/general-mcp/probe",
|
|
626
|
+
handler: (req, res) => {
|
|
627
|
+
void (async () => {
|
|
628
|
+
try {
|
|
629
|
+
if (!authorized(req)) {
|
|
630
|
+
send(res, 401, { ok: false, message: "unauthorized" });
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
const body = await readBody(req);
|
|
634
|
+
const endpoint = typeof body.endpoint === "string" ? body.endpoint.trim() : "";
|
|
635
|
+
if (!/^https?:\/\//i.test(endpoint)) throw new Error("endpoint must be an http(s) URL");
|
|
636
|
+
const headers = {};
|
|
637
|
+
if (body.headers !== null && typeof body.headers === "object" && !Array.isArray(body.headers)) {
|
|
638
|
+
for (const [key, value] of Object.entries(body.headers)) {
|
|
639
|
+
if (typeof value === "string") headers[key] = value;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
const probe = new McpClient(endpoint, headers, 15e3);
|
|
643
|
+
const info = await probe.initialize();
|
|
644
|
+
const tools = await probe.listTools();
|
|
645
|
+
send(res, 200, {
|
|
646
|
+
ok: true,
|
|
647
|
+
protocolVersion: info?.protocolVersion ?? null,
|
|
648
|
+
server: info?.serverInfo?.name ?? null,
|
|
649
|
+
version: info?.serverInfo?.version ?? null,
|
|
650
|
+
tools: tools.map((tool) => ({ name: tool.name, description: tool.description ?? "", folder: tool._meta?.["dsh/folder"] ?? null }))
|
|
651
|
+
});
|
|
652
|
+
} catch (error) {
|
|
653
|
+
send(res, 200, { ok: false, message: String(error?.message ?? error) });
|
|
654
|
+
}
|
|
655
|
+
})();
|
|
656
|
+
}
|
|
657
|
+
});
|
|
658
|
+
webServer.register({
|
|
659
|
+
kind: "exact",
|
|
660
|
+
path: "/api/general-mcp/config",
|
|
661
|
+
handler: (req, res) => {
|
|
662
|
+
void (async () => {
|
|
663
|
+
try {
|
|
664
|
+
if (!authorized(req)) {
|
|
665
|
+
send(res, 401, { ok: false, message: "unauthorized" });
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
const body = await readBody(req);
|
|
669
|
+
const { editor, entry } = findEntry();
|
|
670
|
+
const next = {};
|
|
671
|
+
if (typeof body.endpoint === "string") next.endpoint = body.endpoint.trim();
|
|
672
|
+
if (body.headers !== null && typeof body.headers === "object") next.headers = body.headers;
|
|
673
|
+
if (typeof body.toolCallTimeoutMs === "number") next.toolCallTimeoutMs = body.toolCallTimeoutMs;
|
|
674
|
+
await editor.edit(entry, (current) => ({ ...current, ...next }));
|
|
675
|
+
beacon("config-saved");
|
|
676
|
+
send(res, 200, { ok: true });
|
|
677
|
+
} catch (error) {
|
|
678
|
+
beacon("config-save-error " + String(error));
|
|
679
|
+
send(res, 500, { ok: false, message: String(error?.message ?? error) });
|
|
680
|
+
}
|
|
681
|
+
})();
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
webServer.register({
|
|
685
|
+
kind: "exact",
|
|
686
|
+
path: "/api/general-mcp/tools",
|
|
687
|
+
handler: (req, res) => {
|
|
688
|
+
void (async () => {
|
|
689
|
+
try {
|
|
690
|
+
if (!authorized(req)) {
|
|
691
|
+
send(res, 401, { ok: false, message: "unauthorized" });
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
const body = await readBody(req);
|
|
695
|
+
const { editor, entry } = findEntry();
|
|
696
|
+
const tools = {
|
|
697
|
+
disabled: Array.isArray(body.disabled) ? body.disabled.filter((v) => typeof v === "string") : [],
|
|
698
|
+
hidden: Array.isArray(body.hidden) ? body.hidden.filter((v) => typeof v === "string") : [],
|
|
699
|
+
overrides: body.overrides !== null && typeof body.overrides === "object" ? body.overrides : {}
|
|
700
|
+
};
|
|
701
|
+
await editor.edit(entry, (current) => ({ ...current, tools }));
|
|
702
|
+
beacon("tools-saved");
|
|
703
|
+
send(res, 200, { ok: true });
|
|
704
|
+
} catch (error) {
|
|
705
|
+
beacon("tools-save-error " + String(error));
|
|
706
|
+
send(res, 500, { ok: false, message: String(error?.message ?? error) });
|
|
707
|
+
}
|
|
708
|
+
})();
|
|
709
|
+
}
|
|
710
|
+
});
|
|
711
|
+
beacon("routes-installed");
|
|
712
|
+
} catch (error) {
|
|
713
|
+
beacon("host-route-error " + String(error));
|
|
714
|
+
}
|
|
715
|
+
};
|
|
716
|
+
const startRoutes = (webCtx) => {
|
|
717
|
+
try {
|
|
718
|
+
installRoutes(webCtx);
|
|
719
|
+
} catch (error) {
|
|
720
|
+
beacon("host-route-failed " + String(error));
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
if (typeof ctx.inject === "function") {
|
|
724
|
+
try {
|
|
725
|
+
ctx.inject(["webServer"], (sub) => startRoutes(sub));
|
|
726
|
+
} catch (error) {
|
|
727
|
+
beacon("host-inject-failed " + String(error));
|
|
728
|
+
startRoutes(ctx);
|
|
729
|
+
}
|
|
730
|
+
} else {
|
|
731
|
+
startRoutes(ctx);
|
|
732
|
+
}
|
|
733
|
+
const onInject = (table) => {
|
|
734
|
+
table.push({
|
|
735
|
+
kind: "global",
|
|
736
|
+
name: "__GENMCP__",
|
|
737
|
+
value: { token: live.token, server: live.serverName, catalogPath: "/api/general-mcp/catalog" }
|
|
738
|
+
});
|
|
739
|
+
};
|
|
740
|
+
ctx.effect(() => ctx.on("webserver/index-inject", onInject));
|
|
741
|
+
stopRetry();
|
|
742
|
+
void sync().then((ok) => {
|
|
743
|
+
if (!ok && state().endpoint !== "") scheduleRetry();
|
|
744
|
+
}).catch((error) => {
|
|
745
|
+
const current = state();
|
|
746
|
+
current.lastError = String(error?.message ?? error);
|
|
747
|
+
current.version += 1;
|
|
748
|
+
});
|
|
749
|
+
ctx.effect(() => () => stopRetry());
|
|
750
|
+
const statusDispose = ctx.tools.register({
|
|
751
|
+
name: "general_mcp_status",
|
|
752
|
+
description: "Report the general-mcp gateway connection status.",
|
|
753
|
+
parameters: { type: "object", properties: {}, additionalProperties: false },
|
|
754
|
+
output: {
|
|
755
|
+
schema: {
|
|
756
|
+
type: "object",
|
|
757
|
+
properties: {
|
|
758
|
+
ok: { type: "boolean" },
|
|
759
|
+
serverName: { type: "string" },
|
|
760
|
+
endpoint: { type: "string" },
|
|
761
|
+
connected: { type: "boolean" },
|
|
762
|
+
toolCount: { type: "number" },
|
|
763
|
+
lastError: { type: "string" },
|
|
764
|
+
startedAt: { type: "string" }
|
|
765
|
+
},
|
|
766
|
+
required: ["ok", "serverName", "endpoint", "connected", "toolCount", "lastError", "startedAt"],
|
|
767
|
+
additionalProperties: false
|
|
768
|
+
},
|
|
769
|
+
render(_args, value) {
|
|
770
|
+
return [{
|
|
771
|
+
type: "text",
|
|
772
|
+
text: "general-mcp: " + value.serverName + " endpoint=" + (value.endpoint === "" ? "(unset)" : value.endpoint) + " connected=" + value.connected + " tools=" + value.toolCount + (value.lastError === "" ? "" : " error=" + value.lastError)
|
|
773
|
+
}];
|
|
774
|
+
}
|
|
775
|
+
},
|
|
776
|
+
async execute() {
|
|
777
|
+
return {
|
|
778
|
+
ok: live.endpoint !== "" && live.lastError === "" && live.connected,
|
|
779
|
+
serverName: live.serverName,
|
|
780
|
+
endpoint: live.endpoint,
|
|
781
|
+
connected: live.connected,
|
|
782
|
+
toolCount: live.toolCount,
|
|
783
|
+
lastError: live.lastError,
|
|
784
|
+
startedAt
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
});
|
|
788
|
+
ctx.effect(() => () => statusDispose());
|
|
789
|
+
}
|
|
790
|
+
export {
|
|
791
|
+
apply,
|
|
792
|
+
inject,
|
|
793
|
+
name
|
|
794
|
+
};
|