mcp-expose 1.0.0 → 1.1.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 (55) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/README.md +102 -13
  3. package/dist/adonisjs/index.cjs +238 -0
  4. package/dist/adonisjs/index.cjs.map +1 -1
  5. package/dist/adonisjs/index.d.cts +2 -1
  6. package/dist/adonisjs/index.d.ts +2 -1
  7. package/dist/adonisjs/index.js +238 -0
  8. package/dist/adonisjs/index.js.map +1 -1
  9. package/dist/express/index.cjs +236 -1
  10. package/dist/express/index.cjs.map +1 -1
  11. package/dist/express/index.d.cts +4 -2
  12. package/dist/express/index.d.ts +4 -2
  13. package/dist/express/index.js +236 -1
  14. package/dist/express/index.js.map +1 -1
  15. package/dist/fastify/index.cjs +245 -0
  16. package/dist/fastify/index.cjs.map +1 -1
  17. package/dist/fastify/index.d.cts +2 -1
  18. package/dist/fastify/index.d.ts +2 -1
  19. package/dist/fastify/index.js +245 -0
  20. package/dist/fastify/index.js.map +1 -1
  21. package/dist/hono/index.cjs +239 -0
  22. package/dist/hono/index.cjs.map +1 -1
  23. package/dist/hono/index.d.cts +2 -1
  24. package/dist/hono/index.d.ts +2 -1
  25. package/dist/hono/index.js +239 -0
  26. package/dist/hono/index.js.map +1 -1
  27. package/dist/index.cjs +243 -0
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +5 -2
  30. package/dist/index.d.ts +5 -2
  31. package/dist/index.js +239 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/koa/index.cjs +238 -0
  34. package/dist/koa/index.cjs.map +1 -1
  35. package/dist/koa/index.d.cts +2 -1
  36. package/dist/koa/index.d.ts +2 -1
  37. package/dist/koa/index.js +238 -0
  38. package/dist/koa/index.js.map +1 -1
  39. package/dist/nestjs/index.cjs +253 -1
  40. package/dist/nestjs/index.cjs.map +1 -1
  41. package/dist/nestjs/index.d.cts +21 -7
  42. package/dist/nestjs/index.d.ts +21 -7
  43. package/dist/nestjs/index.js +254 -2
  44. package/dist/nestjs/index.js.map +1 -1
  45. package/dist/oauth/index.cjs +214 -0
  46. package/dist/oauth/index.cjs.map +1 -0
  47. package/dist/oauth/index.d.cts +69 -0
  48. package/dist/oauth/index.d.ts +69 -0
  49. package/dist/oauth/index.js +177 -0
  50. package/dist/oauth/index.js.map +1 -0
  51. package/dist/oauth-8RmQamGP.d.cts +75 -0
  52. package/dist/oauth-8RmQamGP.d.ts +75 -0
  53. package/dist/{server-fzkb-wJo.d.ts → server-BFQ_Hdh9.d.cts} +27 -0
  54. package/dist/{server-fzkb-wJo.d.cts → server-BRw1E2xy.d.ts} +27 -0
  55. package/package.json +21 -2
@@ -324,6 +324,7 @@ function createRouteTool(route, opts, dispatch, serverOpts = {}) {
324
324
  ...defaultAnnotations(method),
325
325
  ...opts.annotations
326
326
  },
327
+ scopes: opts.scopes,
327
328
  validate: toValidator(opts.input),
328
329
  async handler(args, ctx) {
329
330
  const missing = opts.input ? void 0 : checkRequired(schema, args);
@@ -372,6 +373,115 @@ function createRouteTool(route, opts, dispatch, serverOpts = {}) {
372
373
  }
373
374
  __name(createRouteTool, "createRouteTool");
374
375
 
376
+ // src/core/oauth.ts
377
+ var PROTECTED_RESOURCE_WELL_KNOWN = "/.well-known/oauth-protected-resource";
378
+ function protectedResourceMetadataPaths(resource) {
379
+ const pathname = new URL(resource).pathname.replace(/\/+$/, "");
380
+ return pathname ? [
381
+ PROTECTED_RESOURCE_WELL_KNOWN + pathname,
382
+ PROTECTED_RESOURCE_WELL_KNOWN
383
+ ] : [
384
+ PROTECTED_RESOURCE_WELL_KNOWN
385
+ ];
386
+ }
387
+ __name(protectedResourceMetadataPaths, "protectedResourceMetadataPaths");
388
+ function protectedResourceMetadataUrl(resource) {
389
+ return new URL(protectedResourceMetadataPaths(resource)[0], resource).href;
390
+ }
391
+ __name(protectedResourceMetadataUrl, "protectedResourceMetadataUrl");
392
+ function validateOAuthOptions(o) {
393
+ let url;
394
+ try {
395
+ url = new URL(o.resource);
396
+ } catch {
397
+ throw new Error(`mcp-expose: oauth.resource must be an absolute URL, got ${JSON.stringify(o.resource)}`);
398
+ }
399
+ if (url.hash) throw new Error("mcp-expose: oauth.resource must not contain a fragment");
400
+ if (!o.authorizationServers?.length) throw new Error("mcp-expose: oauth.authorizationServers must not be empty");
401
+ if (typeof o.verifyToken !== "function") throw new Error("mcp-expose: oauth.verifyToken is required");
402
+ }
403
+ __name(validateOAuthOptions, "validateOAuthOptions");
404
+ var quote = /* @__PURE__ */ __name((v) => `"${v.replace(/["\\]/g, "\\$&")}"`, "quote");
405
+ function bearerChallenge(resource, params = {}) {
406
+ const parts = [];
407
+ if (params.error) parts.push(`error=${quote(params.error)}`);
408
+ if (params.errorDescription) parts.push(`error_description=${quote(params.errorDescription)}`);
409
+ if (params.scope?.length) parts.push(`scope=${quote(params.scope.join(" "))}`);
410
+ parts.push(`resource_metadata=${quote(protectedResourceMetadataUrl(resource))}`);
411
+ return `Bearer ${parts.join(", ")}`;
412
+ }
413
+ __name(bearerChallenge, "bearerChallenge");
414
+ function bearerToken(headers) {
415
+ const m = /^Bearer[ ]+([^\s,]+)\s*$/i.exec(headers.authorization ?? "");
416
+ return m?.[1];
417
+ }
418
+ __name(bearerToken, "bearerToken");
419
+ async function authenticate(o, headers) {
420
+ const token = bearerToken(headers);
421
+ if (!token) {
422
+ return {
423
+ ok: false,
424
+ status: 401,
425
+ error: "unauthorized",
426
+ description: "Authorization required",
427
+ challenge: bearerChallenge(o.resource, {
428
+ scope: o.requiredScopes
429
+ })
430
+ };
431
+ }
432
+ let auth;
433
+ try {
434
+ auth = await o.verifyToken(token, {
435
+ resource: o.resource,
436
+ headers
437
+ });
438
+ } catch {
439
+ auth = void 0;
440
+ }
441
+ if (!auth) return deny(o, 401, "invalid_token", "The access token is invalid");
442
+ if (auth.expiresAt !== void 0 && auth.expiresAt * 1e3 <= Date.now()) {
443
+ return deny(o, 401, "invalid_token", "The access token has expired");
444
+ }
445
+ const missing = missingScopes(auth, o.requiredScopes);
446
+ if (missing.length) {
447
+ const scope = [
448
+ .../* @__PURE__ */ new Set([
449
+ ...auth.scopes ?? [],
450
+ ...o.requiredScopes ?? []
451
+ ])
452
+ ];
453
+ return deny(o, 403, "insufficient_scope", `Missing scope: ${missing.join(" ")}`, scope);
454
+ }
455
+ return {
456
+ ok: true,
457
+ auth: {
458
+ ...auth,
459
+ scopes: auth.scopes ?? []
460
+ }
461
+ };
462
+ }
463
+ __name(authenticate, "authenticate");
464
+ function deny(o, status, error, description, scope) {
465
+ return {
466
+ ok: false,
467
+ status,
468
+ error,
469
+ description,
470
+ challenge: bearerChallenge(o.resource, {
471
+ error,
472
+ errorDescription: description,
473
+ scope
474
+ })
475
+ };
476
+ }
477
+ __name(deny, "deny");
478
+ function missingScopes(auth, required) {
479
+ if (!required?.length) return [];
480
+ const granted = new Set(auth?.scopes ?? []);
481
+ return required.filter((s) => !granted.has(s));
482
+ }
483
+ __name(missingScopes, "missingScopes");
484
+
375
485
  // src/core/server.ts
376
486
  var SUPPORTED_PROTOCOL_VERSIONS = [
377
487
  "2025-11-25",
@@ -406,6 +516,7 @@ var McpServer = class {
406
516
  loaders = [];
407
517
  constructor(options) {
408
518
  this.options = options;
519
+ if (options.oauth) validateOAuthOptions(options.oauth);
409
520
  }
410
521
  /** Register a tool. Throws on duplicate names. */
411
522
  addTool(tool) {
@@ -540,6 +651,79 @@ var McpServer = class {
540
651
  return (allowed ?? []).includes(origin);
541
652
  }
542
653
  /**
654
+ * Paths on which adapters serve the OAuth Protected Resource Metadata
655
+ * (empty when `oauth` is not configured). They must be public: no auth middleware.
656
+ */
657
+ get oauthMetadataPaths() {
658
+ return this.options.oauth ? protectedResourceMetadataPaths(this.options.oauth.resource) : [];
659
+ }
660
+ /** The OAuth Protected Resource Metadata document (RFC 9728). */
661
+ async protectedResourceMetadata() {
662
+ const o = this.options.oauth;
663
+ if (!o) throw new Error("mcp-expose: the oauth option is not configured");
664
+ await this.load();
665
+ const scopes = o.scopesSupported ?? [
666
+ .../* @__PURE__ */ new Set([
667
+ ...o.requiredScopes ?? [],
668
+ ...[
669
+ ...this.tools.values()
670
+ ].flatMap((t) => t.scopes ?? [])
671
+ ])
672
+ ];
673
+ return {
674
+ resource: o.resource,
675
+ authorization_servers: o.authorizationServers,
676
+ ...scopes.length ? {
677
+ scopes_supported: scopes
678
+ } : {},
679
+ bearer_methods_supported: [
680
+ "header"
681
+ ],
682
+ ...o.resourceName ? {
683
+ resource_name: o.resourceName
684
+ } : {},
685
+ ...o.resourceDocumentation ? {
686
+ resource_documentation: o.resourceDocumentation
687
+ } : {},
688
+ ...o.metadata
689
+ };
690
+ }
691
+ /** HTTP handler for the metadata paths. Public and CORS-enabled so browser-based clients can read it. */
692
+ async handleMetadataHttp(req) {
693
+ const cors = {
694
+ "access-control-allow-origin": "*",
695
+ "access-control-allow-methods": "GET, OPTIONS"
696
+ };
697
+ const method = req.method.toUpperCase();
698
+ if (!this.options.oauth) return {
699
+ status: 404,
700
+ headers: {}
701
+ };
702
+ if (method === "OPTIONS") return {
703
+ status: 204,
704
+ headers: {
705
+ ...cors,
706
+ "access-control-allow-headers": "*"
707
+ }
708
+ };
709
+ if (method !== "GET" && method !== "HEAD") return {
710
+ status: 405,
711
+ headers: {
712
+ allow: "GET, OPTIONS"
713
+ }
714
+ };
715
+ const body = JSON.stringify(await this.protectedResourceMetadata());
716
+ return {
717
+ status: 200,
718
+ headers: {
719
+ ...cors,
720
+ "content-type": "application/json",
721
+ "cache-control": "public, max-age=3600"
722
+ },
723
+ body: method === "HEAD" ? void 0 : body
724
+ };
725
+ }
726
+ /**
543
727
  * Framework-neutral Streamable HTTP handler. Adapters convert their request
544
728
  * into McpHttpRequest, call this, and write the McpHttpResponse back.
545
729
  */
@@ -554,6 +738,15 @@ var McpServer = class {
554
738
  body: JSON.stringify(fail(null, INVALID_REQUEST, "Origin not allowed"))
555
739
  };
556
740
  }
741
+ const oauth = this.options.oauth;
742
+ if (oauth) {
743
+ const outcome = await authenticate(oauth, req.headers);
744
+ if (!outcome.ok) return authError(outcome);
745
+ ctx = {
746
+ ...ctx,
747
+ auth: outcome.auth
748
+ };
749
+ }
557
750
  if (req.method.toUpperCase() !== "POST") {
558
751
  return {
559
752
  status: 405,
@@ -574,6 +767,27 @@ var McpServer = class {
574
767
  };
575
768
  }
576
769
  }
770
+ if (oauth) {
771
+ await this.load();
772
+ const calls = Array.isArray(body) ? body : [
773
+ body
774
+ ];
775
+ for (const m of calls) {
776
+ if (m?.method !== "tools/call") continue;
777
+ const tool = this.tools.get(m.params?.name);
778
+ const missing = missingScopes(ctx.auth, tool?.scopes);
779
+ if (missing.length) {
780
+ const scope = [
781
+ .../* @__PURE__ */ new Set([
782
+ ...ctx.auth?.scopes ?? [],
783
+ ...oauth.requiredScopes ?? [],
784
+ ...tool?.scopes ?? []
785
+ ])
786
+ ];
787
+ return authError(deny(oauth, 403, "insufficient_scope", `Tool "${tool.name}" needs scope: ${missing.join(" ")}`, scope));
788
+ }
789
+ }
790
+ }
577
791
  const response = await this.handleMessage(body, ctx);
578
792
  if (response === null) return {
579
793
  status: 202,
@@ -586,6 +800,20 @@ var McpServer = class {
586
800
  };
587
801
  }
588
802
  };
803
+ function authError(o) {
804
+ return {
805
+ status: o.status,
806
+ headers: {
807
+ "content-type": "application/json",
808
+ "www-authenticate": o.challenge
809
+ },
810
+ body: JSON.stringify({
811
+ error: o.error,
812
+ error_description: o.description
813
+ })
814
+ };
815
+ }
816
+ __name(authError, "authError");
589
817
 
590
818
  // src/hono/index.ts
591
819
  function mcpTool(options = {}) {
@@ -645,6 +873,17 @@ function mountMcp(app, options) {
645
873
  headers: out.headers
646
874
  });
647
875
  });
