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