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