876
+ for (const p of server.oauthMetadataPaths) {
877
+ app.all(p, async (c) => {
878
+ const out = await server.handleMetadataHttp({
879
+ method: c.req.method
880
+ });
881
+ return new Response(out.body ?? null, {
882
+ status: out.status,
883
+ headers: out.headers
884
+ });
885
+ });
886
+ }
648
887
  return server;
649
888
  }
650
889
  __name(mountMcp, "mountMcp");
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hono/index.ts","../../src/core/dispatch.ts","../../src/core/marker.ts","../../src/core/schema.ts","../../src/core/route-tool.ts","../../src/core/server.ts"],"sourcesContent":["import { buildUrl } from '../core/dispatch.js';\nimport { mark, markerOf } from '../core/marker.js';\nimport { createRouteTool } from '../core/route-tool.js';\nimport { McpServer } from '../core/server.js';\nimport type { Dispatcher, McpServerOptions, McpToolDefinition, RouteToolOptions, ToolContext } from '../core/types.js';\n\ninterface HonoContextLike {\n // Hono >= 3 wraps the request (`c.req.raw`); in Hono 2 `c.req` is the Request itself.\n req: { method: string; raw?: Request; header(): Record<string, string> };\n env?: unknown;\n}\ntype HonoMiddleware = (c: HonoContextLike, next: () => Promise<void>) => Promise<void | Response>;\n\ninterface HonoLike {\n routes: { method: string; path: string; handler: unknown }[];\n request(input: string, init?: RequestInit, env?: unknown): Response | Promise<Response>;\n all(path: string, handler: (c: HonoContextLike) => Promise<Response>): unknown;\n}\n\n/**\n * Mark a Hono route as an MCP tool:\n *\n * app.get('/users/:id', mcpTool({ description: 'Get a user' }), auth, (c) => ...)\n */\nexport function mcpTool(options: RouteToolOptions = {}): HonoMiddleware {\n return mark<HonoMiddleware>(async (_c, next) => {\n await next();\n }, options);\n}\n\nexport interface HonoMcpOptions extends McpServerOptions {\n /** Path of the MCP endpoint. @default '/mcp' */\n path?: string;\n routes?: (RouteToolOptions & { method: string; path: string })[];\n tools?: McpToolDefinition[];\n}\n\n/**\n * Add an MCP endpoint to a Hono app. Works on every Hono runtime (Node, Bun,\n * Deno, Cloudflare Workers). Tool calls use `app.request()`: in-process, with\n * all middleware applied. Call this AFTER defining your routes... or not:\n * discovery is lazy, on the first MCP request.\n */\nexport function mountMcp(app: HonoLike, options: HonoMcpOptions): McpServer {\n const path = options.path ?? '/mcp';\n const server = new McpServer(options);\n\n const dispatch: Dispatcher = async (req, ctx) => {\n const res = await app.request(\n buildUrl('http://localhost', req),\n {\n method: req.method,\n headers: req.headers,\n body: req.body === undefined ? undefined : JSON.stringify(req.body),\n },\n (ctx.raw as HonoContextLike | undefined)?.env,\n );\n const headers: Record<string, string> = {};\n res.headers.forEach((v, k) => (headers[k] = v));\n return { status: res.status, headers, body: await res.text() };\n };\n\n for (const t of options.tools ?? []) server.addTool(t);\n server.onLoad(() => {\n const seen = new Set<string>();\n for (const r of app.routes) {\n const marker = markerOf(r.handler);\n const key = `${r.method} ${r.path}`;\n if (!marker || seen.has(key) || r.method === 'ALL') continue;\n seen.add(key);\n server.addTool(createRouteTool({ method: r.method, path: r.path }, marker, dispatch, options));\n }\n for (const r of options.routes ?? []) server.addTool(createRouteTool(r, r, dispatch, options));\n });\n\n // `all` (not `on([...])`) works on every Hono major; non-POST methods get 405.\n app.all(path, async (c) => {\n const request = c.req.raw ?? (c.req as unknown as Request);\n const headers: Record<string, string> = {};\n request.headers.forEach((v, k) => (headers[k] = v));\n const ctx: ToolContext = { headers, raw: c };\n const body = c.req.method === 'POST' ? await request.text() : undefined;\n const out = await server.handleHttp({ method: c.req.method, headers, body }, ctx);\n return new Response(out.body ?? null, { status: out.status, headers: out.headers });\n });\n return server;\n}\n","import type { Dispatcher, RouteRequest, ToolContext } from './types.js';\n\nexport function buildUrl(base: string, req: Pick<RouteRequest, 'path' | 'query'>): string {\n const url = new URL(base.replace(/\\/+$/, '') + req.path);\n for (const [k, v] of Object.entries(req.query)) {\n for (const item of Array.isArray(v) ? v : [v]) url.searchParams.append(k, item);\n }\n return url.toString();\n}\n\nexport interface FetchDispatcherOptions {\n /**\n * Base URL of the API, e.g. `http://127.0.0.1:3000` or `https://api.example.com/v1`.\n * A function lets adapters resolve it per call (e.g. from the local port).\n */\n baseUrl: string | ((ctx: ToolContext) => string);\n /** Custom fetch implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout in ms. @default 30_000 */\n timeoutMs?: number;\n}\n\n/**\n * Dispatches tool calls as real HTTP requests. Used for loopback calls into the\n * host app (Express, Koa, NestJS) and for standalone gateways in front of any API.\n */\nexport function createFetchDispatcher(opts: FetchDispatcherOptions): Dispatcher {\n const doFetch = opts.fetch ?? fetch;\n return async (req, ctx) => {\n const base = typeof opts.baseUrl === 'function' ? opts.baseUrl(ctx) : opts.baseUrl;\n const res = await doFetch(buildUrl(base, req), {\n method: req.method,\n headers: req.headers,\n body:\n req.body === undefined || req.method === 'GET' || req.method === 'HEAD' ? undefined : JSON.stringify(req.body),\n signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),\n });\n const headers: Record<string, string> = {};\n res.headers.forEach((v, k) => (headers[k] = v));\n return { status: res.status, headers, body: await res.text() };\n };\n}\n","import type { RouteToolOptions } from './types.js';\n\n/** Symbol under which marker middleware carries its tool options. */\nexport const MCP_TOOL = Symbol.for('mcp-expose.tool');\n\nexport type Marked<T> = T & { [MCP_TOOL]: RouteToolOptions };\n\nexport function markerOf(fn: unknown): RouteToolOptions | undefined {\n return typeof fn === 'function' ? (fn as Partial<Marked<object>>)[MCP_TOOL] : undefined;\n}\n\nexport function mark<T extends object>(fn: T, opts: RouteToolOptions): Marked<T> {\n Object.defineProperty(fn, MCP_TOOL, { value: opts, enumerable: false });\n return fn as Marked<T>;\n}\n","import type { JsonSchema, McpToolDefinition, SchemaLike } from './types.js';\n\ninterface StandardSchemaV1 {\n '~standard': {\n validate?: (value: unknown) => unknown;\n jsonSchema?: { input?: (opts: { target: string }) => unknown };\n };\n}\n\nfunction isStandard(s: unknown): s is StandardSchemaV1 {\n return typeof s === 'object' && s !== null && '~standard' in s;\n}\n\n/** Convert any supported schema flavour into a plain JSON Schema object. */\nexport function toJsonSchema(schema: SchemaLike | undefined): JsonSchema | undefined {\n if (schema === undefined || schema === null) return undefined;\n let out: unknown;\n if (isStandard(schema) && typeof schema['~standard'].jsonSchema?.input === 'function') {\n out = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' });\n } else if (typeof (schema as { toJSONSchema?: unknown }).toJSONSchema === 'function') {\n out = (schema as { toJSONSchema(): unknown }).toJSONSchema();\n } else if (isStandard(schema)) {\n throw new Error(\n 'mcp-expose: this schema library does not support JSON Schema export. Pass a plain JSON Schema instead.',\n );\n } else {\n out = schema;\n }\n const { $schema: _ignored, ...rest } = out as JsonSchema;\n return rest;\n}\n\n/** Build a validator from a Standard Schema, if the input is one. */\nexport function toValidator(schema: SchemaLike | undefined): McpToolDefinition['validate'] {\n if (!isStandard(schema) || typeof schema['~standard'].validate !== 'function') return undefined;\n const validate = schema['~standard'].validate;\n return async (value) => {\n const result = (await validate(value)) as {\n value?: unknown;\n issues?: { message: string; path?: (PropertyKey | { key: PropertyKey })[] }[];\n };\n if (!result.issues) return { ok: true, value: result.value };\n const message = result.issues\n .map((i) => {\n const path = (i.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return path ? `${path}: ${i.message}` : i.message;\n })\n .join('; ');\n return { ok: false, message };\n };\n}\n\n/** Very small structural check used when no Standard Schema validator exists. */\nexport function checkRequired(schema: JsonSchema, args: Record<string, unknown>): string | undefined {\n const missing = (schema.required ?? []).filter((k) => args[k] === undefined);\n return missing.length ? `Missing required argument(s): ${missing.join(', ')}` : undefined;\n}\n","import { checkRequired, toJsonSchema, toValidator } from './schema.js';\nimport type {\n Dispatcher,\n JsonSchema,\n McpServerOptions,\n McpToolDefinition,\n RouteResponse,\n RouteSpec,\n RouteToolOptions,\n ToolAnnotations,\n ToolContext,\n ToolResult,\n} from './types.js';\n\nexport const DEFAULT_FORWARD_HEADERS = ['authorization', 'cookie', 'x-api-key', 'accept-language'];\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);\nconst PARAM_RE = /:([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\}/g;\n\n/** Names of the path parameters in a route path (`/a/:id/{slug}` -> ['id', 'slug']). */\nexport function pathParams(path: string): string[] {\n return [...path.matchAll(PARAM_RE)].map((m) => (m[1] ?? m[2]) as string);\n}\n\n/**\n * Encode one path-parameter value. Rejects empty, `.` and `..` values: after URL\n * normalisation they would change which route is called (e.g. `/orders/../admin`),\n * letting an agent reach routes that were never exposed as tools.\n */\nfunction encodeSegment(name: string, value: unknown): string {\n const raw = String(value);\n if (raw === '' || raw === '.' || raw === '..') {\n throw new Error(`Invalid value for path parameter \"${name}\": ${JSON.stringify(raw)}`);\n }\n return encodeURIComponent(raw);\n}\n\n/** Replace path placeholders with URL-encoded values. Missing optional params drop their segment. */\nexport function interpolatePath(path: string, values: Record<string, unknown>): string {\n return path\n .replace(/\\/:([A-Za-z0-9_]+)\\?/g, (_, k: string) =>\n values[k] === undefined ? '' : `/${encodeSegment(k, values[k])}`,\n )\n .replace(PARAM_RE, (_, a?: string, b?: string) => {\n const k = (a ?? b) as string;\n return encodeSegment(k, values[k]);\n });\n}\n\n/** Join path segments, normalising slashes. */\nexport function joinPaths(...parts: (string | undefined)[]): string {\n const joined = parts\n .filter((p): p is string => !!p && p !== '/')\n .map((p) => p.replace(/^\\/+|\\/+$/g, ''))\n .filter(Boolean)\n .join('/');\n return `/${joined}`;\n}\n\n/** `GET /users/:id/orders` -> `get_users_by_id_orders` */\nexport function toolNameFromRoute(method: string, path: string): string {\n const segments = path\n .split('/')\n .filter(Boolean)\n .map((s) => {\n const m = /^(?::([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\})$/.exec(s);\n return m ? `by_${m[1] ?? m[2]}` : s;\n });\n return sanitizeToolName([method.toLowerCase(), ...segments].join('_'));\n}\n\nexport function sanitizeToolName(name: string): string {\n return name\n .replace(/[^A-Za-z0-9_-]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n .slice(0, 64);\n}\n\nfunction defaultAnnotations(method: string): ToolAnnotations {\n switch (method) {\n case 'GET':\n case 'HEAD':\n return { readOnlyHint: true, openWorldHint: false };\n case 'DELETE':\n return { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false };\n case 'PUT':\n return { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };\n default:\n return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };\n }\n}\n\ninterface ArgMapping {\n params: string[];\n query: Set<string>;\n body: Set<string>;\n /** Body schema is not an object: the whole body is passed under the `body` key. */\n wholeBody: boolean;\n bodyMethod: boolean;\n}\n\n/**\n * Build the flat input schema an agent sees, and remember which argument goes\n * to the path, query string or body when the tool is called.\n */\nexport function buildInputSchema(\n route: RouteSpec,\n opts: RouteToolOptions,\n): { schema: JsonSchema; mapping: ArgMapping } {\n const method = route.method.toUpperCase();\n const params = pathParams(route.path);\n const mapping: ArgMapping = {\n params,\n query: new Set(),\n body: new Set(),\n wholeBody: false,\n bodyMethod: BODY_METHODS.has(method),\n };\n\n if (opts.input) {\n const schema = toJsonSchema(opts.input) as JsonSchema;\n return { schema: { type: 'object', ...schema }, mapping };\n }\n\n const properties: Record<string, JsonSchema> = {};\n const required = new Set<string>();\n\n const paramSchema = toJsonSchema(opts.params);\n for (const p of params) {\n properties[p] = paramSchema?.properties?.[p] ?? { type: 'string', description: `Path parameter \"${p}\"` };\n if (!route.path.includes(`:${p}?`)) required.add(p);\n }\n\n const querySchema = toJsonSchema(opts.query);\n for (const [k, v] of Object.entries(querySchema?.properties ?? {})) {\n properties[k] = v;\n mapping.query.add(k);\n }\n for (const k of querySchema?.required ?? []) required.add(k);\n\n const bodySchema = toJsonSchema(opts.body);\n if (bodySchema) {\n if (bodySchema.properties && (bodySchema.type === undefined || bodySchema.type === 'object')) {\n for (const [k, v] of Object.entries(bodySchema.properties)) {\n properties[k] = v;\n mapping.body.add(k);\n }\n for (const k of bodySchema.required ?? []) required.add(k);\n } else {\n properties.body = bodySchema;\n required.add('body');\n mapping.wholeBody = true;\n }\n }\n\n const schema: JsonSchema = { type: 'object', properties };\n if (required.size) schema.required = [...required];\n return { schema, mapping };\n}\n\nfunction splitArgs(args: Record<string, unknown>, mapping: ArgMapping) {\n const pathValues: Record<string, unknown> = {};\n const query: Record<string, string | string[]> = {};\n let body: Record<string, unknown> | unknown | undefined;\n\n for (const [k, v] of Object.entries(args)) {\n if (v === undefined) continue;\n if (mapping.params.includes(k)) {\n pathValues[k] = v;\n } else if (mapping.wholeBody && k === 'body') {\n body = v;\n } else if (mapping.query.has(k) || (!mapping.body.has(k) && !mapping.bodyMethod)) {\n query[k] = Array.isArray(v) ? v.map(String) : typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v);\n } else {\n body = { ...((body as Record<string, unknown>) ?? {}), [k]: v };\n }\n }\n if (body === undefined && mapping.bodyMethod) body = {};\n return { pathValues, query, body };\n}\n\nexport function responseToResult(res: RouteResponse, maxChars: number): ToolResult {\n let text = res.body;\n if (text.length > maxChars) text = `${text.slice(0, maxChars)}\\n…[truncated ${text.length - maxChars} chars]`;\n const isError = res.status >= 400;\n const result: ToolResult = {\n content: [{ type: 'text', text: isError ? `HTTP ${res.status}\\n${text}` : text || `HTTP ${res.status}` }],\n };\n if (isError) {\n result.isError = true;\n return result;\n }\n if ((res.headers['content-type'] ?? '').includes('json') && text === res.body) {\n try {\n const parsed = JSON.parse(res.body);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) result.structuredContent = parsed;\n } catch {\n /* not JSON after all */\n }\n }\n return result;\n}\n\nexport function pickForwardHeaders(ctx: ToolContext, names: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of names) {\n const v = ctx.headers[name.toLowerCase()];\n if (v !== undefined) out[name.toLowerCase()] = v;\n }\n return out;\n}\n\n/**\n * Turn an HTTP route + options into an MCP tool whose handler calls the route\n * through `dispatch`, so auth guards, validation and rate limits all still apply.\n */\nexport function createRouteTool(\n route: RouteSpec,\n opts: RouteToolOptions,\n dispatch: Dispatcher,\n serverOpts: Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars'> = {},\n): McpToolDefinition {\n const method = route.method.toUpperCase();\n const name = sanitizeToolName(opts.name ?? toolNameFromRoute(method, route.path));\n const { schema, mapping } = buildInputSchema(route, opts);\n const forward = serverOpts.forwardHeaders ?? DEFAULT_FORWARD_HEADERS;\n const maxChars = serverOpts.maxResponseChars ?? 100_000;\n\n return {\n name,\n title: opts.title,\n description: opts.description ?? `${method} ${route.path}`,\n inputSchema: schema,\n annotations: { ...defaultAnnotations(method), ...opts.annotations },\n validate: toValidator(opts.input),\n async handler(args, ctx) {\n const missing = opts.input ? undefined : checkRequired(schema, args);\n if (missing) return { isError: true, content: [{ type: 'text', text: missing }] };\n\n const { pathValues, query, body } = splitArgs(args, mapping);\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...pickForwardHeaders(ctx, forward),\n ...opts.headers,\n 'x-mcp-tool': name,\n };\n if (ctx.clientIp) headers['x-forwarded-for'] = ctx.clientIp;\n if (body !== undefined) headers['content-type'] = 'application/json';\n\n let path: string;\n try {\n path = interpolatePath(route.path, pathValues);\n } catch (err) {\n return { isError: true, content: [{ type: 'text', text: (err as Error).message }] };\n }\n const res = await dispatch({ method, path, query, body, headers }, ctx);\n return responseToResult(res, maxChars);\n },\n };\n}\n","import type { McpServerOptions, McpToolDefinition, ToolContext, ToolResult } from './types.js';\n\nexport const SUPPORTED_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];\nexport const LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0] as string;\n\ntype JsonRpcId = string | number | null;\ninterface JsonRpcRequest {\n jsonrpc: '2.0';\n id?: JsonRpcId;\n method: string;\n params?: Record<string, unknown>;\n}\nexport interface JsonRpcResponse {\n jsonrpc: '2.0';\n id: JsonRpcId;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nconst PARSE_ERROR = -32700;\nconst INVALID_REQUEST = -32600;\nconst METHOD_NOT_FOUND = -32601;\nconst INVALID_PARAMS = -32602;\n\nconst ok = (id: JsonRpcId, result: unknown): JsonRpcResponse => ({ jsonrpc: '2.0', id, result });\nconst fail = (id: JsonRpcId, code: number, message: string): JsonRpcResponse => ({\n jsonrpc: '2.0',\n id,\n error: { code, message },\n});\n\n/** Minimal HTTP request/response shapes, so each adapter can bridge its own framework. */\nexport interface McpHttpRequest {\n method: string;\n headers: Record<string, string>;\n /** Parsed JSON body, or the raw string. */\n body: unknown;\n}\nexport interface McpHttpResponse {\n status: number;\n headers: Record<string, string>;\n body?: string;\n}\n\n/**\n * A stateless MCP server speaking the Streamable HTTP transport (JSON responses).\n * Holds the tool registry and answers JSON-RPC messages.\n */\nexport class McpServer {\n private readonly tools = new Map<string, McpToolDefinition>();\n private loaders: (() => void | Promise<void>)[] = [];\n\n constructor(readonly options: McpServerOptions) {}\n\n /** Register a tool. Throws on duplicate names. */\n addTool(tool: McpToolDefinition): this {\n if (this.tools.has(tool.name)) {\n throw new Error(`mcp-expose: duplicate tool name \"${tool.name}\". Set an explicit \\`name\\`.`);\n }\n this.tools.set(tool.name, tool);\n return this;\n }\n\n /** Register a function that adds tools lazily, right before the first MCP request is served. */\n onLoad(loader: () => void | Promise<void>): this {\n this.loaders.push(loader);\n return this;\n }\n\n async listTools(): Promise<McpToolDefinition[]> {\n await this.load();\n return [...this.tools.values()];\n }\n\n private async load() {\n if (!this.loaders.length) return;\n const loaders = this.loaders;\n this.loaders = [];\n for (const l of loaders) await l();\n }\n\n /** Handle one JSON-RPC message (or a batch). Returns null when no response is due. */\n async handleMessage(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | JsonRpcResponse[] | null> {\n if (Array.isArray(message)) {\n const results = (await Promise.all(message.map((m) => this.handleOne(m, ctx)))).filter(\n (r): r is JsonRpcResponse => r !== null,\n );\n return results.length ? results : null;\n }\n return this.handleOne(message, ctx);\n }\n\n private async handleOne(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | null> {\n const msg = message as Partial<JsonRpcRequest>;\n if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0') {\n return fail(null, INVALID_REQUEST, 'Invalid JSON-RPC message');\n }\n // Responses from the client or notifications: acknowledge, no reply.\n if (typeof msg.method !== 'string' || msg.id === undefined) return null;\n const id = msg.id;\n const params = msg.params ?? {};\n\n await this.load();\n switch (msg.method) {\n case 'initialize': {\n const requested = params.protocolVersion as string | undefined;\n const protocolVersion =\n requested && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;\n return ok(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: { name: this.options.name, version: this.options.version ?? '1.0.0' },\n ...(this.options.instructions ? { instructions: this.options.instructions } : {}),\n });\n }\n case 'ping':\n return ok(id, {});\n case 'tools/list':\n return ok(id, {\n tools: [...this.tools.values()].map((t) => ({\n name: t.name,\n ...(t.title ? { title: t.title } : {}),\n description: t.description,\n inputSchema: t.inputSchema,\n ...(t.annotations ? { annotations: t.annotations } : {}),\n })),\n });\n case 'tools/call': {\n const tool = this.tools.get(params.name as string);\n if (!tool) return fail(id, INVALID_PARAMS, `Unknown tool: ${String(params.name)}`);\n return ok(id, await this.callTool(tool, (params.arguments ?? {}) as Record<string, unknown>, ctx));\n }\n case 'resources/list':\n return ok(id, { resources: [] });\n case 'prompts/list':\n return ok(id, { prompts: [] });\n default:\n return fail(id, METHOD_NOT_FOUND, `Method not found: ${msg.method}`);\n }\n }\n\n private async callTool(\n tool: McpToolDefinition,\n args: Record<string, unknown>,\n ctx: ToolContext,\n ): Promise<ToolResult> {\n try {\n if (tool.validate) {\n const v = await tool.validate(args);\n if (!v.ok) return { isError: true, content: [{ type: 'text', text: `Invalid arguments: ${v.message}` }] };\n args = v.value as Record<string, unknown>;\n }\n return await tool.handler(args, ctx);\n } catch (err) {\n // Tool failures are reported in-band so the model can react to them.\n return { isError: true, content: [{ type: 'text', text: `Tool error: ${(err as Error).message}` }] };\n }\n }\n\n /** Check the Origin header (DNS rebinding protection). */\n isOriginAllowed(origin: string | undefined): boolean {\n if (!origin) return true;\n const allowed = this.options.allowedOrigins;\n if (allowed === '*') return true;\n return (allowed ?? []).includes(origin);\n }\n\n /**\n * Framework-neutral Streamable HTTP handler. Adapters convert their request\n * into McpHttpRequest, call this, and write the McpHttpResponse back.\n */\n async handleHttp(req: McpHttpRequest, ctx: ToolContext): Promise<McpHttpResponse> {\n const json = { 'content-type': 'application/json' };\n if (!this.isOriginAllowed(req.headers.origin)) {\n return { status: 403, headers: json, body: JSON.stringify(fail(null, INVALID_REQUEST, 'Origin not allowed')) };\n }\n if (req.method.toUpperCase() !== 'POST') {\n // Stateless server: no standalone SSE stream and no sessions to delete.\n return { status: 405, headers: { allow: 'POST' } };\n }\n let body = req.body;\n if (typeof body === 'string' || body instanceof Uint8Array) {\n try {\n body = JSON.parse(typeof body === 'string' ? body : new TextDecoder().decode(body));\n } catch {\n return { status: 400, headers: json, body: JSON.stringify(fail(null, PARSE_ERROR, 'Parse error')) };\n }\n }\n const response = await this.handleMessage(body, ctx);\n if (response === null) return { status: 202, headers: {} };\n return { status: 200, headers: json, body: JSON.stringify(response) };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;ACEO,SAASA,SAASC,MAAcC,KAAyC;AAC9E,QAAMC,MAAM,IAAIC,IAAIH,KAAKI,QAAQ,QAAQ,EAAA,IAAMH,IAAII,IAAI;AACvD,aAAW,CAACC,GAAGC,CAAAA,KAAMC,OAAOC,QAAQR,IAAIS,KAAK,GAAG;AAC9C,eAAWC,QAAQC,MAAMC,QAAQN,CAAAA,IAAKA,IAAI;MAACA;MAAIL,KAAIY,aAAaC,OAAOT,GAAGK,IAAAA;EAC5E;AACA,SAAOT,IAAIc,SAAQ;AACrB;AANgBjB;;;ACCT,IAAMkB,WAAWC,uBAAOC,IAAI,iBAAA;AAI5B,SAASC,SAASC,IAAW;AAClC,SAAO,OAAOA,OAAO,aAAcA,GAA+BJ,QAAAA,IAAYK;AAChF;AAFgBF;AAIT,SAASG,KAAuBF,IAAOG,MAAsB;AAClEC,SAAOC,eAAeL,IAAIJ,UAAU;IAAEU,OAAOH;IAAMI,YA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AAIC,IAAAA;AACjB,eAAWC,KAAK7B,IAAI8B,QAAQ;AAC1B,YAAMC,SAASC,SAASH,EAAEI,OAAO;AACjC,YAAMC,MAAM,GAAGL,EAAEnB,MAAM,IAAImB,EAAE5B,IAAI;AACjC,UAAI,CAAC8B,UAAUJ,KAAKQ,IAAID,GAAAA,KAAQL,EAAEnB,WAAW,MAAO;AACpDiB,WAAKS,IAAIF,GAAAA;AACThC,aAAOuB,QAAQY,gBAAgB;QAAE3B,QAAQmB,EAAEnB;QAAQT,MAAM4B,EAAE5B;MAAK,GAAG8B,QAAQ3B,UAAUT,OAAAA,CAAAA;IACvF;AACA,eAAWkC,KAAKlC,QAAQmC,UAAU,CAAA,EAAI5B,QAAOuB,QAAQY,gBAAgBR,GAAGA,GAAGzB,UAAUT,OAAAA,CAAAA;EACvF,CAAA;AAGAK,MAAIsC,IAAIrC,MAAM,OAAOsC,MAAAA;AACnB,UAAM/B,UAAU+B,EAAElC,IAAIW,OAAQuB,EAAElC;AAChC,UAAMM,UAAkC,CAAC;AACzCH,YAAQG,QAAQO,QAAQ,CAACC,GAAGC,MAAOT,QAAQS,CAAAA,IAAKD,CAAAA;AAChD,UAAMb,MAAmB;MAAEK;MAASK,KAAKuB;IAAE;AAC3C,UAAM3B,OAAO2B,EAAElC,IAAIK,WAAW,SAAS,MAAMF,QAAQc,KAAI,IAAKT;AAC9D,UAAM2B,MAAM,MAAMtC,OAAOuC,WAAW;MAAE/B,QAAQ6B,EAAElC,IAAIK;MAAQC;MAASC;IAAK,GAAGN,GAAAA;AAC7E,WAAO,IAAIoC,SAASF,IAAI5B,QAAQ,MAAM;MAAES,QAAQmB,IAAInB;MAAQV,SAAS6B,IAAI7B;IAAQ,CAAA;EACnF,CAAA;AACA,SAAOT;AACT;AA3CgBH;","names":["buildUrl","base","req","url","URL","replace","path","k","v","Object","entries","query","item","Array","isArray","searchParams","append","toString","MCP_TOOL","Symbol","for","markerOf","fn","undefined","mark","opts","Object","defineProperty","value","enumerable","isStandard","s","toJsonSchema","schema","undefined","out","jsonSchema","input","target","toJSONSchema","Error","$schema","_ignored","rest","toValidator","validate","value","result","issues","ok","message","map","i","path","p","String","key","join","checkRequired","args","missing","required","filter","k","length","DEFAULT_FORWARD_HEADERS","BODY_METHODS","Set","PARAM_RE","pathParams","path","matchAll","map","m","encodeSegment","name","value","raw","String","Error","JSON","stringify","encodeURIComponent","interpolatePath","values","replace","_","k","undefined","a","b","toolNameFromRoute","method","path","segments","split","filter","Boolean","map","s","m","exec","sanitizeToolName","toLowerCase","join","name","replace","slice","defaultAnnotations","readOnlyHint","openWorldHint","destructiveHint","idempotentHint","buildInputSchema","route","opts","toUpperCase","params","pathParams","mapping","query","Set","body","wholeBody","bodyMethod","BODY_METHODS","has","input","schema","toJsonSchema","type","properties","required","paramSchema","p","description","includes","add","querySchema","k","v","Object","entries","bodySchema","undefined","size","splitArgs","args","pathValues","Array","isArray","String","JSON","stringify","responseToResult","res","maxChars","text","length","isError","status","result","content","headers","parsed","parse","structuredContent","pickForwardHeaders","ctx","names","out","createRouteTool","dispatch","serverOpts","forward","forwardHeaders","DEFAULT_FORWARD_HEADERS","maxResponseChars","title","inputSchema","annotations","validate","toValidator","handler","missing","checkRequired","accept","clientIp","interpolatePath","err","message","SUPPORTED_PROTOCOL_VERSIONS","LATEST_PROTOCOL_VERSION","PARSE_ERROR","INVALID_REQUEST","METHOD_NOT_FOUND","INVALID_PARAMS","ok","id","result","jsonrpc","fail","code","message","error","McpServer","tools","Map","loaders","options","addTool","tool","has","name","Error","set","onLoad","loader","push","listTools","load","values","length","l","handleMessage","ctx","Array","isArray","results","Promise","all","map","m","handleOne","filter","r","msg","method","undefined","params","requested","protocolVersion","includes","capabilities","listChanged","serverInfo","version","instructions","t","title","description","inputSchema","annotations","get","String","callTool","arguments","resources","prompts","args","validate","v","isError","content","type","text","value","handler","err","isOriginAllowed","origin","allowed","allowedOrigins","handleHttp","req","json","headers","status","body","JSON","stringify","toUpperCase","allow","Uint8Array","parse","TextDecoder","decode","response","mcpTool","options","mark","_c","next","mountMcp","app","path","server","McpServer","dispatch","req","ctx","res","request","buildUrl","method","headers","body","undefined","JSON","stringify","raw","env","forEach","v","k","status","text","t","tools","addTool","onLoad","seen","Set","r","routes","marker","markerOf","handler","key","has","add","createRouteTool","all","c","out","handleHttp","Response"]}
1
+ {"version":3,"sources":["../../src/hono/index.ts","../../src/core/dispatch.ts","../../src/core/marker.ts","../../src/core/schema.ts","../../src/core/route-tool.ts","../../src/core/oauth.ts","../../src/core/server.ts"],"sourcesContent":["import { buildUrl } from '../core/dispatch.js';\nimport { mark, markerOf } from '../core/marker.js';\nimport { createRouteTool } from '../core/route-tool.js';\nimport { McpServer } from '../core/server.js';\nimport type { Dispatcher, McpServerOptions, McpToolDefinition, RouteToolOptions, ToolContext } from '../core/types.js';\n\ninterface HonoContextLike {\n // Hono >= 3 wraps the request (`c.req.raw`); in Hono 2 `c.req` is the Request itself.\n req: { method: string; raw?: Request; header(): Record<string, string> };\n env?: unknown;\n}\ntype HonoMiddleware = (c: HonoContextLike, next: () => Promise<void>) => Promise<void | Response>;\n\ninterface HonoLike {\n routes: { method: string; path: string; handler: unknown }[];\n request(input: string, init?: RequestInit, env?: unknown): Response | Promise<Response>;\n all(path: string, handler: (c: HonoContextLike) => Promise<Response>): unknown;\n}\n\n/**\n * Mark a Hono route as an MCP tool:\n *\n * app.get('/users/:id', mcpTool({ description: 'Get a user' }), auth, (c) => ...)\n */\nexport function mcpTool(options: RouteToolOptions = {}): HonoMiddleware {\n return mark<HonoMiddleware>(async (_c, next) => {\n await next();\n }, options);\n}\n\nexport interface HonoMcpOptions extends McpServerOptions {\n /** Path of the MCP endpoint. @default '/mcp' */\n path?: string;\n routes?: (RouteToolOptions & { method: string; path: string })[];\n tools?: McpToolDefinition[];\n}\n\n/**\n * Add an MCP endpoint to a Hono app. Works on every Hono runtime (Node, Bun,\n * Deno, Cloudflare Workers). Tool calls use `app.request()`: in-process, with\n * all middleware applied. Call this AFTER defining your routes... or not:\n * discovery is lazy, on the first MCP request.\n */\nexport function mountMcp(app: HonoLike, options: HonoMcpOptions): McpServer {\n const path = options.path ?? '/mcp';\n const server = new McpServer(options);\n\n const dispatch: Dispatcher = async (req, ctx) => {\n const res = await app.request(\n buildUrl('http://localhost', req),\n {\n method: req.method,\n headers: req.headers,\n body: req.body === undefined ? undefined : JSON.stringify(req.body),\n },\n (ctx.raw as HonoContextLike | undefined)?.env,\n );\n const headers: Record<string, string> = {};\n res.headers.forEach((v, k) => (headers[k] = v));\n return { status: res.status, headers, body: await res.text() };\n };\n\n for (const t of options.tools ?? []) server.addTool(t);\n server.onLoad(() => {\n const seen = new Set<string>();\n for (const r of app.routes) {\n const marker = markerOf(r.handler);\n const key = `${r.method} ${r.path}`;\n if (!marker || seen.has(key) || r.method === 'ALL') continue;\n seen.add(key);\n server.addTool(createRouteTool({ method: r.method, path: r.path }, marker, dispatch, options));\n }\n for (const r of options.routes ?? []) server.addTool(createRouteTool(r, r, dispatch, options));\n });\n\n // `all` (not `on([...])`) works on every Hono major; non-POST methods get 405.\n app.all(path, async (c) => {\n const request = c.req.raw ?? (c.req as unknown as Request);\n const headers: Record<string, string> = {};\n request.headers.forEach((v, k) => (headers[k] = v));\n const ctx: ToolContext = { headers, raw: c };\n const body = c.req.method === 'POST' ? await request.text() : undefined;\n const out = await server.handleHttp({ method: c.req.method, headers, body }, ctx);\n return new Response(out.body ?? null, { status: out.status, headers: out.headers });\n });\n // OAuth Protected Resource Metadata (public).\n for (const p of server.oauthMetadataPaths) {\n app.all(p, async (c) => {\n const out = await server.handleMetadataHttp({ method: c.req.method });\n return new Response(out.body ?? null, { status: out.status, headers: out.headers });\n });\n }\n return server;\n}\n","import type { Dispatcher, RouteRequest, ToolContext } from './types.js';\n\nexport function buildUrl(base: string, req: Pick<RouteRequest, 'path' | 'query'>): string {\n const url = new URL(base.replace(/\\/+$/, '') + req.path);\n for (const [k, v] of Object.entries(req.query)) {\n for (const item of Array.isArray(v) ? v : [v]) url.searchParams.append(k, item);\n }\n return url.toString();\n}\n\nexport interface FetchDispatcherOptions {\n /**\n * Base URL of the API, e.g. `http://127.0.0.1:3000` or `https://api.example.com/v1`.\n * A function lets adapters resolve it per call (e.g. from the local port).\n */\n baseUrl: string | ((ctx: ToolContext) => string);\n /** Custom fetch implementation. Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout in ms. @default 30_000 */\n timeoutMs?: number;\n}\n\n/**\n * Dispatches tool calls as real HTTP requests. Used for loopback calls into the\n * host app (Express, Koa, NestJS) and for standalone gateways in front of any API.\n */\nexport function createFetchDispatcher(opts: FetchDispatcherOptions): Dispatcher {\n const doFetch = opts.fetch ?? fetch;\n return async (req, ctx) => {\n const base = typeof opts.baseUrl === 'function' ? opts.baseUrl(ctx) : opts.baseUrl;\n const res = await doFetch(buildUrl(base, req), {\n method: req.method,\n headers: req.headers,\n body:\n req.body === undefined || req.method === 'GET' || req.method === 'HEAD' ? undefined : JSON.stringify(req.body),\n signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),\n });\n const headers: Record<string, string> = {};\n res.headers.forEach((v, k) => (headers[k] = v));\n return { status: res.status, headers, body: await res.text() };\n };\n}\n","import type { RouteToolOptions } from './types.js';\n\n/** Symbol under which marker middleware carries its tool options. */\nexport const MCP_TOOL = Symbol.for('mcp-expose.tool');\n\nexport type Marked<T> = T & { [MCP_TOOL]: RouteToolOptions };\n\nexport function markerOf(fn: unknown): RouteToolOptions | undefined {\n return typeof fn === 'function' ? (fn as Partial<Marked<object>>)[MCP_TOOL] : undefined;\n}\n\nexport function mark<T extends object>(fn: T, opts: RouteToolOptions): Marked<T> {\n Object.defineProperty(fn, MCP_TOOL, { value: opts, enumerable: false });\n return fn as Marked<T>;\n}\n","import type { JsonSchema, McpToolDefinition, SchemaLike } from './types.js';\n\ninterface StandardSchemaV1 {\n '~standard': {\n validate?: (value: unknown) => unknown;\n jsonSchema?: { input?: (opts: { target: string }) => unknown };\n };\n}\n\nfunction isStandard(s: unknown): s is StandardSchemaV1 {\n return typeof s === 'object' && s !== null && '~standard' in s;\n}\n\n/** Convert any supported schema flavour into a plain JSON Schema object. */\nexport function toJsonSchema(schema: SchemaLike | undefined): JsonSchema | undefined {\n if (schema === undefined || schema === null) return undefined;\n let out: unknown;\n if (isStandard(schema) && typeof schema['~standard'].jsonSchema?.input === 'function') {\n out = schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' });\n } else if (typeof (schema as { toJSONSchema?: unknown }).toJSONSchema === 'function') {\n out = (schema as { toJSONSchema(): unknown }).toJSONSchema();\n } else if (isStandard(schema)) {\n throw new Error(\n 'mcp-expose: this schema library does not support JSON Schema export. Pass a plain JSON Schema instead.',\n );\n } else {\n out = schema;\n }\n const { $schema: _ignored, ...rest } = out as JsonSchema;\n return rest;\n}\n\n/** Build a validator from a Standard Schema, if the input is one. */\nexport function toValidator(schema: SchemaLike | undefined): McpToolDefinition['validate'] {\n if (!isStandard(schema) || typeof schema['~standard'].validate !== 'function') return undefined;\n const validate = schema['~standard'].validate;\n return async (value) => {\n const result = (await validate(value)) as {\n value?: unknown;\n issues?: { message: string; path?: (PropertyKey | { key: PropertyKey })[] }[];\n };\n if (!result.issues) return { ok: true, value: result.value };\n const message = result.issues\n .map((i) => {\n const path = (i.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return path ? `${path}: ${i.message}` : i.message;\n })\n .join('; ');\n return { ok: false, message };\n };\n}\n\n/** Very small structural check used when no Standard Schema validator exists. */\nexport function checkRequired(schema: JsonSchema, args: Record<string, unknown>): string | undefined {\n const missing = (schema.required ?? []).filter((k) => args[k] === undefined);\n return missing.length ? `Missing required argument(s): ${missing.join(', ')}` : undefined;\n}\n","import { checkRequired, toJsonSchema, toValidator } from './schema.js';\nimport type {\n Dispatcher,\n JsonSchema,\n McpServerOptions,\n McpToolDefinition,\n RouteResponse,\n RouteSpec,\n RouteToolOptions,\n ToolAnnotations,\n ToolContext,\n ToolResult,\n} from './types.js';\n\nexport const DEFAULT_FORWARD_HEADERS = ['authorization', 'cookie', 'x-api-key', 'accept-language'];\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);\nconst PARAM_RE = /:([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\}/g;\n\n/** Names of the path parameters in a route path (`/a/:id/{slug}` -> ['id', 'slug']). */\nexport function pathParams(path: string): string[] {\n return [...path.matchAll(PARAM_RE)].map((m) => (m[1] ?? m[2]) as string);\n}\n\n/**\n * Encode one path-parameter value. Rejects empty, `.` and `..` values: after URL\n * normalisation they would change which route is called (e.g. `/orders/../admin`),\n * letting an agent reach routes that were never exposed as tools.\n */\nfunction encodeSegment(name: string, value: unknown): string {\n const raw = String(value);\n if (raw === '' || raw === '.' || raw === '..') {\n throw new Error(`Invalid value for path parameter \"${name}\": ${JSON.stringify(raw)}`);\n }\n return encodeURIComponent(raw);\n}\n\n/** Replace path placeholders with URL-encoded values. Missing optional params drop their segment. */\nexport function interpolatePath(path: string, values: Record<string, unknown>): string {\n return path\n .replace(/\\/:([A-Za-z0-9_]+)\\?/g, (_, k: string) =>\n values[k] === undefined ? '' : `/${encodeSegment(k, values[k])}`,\n )\n .replace(PARAM_RE, (_, a?: string, b?: string) => {\n const k = (a ?? b) as string;\n return encodeSegment(k, values[k]);\n });\n}\n\n/** Join path segments, normalising slashes. */\nexport function joinPaths(...parts: (string | undefined)[]): string {\n const joined = parts\n .filter((p): p is string => !!p && p !== '/')\n .map((p) => p.replace(/^\\/+|\\/+$/g, ''))\n .filter(Boolean)\n .join('/');\n return `/${joined}`;\n}\n\n/** `GET /users/:id/orders` -> `get_users_by_id_orders` */\nexport function toolNameFromRoute(method: string, path: string): string {\n const segments = path\n .split('/')\n .filter(Boolean)\n .map((s) => {\n const m = /^(?::([A-Za-z0-9_]+)\\??|\\{([A-Za-z0-9_]+)\\})$/.exec(s);\n return m ? `by_${m[1] ?? m[2]}` : s;\n });\n return sanitizeToolName([method.toLowerCase(), ...segments].join('_'));\n}\n\nexport function sanitizeToolName(name: string): string {\n return name\n .replace(/[^A-Za-z0-9_-]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n .slice(0, 64);\n}\n\nfunction defaultAnnotations(method: string): ToolAnnotations {\n switch (method) {\n case 'GET':\n case 'HEAD':\n return { readOnlyHint: true, openWorldHint: false };\n case 'DELETE':\n return { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false };\n case 'PUT':\n return { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };\n default:\n return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };\n }\n}\n\ninterface ArgMapping {\n params: string[];\n query: Set<string>;\n body: Set<string>;\n /** Body schema is not an object: the whole body is passed under the `body` key. */\n wholeBody: boolean;\n bodyMethod: boolean;\n}\n\n/**\n * Build the flat input schema an agent sees, and remember which argument goes\n * to the path, query string or body when the tool is called.\n */\nexport function buildInputSchema(\n route: RouteSpec,\n opts: RouteToolOptions,\n): { schema: JsonSchema; mapping: ArgMapping } {\n const method = route.method.toUpperCase();\n const params = pathParams(route.path);\n const mapping: ArgMapping = {\n params,\n query: new Set(),\n body: new Set(),\n wholeBody: false,\n bodyMethod: BODY_METHODS.has(method),\n };\n\n if (opts.input) {\n const schema = toJsonSchema(opts.input) as JsonSchema;\n return { schema: { type: 'object', ...schema }, mapping };\n }\n\n const properties: Record<string, JsonSchema> = {};\n const required = new Set<string>();\n\n const paramSchema = toJsonSchema(opts.params);\n for (const p of params) {\n properties[p] = paramSchema?.properties?.[p] ?? { type: 'string', description: `Path parameter \"${p}\"` };\n if (!route.path.includes(`:${p}?`)) required.add(p);\n }\n\n const querySchema = toJsonSchema(opts.query);\n for (const [k, v] of Object.entries(querySchema?.properties ?? {})) {\n properties[k] = v;\n mapping.query.add(k);\n }\n for (const k of querySchema?.required ?? []) required.add(k);\n\n const bodySchema = toJsonSchema(opts.body);\n if (bodySchema) {\n if (bodySchema.properties && (bodySchema.type === undefined || bodySchema.type === 'object')) {\n for (const [k, v] of Object.entries(bodySchema.properties)) {\n properties[k] = v;\n mapping.body.add(k);\n }\n for (const k of bodySchema.required ?? []) required.add(k);\n } else {\n properties.body = bodySchema;\n required.add('body');\n mapping.wholeBody = true;\n }\n }\n\n const schema: JsonSchema = { type: 'object', properties };\n if (required.size) schema.required = [...required];\n return { schema, mapping };\n}\n\nfunction splitArgs(args: Record<string, unknown>, mapping: ArgMapping) {\n const pathValues: Record<string, unknown> = {};\n const query: Record<string, string | string[]> = {};\n let body: Record<string, unknown> | unknown | undefined;\n\n for (const [k, v] of Object.entries(args)) {\n if (v === undefined) continue;\n if (mapping.params.includes(k)) {\n pathValues[k] = v;\n } else if (mapping.wholeBody && k === 'body') {\n body = v;\n } else if (mapping.query.has(k) || (!mapping.body.has(k) && !mapping.bodyMethod)) {\n query[k] = Array.isArray(v) ? v.map(String) : typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v);\n } else {\n body = { ...((body as Record<string, unknown>) ?? {}), [k]: v };\n }\n }\n if (body === undefined && mapping.bodyMethod) body = {};\n return { pathValues, query, body };\n}\n\nexport function responseToResult(res: RouteResponse, maxChars: number): ToolResult {\n let text = res.body;\n if (text.length > maxChars) text = `${text.slice(0, maxChars)}\\n…[truncated ${text.length - maxChars} chars]`;\n const isError = res.status >= 400;\n const result: ToolResult = {\n content: [{ type: 'text', text: isError ? `HTTP ${res.status}\\n${text}` : text || `HTTP ${res.status}` }],\n };\n if (isError) {\n result.isError = true;\n return result;\n }\n if ((res.headers['content-type'] ?? '').includes('json') && text === res.body) {\n try {\n const parsed = JSON.parse(res.body);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) result.structuredContent = parsed;\n } catch {\n /* not JSON after all */\n }\n }\n return result;\n}\n\nexport function pickForwardHeaders(ctx: ToolContext, names: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of names) {\n const v = ctx.headers[name.toLowerCase()];\n if (v !== undefined) out[name.toLowerCase()] = v;\n }\n return out;\n}\n\n/**\n * Turn an HTTP route + options into an MCP tool whose handler calls the route\n * through `dispatch`, so auth guards, validation and rate limits all still apply.\n */\nexport function createRouteTool(\n route: RouteSpec,\n opts: RouteToolOptions,\n dispatch: Dispatcher,\n serverOpts: Pick<McpServerOptions, 'forwardHeaders' | 'maxResponseChars'> = {},\n): McpToolDefinition {\n const method = route.method.toUpperCase();\n const name = sanitizeToolName(opts.name ?? toolNameFromRoute(method, route.path));\n const { schema, mapping } = buildInputSchema(route, opts);\n const forward = serverOpts.forwardHeaders ?? DEFAULT_FORWARD_HEADERS;\n const maxChars = serverOpts.maxResponseChars ?? 100_000;\n\n return {\n name,\n title: opts.title,\n description: opts.description ?? `${method} ${route.path}`,\n inputSchema: schema,\n annotations: { ...defaultAnnotations(method), ...opts.annotations },\n scopes: opts.scopes,\n validate: toValidator(opts.input),\n async handler(args, ctx) {\n const missing = opts.input ? undefined : checkRequired(schema, args);\n if (missing) return { isError: true, content: [{ type: 'text', text: missing }] };\n\n const { pathValues, query, body } = splitArgs(args, mapping);\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...pickForwardHeaders(ctx, forward),\n ...opts.headers,\n 'x-mcp-tool': name,\n };\n if (ctx.clientIp) headers['x-forwarded-for'] = ctx.clientIp;\n if (body !== undefined) headers['content-type'] = 'application/json';\n\n let path: string;\n try {\n path = interpolatePath(route.path, pathValues);\n } catch (err) {\n return { isError: true, content: [{ type: 'text', text: (err as Error).message }] };\n }\n const res = await dispatch({ method, path, query, body, headers }, ctx);\n return responseToResult(res, maxChars);\n },\n };\n}\n","/**\n * OAuth 2.1 support per the MCP authorization spec: the MCP endpoint acts as an\n * OAuth *resource server*. It publishes Protected Resource Metadata (RFC 9728),\n * answers unauthenticated requests with a `WWW-Authenticate` challenge that\n * tells the client where to log in, and checks bearer tokens with a verifier\n * you provide (see `jwtVerifier` / `introspectionVerifier` in `mcp-expose/oauth`).\n *\n * Runtime-agnostic: no `node:*` imports.\n */\n\n/** Who the access token belongs to and what it allows. Available to tools as `ctx.auth`. */\nexport interface AuthInfo {\n /** The raw access token. */\n token: string;\n /** Scopes granted to the token. */\n scopes: string[];\n /** Subject (user id), e.g. the JWT `sub` claim. */\n subject?: string;\n /** OAuth client the token was issued to. */\n clientId?: string;\n /** Expiry, in seconds since the epoch. Expired tokens are rejected. */\n expiresAt?: number;\n /** All claims / introspection fields. */\n claims?: Record<string, unknown>;\n}\n\nexport interface VerifyTokenContext {\n /** The canonical resource URL (`oauth.resource`). Tokens must be issued for it (audience). */\n resource: string;\n /** Lower-cased headers of the MCP request. */\n headers: Record<string, string>;\n}\n\n/**\n * Checks an access token. Return its AuthInfo, or `undefined` / throw when the\n * token is invalid. It MUST check that the token was issued for this server\n * (audience = `ctx.resource`), or tokens meant for other services would be accepted.\n */\nexport type TokenVerifier = (\n token: string,\n ctx: VerifyTokenContext,\n) => AuthInfo | undefined | null | Promise<AuthInfo | undefined | null>;\n\nexport interface OAuthOptions {\n /**\n * Canonical, public URL of the MCP endpoint, e.g. `https://api.example.com/mcp`.\n * Clients request tokens for this resource, and it must match the URL they connect to.\n */\n resource: string;\n /** Issuer URLs of the authorization servers that issue tokens for this server. */\n authorizationServers: string[];\n /** Checks bearer tokens. */\n verifyToken: TokenVerifier;\n /** Scopes every token needs to use the MCP endpoint at all. */\n requiredScopes?: string[];\n /** Scopes advertised in the metadata. @default requiredScopes plus every tool's `scopes` */\n scopesSupported?: string[];\n /** Human-readable name shown by clients. */\n resourceName?: string;\n /** URL of documentation for developers. */\n resourceDocumentation?: string;\n /** Extra fields merged into the Protected Resource Metadata document. */\n metadata?: Record<string, unknown>;\n}\n\nexport const PROTECTED_RESOURCE_WELL_KNOWN = '/.well-known/oauth-protected-resource';\n\n/**\n * Paths the metadata is served on, per RFC 9728: the well-known prefix with the\n * resource path appended (`/.well-known/oauth-protected-resource/mcp`), plus the\n * bare well-known path that older clients fall back to.\n */\nexport function protectedResourceMetadataPaths(resource: string): string[] {\n const pathname = new URL(resource).pathname.replace(/\\/+$/, '');\n return pathname\n ? [PROTECTED_RESOURCE_WELL_KNOWN + pathname, PROTECTED_RESOURCE_WELL_KNOWN]\n : [PROTECTED_RESOURCE_WELL_KNOWN];\n}\n\n/** Absolute URL of the metadata document, used in `WWW-Authenticate`. */\nexport function protectedResourceMetadataUrl(resource: string): string {\n return new URL(protectedResourceMetadataPaths(resource)[0] as string, resource).href;\n}\n\nexport function validateOAuthOptions(o: OAuthOptions): void {\n let url: URL;\n try {\n url = new URL(o.resource);\n } catch {\n throw new Error(`mcp-expose: oauth.resource must be an absolute URL, got ${JSON.stringify(o.resource)}`);\n }\n if (url.hash) throw new Error('mcp-expose: oauth.resource must not contain a fragment');\n if (!o.authorizationServers?.length) throw new Error('mcp-expose: oauth.authorizationServers must not be empty');\n if (typeof o.verifyToken !== 'function') throw new Error('mcp-expose: oauth.verifyToken is required');\n}\n\nconst quote = (v: string) => `\"${v.replace(/[\"\\\\]/g, '\\\\$&')}\"`;\n\n/** Build a `WWW-Authenticate: Bearer ...` challenge (RFC 6750 + RFC 9728). */\nexport function bearerChallenge(\n resource: string,\n params: { error?: string; errorDescription?: string; scope?: string[] } = {},\n): string {\n const parts: string[] = [];\n if (params.error) parts.push(`error=${quote(params.error)}`);\n if (params.errorDescription) parts.push(`error_description=${quote(params.errorDescription)}`);\n if (params.scope?.length) parts.push(`scope=${quote(params.scope.join(' '))}`);\n parts.push(`resource_metadata=${quote(protectedResourceMetadataUrl(resource))}`);\n return `Bearer ${parts.join(', ')}`;\n}\n\n/** Extract the token from `Authorization: Bearer <token>`. Tokens in the query string are never accepted. */\nexport function bearerToken(headers: Record<string, string>): string | undefined {\n const m = /^Bearer[ ]+([^\\s,]+)\\s*$/i.exec(headers.authorization ?? '');\n return m?.[1];\n}\n\nexport type AuthOutcome =\n | { ok: true; auth: AuthInfo }\n | { ok: false; status: 401 | 403; challenge: string; error: string; description: string };\n\n/** Authenticate one MCP request. */\nexport async function authenticate(o: OAuthOptions, headers: Record<string, string>): Promise<AuthOutcome> {\n const token = bearerToken(headers);\n if (!token) {\n // No credentials: a bare challenge pointing at the metadata starts the client's login flow.\n return {\n ok: false,\n status: 401,\n error: 'unauthorized',\n description: 'Authorization required',\n challenge: bearerChallenge(o.resource, { scope: o.requiredScopes }),\n };\n }\n\n let auth: AuthInfo | undefined | null;\n try {\n auth = await o.verifyToken(token, { resource: o.resource, headers });\n } catch {\n auth = undefined;\n }\n if (!auth) return deny(o, 401, 'invalid_token', 'The access token is invalid');\n if (auth.expiresAt !== undefined && auth.expiresAt * 1000 <= Date.now()) {\n return deny(o, 401, 'invalid_token', 'The access token has expired');\n }\n const missing = missingScopes(auth, o.requiredScopes);\n if (missing.length) {\n // Keep the scopes already granted in the challenge, so re-authorizing never drops access.\n const scope = [...new Set([...(auth.scopes ?? []), ...(o.requiredScopes ?? [])])];\n return deny(o, 403, 'insufficient_scope', `Missing scope: ${missing.join(' ')}`, scope);\n }\n return { ok: true, auth: { ...auth, scopes: auth.scopes ?? [] } };\n}\n\n/** A failed AuthOutcome with an RFC 6750 error challenge. */\nexport function deny(\n o: OAuthOptions,\n status: 401 | 403,\n error: string,\n description: string,\n scope?: string[],\n): AuthOutcome & { ok: false } {\n return {\n ok: false,\n status,\n error,\n description,\n challenge: bearerChallenge(o.resource, { error, errorDescription: description, scope }),\n };\n}\n\nexport function missingScopes(auth: AuthInfo | undefined, required: string[] | undefined): string[] {\n if (!required?.length) return [];\n const granted = new Set(auth?.scopes ?? []);\n return required.filter((s) => !granted.has(s));\n}\n\n/** Parse a space-separated `scope` string or an array of scopes. */\nexport function parseScopes(value: unknown): string[] {\n if (Array.isArray(value)) return value.map(String);\n if (typeof value === 'string') return value.split(' ').filter(Boolean);\n return [];\n}\n","import { authenticate, deny, missingScopes, protectedResourceMetadataPaths, validateOAuthOptions } from './oauth.js';\nimport type { McpServerOptions, McpToolDefinition, ToolContext, ToolResult } from './types.js';\n\nexport const SUPPORTED_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];\nexport const LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0] as string;\n\ntype JsonRpcId = string | number | null;\ninterface JsonRpcRequest {\n jsonrpc: '2.0';\n id?: JsonRpcId;\n method: string;\n params?: Record<string, unknown>;\n}\nexport interface JsonRpcResponse {\n jsonrpc: '2.0';\n id: JsonRpcId;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nconst PARSE_ERROR = -32700;\nconst INVALID_REQUEST = -32600;\nconst METHOD_NOT_FOUND = -32601;\nconst INVALID_PARAMS = -32602;\n\nconst ok = (id: JsonRpcId, result: unknown): JsonRpcResponse => ({ jsonrpc: '2.0', id, result });\nconst fail = (id: JsonRpcId, code: number, message: string): JsonRpcResponse => ({\n jsonrpc: '2.0',\n id,\n error: { code, message },\n});\n\n/** Minimal HTTP request/response shapes, so each adapter can bridge its own framework. */\nexport interface McpHttpRequest {\n method: string;\n headers: Record<string, string>;\n /** Parsed JSON body, or the raw string. */\n body: unknown;\n}\nexport interface McpHttpResponse {\n status: number;\n headers: Record<string, string>;\n body?: string;\n}\n\n/**\n * A stateless MCP server speaking the Streamable HTTP transport (JSON responses).\n * Holds the tool registry and answers JSON-RPC messages.\n */\nexport class McpServer {\n private readonly tools = new Map<string, McpToolDefinition>();\n private loaders: (() => void | Promise<void>)[] = [];\n\n constructor(readonly options: McpServerOptions) {\n if (options.oauth) validateOAuthOptions(options.oauth);\n }\n\n /** Register a tool. Throws on duplicate names. */\n addTool(tool: McpToolDefinition): this {\n if (this.tools.has(tool.name)) {\n throw new Error(`mcp-expose: duplicate tool name \"${tool.name}\". Set an explicit \\`name\\`.`);\n }\n this.tools.set(tool.name, tool);\n return this;\n }\n\n /** Register a function that adds tools lazily, right before the first MCP request is served. */\n onLoad(loader: () => void | Promise<void>): this {\n this.loaders.push(loader);\n return this;\n }\n\n async listTools(): Promise<McpToolDefinition[]> {\n await this.load();\n return [...this.tools.values()];\n }\n\n private async load() {\n if (!this.loaders.length) return;\n const loaders = this.loaders;\n this.loaders = [];\n for (const l of loaders) await l();\n }\n\n /** Handle one JSON-RPC message (or a batch). Returns null when no response is due. */\n async handleMessage(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | JsonRpcResponse[] | null> {\n if (Array.isArray(message)) {\n const results = (await Promise.all(message.map((m) => this.handleOne(m, ctx)))).filter(\n (r): r is JsonRpcResponse => r !== null,\n );\n return results.length ? results : null;\n }\n return this.handleOne(message, ctx);\n }\n\n private async handleOne(message: unknown, ctx: ToolContext): Promise<JsonRpcResponse | null> {\n const msg = message as Partial<JsonRpcRequest>;\n if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0') {\n return fail(null, INVALID_REQUEST, 'Invalid JSON-RPC message');\n }\n // Responses from the client or notifications: acknowledge, no reply.\n if (typeof msg.method !== 'string' || msg.id === undefined) return null;\n const id = msg.id;\n const params = msg.params ?? {};\n\n await this.load();\n switch (msg.method) {\n case 'initialize': {\n const requested = params.protocolVersion as string | undefined;\n const protocolVersion =\n requested && SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;\n return ok(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: { name: this.options.name, version: this.options.version ?? '1.0.0' },\n ...(this.options.instructions ? { instructions: this.options.instructions } : {}),\n });\n }\n case 'ping':\n return ok(id, {});\n case 'tools/list':\n return ok(id, {\n tools: [...this.tools.values()].map((t) => ({\n name: t.name,\n ...(t.title ? { title: t.title } : {}),\n description: t.description,\n inputSchema: t.inputSchema,\n ...(t.annotations ? { annotations: t.annotations } : {}),\n })),\n });\n case 'tools/call': {\n const tool = this.tools.get(params.name as string);\n if (!tool) return fail(id, INVALID_PARAMS, `Unknown tool: ${String(params.name)}`);\n return ok(id, await this.callTool(tool, (params.arguments ?? {}) as Record<string, unknown>, ctx));\n }\n case 'resources/list':\n return ok(id, { resources: [] });\n case 'prompts/list':\n return ok(id, { prompts: [] });\n default:\n return fail(id, METHOD_NOT_FOUND, `Method not found: ${msg.method}`);\n }\n }\n\n private async callTool(\n tool: McpToolDefinition,\n args: Record<string, unknown>,\n ctx: ToolContext,\n ): Promise<ToolResult> {\n try {\n if (tool.validate) {\n const v = await tool.validate(args);\n if (!v.ok) return { isError: true, content: [{ type: 'text', text: `Invalid arguments: ${v.message}` }] };\n args = v.value as Record<string, unknown>;\n }\n return await tool.handler(args, ctx);\n } catch (err) {\n // Tool failures are reported in-band so the model can react to them.\n return { isError: true, content: [{ type: 'text', text: `Tool error: ${(err as Error).message}` }] };\n }\n }\n\n /** Check the Origin header (DNS rebinding protection). */\n isOriginAllowed(origin: string | undefined): boolean {\n if (!origin) return true;\n const allowed = this.options.allowedOrigins;\n if (allowed === '*') return true;\n return (allowed ?? []).includes(origin);\n }\n\n /**\n * Paths on which adapters serve the OAuth Protected Resource Metadata\n * (empty when `oauth` is not configured). They must be public: no auth middleware.\n */\n get oauthMetadataPaths(): string[] {\n return this.options.oauth ? protectedResourceMetadataPaths(this.options.oauth.resource) : [];\n }\n\n /** The OAuth Protected Resource Metadata document (RFC 9728). */\n async protectedResourceMetadata(): Promise<Record<string, unknown>> {\n const o = this.options.oauth;\n if (!o) throw new Error('mcp-expose: the oauth option is not configured');\n await this.load();\n const scopes = o.scopesSupported ?? [\n ...new Set([...(o.requiredScopes ?? []), ...[...this.tools.values()].flatMap((t) => t.scopes ?? [])]),\n ];\n return {\n resource: o.resource,\n authorization_servers: o.authorizationServers,\n ...(scopes.length ? { scopes_supported: scopes } : {}),\n bearer_methods_supported: ['header'],\n ...(o.resourceName ? { resource_name: o.resourceName } : {}),\n ...(o.resourceDocumentation ? { resource_documentation: o.resourceDocumentation } : {}),\n ...o.metadata,\n };\n }\n\n /** HTTP handler for the metadata paths. Public and CORS-enabled so browser-based clients can read it. */\n async handleMetadataHttp(req: Pick<McpHttpRequest, 'method'>): Promise<McpHttpResponse> {\n const cors = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, OPTIONS' };\n const method = req.method.toUpperCase();\n if (!this.options.oauth) return { status: 404, headers: {} };\n if (method === 'OPTIONS') return { status: 204, headers: { ...cors, 'access-control-allow-headers': '*' } };\n if (method !== 'GET' && method !== 'HEAD') return { status: 405, headers: { allow: 'GET, OPTIONS' } };\n const body = JSON.stringify(await this.protectedResourceMetadata());\n return {\n status: 200,\n headers: { ...cors, 'content-type': 'application/json', 'cache-control': 'public, max-age=3600' },\n body: method === 'HEAD' ? undefined : body,\n };\n }\n\n /**\n * Framework-neutral Streamable HTTP handler. Adapters convert their request\n * into McpHttpRequest, call this, and write the McpHttpResponse back.\n */\n async handleHttp(req: McpHttpRequest, ctx: ToolContext): Promise<McpHttpResponse> {\n const json = { 'content-type': 'application/json' };\n if (!this.isOriginAllowed(req.headers.origin)) {\n return { status: 403, headers: json, body: JSON.stringify(fail(null, INVALID_REQUEST, 'Origin not allowed')) };\n }\n const oauth = this.options.oauth;\n if (oauth) {\n const outcome = await authenticate(oauth, req.headers);\n if (!outcome.ok) return authError(outcome);\n ctx = { ...ctx, auth: outcome.auth };\n }\n if (req.method.toUpperCase() !== 'POST') {\n // Stateless server: no standalone SSE stream and no sessions to delete.\n return { status: 405, headers: { allow: 'POST' } };\n }\n let body = req.body;\n if (typeof body === 'string' || body instanceof Uint8Array) {\n try {\n body = JSON.parse(typeof body === 'string' ? body : new TextDecoder().decode(body));\n } catch {\n return { status: 400, headers: json, body: JSON.stringify(fail(null, PARSE_ERROR, 'Parse error')) };\n }\n }\n if (oauth) {\n // Per-tool scopes: answer 403 so the client can ask the user for more access (step-up).\n await this.load();\n const calls = (Array.isArray(body) ? body : [body]) as Partial<JsonRpcRequest>[];\n for (const m of calls) {\n if (m?.method !== 'tools/call') continue;\n const tool = this.tools.get(m.params?.name as string);\n const missing = missingScopes(ctx.auth, tool?.scopes);\n if (missing.length) {\n // Include the scopes already granted, so re-authorizing never drops access the user gave before.\n const scope = [\n ...new Set([...(ctx.auth?.scopes ?? []), ...(oauth.requiredScopes ?? []), ...(tool?.scopes ?? [])]),\n ];\n return authError(\n deny(oauth, 403, 'insufficient_scope', `Tool \"${tool!.name}\" needs scope: ${missing.join(' ')}`, scope),\n );\n }\n }\n }\n const response = await this.handleMessage(body, ctx);\n if (response === null) return { status: 202, headers: {} };\n return { status: 200, headers: json, body: JSON.stringify(response) };\n }\n}\n\nfunction authError(o: { status: number; challenge: string; error: string; description: string }): McpHttpResponse {\n return {\n status: o.status,\n headers: { 'content-type': 'application/json', 'www-authenticate': o.challenge },\n body: JSON.stringify({ error: o.error, error_description: o.description }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;ACEO,SAASA,SAASC,MAAcC,KAAyC;AAC9E,QAAMC,MAAM,IAAIC,IAAIH,KAAKI,QAAQ,QAAQ,EAAA,IAAMH,IAAII,IAAI;AACvD,aAAW,CAACC,GAAGC,CAAAA,KAAMC,OAAOC,QAAQR,IAAIS,KAAK,GAAG;AAC9C,eAAWC,QAAQC,MAAMC,QAAQN,CAAAA,IAAKA,IAAI;MAACA;MAAIL,KAAIY,aAAaC,OAAOT,GAAGK,IAAAA;EAC5E;AACA,SAAOT,IAAIc,SAAQ;AACrB;AANgBjB;;;ACCT,IAAMkB,WAAWC,uBAAOC,IAAI,iBAAA;AAI5B,SAASC,SAASC,IAAW;AAClC,SAAO,OAAOA,OAAO,aAAcA,GAA+BJ,QAAAA,IAAYK;AAChF;AAFgBF;AAIT,SAASG,KAAuBF,IAAOG,MAAsB;AAClEC,SAAOC,eAAeL,IAAIJ,UAAU;IAAEU,OAAOH;IAAMI,YAAY;EAAM,CAAA;AACrE,SAAOP;AACT;AAHgBE;;;ACFhB,SAASM,WAAWC,GAAU;AAC5B,SAAO,OAAOA,MAAM,YAAYA,MAAM,QAAQ,eAAeA;AAC/D;AAFSD;AAKF,SAASE,aAAaC,QAA8B;AACzD,MAAIA,WAAWC,UAAaD,WAAW,KAAM,QAAOC;AACpD,MAAIC;AACJ,MAAIL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;MAAES,QAAQmB,IAAInB;MAAQV,SAAS6B,IAAI7B;IAAQ,CAAA;EACnF,CAAA;AAEA,aAAWgC,KAAKzC,OAAO0C,oBAAoB;AACzC5C,QAAIsC,IAAIK,GAAG,OAAOJ,MAAAA;AAChB,YAAMC,MAAM,MAAMtC,OAAO2C,mBAAmB;QAAEnC,QAAQ6B,EAAElC,IAAIK;MAAO,CAAA;AACnE,aAAO,IAAIgC,SAASF,IAAI5B,QAAQ,MAAM;QAAES,QAAQmB,IAAInB;QAAQV,SAAS6B,IAAI7B;MAAQ,CAAA;IACnF,CAAA;EACF;AACA,SAAOT;AACT;AAlDgBH;","names":["buildUrl","base","req","url","URL","replace","path","k","v","Object","entries","query","item","Array","isArray","searchParams","append","toString","MCP_TOOL","Symbol","for","markerOf","fn","undefined","mark","opts","Object","defineProperty","value","enumerable","isStandard","s","toJsonSchema","schema","undefined","out","jsonSchema","input","target","toJSONSchema","Error","$schema","_ignored","rest","toValidator","validate","value","result","issues","ok","message","map","i","path","p","String","key","join","checkRequired","args","missing","required","filter","k","length","DEFAULT_FORWARD_HEADERS","BODY_METHODS","Set","PARAM_RE","pathParams","path","matchAll","map","m","encodeSegment","name","value","raw","String","Error","JSON","stringify","encodeURIComponent","interpolatePath","values","replace","_","k","undefined","a","b","toolNameFromRoute","method","path","segments","split","filter","Boolean","map","s","m","exec","sanitizeToolName","toLowerCase","join","name","replace","slice","defaultAnnotations","readOnlyHint","openWorldHint","destructiveHint","idempotentHint","buildInputSchema","route","opts","toUpperCase","params","pathParams","mapping","query","Set","body","wholeBody","bodyMethod","BODY_METHODS","has","input","schema","toJsonSchema","type","properties","required","paramSchema","p","description","includes","add","querySchema","k","v","Object","entries","bodySchema","undefined","size","splitArgs","args","pathValues","Array","isArray","String","JSON","stringify","responseToResult","res","maxChars","text","length","isError","status","result","content","headers","parsed","parse","structuredContent","pickForwardHeaders","ctx","names","out","createRouteTool","dispatch","serverOpts","forward","forwardHeaders","DEFAULT_FORWARD_HEADERS","maxResponseChars","title","inputSchema","annotations","scopes","validate","toValidator","handler","missing","checkRequired","accept","clientIp","interpolatePath","err","message","PROTECTED_RESOURCE_WELL_KNOWN","protectedResourceMetadataPaths","resource","pathname","URL","replace","protectedResourceMetadataUrl","href","validateOAuthOptions","o","url","Error","JSON","stringify","hash","authorizationServers","length","verifyToken","quote","v","bearerChallenge","params","parts","error","push","errorDescription","scope","join","bearerToken","headers","m","exec","authorization","authenticate","token","ok","status","description","challenge","requiredScopes","auth","undefined","deny","expiresAt","Date","now","missing","missingScopes","Set","scopes","required","granted","filter","s","has","SUPPORTED_PROTOCOL_VERSIONS","LATEST_PROTOCOL_VERSION","PARSE_ERROR","INVALID_REQUEST","METHOD_NOT_FOUND","INVALID_PARAMS","ok","id","result","jsonrpc","fail","code","message","error","McpServer","tools","Map","loaders","options","oauth","validateOAuthOptions","addTool","tool","has","name","Error","set","onLoad","loader","push","listTools","load","values","length","l","handleMessage","ctx","Array","isArray","results","Promise","all","map","m","handleOne","filter","r","msg","method","undefined","params","requested","protocolVersion","includes","capabilities","listChanged","serverInfo","version","instructions","t","title","description","inputSchema","annotations","get","String","callTool","arguments","resources","prompts","args","validate","v","isError","content","type","text","value","handler","err","isOriginAllowed","origin","allowed","allowedOrigins","oauthMetadataPaths","protectedResourceMetadataPaths","resource","protectedResourceMetadata","o","scopes","scopesSupported","Set","requiredScopes","flatMap","authorization_servers","authorizationServers","scopes_supported","bearer_methods_supported","resourceName","resource_name","resourceDocumentation","resource_documentation","metadata","handleMetadataHttp","req","cors","toUpperCase","status","headers","allow","body","JSON","stringify","handleHttp","json","outcome","authenticate","authError","auth","Uint8Array","parse","TextDecoder","decode","calls","missing","missingScopes","scope","deny","join","response","challenge","error_description","mcpTool","options","mark","_c","next","mountMcp","app","path","server","McpServer","dispatch","req","ctx","res","request","buildUrl","method","headers","body","undefined","JSON","stringify","raw","env","forEach","v","k","status","text","t","tools","addTool","onLoad","seen","Set","r","routes","marker","markerOf","handler","key","has","add","createRouteTool","all","c","out","handleHttp","Response","p","oauthMetadataPaths","handleMetadataHttp"]}
@@ -1,4 +1,5 @@
1
- import { M as McpServerOptions, R as RouteToolOptions, a as McpToolDefinition, b as McpServer } from '../server-fzkb-wJo.cjs';
1
+ import { M as McpServerOptions, R as RouteToolOptions, a as McpToolDefinition, b as McpServer } from '../server-BFQ_Hdh9.cjs';
2
+ import '../oauth-8RmQamGP.cjs';
2
3
 
3
4
  interface HonoContextLike {
4
5
  req: {
@@ -1,4 +1,5 @@
1
- import { M as McpServerOptions, R as RouteToolOptions, a as McpToolDefinition, b as McpServer } from '../server-fzkb-wJo.js';
1
+ import { M as McpServerOptions, R as RouteToolOptions, a as McpToolDefinition, b as McpServer } from '../server-BRw1E2xy.js';
2
+ import '../oauth-8RmQamGP.js';
2
3
 
3
4
  interface HonoContextLike {
4
5
  req: {