mcp-expose 1.0.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/CHANGELOG.md +39 -0
- package/LICENSE +21 -0
- package/README.md +708 -0
- package/dist/adonisjs/index.cjs +708 -0
- package/dist/adonisjs/index.cjs.map +1 -0
- package/dist/adonisjs/index.d.cts +68 -0
- package/dist/adonisjs/index.d.ts +68 -0
- package/dist/adonisjs/index.js +684 -0
- package/dist/adonisjs/index.js.map +1 -0
- package/dist/express/index.cjs +789 -0
- package/dist/express/index.cjs.map +1 -0
- package/dist/express/index.d.cts +61 -0
- package/dist/express/index.d.ts +61 -0
- package/dist/express/index.js +763 -0
- package/dist/express/index.js.map +1 -0
- package/dist/fastify/index.cjs +660 -0
- package/dist/fastify/index.cjs.map +1 -0
- package/dist/fastify/index.d.cts +42 -0
- package/dist/fastify/index.d.ts +42 -0
- package/dist/fastify/index.js +635 -0
- package/dist/fastify/index.js.map +1 -0
- package/dist/hono/index.cjs +656 -0
- package/dist/hono/index.cjs.map +1 -0
- package/dist/hono/index.d.cts +44 -0
- package/dist/hono/index.d.ts +44 -0
- package/dist/hono/index.js +630 -0
- package/dist/hono/index.js.map +1 -0
- package/dist/index.cjs +720 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +81 -0
- package/dist/index.d.ts +81 -0
- package/dist/index.js +686 -0
- package/dist/index.js.map +1 -0
- package/dist/koa/index.cjs +739 -0
- package/dist/koa/index.cjs.map +1 -0
- package/dist/koa/index.d.cts +68 -0
- package/dist/koa/index.d.ts +68 -0
- package/dist/koa/index.js +709 -0
- package/dist/koa/index.js.map +1 -0
- package/dist/nestjs/index.cjs +1117 -0
- package/dist/nestjs/index.cjs.map +1 -0
- package/dist/nestjs/index.d.cts +104 -0
- package/dist/nestjs/index.d.ts +104 -0
- package/dist/nestjs/index.js +1079 -0
- package/dist/nestjs/index.js.map +1 -0
- package/dist/server-fzkb-wJo.d.cts +194 -0
- package/dist/server-fzkb-wJo.d.ts +194 -0
- package/package.json +225 -0
|
@@ -0,0 +1,763 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
|
|
4
|
+
// src/core/dispatch.ts
|
|
5
|
+
function buildUrl(base, req) {
|
|
6
|
+
const url = new URL(base.replace(/\/+$/, "") + req.path);
|
|
7
|
+
for (const [k, v] of Object.entries(req.query)) {
|
|
8
|
+
for (const item of Array.isArray(v) ? v : [
|
|
9
|
+
v
|
|
10
|
+
]) url.searchParams.append(k, item);
|
|
11
|
+
}
|
|
12
|
+
return url.toString();
|
|
13
|
+
}
|
|
14
|
+
__name(buildUrl, "buildUrl");
|
|
15
|
+
function createFetchDispatcher(opts) {
|
|
16
|
+
const doFetch = opts.fetch ?? fetch;
|
|
17
|
+
return async (req, ctx) => {
|
|
18
|
+
const base = typeof opts.baseUrl === "function" ? opts.baseUrl(ctx) : opts.baseUrl;
|
|
19
|
+
const res = await doFetch(buildUrl(base, req), {
|
|
20
|
+
method: req.method,
|
|
21
|
+
headers: req.headers,
|
|
22
|
+
body: req.body === void 0 || req.method === "GET" || req.method === "HEAD" ? void 0 : JSON.stringify(req.body),
|
|
23
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? 3e4)
|
|
24
|
+
});
|
|
25
|
+
const headers = {};
|
|
26
|
+
res.headers.forEach((v, k) => headers[k] = v);
|
|
27
|
+
return {
|
|
28
|
+
status: res.status,
|
|
29
|
+
headers,
|
|
30
|
+
body: await res.text()
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
__name(createFetchDispatcher, "createFetchDispatcher");
|
|
35
|
+
|
|
36
|
+
// src/core/marker.ts
|
|
37
|
+
var MCP_TOOL = /* @__PURE__ */ Symbol.for("mcp-expose.tool");
|
|
38
|
+
function markerOf(fn) {
|
|
39
|
+
return typeof fn === "function" ? fn[MCP_TOOL] : void 0;
|
|
40
|
+
}
|
|
41
|
+
__name(markerOf, "markerOf");
|
|
42
|
+
function mark(fn, opts) {
|
|
43
|
+
Object.defineProperty(fn, MCP_TOOL, {
|
|
44
|
+
value: opts,
|
|
45
|
+
enumerable: false
|
|
46
|
+
});
|
|
47
|
+
return fn;
|
|
48
|
+
}
|
|
49
|
+
__name(mark, "mark");
|
|
50
|
+
|
|
51
|
+
// src/core/node.ts
|
|
52
|
+
function normalizeHeaders(headers) {
|
|
53
|
+
const out = {};
|
|
54
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
55
|
+
if (v === void 0) continue;
|
|
56
|
+
out[k.toLowerCase()] = Array.isArray(v) ? v.join(", ") : String(v);
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
__name(normalizeHeaders, "normalizeHeaders");
|
|
61
|
+
function readRawBody(req, limit = 4 * 1024 * 1024) {
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
let size = 0;
|
|
64
|
+
const chunks = [];
|
|
65
|
+
req.on("data", (c) => {
|
|
66
|
+
size += c.length;
|
|
67
|
+
if (size > limit) {
|
|
68
|
+
reject(new Error("Request body too large"));
|
|
69
|
+
req.destroy();
|
|
70
|
+
} else chunks.push(c);
|
|
71
|
+
});
|
|
72
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
73
|
+
req.on("error", reject);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
__name(readRawBody, "readRawBody");
|
|
77
|
+
function loopbackBaseUrl(req) {
|
|
78
|
+
const socket = req.socket;
|
|
79
|
+
const port = socket.localPort;
|
|
80
|
+
const encrypted = socket.encrypted;
|
|
81
|
+
const bound = socket.server?.address();
|
|
82
|
+
let host = typeof bound === "object" && bound?.address || socket.localAddress || "127.0.0.1";
|
|
83
|
+
if (host.startsWith("::ffff:")) host = host.slice(7);
|
|
84
|
+
if (host === "::" || host === "0.0.0.0") host = "127.0.0.1";
|
|
85
|
+
if (host.includes(":")) host = `[${host}]`;
|
|
86
|
+
return `${encrypted ? "https" : "http"}://${host}:${port}`;
|
|
87
|
+
}
|
|
88
|
+
__name(loopbackBaseUrl, "loopbackBaseUrl");
|
|
89
|
+
function writeNodeResponse(res, out) {
|
|
90
|
+
res.statusCode = out.status;
|
|
91
|
+
for (const [k, v] of Object.entries(out.headers)) res.setHeader(k, v);
|
|
92
|
+
res.end(out.body);
|
|
93
|
+
}
|
|
94
|
+
__name(writeNodeResponse, "writeNodeResponse");
|
|
95
|
+
|
|
96
|
+
// src/core/schema.ts
|
|
97
|
+
function isStandard(s) {
|
|
98
|
+
return typeof s === "object" && s !== null && "~standard" in s;
|
|
99
|
+
}
|
|
100
|
+
__name(isStandard, "isStandard");
|
|
101
|
+
function toJsonSchema(schema) {
|
|
102
|
+
if (schema === void 0 || schema === null) return void 0;
|
|
103
|
+
let out;
|
|
104
|
+
if (isStandard(schema) && typeof schema["~standard"].jsonSchema?.input === "function") {
|
|
105
|
+
out = schema["~standard"].jsonSchema.input({
|
|
106
|
+
target: "draft-2020-12"
|
|
107
|
+
});
|
|
108
|
+
} else if (typeof schema.toJSONSchema === "function") {
|
|
109
|
+
out = schema.toJSONSchema();
|
|
110
|
+
} else if (isStandard(schema)) {
|
|
111
|
+
throw new Error("mcp-expose: this schema library does not support JSON Schema export. Pass a plain JSON Schema instead.");
|
|
112
|
+
} else {
|
|
113
|
+
out = schema;
|
|
114
|
+
}
|
|
115
|
+
const { $schema: _ignored, ...rest } = out;
|
|
116
|
+
return rest;
|
|
117
|
+
}
|
|
118
|
+
__name(toJsonSchema, "toJsonSchema");
|
|
119
|
+
function toValidator(schema) {
|
|
120
|
+
if (!isStandard(schema) || typeof schema["~standard"].validate !== "function") return void 0;
|
|
121
|
+
const validate = schema["~standard"].validate;
|
|
122
|
+
return async (value) => {
|
|
123
|
+
const result = await validate(value);
|
|
124
|
+
if (!result.issues) return {
|
|
125
|
+
ok: true,
|
|
126
|
+
value: result.value
|
|
127
|
+
};
|
|
128
|
+
const message = result.issues.map((i) => {
|
|
129
|
+
const path = (i.path ?? []).map((p) => typeof p === "object" ? String(p.key) : String(p)).join(".");
|
|
130
|
+
return path ? `${path}: ${i.message}` : i.message;
|
|
131
|
+
}).join("; ");
|
|
132
|
+
return {
|
|
133
|
+
ok: false,
|
|
134
|
+
message
|
|
135
|
+
};
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
__name(toValidator, "toValidator");
|
|
139
|
+
function checkRequired(schema, args) {
|
|
140
|
+
const missing = (schema.required ?? []).filter((k) => args[k] === void 0);
|
|
141
|
+
return missing.length ? `Missing required argument(s): ${missing.join(", ")}` : void 0;
|
|
142
|
+
}
|
|
143
|
+
__name(checkRequired, "checkRequired");
|
|
144
|
+
|
|
145
|
+
// src/core/route-tool.ts
|
|
146
|
+
var DEFAULT_FORWARD_HEADERS = [
|
|
147
|
+
"authorization",
|
|
148
|
+
"cookie",
|
|
149
|
+
"x-api-key",
|
|
150
|
+
"accept-language"
|
|
151
|
+
];
|
|
152
|
+
var BODY_METHODS = /* @__PURE__ */ new Set([
|
|
153
|
+
"POST",
|
|
154
|
+
"PUT",
|
|
155
|
+
"PATCH"
|
|
156
|
+
]);
|
|
157
|
+
var PARAM_RE = /:([A-Za-z0-9_]+)\??|\{([A-Za-z0-9_]+)\}/g;
|
|
158
|
+
function pathParams(path) {
|
|
159
|
+
return [
|
|
160
|
+
...path.matchAll(PARAM_RE)
|
|
161
|
+
].map((m) => m[1] ?? m[2]);
|
|
162
|
+
}
|
|
163
|
+
__name(pathParams, "pathParams");
|
|
164
|
+
function encodeSegment(name, value) {
|
|
165
|
+
const raw = String(value);
|
|
166
|
+
if (raw === "" || raw === "." || raw === "..") {
|
|
167
|
+
throw new Error(`Invalid value for path parameter "${name}": ${JSON.stringify(raw)}`);
|
|
168
|
+
}
|
|
169
|
+
return encodeURIComponent(raw);
|
|
170
|
+
}
|
|
171
|
+
__name(encodeSegment, "encodeSegment");
|
|
172
|
+
function interpolatePath(path, values) {
|
|
173
|
+
return path.replace(/\/:([A-Za-z0-9_]+)\?/g, (_, k) => values[k] === void 0 ? "" : `/${encodeSegment(k, values[k])}`).replace(PARAM_RE, (_, a, b) => {
|
|
174
|
+
const k = a ?? b;
|
|
175
|
+
return encodeSegment(k, values[k]);
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
__name(interpolatePath, "interpolatePath");
|
|
179
|
+
function joinPaths(...parts) {
|
|
180
|
+
const joined = parts.filter((p) => !!p && p !== "/").map((p) => p.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
|
|
181
|
+
return `/${joined}`;
|
|
182
|
+
}
|
|
183
|
+
__name(joinPaths, "joinPaths");
|
|
184
|
+
function toolNameFromRoute(method, path) {
|
|
185
|
+
const segments = path.split("/").filter(Boolean).map((s) => {
|
|
186
|
+
const m = /^(?::([A-Za-z0-9_]+)\??|\{([A-Za-z0-9_]+)\})$/.exec(s);
|
|
187
|
+
return m ? `by_${m[1] ?? m[2]}` : s;
|
|
188
|
+
});
|
|
189
|
+
return sanitizeToolName([
|
|
190
|
+
method.toLowerCase(),
|
|
191
|
+
...segments
|
|
192
|
+
].join("_"));
|
|
193
|
+
}
|
|
194
|
+
__name(toolNameFromRoute, "toolNameFromRoute");
|
|
195
|
+
function sanitizeToolName(name) {
|
|
196
|
+
return name.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "").slice(0, 64);
|
|
197
|
+
}
|
|
198
|
+
__name(sanitizeToolName, "sanitizeToolName");
|
|
199
|
+
function defaultAnnotations(method) {
|
|
200
|
+
switch (method) {
|
|
201
|
+
case "GET":
|
|
202
|
+
case "HEAD":
|
|
203
|
+
return {
|
|
204
|
+
readOnlyHint: true,
|
|
205
|
+
openWorldHint: false
|
|
206
|
+
};
|
|
207
|
+
case "DELETE":
|
|
208
|
+
return {
|
|
209
|
+
readOnlyHint: false,
|
|
210
|
+
destructiveHint: true,
|
|
211
|
+
idempotentHint: true,
|
|
212
|
+
openWorldHint: false
|
|
213
|
+
};
|
|
214
|
+
case "PUT":
|
|
215
|
+
return {
|
|
216
|
+
readOnlyHint: false,
|
|
217
|
+
destructiveHint: false,
|
|
218
|
+
idempotentHint: true,
|
|
219
|
+
openWorldHint: false
|
|
220
|
+
};
|
|
221
|
+
default:
|
|
222
|
+
return {
|
|
223
|
+
readOnlyHint: false,
|
|
224
|
+
destructiveHint: false,
|
|
225
|
+
openWorldHint: false
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
__name(defaultAnnotations, "defaultAnnotations");
|
|
230
|
+
function buildInputSchema(route, opts) {
|
|
231
|
+
const method = route.method.toUpperCase();
|
|
232
|
+
const params = pathParams(route.path);
|
|
233
|
+
const mapping = {
|
|
234
|
+
params,
|
|
235
|
+
query: /* @__PURE__ */ new Set(),
|
|
236
|
+
body: /* @__PURE__ */ new Set(),
|
|
237
|
+
wholeBody: false,
|
|
238
|
+
bodyMethod: BODY_METHODS.has(method)
|
|
239
|
+
};
|
|
240
|
+
if (opts.input) {
|
|
241
|
+
const schema2 = toJsonSchema(opts.input);
|
|
242
|
+
return {
|
|
243
|
+
schema: {
|
|
244
|
+
type: "object",
|
|
245
|
+
...schema2
|
|
246
|
+
},
|
|
247
|
+
mapping
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
const properties = {};
|
|
251
|
+
const required = /* @__PURE__ */ new Set();
|
|
252
|
+
const paramSchema = toJsonSchema(opts.params);
|
|
253
|
+
for (const p of params) {
|
|
254
|
+
properties[p] = paramSchema?.properties?.[p] ?? {
|
|
255
|
+
type: "string",
|
|
256
|
+
description: `Path parameter "${p}"`
|
|
257
|
+
};
|
|
258
|
+
if (!route.path.includes(`:${p}?`)) required.add(p);
|
|
259
|
+
}
|
|
260
|
+
const querySchema = toJsonSchema(opts.query);
|
|
261
|
+
for (const [k, v] of Object.entries(querySchema?.properties ?? {})) {
|
|
262
|
+
properties[k] = v;
|
|
263
|
+
mapping.query.add(k);
|
|
264
|
+
}
|
|
265
|
+
for (const k of querySchema?.required ?? []) required.add(k);
|
|
266
|
+
const bodySchema = toJsonSchema(opts.body);
|
|
267
|
+
if (bodySchema) {
|
|
268
|
+
if (bodySchema.properties && (bodySchema.type === void 0 || bodySchema.type === "object")) {
|
|
269
|
+
for (const [k, v] of Object.entries(bodySchema.properties)) {
|
|
270
|
+
properties[k] = v;
|
|
271
|
+
mapping.body.add(k);
|
|
272
|
+
}
|
|
273
|
+
for (const k of bodySchema.required ?? []) required.add(k);
|
|
274
|
+
} else {
|
|
275
|
+
properties.body = bodySchema;
|
|
276
|
+
required.add("body");
|
|
277
|
+
mapping.wholeBody = true;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
const schema = {
|
|
281
|
+
type: "object",
|
|
282
|
+
properties
|
|
283
|
+
};
|
|
284
|
+
if (required.size) schema.required = [
|
|
285
|
+
...required
|
|
286
|
+
];
|
|
287
|
+
return {
|
|
288
|
+
schema,
|
|
289
|
+
mapping
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
__name(buildInputSchema, "buildInputSchema");
|
|
293
|
+
function splitArgs(args, mapping) {
|
|
294
|
+
const pathValues = {};
|
|
295
|
+
const query = {};
|
|
296
|
+
let body;
|
|
297
|
+
for (const [k, v] of Object.entries(args)) {
|
|
298
|
+
if (v === void 0) continue;
|
|
299
|
+
if (mapping.params.includes(k)) {
|
|
300
|
+
pathValues[k] = v;
|
|
301
|
+
} else if (mapping.wholeBody && k === "body") {
|
|
302
|
+
body = v;
|
|
303
|
+
} else if (mapping.query.has(k) || !mapping.body.has(k) && !mapping.bodyMethod) {
|
|
304
|
+
query[k] = Array.isArray(v) ? v.map(String) : typeof v === "object" && v !== null ? JSON.stringify(v) : String(v);
|
|
305
|
+
} else {
|
|
306
|
+
body = {
|
|
307
|
+
...body ?? {},
|
|
308
|
+
[k]: v
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (body === void 0 && mapping.bodyMethod) body = {};
|
|
313
|
+
return {
|
|
314
|
+
pathValues,
|
|
315
|
+
query,
|
|
316
|
+
body
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
__name(splitArgs, "splitArgs");
|
|
320
|
+
function responseToResult(res, maxChars) {
|
|
321
|
+
let text = res.body;
|
|
322
|
+
if (text.length > maxChars) text = `${text.slice(0, maxChars)}
|
|
323
|
+
\u2026[truncated ${text.length - maxChars} chars]`;
|
|
324
|
+
const isError = res.status >= 400;
|
|
325
|
+
const result = {
|
|
326
|
+
content: [
|
|
327
|
+
{
|
|
328
|
+
type: "text",
|
|
329
|
+
text: isError ? `HTTP ${res.status}
|
|
330
|
+
${text}` : text || `HTTP ${res.status}`
|
|
331
|
+
}
|
|
332
|
+
]
|
|
333
|
+
};
|
|
334
|
+
if (isError) {
|
|
335
|
+
result.isError = true;
|
|
336
|
+
return result;
|
|
337
|
+
}
|
|
338
|
+
if ((res.headers["content-type"] ?? "").includes("json") && text === res.body) {
|
|
339
|
+
try {
|
|
340
|
+
const parsed = JSON.parse(res.body);
|
|
341
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) result.structuredContent = parsed;
|
|
342
|
+
} catch {
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return result;
|
|
346
|
+
}
|
|
347
|
+
__name(responseToResult, "responseToResult");
|
|
348
|
+
function pickForwardHeaders(ctx, names) {
|
|
349
|
+
const out = {};
|
|
350
|
+
for (const name of names) {
|
|
351
|
+
const v = ctx.headers[name.toLowerCase()];
|
|
352
|
+
if (v !== void 0) out[name.toLowerCase()] = v;
|
|
353
|
+
}
|
|
354
|
+
return out;
|
|
355
|
+
}
|
|
356
|
+
__name(pickForwardHeaders, "pickForwardHeaders");
|
|
357
|
+
function createRouteTool(route, opts, dispatch, serverOpts = {}) {
|
|
358
|
+
const method = route.method.toUpperCase();
|
|
359
|
+
const name = sanitizeToolName(opts.name ?? toolNameFromRoute(method, route.path));
|
|
360
|
+
const { schema, mapping } = buildInputSchema(route, opts);
|
|
361
|
+
const forward = serverOpts.forwardHeaders ?? DEFAULT_FORWARD_HEADERS;
|
|
362
|
+
const maxChars = serverOpts.maxResponseChars ?? 1e5;
|
|
363
|
+
return {
|
|
364
|
+
name,
|
|
365
|
+
title: opts.title,
|
|
366
|
+
description: opts.description ?? `${method} ${route.path}`,
|
|
367
|
+
inputSchema: schema,
|
|
368
|
+
annotations: {
|
|
369
|
+
...defaultAnnotations(method),
|
|
370
|
+
...opts.annotations
|
|
371
|
+
},
|
|
372
|
+
validate: toValidator(opts.input),
|
|
373
|
+
async handler(args, ctx) {
|
|
374
|
+
const missing = opts.input ? void 0 : checkRequired(schema, args);
|
|
375
|
+
if (missing) return {
|
|
376
|
+
isError: true,
|
|
377
|
+
content: [
|
|
378
|
+
{
|
|
379
|
+
type: "text",
|
|
380
|
+
text: missing
|
|
381
|
+
}
|
|
382
|
+
]
|
|
383
|
+
};
|
|
384
|
+
const { pathValues, query, body } = splitArgs(args, mapping);
|
|
385
|
+
const headers = {
|
|
386
|
+
accept: "application/json",
|
|
387
|
+
...pickForwardHeaders(ctx, forward),
|
|
388
|
+
...opts.headers,
|
|
389
|
+
"x-mcp-tool": name
|
|
390
|
+
};
|
|
391
|
+
if (ctx.clientIp) headers["x-forwarded-for"] = ctx.clientIp;
|
|
392
|
+
if (body !== void 0) headers["content-type"] = "application/json";
|
|
393
|
+
let path;
|
|
394
|
+
try {
|
|
395
|
+
path = interpolatePath(route.path, pathValues);
|
|
396
|
+
} catch (err) {
|
|
397
|
+
return {
|
|
398
|
+
isError: true,
|
|
399
|
+
content: [
|
|
400
|
+
{
|
|
401
|
+
type: "text",
|
|
402
|
+
text: err.message
|
|
403
|
+
}
|
|
404
|
+
]
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
const res = await dispatch({
|
|
408
|
+
method,
|
|
409
|
+
path,
|
|
410
|
+
query,
|
|
411
|
+
body,
|
|
412
|
+
headers
|
|
413
|
+
}, ctx);
|
|
414
|
+
return responseToResult(res, maxChars);
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
__name(createRouteTool, "createRouteTool");
|
|
419
|
+
|
|
420
|
+
// src/core/server.ts
|
|
421
|
+
var SUPPORTED_PROTOCOL_VERSIONS = [
|
|
422
|
+
"2025-11-25",
|
|
423
|
+
"2025-06-18",
|
|
424
|
+
"2025-03-26",
|
|
425
|
+
"2024-11-05"
|
|
426
|
+
];
|
|
427
|
+
var LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0];
|
|
428
|
+
var PARSE_ERROR = -32700;
|
|
429
|
+
var INVALID_REQUEST = -32600;
|
|
430
|
+
var METHOD_NOT_FOUND = -32601;
|
|
431
|
+
var INVALID_PARAMS = -32602;
|
|
432
|
+
var ok = /* @__PURE__ */ __name((id, result) => ({
|
|
433
|
+
jsonrpc: "2.0",
|
|
434
|
+
id,
|
|
435
|
+
result
|
|
436
|
+
}), "ok");
|
|
437
|
+
var fail = /* @__PURE__ */ __name((id, code, message) => ({
|
|
438
|
+
jsonrpc: "2.0",
|
|
439
|
+
id,
|
|
440
|
+
error: {
|
|
441
|
+
code,
|
|
442
|
+
message
|
|
443
|
+
}
|
|
444
|
+
}), "fail");
|
|
445
|
+
var McpServer = class {
|
|
446
|
+
static {
|
|
447
|
+
__name(this, "McpServer");
|
|
448
|
+
}
|
|
449
|
+
options;
|
|
450
|
+
tools = /* @__PURE__ */ new Map();
|
|
451
|
+
loaders = [];
|
|
452
|
+
constructor(options) {
|
|
453
|
+
this.options = options;
|
|
454
|
+
}
|
|
455
|
+
/** Register a tool. Throws on duplicate names. */
|
|
456
|
+
addTool(tool) {
|
|
457
|
+
if (this.tools.has(tool.name)) {
|
|
458
|
+
throw new Error(`mcp-expose: duplicate tool name "${tool.name}". Set an explicit \`name\`.`);
|
|
459
|
+
}
|
|
460
|
+
this.tools.set(tool.name, tool);
|
|
461
|
+
return this;
|
|
462
|
+
}
|
|
463
|
+
/** Register a function that adds tools lazily, right before the first MCP request is served. */
|
|
464
|
+
onLoad(loader) {
|
|
465
|
+
this.loaders.push(loader);
|
|
466
|
+
return this;
|
|
467
|
+
}
|
|
468
|
+
async listTools() {
|
|
469
|
+
await this.load();
|
|
470
|
+
return [
|
|
471
|
+
...this.tools.values()
|
|
472
|
+
];
|
|
473
|
+
}
|
|
474
|
+
async load() {
|
|
475
|
+
if (!this.loaders.length) return;
|
|
476
|
+
const loaders = this.loaders;
|
|
477
|
+
this.loaders = [];
|
|
478
|
+
for (const l of loaders) await l();
|
|
479
|
+
}
|
|
480
|
+
/** Handle one JSON-RPC message (or a batch). Returns null when no response is due. */
|
|
481
|
+
async handleMessage(message, ctx) {
|
|
482
|
+
if (Array.isArray(message)) {
|
|
483
|
+
const results = (await Promise.all(message.map((m) => this.handleOne(m, ctx)))).filter((r) => r !== null);
|
|
484
|
+
return results.length ? results : null;
|
|
485
|
+
}
|
|
486
|
+
return this.handleOne(message, ctx);
|
|
487
|
+
}
|
|
488
|
+
async handleOne(message, ctx) {
|
|
489
|
+
const msg = message;
|
|
490
|
+
if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") {
|
|
491
|
+
return fail(null, INVALID_REQUEST, "Invalid JSON-RPC message");
|
|
492
|
+
}
|
|
493
|
+
if (typeof msg.method !== "string" || msg.id === void 0) return null;
|
|
494
|
+
const id = msg.id;
|
|
495
|
+
const params = msg.params ?? {};
|
|
496
|
+
await this.load();
|
|
497
|
+
switch (msg.method) {
|
|
498
|
+
case "initialize": {
|
|
499
|
+
const requested = params.protocolVersion;
|
|
500
|
+
const protocolVersion = requested && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;
|
|
501
|
+
return ok(id, {
|
|
502
|
+
protocolVersion,
|
|
503
|
+
capabilities: {
|
|
504
|
+
tools: {
|
|
505
|
+
listChanged: false
|
|
506
|
+
}
|
|
507
|
+
},
|
|
508
|
+
serverInfo: {
|
|
509
|
+
name: this.options.name,
|
|
510
|
+
version: this.options.version ?? "1.0.0"
|
|
511
|
+
},
|
|
512
|
+
...this.options.instructions ? {
|
|
513
|
+
instructions: this.options.instructions
|
|
514
|
+
} : {}
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
case "ping":
|
|
518
|
+
return ok(id, {});
|
|
519
|
+
case "tools/list":
|
|
520
|
+
return ok(id, {
|
|
521
|
+
tools: [
|
|
522
|
+
...this.tools.values()
|
|
523
|
+
].map((t) => ({
|
|
524
|
+
name: t.name,
|
|
525
|
+
...t.title ? {
|
|
526
|
+
title: t.title
|
|
527
|
+
} : {},
|
|
528
|
+
description: t.description,
|
|
529
|
+
inputSchema: t.inputSchema,
|
|
530
|
+
...t.annotations ? {
|
|
531
|
+
annotations: t.annotations
|
|
532
|
+
} : {}
|
|
533
|
+
}))
|
|
534
|
+
});
|
|
535
|
+
case "tools/call": {
|
|
536
|
+
const tool = this.tools.get(params.name);
|
|
537
|
+
if (!tool) return fail(id, INVALID_PARAMS, `Unknown tool: ${String(params.name)}`);
|
|
538
|
+
return ok(id, await this.callTool(tool, params.arguments ?? {}, ctx));
|
|
539
|
+
}
|
|
540
|
+
case "resources/list":
|
|
541
|
+
return ok(id, {
|
|
542
|
+
resources: []
|
|
543
|
+
});
|
|
544
|
+
case "prompts/list":
|
|
545
|
+
return ok(id, {
|
|
546
|
+
prompts: []
|
|
547
|
+
});
|
|
548
|
+
default:
|
|
549
|
+
return fail(id, METHOD_NOT_FOUND, `Method not found: ${msg.method}`);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
async callTool(tool, args, ctx) {
|
|
553
|
+
try {
|
|
554
|
+
if (tool.validate) {
|
|
555
|
+
const v = await tool.validate(args);
|
|
556
|
+
if (!v.ok) return {
|
|
557
|
+
isError: true,
|
|
558
|
+
content: [
|
|
559
|
+
{
|
|
560
|
+
type: "text",
|
|
561
|
+
text: `Invalid arguments: ${v.message}`
|
|
562
|
+
}
|
|
563
|
+
]
|
|
564
|
+
};
|
|
565
|
+
args = v.value;
|
|
566
|
+
}
|
|
567
|
+
return await tool.handler(args, ctx);
|
|
568
|
+
} catch (err) {
|
|
569
|
+
return {
|
|
570
|
+
isError: true,
|
|
571
|
+
content: [
|
|
572
|
+
{
|
|
573
|
+
type: "text",
|
|
574
|
+
text: `Tool error: ${err.message}`
|
|
575
|
+
}
|
|
576
|
+
]
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
/** Check the Origin header (DNS rebinding protection). */
|
|
581
|
+
isOriginAllowed(origin) {
|
|
582
|
+
if (!origin) return true;
|
|
583
|
+
const allowed = this.options.allowedOrigins;
|
|
584
|
+
if (allowed === "*") return true;
|
|
585
|
+
return (allowed ?? []).includes(origin);
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Framework-neutral Streamable HTTP handler. Adapters convert their request
|
|
589
|
+
* into McpHttpRequest, call this, and write the McpHttpResponse back.
|
|
590
|
+
*/
|
|
591
|
+
async handleHttp(req, ctx) {
|
|
592
|
+
const json = {
|
|
593
|
+
"content-type": "application/json"
|
|
594
|
+
};
|
|
595
|
+
if (!this.isOriginAllowed(req.headers.origin)) {
|
|
596
|
+
return {
|
|
597
|
+
status: 403,
|
|
598
|
+
headers: json,
|
|
599
|
+
body: JSON.stringify(fail(null, INVALID_REQUEST, "Origin not allowed"))
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
if (req.method.toUpperCase() !== "POST") {
|
|
603
|
+
return {
|
|
604
|
+
status: 405,
|
|
605
|
+
headers: {
|
|
606
|
+
allow: "POST"
|
|
607
|
+
}
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
let body = req.body;
|
|
611
|
+
if (typeof body === "string" || body instanceof Uint8Array) {
|
|
612
|
+
try {
|
|
613
|
+
body = JSON.parse(typeof body === "string" ? body : new TextDecoder().decode(body));
|
|
614
|
+
} catch {
|
|
615
|
+
return {
|
|
616
|
+
status: 400,
|
|
617
|
+
headers: json,
|
|
618
|
+
body: JSON.stringify(fail(null, PARSE_ERROR, "Parse error"))
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
const response = await this.handleMessage(body, ctx);
|
|
623
|
+
if (response === null) return {
|
|
624
|
+
status: 202,
|
|
625
|
+
headers: {}
|
|
626
|
+
};
|
|
627
|
+
return {
|
|
628
|
+
status: 200,
|
|
629
|
+
headers: json,
|
|
630
|
+
body: JSON.stringify(response)
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
|
|
635
|
+
// src/express/discover.ts
|
|
636
|
+
function collectExpress3(routes, out) {
|
|
637
|
+
for (const list of Object.values(routes)) {
|
|
638
|
+
for (const r of list) {
|
|
639
|
+
const marker = r.callbacks.map(markerOf).find(Boolean);
|
|
640
|
+
if (marker && typeof r.path === "string") out.push({
|
|
641
|
+
method: r.method.toUpperCase(),
|
|
642
|
+
path: r.path,
|
|
643
|
+
options: marker
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
__name(collectExpress3, "collectExpress3");
|
|
649
|
+
function stackOf(app) {
|
|
650
|
+
let router = app._router;
|
|
651
|
+
if (!router) {
|
|
652
|
+
try {
|
|
653
|
+
router = app.router;
|
|
654
|
+
} catch {
|
|
655
|
+
router = void 0;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return router?.stack ?? [];
|
|
659
|
+
}
|
|
660
|
+
__name(stackOf, "stackOf");
|
|
661
|
+
function express4Prefix(layer) {
|
|
662
|
+
const re = layer.regexp;
|
|
663
|
+
if (!re) return void 0;
|
|
664
|
+
if (re.fast_slash) return "";
|
|
665
|
+
const m = /^\/\^((?:\\[.*+?^${}()|[\]\\/]|[^.*+?^${}()|[\]\\/])*)\\\/\?\(\?=\\\/\|\$\)\/i?$/.exec(re.toString());
|
|
666
|
+
return m ? m[1].replace(/\\(.)/g, "$1") : void 0;
|
|
667
|
+
}
|
|
668
|
+
__name(express4Prefix, "express4Prefix");
|
|
669
|
+
function collect(stack, prefix, routers, out, unresolved) {
|
|
670
|
+
for (const layer of stack) {
|
|
671
|
+
if (layer.route) {
|
|
672
|
+
const marker = layer.route.stack.map((l) => markerOf(l.handle)).find(Boolean);
|
|
673
|
+
if (!marker) continue;
|
|
674
|
+
const paths = Array.isArray(layer.route.path) ? layer.route.path : [
|
|
675
|
+
layer.route.path
|
|
676
|
+
];
|
|
677
|
+
for (const method of Object.keys(layer.route.methods).filter((m) => m !== "_all")) {
|
|
678
|
+
for (const p of paths) out.push({
|
|
679
|
+
method: method.toUpperCase(),
|
|
680
|
+
path: joinPaths(prefix, p),
|
|
681
|
+
options: marker
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
} else if (layer.handle?.stack) {
|
|
685
|
+
const known = routers.get(layer.handle);
|
|
686
|
+
const sub = known ?? express4Prefix(layer);
|
|
687
|
+
if (sub === void 0) {
|
|
688
|
+
const inner = [];
|
|
689
|
+
collect(layer.handle.stack, "", routers, inner, unresolved);
|
|
690
|
+
if (inner.length) unresolved.push(...inner.map((f) => `${f.method} ${f.path}`));
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
collect(layer.handle.stack, joinPaths(prefix, sub), routers, out, unresolved);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
__name(collect, "collect");
|
|
698
|
+
function discoverExpressRoutes(app, routers = {}) {
|
|
699
|
+
const stack = stackOf(app);
|
|
700
|
+
const byRouter = new Map(Object.entries(routers).map(([prefix, r]) => [
|
|
701
|
+
r,
|
|
702
|
+
prefix
|
|
703
|
+
]));
|
|
704
|
+
const out = [];
|
|
705
|
+
const unresolved = [];
|
|
706
|
+
collect(stack, "", byRouter, out, unresolved);
|
|
707
|
+
if (!stack.length && app.routes && typeof app.routes === "object") collectExpress3(app.routes, out);
|
|
708
|
+
if (unresolved.length) {
|
|
709
|
+
throw new Error(`mcp-expose: cannot determine the mount path of a router containing MCP tools (${unresolved.join(", ")}). Pass it via the \`routers\` option, e.g. mountMcp(app, { routers: { '/api': apiRouter } }).`);
|
|
710
|
+
}
|
|
711
|
+
return out;
|
|
712
|
+
}
|
|
713
|
+
__name(discoverExpressRoutes, "discoverExpressRoutes");
|
|
714
|
+
|
|
715
|
+
// src/express/index.ts
|
|
716
|
+
function mcpTool(options = {}) {
|
|
717
|
+
return mark((_req, _res, next) => next(), options);
|
|
718
|
+
}
|
|
719
|
+
__name(mcpTool, "mcpTool");
|
|
720
|
+
function mountMcp(app, options) {
|
|
721
|
+
const path = options.path ?? "/mcp";
|
|
722
|
+
const server = new McpServer(options);
|
|
723
|
+
const dispatch = createFetchDispatcher({
|
|
724
|
+
baseUrl: options.baseUrl ?? ((ctx) => loopbackBaseUrl(ctx.raw))
|
|
725
|
+
});
|
|
726
|
+
for (const t of options.tools ?? []) server.addTool(t);
|
|
727
|
+
server.onLoad(() => {
|
|
728
|
+
const found = discoverExpressRoutes(app, options.routers);
|
|
729
|
+
for (const r of options.routes ?? []) found.push({
|
|
730
|
+
method: r.method,
|
|
731
|
+
path: r.path,
|
|
732
|
+
options: r
|
|
733
|
+
});
|
|
734
|
+
for (const f of found) server.addTool(createRouteTool({
|
|
735
|
+
method: f.method,
|
|
736
|
+
path: f.path
|
|
737
|
+
}, f.options, dispatch, options));
|
|
738
|
+
});
|
|
739
|
+
const handler = /* @__PURE__ */ __name((req, res, next) => {
|
|
740
|
+
(async () => {
|
|
741
|
+
const body = req.method === "POST" && req.body === void 0 ? await readRawBody(req) : req.body;
|
|
742
|
+
const ctx = {
|
|
743
|
+
headers: normalizeHeaders(req.headers),
|
|
744
|
+
clientIp: req.ip ?? req.socket.remoteAddress,
|
|
745
|
+
raw: req
|
|
746
|
+
};
|
|
747
|
+
const out = await server.handleHttp({
|
|
748
|
+
method: req.method ?? "POST",
|
|
749
|
+
headers: ctx.headers,
|
|
750
|
+
body
|
|
751
|
+
}, ctx);
|
|
752
|
+
writeNodeResponse(res, out);
|
|
753
|
+
})().catch(next);
|
|
754
|
+
}, "handler");
|
|
755
|
+
app.all.call(app, path, ...options.middleware ?? [], handler);
|
|
756
|
+
return server;
|
|
757
|
+
}
|
|
758
|
+
__name(mountMcp, "mountMcp");
|
|
759
|
+
export {
|
|
760
|
+
mcpTool,
|
|
761
|
+
mountMcp
|
|
762
|
+
};
|
|
763
|
+
//# sourceMappingURL=index.js.map
|