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.
Files changed (48) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/LICENSE +21 -0
  3. package/README.md +708 -0
  4. package/dist/adonisjs/index.cjs +708 -0
  5. package/dist/adonisjs/index.cjs.map +1 -0
  6. package/dist/adonisjs/index.d.cts +68 -0
  7. package/dist/adonisjs/index.d.ts +68 -0
  8. package/dist/adonisjs/index.js +684 -0
  9. package/dist/adonisjs/index.js.map +1 -0
  10. package/dist/express/index.cjs +789 -0
  11. package/dist/express/index.cjs.map +1 -0
  12. package/dist/express/index.d.cts +61 -0
  13. package/dist/express/index.d.ts +61 -0
  14. package/dist/express/index.js +763 -0
  15. package/dist/express/index.js.map +1 -0
  16. package/dist/fastify/index.cjs +660 -0
  17. package/dist/fastify/index.cjs.map +1 -0
  18. package/dist/fastify/index.d.cts +42 -0
  19. package/dist/fastify/index.d.ts +42 -0
  20. package/dist/fastify/index.js +635 -0
  21. package/dist/fastify/index.js.map +1 -0
  22. package/dist/hono/index.cjs +656 -0
  23. package/dist/hono/index.cjs.map +1 -0
  24. package/dist/hono/index.d.cts +44 -0
  25. package/dist/hono/index.d.ts +44 -0
  26. package/dist/hono/index.js +630 -0
  27. package/dist/hono/index.js.map +1 -0
  28. package/dist/index.cjs +720 -0
  29. package/dist/index.cjs.map +1 -0
  30. package/dist/index.d.cts +81 -0
  31. package/dist/index.d.ts +81 -0
  32. package/dist/index.js +686 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/koa/index.cjs +739 -0
  35. package/dist/koa/index.cjs.map +1 -0
  36. package/dist/koa/index.d.cts +68 -0
  37. package/dist/koa/index.d.ts +68 -0
  38. package/dist/koa/index.js +709 -0
  39. package/dist/koa/index.js.map +1 -0
  40. package/dist/nestjs/index.cjs +1117 -0
  41. package/dist/nestjs/index.cjs.map +1 -0
  42. package/dist/nestjs/index.d.cts +104 -0
  43. package/dist/nestjs/index.d.ts +104 -0
  44. package/dist/nestjs/index.js +1079 -0
  45. package/dist/nestjs/index.js.map +1 -0
  46. package/dist/server-fzkb-wJo.d.cts +194 -0
  47. package/dist/server-fzkb-wJo.d.ts +194 -0
  48. package/package.json +225 -0
