@20baht/elysia-openapi-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/auth/authenticate.ts", "../src/auth/bearer.ts", "../src/auth/access.ts", "../src/auth/prm.ts", "../src/auth/resource.ts", "../src/auth/verify.ts", "../src/auth/resolve.ts", "../src/execute.ts", "../src/openapi/schema.ts", "../src/openapi/naming.ts", "../src/openapi/types.ts", "../src/openapi/derive.ts", "../src/transport.ts", "../src/warnings.ts", "../src/plugin.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * The resource-server gate in front of `/mcp`. Every failure is a proper\n * RFC 6750 / RFC 9728 response so clients can discover the authorization\n * server and retry.\n */\nimport type { AuthInfo } from '@modelcontextprotocol/server';\nimport { audienceMatches, checkBearer } from '@20baht/elysia-resource-server';\nimport { bearerChallenge, type BearerErrorCode } from './bearer.ts';\nimport type { ResolvedAuth } from './resolve.ts';\nimport type { TokenClaims } from './verify.ts';\n\nexport const NO_STORE: Record<string, string> = { 'cache-control': 'no-store', pragma: 'no-cache' };\n\nexport type AuthOutcome =\n { ok: true; claims: TokenClaims; authInfo: AuthInfo } | { ok: false; response: Response };\n\n/** An RFC 6750 error response carrying the RFC 9728 `resource_metadata` challenge. */\nexport function challengeResponse(\n auth: ResolvedAuth,\n status: 401 | 403,\n error: BearerErrorCode | undefined,\n description: string | undefined,\n scope: readonly string[] | undefined,\n): Response {\n const headers: Record<string, string> = {\n ...NO_STORE,\n 'www-authenticate': bearerChallenge({\n resourceMetadataUrl: auth.resourceMetadataUrl,\n error,\n errorDescription: description,\n scope,\n }),\n };\n const body = error ? { error, error_description: description } : null;\n return body ? Response.json(body, { status, headers }) : new Response(null, { status, headers });\n}\n\nconst reject = (...args: Parameters<typeof challengeResponse>): AuthOutcome => ({\n ok: false,\n response: challengeResponse(...args),\n});\n\nexport async function authenticate(request: Request, auth: ResolvedAuth): Promise<AuthOutcome> {\n const hint = auth.scopesSupported ?? (auth.scopes.length ? auth.scopes : undefined);\n // the token itself: genuine, from a trusted issuer, for this resource, in date\n const checked = await checkBearer(request, auth);\n if (!checked.ok) return reject(auth, 401, checked.error, checked.description, hint);\n const { token, claims, scopes } = checked;\n const missing = auth.scopes.filter((s) => !scopes.includes(s));\n if (missing.length > 0) {\n return reject(\n auth,\n 403,\n 'insufficient_scope',\n `Requires scope: ${auth.scopes.join(' ')}`,\n auth.scopes,\n );\n }\n\n const authInfo: AuthInfo = {\n token,\n clientId:\n typeof claims.client_id === 'string'\n ? claims.client_id\n : typeof claims.azp === 'string'\n ? claims.azp\n : claims.sub,\n scopes,\n expiresAt: typeof claims.exp === 'number' ? claims.exp : undefined,\n resource: auth.resourceUrl,\n extra: claims,\n };\n return { ok: true, claims, authInfo };\n}\n\nexport { audienceMatches };\n",
6
+ "// Moved to @20baht/elysia-resource-server (NOTES 2026-11-21); re-exported so this package's API is unchanged.\nexport { bearerChallenge, extractBearer } from '@20baht/elysia-resource-server';\nexport type { BearerErrorCode, ChallengeOptions } from '@20baht/elysia-resource-server';\n",
7
+ "/**\n * Per-message access policy, applied after the token gate and before the SDK\n * sees the payload: anonymous callers reach only discovery and public tools,\n * and each tool's `detail.mcp.scopes` is enforced with a step-up challenge.\n */\nimport type { AuthInfo } from '@modelcontextprotocol/server';\nimport type { ToolSpec } from '../openapi/derive.ts';\nimport { challengeResponse } from './authenticate.ts';\nimport type { ResolvedAuth } from './resolve.ts';\n\n/**\n * Methods a caller without a token may issue: the handshake of both protocol\n * eras, `ping`, and `tools/list`, so hosts can show the tools before asking\n * the user to sign in. `tools/call` is decided per tool.\n */\nconst ANONYMOUS_METHODS = new Set(['initialize', 'server/discover', 'ping', 'tools/list']);\n\ninterface RpcRequest {\n method: string;\n params?: { name?: unknown };\n}\n\n/** JSON-RPC requests in the payload (a 2025-03-26 batch may carry several). */\nfunction requestsIn(body: unknown): RpcRequest[] {\n const messages = Array.isArray(body) ? body : [body];\n return messages.filter(\n (m): m is RpcRequest =>\n typeof m === 'object' && m !== null && typeof (m as RpcRequest).method === 'string',\n );\n}\n\n/** A tool's own `detail.mcp.scopes` are all among `granted` (vacuously true without any). */\nexport const holdsToolScopes = (tool: ToolSpec, granted: readonly string[]) =>\n tool.scopes.every((s) => granted.includes(s));\n\nconst union = (...lists: readonly (readonly string[])[]) => [...new Set(lists.flat())];\n\n/** `null` lets the payload through; otherwise the challenge to answer with. */\n// eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\nexport function checkAccess(\n body: unknown,\n tools: ReadonlyMap<string, ToolSpec>,\n auth: ResolvedAuth,\n authInfo: AuthInfo | undefined,\n): Response | null {\n for (const message of requestsIn(body)) {\n // Notifications carry no data back; leave them to the SDK.\n if (message.method.startsWith('notifications/')) continue;\n const tool =\n message.method === 'tools/call' && typeof message.params?.name === 'string'\n ? tools.get(message.params.name)\n : undefined;\n\n if (!authInfo) {\n if (ANONYMOUS_METHODS.has(message.method) || tool?.public) continue;\n // An unknown tool is answered by the SDK only once signed in, so the\n // challenge does not depend on which names exist.\n const hint = tool?.scopes.length\n ? union(auth.scopes, tool.scopes)\n : (auth.scopesSupported ?? (auth.scopes.length ? auth.scopes : undefined));\n return challengeResponse(auth, 401, undefined, undefined, hint);\n }\n\n if (tool && !holdsToolScopes(tool, authInfo.scopes)) {\n // Ask for everything already granted plus what is missing, so the\n // re-authorized token keeps working for the other tools.\n return challengeResponse(\n auth,\n 403,\n 'insufficient_scope',\n `Tool ${tool.name} requires scope: ${tool.scopes.join(' ')}`,\n union(authInfo.scopes, auth.scopes, tool.scopes),\n );\n }\n }\n return null;\n}\n",
8
+ "/** RFC 9728 Protected Resource Metadata. */\nimport type { ResolvedAuth } from './resolve.ts';\n\nexport function protectedResourceMetadata(auth: ResolvedAuth): Record<string, unknown> {\n const doc: Record<string, unknown> = {\n resource: auth.resource,\n authorization_servers: auth.authorizationServers,\n bearer_methods_supported: ['header'],\n };\n if (auth.scopesSupported && auth.scopesSupported.length > 0) {\n doc.scopes_supported = auth.scopesSupported;\n }\n if (auth.resourceName) doc.resource_name = auth.resourceName;\n if (auth.resourceDocumentation) doc.resource_documentation = auth.resourceDocumentation;\n return doc;\n}\n",
9
+ "// Moved to @20baht/elysia-resource-server (NOTES 2026-11-21); re-exported so this package's API is unchanged.\nexport {\n normalizeResource,\n resourcesEqual,\n validateResourceUri,\n} from '@20baht/elysia-resource-server';\n",
10
+ "// Moved to @20baht/elysia-resource-server (NOTES 2026-11-21); re-exported so this package's API is unchanged.\nexport {\n createJwksVerifier,\n metadataCandidates,\n verifyWithOAuthProvider,\n} from '@20baht/elysia-resource-server';\nexport type {\n FetchLike,\n JwksVerifierOptions,\n OAuthProviderLike,\n TokenClaims,\n TokenVerifier,\n} from '@20baht/elysia-resource-server';\n",
11
+ "/** Validate and normalise the `auth` option block. */\nimport type { ToolSpec } from '../openapi/derive.ts';\nimport { normalizeResource, validateResourceUri } from './resource.ts';\nimport { createJwksVerifier, type FetchLike, type TokenVerifier } from './verify.ts';\n\nexport interface McpifyAuthOptions {\n /** Canonical URI of this MCP server; the audience every token must carry (RFC 8707). */\n resource: string;\n /** Issuer identifiers of the authorization servers allowed to mint tokens for it. */\n authorizationServers: string[];\n /** Replace the default JWKS verifier (e.g. `verifyWithOAuthProvider(...)`). */\n verify?: TokenVerifier;\n /** Where the RFC 9728 document is served. Default: `/.well-known/oauth-protected-resource<resource path>`. */\n prmPath?: string;\n /** Scopes every MCP request must hold (403 `insufficient_scope` otherwise). */\n scopes?: string[];\n /**\n * Let requests without an `Authorization` header connect, list tools, and\n * call tools marked `detail.mcp: { public: true }`; any other call gets the\n * 401 challenge that starts sign-in. A token that is present is always\n * verified. Default false.\n */\n allowAnonymous?: boolean;\n /**\n * Expose only tools that declare `detail.mcp.scopes` or `detail.mcp.public`;\n * the rest are left out of the tool set with a warning. Default false: any\n * token valid for `resource` (and holding `scopes`) can call every tool that\n * declares no scopes of its own.\n */\n requireToolScopes?: boolean;\n /** Advertised in the PRM document and the 401 challenge. */\n scopesSupported?: string[];\n resourceName?: string;\n resourceDocumentation?: string;\n /**\n * Seconds of slack when checking `exp`. Default: `jwks.clockTolerance`\n * (30) with the built-in verifier, 0 with a custom `verify`.\n */\n clockTolerance?: number;\n /** Default verifier tuning; ignored when `verify` is set. */\n jwks?: {\n uri?: string | Record<string, string>;\n algorithms?: string[];\n clockTolerance?: number;\n /** Required JOSE `typ` header. Default `at+jwt` (RFC 9068); `false` skips the check. */\n typ?: string | false;\n fetch?: FetchLike;\n };\n}\n\n/**\n * `verify` refusing with its own answer: a JSON-RPC error with this HTTP\n * `status` (400-599), `code` (default -32001) and `message`, so a caller who\n * is signed in but may not use the endpoint learns why.\n */\nexport interface RequestAuthRefusal {\n status: number;\n code?: number;\n message: string;\n}\n\n/**\n * `verify` admitting with limits. Only the tools that pass every given\n * filter are listed by `tools/list` and callable by `tools/call`; any other\n * is answered like an unknown tool. At least one field must be present.\n */\nexport interface RequestAuthAdmission {\n /**\n * Scopes the caller holds. A tool that declares `detail.mcp.scopes` is kept\n * only when every one of them is here, as in OAuth mode; a tool without\n * scopes is kept.\n */\n scopes?: string[];\n /** Keep only the tools for which this returns `true`. */\n tools?: (tool: ToolSpec) => boolean;\n /** `true` keeps only the tools marked `readOnlyHint` (GET routes). */\n readOnly?: boolean;\n}\n\n/**\n * `true` admits with every tool, an admission object admits with a filtered\n * tool set, a refusal object answers with its own error; anything else\n * (`false`, a throw, any other value) is a bare 401.\n */\nexport type RequestAuthResult = boolean | RequestAuthRefusal | RequestAuthAdmission;\n\n/**\n * Request mode, for apps that already guard their routes with an API key or a\n * session cookie: `verify` sees every MCP request (including `tools/list`)\n * and decides with a `RequestAuthResult`. No OAuth discovery is offered.\n */\nexport interface McpifyRequestAuthOptions {\n verify: (request: Request) => RequestAuthResult | Promise<RequestAuthResult>;\n resource?: never;\n authorizationServers?: never;\n}\n\n/** Keys that only mean something in OAuth resource-server mode. */\nconst OAUTH_ONLY_KEYS = [\n 'authorizationServers',\n 'prmPath',\n 'scopes',\n 'allowAnonymous',\n 'scopesSupported',\n 'resourceName',\n 'resourceDocumentation',\n 'clockTolerance',\n 'jwks',\n] as const;\n\n/** OAuth when `resource` is set; request mode otherwise (and then OAuth-only keys are an error). */\nexport function isRequestAuth(\n auth: McpifyAuthOptions | McpifyRequestAuthOptions,\n): auth is McpifyRequestAuthOptions {\n if ('resource' in auth && auth.resource !== undefined) return false;\n const stray = OAUTH_ONLY_KEYS.filter((k) => k in auth);\n if (stray.length > 0) {\n // Most likely an OAuth config missing `resource`; never run it as request mode.\n throw new TypeError(\n `[mcpify] auth.${stray[0]} needs auth.resource (OAuth mode); request mode takes only auth.verify`,\n );\n }\n if (typeof auth.verify !== 'function') {\n throw new TypeError(\n '[mcpify] auth needs either `resource` + `authorizationServers` (OAuth) or `verify(request)`',\n );\n }\n return true;\n}\n\nexport interface ResolvedAuth {\n resource: string;\n resourceUrl: URL;\n authorizationServers: string[];\n verify: TokenVerifier;\n prmPath: string;\n resourceMetadataUrl: string;\n scopes: string[];\n allowAnonymous: boolean;\n requireToolScopes: boolean;\n scopesSupported?: string[];\n resourceName?: string;\n resourceDocumentation?: string;\n /** Seconds of slack applied to the `exp` check. */\n clockTolerance: number;\n}\n\nexport function resolveAuth(auth: McpifyAuthOptions): ResolvedAuth {\n const resourceUrl = validateResourceUri(auth.resource, 'auth.resource');\n const resource = normalizeResource(auth.resource);\n if (!Array.isArray(auth.authorizationServers) || auth.authorizationServers.length === 0) {\n throw new TypeError('[mcpify] auth.authorizationServers needs at least one issuer URL');\n }\n const authorizationServers = auth.authorizationServers.map((as) =>\n normalizeResource(validateResourceUri(as, 'auth.authorizationServers entry').toString()),\n );\n const resourcePath = resourceUrl.pathname.replace(/\\/+$/, '');\n const prmPath = auth.prmPath ?? `/.well-known/oauth-protected-resource${resourcePath}`;\n if (!prmPath.startsWith('/')) throw new TypeError('[mcpify] auth.prmPath must start with \"/\"');\n\n const clockTolerance =\n auth.clockTolerance ?? (auth.verify ? 0 : (auth.jwks?.clockTolerance ?? 30));\n if (!Number.isFinite(clockTolerance) || clockTolerance < 0) {\n throw new TypeError('[mcpify] auth.clockTolerance must be a non-negative number of seconds');\n }\n\n return {\n resource,\n resourceUrl,\n authorizationServers,\n verify:\n auth.verify ??\n createJwksVerifier({\n authorizationServers,\n jwksUri: auth.jwks?.uri,\n algorithms: auth.jwks?.algorithms,\n clockTolerance: auth.jwks?.clockTolerance,\n typ: auth.jwks?.typ,\n fetch: auth.jwks?.fetch,\n }),\n prmPath,\n resourceMetadataUrl: `${resourceUrl.origin}${prmPath}`,\n scopes: auth.scopes ?? [],\n allowAnonymous: auth.allowAnonymous === true,\n requireToolScopes: auth.requireToolScopes === true,\n scopesSupported: auth.scopesSupported,\n resourceName: auth.resourceName,\n resourceDocumentation: auth.resourceDocumentation,\n clockTolerance,\n };\n}\n",
12
+ "/**\n * Tool execution: unflatten arguments, build a synthetic `Request`, run it\n * through `app.handle()` (full Elysia lifecycle), and turn the `Response`\n * into an MCP `CallToolResult`.\n */\nimport {\n ProtocolError,\n ProtocolErrorCode,\n type CallToolResult,\n} from '@modelcontextprotocol/server';\nimport type { ToolSpec } from './openapi/derive.ts';\nimport { unflattenArgs, WRAPPED_RESULT_KEY } from './openapi/schema.ts';\n\nexport interface Handler {\n handle(request: Request): Promise<Response>;\n}\n\n/**\n * Every synthetic request `buildToolRequest` has made. Membership is the mark\n * `isToolCall` reads: it lives in this module, not on the wire, so a client\n * cannot forge it and a header policy cannot strip it.\n */\nconst toolRequests = new WeakSet<Request>();\n\n/**\n * True for the request a `tools/call` runs through the app, so hooks and\n * handlers can tell an agent's call from a direct HTTP request (to audit it,\n * or to refuse what only people may do). Elysia hands that same object to\n * every lifecycle hook as `request`.\n */\nexport function isToolCall(request: Request): boolean {\n return toolRequests.has(request);\n}\n\n/** What `onToolCall` hears after each tool call that reached the app. */\nexport interface ToolCallEvent {\n tool: ToolSpec;\n /** The arguments as the client sent them. */\n args: Record<string, unknown>;\n /** The synthetic request the route ran on (`isToolCall(request)` is true; its body is spent). */\n request: Request;\n /** A copy of the route's response, free to read. */\n response: Response;\n /** Time spent in `app.handle()`, in milliseconds. */\n durationMs: number;\n}\n\nexport type OnToolCall = (event: ToolCallEvent) => void | Promise<void>;\n\n/** Decide which incoming MCP request headers reach the synthetic request. */\nexport type HeaderPolicy = (incoming: Headers) => HeadersInit;\n\n/**\n * Hop-by-hop and transport-level headers never make sense on the synthetic\n * request; everything else (Authorization, Cookie, X-Api-Key, …) is forwarded\n * so the route's own guards see exactly what the MCP client sent.\n */\nconst STRIPPED = new Set([\n 'host',\n 'content-length',\n 'content-type',\n 'accept',\n 'accept-encoding',\n 'connection',\n 'transfer-encoding',\n 'keep-alive',\n 'upgrade',\n 'te',\n 'trailer',\n 'last-event-id',\n]);\n\nexport const defaultHeaderPolicy: HeaderPolicy = (incoming) => {\n const out = new Headers();\n incoming.forEach((value, key) => {\n const name = key.toLowerCase();\n // `Mcp-*` (session, protocol version, 2026-07-28 method/name/param\n // mirrors) describe the MCP exchange, not the route call.\n if (!STRIPPED.has(name) && !name.startsWith('mcp-')) out.set(key, value);\n });\n return out;\n};\n\nfunction toQueryString(query: Record<string, unknown>): string {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n const values = Array.isArray(value) ? value : [value];\n for (const v of values) {\n params.append(key, typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\n/** Static template text is percent-encoded the way `URL` would, so the final guard compares like with like. */\nconst encodeStatic = (text: string) => text.replace(/[^\\x21-\\x7e]/gu, encodeURIComponent);\n\nexport function buildToolRequest(\n tool: ToolSpec,\n args: Record<string, unknown>,\n original: Request,\n headerPolicy: HeaderPolicy = defaultHeaderPolicy,\n): Request {\n const { params, query, headers: headerArgs, body } = unflattenArgs(args, tool.flat);\n\n const path = tool.path\n .split(/(\\{[^}]+\\})/)\n .map((part) => {\n if (!/^\\{[^}]+\\}$/.test(part)) return encodeStatic(part);\n const name = part.slice(1, -1);\n const value = params[name];\n if (value === undefined || value === null || value === '') {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Missing required path parameter \"${name}\" for tool ${tool.name}`,\n );\n }\n const text = String(value);\n // encodeURIComponent leaves dots alone and `new Request` collapses dot\n // segments, so these would climb out of the tool's route.\n if (text === '.' || text === '..') {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Invalid path parameter \"${name}\" for tool ${tool.name}: \"${text}\" is not allowed`,\n );\n }\n return encodeURIComponent(text);\n })\n .join('');\n\n const origin = new URL(original.url).origin;\n const url = new URL(`${origin}${path}${toQueryString(query)}`);\n if (url.pathname !== path) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Path parameters for tool ${tool.name} resolve outside the tool's route`,\n );\n }\n\n const headers = new Headers(headerPolicy(original.headers));\n headers.set('accept', 'application/json, text/plain;q=0.9, */*;q=0.8');\n for (const [name, value] of Object.entries(headerArgs)) {\n if (value === undefined || value === null) continue;\n const text = Array.isArray(value)\n ? value.join(',')\n : typeof value === 'object'\n ? JSON.stringify(value)\n : String(value);\n try {\n headers.set(name, text);\n } catch {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Invalid value for header parameter \"${name}\" for tool ${tool.name}`,\n );\n }\n }\n let bodyText: string | undefined;\n if (body !== undefined && tool.method !== 'GET') {\n bodyText = JSON.stringify(body);\n headers.set('content-type', 'application/json');\n }\n const request = new Request(url, { method: tool.method, headers, body: bodyText });\n toolRequests.add(request);\n return request;\n}\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\nasync function readBody(\n res: Response,\n): Promise<{ text: string; parsed: unknown; isJson: boolean }> {\n const text = await res.text();\n const type = (res.headers.get('content-type') ?? '').split(';')[0]!.trim().toLowerCase();\n const looksJson = type === 'application/json' || type.endsWith('+json');\n if (looksJson || (!type && text && /^[[{\"\\d\\-tfn]/.test(text.trimStart()))) {\n try {\n return { text, parsed: JSON.parse(text), isJson: true };\n } catch {\n /* fall through: treat as text */\n }\n }\n return { text, parsed: text, isJson: false };\n}\n\nexport async function toCallToolResult(tool: ToolSpec, res: Response): Promise<CallToolResult> {\n const { text, parsed, isJson } = await readBody(res);\n const display = isJson ? JSON.stringify(parsed) : text;\n\n if (!res.ok) {\n return {\n isError: true,\n content: [{ type: 'text', text: `HTTP ${res.status}${display ? `: ${display}` : ''}` }],\n };\n }\n\n const result: CallToolResult = { content: [{ type: 'text', text: display }] };\n if (tool.output) {\n if (tool.output.wrapped) result.structuredContent = { [WRAPPED_RESULT_KEY]: parsed };\n else if (isPlainObject(parsed)) result.structuredContent = parsed;\n else {\n // The advertised outputSchema requires an object; a result without one\n // would be rejected by spec-validating clients.\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: `Tool ${tool.name} declares an object output but the response (HTTP ${res.status}) was ${isJson ? 'JSON that is not an object' : 'not a JSON object'}${display ? `: ${display}` : ''}`,\n },\n ],\n };\n }\n }\n return result;\n}\n\n/**\n * Run one tool call through the app. `onToolCall` is awaited after the\n * result is built; it gets a clone of the response, so reading it does not\n * disturb the result. Errors it throws reach the caller (the plugin catches\n * and reports them).\n */\nexport async function callTool(\n app: Handler,\n tool: ToolSpec,\n args: Record<string, unknown>,\n original: Request,\n headerPolicy?: HeaderPolicy,\n onToolCall?: OnToolCall,\n): Promise<CallToolResult> {\n const request = buildToolRequest(tool, args, original, headerPolicy);\n const started = performance.now();\n const response = await app.handle(request);\n const durationMs = performance.now() - started;\n const copy = onToolCall ? response.clone() : undefined;\n const result = await toCallToolResult(tool, response);\n if (onToolCall) await onToolCall({ tool, args, request, response: copy!, durationMs });\n return result;\n}\n",
13
+ "/**\n * Schema plumbing: `$ref` resolution, flattening of path/query/body into one\n * MCP input schema (with per-property origin tracking), unflattening tool\n * arguments back into buckets, and response → `outputSchema` mapping.\n */\nimport type { McpifyWarning } from '../warnings.ts';\nimport type { JsonSchema, OpenAPIOperation, OpenAPIResponse } from './types.ts';\n\ntype Bucket = 'path' | 'query' | 'header' | 'body';\n\nexport interface PropertyOrigin {\n bucket: Bucket;\n /** Original property name inside its bucket. */\n name: string;\n}\n\nexport interface FlatSchema {\n /** MCP `inputSchema`: always `type: object`. */\n schema: JsonSchema & {\n type: 'object';\n properties: Record<string, JsonSchema>;\n required?: string[];\n };\n /** flat property name → where it came from. */\n origins: Record<string, PropertyOrigin>;\n /** Set when the request body is not an object and is exposed as one property. */\n rawBodyKey?: string;\n /** The messages of `diagnostics`. */\n warnings: string[];\n /** Derivation warnings, each tagged with its kind. */\n diagnostics: McpifyWarning[];\n}\n\nexport interface OutputSchema {\n schema: JsonSchema & { type: 'object' };\n /** True when a non-object response was wrapped as `{ result }`. */\n wrapped: boolean;\n}\n\nexport const WRAPPED_RESULT_KEY = 'result';\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\nfunction refName(ref: string): string {\n const idx = ref.lastIndexOf('/');\n return idx === -1 ? ref : ref.slice(idx + 1);\n}\n\nconst NESTED_MAPS = new Set(['properties', 'patternProperties', '$defs', 'definitions']);\nconst NESTED_SINGLE = new Set([\n 'items',\n 'additionalProperties',\n 'not',\n 'contains',\n 'propertyNames',\n]);\nconst NESTED_LISTS = new Set(['anyOf', 'oneOf', 'allOf', 'prefixItems']);\n\n/**\n * Inline every `$ref` (either `#/components/schemas/X` or a bare `X`, which\n * `@elysiajs/openapi` emits for array items). Cycles become an opaque object.\n */\n// eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\nexport function dereference(\n schema: JsonSchema | undefined,\n components: Record<string, JsonSchema>,\n stack: readonly string[] = [],\n): JsonSchema | undefined {\n if (!isObject(schema)) return schema;\n if (typeof schema.$ref === 'string') {\n const name = refName(schema.$ref);\n const target = components[name];\n const { $ref: _ref, ...siblings } = schema;\n if (!target) {\n return { ...siblings, description: siblings.description ?? `Unresolved reference ${name}` };\n }\n if (stack.includes(name)) {\n return { type: 'object', description: `Recursive reference to ${name}`, ...siblings };\n }\n return { ...dereference(target, components, [...stack, name]), ...siblings };\n }\n const out: JsonSchema = {};\n for (const [key, value] of Object.entries(schema)) {\n if (key === '$id') continue;\n if (NESTED_MAPS.has(key) && isObject(value)) {\n out[key] = Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, dereference(v as JsonSchema, components, stack)]),\n );\n } else if (NESTED_SINGLE.has(key)) {\n out[key] = Array.isArray(value)\n ? value.map((v) => dereference(v as JsonSchema, components, stack))\n : isObject(value)\n ? dereference(value, components, stack)\n : value;\n } else if (NESTED_LISTS.has(key) && Array.isArray(value)) {\n out[key] = value.map((v) => dereference(v as JsonSchema, components, stack));\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * Elysia's `t.Numeric()` becomes `anyOf: [{ type: 'string', format: 'numeric' }, { type: 'number' }]`.\n * Agents should just send a number, so collapse it to the numeric branch,\n * at any depth (properties, items, and union members).\n */\n// eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\nexport function simplifyNumeric(schema: JsonSchema): JsonSchema {\n if (!isObject(schema)) return schema;\n let out: JsonSchema = schema;\n for (const [key, value] of Object.entries(schema)) {\n let next: unknown = value;\n if (NESTED_MAPS.has(key) && isObject(value)) {\n next = Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, simplifyNumeric(v as JsonSchema)]),\n );\n } else if (NESTED_SINGLE.has(key)) {\n next = Array.isArray(value)\n ? value.map((v) => simplifyNumeric(v as JsonSchema))\n : isObject(value)\n ? simplifyNumeric(value)\n : value;\n } else if (NESTED_LISTS.has(key) && Array.isArray(value)) {\n next = value.map((v) => simplifyNumeric(v as JsonSchema));\n }\n if (next !== value) out = { ...out, [key]: next };\n }\n return collapseNumeric(out);\n}\n\nfunction collapseNumeric(schema: JsonSchema): JsonSchema {\n const anyOf = schema.anyOf;\n if (!Array.isArray(anyOf) || anyOf.length !== 2) return schema;\n const isNumericString = (s: unknown) =>\n isObject(s) && s.type === 'string' && s.format === 'numeric';\n const numberBranch: unknown = anyOf.find(\n (s) => isObject(s) && (s.type === 'number' || s.type === 'integer'),\n );\n if (!anyOf.some(isNumericString) || !isObject(numberBranch)) return schema;\n const { anyOf: _drop, ...rest } = schema;\n return { ...(numberBranch as JsonSchema), ...rest };\n}\n\n/**\n * `t.Nullable(t.String({ description }))` and `t.Optional(t.Union([X, t.Null()]))`\n * put the description on the member: `anyOf: [{ type: 'string', description }, { type: 'null' }]`.\n * Agents read the property's own description, so lift it from the only\n * non-null member when the property has none.\n */\nfunction hoistUnionDescription(schema: JsonSchema): JsonSchema {\n if (typeof schema.description === 'string' && schema.description) return schema;\n const members = Array.isArray(schema.anyOf)\n ? schema.anyOf\n : Array.isArray(schema.oneOf)\n ? schema.oneOf\n : undefined;\n if (!members) return schema;\n const nonNull = members.filter((m) => !(isObject(m) && m.type === 'null'));\n const only: unknown = nonNull.length === 1 ? nonNull[0] : undefined;\n if (!isObject(only) || typeof only.description !== 'string' || !only.description) return schema;\n return { ...schema, description: only.description };\n}\n\nconst isObjectSchema = (s: JsonSchema | undefined): s is JsonSchema =>\n isObject(s) && (s.type === 'object' || isObject(s.properties));\n\nconst isJsonMedia = (type: string) => {\n const base = type.split(';')[0]!.trim().toLowerCase();\n return base === 'application/json' || base.endsWith('+json');\n};\n\n/** The schema of the JSON media type, if the content has one. */\nfunction jsonSchemaOf(content: Record<string, { schema?: JsonSchema }> | undefined) {\n if (!content) return undefined;\n const json =\n content['application/json'] ?? Object.entries(content).find(([type]) => isJsonMedia(type))?.[1];\n return json?.schema;\n}\n\n/** True when a request body is declared but offers no JSON media type (multipart, form, binary). */\nexport function hasNonJsonBodyOnly(op: OpenAPIOperation): boolean {\n const types = Object.keys(op.requestBody?.content ?? {});\n return types.length > 0 && !types.some(isJsonMedia);\n}\n\nconst IGNORED_HEADER_PARAMS = new Set(['accept', 'content-type', 'authorization']);\n\n/**\n * Merge path params + query + body into one flat object schema. Path params\n * come first, then query, then header (only with `headerParams`), then body; a later bucket that collides with an\n * earlier property is renamed `${bucket}_${name}` and reported.\n */\n// eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\nexport function flattenOperation(\n toolName: string,\n op: OpenAPIOperation,\n components: Record<string, JsonSchema>,\n pathParams: readonly string[],\n options: { headerParams?: boolean } = {},\n): FlatSchema {\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n const origins: Record<string, PropertyOrigin> = {};\n const diagnostics: McpifyWarning[] = [];\n const missingDescription: string[] = [];\n const missingPathDescription: string[] = [];\n let rawBodyKey: string | undefined;\n\n const add = (bucket: Bucket, name: string, rawSchema: JsonSchema, isRequired: boolean) => {\n const schema = hoistUnionDescription(simplifyNumeric(rawSchema));\n let flat = name;\n if (flat in properties) {\n flat = `${bucket}_${name}`;\n diagnostics.push({\n kind: 'argument-collision',\n message: `[mcpify] tool \"${toolName}\": \"${name}\" exists in both ${origins[name]!.bucket} and ${bucket}; the ${bucket} one is exposed as \"${flat}\"`,\n });\n }\n properties[flat] = schema;\n origins[flat] = { bucket, name };\n if (isRequired) required.push(flat);\n if (!schema.description)\n (bucket === 'path' ? missingPathDescription : missingDescription).push(flat);\n return flat;\n };\n\n const params = (op.parameters ?? []).filter(isObject);\n const byPath = new Map(params.filter((p) => p.in === 'path').map((p) => [p.name, p]));\n for (const name of pathParams) {\n const p = byPath.get(name);\n const schema = dereference(p?.schema, components) ?? { type: 'string' };\n if (p?.description && !schema.description) schema.description = p.description;\n add('path', name, schema, true);\n }\n for (const p of byPath.values()) {\n if (!pathParams.includes(p.name)) {\n diagnostics.push({\n kind: 'stray-path-param',\n message: `[mcpify] tool \"${toolName}\": path parameter \"${p.name}\" is not in the path template and was ignored`,\n });\n }\n }\n\n for (const p of params) {\n if (p.in !== 'query') continue;\n const schema = dereference(p.schema, components) ?? { type: 'string' };\n if (p.description && !schema.description) schema.description = p.description;\n add('query', p.name, schema, p.required === true);\n }\n\n const headerParams = params.filter((p) => p.in === 'header');\n if (options.headerParams) {\n for (const p of headerParams) {\n // OpenAPI says these three header parameters are ignored; the call owns them.\n if (IGNORED_HEADER_PARAMS.has(p.name.toLowerCase())) continue;\n const schema = dereference(p.schema, components) ?? { type: 'string' };\n if (p.description && !schema.description) schema.description = p.description;\n add('header', p.name, schema, p.required === true);\n }\n }\n const requiredHeaders = options.headerParams ? [] : headerParams.filter((p) => p.required);\n if (requiredHeaders.length > 0) {\n diagnostics.push({\n kind: 'header-param',\n message: `[mcpify] tool \"${toolName}\": required header(s) ${requiredHeaders.map((h) => h.name).join(', ')} are not tool arguments; they must arrive on the MCP request itself`,\n });\n }\n\n const body = dereference(jsonSchemaOf(op.requestBody?.content), components);\n if (body) {\n const bodyRequired = op.requestBody?.required !== false;\n if (isObjectSchema(body)) {\n const req = new Set(bodyRequired ? (body.required ?? []) : []);\n for (const [name, schema] of Object.entries(body.properties ?? {})) {\n add('body', name, schema, req.has(name));\n }\n } else {\n rawBodyKey = add('body', 'body', body, bodyRequired);\n }\n }\n\n if (missingPathDescription.length > 0) {\n diagnostics.push({\n kind: 'path-param-description',\n message: `[mcpify] tool \"${toolName}\": no description for path parameter ${missingPathDescription.join(', ')} — agents pick arguments better with one`,\n });\n }\n if (missingDescription.length > 0) {\n diagnostics.push({\n kind: 'argument-description',\n message: `[mcpify] tool \"${toolName}\": no description for ${missingDescription.join(', ')} — agents pick arguments better with one`,\n });\n }\n\n const schema: FlatSchema['schema'] = { type: 'object', properties };\n if (required.length > 0) schema.required = required;\n return { schema, origins, rawBodyKey, warnings: diagnostics.map((d) => d.message), diagnostics };\n}\n\nexport interface UnflattenedArgs {\n params: Record<string, unknown>;\n query: Record<string, unknown>;\n headers: Record<string, unknown>;\n body: unknown;\n}\n\n/** Split flat tool arguments back into path / query / header / body buckets. */\nexport function unflattenArgs(args: Record<string, unknown>, flat: FlatSchema): UnflattenedArgs {\n const params: Record<string, unknown> = {};\n const query: Record<string, unknown> = {};\n const headers: Record<string, unknown> = {};\n let body: Record<string, unknown> | undefined;\n let rawBody: unknown;\n let hasRawBody = false;\n\n for (const [key, value] of Object.entries(args)) {\n const origin = flat.origins[key];\n if (!origin) continue;\n if (flat.rawBodyKey === key) {\n rawBody = value;\n hasRawBody = true;\n continue;\n }\n if (origin.bucket === 'path') params[origin.name] = value;\n else if (origin.bucket === 'query') query[origin.name] = value;\n else if (origin.bucket === 'header') headers[origin.name] = value;\n else (body ??= {})[origin.name] = value;\n }\n return { params, query, headers, body: hasRawBody ? rawBody : body };\n}\n\nconst isSuccessKey = (k: string) => /^2(\\d\\d|xx)$/i.test(k);\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (Array.isArray(a)) {\n return Array.isArray(b) && a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));\n }\n if (isObject(a) && isObject(b)) {\n const keys = Object.keys(a);\n return (\n keys.length === Object.keys(b).length && keys.every((k) => k in b && deepEqual(a[k], b[k]))\n );\n }\n return false;\n}\n\n/**\n * Map the success response schema to an MCP `outputSchema`. An output schema\n * promises `structuredContent` on every success, so one is emitted only when\n * every declared 2xx response has JSON content and they all share one schema;\n * otherwise `report` is told why and none is emitted. MCP requires\n * `type: object`; a non-object response is wrapped as `{ result }` when\n * `wrapNonObject` is set, otherwise no output schema is emitted.\n */\nexport function outputSchemaFor(\n op: OpenAPIOperation,\n components: Record<string, JsonSchema>,\n wrapNonObject: boolean,\n report?: (reason: string) => void,\n): OutputSchema | undefined {\n const responses = op.responses ?? {};\n let keys = Object.keys(responses).filter(isSuccessKey);\n if (keys.length === 0 && 'default' in responses) keys = ['default'];\n const schemas = keys.map((key) => {\n const res = responses[key];\n const content = isObject(res) ? (res as OpenAPIResponse).content : undefined;\n // Elysia documents `t.String()` responses as text/plain; a plain-text body\n // always fits the wrapped `{ result }` shape, so it counts as content.\n return dereference(jsonSchemaOf(content) ?? content?.['text/plain']?.schema, components);\n });\n const present = schemas.filter((s) => s !== undefined);\n if (present.length === 0) return undefined;\n const schema = present[0]!;\n if (present.length !== schemas.length || !present.every((s) => deepEqual(s, schema))) {\n report?.(\n `the 2xx responses (${keys.join(', ')}) do not all declare JSON content with the same schema`,\n );\n return undefined;\n }\n return toOutputSchema(schema, wrapNonObject);\n}\n\n/**\n * A response schema as an MCP `outputSchema`, which must be `type: object`:\n * an object schema is used as is, anything else is wrapped as `{ result }`\n * when `wrapNonObject` is set (and gives none otherwise).\n */\nexport function toOutputSchema(\n schema: JsonSchema,\n wrapNonObject: boolean,\n): OutputSchema | undefined {\n if (isObjectSchema(schema)) return { schema: { ...schema, type: 'object' }, wrapped: false };\n if (!wrapNonObject) return undefined;\n return {\n schema: {\n type: 'object',\n properties: { [WRAPPED_RESULT_KEY]: schema },\n required: [WRAPPED_RESULT_KEY],\n },\n wrapped: true,\n };\n}\n",
14
+ "/**\n * Tool-name derivation from method + path, and reproduction of the\n * `operationId` that `@elysiajs/openapi` auto-generates (so we can tell an\n * explicit `detail.operationId` from a default one).\n */\n\nconst METHOD_VERB: Record<string, string> = {\n POST: 'create',\n PUT: 'update',\n PATCH: 'update',\n DELETE: 'delete',\n};\n\n/** `{id}`, `:id`, `:id?` and `*` are all path parameters. */\nfunction isParamSegment(segment: string): boolean {\n return segment.startsWith('{') || segment.startsWith(':') || segment === '*' || segment === '**';\n}\n\n/** Names of the `{param}` placeholders in an OpenAPI path template, in order. */\nexport function templateParams(path: string): string[] {\n const out: string[] = [];\n for (const m of path.matchAll(/\\{([^}]+)\\}/g)) out.push(m[1]!);\n return out;\n}\n\nfunction toSnake(word: string): string {\n return word\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .toLowerCase()\n .replace(/^_+|_+$/g, '');\n}\n\n/** Good-enough English singularisation for resource names. */\nfunction singular(word: string): string {\n if (word.length <= 2) return word;\n if (/(ss|us|is|ews)$/.test(word)) return word;\n if (word.endsWith('ies') && word.length > 3) return word.slice(0, -3) + 'y';\n if (/(sses|shes|ches|xes|zes)$/.test(word)) return word.slice(0, -2);\n if (word.endsWith('s')) return word.slice(0, -1);\n return word;\n}\n\n/** MCP tool names must match `^[a-zA-Z0-9_-]{1,64}$`. */\nexport function sanitizeToolName(name: string): string {\n const cleaned = name\n .replace(/[^A-Za-z0-9_-]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_+|_+$/g, '');\n return (cleaned || 'tool').slice(0, 64);\n}\n\n/**\n * `GET /users` → `list_users`, `GET /users/{id}` → `get_user`,\n * `POST /users` → `create_user`, `GET /users/{uid}/posts` → `list_user_posts`.\n * Leading `api` / `v1`-style prefixes are dropped.\n */\n// eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\nexport function deriveToolName(method: string, path: string): string {\n const verbMethod = method.toUpperCase();\n const segments = path.split('/').filter(Boolean);\n\n let start = 0;\n while (\n start < segments.length &&\n !isParamSegment(segments[start]!) &&\n /^(api|v\\d+)$/i.test(segments[start]!)\n ) {\n start++;\n }\n\n const words: string[] = [];\n let trailingParam = false;\n for (let i = start; i < segments.length; i++) {\n const seg = segments[i]!;\n if (isParamSegment(seg)) {\n trailingParam = i === segments.length - 1;\n continue;\n }\n const next = segments[i + 1];\n let word = toSnake(seg);\n if (next !== undefined && isParamSegment(next)) word = singular(word);\n if (word) words.push(word);\n }\n\n let verb: string;\n if (verbMethod === 'GET') verb = trailingParam ? 'get' : 'list';\n else verb = METHOD_VERB[verbMethod] ?? verbMethod.toLowerCase();\n\n if (verbMethod !== 'GET' && !trailingParam && words.length > 0) {\n words[words.length - 1] = singular(words[words.length - 1]!);\n }\n\n const resource = words.length > 0 ? words.join('_') : 'root';\n return sanitizeToolName(`${verb}_${resource}`);\n}\n\nconst capitalize = (word: string) => word.charAt(0).toUpperCase() + word.slice(1);\n\n/**\n * Reproduces `@elysiajs/openapi`'s default `operationId` (`getUsersById`) so a\n * default can be told apart from one the developer wrote in `detail.operationId`.\n */\nexport function elysiaDefaultOperationId(method: string, openapiPath: string): string {\n const path = openapiPath.replace(/\\{([^}]+)\\}/g, ':$1');\n let id = method.toLowerCase();\n if (!path || path === '/') return id + 'Index';\n for (const seg of path.split('/')) {\n id += seg.includes(':') ? 'By' + capitalize(seg.replace(':', '')) : capitalize(seg);\n }\n return id.replace(/\\?/g, 'Optional');\n}\n",
15
+ "/**\n * Minimal OpenAPI 3.x / JSON Schema shapes — just what tool derivation reads.\n * Deliberately loose: the document is produced by `@elysiajs/openapi` and we\n * only need to walk it, not validate it.\n */\n\nexport interface JsonSchema {\n type?: string | string[];\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema | JsonSchema[];\n description?: string;\n $ref?: string;\n [key: string]: unknown;\n}\n\nexport interface OpenAPIParameter {\n name: string;\n in: 'path' | 'query' | 'header' | 'cookie' | string;\n required?: boolean;\n description?: string;\n schema?: JsonSchema;\n}\n\ninterface OpenAPIMediaType {\n schema?: JsonSchema;\n}\n\ninterface OpenAPIRequestBody {\n required?: boolean;\n description?: string;\n content?: Record<string, OpenAPIMediaType>;\n}\n\nexport interface OpenAPIResponse {\n description?: string;\n content?: Record<string, OpenAPIMediaType>;\n}\n\n/** The object form of `detail.mcp`; it opts the route in like `true`. */\nexport interface McpRouteOptions {\n /** Scopes a token must hold to call this tool, on top of `auth.scopes` (403 `insufficient_scope` otherwise). */\n scopes?: string[];\n /** Callable without a token when `auth.allowAnonymous` is set. */\n public?: boolean;\n /**\n * JSON Schema of the tool's result, advertised as its `outputSchema` in\n * place of the one derived from the route's `response`. Unlike `response`,\n * Elysia does not check answers against it: it documents the result for\n * agents only. A non-object schema is wrapped as `{ result }` (see\n * `wrapNonObjectOutput`). A TypeBox `t.Object(...)` works too.\n */\n output?: JsonSchema;\n}\n\nexport interface OpenAPIOperation {\n operationId?: string;\n summary?: string;\n description?: string;\n tags?: string[];\n deprecated?: boolean;\n parameters?: OpenAPIParameter[];\n requestBody?: OpenAPIRequestBody;\n responses?: Record<string, OpenAPIResponse>;\n /** `@elysiajs/openapi` passes `detail.*` through verbatim, so these land here. */\n hide?: boolean;\n mcp?: boolean | McpRouteOptions;\n [key: string]: unknown;\n}\n\nexport interface OpenAPIDocument {\n openapi?: string;\n info?: { title?: string; version?: string; description?: string };\n /** Loose on purpose: accepts `toOpenAPISchema()` output and `openapi-types` documents alike. */\n paths?: Record<string, unknown>;\n components?: { schemas?: Record<string, JsonSchema> };\n}\n\nexport const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete'] as const;\n\nexport function isOperation(value: unknown): value is OpenAPIOperation {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n",
16
+ "/**\n * OpenAPI document → MCP tool specs. The document is the single source of\n * truth: nothing here touches Elysia route internals.\n */\nimport type { Tool } from '@modelcontextprotocol/server';\nimport type { McpifyWarning } from '../warnings.ts';\nimport {\n deriveToolName,\n elysiaDefaultOperationId,\n sanitizeToolName,\n templateParams,\n} from './naming.ts';\nimport {\n dereference,\n flattenOperation,\n hasNonJsonBodyOnly,\n outputSchemaFor,\n toOutputSchema,\n type FlatSchema,\n type OutputSchema,\n} from './schema.ts';\nimport {\n HTTP_METHODS,\n isOperation,\n type JsonSchema,\n type OpenAPIDocument,\n type OpenAPIOperation,\n} from './types.ts';\n\nexport interface ToolSpec {\n name: string;\n title?: string;\n description: string;\n /** Upper-case HTTP method. */\n method: string;\n /** OpenAPI path template, e.g. `/users/{id}`. */\n path: string;\n flat: FlatSchema;\n output?: OutputSchema;\n tags: string[];\n annotations: NonNullable<Tool['annotations']>;\n /** Scopes a token must hold to call this tool (from `detail.mcp.scopes`). */\n scopes: string[];\n /** Callable without a token when anonymous access is enabled (`detail.mcp.public`). */\n public: boolean;\n}\n\nexport interface DeriveOptions {\n /** Expose every operation unless `mcp: false` (true) or only `mcp: true` ones (false). */\n allRoutes: boolean;\n /** Keep only operations carrying at least one of these tags. */\n tags?: string[];\n /** Wrap non-object responses as `{ result }` so they still get an `outputSchema`. */\n wrapNonObjectOutput: boolean;\n /** Expose OpenAPI `in: 'header'` parameters as tool arguments. Default false. */\n headerParams?: boolean;\n /** OpenAPI paths that must never become tools (exact string or RegExp). */\n exclude?: readonly (string | RegExp)[];\n /**\n * Path prefixes dropped before deriving a fallback name, so routes mounted\n * under the MCP endpoint itself (`/mcp/expenses`) become `list_expenses`.\n */\n stripPrefixes?: readonly string[];\n}\n\n/**\n * Paths excluded by default: OAuth / discovery endpoints. An MCP tool that\n * calls `/token` is exactly what the resource-server model forbids.\n */\nexport const DEFAULT_EXCLUDED_PATHS: readonly (string | RegExp)[] = [\n /^\\/\\.well-known(\\/|$)/,\n '/authorize',\n '/token',\n '/register',\n '/revoke',\n '/introspect',\n '/userinfo',\n];\n\nexport function isExcluded(path: string, exclude: readonly (string | RegExp)[]): boolean {\n return exclude.some((rule) => (typeof rule === 'string' ? rule === path : rule.test(path)));\n}\n\nexport interface DeriveResult {\n tools: ToolSpec[];\n /** The messages of `diagnostics`. */\n warnings: string[];\n /** Each warning tagged with its kind. */\n diagnostics: McpifyWarning[];\n}\n\nfunction annotationsFor(method: string, summary?: string): ToolSpec['annotations'] {\n const base: ToolSpec['annotations'] = summary ? { title: summary } : {};\n switch (method) {\n case 'GET':\n return { ...base, readOnlyHint: true, idempotentHint: true, destructiveHint: false };\n case 'PUT':\n return { ...base, readOnlyHint: false, idempotentHint: true, destructiveHint: false };\n case 'PATCH':\n return { ...base, readOnlyHint: false, idempotentHint: false, destructiveHint: false };\n case 'DELETE':\n return { ...base, readOnlyHint: false, idempotentHint: true, destructiveHint: true };\n default:\n return { ...base, readOnlyHint: false };\n }\n}\n\nfunction describe(op: OpenAPIOperation, method: string, path: string): string {\n const summary = op.summary?.trim();\n const description = op.description?.trim();\n if (summary && description && summary !== description) return `${summary}\\n\\n${description}`;\n return summary || description || `${method} ${path}`;\n}\n\nfunction stripPrefix(path: string, prefixes: readonly string[]): string {\n for (const raw of prefixes) {\n const prefix = raw.replace(/\\/+$/, '');\n if (prefix && path.startsWith(`${prefix}/`)) return path.slice(prefix.length);\n }\n return path;\n}\n\n/** Explicit `detail.operationId` wins; the auto-generated one is ignored. */\nexport function toolNameFor(\n op: OpenAPIOperation,\n method: string,\n path: string,\n stripPrefixes: readonly string[] = [],\n): string {\n const id = op.operationId;\n if (typeof id === 'string' && id.trim() && id !== elysiaDefaultOperationId(method, path)) {\n return sanitizeToolName(id);\n }\n return deriveToolName(method, stripPrefix(path, stripPrefixes));\n}\n\n/** Read the object form of `detail.mcp`; malformed fields are dropped with a warning. */\nfunction routeOptions(\n mcp: OpenAPIOperation['mcp'],\n where: string,\n warn: (w: McpifyWarning) => void,\n): { scopes: string[]; public: boolean; output?: JsonSchema } {\n if (typeof mcp !== 'object' || mcp === null) return { scopes: [], public: false };\n const o = mcp;\n let scopes: string[] = [];\n if (o.scopes !== undefined) {\n // RFC 6749 §3.3 scope-token: printable ASCII except space, `\"` and `\\`.\n const valid = (s: unknown) => typeof s === 'string' && /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/.test(s);\n if (Array.isArray(o.scopes) && o.scopes.every(valid)) {\n scopes = [...new Set(o.scopes)];\n } else {\n warn({\n kind: 'invalid-scopes',\n message: `[mcpify] ${where}: detail.mcp.scopes must be an array of OAuth scope tokens; ignored`,\n });\n }\n }\n let output: JsonSchema | undefined;\n if (o.output !== undefined) {\n if (typeof o.output === 'object' && o.output !== null && !Array.isArray(o.output)) {\n output = o.output;\n } else {\n warn({\n kind: 'no-output-schema',\n message: `[mcpify] ${where}: detail.mcp.output must be a JSON Schema object; ignored`,\n });\n }\n }\n return { scopes, public: o.public === true, ...(output ? { output } : {}) };\n}\n\n// eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\nexport function deriveTools(doc: OpenAPIDocument, o: DeriveOptions): DeriveResult {\n const tools: ToolSpec[] = [];\n const warnings: McpifyWarning[] = [];\n const components = doc.components?.schemas ?? {};\n const seen = new Map<string, number>();\n const exclude = o.exclude ?? DEFAULT_EXCLUDED_PATHS;\n\n for (const [path, item] of Object.entries(doc.paths ?? {})) {\n if (!isOperation(item) || isExcluded(path, exclude)) continue;\n for (const method of HTTP_METHODS) {\n const op = item[method];\n if (!isOperation(op)) continue;\n if (op.hide === true || op.mcp === false) continue;\n const optedIn = op.mcp === true || (typeof op.mcp === 'object' && op.mcp !== null);\n if (!o.allRoutes && !optedIn) continue;\n const tags = Array.isArray(op.tags) ? op.tags.filter((t) => typeof t === 'string') : [];\n if (o.tags && !tags.some((t) => o.tags!.includes(t))) continue;\n\n const METHOD = method.toUpperCase();\n if (hasNonJsonBodyOnly(op)) {\n warnings.push({\n kind: 'non-json-body',\n message: `[mcpify] skipped ${METHOD} ${path}: its request body has no JSON media type (${Object.keys(op.requestBody!.content!).join(', ')}), which tools cannot send`,\n });\n continue;\n }\n let name = toolNameFor(op, METHOD, path, o.stripPrefixes ?? []);\n const count = seen.get(name) ?? 0;\n seen.set(name, count + 1);\n if (count > 0) {\n const renamed = sanitizeToolName(`${name}_${count + 1}`);\n warnings.push({\n kind: 'duplicate-name',\n message: `[mcpify] duplicate tool name \"${name}\" (${METHOD} ${path}) — exposed as \"${renamed}\"; set detail.operationId to pick names explicitly`,\n });\n name = renamed;\n }\n\n const flat = flattenOperation(name, op, components, templateParams(path), {\n headerParams: o.headerParams,\n });\n warnings.push(...flat.diagnostics);\n const { output: declared, ...access } = routeOptions(op.mcp, `tool \"${name}\"`, (m) =>\n warnings.push(m),\n );\n const report = (reason: string) =>\n warnings.push({\n kind: 'no-output-schema',\n message: `[mcpify] tool \"${name}\": no outputSchema emitted; ${reason}`,\n });\n let output: OutputSchema | undefined;\n if (declared) {\n // `detail.mcp.output` wins over the response schema and is not enforced.\n output = toOutputSchema(dereference(declared, components)!, o.wrapNonObjectOutput);\n if (!output)\n report('detail.mcp.output is not an object schema and wrapNonObjectOutput is off');\n } else {\n output = outputSchemaFor(op, components, o.wrapNonObjectOutput, report);\n }\n\n tools.push({\n name,\n title: op.summary?.trim() || undefined,\n description: describe(op, METHOD, path),\n method: METHOD,\n path,\n flat,\n output,\n tags,\n annotations: annotationsFor(METHOD, op.summary?.trim() || undefined),\n ...access,\n });\n }\n }\n\n if (tools.length === 0) {\n warnings.push({\n kind: 'no-tools',\n message:\n '[mcpify] no MCP-eligible operations found in the OpenAPI document — tools/list is empty',\n });\n }\n return { tools, warnings: warnings.map((w) => w.message), diagnostics: warnings };\n}\n\n/** The wire representation for `tools/list`. */\nexport function toMcpTool(spec: ToolSpec): Tool {\n const tool: Tool = {\n name: spec.name,\n description: spec.description,\n // Our JsonSchema is open-ended; the SDK types schemas as JSON values.\n inputSchema: spec.flat.schema as Tool['inputSchema'],\n annotations: spec.annotations,\n };\n if (spec.title) tool.title = spec.title;\n if (spec.output) tool.outputSchema = spec.output.schema;\n return tool;\n}\n",
17
+ "/**\n * Stateless Streamable HTTP, both protocol eras. 2026-07-28 (per-request\n * envelope) traffic goes to the SDK's `createMcpHandler`; 2025-era traffic to\n * a session-less transport answering plain JSON (the handler's own legacy leg\n * always streams SSE). Every request gets a fresh server, which is what makes\n * `tools/call` see the calling request's headers.\n */\nimport {\n createMcpHandler,\n isLegacyRequest,\n McpServer,\n ProtocolError,\n ProtocolErrorCode,\n type AuthInfo,\n type Tool,\n WebStandardStreamableHTTPServerTransport,\n} from '@modelcontextprotocol/server';\nimport { callTool, type Handler, type HeaderPolicy, type OnToolCall } from './execute.ts';\nimport type { ToolSpec } from './openapi/derive.ts';\n\nexport interface ToolSet {\n list: Tool[];\n byName: Map<string, ToolSpec>;\n}\n\nexport interface ServeOptions {\n request: Request;\n app: Handler;\n tools: ToolSet;\n serverInfo: { name: string; version: string };\n instructions?: string | undefined;\n headerPolicy?: HeaderPolicy;\n authInfo?: AuthInfo;\n /** The JSON body, when something upstream already consumed the request stream. */\n parsedBody?: unknown;\n /** Called after each tool call that reached the app. */\n onToolCall?: OnToolCall | undefined;\n}\n\nfunction createServer(o: ServeOptions): McpServer {\n const mcp = new McpServer(o.serverInfo, {\n capabilities: { tools: {} },\n ...(o.instructions === undefined ? {} : { instructions: o.instructions }),\n });\n // Tools carry pre-built JSON Schema and arguments are validated by the\n // route itself, so serve the list and the calls at the protocol level.\n mcp.server.setRequestHandler('tools/list', () => ({ tools: o.tools.list }));\n mcp.server.setRequestHandler('tools/call', async (req) => {\n const tool = o.tools.byName.get(req.params.name);\n if (!tool) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${req.params.name} not found`);\n }\n const result = await callTool(\n o.app,\n tool,\n req.params.arguments ?? {},\n o.request,\n o.headerPolicy,\n o.onToolCall,\n );\n return mcp.server.projectCallToolResult(result, tool.output?.schema);\n });\n return mcp;\n}\n\nasync function serveLegacy(o: ServeOptions): Promise<Response> {\n const mcp = createServer(o);\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n await mcp.connect(transport);\n try {\n return await transport.handleRequest(o.request, {\n authInfo: o.authInfo,\n parsedBody: o.parsedBody,\n });\n } finally {\n await transport.close();\n }\n}\n\nasync function serveModern(o: ServeOptions): Promise<Response> {\n // Nothing is emitted mid-call, so `auto` answers every call with one JSON body.\n const handler = createMcpHandler(() => createServer(o), { legacy: 'reject' });\n let response: Response;\n try {\n response = await handler.fetch(o.request, {\n ...(o.authInfo === undefined ? {} : { authInfo: o.authInfo }),\n ...(o.parsedBody === undefined ? {} : { parsedBody: o.parsedBody }),\n });\n } catch (e) {\n await handler.close();\n throw e;\n }\n // A stream stays open until the client leaves; buffered responses are done.\n if (!response.headers.get('content-type')?.startsWith('text/event-stream')) {\n await handler.close();\n }\n return response;\n}\n\nexport async function serveMcp(o: ServeOptions): Promise<Response> {\n return (await isLegacyRequest(o.request, o.parsedBody)) ? serveLegacy(o) : serveModern(o);\n}\n",
18
+ "/**\n * Every message the plugin sends to `warn` carries one of these kinds, so a\n * caller can silence one kind (`warnings: { kind: false }`) or route kinds\n * differently in its own `warn` without matching on the text.\n */\nexport const MCPIFY_WARNING_KINDS = [\n /** Startup banner: the endpoint is mounted with `unsafeNoAuth: true`. */\n 'unauthenticated',\n /** A path parameter without a description. */\n 'path-param-description',\n /** A query / header / body argument without a description. */\n 'argument-description',\n /** The same argument name in more than one of path / query / header / body. */\n 'argument-collision',\n /** Two operations derive the same tool name; the later one is suffixed. */\n 'duplicate-name',\n /** A declared path parameter that is not in the path template. */\n 'stray-path-param',\n /** A required header parameter that is not a tool argument (no `headerParams`). */\n 'header-param',\n /** An operation skipped because its request body has no JSON media type. */\n 'non-json-body',\n /** A tool without an `outputSchema` (2xx responses differ or are not JSON). */\n 'no-output-schema',\n /** `detail.mcp.scopes` that is not a list of OAuth scope tokens. */\n 'invalid-scopes',\n /**\n * `detail.mcp.scopes` set while nothing enforces it: at startup with\n * `unsafeNoAuth`, or in request mode once `verify` admits a request without\n * returning `{ scopes }`.\n */\n 'scopes-not-enforced',\n /** A tool left out because `auth.requireToolScopes` is set and it declares no scopes / public. */\n 'tool-hidden',\n /** The document yielded no tools. */\n 'no-tools',\n /** The OpenAPI document could not be loaded (the client got a 500). */\n 'document',\n /** `auth.verify(request)` threw or returned a malformed result (the client got a 401). */\n 'verify-error',\n /** `onToolCall` threw or rejected (the tool call itself still answered). */\n 'on-tool-call-error',\n /** `cors: true` set explicitly in request mode: any site may call the endpoint from a browser. */\n 'cors-reflects-origin',\n] as const;\n\nexport type McpifyWarningKind = (typeof MCPIFY_WARNING_KINDS)[number];\n\nexport interface McpifyWarning {\n kind: McpifyWarningKind;\n message: string;\n}\n\n/** Validate `warnings` and return the set of silenced kinds. */\nexport function silencedKinds(\n option: Partial<Record<McpifyWarningKind, boolean>> | undefined,\n): Set<McpifyWarningKind> {\n const off = new Set<McpifyWarningKind>();\n for (const [kind, on] of Object.entries(option ?? {})) {\n if (!(MCPIFY_WARNING_KINDS as readonly string[]).includes(kind)) {\n throw new TypeError(\n `[mcpify] unknown warning kind \"${kind}\" in \\`warnings\\`; known: ${MCPIFY_WARNING_KINDS.join(', ')}`,\n );\n }\n if (!on) off.add(kind as McpifyWarningKind);\n }\n return off;\n}\n",
19
+ "/**\n * `mcpify()` — mount an MCP server on an Elysia app, deriving tools from the\n * OpenAPI document `@elysiajs/openapi` generates, and enforcing the MCP\n * authorization spec's resource-server obligations.\n */\nimport type { toOpenAPISchema } from '@elysiajs/openapi';\nimport type { AnyElysia, Elysia } from 'elysia';\nimport { checkAccess, holdsToolScopes } from './auth/access.ts';\nimport { authenticate, NO_STORE } from './auth/authenticate.ts';\nimport { protectedResourceMetadata } from './auth/prm.ts';\nimport {\n isRequestAuth,\n resolveAuth,\n type McpifyAuthOptions,\n type McpifyRequestAuthOptions,\n type RequestAuthAdmission,\n type ResolvedAuth,\n} from './auth/resolve.ts';\nimport { defaultHeaderPolicy, type HeaderPolicy, type OnToolCall } from './execute.ts';\nimport { DEFAULT_EXCLUDED_PATHS, deriveTools, toMcpTool, type ToolSpec } from './openapi/derive.ts';\nimport type { McpRouteOptions, OpenAPIDocument } from './openapi/types.ts';\nimport { serveMcp, type ToolSet } from './transport.ts';\nimport { silencedKinds, type McpifyWarning, type McpifyWarningKind } from './warnings.ts';\n\ndeclare module 'elysia' {\n interface DocumentDecoration {\n /**\n * `false` hides the route from MCP; with `allRoutes: false`, `true` opts\n * it in. The object form opts in too and sets per-tool access:\n * `{ scopes: ['users:write'] }`, `{ public: true }`.\n */\n mcp?: boolean | McpRouteOptions;\n }\n}\n\nexport interface McpifyBaseOptions {\n /** Where the MCP endpoint lives. Default `/mcp`. */\n path?: string;\n /**\n * MCP server name / version reported on `initialize`. Default: the\n * OpenAPI document's `info.title` / `info.version` (as set with\n * `openapi({ documentation: { info } })`), else `@20baht/elysia-openapi-mcp` / `1.0.0`.\n */\n name?: string;\n version?: string;\n /**\n * Returned in the `initialize` result: how to use the tools as a whole\n * (when to call which, what to ask the user first). Clients typically put\n * it in the model's context for the session.\n */\n instructions?: string;\n /**\n * Expose every operation unless `detail.mcp === false` (default true);\n * `false` requires `detail.mcp: true`. With the default, a tool that declares\n * no `detail.mcp.scopes` is callable by any token valid for the resource; see\n * `auth.requireToolScopes`.\n */\n allRoutes?: boolean;\n /** Only expose operations carrying one of these OpenAPI tags. */\n tags?: string[];\n /**\n * OpenAPI paths that never become tools (exact string or RegExp). Added to\n * `DEFAULT_EXCLUDED_PATHS` (OAuth + `.well-known` endpoints) unless\n * `excludeDefaults` is false; the MCP endpoint and the PRM path are always\n * excluded.\n */\n exclude?: (string | RegExp)[];\n /** Keep `DEFAULT_EXCLUDED_PATHS` in the exclusion list. Default true. */\n excludeDefaults?: boolean;\n /**\n * Expose OpenAPI `in: 'header'` parameters as tool arguments, sent as\n * request headers (overriding forwarded ones). Default false: they stay\n * unexposed and a warning is printed for required ones.\n */\n headerParams?: boolean;\n /**\n * Where `@elysiajs/openapi` serves the JSON document. It is fetched\n * in-process through `app.handle()` on the first MCP request and re-read\n * whenever routes are added. When that route exists but does not answer\n * with a document (it is guarded, say), the document is built in-process\n * with `toOpenAPISchema(app)` instead, without the `openapi()` plugin's own\n * options (`documentation`, `exclude`, `references`, `mapJsonSchema`).\n * Default `/openapi/json`.\n */\n specPath?: string;\n /**\n * Bypass `specPath`: a document, or a function producing one. The function\n * receives the app the plugin is mounted on, so\n * `({ app }) => toOpenAPISchema(app)` from `@elysiajs/openapi` builds the\n * document in-process even when the OpenAPI routes are disabled.\n */\n document?:\n | OpenAPIDocument\n | ((ctx: { origin: string; app: AnyElysia }) => OpenAPIDocument | Promise<OpenAPIDocument>);\n /** Wrap non-object responses as `{ result }` so they still get an `outputSchema`. Default true. */\n wrapNonObjectOutput?: boolean;\n /** Which incoming MCP request headers reach the synthetic request. Default: all but hop-by-hop and transport headers. */\n headers?: HeaderPolicy;\n /**\n * CORS on the MCP + metadata endpoints. `true` reflects any `Origin` and\n * answers preflight; `{ origins }` does so only for listed origins (exact\n * strings, or a predicate) and sends no `Access-Control-Allow-Origin` for any\n * other; `false` sends no CORS headers. Default `false` in request mode\n * (`auth: { verify }`, which may trust cookies) and `true` otherwise (bearer\n * tokens are not sent by browsers on their own).\n */\n cors?: McpifyCorsOption;\n /**\n * Called after every `tools/call` that reached the app, with the tool, its\n * arguments, the synthetic request, a copy of the response and the time the\n * app took: an audit log, metrics. It is awaited before the client gets the\n * result; a throw is reported as `on-tool-call-error` and does not fail the\n * call. Calls refused before the app (unknown tool, bad arguments, auth)\n * are not reported. See also `isToolCall(request)`.\n */\n onToolCall?: OnToolCall;\n /**\n * Where warnings go, with their kind. Default `console.warn(message)`, each\n * distinct message once per process (across every mounted instance); a\n * custom `warn` gets each message once per instance.\n */\n warn?: (message: string, kind: McpifyWarningKind) => void;\n /**\n * Per-kind switch for warnings: `{ 'path-param-description': false }`\n * silences that kind only. Every kind is on by default; an unknown kind\n * throws.\n */\n warnings?: Partial<Record<McpifyWarningKind, boolean>>;\n}\n\n/**\n * Exactly one of the two is required, so an endpoint never ends up open by\n * forgetting `auth`.\n */\nexport type McpifyAuthMode =\n | {\n /**\n * `{ resource, authorizationServers, ... }`: OAuth 2.1 resource server,\n * every MCP request needs a valid access token.\n * `{ verify(request) }`: request mode, for API-key or cookie-guarded\n * apps; `true` or an admission (`{ scopes, tools, readOnly }`, which\n * filters the tools) lets a request reach the endpoint, a refusal\n * (`{ status, message }`) answers with that error, anything else gets a\n * bare `401` with no OAuth challenge.\n */\n auth: McpifyAuthOptions | McpifyRequestAuthOptions;\n unsafeNoAuth?: never;\n }\n | {\n auth?: never;\n /**\n * Mount the endpoint with no authorization at all: anyone who can reach\n * it can call every exposed route. Local development only.\n */\n unsafeNoAuth: true;\n };\n\nexport type McpifyOptions = McpifyBaseOptions & McpifyAuthMode;\n\n/** See `McpifyBaseOptions.cors`. */\nexport type McpifyCorsOption =\n | boolean\n | {\n /** Exact origins (`https://app.example`), or a predicate on the request's `Origin`. */\n origins: string[] | ((origin: string) => boolean);\n };\n\nexport const DEFAULT_SPEC_PATH = '/openapi/json';\n\nconst UNAUTHENTICATED_WARNING = `\n[mcpify] ┌──────────────────────────────────────────────────────────────────┐\n[mcpify] │ WARNING: MCP endpoint mounted WITHOUT authorization. │\n[mcpify] │ unsafeNoAuth: any client that can reach it can list the tools, │\n[mcpify] │ and calls are guarded only by your routes. Pass │\n[mcpify] │ \\`auth: { verify }\\` or \\`auth: { resource, authorizationServers }\\`│\n[mcpify] │ instead; \\`warnings: { unauthenticated: false }\\` hushes this. │\n[mcpify] └──────────────────────────────────────────────────────────────────┘`;\n\n/** Which origins get CORS headers; `null` means none. */\ntype OriginPolicy = ((origin: string) => boolean) | null;\n\nfunction originPolicy(option: McpifyCorsOption): OriginPolicy {\n if (option === true) return () => true;\n if (option === false) return null;\n if (typeof option !== 'object' || option === null) {\n throw new TypeError('[mcpify] cors must be a boolean or { origins }');\n }\n const { origins } = option;\n if (typeof origins === 'function') {\n return (origin) => {\n try {\n return origins(origin);\n } catch {\n return false;\n }\n };\n }\n if (!Array.isArray(origins) || !origins.every((o) => typeof o === 'string')) {\n throw new TypeError('[mcpify] cors.origins must be an array of origins or a predicate');\n }\n // `https://App.example/` and `https://app.example` are the same origin.\n const normalize = (o: string) => {\n try {\n return new URL(o).origin;\n } catch {\n return o;\n }\n };\n const allowed = new Set(origins.map(normalize));\n return (origin) => allowed.has(origin);\n}\n\nfunction corsHeaders(request: Request, policy: OriginPolicy): Record<string, string> {\n if (!policy) return {};\n const origin = request.headers.get('origin');\n if (!origin) return {};\n // Whatever the answer, it depends on Origin, so caches must key on it.\n if (!policy(origin)) return { vary: 'Origin' };\n return {\n 'access-control-allow-origin': origin,\n 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',\n // 2026-07-28 clients also send Mcp-Method, Mcp-Name and Mcp-Param-* headers.\n 'access-control-allow-headers':\n request.headers.get('access-control-request-headers') ??\n 'Authorization, Content-Type, Accept, Mcp-Session-Id, Mcp-Protocol-Version, Mcp-Method, Mcp-Name, Last-Event-ID',\n 'access-control-expose-headers': 'WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version',\n 'access-control-max-age': '86400',\n vary: 'Origin, Access-Control-Request-Headers',\n };\n}\n\nfunction withHeaders(res: Response, extra: Record<string, string>): Response {\n const keys = Object.keys(extra);\n if (keys.length === 0) return res;\n const headers = new Headers(res.headers);\n for (const key of keys) if (!headers.has(key)) headers.set(key, extra[key]!);\n return new Response(res.body, { status: res.status, statusText: res.statusText, headers });\n}\n\n/** Same bound the SDK applies to bodies it reads itself. */\nconst MAX_BODY_BYTES = 4 * 1024 * 1024;\n\nconst rpcError = (\n status: number,\n code: number,\n message: string,\n headers?: Record<string, string>,\n) => Response.json({ jsonrpc: '2.0', error: { code, message }, id: null }, { status, headers });\n\n/**\n * Request-mode rejection. Deliberately no `WWW-Authenticate: Bearer\n * resource_metadata=...`: there is no authorization server to discover, and a\n * challenge would send MCP clients into an OAuth flow that cannot succeed.\n */\nconst unauthorized = () => rpcError(401, -32001, 'Unauthorized.', NO_STORE);\n\n/**\n * The JSON-RPC payload of a POST, read once: the access policy needs it and\n * the SDK takes it as `parsedBody`. An app-level `onParse` hook runs before\n * the route's own and may already have drained the stream; Elysia then hands\n * us what it parsed.\n */\nasync function readJsonBody(\n request: Request,\n body: unknown,\n): Promise<{ ok: true; value: unknown } | { ok: false; response: Response }> {\n const tooLarge = {\n ok: false,\n response: rpcError(413, -32600, 'Request body too large.'),\n } as const;\n let text: string;\n if (request.bodyUsed) {\n if (typeof body !== 'string') return { ok: true, value: body };\n text = body;\n } else {\n if (Number(request.headers.get('content-length') ?? 0) > MAX_BODY_BYTES) return tooLarge;\n text = await request.text();\n }\n if (text.length > MAX_BODY_BYTES) return tooLarge;\n try {\n return { ok: true, value: JSON.parse(text) };\n } catch {\n return { ok: false, response: rpcError(400, -32700, 'Parse error: Invalid JSON') };\n }\n}\n\ntype RequestGuard = McpifyRequestAuthOptions['verify'];\n\n/**\n * Runtime twin of `McpifyAuthMode` for callers the type checker does not\n * reach. Request mode (`auth: { verify }`) counts as auth given.\n */\nfunction resolveAuthMode(options: Partial<McpifyAuthMode> | undefined): {\n auth: ResolvedAuth | null;\n guard: RequestGuard | null;\n} {\n const auth = options?.auth;\n const unsafe = options?.unsafeNoAuth === true;\n if (auth !== undefined && unsafe) {\n throw new TypeError('[mcpify] pass either `auth` or `unsafeNoAuth: true`, not both');\n }\n if (auth !== undefined) {\n if (typeof auth !== 'object' || auth === null) {\n throw new TypeError('[mcpify] auth must be an object');\n }\n return isRequestAuth(auth)\n ? { auth: null, guard: auth.verify.bind(auth) }\n : { auth: resolveAuth(auth), guard: null };\n }\n if (unsafe) return { auth: null, guard: null };\n throw new TypeError(\n '[mcpify] refusing to mount an unauthenticated MCP endpoint: pass `auth: { verify(request) }`, ' +\n '`auth: { resource, authorizationServers }`, or `unsafeNoAuth: true` for local development',\n );\n}\n\n/**\n * Messages the default sink has printed. Shared by every `mcpify()` instance\n * in the process, so an app that mounts the plugin more than once (or is\n * rebuilt per test or per hot reload) prints each warning a single time. A\n * custom `warn` gets every warning of its own instance.\n */\nconst printed = new Set<string>();\nconst printOnce = (message: string) => {\n if (printed.has(message)) return;\n printed.add(message);\n console.warn(message);\n};\n\ntype GuardDecision =\n | { admit: true; admission: RequestAuthAdmission | null }\n | { admit: false; response: Response; problem?: string };\n\nconst ADMISSION_KEYS = ['scopes', 'tools', 'readOnly'] as const;\n\n/** Read what `auth.verify` returned; every unexpected shape fails closed. */\nfunction decide(value: unknown): GuardDecision {\n if (value === true) return { admit: true, admission: null };\n const denied = (problem?: string): GuardDecision => ({\n admit: false,\n response: unauthorized(),\n ...(problem ? { problem } : {}),\n });\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return denied();\n const v = value as Record<string, unknown>;\n if ('status' in v) {\n const { status, code, message } = v;\n if (\n !Number.isInteger(status) ||\n (status as number) < 400 ||\n (status as number) > 599 ||\n typeof message !== 'string' ||\n !message ||\n (code !== undefined && !Number.isInteger(code))\n ) {\n return denied(\n 'returned a malformed refusal (want { status: 400-599, code?: integer, message })',\n );\n }\n return {\n admit: false,\n response: rpcError(\n status as number,\n (code as number | undefined) ?? -32001,\n message,\n NO_STORE,\n ),\n };\n }\n if (!ADMISSION_KEYS.some((k) => k in v)) {\n return denied('returned an object that is neither a refusal nor an admission (answered 401)');\n }\n const { scopes, tools, readOnly } = v;\n if (\n (scopes !== undefined &&\n !(Array.isArray(scopes) && scopes.every((s) => typeof s === 'string'))) ||\n (tools !== undefined && typeof tools !== 'function') ||\n (readOnly !== undefined && typeof readOnly !== 'boolean')\n ) {\n return denied(\n 'returned a malformed admission (want { scopes?: string[], tools?: (tool) => boolean, readOnly?: boolean })',\n );\n }\n return { admit: true, admission: v };\n}\n\ninterface ServerInfo {\n name: string;\n version: string;\n}\n\n/** What one document yields: the tools and the name to answer `initialize` with. */\ninterface Loaded {\n tools: ToolSet;\n serverInfo: ServerInfo;\n}\n\n/** `@elysiajs/openapi`'s default `info`, which names no app. */\nconst PLACEHOLDER_INFO = { title: 'Elysia Documentation', version: '0.0.0' };\n\nconst isDocument = (v: unknown): v is OpenAPIDocument =>\n typeof v === 'object' &&\n v !== null &&\n typeof (v as OpenAPIDocument).paths === 'object' &&\n (v as OpenAPIDocument).paths !== null;\n\ninterface OpenAPIModule {\n toOpenAPISchema: typeof toOpenAPISchema;\n}\nlet openapiModule: Promise<OpenAPIModule | null> | undefined;\n\n/**\n * `toOpenAPISchema(app)` from `@elysiajs/openapi`, an optional peer loaded\n * only when needed; `null` when it is not installed or fails on this app.\n */\nasync function buildInProcess(app: AnyElysia): Promise<OpenAPIDocument | null> {\n openapiModule ??= import('@elysiajs/openapi').catch(() => null);\n const mod = await openapiModule;\n if (!mod) return null;\n try {\n const doc: unknown = mod.toOpenAPISchema(app);\n return isDocument(doc) ? doc : null;\n } catch {\n return null;\n }\n}\n\nexport function mcpify(options: McpifyOptions) {\n const { auth, guard } = resolveAuthMode(options);\n const path = options.path ?? '/mcp';\n if (!path.startsWith('/')) throw new TypeError('[mcpify] path must start with \"/\"');\n const specPath = options.specPath ?? DEFAULT_SPEC_PATH;\n /**\n * `name` / `version`, else the document's `info` (unless it is\n * `@elysiajs/openapi`'s placeholder), else the library's.\n */\n const serverInfoFor = (doc: OpenAPIDocument): ServerInfo => {\n const title = doc.info?.title;\n const version = doc.info?.version;\n return {\n name:\n options.name ??\n (typeof title === 'string' && title.trim() && title !== PLACEHOLDER_INFO.title\n ? title.trim()\n : '@20baht/elysia-openapi-mcp'),\n version:\n options.version ??\n (typeof version === 'string' && version.trim() && version !== PLACEHOLDER_INFO.version\n ? version.trim()\n : '1.0.0'),\n };\n };\n const allRoutes = options.allRoutes ?? true;\n const wrapNonObjectOutput = options.wrapNonObjectOutput ?? true;\n const headerPolicy = options.headers ?? defaultHeaderPolicy;\n const cors = originPolicy(options.cors ?? guard === null);\n const sink = options.warn ?? printOnce;\n const silenced = silencedKinds(options.warnings);\n const emit = (w: McpifyWarning) => {\n if (!silenced.has(w.kind)) sink(w.message, w.kind);\n };\n if (!auth && !guard) emit({ kind: 'unauthenticated', message: UNAUTHENTICATED_WARNING });\n if (guard && options.cors === true) {\n emit({\n kind: 'cors-reflects-origin',\n message:\n '[mcpify] cors: true with auth: { verify } reflects any Origin; if verify trusts cookies, any site can call your tools from a signed-in browser. Pass cors: { origins: [...] } instead.',\n });\n }\n\n return <App extends AnyElysia>(app: App): App => {\n const emitted = new Set<string>();\n const warnOnce = (w: McpifyWarning) => {\n if (emitted.has(w.message)) return;\n emitted.add(w.message);\n emit(w);\n };\n\n const userHook = options.onToolCall;\n const onToolCall: OnToolCall | undefined = userHook\n ? async (event) => {\n try {\n await userHook(event);\n } catch (e) {\n warnOnce({\n kind: 'on-tool-call-error',\n message: `[mcpify] onToolCall threw for tool \"${event.tool.name}\": ${e instanceof Error ? e.message : String(e)}`,\n });\n }\n }\n : undefined;\n\n let cached: { key: number; loaded: Loaded } | null = null;\n let inflight: Promise<Loaded> | null = null;\n\n const loadDocument = async (origin: string): Promise<OpenAPIDocument> => {\n const source = options.document;\n if (typeof source === 'function') return source({ origin, app });\n if (source) return source;\n // The served document carries the plugin's own options (`documentation`,\n // `exclude`, `references`, `mapJsonSchema`), so it is read first.\n let failure: string;\n try {\n const res = await app.handle(\n new Request(`${origin}${specPath}`, { headers: { accept: 'application/json' } }),\n );\n const doc: unknown = res.ok ? await res.json().catch(() => undefined) : undefined;\n if (isDocument(doc)) return doc;\n failure = res.ok ? 'not an OpenAPI document' : `HTTP ${res.status}`;\n } catch (e) {\n failure = e instanceof Error ? e.message : String(e);\n }\n // The route is there but would not serve a caller without credentials\n // (a guarded /openapi): build the same document in-process instead.\n if (app.routes.some((r) => r.path === specPath)) {\n const built = await buildInProcess(app);\n if (built) return built;\n }\n throw new Error(\n `[mcpify] could not load the OpenAPI document from ${specPath} (${failure}). ` +\n 'Mount @elysiajs/openapi (or pass `document`) before mcpify().',\n );\n };\n\n const buildTools = async (origin: string): Promise<Loaded> => {\n const doc = await loadDocument(origin);\n const exclude: (string | RegExp)[] = [\n ...(options.excludeDefaults === false ? [] : DEFAULT_EXCLUDED_PATHS),\n ...(options.exclude ?? []),\n path,\n ];\n if (auth) exclude.push(auth.prmPath);\n const { tools, diagnostics } = deriveTools(doc, {\n allRoutes,\n tags: options.tags,\n wrapNonObjectOutput,\n headerParams: options.headerParams ?? false,\n exclude,\n stripPrefixes: [path],\n });\n for (const w of diagnostics) warnOnce(w);\n const exposed = auth?.requireToolScopes\n ? tools.filter((t) => {\n if (t.public || t.scopes.length > 0) return true;\n warnOnce({\n kind: 'tool-hidden',\n message: `[mcpify] tool \"${t.name}\" hidden: requireToolScopes is set and it declares neither detail.mcp.scopes nor detail.mcp.public`,\n });\n return false;\n })\n : tools;\n // Request mode can enforce scopes (an admission with `scopes`); whether\n // it does is only known per request, see `restrict`.\n if (!auth && !guard) {\n for (const t of tools) {\n if (t.scopes.length > 0) {\n warnOnce({\n kind: 'scopes-not-enforced',\n message: `[mcpify] tool \"${t.name}\": detail.mcp.scopes is not enforced without OAuth \\`auth\\``,\n });\n }\n }\n }\n return {\n tools: { list: exposed.map(toMcpTool), byName: new Map(exposed.map((t) => [t.name, t])) },\n serverInfo: serverInfoFor(doc),\n };\n };\n\n /** Re-derive whenever the route table grows (same strategy as @elysiajs/openapi). */\n const getTools = (origin: string): Promise<Loaded> => {\n const key =\n options.document && typeof options.document !== 'function' ? 0 : app.routes.length;\n if (cached?.key === key) return Promise.resolve(cached.loaded);\n if (!inflight) {\n inflight = buildTools(origin)\n .then((loaded) => {\n cached = { key, loaded };\n return loaded;\n })\n .finally(() => {\n inflight = null;\n });\n }\n return inflight;\n };\n\n /**\n * The tools one request-mode caller may see and call. A tool left out is\n * absent from `byName`, so calling it answers like an unknown tool and\n * does not reveal that it exists.\n */\n const restrict = (tools: ToolSet, admission: RequestAuthAdmission | null): ToolSet => {\n if (!admission?.scopes) {\n for (const t of tools.byName.values()) {\n if (t.scopes.length > 0) {\n warnOnce({\n kind: 'scopes-not-enforced',\n message: `[mcpify] tool \"${t.name}\": detail.mcp.scopes is not enforced: auth.verify admitted a request without returning { scopes }`,\n });\n }\n }\n }\n if (!admission) return tools;\n const { scopes, tools: pick, readOnly } = admission;\n const keep = (t: ToolSpec) => {\n if (scopes && !holdsToolScopes(t, scopes)) return false;\n if (readOnly && t.annotations.readOnlyHint !== true) return false;\n if (!pick) return true;\n try {\n return pick(t);\n } catch (e) {\n warnOnce({\n kind: 'verify-error',\n message: `[mcpify] the tools filter auth.verify returned threw for \"${t.name}\" (tool hidden): ${e instanceof Error ? e.message : String(e)}`,\n });\n return false;\n }\n };\n const byName = new Map([...tools.byName].filter(([, t]) => keep(t)));\n return { list: tools.list.filter((t) => byName.has(t.name)), byName };\n };\n\n // eslint-disable-next-line sonarjs/cognitive-complexity -- above the limit since before the move into this repo (NOTES 2026-11-20); split it when it is next changed\n const handleMcp = async (request: Request, rawBody: unknown): Promise<Response> => {\n const extra = corsHeaders(request, cors);\n if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: extra });\n\n let admission: RequestAuthAdmission | null = null;\n if (guard) {\n let decision: GuardDecision;\n try {\n decision = decide(await guard(request));\n } catch (e) {\n decision = {\n admit: false,\n response: unauthorized(),\n problem: `threw (answered 401): ${e instanceof Error ? e.message : String(e)}`,\n };\n }\n if (!decision.admit) {\n if (decision.problem) {\n warnOnce({ kind: 'verify-error', message: `[mcpify] auth.verify ${decision.problem}` });\n }\n return withHeaders(decision.response, extra);\n }\n admission = decision.admission;\n }\n\n let authInfo;\n // Without a token at all, anonymous callers are let through to the\n // per-message policy below; a token that is present is always verified.\n if (auth && !(auth.allowAnonymous && !request.headers.has('authorization'))) {\n const outcome = await authenticate(request, auth);\n if (!outcome.ok) return withHeaders(outcome.response, extra);\n authInfo = outcome.authInfo;\n }\n\n // Stateless: nothing is ever pushed to the client, so there is no stream\n // to open (GET) and no session to end (DELETE).\n if (request.method === 'GET' || request.method === 'DELETE') {\n return withHeaders(\n Response.json(\n { jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed.' }, id: null },\n { status: 405, headers: { allow: 'POST' } },\n ),\n extra,\n );\n }\n\n const read = await readJsonBody(request, rawBody);\n if (!read.ok) return withHeaders(read.response, extra);\n const parsedBody = read.value;\n\n let loaded: Loaded;\n try {\n loaded = await getTools(new URL(request.url).origin);\n } catch (e) {\n // The detail (paths, upstream status) goes to the operator, not the client.\n warnOnce({ kind: 'document', message: e instanceof Error ? e.message : String(e) });\n return withHeaders(\n Response.json(\n { error: 'server_error', error_description: 'Could not load the tool definitions' },\n { status: 500 },\n ),\n extra,\n );\n }\n const { serverInfo } = loaded;\n const tools = guard ? restrict(loaded.tools, admission) : loaded.tools;\n if (auth) {\n const denied = checkAccess(parsedBody, tools.byName, auth, authInfo);\n if (denied) return withHeaders(denied, extra);\n }\n const response = await serveMcp({\n request,\n app,\n tools,\n serverInfo,\n instructions: options.instructions,\n headerPolicy,\n authInfo,\n parsedBody,\n onToolCall,\n });\n return withHeaders(response, extra);\n };\n\n const hidden = { hide: true, mcp: false } as const;\n // Routes are registered on the caller's instance so `app.handle()` sees\n // the whole application; the generic is preserved for the caller's chain.\n const root = app as unknown as Elysia;\n root.all(path, ({ request, body }) => handleMcp(request, body), {\n // The handler reads the raw body itself. `parse: 'none'` is not enough\n // on `aot: false`, where Elysia still reads it; a hook that claims the\n // body without touching it is honoured by both compilers.\n parse: () => true,\n detail: hidden,\n });\n\n if (auth) {\n const prm = protectedResourceMetadata(auth);\n root.get(\n auth.prmPath,\n ({ request }) =>\n Response.json(prm, {\n headers: {\n ...corsHeaders(request, cors),\n 'cache-control': 'public, max-age=300',\n },\n }),\n { detail: hidden },\n );\n root.options(\n auth.prmPath,\n ({ request }) =>\n new Response(null, {\n status: 204,\n headers: { ...corsHeaders(request, cors), ...NO_STORE },\n }),\n { detail: hidden },\n );\n }\n\n return app;\n };\n}\n"
20
+ ],
21
+ "mappings": ";;;;AAMA;;;ACLA;;;ADUO,IAAM,WAAmC,EAAE,iBAAiB,YAAY,QAAQ,WAAW;AAM3F,SAAS,iBAAiB,CAC/B,MACA,QACA,OACA,aACA,OACU;AAAA,EACV,MAAM,UAAkC;AAAA,OACnC;AAAA,IACH,oBAAoB,gBAAgB;AAAA,MAClC,qBAAqB,KAAK;AAAA,MAC1B;AAAA,MACA,kBAAkB;AAAA,MAClB;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EACA,MAAM,OAAO,QAAQ,EAAE,OAAO,mBAAmB,YAAY,IAAI;AAAA,EACjE,OAAO,OAAO,SAAS,KAAK,MAAM,EAAE,QAAQ,QAAQ,CAAC,IAAI,IAAI,SAAS,MAAM,EAAE,QAAQ,QAAQ,CAAC;AAAA;AAGjG,IAAM,SAAS,IAAI,UAA6D;AAAA,EAC9E,IAAI;AAAA,EACJ,UAAU,kBAAkB,GAAG,IAAI;AACrC;AAEA,eAAsB,YAAY,CAAC,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IAAI,MAAM,GAAG,SAAS,WAAW,UAAU,SAAS,IAAI,GAAG;AAAA,MAI9D,OAAO,MAAM;AAAA,MACb,QAAQ;AAAA,IACV,CAAC;AAAA,IAED,IAAI,MAAM;AAAA,MACR,MAAM,MAAM,0BAA0B,IAAI;AAAA,MAC1C,KAAK,IACH,KAAK,SACL,GAAG,cACD,SAAS,KAAK,KAAK;AAAA,QACjB,SAAS;AAAA,aACJ,YAAY,SAAS,IAAI;AAAA,UAC5B,iBAAiB;AAAA,QACnB;AAAA,MACF,CAAC,GACH,EAAE,QAAQ,OAAO,CACnB;AAAA,MACA,KAAK,QACH,KAAK,SACL,GAAG,cACD,IAAI,SAAS,MAAM;AAAA,QACjB,QAAQ;AAAA,QACR,SAAS,KAAK,YAAY,SAAS,IAAI,MAAM,SAAS;AAAA,MACxD,CAAC,GACH,EAAE,QAAQ,OAAO,CACnB;AAAA,IACF;AAAA,IAEA,OAAO;AAAA;AAAA;",
22
+ "debugId": "C5EE4AFDAF16E9E364756E2164756E21",
23
+ "names": []
24
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * OpenAPI document → MCP tool specs. The document is the single source of
3
+ * truth: nothing here touches Elysia route internals.
4
+ */
5
+ import type { Tool } from '@modelcontextprotocol/server';
6
+ import type { McpifyWarning } from '../warnings.js';
7
+ import { type FlatSchema, type OutputSchema } from './schema.js';
8
+ import { type OpenAPIDocument, type OpenAPIOperation } from './types.js';
9
+ export interface ToolSpec {
10
+ name: string;
11
+ title?: string;
12
+ description: string;
13
+ /** Upper-case HTTP method. */
14
+ method: string;
15
+ /** OpenAPI path template, e.g. `/users/{id}`. */
16
+ path: string;
17
+ flat: FlatSchema;
18
+ output?: OutputSchema;
19
+ tags: string[];
20
+ annotations: NonNullable<Tool['annotations']>;
21
+ /** Scopes a token must hold to call this tool (from `detail.mcp.scopes`). */
22
+ scopes: string[];
23
+ /** Callable without a token when anonymous access is enabled (`detail.mcp.public`). */
24
+ public: boolean;
25
+ }
26
+ export interface DeriveOptions {
27
+ /** Expose every operation unless `mcp: false` (true) or only `mcp: true` ones (false). */
28
+ allRoutes: boolean;
29
+ /** Keep only operations carrying at least one of these tags. */
30
+ tags?: string[];
31
+ /** Wrap non-object responses as `{ result }` so they still get an `outputSchema`. */
32
+ wrapNonObjectOutput: boolean;
33
+ /** Expose OpenAPI `in: 'header'` parameters as tool arguments. Default false. */
34
+ headerParams?: boolean;
35
+ /** OpenAPI paths that must never become tools (exact string or RegExp). */
36
+ exclude?: readonly (string | RegExp)[];
37
+ /**
38
+ * Path prefixes dropped before deriving a fallback name, so routes mounted
39
+ * under the MCP endpoint itself (`/mcp/expenses`) become `list_expenses`.
40
+ */
41
+ stripPrefixes?: readonly string[];
42
+ }
43
+ /**
44
+ * Paths excluded by default: OAuth / discovery endpoints. An MCP tool that
45
+ * calls `/token` is exactly what the resource-server model forbids.
46
+ */
47
+ export declare const DEFAULT_EXCLUDED_PATHS: readonly (string | RegExp)[];
48
+ export declare function isExcluded(path: string, exclude: readonly (string | RegExp)[]): boolean;
49
+ export interface DeriveResult {
50
+ tools: ToolSpec[];
51
+ /** The messages of `diagnostics`. */
52
+ warnings: string[];
53
+ /** Each warning tagged with its kind. */
54
+ diagnostics: McpifyWarning[];
55
+ }
56
+ /** Explicit `detail.operationId` wins; the auto-generated one is ignored. */
57
+ export declare function toolNameFor(op: OpenAPIOperation, method: string, path: string, stripPrefixes?: readonly string[]): string;
58
+ export declare function deriveTools(doc: OpenAPIDocument, o: DeriveOptions): DeriveResult;
59
+ /** The wire representation for `tools/list`. */
60
+ export declare function toMcpTool(spec: ToolSpec): Tool;
61
+ //# sourceMappingURL=derive.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"derive.d.ts","sourceRoot":"","sources":["../../src/openapi/derive.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,8BAA8B,CAAC;AACzD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBA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F;AAED,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,qCAAqC;IACrC,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,yCAAyC;IACzC,WAAW,EAAE,aAAa,EAAE,CAAC;CAC9B;AAiCD,6EAA6E;AAC7E,wBAAgB,WAAW,CACzB,EAAE,EAAE,gBAAgB,EACpB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,aAAa,GAAE,SAAS,MAAM,EAAO,GACpC,MAAM,CAMR;AAsCD,wBAAgB,WAAW,CAAC,GAAG,EAAE,eAAe,EAAE,CAAC,EAAE,aAAa,GAAG,YAAY,CAmFhF;AAED,gDAAgD;AAChD,wBAAgB,SAAS,CAAC,IAAI,EAAE,QAAQ,GAAG,IAAI,CAW9C"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Tool-name derivation from method + path, and reproduction of the
3
+ * `operationId` that `@elysiajs/openapi` auto-generates (so we can tell an
4
+ * explicit `detail.operationId` from a default one).
5
+ */
6
+ /** Names of the `{param}` placeholders in an OpenAPI path template, in order. */
7
+ export declare function templateParams(path: string): string[];
8
+ /** MCP tool names must match `^[a-zA-Z0-9_-]{1,64}$`. */
9
+ export declare function sanitizeToolName(name: string): string;
10
+ /**
11
+ * `GET /users` → `list_users`, `GET /users/{id}` → `get_user`,
12
+ * `POST /users` → `create_user`, `GET /users/{uid}/posts` → `list_user_posts`.
13
+ * Leading `api` / `v1`-style prefixes are dropped.
14
+ */
15
+ export declare function deriveToolName(method: string, path: string): string;
16
+ /**
17
+ * Reproduces `@elysiajs/openapi`'s default `operationId` (`getUsersById`) so a
18
+ * default can be told apart from one the developer wrote in `detail.operationId`.
19
+ */
20
+ export declare function elysiaDefaultOperationId(method: string, openapiPath: string): string;
21
+ //# sourceMappingURL=naming.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"naming.d.ts","sourceRoot":"","sources":["../../src/openapi/naming.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAcH,iFAAiF;AACjF,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAIrD;AAoBD,yDAAyD;AACzD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMrD;AAED;;;;GAIG;AAEH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAqCnE;AAID;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAQpF"}
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Schema plumbing: `$ref` resolution, flattening of path/query/body into one
3
+ * MCP input schema (with per-property origin tracking), unflattening tool
4
+ * arguments back into buckets, and response → `outputSchema` mapping.
5
+ */
6
+ import type { McpifyWarning } from '../warnings.js';
7
+ import type { JsonSchema, OpenAPIOperation } from './types.js';
8
+ type Bucket = 'path' | 'query' | 'header' | 'body';
9
+ export interface PropertyOrigin {
10
+ bucket: Bucket;
11
+ /** Original property name inside its bucket. */
12
+ name: string;
13
+ }
14
+ export interface FlatSchema {
15
+ /** MCP `inputSchema`: always `type: object`. */
16
+ schema: JsonSchema & {
17
+ type: 'object';
18
+ properties: Record<string, JsonSchema>;
19
+ required?: string[];
20
+ };
21
+ /** flat property name → where it came from. */
22
+ origins: Record<string, PropertyOrigin>;
23
+ /** Set when the request body is not an object and is exposed as one property. */
24
+ rawBodyKey?: string;
25
+ /** The messages of `diagnostics`. */
26
+ warnings: string[];
27
+ /** Derivation warnings, each tagged with its kind. */
28
+ diagnostics: McpifyWarning[];
29
+ }
30
+ export interface OutputSchema {
31
+ schema: JsonSchema & {
32
+ type: 'object';
33
+ };
34
+ /** True when a non-object response was wrapped as `{ result }`. */
35
+ wrapped: boolean;
36
+ }
37
+ export declare const WRAPPED_RESULT_KEY = "result";
38
+ /**
39
+ * Inline every `$ref` (either `#/components/schemas/X` or a bare `X`, which
40
+ * `@elysiajs/openapi` emits for array items). Cycles become an opaque object.
41
+ */
42
+ export declare function dereference(schema: JsonSchema | undefined, components: Record<string, JsonSchema>, stack?: readonly string[]): JsonSchema | undefined;
43
+ /**
44
+ * Elysia's `t.Numeric()` becomes `anyOf: [{ type: 'string', format: 'numeric' }, { type: 'number' }]`.
45
+ * Agents should just send a number, so collapse it to the numeric branch,
46
+ * at any depth (properties, items, and union members).
47
+ */
48
+ export declare function simplifyNumeric(schema: JsonSchema): JsonSchema;
49
+ /** True when a request body is declared but offers no JSON media type (multipart, form, binary). */
50
+ export declare function hasNonJsonBodyOnly(op: OpenAPIOperation): boolean;
51
+ /**
52
+ * Merge path params + query + body into one flat object schema. Path params
53
+ * come first, then query, then header (only with `headerParams`), then body; a later bucket that collides with an
54
+ * earlier property is renamed `${bucket}_${name}` and reported.
55
+ */
56
+ export declare function flattenOperation(toolName: string, op: OpenAPIOperation, components: Record<string, JsonSchema>, pathParams: readonly string[], options?: {
57
+ headerParams?: boolean;
58
+ }): FlatSchema;
59
+ export interface UnflattenedArgs {
60
+ params: Record<string, unknown>;
61
+ query: Record<string, unknown>;
62
+ headers: Record<string, unknown>;
63
+ body: unknown;
64
+ }
65
+ /** Split flat tool arguments back into path / query / header / body buckets. */
66
+ export declare function unflattenArgs(args: Record<string, unknown>, flat: FlatSchema): UnflattenedArgs;
67
+ /**
68
+ * Map the success response schema to an MCP `outputSchema`. An output schema
69
+ * promises `structuredContent` on every success, so one is emitted only when
70
+ * every declared 2xx response has JSON content and they all share one schema;
71
+ * otherwise `report` is told why and none is emitted. MCP requires
72
+ * `type: object`; a non-object response is wrapped as `{ result }` when
73
+ * `wrapNonObject` is set, otherwise no output schema is emitted.
74
+ */
75
+ export declare function outputSchemaFor(op: OpenAPIOperation, components: Record<string, JsonSchema>, wrapNonObject: boolean, report?: (reason: string) => void): OutputSchema | undefined;
76
+ /**
77
+ * A response schema as an MCP `outputSchema`, which must be `type: object`:
78
+ * an object schema is used as is, anything else is wrapped as `{ result }`
79
+ * when `wrapNonObject` is set (and gives none otherwise).
80
+ */
81
+ export declare function toOutputSchema(schema: JsonSchema, wrapNonObject: boolean): OutputSchema | undefined;
82
+ export {};
83
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/openapi/schema.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAmB,MAAM,YAAY,CAAC;AAEhF,KAAK,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEnD,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,UAAU;IACzB,gDAAgD;IAChD,MAAM,EAAE,UAAU,GAAG;QACnB,IAAI,EAAE,QAAQ,CAAC;QACf,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;QACvC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;KACrB,CAAC;IACF,+CAA+C;IAC/C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACxC,iFAAiF;IACjF,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qCAAqC;IACrC,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,sDAAsD;IACtD,WAAW,EAAE,aAAa,EAAE,CAAC;CAC9B;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,UAAU,GAAG;QAAE,IAAI,EAAE,QAAQ,CAAA;KAAE,CAAC;IACxC,mEAAmE;IACnE,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,eAAO,MAAM,kBAAkB,WAAW,CAAC;AAoB3C;;;GAGG;AAEH,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wBAAgB,cAAc,CAC5B,MAAM,EAAE,UAAU,EAClB,aAAa,EAAE,OAAO,GACrB,YAAY,GAAG,SAAS,CAW1B"}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Minimal OpenAPI 3.x / JSON Schema shapes — just what tool derivation reads.
3
+ * Deliberately loose: the document is produced by `@elysiajs/openapi` and we
4
+ * only need to walk it, not validate it.
5
+ */
6
+ export interface JsonSchema {
7
+ type?: string | string[];
8
+ properties?: Record<string, JsonSchema>;
9
+ required?: string[];
10
+ items?: JsonSchema | JsonSchema[];
11
+ description?: string;
12
+ $ref?: string;
13
+ [key: string]: unknown;
14
+ }
15
+ export interface OpenAPIParameter {
16
+ name: string;
17
+ in: 'path' | 'query' | 'header' | 'cookie' | string;
18
+ required?: boolean;
19
+ description?: string;
20
+ schema?: JsonSchema;
21
+ }
22
+ interface OpenAPIMediaType {
23
+ schema?: JsonSchema;
24
+ }
25
+ interface OpenAPIRequestBody {
26
+ required?: boolean;
27
+ description?: string;
28
+ content?: Record<string, OpenAPIMediaType>;
29
+ }
30
+ export interface OpenAPIResponse {
31
+ description?: string;
32
+ content?: Record<string, OpenAPIMediaType>;
33
+ }
34
+ /** The object form of `detail.mcp`; it opts the route in like `true`. */
35
+ export interface McpRouteOptions {
36
+ /** Scopes a token must hold to call this tool, on top of `auth.scopes` (403 `insufficient_scope` otherwise). */
37
+ scopes?: string[];
38
+ /** Callable without a token when `auth.allowAnonymous` is set. */
39
+ public?: boolean;
40
+ /**
41
+ * JSON Schema of the tool's result, advertised as its `outputSchema` in
42
+ * place of the one derived from the route's `response`. Unlike `response`,
43
+ * Elysia does not check answers against it: it documents the result for
44
+ * agents only. A non-object schema is wrapped as `{ result }` (see
45
+ * `wrapNonObjectOutput`). A TypeBox `t.Object(...)` works too.
46
+ */
47
+ output?: JsonSchema;
48
+ }
49
+ export interface OpenAPIOperation {
50
+ operationId?: string;
51
+ summary?: string;
52
+ description?: string;
53
+ tags?: string[];
54
+ deprecated?: boolean;
55
+ parameters?: OpenAPIParameter[];
56
+ requestBody?: OpenAPIRequestBody;
57
+ responses?: Record<string, OpenAPIResponse>;
58
+ /** `@elysiajs/openapi` passes `detail.*` through verbatim, so these land here. */
59
+ hide?: boolean;
60
+ mcp?: boolean | McpRouteOptions;
61
+ [key: string]: unknown;
62
+ }
63
+ export interface OpenAPIDocument {
64
+ openapi?: string;
65
+ info?: {
66
+ title?: string;
67
+ version?: string;
68
+ description?: string;
69
+ };
70
+ /** Loose on purpose: accepts `toOpenAPISchema()` output and `openapi-types` documents alike. */
71
+ paths?: Record<string, unknown>;
72
+ components?: {
73
+ schemas?: Record<string, JsonSchema>;
74
+ };
75
+ }
76
+ export declare const HTTP_METHODS: readonly ["get", "post", "put", "patch", "delete"];
77
+ export declare function isOperation(value: unknown): value is OpenAPIOperation;
78
+ export {};
79
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/openapi/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACxC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,KAAK,CAAC,EAAE,UAAU,GAAG,UAAU,EAAE,CAAC;IAClC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,GAAG,OAAO,GAAG,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAAC;IACpD,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAA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