mcp-expose 1.1.0 → 1.1.2
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.
- package/CHANGELOG.md +33 -1
- package/README.md +143 -34
- package/dist/adonisjs/index.cjs +128 -6
- package/dist/adonisjs/index.cjs.map +1 -1
- package/dist/adonisjs/index.d.cts +1 -1
- package/dist/adonisjs/index.d.ts +1 -1
- package/dist/adonisjs/index.js +128 -6
- package/dist/adonisjs/index.js.map +1 -1
- package/dist/express/index.cjs +128 -6
- package/dist/express/index.cjs.map +1 -1
- package/dist/express/index.d.cts +1 -1
- package/dist/express/index.d.ts +1 -1
- package/dist/express/index.js +128 -6
- package/dist/express/index.js.map +1 -1
- package/dist/fastify/index.cjs +128 -6
- package/dist/fastify/index.cjs.map +1 -1
- package/dist/fastify/index.d.cts +1 -1
- package/dist/fastify/index.d.ts +1 -1
- package/dist/fastify/index.js +128 -6
- package/dist/fastify/index.js.map +1 -1
- package/dist/hono/index.cjs +128 -6
- package/dist/hono/index.cjs.map +1 -1
- package/dist/hono/index.d.cts +1 -1
- package/dist/hono/index.d.ts +1 -1
- package/dist/hono/index.js +128 -6
- package/dist/hono/index.js.map +1 -1
- package/dist/index.cjs +128 -31
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -5
- package/dist/index.d.ts +7 -5
- package/dist/index.js +128 -31
- package/dist/index.js.map +1 -1
- package/dist/koa/index.cjs +128 -6
- package/dist/koa/index.cjs.map +1 -1
- package/dist/koa/index.d.cts +1 -1
- package/dist/koa/index.d.ts +1 -1
- package/dist/koa/index.js +128 -6
- package/dist/koa/index.js.map +1 -1
- package/dist/nestjs/index.cjs +128 -6
- package/dist/nestjs/index.cjs.map +1 -1
- package/dist/nestjs/index.d.cts +1 -1
- package/dist/nestjs/index.d.ts +1 -1
- package/dist/nestjs/index.js +128 -6
- package/dist/nestjs/index.js.map +1 -1
- package/dist/{server-BFQ_Hdh9.d.cts → server--mQVQq3A.d.cts} +55 -2
- package/dist/{server-BRw1E2xy.d.ts → server-BPDTsT2o.d.ts} +55 -2
- package/package.json +2 -1
package/dist/hono/index.cjs.map
CHANGED
|
@@ -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/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,WAAWG,MAAAA,KAAW,OAAOA,OAAO,WAAA,EAAaG,YAAYC,UAAU,YAAY;AACrF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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
|
+
{"version":3,"sources":["../../src/hono/index.ts","../../src/core/dispatch.ts","../../src/core/marker.ts","../../src/core/result.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 { ToolResult } from './types.js';\n\n/** A ToolResult: `{ content: [{ type: 'text', ... }, ...] }`. Plain data with a `content` array is not one. */\nexport function isToolResult(value: unknown): value is ToolResult {\n const content = (value as ToolResult | undefined)?.content;\n return (\n !!value &&\n typeof value === 'object' &&\n Array.isArray(content) &&\n content.length > 0 &&\n content.every((c) => !!c && typeof c === 'object' && typeof (c as { type?: unknown }).type === 'string')\n );\n}\n\n/** Turn a handler's return value (string, JSON value or ToolResult) into a ToolResult. */\nexport function toToolResult(value: unknown): ToolResult {\n if (isToolResult(value)) return value;\n if (typeof value === 'string') return { content: [{ type: 'text', text: value }] };\n const text = JSON.stringify(value ?? null);\n const result: ToolResult = { content: [{ type: 'text', text }] };\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n result.structuredContent = value as Record<string, unknown>;\n }\n return result;\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 { isToolResult, toToolResult } from './result.js';\nimport { checkRequired, toJsonSchema, toValidator } from './schema.js';\nimport type {\n Dispatcher,\n JsonSchema,\n McpServerOptions,\n McpToolDefinition,\n ResponseTransformContext,\n RouteRequest,\n RouteResponse,\n RouteToolResponse,\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 const text = truncate(res.body, maxChars);\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\nfunction safeDecode(segment: string): string {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n}\n\nfunction truncate(text: string, maxChars: number): string {\n return text.length > maxChars ? `${text.slice(0, maxChars)}\\n…[truncated ${text.length - maxChars} chars]` : text;\n}\n\n/** Add the parsed JSON body (when the response is JSON) and an `ok` flag. */\nexport function toRouteToolResponse(res: RouteResponse): RouteToolResponse {\n let json: unknown;\n if ((res.headers['content-type'] ?? '').includes('json') && res.body) {\n try {\n json = JSON.parse(res.body);\n } catch {\n /* not JSON after all */\n }\n }\n return { ...res, json, ok: res.status < 400 };\n}\n\n/**\n * Turn what a `transformResponse` hook returned into the tool result. Plain values\n * keep the route's error status; ToolResults are used as they are. Text is capped\n * at `maxChars` either way.\n */\nfunction transformedResult(value: unknown, res: RouteToolResponse, maxChars: number): ToolResult {\n const explicit = isToolResult(value);\n const result = toToolResult(value);\n if (!explicit && !res.ok) {\n result.isError = true;\n delete result.structuredContent;\n }\n let truncated = false;\n const content = result.content.map((c) => {\n if (c.type !== 'text' || c.text.length <= maxChars) return c;\n truncated = true;\n return { ...c, text: truncate(c.text, maxChars) };\n });\n if (!truncated) return result;\n // The text no longer matches the structured data, so only keep the text.\n const { structuredContent: _dropped, ...rest } = result;\n return { ...rest, content };\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' | 'transformResponse'> = {},\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 const transform = opts.transformResponse ?? serverOpts.transformResponse;\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 request: RouteRequest = { method, path, query, body, headers };\n const res = await dispatch(request, ctx);\n if (!transform) return responseToResult(res, maxChars);\n\n const { 'content-type': _ct, ...baseHeaders } = headers;\n const hookCtx: ResponseTransformContext = {\n tool: name,\n args,\n request,\n toolContext: ctx,\n defaultResult: () => responseToResult(res, maxChars),\n async callRoute(r) {\n if (!r.path.startsWith('/')) {\n throw new Error(`callRoute: path must start with \"/\", got ${JSON.stringify(r.path)}`);\n }\n // Placeholders are encoded like tool arguments; dot segments are never allowed.\n const params = r.params ?? {};\n const missing = pathParams(r.path).filter((p) => params[p] === undefined && !r.path.includes(`:${p}?`));\n if (missing.length) throw new Error(`callRoute: missing params for ${r.path}: ${missing.join(', ')}`);\n const subPath = interpolatePath(r.path, params);\n if (subPath.split('/').some((seg) => ['.', '..'].includes(safeDecode(seg)))) {\n throw new Error(`callRoute: path must not contain \".\" or \"..\" segments: ${JSON.stringify(subPath)}`);\n }\n const sub: RouteRequest = {\n method: (r.method ?? 'GET').toUpperCase(),\n path: subPath,\n query: r.query ?? {},\n body: r.body,\n headers: { ...baseHeaders, ...r.headers },\n };\n if (sub.body !== undefined) sub.headers['content-type'] = 'application/json';\n return toRouteToolResponse(await dispatch(sub, ctx));\n },\n };\n const response = toRouteToolResponse(res);\n const value = await transform(response, hookCtx);\n return value === undefined ? responseToResult(res, maxChars) : transformedResult(value, response, 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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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;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","isToolResult","value","content","Array","isArray","length","every","c","type","toToolResult","text","JSON","stringify","result","structuredContent","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","truncate","isError","status","result","content","headers","parsed","parse","structuredContent","safeDecode","segment","decodeURIComponent","length","toRouteToolResponse","json","ok","transformedResult","value","explicit","isToolResult","toToolResult","truncated","c","_dropped","rest","pickForwardHeaders","ctx","names","out","createRouteTool","dispatch","serverOpts","forward","forwardHeaders","DEFAULT_FORWARD_HEADERS","maxResponseChars","transform","transformResponse","title","inputSchema","annotations","scopes","validate","toValidator","handler","missing","checkRequired","accept","clientIp","interpolatePath","err","message","request","_ct","baseHeaders","hookCtx","tool","toolContext","defaultResult","callRoute","r","startsWith","Error","subPath","some","seg","sub","response","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"]}
|
package/dist/hono/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as McpServerOptions, R as RouteToolOptions, a as McpToolDefinition, b as McpServer } from '../server
|
|
1
|
+
import { M as McpServerOptions, R as RouteToolOptions, a as McpToolDefinition, b as McpServer } from '../server--mQVQq3A.cjs';
|
|
2
2
|
import '../oauth-8RmQamGP.cjs';
|
|
3
3
|
|
|
4
4
|
interface HonoContextLike {
|
package/dist/hono/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as McpServerOptions, R as RouteToolOptions, a as McpToolDefinition, b as McpServer } from '../server-
|
|
1
|
+
import { M as McpServerOptions, R as RouteToolOptions, a as McpToolDefinition, b as McpServer } from '../server-BPDTsT2o.js';
|
|
2
2
|
import '../oauth-8RmQamGP.js';
|
|
3
3
|
|
|
4
4
|
interface HonoContextLike {
|
package/dist/hono/index.js
CHANGED
|
@@ -28,6 +28,38 @@ function mark(fn, opts) {
|
|
|
28
28
|
}
|
|
29
29
|
__name(mark, "mark");
|
|
30
30
|
|
|
31
|
+
// src/core/result.ts
|
|
32
|
+
function isToolResult(value) {
|
|
33
|
+
const content = value?.content;
|
|
34
|
+
return !!value && typeof value === "object" && Array.isArray(content) && content.length > 0 && content.every((c) => !!c && typeof c === "object" && typeof c.type === "string");
|
|
35
|
+
}
|
|
36
|
+
__name(isToolResult, "isToolResult");
|
|
37
|
+
function toToolResult(value) {
|
|
38
|
+
if (isToolResult(value)) return value;
|
|
39
|
+
if (typeof value === "string") return {
|
|
40
|
+
content: [
|
|
41
|
+
{
|
|
42
|
+
type: "text",
|
|
43
|
+
text: value
|
|
44
|
+
}
|
|
45
|
+
]
|
|
46
|
+
};
|
|
47
|
+
const text = JSON.stringify(value ?? null);
|
|
48
|
+
const result = {
|
|
49
|
+
content: [
|
|
50
|
+
{
|
|
51
|
+
type: "text",
|
|
52
|
+
text
|
|
53
|
+
}
|
|
54
|
+
]
|
|
55
|
+
};
|
|
56
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
57
|
+
result.structuredContent = value;
|
|
58
|
+
}
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
__name(toToolResult, "toToolResult");
|
|
62
|
+
|
|
31
63
|
// src/core/schema.ts
|
|
32
64
|
function isStandard(s) {
|
|
33
65
|
return typeof s === "object" && s !== null && "~standard" in s;
|
|
@@ -248,9 +280,7 @@ function splitArgs(args, mapping) {
|
|
|
248
280
|
}
|
|
249
281
|
__name(splitArgs, "splitArgs");
|
|
250
282
|
function responseToResult(res, maxChars) {
|
|
251
|
-
|
|
252
|
-
if (text.length > maxChars) text = `${text.slice(0, maxChars)}
|
|
253
|
-
\u2026[truncated ${text.length - maxChars} chars]`;
|
|
283
|
+
const text = truncate(res.body, maxChars);
|
|
254
284
|
const isError = res.status >= 400;
|
|
255
285
|
const result = {
|
|
256
286
|
content: [
|
|
@@ -275,6 +305,58 @@ ${text}` : text || `HTTP ${res.status}`
|
|
|
275
305
|
return result;
|
|
276
306
|
}
|
|
277
307
|
__name(responseToResult, "responseToResult");
|
|
308
|
+
function safeDecode(segment) {
|
|
309
|
+
try {
|
|
310
|
+
return decodeURIComponent(segment);
|
|
311
|
+
} catch {
|
|
312
|
+
return segment;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
__name(safeDecode, "safeDecode");
|
|
316
|
+
function truncate(text, maxChars) {
|
|
317
|
+
return text.length > maxChars ? `${text.slice(0, maxChars)}
|
|
318
|
+
\u2026[truncated ${text.length - maxChars} chars]` : text;
|
|
319
|
+
}
|
|
320
|
+
__name(truncate, "truncate");
|
|
321
|
+
function toRouteToolResponse(res) {
|
|
322
|
+
let json;
|
|
323
|
+
if ((res.headers["content-type"] ?? "").includes("json") && res.body) {
|
|
324
|
+
try {
|
|
325
|
+
json = JSON.parse(res.body);
|
|
326
|
+
} catch {
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
...res,
|
|
331
|
+
json,
|
|
332
|
+
ok: res.status < 400
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
__name(toRouteToolResponse, "toRouteToolResponse");
|
|
336
|
+
function transformedResult(value, res, maxChars) {
|
|
337
|
+
const explicit = isToolResult(value);
|
|
338
|
+
const result = toToolResult(value);
|
|
339
|
+
if (!explicit && !res.ok) {
|
|
340
|
+
result.isError = true;
|
|
341
|
+
delete result.structuredContent;
|
|
342
|
+
}
|
|
343
|
+
let truncated = false;
|
|
344
|
+
const content = result.content.map((c) => {
|
|
345
|
+
if (c.type !== "text" || c.text.length <= maxChars) return c;
|
|
346
|
+
truncated = true;
|
|
347
|
+
return {
|
|
348
|
+
...c,
|
|
349
|
+
text: truncate(c.text, maxChars)
|
|
350
|
+
};
|
|
351
|
+
});
|
|
352
|
+
if (!truncated) return result;
|
|
353
|
+
const { structuredContent: _dropped, ...rest } = result;
|
|
354
|
+
return {
|
|
355
|
+
...rest,
|
|
356
|
+
content
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
__name(transformedResult, "transformedResult");
|
|
278
360
|
function pickForwardHeaders(ctx, names) {
|
|
279
361
|
const out = {};
|
|
280
362
|
for (const name of names) {
|
|
@@ -290,6 +372,7 @@ function createRouteTool(route, opts, dispatch, serverOpts = {}) {
|
|
|
290
372
|
const { schema, mapping } = buildInputSchema(route, opts);
|
|
291
373
|
const forward = serverOpts.forwardHeaders ?? DEFAULT_FORWARD_HEADERS;
|
|
292
374
|
const maxChars = serverOpts.maxResponseChars ?? 1e5;
|
|
375
|
+
const transform = opts.transformResponse ?? serverOpts.transformResponse;
|
|
293
376
|
return {
|
|
294
377
|
name,
|
|
295
378
|
title: opts.title,
|
|
@@ -335,14 +418,53 @@ function createRouteTool(route, opts, dispatch, serverOpts = {}) {
|
|
|
335
418
|
]
|
|
336
419
|
};
|
|
337
420
|
}
|
|
338
|
-
const
|
|
421
|
+
const request = {
|
|
339
422
|
method,
|
|
340
423
|
path,
|
|
341
424
|
query,
|
|
342
425
|
body,
|
|
343
426
|
headers
|
|
344
|
-
}
|
|
345
|
-
|
|
427
|
+
};
|
|
428
|
+
const res = await dispatch(request, ctx);
|
|
429
|
+
if (!transform) return responseToResult(res, maxChars);
|
|
430
|
+
const { "content-type": _ct, ...baseHeaders } = headers;
|
|
431
|
+
const hookCtx = {
|
|
432
|
+
tool: name,
|
|
433
|
+
args,
|
|
434
|
+
request,
|
|
435
|
+
toolContext: ctx,
|
|
436
|
+
defaultResult: /* @__PURE__ */ __name(() => responseToResult(res, maxChars), "defaultResult"),
|
|
437
|
+
async callRoute(r) {
|
|
438
|
+
if (!r.path.startsWith("/")) {
|
|
439
|
+
throw new Error(`callRoute: path must start with "/", got ${JSON.stringify(r.path)}`);
|
|
440
|
+
}
|
|
441
|
+
const params = r.params ?? {};
|
|
442
|
+
const missing2 = pathParams(r.path).filter((p) => params[p] === void 0 && !r.path.includes(`:${p}?`));
|
|
443
|
+
if (missing2.length) throw new Error(`callRoute: missing params for ${r.path}: ${missing2.join(", ")}`);
|
|
444
|
+
const subPath = interpolatePath(r.path, params);
|
|
445
|
+
if (subPath.split("/").some((seg) => [
|
|
446
|
+
".",
|
|
447
|
+
".."
|
|
448
|
+
].includes(safeDecode(seg)))) {
|
|
449
|
+
throw new Error(`callRoute: path must not contain "." or ".." segments: ${JSON.stringify(subPath)}`);
|
|
450
|
+
}
|
|
451
|
+
const sub = {
|
|
452
|
+
method: (r.method ?? "GET").toUpperCase(),
|
|
453
|
+
path: subPath,
|
|
454
|
+
query: r.query ?? {},
|
|
455
|
+
body: r.body,
|
|
456
|
+
headers: {
|
|
457
|
+
...baseHeaders,
|
|
458
|
+
...r.headers
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
if (sub.body !== void 0) sub.headers["content-type"] = "application/json";
|
|
462
|
+
return toRouteToolResponse(await dispatch(sub, ctx));
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
const response = toRouteToolResponse(res);
|
|
466
|
+
const value = await transform(response, hookCtx);
|
|
467
|
+
return value === void 0 ? responseToResult(res, maxChars) : transformedResult(value, response, maxChars);
|
|
346
468
|
}
|
|
347
469
|
};
|
|
348
470
|
}
|