@@ -0,0 +1,1079 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/nestjs/index.ts
5
+ import { All, Controller, Inject, Injectable, Module, Req, Res, SetMetadata, UseGuards, VERSION_NEUTRAL } from "@nestjs/common";
6
+ import { ApplicationConfig, DiscoveryModule, DiscoveryService } from "@nestjs/core";
7
+
8
+ // src/core/dispatch.ts
9
+ function buildUrl(base, req) {
10
+ const url = new URL(base.replace(/\/+$/, "") + req.path);
11
+ for (const [k, v] of Object.entries(req.query)) {
12
+ for (const item of Array.isArray(v) ? v : [
13
+ v
14
+ ]) url.searchParams.append(k, item);
15
+ }
16
+ return url.toString();
17
+ }
18
+ __name(buildUrl, "buildUrl");
19
+ function createFetchDispatcher(opts) {
20
+ const doFetch = opts.fetch ?? fetch;
21
+ return async (req, ctx) => {
22
+ const base = typeof opts.baseUrl === "function" ? opts.baseUrl(ctx) : opts.baseUrl;
23
+ const res = await doFetch(buildUrl(base, req), {
24
+ method: req.method,
25
+ headers: req.headers,
26
+ body: req.body === void 0 || req.method === "GET" || req.method === "HEAD" ? void 0 : JSON.stringify(req.body),
27
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 3e4)
28
+ });
29
+ const headers = {};
30
+ res.headers.forEach((v, k) => headers[k] = v);
31
+ return {
32
+ status: res.status,
33
+ headers,
34
+ body: await res.text()
35
+ };
36
+ };
37
+ }
38
+ __name(createFetchDispatcher, "createFetchDispatcher");
39
+
40
+ // src/core/node.ts
41
+ function normalizeHeaders(headers) {
42
+ const out = {};
43
+ for (const [k, v] of Object.entries(headers)) {
44
+ if (v === void 0) continue;
45
+ out[k.toLowerCase()] = Array.isArray(v) ? v.join(", ") : String(v);
46
+ }
47
+ return out;
48
+ }
49
+ __name(normalizeHeaders, "normalizeHeaders");
50
+ function loopbackBaseUrl(req) {
51
+ const socket = req.socket;
52
+ const port = socket.localPort;
53
+ const encrypted = socket.encrypted;
54
+ const bound = socket.server?.address();
55
+ let host = typeof bound === "object" && bound?.address || socket.localAddress || "127.0.0.1";
56
+ if (host.startsWith("::ffff:")) host = host.slice(7);
57
+ if (host === "::" || host === "0.0.0.0") host = "127.0.0.1";
58
+ if (host.includes(":")) host = `[${host}]`;
59
+ return `${encrypted ? "https" : "http"}://${host}:${port}`;
60
+ }
61
+ __name(loopbackBaseUrl, "loopbackBaseUrl");
62
+
63
+ // src/core/schema.ts
64
+ function isStandard(s) {
65
+ return typeof s === "object" && s !== null && "~standard" in s;
66
+ }
67
+ __name(isStandard, "isStandard");
68
+ function toJsonSchema(schema) {
69
+ if (schema === void 0 || schema === null) return void 0;
70
+ let out;
71
+ if (isStandard(schema) && typeof schema["~standard"].jsonSchema?.input === "function") {
72
+ out = schema["~standard"].jsonSchema.input({
73
+ target: "draft-2020-12"
74
+ });
75
+ } else if (typeof schema.toJSONSchema === "function") {
76
+ out = schema.toJSONSchema();
77
+ } else if (isStandard(schema)) {
78
+ throw new Error("mcp-expose: this schema library does not support JSON Schema export. Pass a plain JSON Schema instead.");
79
+ } else {
80
+ out = schema;
81
+ }
82
+ const { $schema: _ignored, ...rest } = out;
83
+ return rest;
84
+ }
85
+ __name(toJsonSchema, "toJsonSchema");
86
+ function toValidator(schema) {
87
+ if (!isStandard(schema) || typeof schema["~standard"].validate !== "function") return void 0;
88
+ const validate = schema["~standard"].validate;
89
+ return async (value) => {
90
+ const result = await validate(value);
91
+ if (!result.issues) return {
92
+ ok: true,
93
+ value: result.value
94
+ };
95
+ const message = result.issues.map((i) => {
96
+ const path = (i.path ?? []).map((p) => typeof p === "object" ? String(p.key) : String(p)).join(".");
97
+ return path ? `${path}: ${i.message}` : i.message;
98
+ }).join("; ");
99
+ return {
100
+ ok: false,
101
+ message
102
+ };
103
+ };
104
+ }
105
+ __name(toValidator, "toValidator");
106
+ function checkRequired(schema, args) {
107
+ const missing = (schema.required ?? []).filter((k) => args[k] === void 0);
108
+ return missing.length ? `Missing required argument(s): ${missing.join(", ")}` : void 0;
109
+ }
110
+ __name(checkRequired, "checkRequired");
111
+
112
+ // src/core/route-tool.ts
113
+ var DEFAULT_FORWARD_HEADERS = [
114
+ "authorization",
115
+ "cookie",
116
+ "x-api-key",
117
+ "accept-language"
118
+ ];
119
+ var BODY_METHODS = /* @__PURE__ */ new Set([
120
+ "POST",
121
+ "PUT",
122
+ "PATCH"
123
+ ]);
124
+ var PARAM_RE = /:([A-Za-z0-9_]+)\??|\{([A-Za-z0-9_]+)\}/g;
125
+ function pathParams(path) {
126
+ return [
127
+ ...path.matchAll(PARAM_RE)
128
+ ].map((m) => m[1] ?? m[2]);
129
+ }
130
+ __name(pathParams, "pathParams");
131
+ function encodeSegment(name, value) {
132
+ const raw = String(value);
133
+ if (raw === "" || raw === "." || raw === "..") {
134
+ throw new Error(`Invalid value for path parameter "${name}": ${JSON.stringify(raw)}`);
135
+ }
136
+ return encodeURIComponent(raw);
137
+ }
138
+ __name(encodeSegment, "encodeSegment");
139
+ function interpolatePath(path, values) {
140
+ return path.replace(/\/:([A-Za-z0-9_]+)\?/g, (_, k) => values[k] === void 0 ? "" : `/${encodeSegment(k, values[k])}`).replace(PARAM_RE, (_, a, b) => {
141
+ const k = a ?? b;
142
+ return encodeSegment(k, values[k]);
143
+ });
144
+ }
145
+ __name(interpolatePath, "interpolatePath");
146
+ function joinPaths(...parts) {
147
+ const joined = parts.filter((p) => !!p && p !== "/").map((p) => p.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
148
+ return `/${joined}`;
149
+ }
150
+ __name(joinPaths, "joinPaths");
151
+ function toolNameFromRoute(method, path) {
152
+ const segments = path.split("/").filter(Boolean).map((s) => {
153
+ const m = /^(?::([A-Za-z0-9_]+)\??|\{([A-Za-z0-9_]+)\})$/.exec(s);
154
+ return m ? `by_${m[1] ?? m[2]}` : s;
155
+ });
156
+ return sanitizeToolName([
157
+ method.toLowerCase(),
158
+ ...segments
159
+ ].join("_"));
160
+ }
161
+ __name(toolNameFromRoute, "toolNameFromRoute");
162
+ function sanitizeToolName(name) {
163
+ return name.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "").slice(0, 64);
164
+ }
165
+ __name(sanitizeToolName, "sanitizeToolName");
166
+ function defaultAnnotations(method) {
167
+ switch (method) {
168
+ case "GET":
169
+ case "HEAD":
170
+ return {
171
+ readOnlyHint: true,
172
+ openWorldHint: false
173
+ };
174
+ case "DELETE":
175
+ return {
176
+ readOnlyHint: false,
177
+ destructiveHint: true,
178
+ idempotentHint: true,
179
+ openWorldHint: false
180
+ };
181
+ case "PUT":
182
+ return {
183
+ readOnlyHint: false,
184
+ destructiveHint: false,
185
+ idempotentHint: true,
186
+ openWorldHint: false
187
+ };
188
+ default:
189
+ return {
190
+ readOnlyHint: false,
191
+ destructiveHint: false,
192
+ openWorldHint: false
193
+ };
194
+ }
195
+ }
196
+ __name(defaultAnnotations, "defaultAnnotations");
197
+ function buildInputSchema(route, opts) {
198
+ const method = route.method.toUpperCase();
199
+ const params = pathParams(route.path);
200
+ const mapping = {
201
+ params,
202
+ query: /* @__PURE__ */ new Set(),
203
+ body: /* @__PURE__ */ new Set(),
204
+ wholeBody: false,
205
+ bodyMethod: BODY_METHODS.has(method)
206
+ };
207
+ if (opts.input) {
208
+ const schema2 = toJsonSchema(opts.input);
209
+ return {
210
+ schema: {
211
+ type: "object",
212
+ ...schema2
213
+ },
214
+ mapping
215
+ };
216
+ }
217
+ const properties = {};
218
+ const required = /* @__PURE__ */ new Set();
219
+ const paramSchema = toJsonSchema(opts.params);
220
+ for (const p of params) {
221
+ properties[p] = paramSchema?.properties?.[p] ?? {
222
+ type: "string",
223
+ description: `Path parameter "${p}"`
224
+ };
225
+ if (!route.path.includes(`:${p}?`)) required.add(p);
226
+ }
227
+ const querySchema = toJsonSchema(opts.query);
228
+ for (const [k, v] of Object.entries(querySchema?.properties ?? {})) {
229
+ properties[k] = v;
230
+ mapping.query.add(k);
231
+ }
232
+ for (const k of querySchema?.required ?? []) required.add(k);
233
+ const bodySchema = toJsonSchema(opts.body);
234
+ if (bodySchema) {
235
+ if (bodySchema.properties && (bodySchema.type === void 0 || bodySchema.type === "object")) {
236
+ for (const [k, v] of Object.entries(bodySchema.properties)) {
237
+ properties[k] = v;
238
+ mapping.body.add(k);
239
+ }
240
+ for (const k of bodySchema.required ?? []) required.add(k);
241
+ } else {
242
+ properties.body = bodySchema;
243
+ required.add("body");
244
+ mapping.wholeBody = true;
245
+ }
246
+ }
247
+ const schema = {
248
+ type: "object",
249
+ properties
250
+ };
251
+ if (required.size) schema.required = [
252
+ ...required
253
+ ];
254
+ return {
255
+ schema,
256
+ mapping
257
+ };
258
+ }
259
+ __name(buildInputSchema, "buildInputSchema");
260
+ function splitArgs(args, mapping) {
261
+ const pathValues = {};
262
+ const query = {};
263
+ let body;
264
+ for (const [k, v] of Object.entries(args)) {
265
+ if (v === void 0) continue;
266
+ if (mapping.params.includes(k)) {
267
+ pathValues[k] = v;
268
+ } else if (mapping.wholeBody && k === "body") {
269
+ body = v;
270
+ } else if (mapping.query.has(k) || !mapping.body.has(k) && !mapping.bodyMethod) {
271
+ query[k] = Array.isArray(v) ? v.map(String) : typeof v === "object" && v !== null ? JSON.stringify(v) : String(v);
272
+ } else {
273
+ body = {
274
+ ...body ?? {},
275
+ [k]: v
276
+ };
277
+ }
278
+ }
279
+ if (body === void 0 && mapping.bodyMethod) body = {};
280
+ return {
281
+ pathValues,
282
+ query,
283
+ body
284
+ };
285
+ }
286
+ __name(splitArgs, "splitArgs");
287
+ function responseToResult(res, maxChars) {
288
+ let text = res.body;
289
+ if (text.length > maxChars) text = `${text.slice(0, maxChars)}
290
+ \u2026[truncated ${text.length - maxChars} chars]`;
291
+ const isError = res.status >= 400;
292
+ const result = {
293
+ content: [
294
+ {
295
+ type: "text",
296
+ text: isError ? `HTTP ${res.status}
297
+ ${text}` : text || `HTTP ${res.status}`
298
+ }
299
+ ]
300
+ };
301
+ if (isError) {
302
+ result.isError = true;
303
+ return result;
304
+ }
305
+ if ((res.headers["content-type"] ?? "").includes("json") && text === res.body) {
306
+ try {
307
+ const parsed = JSON.parse(res.body);
308
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) result.structuredContent = parsed;
309
+ } catch {
310
+ }
311
+ }
312
+ return result;
313
+ }
314
+ __name(responseToResult, "responseToResult");
315
+ function pickForwardHeaders(ctx, names) {
316
+ const out = {};
317
+ for (const name of names) {
318
+ const v = ctx.headers[name.toLowerCase()];
319
+ if (v !== void 0) out[name.toLowerCase()] = v;
320
+ }
321
+ return out;
322
+ }
323
+ __name(pickForwardHeaders, "pickForwardHeaders");
324
+ function createRouteTool(route, opts, dispatch, serverOpts = {}) {
325
+ const method = route.method.toUpperCase();
326
+ const name = sanitizeToolName(opts.name ?? toolNameFromRoute(method, route.path));
327
+ const { schema, mapping } = buildInputSchema(route, opts);
328
+ const forward = serverOpts.forwardHeaders ?? DEFAULT_FORWARD_HEADERS;
329
+ const maxChars = serverOpts.maxResponseChars ?? 1e5;
330
+ return {
331
+ name,
332
+ title: opts.title,
333
+ description: opts.description ?? `${method} ${route.path}`,
334
+ inputSchema: schema,
335
+ annotations: {
336
+ ...defaultAnnotations(method),
337
+ ...opts.annotations
338
+ },
339
+ validate: toValidator(opts.input),
340
+ async handler(args, ctx) {
341
+ const missing = opts.input ? void 0 : checkRequired(schema, args);
342
+ if (missing) return {
343
+ isError: true,
344
+ content: [
345
+ {
346
+ type: "text",
347
+ text: missing
348
+ }
349
+ ]
350
+ };
351
+ const { pathValues, query, body } = splitArgs(args, mapping);
352
+ const headers = {
353
+ accept: "application/json",
354
+ ...pickForwardHeaders(ctx, forward),
355
+ ...opts.headers,
356
+ "x-mcp-tool": name
357
+ };
358
+ if (ctx.clientIp) headers["x-forwarded-for"] = ctx.clientIp;
359
+ if (body !== void 0) headers["content-type"] = "application/json";
360
+ let path;
361
+ try {
362
+ path = interpolatePath(route.path, pathValues);
363
+ } catch (err) {
364
+ return {
365
+ isError: true,
366
+ content: [
367
+ {
368
+ type: "text",
369
+ text: err.message
370
+ }
371
+ ]
372
+ };
373
+ }
374
+ const res = await dispatch({
375
+ method,
376
+ path,
377
+ query,
378
+ body,
379
+ headers
380
+ }, ctx);
381
+ return responseToResult(res, maxChars);
382
+ }
383
+ };
384
+ }
385
+ __name(createRouteTool, "createRouteTool");
386
+
387
+ // src/core/server.ts
388
+ var SUPPORTED_PROTOCOL_VERSIONS = [
389
+ "2025-11-25",
390
+ "2025-06-18",
391
+ "2025-03-26",
392
+ "2024-11-05"
393
+ ];
394
+ var LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0];
395
+ var PARSE_ERROR = -32700;
396
+ var INVALID_REQUEST = -32600;
397
+ var METHOD_NOT_FOUND = -32601;
398
+ var INVALID_PARAMS = -32602;
399
+ var ok = /* @__PURE__ */ __name((id, result) => ({
400
+ jsonrpc: "2.0",
401
+ id,
402
+ result
403
+ }), "ok");
404
+ var fail = /* @__PURE__ */ __name((id, code, message) => ({
405
+ jsonrpc: "2.0",
406
+ id,
407
+ error: {
408
+ code,
409
+ message
410
+ }
411
+ }), "fail");
412
+ var McpServer = class {
413
+ static {
414
+ __name(this, "McpServer");
415
+ }
416
+ options;
417
+ tools = /* @__PURE__ */ new Map();
418
+ loaders = [];
419
+ constructor(options) {
420
+ this.options = options;
421
+ }
422
+ /** Register a tool. Throws on duplicate names. */
423
+ addTool(tool) {
424
+ if (this.tools.has(tool.name)) {
425
+ throw new Error(`mcp-expose: duplicate tool name "${tool.name}". Set an explicit \`name\`.`);
426
+ }
427
+ this.tools.set(tool.name, tool);
428
+ return this;
429
+ }
430
+ /** Register a function that adds tools lazily, right before the first MCP request is served. */
431
+ onLoad(loader) {
432
+ this.loaders.push(loader);
433
+ return this;
434
+ }
435
+ async listTools() {
436
+ await this.load();
437
+ return [
438
+ ...this.tools.values()
439
+ ];
440
+ }
441
+ async load() {
442
+ if (!this.loaders.length) return;
443
+ const loaders = this.loaders;
444
+ this.loaders = [];
445
+ for (const l of loaders) await l();
446
+ }
447
+ /** Handle one JSON-RPC message (or a batch). Returns null when no response is due. */
448
+ async handleMessage(message, ctx) {
449
+ if (Array.isArray(message)) {
450
+ const results = (await Promise.all(message.map((m) => this.handleOne(m, ctx)))).filter((r) => r !== null);
451
+ return results.length ? results : null;
452
+ }
453
+ return this.handleOne(message, ctx);
454
+ }
455
+ async handleOne(message, ctx) {
456
+ const msg = message;
457
+ if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") {
458
+ return fail(null, INVALID_REQUEST, "Invalid JSON-RPC message");
459
+ }
460
+ if (typeof msg.method !== "string" || msg.id === void 0) return null;
461
+ const id = msg.id;
462
+ const params = msg.params ?? {};
463
+ await this.load();
464
+ switch (msg.method) {
465
+ case "initialize": {
466
+ const requested = params.protocolVersion;
467
+ const protocolVersion = requested && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;
468
+ return ok(id, {
469
+ protocolVersion,
470
+ capabilities: {
471
+ tools: {
472
+ listChanged: false
473
+ }
474
+ },
475
+ serverInfo: {
476
+ name: this.options.name,
477
+ version: this.options.version ?? "1.0.0"
478
+ },
479
+ ...this.options.instructions ? {
480
+ instructions: this.options.instructions
481
+ } : {}
482
+ });
483
+ }
484
+ case "ping":
485
+ return ok(id, {});
486
+ case "tools/list":
487
+ return ok(id, {
488
+ tools: [
489
+ ...this.tools.values()
490
+ ].map((t) => ({
491
+ name: t.name,
492
+ ...t.title ? {
493
+ title: t.title
494
+ } : {},
495
+ description: t.description,
496
+ inputSchema: t.inputSchema,
497
+ ...t.annotations ? {
498
+ annotations: t.annotations
499
+ } : {}
500
+ }))
501
+ });
502
+ case "tools/call": {
503
+ const tool = this.tools.get(params.name);
504
+ if (!tool) return fail(id, INVALID_PARAMS, `Unknown tool: ${String(params.name)}`);
505
+ return ok(id, await this.callTool(tool, params.arguments ?? {}, ctx));
506
+ }
507
+ case "resources/list":
508
+ return ok(id, {
509
+ resources: []
510
+ });
511
+ case "prompts/list":
512
+ return ok(id, {
513
+ prompts: []
514
+ });
515
+ default:
516
+ return fail(id, METHOD_NOT_FOUND, `Method not found: ${msg.method}`);
517
+ }
518
+ }
519
+ async callTool(tool, args, ctx) {
520
+ try {
521
+ if (tool.validate) {
522
+ const v = await tool.validate(args);
523
+ if (!v.ok) return {
524
+ isError: true,
525
+ content: [
526
+ {
527
+ type: "text",
528
+ text: `Invalid arguments: ${v.message}`
529
+ }
530
+ ]
531
+ };
532
+ args = v.value;
533
+ }
534
+ return await tool.handler(args, ctx);
535
+ } catch (err) {
536
+ return {
537
+ isError: true,
538
+ content: [
539
+ {
540
+ type: "text",
541
+ text: `Tool error: ${err.message}`
542
+ }
543
+ ]
544
+ };
545
+ }
546
+ }
547
+ /** Check the Origin header (DNS rebinding protection). */
548
+ isOriginAllowed(origin) {
549
+ if (!origin) return true;
550
+ const allowed = this.options.allowedOrigins;
551
+ if (allowed === "*") return true;
552
+ return (allowed ?? []).includes(origin);
553
+ }
554
+ /**
555
+ * Framework-neutral Streamable HTTP handler. Adapters convert their request
556
+ * into McpHttpRequest, call this, and write the McpHttpResponse back.
557
+ */
558
+ async handleHttp(req, ctx) {
559
+ const json = {
560
+ "content-type": "application/json"
561
+ };
562
+ if (!this.isOriginAllowed(req.headers.origin)) {
563
+ return {
564
+ status: 403,
565
+ headers: json,
566
+ body: JSON.stringify(fail(null, INVALID_REQUEST, "Origin not allowed"))
567
+ };
568
+ }
569
+ if (req.method.toUpperCase() !== "POST") {
570
+ return {
571
+ status: 405,
572
+ headers: {
573
+ allow: "POST"
574
+ }
575
+ };
576
+ }
577
+ let body = req.body;
578
+ if (typeof body === "string" || body instanceof Uint8Array) {
579
+ try {
580
+ body = JSON.parse(typeof body === "string" ? body : new TextDecoder().decode(body));
581
+ } catch {
582
+ return {
583
+ status: 400,
584
+ headers: json,
585
+ body: JSON.stringify(fail(null, PARSE_ERROR, "Parse error"))
586
+ };
587
+ }
588
+ }
589
+ const response = await this.handleMessage(body, ctx);
590
+ if (response === null) return {
591
+ status: 202,
592
+ headers: {}
593
+ };
594
+ return {
595
+ status: 200,
596
+ headers: json,
597
+ body: JSON.stringify(response)
598
+ };
599
+ }
600
+ };
601
+
602
+ // src/nestjs/dto-schema.ts
603
+ var PRIMITIVES = /* @__PURE__ */ new Map([
604
+ [
605
+ String,
606
+ {
607
+ type: "string"
608
+ }
609
+ ],
610
+ [
611
+ Number,
612
+ {
613
+ type: "number"
614
+ }
615
+ ],
616
+ [
617
+ Boolean,
618
+ {
619
+ type: "boolean"
620
+ }
621
+ ],
622
+ [
623
+ Date,
624
+ {
625
+ type: "string",
626
+ format: "date-time"
627
+ }
628
+ ],
629
+ [
630
+ Array,
631
+ {
632
+ type: "array"
633
+ }
634
+ ],
635
+ [
636
+ Object,
637
+ {
638
+ type: "object"
639
+ }
640
+ ]
641
+ ]);
642
+ function primitiveSchema(type) {
643
+ const s = PRIMITIVES.get(type);
644
+ return s ? {
645
+ ...s
646
+ } : void 0;
647
+ }
648
+ __name(primitiveSchema, "primitiveSchema");
649
+ function applyRule(s, name, c = []) {
650
+ switch (name) {
651
+ case "isString":
652
+ s.type = "string";
653
+ break;
654
+ case "isNumber":
655
+ case "isNumberString":
656
+ s.type = name === "isNumber" ? "number" : "string";
657
+ break;
658
+ case "isInt":
659
+ s.type = "integer";
660
+ break;
661
+ case "isBoolean":
662
+ s.type = "boolean";
663
+ break;
664
+ case "isDate":
665
+ case "isDateString":
666
+ case "isISO8601":
667
+ s.type = "string";
668
+ s.format = "date-time";
669
+ break;
670
+ case "isEmail":
671
+ s.type = "string";
672
+ s.format = "email";
673
+ break;
674
+ case "isUrl":
675
+ s.type = "string";
676
+ s.format = "uri";
677
+ break;
678
+ case "isUUID":
679
+ s.type = "string";
680
+ s.format = "uuid";
681
+ break;
682
+ case "isPositive":
683
+ s.exclusiveMinimum = 0;
684
+ break;
685
+ case "isNegative":
686
+ s.exclusiveMaximum = 0;
687
+ break;
688
+ case "min":
689
+ s.minimum = c[0];
690
+ break;
691
+ case "max":
692
+ s.maximum = c[0];
693
+ break;
694
+ case "minLength":
695
+ s.minLength = c[0];
696
+ break;
697
+ case "maxLength":
698
+ s.maxLength = c[0];
699
+ break;
700
+ case "length":
701
+ s.minLength = c[0];
702
+ if (c[1] !== void 0) s.maxLength = c[1];
703
+ break;
704
+ case "matches":
705
+ if (c[0] instanceof RegExp) s.pattern = c[0].source;
706
+ break;
707
+ case "isIn":
708
+ s.enum = c[0];
709
+ break;
710
+ case "isEnum":
711
+ s.enum = c[1] ?? Object.values(c[0]);
712
+ break;
713
+ case "isNotEmpty":
714
+ if (s.type === "string") s.minLength = Math.max(1, Number(s.minLength ?? 0));
715
+ break;
716
+ case "isArray":
717
+ s.type = "array";
718
+ break;
719
+ case "arrayMinSize":
720
+ s.minItems = c[0];
721
+ break;
722
+ case "arrayMaxSize":
723
+ s.maxItems = c[0];
724
+ break;
725
+ case "isObject":
726
+ s.type = "object";
727
+ break;
728
+ }
729
+ }
730
+ __name(applyRule, "applyRule");
731
+ function dtoToJsonSchema(dto, storage, depth = 0) {
732
+ const schema = {
733
+ type: "object",
734
+ properties: {}
735
+ };
736
+ if (!storage || depth > 5) return schema;
737
+ const metas = storage.getTargetValidationMetadatas(dto, "", true, false);
738
+ const properties = {};
739
+ const optional = /* @__PURE__ */ new Set();
740
+ for (const m of metas) {
741
+ const prop = properties[m.propertyName] ??= initial(dto, m.propertyName);
742
+ if (m.type === "conditionalValidation" && m.name === "isOptional") {
743
+ optional.add(m.propertyName);
744
+ } else if (m.type === "nestedValidation") {
745
+ const nestedType = Reflect.getMetadata?.("design:type", dto.prototype, m.propertyName);
746
+ if (typeof nestedType === "function" && !PRIMITIVES.has(nestedType)) {
747
+ Object.assign(prop, dtoToJsonSchema(nestedType, storage, depth + 1));
748
+ }
749
+ } else if (m.type === "customValidation" && m.name) {
750
+ if (m.each) {
751
+ prop.type = "array";
752
+ const items = prop.items ??= {};
753
+ applyRule(items, m.name, m.constraints);
754
+ } else {
755
+ applyRule(prop, m.name, m.constraints);
756
+ }
757
+ }
758
+ }
759
+ schema.properties = properties;
760
+ const required = Object.keys(properties).filter((p) => !optional.has(p));
761
+ if (required.length) schema.required = required;
762
+ return schema;
763
+ }
764
+ __name(dtoToJsonSchema, "dtoToJsonSchema");
765
+ function initial(dto, prop) {
766
+ const designType = Reflect.getMetadata?.("design:type", dto.prototype, prop);
767
+ const s = primitiveSchema(designType) ?? {};
768
+ const api = Reflect.getMetadata?.("swagger/apiModelProperties", dto.prototype, prop);
769
+ if (api?.description) s.description = api.description;
770
+ if (api?.example !== void 0) s.examples = [
771
+ api.example
772
+ ];
773
+ if (Array.isArray(api?.enum)) s.enum = api.enum;
774
+ return s;
775
+ }
776
+ __name(initial, "initial");
777
+
778
+ // src/nestjs/index.ts
779
+ var PATH_METADATA = "path";
780
+ var METHOD_METADATA = "method";
781
+ var ROUTE_ARGS_METADATA = "__routeArguments__";
782
+ var VERSION_METADATA = "__version__";
783
+ var REQUEST_METHODS = [
784
+ "GET",
785
+ "POST",
786
+ "PUT",
787
+ "DELETE",
788
+ "PATCH",
789
+ "ALL",
790
+ "OPTIONS",
791
+ "HEAD"
792
+ ];
793
+ var PARAMTYPE_BODY = 3;
794
+ var PARAMTYPE_QUERY = 4;
795
+ var PARAMTYPE_PARAM = 5;
796
+ var MCP_TOOL_METADATA = "mcp-expose:tool";
797
+ var MCP_MODULE_OPTIONS = /* @__PURE__ */ Symbol("MCP_MODULE_OPTIONS");
798
+ function McpTool(options = {}) {
799
+ return SetMetadata(MCP_TOOL_METADATA, options);
800
+ }
801
+ __name(McpTool, "McpTool");
802
+ var McpService = class {
803
+ static {
804
+ __name(this, "McpService");
805
+ }
806
+ discovery;
807
+ appConfig;
808
+ options;
809
+ server;
810
+ constructor(discovery, appConfig, options) {
811
+ this.discovery = discovery;
812
+ this.appConfig = appConfig;
813
+ this.options = options;
814
+ this.server = new McpServer(options);
815
+ for (const t of options.tools ?? []) this.server.addTool(t);
816
+ const dispatch = createFetchDispatcher({
817
+ baseUrl: options.baseUrl ?? ((ctx) => loopbackBaseUrl(ctx.raw))
818
+ });
819
+ this.server.onLoad(async () => {
820
+ const storage = options.classValidatorStorage ?? await loadClassValidator();
821
+ for (const t of this.discover(storage)) {
822
+ this.server.addTool(createRouteTool(t.route, t.options, dispatch, options));
823
+ }
824
+ });
825
+ }
826
+ globalPrefix() {
827
+ return this.appConfig.getGlobalPrefix?.() ?? "";
828
+ }
829
+ versionSegment(controller, handler) {
830
+ const versioning = this.appConfig.getVersioning?.();
831
+ if (!versioning || versioning.type !== 0) return void 0;
832
+ let version = Reflect.getMetadata(VERSION_METADATA, handler) ?? Reflect.getMetadata(VERSION_METADATA, controller) ?? versioning.defaultVersion;
833
+ if (Array.isArray(version)) version = version[0];
834
+ if (version === void 0 || typeof version === "symbol") return void 0;
835
+ const prefix = versioning.prefix === false ? "" : versioning.prefix ?? "v";
836
+ return `${prefix}${String(version)}`;
837
+ }
838
+ discover(storage) {
839
+ const found = [];
840
+ for (const wrapper of this.discovery.getControllers()) {
841
+ const controller = wrapper.metatype;
842
+ if (!controller?.prototype) continue;
843
+ const proto = controller.prototype;
844
+ const ctrlPaths = toArray(Reflect.getMetadata(PATH_METADATA, controller) ?? "/");
845
+ const ctrlName = controller.name.replace(/Controller$/, "");
846
+ for (const key of Object.getOwnPropertyNames(proto)) {
847
+ if (key === "constructor") continue;
848
+ const handler = Object.getOwnPropertyDescriptor(proto, key)?.value;
849
+ if (typeof handler !== "function") continue;
850
+ const meta = Reflect.getMetadata(MCP_TOOL_METADATA, handler);
851
+ if (!meta) continue;
852
+ const method = REQUEST_METHODS[Reflect.getMetadata(METHOD_METADATA, handler)] ?? "GET";
853
+ const methodPath = toArray(Reflect.getMetadata(PATH_METADATA, handler) ?? "/")[0];
854
+ const path = joinPaths(this.globalPrefix(), this.versionSegment(controller, handler), this.options.pathPrefix, ctrlPaths[0], methodPath);
855
+ found.push({
856
+ route: {
857
+ method: method === "ALL" ? "POST" : method,
858
+ path
859
+ },
860
+ options: {
861
+ name: sanitizeToolName(`${toSnake(ctrlName)}_${toSnake(key)}`),
862
+ ...describeArgs(controller, key, storage),
863
+ ...meta
864
+ }
865
+ });
866
+ }
867
+ }
868
+ return found;
869
+ }
870
+ };
871
+ function describeArgs(controller, key, storage) {
872
+ const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, controller, key) ?? {};
873
+ const types = Reflect.getMetadata("design:paramtypes", controller.prototype, key) ?? [];
874
+ const params = {
875
+ type: "object",
876
+ properties: {}
877
+ };
878
+ const query = {
879
+ type: "object",
880
+ properties: {},
881
+ required: []
882
+ };
883
+ let body;
884
+ const schemaFor = /* @__PURE__ */ __name((t) => primitiveSchema(t) ?? (typeof t === "function" ? dtoToJsonSchema(t, storage) : {}), "schemaFor");
885
+ for (const [k, arg] of Object.entries(args)) {
886
+ const paramtype = Number(k.split(":")[0]);
887
+ const t = types[arg.index];
888
+ const field = typeof arg.data === "string" ? arg.data : void 0;
889
+ if (paramtype === PARAMTYPE_PARAM && field) {
890
+ params.properties[field] = primitiveSchema(t) ?? {
891
+ type: "string"
892
+ };
893
+ } else if (paramtype === PARAMTYPE_QUERY) {
894
+ if (field) query.properties[field] = primitiveSchema(t) ?? {
895
+ type: "string"
896
+ };
897
+ else Object.assign(query, mergeObject(query, schemaFor(t)));
898
+ } else if (paramtype === PARAMTYPE_BODY) {
899
+ if (field) {
900
+ body ??= {
901
+ type: "object",
902
+ properties: {},
903
+ required: []
904
+ };
905
+ body.properties[field] = schemaFor(t);
906
+ body.required.push(field);
907
+ } else {
908
+ body = mergeObject(body, schemaFor(t));
909
+ }
910
+ }
911
+ }
912
+ const out = {
913
+ params
914
+ };
915
+ if (Object.keys(query.properties).length) out.query = query;
916
+ if (body) out.body = body;
917
+ return out;
918
+ }
919
+ __name(describeArgs, "describeArgs");
920
+ function mergeObject(a, b) {
921
+ if (!a) return b;
922
+ return {
923
+ type: "object",
924
+ properties: {
925
+ ...a.properties,
926
+ ...b.properties
927
+ },
928
+ required: [
929
+ ...a.required ?? [],
930
+ ...b.required ?? []
931
+ ]
932
+ };
933
+ }
934
+ __name(mergeObject, "mergeObject");
935
+ async function loadClassValidator() {
936
+ try {
937
+ const cv = await import("class-validator");
938
+ return cv.getMetadataStorage?.();
939
+ } catch {
940
+ return void 0;
941
+ }
942
+ }
943
+ __name(loadClassValidator, "loadClassValidator");
944
+ function toArray(v) {
945
+ return Array.isArray(v) ? v : [
946
+ v
947
+ ];
948
+ }
949
+ __name(toArray, "toArray");
950
+ function toSnake(s) {
951
+ return s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
952
+ }
953
+ __name(toSnake, "toSnake");
954
+ Injectable()(McpService);
955
+ Inject(DiscoveryService)(McpService, void 0, 0);
956
+ Inject(ApplicationConfig)(McpService, void 0, 1);
957
+ Inject(MCP_MODULE_OPTIONS)(McpService, void 0, 2);
958
+ function createMcpController(options) {
959
+ let McpController = class McpController {
960
+ static {
961
+ __name(this, "McpController");
962
+ }
963
+ mcp;
964
+ constructor(mcp) {
965
+ this.mcp = mcp;
966
+ }
967
+ async handle(req, res) {
968
+ const nodeReq = req.raw ?? req;
969
+ const headers = normalizeHeaders(req.headers);
970
+ const ctx = {
971
+ headers,
972
+ clientIp: req.ip,
973
+ raw: nodeReq
974
+ };
975
+ const out = await this.mcp.server.handleHttp({
976
+ method: req.method,
977
+ headers,
978
+ body: req.body
979
+ }, ctx);
980
+ if (typeof res.code === "function") {
981
+ res.code(out.status).headers(out.headers).send(out.body);
982
+ } else {
983
+ res.status(out.status).set(out.headers);
984
+ if (out.body === void 0) res.end();
985
+ else res.send(out.body);
986
+ }
987
+ }
988
+ };
989
+ const proto = McpController.prototype;
990
+ const descriptor = Object.getOwnPropertyDescriptor(proto, "handle");
991
+ Controller({
992
+ path: options.path ?? "mcp",
993
+ version: VERSION_NEUTRAL
994
+ })(McpController);
995
+ Inject(McpService)(McpController, void 0, 0);
996
+ All()(proto, "handle", descriptor);
997
+ Req()(proto, "handle", 0);
998
+ Res()(proto, "handle", 1);
999
+ if (options.guards?.length) UseGuards(...options.guards)(McpController);
1000
+ return McpController;
1001
+ }
1002
+ __name(createMcpController, "createMcpController");
1003
+ var McpModule = class _McpModule {
1004
+ static {
1005
+ __name(this, "McpModule");
1006
+ }
1007
+ static forRoot(options) {
1008
+ return {
1009
+ module: _McpModule,
1010
+ global: true,
1011
+ imports: [
1012
+ DiscoveryModule
1013
+ ],
1014
+ controllers: [
1015
+ createMcpController(options)
1016
+ ],
1017
+ providers: [
1018
+ {
1019
+ provide: MCP_MODULE_OPTIONS,
1020
+ useValue: options
1021
+ },
1022
+ McpService
1023
+ ],
1024
+ exports: [
1025
+ McpService
1026
+ ]
1027
+ };
1028
+ }
1029
+ /**
1030
+ * Resolve the options from other providers, e.g. `ConfigService`:
1031
+ *
1032
+ * McpModule.forRootAsync({
1033
+ * imports: [ConfigModule],
1034
+ * inject: [ConfigService],
1035
+ * useFactory: (config: ConfigService) => ({ name: config.get('APP_NAME') }),
1036
+ * })
1037
+ *
1038
+ * `path` and `guards` define the MCP controller, so they are passed directly.
1039
+ */
1040
+ static forRootAsync(options) {
1041
+ return {
1042
+ module: _McpModule,
1043
+ global: true,
1044
+ imports: [
1045
+ DiscoveryModule,
1046
+ ...options.imports ?? []
1047
+ ],
1048
+ controllers: [
1049
+ createMcpController(options)
1050
+ ],
1051
+ providers: [
1052
+ {
1053
+ provide: MCP_MODULE_OPTIONS,
1054
+ inject: options.inject ?? [],
1055
+ useFactory: /* @__PURE__ */ __name(async (...args) => ({
1056
+ ...await options.useFactory(...args),
1057
+ ...options.path ? {
1058
+ path: options.path
1059
+ } : {}
1060
+ }), "useFactory")
1061
+ },
1062
+ McpService
1063
+ ],
1064
+ exports: [
1065
+ McpService
1066
+ ]
1067
+ };
1068
+ }
1069
+ };
1070
+ Module({})(McpModule);
1071
+ export {
1072
+ MCP_MODULE_OPTIONS,
1073
+ MCP_TOOL_METADATA,
1074
+ McpModule,
1075
+ McpService,
1076
+ McpTool,
1077
+ dtoToJsonSchema
1078
+ };
1079
+ //# sourceMappingURL=index.js.map