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