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,708 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/adonisjs/index.ts
22
+ var adonisjs_exports = {};
23
+ __export(adonisjs_exports, {
24
+ mcpTool: () => mcpTool,
25
+ mountMcp: () => mountMcp
26
+ });
27
+ module.exports = __toCommonJS(adonisjs_exports);
28
+ var import_http = require("@adonisjs/core/http");
29
+
30
+ // src/core/dispatch.ts
31
+ function buildUrl(base, req) {
32
+ const url = new URL(base.replace(/\/+$/, "") + req.path);
33
+ for (const [k, v] of Object.entries(req.query)) {
34
+ for (const item of Array.isArray(v) ? v : [
35
+ v
36
+ ]) url.searchParams.append(k, item);
37
+ }
38
+ return url.toString();
39
+ }
40
+ __name(buildUrl, "buildUrl");
41
+ function createFetchDispatcher(opts) {
42
+ const doFetch = opts.fetch ?? fetch;
43
+ return async (req, ctx) => {
44
+ const base = typeof opts.baseUrl === "function" ? opts.baseUrl(ctx) : opts.baseUrl;
45
+ const res = await doFetch(buildUrl(base, req), {
46
+ method: req.method,
47
+ headers: req.headers,
48
+ body: req.body === void 0 || req.method === "GET" || req.method === "HEAD" ? void 0 : JSON.stringify(req.body),
49
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 3e4)
50
+ });
51
+ const headers = {};
52
+ res.headers.forEach((v, k) => headers[k] = v);
53
+ return {
54
+ status: res.status,
55
+ headers,
56
+ body: await res.text()
57
+ };
58
+ };
59
+ }
60
+ __name(createFetchDispatcher, "createFetchDispatcher");
61
+
62
+ // src/core/node.ts
63
+ function normalizeHeaders(headers) {
64
+ const out = {};
65
+ for (const [k, v] of Object.entries(headers)) {
66
+ if (v === void 0) continue;
67
+ out[k.toLowerCase()] = Array.isArray(v) ? v.join(", ") : String(v);
68
+ }
69
+ return out;
70
+ }
71
+ __name(normalizeHeaders, "normalizeHeaders");
72
+ function readRawBody(req, limit = 4 * 1024 * 1024) {
73
+ return new Promise((resolve, reject) => {
74
+ let size = 0;
75
+ const chunks = [];
76
+ req.on("data", (c) => {
77
+ size += c.length;
78
+ if (size > limit) {
79
+ reject(new Error("Request body too large"));
80
+ req.destroy();
81
+ } else chunks.push(c);
82
+ });
83
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
84
+ req.on("error", reject);
85
+ });
86
+ }
87
+ __name(readRawBody, "readRawBody");
88
+ function loopbackBaseUrl(req) {
89
+ const socket = req.socket;
90
+ const port = socket.localPort;
91
+ const encrypted = socket.encrypted;
92
+ const bound = socket.server?.address();
93
+ let host = typeof bound === "object" && bound?.address || socket.localAddress || "127.0.0.1";
94
+ if (host.startsWith("::ffff:")) host = host.slice(7);
95
+ if (host === "::" || host === "0.0.0.0") host = "127.0.0.1";
96
+ if (host.includes(":")) host = `[${host}]`;
97
+ return `${encrypted ? "https" : "http"}://${host}:${port}`;
98
+ }
99
+ __name(loopbackBaseUrl, "loopbackBaseUrl");
100
+
101
+ // src/core/schema.ts
102
+ function isStandard(s) {
103
+ return typeof s === "object" && s !== null && "~standard" in s;
104
+ }
105
+ __name(isStandard, "isStandard");
106
+ function toJsonSchema(schema) {
107
+ if (schema === void 0 || schema === null) return void 0;
108
+ let out;
109
+ if (isStandard(schema) && typeof schema["~standard"].jsonSchema?.input === "function") {
110
+ out = schema["~standard"].jsonSchema.input({
111
+ target: "draft-2020-12"
112
+ });
113
+ } else if (typeof schema.toJSONSchema === "function") {
114
+ out = schema.toJSONSchema();
115
+ } else if (isStandard(schema)) {
116
+ throw new Error("mcp-expose: this schema library does not support JSON Schema export. Pass a plain JSON Schema instead.");
117
+ } else {
118
+ out = schema;
119
+ }
120
+ const { $schema: _ignored, ...rest } = out;
121
+ return rest;
122
+ }
123
+ __name(toJsonSchema, "toJsonSchema");
124
+ function toValidator(schema) {
125
+ if (!isStandard(schema) || typeof schema["~standard"].validate !== "function") return void 0;
126
+ const validate = schema["~standard"].validate;
127
+ return async (value) => {
128
+ const result = await validate(value);
129
+ if (!result.issues) return {
130
+ ok: true,
131
+ value: result.value
132
+ };
133
+ const message = result.issues.map((i) => {
134
+ const path = (i.path ?? []).map((p) => typeof p === "object" ? String(p.key) : String(p)).join(".");
135
+ return path ? `${path}: ${i.message}` : i.message;
136
+ }).join("; ");
137
+ return {
138
+ ok: false,
139
+ message
140
+ };
141
+ };
142
+ }
143
+ __name(toValidator, "toValidator");
144
+ function checkRequired(schema, args) {
145
+ const missing = (schema.required ?? []).filter((k) => args[k] === void 0);
146
+ return missing.length ? `Missing required argument(s): ${missing.join(", ")}` : void 0;
147
+ }
148
+ __name(checkRequired, "checkRequired");
149
+
150
+ // src/core/route-tool.ts
151
+ var DEFAULT_FORWARD_HEADERS = [
152
+ "authorization",
153
+ "cookie",
154
+ "x-api-key",
155
+ "accept-language"
156
+ ];
157
+ var BODY_METHODS = /* @__PURE__ */ new Set([
158
+ "POST",
159
+ "PUT",
160
+ "PATCH"
161
+ ]);
162
+ var PARAM_RE = /:([A-Za-z0-9_]+)\??|\{([A-Za-z0-9_]+)\}/g;
163
+ function pathParams(path) {
164
+ return [
165
+ ...path.matchAll(PARAM_RE)
166
+ ].map((m) => m[1] ?? m[2]);
167
+ }
168
+ __name(pathParams, "pathParams");
169
+ function encodeSegment(name, value) {
170
+ const raw = String(value);
171
+ if (raw === "" || raw === "." || raw === "..") {
172
+ throw new Error(`Invalid value for path parameter "${name}": ${JSON.stringify(raw)}`);
173
+ }
174
+ return encodeURIComponent(raw);
175
+ }
176
+ __name(encodeSegment, "encodeSegment");
177
+ function interpolatePath(path, values) {
178
+ return path.replace(/\/:([A-Za-z0-9_]+)\?/g, (_, k) => values[k] === void 0 ? "" : `/${encodeSegment(k, values[k])}`).replace(PARAM_RE, (_, a, b) => {
179
+ const k = a ?? b;
180
+ return encodeSegment(k, values[k]);
181
+ });
182
+ }
183
+ __name(interpolatePath, "interpolatePath");
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/adonisjs/index.ts
636
+ var marked = /* @__PURE__ */ new Map();
637
+ import_http.Route.macro("mcp", function(options = {}) {
638
+ marked.set(this, options);
639
+ return this;
640
+ });
641
+ function mcpTool(route, options = {}) {
642
+ marked.set(route, options);
643
+ return route;
644
+ }
645
+ __name(mcpTool, "mcpTool");
646
+ function isEmptyObject(v) {
647
+ return typeof v === "object" && v !== null && !Array.isArray(v) && Object.keys(v).length === 0;
648
+ }
649
+ __name(isEmptyObject, "isEmptyObject");
650
+ function mountMcp(router, options) {
651
+ const path = options.path ?? "/mcp";
652
+ const server = new McpServer(options);
653
+ const dispatch = createFetchDispatcher({
654
+ baseUrl: options.baseUrl ?? ((ctx) => loopbackBaseUrl(ctx.raw))
655
+ });
656
+ for (const t of options.tools ?? []) server.addTool(t);
657
+ server.onLoad(() => {
658
+ const registered = /* @__PURE__ */ new Set();
659
+ for (const routes of Object.values(router.toJSON())) {
660
+ for (const r of routes) for (const m of r.methods) registered.add(`${m} ${r.pattern}`);
661
+ }
662
+ const seen = /* @__PURE__ */ new Set();
663
+ for (const [route2, opts] of marked) {
664
+ if (route2.isDeleted()) continue;
665
+ const { pattern, methods } = route2.toJSON();
666
+ for (const method of methods) {
667
+ const key = `${method} ${pattern}`;
668
+ if (method === "HEAD" || !registered.has(key) || seen.has(key)) continue;
669
+ seen.add(key);
670
+ server.addTool(createRouteTool({
671
+ method,
672
+ path: pattern
673
+ }, opts, dispatch, options));
674
+ }
675
+ }
676
+ });
677
+ const route = router.any(path, async (ctx) => {
678
+ const req = ctx.request.request;
679
+ let body = ctx.request.body();
680
+ if (ctx.request.method() === "POST" && (body === void 0 || isEmptyObject(body))) {
681
+ const raw = ctx.request.raw();
682
+ body = raw ?? (req.readable && !req.readableEnded ? await readRawBody(req) : body);
683
+ }
684
+ const toolCtx = {
685
+ headers: normalizeHeaders(ctx.request.headers()),
686
+ clientIp: ctx.request.ip(),
687
+ raw: req
688
+ };
689
+ const out = await server.handleHttp({
690
+ method: ctx.request.method(),
691
+ headers: toolCtx.headers,
692
+ body
693
+ }, toolCtx);
694
+ ctx.response.status(out.status);
695
+ for (const [k, v] of Object.entries(out.headers)) ctx.response.header(k, v);
696
+ ctx.response.send(out.body ?? "");
697
+ });
698
+ route.as("mcp_expose.endpoint");
699
+ options.configureRoute?.(route);
700
+ return server;
701
+ }
702
+ __name(mountMcp, "mountMcp");
703
+ // Annotate the CommonJS export names for ESM import in node:
704
+ 0 && (module.exports = {
705
+ mcpTool,
706
+ mountMcp
707
+ });
708
+ //# sourceMappingURL=index.cjs.map