@vitemcp/server 1.9.0 → 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/dist/{OAuthProvider-DvW1SyKx.d.cts → OAuthProvider-BaPwgWny.d.cts} +12 -2
- package/dist/{OAuthProvider-DvW1SyKx.d.ts → OAuthProvider-BaPwgWny.d.ts} +12 -2
- package/dist/ViteMCP.cjs +4 -3
- package/dist/ViteMCP.cjs.map +1 -1
- package/dist/ViteMCP.d.cts +2 -2
- package/dist/ViteMCP.d.ts +2 -2
- package/dist/ViteMCP.js +3 -2
- package/dist/auth/index.cjs +2 -2
- package/dist/auth/index.d.cts +2 -2
- package/dist/auth/index.d.ts +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/chunk-4FH73ERY.js +64 -0
- package/dist/chunk-4FH73ERY.js.map +1 -0
- package/dist/chunk-FEM6LNS4.cjs +64 -0
- package/dist/chunk-FEM6LNS4.cjs.map +1 -0
- package/dist/{chunk-UFLW3ODH.js → chunk-IHX3AXKW.js} +106 -129
- package/dist/chunk-IHX3AXKW.js.map +1 -0
- package/dist/{chunk-HWSTK2ZH.js → chunk-KKSDTVEW.js} +79 -18
- package/dist/chunk-KKSDTVEW.js.map +1 -0
- package/dist/{chunk-KFOTRFZS.cjs → chunk-SHPKRGNY.cjs} +93 -32
- package/dist/chunk-SHPKRGNY.cjs.map +1 -0
- package/dist/{chunk-UPZH53RX.cjs → chunk-Y52P2PCS.cjs} +108 -131
- package/dist/chunk-Y52P2PCS.cjs.map +1 -0
- package/dist/edge/index.cjs +128 -21
- package/dist/edge/index.cjs.map +1 -1
- package/dist/edge/index.d.cts +6 -0
- package/dist/edge/index.d.ts +6 -0
- package/dist/edge/index.js +127 -20
- package/dist/edge/index.js.map +1 -1
- package/dist/openapi/index.cjs +36 -18
- package/dist/openapi/index.cjs.map +1 -1
- package/dist/openapi/index.d.cts +1 -1
- package/dist/openapi/index.d.ts +1 -1
- package/dist/openapi/index.js +28 -10
- package/dist/openapi/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-HWSTK2ZH.js.map +0 -1
- package/dist/chunk-KFOTRFZS.cjs.map +0 -1
- package/dist/chunk-UFLW3ODH.js.map +0 -1
- package/dist/chunk-UPZH53RX.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/server/server/dist/openapi/index.cjs","../../src/openapi/parameters.ts","../../src/openapi/executeRequest.ts","../../src/openapi/loadSpec.ts","../../src/openapi/routes.ts","../../src/openapi/naming.ts","../../src/openapi/normalize.ts","../../src/openapi/schemas.ts","../../src/openapi/selection.ts","../../src/openapi/fromOpenAPI.ts"],"names":["resolve","readPointer","slugify","decodeSegment","properties"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACA;ACGO,IAAM,qBAAA,EAAuB,CAClC,KAAA,EACA,SAAA,EACA,KAAA,EAAA,GACS;AACT,EAAA,MAAM,MAAA,mBAAQ,SAAA,CAAU,KAAA,UAAS,QAAA;AACjC,EAAA,MAAM,QAAA,mBAAU,SAAA,CAAU,OAAA,UAAW,MAAA,IAAU,QAAA;AAC/C,EAAA,MAAM,KAAA,EAAO,SAAA,CAAU,IAAA;AAEvB,EAAA,GAAA,CAAI,MAAA,IAAU,KAAA,GAAQ,MAAA,IAAU,KAAA,CAAA,EAAW;AACzC,IAAA,MAAA;AAAA,EACF;AAEA,EAAA,GAAA,CAAI,MAAA,IAAU,YAAA,EAAc;AAC1B,IAAA,GAAA,CAAI,QAAA,CAAS,KAAK,CAAA,EAAG;AACnB,MAAA,IAAA,CAAA,MAAW,CAAC,GAAA,EAAK,KAAK,EAAA,GAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAChD,QAAA,GAAA,CAAI,MAAA,IAAU,KAAA,CAAA,EAAW;AACvB,UAAA,KAAA,CAAM,MAAA,CAAO,CAAA,EAA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A;AACZ,MAAA;AACQ,MAAA;AACV,IAAA;AACF,EAAA;AAEsB,EAAA;AACH,IAAA;AAEC,IAAA;AACA,MAAA;AACd,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AAEc,EAAA;AAChB;AAE0B;APuiBF;AACA;AQt6BS;AAOgB;AACvC,EAAA;AACH,EAAA;AACE,EAAA;AACD,EAAA;AACD,EAAA;AACP;AAeE;AAGiB,EAAA;AAEF,EAAA;AAIF,EAAA;AACS,IAAA;AACtB,EAAA;AAES,EAAA;AAEL,IAAA;AAEJ,EAAA;AAGE,EAAA;AAEY,EAAA;AACF,IAAA;AACR,MAAA;AAIF,IAAA;AACF,EAAA;AAEO,EAAA;AACT;ARo4BwB;AACA;ASn7BiC;AAC7C,EAAA;AACH,EAAA;AACE,EAAA;AACD,EAAA;AACD,EAAA;AACT;AAEM;AAeqB;AAGP,EAAA;AACD,EAAA;AACH,EAAA;AACK,EAAA;AAGjB,EAAA;AAEe,IAAA;AACC,IAAA;AACG,IAAA;AAClB,EAAA;AAEiB,EAAA;AACC,IAAA;AAER,IAAA;AACT,MAAA;AACF,IAAA;AAEgB,IAAA;AACd,MAAA;AACA,MAAA;AACQ,uBAAA;AACV,IAAA;AAIgB,IAAA;AACG,uBAAA;AACjB,MAAA;AACQ,MAAA;AACV,IAAA;AAEe,IAAA;AACA,MAAA;AACI,QAAA;AACA,QAAA;AACL,QAAA;AACZ,MAAA;AACa,MAAA;AACG,MAAA;AAEZ,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACW,QAAA;AACF,QAAA;AACT,QAAA;AAEe,QAAA;AACf,QAAA;AACD,MAAA;AACH,MAAA;AACc,MAAA;AAGF,MAAA;AACD,MAAA;AACZ,IAAA;AACH,EAAA;AAEO,EAAA;AACT;AAQoC;AAEb,EAAA;AACb,EAAA;AACgB,EAAA;AACtB,EAAA;AACgB,EAAA;AAGV;AAQR;ATo4BsB;AACA;AACA;AACA","file":"/home/runner/work/server/server/dist/openapi/index.cjs","sourcesContent":[null,"import type { OpenApiParameter } from \"./types.js\";\n\n/**\n * Serializes parameters the way the OpenAPI `style`/`explode` pair says to.\n *\n * Worth doing properly rather than stringifying: a `tags` array sent as\n * `?tags=a&tags=b` to an operation declaring `style: form, explode: false`\n * reaches a server that reads a single comma-joined value, and silently sees\n * only `a`. The default of `form` + `explode: true` is the common case, but it\n * is a default, not the rule.\n */\nexport const appendQueryParameter = (\n query: URLSearchParams,\n parameter: OpenApiParameter,\n value: unknown,\n): void => {\n const style = parameter.style ?? \"form\";\n const explode = parameter.explode ?? style === \"form\";\n const name = parameter.name;\n\n if (value === null || value === undefined) {\n return;\n }\n\n if (style === \"deepObject\") {\n if (isRecord(value)) {\n for (const [key, entry] of Object.entries(value)) {\n if (entry !== undefined) {\n query.append(`${name}[${key}]`, stringify(entry));\n }\n }\n }\n\n return;\n }\n\n if (explode) {\n if (Array.isArray(value)) {\n for (const entry of value) {\n query.append(name, stringify(entry));\n }\n\n return;\n }\n\n if (isRecord(value)) {\n for (const [key, entry] of Object.entries(value)) {\n if (entry !== undefined) {\n query.append(key, stringify(entry));\n }\n }\n\n return;\n }\n\n query.append(name, stringify(value));\n return;\n }\n\n const separator = DELIMITERS[style] ?? \",\";\n\n if (Array.isArray(value)) {\n query.append(name, value.map(stringify).join(separator));\n return;\n }\n\n if (isRecord(value)) {\n query.append(\n name,\n Object.entries(value)\n .flatMap(([key, entry]) =>\n entry === undefined ? [] : [key, stringify(entry)],\n )\n .join(separator),\n );\n return;\n }\n\n query.append(name, stringify(value));\n};\n\n/**\n * Renders the collected query parameters.\n *\n * `URLSearchParams` writes a space as `+`, which is the form-encoding rule\n * rather than the URL one; OpenAPI's `spaceDelimited` style means a literal\n * space. A `+` that was itself part of a value is already `%2B` by this point,\n * so every remaining one came from a space and can be rewritten safely.\n */\nexport const toQueryString = (query: URLSearchParams): string =>\n query.toString().replaceAll(\"+\", \"%20\");\n\n/**\n * Serializes a path parameter, percent-encoding the values but not the\n * delimiters that separate them — the delimiters are part of the path's\n * structure, and encoding them would hide it from the server.\n */\nexport const serializePathParameter = (\n parameter: OpenApiParameter,\n value: unknown,\n): string => {\n const style = parameter.style ?? \"simple\";\n const explode = parameter.explode ?? false;\n const body = serializeSimple(value, explode, parameter.name, style);\n\n if (style === \"label\") {\n return `.${body}`;\n }\n\n if (style === \"matrix\") {\n // An exploded matrix parameter already repeats `;name=` per entry.\n return explode && (Array.isArray(value) || isRecord(value))\n ? body\n : `;${parameter.name}=${body}`;\n }\n\n return body;\n};\n\n/**\n * Serializes a header or cookie parameter. Both default to a comma-joined\n * `simple` form; neither is percent-encoded, since header values are not a URL.\n */\nexport const serializeSimpleParameter = (\n parameter: OpenApiParameter,\n value: unknown,\n): string => {\n const explode = parameter.explode ?? false;\n\n if (Array.isArray(value)) {\n return value.map(stringify).join(\",\");\n }\n\n if (isRecord(value)) {\n return Object.entries(value)\n .flatMap(([key, entry]) =>\n entry === undefined\n ? []\n : [\n explode\n ? `${key}=${stringify(entry)}`\n : `${key},${stringify(entry)}`,\n ],\n )\n .join(\",\");\n }\n\n return stringify(value);\n};\n\nconst DELIMITERS: Record<string, string> = {\n form: \",\",\n pipeDelimited: \"|\",\n simple: \",\",\n spaceDelimited: \" \",\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst serializeSimple = (\n value: unknown,\n explode: boolean,\n name: string,\n style: string,\n): string => {\n const encode = (entry: unknown): string =>\n encodeURIComponent(stringify(entry));\n\n if (Array.isArray(value)) {\n if (style === \"matrix\" && explode) {\n return value.map((entry) => `;${name}=${encode(entry)}`).join(\"\");\n }\n\n if (style === \"label\" && explode) {\n return value.map(encode).join(\".\");\n }\n\n return value.map(encode).join(\",\");\n }\n\n if (isRecord(value)) {\n const entries = Object.entries(value).filter(\n ([, entry]) => entry !== undefined,\n );\n\n if (style === \"matrix\" && explode) {\n return entries.map(([key, entry]) => `;${key}=${encode(entry)}`).join(\"\");\n }\n\n if (explode) {\n return entries\n .map(([key, entry]) => `${encodeURIComponent(key)}=${encode(entry)}`)\n .join(style === \"label\" ? \".\" : \",\");\n }\n\n return entries\n .flatMap(([key, entry]) => [encodeURIComponent(key), encode(entry)])\n .join(\",\");\n }\n\n return encode(value);\n};\n\n/**\n * `JSON.stringify` for anything that is not already a primitive, so a nested\n * object reaching a scalar slot arrives as something a server can parse rather\n * than as `[object Object]`.\n */\nconst stringify = (value: unknown): string =>\n typeof value === \"object\" && value !== null\n ? JSON.stringify(value)\n : String(value);\n","import type {\n AudioContent,\n Context,\n ImageContent,\n StructuredResult,\n ViteMCPAuth,\n} from \"../ViteMCP.js\";\nimport type { ToolBinding } from \"./schemas.js\";\nimport type { ContextualHeaders, HttpRoute, OpenApiServer } from \"./types.js\";\n\nimport { UserError } from \"../ViteMCP.js\";\nimport {\n appendQueryParameter,\n serializePathParameter,\n serializeSimpleParameter,\n toQueryString,\n} from \"./parameters.js\";\n\nexport type ExecuteRequestOptions<T extends ViteMCPAuth> = {\n args: Record<string, unknown>;\n baseUrl: string;\n binding: ToolBinding;\n context: Context<T>;\n fetchImpl: typeof globalThis.fetch;\n headers?: ContextualHeaders<T>;\n maxResponseCharacters: number;\n query?: ContextualHeaders<T>;\n route: HttpRoute;\n};\n\nexport type ExecuteRequestResult =\n | AudioContent\n | ImageContent\n | string\n | StructuredResult<Record<string, unknown>>;\n\n/** Bodies over this are never treated as inline media, whatever the type. */\nconst MAX_INLINE_MEDIA_BYTES = 8 * 1024 * 1024;\n\nexport const executeRequest = async <T extends ViteMCPAuth>(\n options: ExecuteRequestOptions<T>,\n): Promise<ExecuteRequestResult> => {\n const { args, binding, context, route } = options;\n\n const pathValues = new Map<string, string>();\n const query = new URLSearchParams();\n const cookies: string[] = [];\n // `Headers` rather than an object, so that a header the operation names\n // `Content-Type` and one this function sets as `content-type` are recognised\n // as the same header instead of being sent twice.\n const headers = new Headers();\n const bodyValues: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(args)) {\n const binder = binding.parameters[key];\n\n if (!binder || value === undefined) {\n continue;\n }\n\n if (binder.kind === \"body\") {\n bodyValues[binder.name] = value;\n continue;\n }\n\n const { parameter } = binder;\n\n switch (parameter.in) {\n case \"cookie\":\n cookies.push(\n `${parameter.name}=${encodeCookieValue(\n serializeSimpleParameter(parameter, value),\n )}`,\n );\n break;\n case \"header\":\n setHeader(\n headers,\n parameter.name,\n serializeSimpleParameter(parameter, value),\n );\n break;\n case \"path\":\n pathValues.set(\n parameter.name,\n serializePathParameter(parameter, value),\n );\n break;\n case \"query\":\n appendQueryParameter(query, parameter, value);\n break;\n }\n }\n\n for (const [name, value] of Object.entries(\n await resolve(options.query, context),\n )) {\n query.delete(name);\n query.append(name, value);\n }\n\n if (cookies.length > 0) {\n setHeader(headers, \"cookie\", cookies.join(\"; \"));\n }\n\n const body = buildBody(binding, bodyValues, headers);\n\n // Applied last on purpose. These are the credentials the server was\n // configured with, and an operation that happens to declare a header or\n // query parameter of the same name must not let a model-supplied argument\n // replace them.\n for (const [name, value] of Object.entries(\n await resolve(options.headers, context),\n )) {\n setHeader(headers, name, value);\n }\n\n const url = new URL(buildPath(route.path, pathValues), `${options.baseUrl}/`);\n url.search = toQueryString(query);\n\n const response = await options.fetchImpl(url, {\n body,\n headers,\n method: route.method.toUpperCase(),\n // Forwarded so an abandoned tool call stops the upstream request too,\n // rather than leaving it running behind a settled promise.\n signal: context.signal,\n });\n\n return await readResponse(response, options);\n};\n\n/**\n * Resolves the address to send to: an explicit override, else the nearest\n * `servers` entry, with a relative URL joined against wherever the document\n * itself was loaded from.\n *\n * That last part is what makes documents like Swagger's own Petstore work —\n * its `servers` is `[{ url: \"/api/v3\" }]`, which a validator accepts and an\n * HTTP client cannot use.\n */\nexport const resolveBaseUrl = (\n servers: OpenApiServer[] | undefined,\n origin: string | undefined,\n override: string | undefined,\n): string => {\n if (override) {\n return trimSlash(override);\n }\n\n const server = servers?.[0];\n\n if (!server?.url) {\n throw new Error(\n \"The OpenAPI document declares no `servers`, so there is no address to call. Pass `baseUrl` to fromOpenAPI().\",\n );\n }\n\n let url = server.url;\n\n for (const [name, variable] of Object.entries(server.variables ?? {})) {\n url = url.replaceAll(`{${name}}`, variable.default);\n }\n\n try {\n return trimSlash(new URL(url).toString());\n } catch {\n if (!origin) {\n throw new Error(\n `The OpenAPI document's server URL (\"${url}\") is relative, and the document was not loaded from an http(s) URL, so there is nothing to resolve it against. Pass \\`baseUrl\\` to fromOpenAPI().`,\n );\n }\n\n return trimSlash(new URL(url, origin).toString());\n }\n};\n\n/**\n * Appends one form-encoded body property, bracketing anything nested.\n *\n * OpenAPI's `style`/`explode` pair only describes flat values, so a nested\n * object has no encoding the specification defines. Sending it as one JSON\n * string is the reading a server never expects: it wants fields. The bracket\n * convention — `metadata[order]=42`, as popularised by Stripe — is what the\n * APIs accepting nested form bodies actually parse, so it is what a nested\n * value serializes to here.\n */\nconst appendFormValue = (\n form: URLSearchParams,\n name: string,\n value: unknown,\n): void => {\n if (value === undefined) {\n return;\n }\n\n if (Array.isArray(value)) {\n // A flat array keeps OpenAPI's `explode: true` default and repeats the\n // key. Indices appear only once an entry is itself nested, where repeating\n // the key would run every entry's fields together into one.\n const nested = value.some(\n (entry) => typeof entry === \"object\" && entry !== null,\n );\n\n for (const [index, entry] of value.entries()) {\n appendFormValue(form, nested ? `${name}[${index}]` : name, entry);\n }\n\n return;\n }\n\n if (isRecord(value)) {\n for (const [key, entry] of Object.entries(value)) {\n appendFormValue(form, `${name}[${key}]`, entry);\n }\n\n return;\n }\n\n form.append(name, String(value));\n};\n\nconst buildBody = (\n binding: ToolBinding,\n values: Record<string, unknown>,\n headers: Headers,\n): string | undefined => {\n const encoding = binding.bodyEncoding;\n\n if (!encoding || Object.keys(values).length === 0) {\n return undefined;\n }\n\n const payload = binding.wholeBodyKey ? values[binding.wholeBodyKey] : values;\n\n if (payload === undefined) {\n return undefined;\n }\n\n if (!headers.has(\"content-type\")) {\n headers.set(\"content-type\", encoding.contentType);\n }\n\n if (encoding.kind === \"text\") {\n return typeof payload === \"string\" ? payload : JSON.stringify(payload);\n }\n\n if (encoding.kind === \"form\") {\n if (!isRecord(payload)) {\n return typeof payload === \"string\" ? payload : JSON.stringify(payload);\n }\n\n const form = new URLSearchParams();\n\n for (const [name, value] of Object.entries(payload)) {\n appendFormValue(form, name, value);\n }\n\n return form.toString();\n }\n\n return JSON.stringify(payload);\n};\n\n/**\n * Substitutes path parameters. Leading slash removed so the result is a\n * relative reference: resolved against a base of `https://host/api/v3/`, a\n * leading slash would discard the `/api/v3` prefix the document asked for.\n */\nconst buildPath = (template: string, values: Map<string, string>): string => {\n let path = template;\n\n for (const [name, value] of values) {\n path = path.replaceAll(`{${name}}`, value);\n }\n\n return path.replace(/^\\//, \"\");\n};\n\nconst resolve = async <T extends ViteMCPAuth>(\n source: ContextualHeaders<T> | undefined,\n context: Context<T>,\n): Promise<Record<string, string>> => {\n if (!source) {\n return {};\n }\n\n return typeof source === \"function\" ? await source(context) : source;\n};\n\nconst readResponse = async <T extends ViteMCPAuth>(\n response: Response,\n options: ExecuteRequestOptions<T>,\n): Promise<ExecuteRequestResult> => {\n const { binding, maxResponseCharacters, route } = options;\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const label = `${route.method.toUpperCase()} ${route.path}`;\n\n if (!response.ok) {\n throw new UserError(\n `${label} failed with ${response.status} ${response.statusText}: ${truncate(\n await response.text(),\n 2000,\n )}`,\n );\n }\n\n if (/^(?:audio|image)\\//.test(contentType) && !binding.outputSchema) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n\n if (bytes.byteLength <= MAX_INLINE_MEDIA_BYTES) {\n const mimeType = contentType.split(\";\")[0].trim();\n\n return contentType.startsWith(\"image/\")\n ? { data: toBase64(bytes), mimeType, type: \"image\" }\n : { data: toBase64(bytes), mimeType, type: \"audio\" };\n }\n\n throw new UserError(\n `${label} returned ${bytes.byteLength} bytes of ${contentType}, too large to return inline.`,\n );\n }\n\n const text = await response.text();\n const parsed = /\\bjson\\b/.test(contentType)\n ? tryParse(text.length <= maxResponseCharacters ? text : undefined)\n : undefined;\n\n // A JSON object goes back as structured content, which ViteMCP mirrors as\n // JSON text for clients that ignore it — so nothing is lost, and clients\n // that read it get a value instead of a string to re-parse.\n if (isRecord(parsed)) {\n return { structuredContent: parsed };\n }\n\n if (binding.outputSchema) {\n throw new UserError(\n `${label} declares a JSON object response but returned ${\n contentType || \"an untyped body\"\n }. Set \\`outputSchema: false\\` if this document's response schemas do not match the API.`,\n );\n }\n\n if (text === \"\") {\n return `${response.status} ${response.statusText}`.trim();\n }\n\n return parsed === undefined\n ? truncate(text, maxResponseCharacters)\n : truncate(JSON.stringify(parsed, null, 2), maxResponseCharacters);\n};\n\n/**\n * Escapes the characters RFC 6265 forbids in a cookie value, so an argument\n * containing `;` sets one cookie with a peculiar value rather than two\n * cookies. Everything else is left alone — `=` in particular, since base64\n * cookie values end in it.\n */\nconst encodeCookieValue = (value: string): string =>\n // eslint-disable-next-line no-control-regex\n value.replace(/[\\u0000-\\u001F\\u007F \",;\\\\]/g, (character) =>\n encodeURIComponent(character),\n );\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * `Headers` rejects a value containing a newline, which is the whole reason a\n * header parameter cannot be used to smuggle extra headers. Rethrown as a\n * `UserError` so a model that supplied one gets told what to fix instead of\n * the call failing as an internal error.\n */\nconst setHeader = (headers: Headers, name: string, value: string): void => {\n try {\n headers.set(name, value);\n } catch {\n throw new UserError(\n `\"${name}\" is not a valid header name, or the value given for it is not a valid header value.`,\n );\n }\n};\n\nconst toBase64 = (bytes: Uint8Array): string => {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(bytes).toString(\"base64\");\n }\n\n let binary = \"\";\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary);\n};\n\nconst trimSlash = (value: string): string => value.replace(/\\/+$/, \"\");\n\nconst truncate = (text: string, limit: number): string =>\n text.length <= limit\n ? text\n : `${text.slice(0, limit)}\\n\\n[truncated after ${limit} characters]`;\n\nconst tryParse = (text: string | undefined): unknown => {\n if (text === undefined) {\n return undefined;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n};\n","import type { OpenApiDocument } from \"./types.js\";\n\nimport { cancelResponseBody } from \"../cancelResponseBody.js\";\n\nexport type LoadedSpec = {\n document: OpenApiDocument;\n /**\n * The URL the document was loaded from, when it was loaded from one. Used to\n * resolve a relative `servers[0].url` against the document's own origin.\n */\n origin?: string;\n};\n\n/**\n * Loads an OpenAPI 3.x document, bundling external `$ref`s only when the\n * document actually has any.\n *\n * The bundler (`@apidevtools/swagger-parser`) is an optional peer dependency\n * imported on demand, not a hard one: it reaches for the filesystem and brings\n * its own JSON Schema stack with it. A single-file JSON document — which is\n * what most published specs are — needs neither, so the common path installs\n * and loads nothing extra. Multi-file documents and YAML are where the bundler\n * earns its weight, and only those pay for it.\n */\nexport const loadSpec = async (\n spec: Record<string, unknown> | string,\n): Promise<LoadedSpec> => {\n if (typeof spec !== \"string\") {\n return {\n document: hasExternalRef(spec)\n ? await bundle(spec)\n : assertOpenApi3(spec as OpenApiDocument),\n };\n }\n\n const origin = isHttpUrl(spec) ? spec : undefined;\n const parsed = parseJson(await readSpecText(spec));\n\n // Re-bundling from the original string rather than from `parsed` is\n // deliberate: external refs resolve against whichever document they were\n // found in, so handing the bundler an already-parsed object would resolve\n // every one of them against the process's working directory instead of the\n // document's own location.\n if (!parsed || hasExternalRef(parsed)) {\n return { document: await bundle(spec), origin };\n }\n\n return { document: assertOpenApi3(parsed), origin };\n};\n\nconst assertOpenApi3 = (document: OpenApiDocument): OpenApiDocument => {\n if (!document?.openapi?.startsWith(\"3.\")) {\n const found =\n document?.openapi ??\n (document?.swagger ? `Swagger ${document.swagger}` : undefined);\n\n throw new Error(\n `fromOpenAPI supports OpenAPI 3.x documents only (found ${\n found ?? \"no recognisable version field\"\n }). Convert a Swagger 2.0 document first — https://converter.swagger.io converts one in place.`,\n );\n }\n\n return document;\n};\n\nconst bundle = async (\n spec: Record<string, unknown> | string,\n): Promise<OpenApiDocument> => {\n let parser;\n\n try {\n parser = await import(\"@apidevtools/swagger-parser\");\n } catch {\n throw new Error(\n 'This document is YAML or has external $refs, which needs the \"@apidevtools/swagger-parser\" package. ' +\n \"Install it with: npm install @apidevtools/swagger-parser\",\n );\n }\n\n // The package ships CommonJS, so depending on the loader the class arrives\n // as the module namespace, as `.default`, or as `.default.default` — the\n // same unwrapping `jsonSchemaAdapter` does for AJV.\n const SwaggerParser = unwrapDefault(unwrapDefault(parser)) as {\n bundle: (spec: unknown) => Promise<unknown>;\n };\n\n return assertOpenApi3((await SwaggerParser.bundle(spec)) as OpenApiDocument);\n};\n\n/**\n * Reports whether any `$ref` in the document points outside it. Iterative\n * rather than recursive: a large document (Stripe's is ~200k lines) nests\n * deeply enough to matter, and this runs before anything else has looked at\n * it.\n */\nconst hasExternalRef = (root: unknown): boolean => {\n const seen = new WeakSet<object>();\n const stack: unknown[] = [root];\n\n while (stack.length > 0) {\n const node = stack.pop();\n\n if (!node || typeof node !== \"object\" || seen.has(node)) {\n continue;\n }\n\n seen.add(node);\n\n if (Array.isArray(node)) {\n // Pushed one at a time rather than spread: a document can hold an array\n // of tens of thousands of enum values, and spreading one of those into a\n // call exceeds the argument limit.\n for (const entry of node) {\n stack.push(entry);\n }\n\n continue;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (key === \"$ref\" && typeof value === \"string\") {\n if (!value.startsWith(\"#\")) {\n return true;\n }\n\n continue;\n }\n\n stack.push(value);\n }\n }\n\n return false;\n};\n\nconst isHttpUrl = (value: string): boolean =>\n value.startsWith(\"http://\") || value.startsWith(\"https://\");\n\nconst parseJson = (text: string): Record<string, unknown> | undefined => {\n try {\n const value: unknown = JSON.parse(text);\n return value && typeof value === \"object\"\n ? (value as Record<string, unknown>)\n : undefined;\n } catch {\n // Not JSON — YAML, most likely, which the bundler parses.\n return undefined;\n }\n};\n\nconst readSpecText = async (spec: string): Promise<string> => {\n if (isHttpUrl(spec)) {\n const response = await fetch(spec, {\n headers: { accept: \"application/json, text/yaml, */*\" },\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(\n `Failed to fetch the OpenAPI document from ${spec}: ${response.status} ${response.statusText}`,\n );\n }\n\n return await response.text();\n }\n\n // Inline document text, rather than a path to one. Unambiguous for JSON;\n // YAML text is indistinguishable from a filename, so it is not accepted.\n if (spec.trimStart().startsWith(\"{\")) {\n return spec;\n }\n\n // Imported on demand so that bundling this module for a runtime without a\n // filesystem does not fail on an unused import.\n const { readFile } = await import(\"node:fs/promises\");\n\n return await readFile(spec, \"utf8\");\n};\n\nconst unwrapDefault = (value: unknown): unknown =>\n typeof value === \"object\" && value !== null && \"default\" in value\n ? (value as { default: unknown }).default\n : value;\n","import type {\n HttpMethod,\n HttpRoute,\n OpenApiDocument,\n OpenApiParameter,\n OpenApiRef,\n OpenApiRequestBody,\n OpenApiResponse,\n OperationSummary,\n} from \"./types.js\";\n\n/**\n * `head`, `options` and `trace` are omitted on purpose: they answer questions\n * about a resource rather than doing anything with it, so a tool built from\n * one gives a model nothing it can act on.\n */\nconst HTTP_METHODS: HttpMethod[] = [\"get\", \"post\", \"put\", \"patch\", \"delete\"];\n\n/** How many `$ref` hops to follow before assuming the document is cyclic. */\nconst MAX_REF_HOPS = 32;\n\n/**\n * Flattens a document's `paths` into a list of routes, resolving the\n * structural (non-schema) `$ref`s on parameters, request bodies and responses\n * — `#/components/parameters/Limit` and the like.\n *\n * Every remaining `$ref` at this point is local (see `loadSpec`), so a plain\n * JSON Pointer lookup is enough. Schema `$ref`s are left alone: those are\n * handed to the client as part of the tool's input schema, where they are\n * resolved against `$defs` instead (see `schemas.ts`).\n */\nexport const extractRoutes = (document: OpenApiDocument): HttpRoute[] => {\n const routes: HttpRoute[] = [];\n\n for (const [path, pathItem] of Object.entries(document.paths ?? {})) {\n if (!pathItem || typeof pathItem !== \"object\") {\n continue;\n }\n\n const pathLevelParameters = (pathItem.parameters ?? []).map((parameter) =>\n resolve<OpenApiParameter>(document, parameter),\n );\n\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n\n if (!operation) {\n continue;\n }\n\n const responses: Record<string, OpenApiResponse> = {};\n\n for (const [status, response] of Object.entries(\n operation.responses ?? {},\n )) {\n responses[status] = resolve<OpenApiResponse>(document, response) ?? {};\n }\n\n routes.push({\n deprecated: operation.deprecated ?? false,\n description: operation.description,\n method,\n operationId: operation.operationId,\n parameters: mergeParameters(\n pathLevelParameters,\n (operation.parameters ?? []).map((parameter) =>\n resolve<OpenApiParameter>(document, parameter),\n ),\n ),\n path,\n requestBody: operation.requestBody\n ? resolve<OpenApiRequestBody>(document, operation.requestBody)\n : undefined,\n responses,\n servers: operation.servers ?? pathItem.servers,\n summary: operation.summary,\n tags: operation.tags ?? [],\n });\n }\n }\n\n return routes;\n};\n\nexport const toOperationSummary = (route: HttpRoute): OperationSummary => ({\n deprecated: route.deprecated,\n description: route.description,\n method: route.method,\n operationId: route.operationId,\n path: route.path,\n summary: route.summary,\n tags: route.tags,\n});\n\n/**\n * An operation-level parameter overrides a path-level one with the same\n * name *and* location, per the OpenAPI specification — the pair is the\n * identity, so a `limit` in the query does not shadow a `limit` in the path.\n */\nconst mergeParameters = (\n pathLevel: OpenApiParameter[],\n operationLevel: OpenApiParameter[],\n): OpenApiParameter[] => {\n const overridden = new Set(\n operationLevel.map((parameter) => `${parameter.in}:${parameter.name}`),\n );\n\n return [\n ...pathLevel.filter(\n (parameter) => !overridden.has(`${parameter.in}:${parameter.name}`),\n ),\n ...operationLevel,\n ].filter((parameter) => parameter?.name && parameter.in);\n};\n\nconst resolve = <TValue>(\n document: OpenApiDocument,\n value: OpenApiRef | TValue,\n): TValue => {\n let node: unknown = value;\n\n for (let hop = 0; hop < MAX_REF_HOPS; hop++) {\n if (!node || typeof node !== \"object\" || !(\"$ref\" in node)) {\n return node as TValue;\n }\n\n const pointer = (node as OpenApiRef).$ref;\n\n if (!pointer.startsWith(\"#\")) {\n // Bundling turns every external ref into a local one; reaching here\n // means the bundler's output shape changed under us.\n throw new Error(`Unresolved external $ref after bundling: ${pointer}`);\n }\n\n node = readPointer(document, pointer);\n }\n\n throw new Error(\n `$ref chain longer than ${MAX_REF_HOPS} hops, which a cyclic document is the only way to produce.`,\n );\n};\n\n/**\n * Reads an RFC 6901 JSON Pointer written as a URI fragment, which is the form\n * the bundler emits — a path like `/pets/{petId}` becomes\n * `~1pets~1%7BpetId%7D`, so each segment needs percent-decoding *and* its\n * `~1`/`~0` escapes undone, in that order.\n */\nconst readPointer = (root: unknown, pointer: string): unknown => {\n const path = pointer.slice(1);\n\n if (path === \"\" || path === \"/\") {\n return root;\n }\n\n let node: unknown = root;\n\n for (const rawSegment of path.slice(1).split(\"/\")) {\n const segment = decodeSegment(rawSegment);\n node = (node as Record<string, unknown> | undefined)?.[segment];\n }\n\n return node;\n};\n\nconst decodeSegment = (segment: string): string => {\n let decoded = segment;\n\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n // A segment that is not valid percent-encoding is used verbatim, which is\n // what a document that never encoded it in the first place intended.\n }\n\n return decoded.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n};\n","import type { HttpRoute, OperationSummary } from \"./types.js\";\n\nimport { toOperationSummary } from \"./routes.js\";\n\n/**\n * Cap on a generated tool name. Nothing in MCP imposes one, but clients that\n * bridge to other tool-calling APIs do — 64 characters is the common limit —\n * and a name silently truncated by a client is worse than one shortened here.\n */\nconst MAX_NAME_LENGTH = 64;\n\n/** Leaves room for a `_<n>` collision suffix without exceeding the cap. */\nconst MAX_BASE_LENGTH = MAX_NAME_LENGTH - 5;\n\n/**\n * Assigns each route a unique tool name.\n *\n * Uniqueness is checked against the final name rather than the base, because a\n * document whose own `operationId`s already look suffixed — both `listPets`\n * and `listPets_2` — would otherwise produce two tools with the same name, and\n * only one of them would be reachable.\n */\nexport const generateToolNames = (\n routes: HttpRoute[],\n override: FromOpenAPIToolNames,\n): Map<HttpRoute, string> => {\n const names = new Map<HttpRoute, string>();\n const taken = new Set<string>();\n\n for (const route of routes) {\n const base = slugify(baseNameFor(route, override));\n let name = base;\n\n for (let suffix = 2; taken.has(name); suffix++) {\n name = `${base}_${suffix}`;\n }\n\n taken.add(name);\n names.set(route, name);\n }\n\n return names;\n};\n\ntype FromOpenAPIToolNames =\n | ((operation: OperationSummary) => string | undefined)\n | Record<string, string>\n | undefined;\n\nconst baseNameFor = (\n route: HttpRoute,\n override: FromOpenAPIToolNames,\n): string => {\n const explicit =\n typeof override === \"function\"\n ? override(toOperationSummary(route))\n : route.operationId\n ? override?.[route.operationId]\n : undefined;\n\n if (explicit) {\n return explicit;\n }\n\n if (route.operationId) {\n // Code generators — FastAPI's, notably — append the path and method to\n // the handler's own name behind a double underscore, producing\n // `read_item_items__item_id__get`. The prefix is the part a human wrote.\n return route.operationId.split(\"__\")[0];\n }\n\n return route.summary || `${route.method}_${route.path}`;\n};\n\nconst slugify = (value: string): string => {\n const slug = value\n .replace(/[^a-zA-Z0-9_-]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^[_-]+|[_-]+$/g, \"\")\n .slice(0, MAX_BASE_LENGTH)\n // Trimming again: the slice can land mid-word and leave a trailing\n // separator that the first trim had nothing to remove.\n .replace(/[_-]+$/, \"\");\n\n return slug || \"operation\";\n};\n","import type { OpenApiDocument, OpenApiSchema } from \"./types.js\";\n\nexport type SchemaNormalizer = {\n /**\n * Every definition hoisted so far, keyed by its `$defs` name. Grows as\n * schemas are normalized; `collectDefinitions` picks the subset one tool\n * actually references.\n */\n definitions: Record<string, OpenApiSchema>;\n /** Rewrites one document schema fragment into standalone JSON Schema. */\n normalize: (schema: unknown) => OpenApiSchema;\n};\n\n/**\n * Keywords whose *keys* are arbitrary names rather than keywords, so the map\n * itself is not a schema and must not be run through the keyword rewrites — a\n * property genuinely named `nullable` or `required` would otherwise be\n * mangled into the keyword of the same name and lost.\n */\nconst SCHEMA_MAP_KEYWORDS = new Set([\n \"$defs\",\n \"definitions\",\n \"dependentSchemas\",\n \"patternProperties\",\n \"properties\",\n]);\n\n/**\n * Keywords holding instance data rather than sub-schemas. Descending into\n * these would rewrite a `$ref`-shaped key inside somebody's example payload.\n */\nconst VALUE_KEYWORDS = new Set([\n \"const\",\n \"default\",\n \"enum\",\n \"example\",\n \"examples\",\n]);\n\n/**\n * Builds a normalizer that turns document schemas into JSON Schema the MCP\n * client — and AJV, via `jsonSchemaAdapter` — will accept.\n *\n * Two jobs. It hoists every local `$ref` into a flat `$defs` table under a\n * name safe to write in a pointer, so a tool's input schema stands alone once\n * detached from the document. And it reconciles the places where OpenAPI is\n * not quite JSON Schema (see `normalizeKeywords`), which real documents lean\n * on constantly.\n */\nexport const createSchemaNormalizer = (\n document: OpenApiDocument,\n): SchemaNormalizer => {\n const definitions: Record<string, OpenApiSchema> = {};\n const namesByPointer = new Map<string, string>();\n const takenNames = new Set<string>();\n\n /**\n * Hoists whatever `pointer` addresses into `$defs`, returning its name.\n *\n * Names are slugified rather than reused verbatim: a `components.schemas`\n * key may contain a space, a slash or a tilde, each of which has to be\n * escaped to survive a round trip through a `$ref` pointer. Renaming once,\n * here, is simpler than encoding correctly at every use.\n */\n const hoist = (pointer: string): string | undefined => {\n const existing = namesByPointer.get(pointer);\n\n if (existing !== undefined) {\n return existing;\n }\n\n const target = readPointer(document, pointer);\n\n if (!target || typeof target !== \"object\") {\n return undefined;\n }\n\n const segments = pointer.split(\"/\");\n const base =\n slugify(decodeSegment(segments[segments.length - 1] ?? \"\")) || \"schema\";\n let name = base;\n\n for (let suffix = 2; takenNames.has(name); suffix++) {\n name = `${base}_${suffix}`;\n }\n\n takenNames.add(name);\n // Registered before the target is normalized, so that a schema that\n // references itself finds the name already reserved instead of recursing\n // forever.\n namesByPointer.set(pointer, name);\n definitions[name] = {};\n definitions[name] = normalize(target);\n\n return name;\n };\n\n const normalize = (value: unknown): OpenApiSchema => {\n const rewritten = rewrite(value);\n\n return rewritten &&\n typeof rewritten === \"object\" &&\n !Array.isArray(rewritten)\n ? (rewritten as OpenApiSchema)\n : {};\n };\n\n const rewrite = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => rewrite(entry));\n }\n\n if (!value || typeof value !== \"object\") {\n return value;\n }\n\n const source = value as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n\n for (const [key, entry] of Object.entries(source)) {\n if (key === \"$ref\" && typeof entry === \"string\") {\n const name = entry.startsWith(\"#\")\n ? hoist(toPointer(entry))\n : undefined;\n\n // A dangling or external ref becomes an unconstrained schema rather\n // than a compile error: one bad pointer in a large document should\n // cost that one field its validation, not the whole server.\n if (name !== undefined) {\n result.$ref = `#/$defs/${name}`;\n }\n\n continue;\n }\n\n if (VALUE_KEYWORDS.has(key)) {\n result[key] = entry;\n continue;\n }\n\n if (SCHEMA_MAP_KEYWORDS.has(key) && entry && typeof entry === \"object\") {\n result[key] = Object.fromEntries(\n Object.entries(entry as Record<string, unknown>).map(\n ([name, schema]) => [name, rewrite(schema)],\n ),\n );\n continue;\n }\n\n result[key] = rewrite(entry);\n }\n\n return normalizeKeywords(result);\n };\n\n return { definitions, normalize };\n};\n\n/**\n * Returns the transitive closure of the `$defs` a schema references, or\n * `undefined` when it references none.\n *\n * Only the ones actually reached: attaching every definition in the document\n * to every tool would multiply the `tools/list` payload by the tool count for\n * no benefit, and on a large document that alone can run to megabytes.\n */\nexport const collectDefinitions = (\n schema: unknown,\n definitions: Record<string, OpenApiSchema>,\n): Record<string, OpenApiSchema> | undefined => {\n const referenced = new Set<string>();\n const stack: unknown[] = [schema];\n\n while (stack.length > 0) {\n const node = stack.pop();\n\n if (Array.isArray(node)) {\n // One at a time rather than spread: see `hasExternalRef` in loadSpec.ts.\n for (const entry of node) {\n stack.push(entry);\n }\n\n continue;\n }\n\n if (!node || typeof node !== \"object\") {\n continue;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (key === \"$ref\" && typeof value === \"string\") {\n const name = value.startsWith(\"#/$defs/\")\n ? value.slice(\"#/$defs/\".length)\n : undefined;\n\n if (\n name !== undefined &&\n name in definitions &&\n !referenced.has(name)\n ) {\n referenced.add(name);\n stack.push(definitions[name]);\n }\n\n continue;\n }\n\n stack.push(value);\n }\n }\n\n if (referenced.size === 0) {\n return undefined;\n }\n\n return Object.fromEntries(\n [...referenced].sort().map((name) => [name, definitions[name]]),\n );\n};\n\n/**\n * Reconciles the three places OpenAPI diverges from the JSON Schema dialect\n * AJV compiles, each of which is common enough in published documents to be\n * worth handling rather than reporting.\n *\n * `nullable: true` widens a sibling `type` in OpenAPI 3.0 but is not itself a\n * JSON Schema keyword, and AJV rejects one that has no `type` to widen — which\n * documents do emit, as a sibling of `oneOf` or `$ref`. Draft-04's boolean\n * `exclusiveMinimum`/`exclusiveMaximum` qualify a sibling bound rather than\n * being one. And a `required: true` left over from draft-04 belongs on the\n * parent as a list, not on the property as a flag; there is nothing to\n * translate it into here, so it is dropped.\n */\nconst normalizeKeywords = (\n schema: Record<string, unknown>,\n): Record<string, unknown> => {\n if (\n !(\"nullable\" in schema) &&\n !(\"required\" in schema) &&\n typeof schema.exclusiveMaximum !== \"boolean\" &&\n typeof schema.exclusiveMinimum !== \"boolean\"\n ) {\n return schema;\n }\n\n const result = { ...schema };\n\n if (\"required\" in result && !Array.isArray(result.required)) {\n delete result.required;\n }\n\n for (const [flag, bound] of [\n [\"exclusiveMaximum\", \"maximum\"],\n [\"exclusiveMinimum\", \"minimum\"],\n ] as const) {\n if (typeof result[flag] !== \"boolean\") {\n continue;\n }\n\n const inclusive = result[bound];\n\n if (result[flag] === true && typeof inclusive === \"number\") {\n result[flag] = inclusive;\n delete result[bound];\n } else {\n delete result[flag];\n }\n }\n\n if (\"nullable\" in result) {\n const nullable = result.nullable;\n const type = result.type;\n\n delete result.nullable;\n\n if (nullable === true && typeof type === \"string\") {\n result.type = [type, \"null\"];\n } else if (nullable === true && Array.isArray(type)) {\n result.type = type.includes(\"null\") ? type : [...type, \"null\"];\n }\n }\n\n return result;\n};\n\n/**\n * Reads an RFC 6901 JSON Pointer, given as the path part of a fragment.\n *\n * Pointers are not followed through a `$ref` encountered mid-walk. They do not\n * need to be: a target that is itself a `$ref` normalizes into another `$ref`,\n * which hoists in turn, so chains resolve without a second traversal that a\n * cyclic document could trap.\n * Segments arrive percent-encoded (the bundler writes a path like\n * `/pets/{petId}` as `~1pets~1%7BpetId%7D`), so each needs decoding before its\n * `~1`/`~0` escapes are undone.\n */\nconst readPointer = (root: unknown, pointer: string): unknown => {\n if (pointer === \"\") {\n return root;\n }\n\n let node: unknown = root;\n\n for (const segment of pointer.split(\"/\").slice(1)) {\n node = (node as Record<string, unknown> | undefined)?.[\n decodeSegment(segment)\n ];\n }\n\n return node;\n};\n\n/**\n * Undoes the two encodings a pointer segment carries: percent-encoding, from\n * being written as a URI fragment, and then RFC 6901's `~1`/`~0` escapes.\n */\nconst decodeSegment = (segment: string): string => {\n let decoded = segment;\n\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n // Not valid percent-encoding, so it was never encoded: use it verbatim.\n }\n\n return decoded.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n};\n\nconst slugify = (value: string): string =>\n value\n .replace(/[^a-zA-Z0-9_.-]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst toPointer = (ref: string): string => ref.slice(1);\n","import type { JsonSchemaObject } from \"../jsonSchemaAdapter.js\";\nimport type { SchemaNormalizer } from \"./normalize.js\";\nimport type { HttpRoute, OpenApiParameter, OpenApiSchema } from \"./types.js\";\n\nimport { collectDefinitions } from \"./normalize.js\";\n\n/** Everything derived from one operation that building a request needs. */\nexport type ToolBinding = {\n /** How to encode the request body, when the operation takes one. */\n bodyEncoding?: BodyEncoding;\n /** A note about the operation, when part of it could not be modelled. */\n caveat?: string;\n inputSchema: JsonSchemaObject;\n outputSchema?: JsonSchemaObject;\n /** Tool argument name to where it belongs in the request. */\n parameters: Record<string, ParameterBinding>;\n /**\n * Set when the body is exposed as one argument rather than flattened into\n * several — an array body, or one the schema describes as a scalar.\n */\n wholeBodyKey?: string;\n};\n\ntype BodyEncoding = {\n contentType: string;\n kind: \"form\" | \"json\" | \"text\";\n};\n\ntype ParameterBinding =\n | { kind: \"body\"; name: string }\n | { kind: \"parameter\"; parameter: OpenApiParameter };\n\n/**\n * Flattens an operation's parameters and request body into the single object\n * schema an MCP tool takes, and records where each argument goes.\n *\n * Flattening is what makes these tools usable: a model filling one flat\n * argument list gets it right far more often than one asked to nest a body\n * under `body` and parameters under `params`. Names can collide across the\n * four parameter locations and the body, so a colliding parameter is suffixed\n * with its location (`id__query`) while a body property always keeps the bare\n * name — the body is the part a model is most likely to name correctly\n * unprompted.\n */\nexport const buildToolBinding = (\n route: HttpRoute,\n normalizer: SchemaNormalizer,\n withOutputSchema: boolean,\n): ToolBinding => {\n const body = describeBody(route, normalizer);\n const properties: Record<string, OpenApiSchema> = {};\n const parameters: Record<string, ParameterBinding> = {};\n const required: string[] = [];\n\n const byName = new Map<string, OpenApiParameter[]>();\n\n for (const parameter of route.parameters) {\n byName.set(parameter.name, [\n ...(byName.get(parameter.name) ?? []),\n parameter,\n ]);\n }\n\n for (const [name, occurrences] of byName) {\n const collides = occurrences.length > 1 || body.properties.has(name);\n\n for (const parameter of occurrences) {\n const key = collides ? `${name}__${parameter.in}` : name;\n\n properties[key] = describeParameter(parameter, normalizer);\n parameters[key] = { kind: \"parameter\", parameter };\n\n // The specification makes a path parameter required whether or not it\n // says so, since the URL cannot be built without it.\n if (parameter.in === \"path\" || parameter.required) {\n required.push(key);\n }\n }\n }\n\n for (const [name, property] of body.properties) {\n properties[name] = property.schema;\n parameters[name] = { kind: \"body\", name };\n\n if (property.required) {\n required.push(name);\n }\n }\n\n const inputSchema: JsonSchemaObject = {\n additionalProperties: false,\n properties,\n type: \"object\",\n ...(required.length > 0 ? { required: required.sort() } : {}),\n };\n\n const definitions = collectDefinitions(properties, normalizer.definitions);\n\n if (definitions) {\n inputSchema.$defs = definitions;\n }\n\n return {\n bodyEncoding: body.encoding,\n caveat: body.caveat,\n inputSchema,\n outputSchema: withOutputSchema\n ? buildOutputSchema(route, normalizer)\n : undefined,\n parameters,\n wholeBodyKey: body.wholeBodyKey,\n };\n};\n\ntype BodyProperty = { required: boolean; schema: OpenApiSchema };\n\ntype DescribedBody = {\n caveat?: string;\n encoding?: BodyEncoding;\n properties: Map<string, BodyProperty>;\n wholeBodyKey?: string;\n};\n\n/**\n * Picks the media type to send and turns its schema into tool arguments.\n *\n * `GET` is excluded outright. A body on a `GET` is legal in OpenAPI and\n * rejected by `fetch`, so a tool built from one would advertise arguments it\n * could never send; leaving them out states the limitation in the schema\n * instead of failing at call time.\n */\nconst describeBody = (\n route: HttpRoute,\n normalizer: SchemaNormalizer,\n): DescribedBody => {\n const properties = new Map<string, BodyProperty>();\n const content =\n route.method === \"get\" ? undefined : route.requestBody?.content;\n\n if (!content || Object.keys(content).length === 0) {\n return { properties };\n }\n\n const contentType = selectContentType(Object.keys(content));\n\n if (!contentType) {\n return {\n caveat: `This operation sends a ${Object.keys(content).sort().join(\" or \")} body, which this tool cannot construct.`,\n properties,\n };\n }\n\n const kind = encodingKindFor(contentType);\n const encoding = { contentType, kind };\n const required = route.requestBody?.required ?? false;\n const rawSchema = content[contentType]?.schema;\n const schema = rawSchema ? normalizer.normalize(rawSchema) : undefined;\n\n if (kind === \"text\") {\n properties.set(\"body\", { required, schema: schema ?? { type: \"string\" } });\n return { encoding, properties, wholeBodyKey: \"body\" };\n }\n\n if (!schema) {\n return { encoding, properties };\n }\n\n const object = flattenObject(schema, normalizer.definitions);\n\n if (object) {\n for (const [name, property] of Object.entries(object.properties)) {\n properties.set(name, {\n required: object.required.has(name),\n schema: property,\n });\n }\n\n return { encoding, properties };\n }\n\n // An array body, or one the document describes only by `$ref` or a\n // composition keyword: there is nothing to flatten, so the whole body\n // becomes one argument.\n properties.set(\"body\", { required, schema });\n\n return { encoding, properties, wholeBodyKey: \"body\" };\n};\n\n/**\n * How many `$defs` one response schema may pull in before it is dropped.\n *\n * Response schemas reference the document's shared components far more freely\n * than request bodies do, and `tools/list` carries every tool's at once. On\n * Stripe's document the median operation reaches 868 definitions and roughly\n * 1MB, which is 362MB across the server — unsendable, and slow well before it\n * fails. The same document splits cleanly either side of this number: schemas\n * either stay under 50 definitions or jump past 500, nothing in between, so a\n * cap in that gap drops the runaway schemas and keeps every tractable one.\n */\nconst MAX_OUTPUT_SCHEMA_DEFINITIONS = 100;\n\n/**\n * Derives a tool's `outputSchema` from its first successful JSON response.\n *\n * Only an object-typed response qualifies: MCP requires `structuredContent` to\n * be an object, so declaring an array or scalar schema would promise a shape\n * the protocol has no way to carry.\n */\nconst buildOutputSchema = (\n route: HttpRoute,\n normalizer: SchemaNormalizer,\n): JsonSchemaObject | undefined => {\n const status = Object.keys(route.responses)\n .filter((code) => /^2\\d\\d$/.test(code))\n .sort()[0];\n\n const content = status ? route.responses[status]?.content : undefined;\n const contentType = content && findJsonContentType(Object.keys(content));\n const raw = contentType ? content?.[contentType]?.schema : undefined;\n\n if (!raw) {\n return undefined;\n }\n\n const schema = normalizer.normalize(raw);\n\n if (!resolvesToObject(schema, normalizer.definitions)) {\n return undefined;\n }\n\n const definitions = collectDefinitions(schema, normalizer.definitions);\n\n // Dropping the schema, rather than truncating its definitions, is what keeps\n // the result usable: a schema whose `$ref`s no longer resolve is worse than\n // no schema at all. The tool falls back to returning text, which is what it\n // does for every operation that declares no response schema.\n if (\n definitions &&\n Object.keys(definitions).length > MAX_OUTPUT_SCHEMA_DEFINITIONS\n ) {\n return undefined;\n }\n\n return {\n ...schema,\n type: \"object\",\n ...(definitions ? { $defs: definitions } : {}),\n } as JsonSchemaObject;\n};\n\n/**\n * A parameter's own `description` and `deprecated` live beside its schema\n * rather than inside it, so they have to be folded in here or they never reach\n * the model — and the description is the main thing it has to go on when\n * deciding what to put in the argument.\n */\nconst describeParameter = (\n parameter: OpenApiParameter,\n normalizer: SchemaNormalizer,\n): OpenApiSchema => {\n const schema = normalizer.normalize(parameter.schema ?? { type: \"string\" });\n const description = [\n parameter.deprecated ? \"Deprecated.\" : undefined,\n parameter.description ?? (schema.description as string | undefined),\n ]\n .filter(Boolean)\n .join(\" \");\n\n return description ? { ...schema, description } : schema;\n};\n\n/**\n * Finds the properties of the object a body schema describes, following\n * `$ref`s and merging an `allOf` composition.\n *\n * Following the reference is what makes flattening work at all in practice:\n * almost every document defines its request bodies as a `$ref` to a named\n * component, and stopping at the reference would put the entire body behind a\n * single opaque argument.\n */\nconst flattenObject = (\n schema: OpenApiSchema | undefined,\n definitions: Record<string, OpenApiSchema>,\n depth = 0,\n):\n | { properties: Record<string, OpenApiSchema>; required: Set<string> }\n | undefined => {\n if (!schema || depth > 8) {\n return undefined;\n }\n\n if (typeof schema.$ref === \"string\" && schema.$ref.startsWith(\"#/$defs/\")) {\n return flattenObject(\n definitions[schema.$ref.slice(\"#/$defs/\".length)],\n definitions,\n depth + 1,\n );\n }\n\n if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n const properties: Record<string, OpenApiSchema> = {};\n const required = new Set<string>();\n\n for (const branch of schema.allOf) {\n const part = flattenObject(\n branch as OpenApiSchema,\n definitions,\n depth + 1,\n );\n\n if (!part) {\n return undefined;\n }\n\n Object.assign(properties, part.properties);\n\n for (const name of part.required) {\n required.add(name);\n }\n }\n\n return { properties, required };\n }\n\n const properties = schema.properties;\n\n if (\n !properties ||\n typeof properties !== \"object\" ||\n Array.isArray(properties)\n ) {\n return undefined;\n }\n\n return {\n properties: properties as Record<string, OpenApiSchema>,\n required: new Set(\n Array.isArray(schema.required) ? (schema.required as string[]) : [],\n ),\n };\n};\n\nconst encodingKindFor = (contentType: string): BodyEncoding[\"kind\"] => {\n if (contentType === \"application/x-www-form-urlencoded\") {\n return \"form\";\n }\n\n return contentType.startsWith(\"text/\") || contentType.includes(\"xml\")\n ? \"text\"\n : \"json\";\n};\n\nconst findJsonContentType = (available: string[]): string | undefined =>\n available.find((type) => type === \"application/json\") ??\n available.find((type) => /^application\\/([\\w.+-]+\\+)?json\\b/.test(type));\n\n/**\n * Whether a schema describes a JSON object, following `$ref`s and accepting a\n * composition whose branches all do.\n */\nconst resolvesToObject = (\n schema: OpenApiSchema | undefined,\n definitions: Record<string, OpenApiSchema>,\n depth = 0,\n): boolean => {\n if (!schema || depth > 8) {\n return false;\n }\n\n if (typeof schema.$ref === \"string\" && schema.$ref.startsWith(\"#/$defs/\")) {\n return resolvesToObject(\n definitions[schema.$ref.slice(\"#/$defs/\".length)],\n definitions,\n depth + 1,\n );\n }\n\n for (const keyword of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n const branches = schema[keyword];\n\n if (Array.isArray(branches) && branches.length > 0) {\n return branches.every((branch) =>\n resolvesToObject(branch as OpenApiSchema, definitions, depth + 1),\n );\n }\n }\n\n return schema.type === \"object\" || schema.properties !== undefined;\n};\n\nconst selectContentType = (available: string[]): string | undefined =>\n findJsonContentType(available) ??\n available.find((type) => type === \"application/x-www-form-urlencoded\") ??\n available.find((type) => type.startsWith(\"text/\") || type.includes(\"xml\"));\n","import type { FromOpenAPIOptions, HttpMethod, HttpRoute } from \"./types.js\";\n\nimport { toOperationSummary } from \"./routes.js\";\n\n/**\n * The ceiling that applies when a caller gave no `include`, `exclude` or\n * `maxTools` at all. Past this, conversion stops and says so.\n */\nexport const DEFAULT_MAX_TOOLS = 40;\n\n/**\n * Read-first ordering. Combined with the throw on exceeding a limit it makes\n * the tool list stable across runs, so a document that gains an operation does\n * not reshuffle every name a client has already seen.\n */\nconst METHOD_ORDER: Record<HttpMethod, number> = {\n delete: 4,\n get: 0,\n patch: 3,\n post: 1,\n put: 2,\n};\n\n/**\n * Narrows the document's operations to the ones that become tools.\n *\n * Deprecated operations are dropped unless `include` asks for them back:\n * a document marks an operation deprecated to steer callers away from it, and\n * a model reading a tool list has no other way to know.\n *\n * Exceeding a limit throws rather than truncating. Silently dropping\n * operations the caller asked for is the failure this option exists to\n * prevent, and a tool list that quietly changes length as a document grows is\n * worse than one that stops and asks.\n */\nexport const selectRoutes = (\n routes: HttpRoute[],\n options: Pick<FromOpenAPIOptions, \"exclude\" | \"include\" | \"maxTools\">,\n): HttpRoute[] => {\n const { exclude, include, maxTools } = options;\n\n let selected = include\n ? routes.filter((route) => include(toOperationSummary(route)))\n : routes.filter((route) => !route.deprecated);\n\n if (exclude) {\n selected = selected.filter((route) => !exclude(toOperationSummary(route)));\n }\n\n selected.sort(\n (a, b) =>\n METHOD_ORDER[a.method] - METHOD_ORDER[b.method] ||\n a.path.localeCompare(b.path),\n );\n\n const limit =\n maxTools ?? (include || exclude ? undefined : DEFAULT_MAX_TOOLS);\n\n if (limit !== undefined && selected.length > limit) {\n throw new Error(\n `fromOpenAPI selected ${selected.length} operations, over the limit of ${limit}` +\n (maxTools === undefined\n ? \" that applies when no selection is given. Turning a large document into a tool per operation produces a list most clients cannot work with, so this stops rather than guessing. Pass `include`/`exclude` to choose the operations you want, or `maxTools` to raise the limit deliberately.\"\n : \". Narrow the selection with `include`/`exclude`, or raise `maxTools`.\"),\n );\n }\n\n return selected;\n};\n","import type { ToolAnnotations } from \"@modelcontextprotocol/server\";\n\nimport type { ViteMCPAuth } from \"../ViteMCP.js\";\nimport type { FromOpenAPIOptions, HttpMethod, HttpRoute } from \"./types.js\";\n\nimport { jsonSchemaAdapter } from \"../jsonSchemaAdapter.js\";\nimport { ViteMCP } from \"../ViteMCP.js\";\nimport { executeRequest, resolveBaseUrl } from \"./executeRequest.js\";\nimport { loadSpec } from \"./loadSpec.js\";\nimport { generateToolNames } from \"./naming.js\";\nimport { createSchemaNormalizer } from \"./normalize.js\";\nimport { extractRoutes } from \"./routes.js\";\nimport { buildToolBinding } from \"./schemas.js\";\nimport { selectRoutes } from \"./selection.js\";\n\n/**\n * How each HTTP method is described to a client, so the annotations say\n * something the model can act on rather than repeating the default.\n *\n * `openWorldHint` is true throughout: every one of these tools calls somebody\n * else's API.\n */\nconst ANNOTATIONS: Record<HttpMethod, ToolAnnotations> = {\n delete: { destructiveHint: true, idempotentHint: true, readOnlyHint: false },\n get: { idempotentHint: true, readOnlyHint: true },\n patch: { destructiveHint: true, idempotentHint: false, readOnlyHint: false },\n post: { destructiveHint: false, idempotentHint: false, readOnlyHint: false },\n put: { destructiveHint: true, idempotentHint: true, readOnlyHint: false },\n};\n\nconst DEFAULT_MAX_RESPONSE_CHARACTERS = 1_000_000;\n\n/**\n * Turns an OpenAPI 3.x document into an MCP server, one tool per operation.\n *\n * ```ts\n * const server = await fromOpenAPI({\n * headers: (context) => ({ authorization: `Bearer ${context.auth?.token}` }),\n * include: (operation) => operation.tags.includes(\"pet\"),\n * spec: \"https://petstore3.swagger.io/api/v3/openapi.json\",\n * });\n * ```\n *\n * See `docs/openapi.md` for the option reference and the known limits.\n */\nexport const fromOpenAPI = async <T extends ViteMCPAuth = ViteMCPAuth>(\n options: FromOpenAPIOptions<T>,\n): Promise<ViteMCP<T>> => {\n const { document, origin } = await loadSpec(options.spec);\n const selected = selectRoutes(extractRoutes(document), options);\n const names = generateToolNames(selected, options.toolNames);\n const normalizer = createSchemaNormalizer(document);\n\n const server =\n options.server ??\n new ViteMCP<T>({\n description: document.info?.description,\n name: options.name ?? document.info?.title ?? \"OpenAPI\",\n version: options.version ?? semanticVersion(document.info?.version),\n });\n\n for (const route of selected) {\n const name = names.get(route);\n\n if (!name) {\n continue;\n }\n\n const binding = buildToolBinding(\n route,\n normalizer,\n options.outputSchema ?? false,\n );\n\n // Resolved once, at build time: an unusable `servers` entry should fail\n // while the server is being built, not on the first call of one tool.\n const baseUrl = resolveBaseUrl(\n route.servers ?? document.servers,\n origin,\n options.baseUrl,\n );\n\n server.addTool({\n annotations: {\n ...ANNOTATIONS[route.method],\n openWorldHint: true,\n ...(route.summary ? { title: route.summary } : {}),\n },\n description: describe(route, binding.caveat),\n execute: (args, context) =>\n executeRequest({\n args: args as Record<string, unknown>,\n baseUrl,\n binding,\n context,\n fetchImpl: options.fetch ?? globalThis.fetch,\n headers: options.headers,\n maxResponseCharacters:\n options.maxResponseCharacters ?? DEFAULT_MAX_RESPONSE_CHARACTERS,\n query: options.query,\n route,\n }),\n name,\n outputSchema: binding.outputSchema\n ? jsonSchemaAdapter(binding.outputSchema)\n : undefined,\n parameters: jsonSchemaAdapter(binding.inputSchema),\n timeoutMs: options.timeoutMs,\n });\n }\n\n return server;\n};\n\n/**\n * The description a model reads before choosing this tool. Both `summary` and\n * `description` are kept — the first is the one-line \"what\", the second the\n * caveats — and the method and path are appended because two operations on\n * neighbouring paths often share a summary word for word.\n */\nconst describe = (route: HttpRoute, caveat: string | undefined): string =>\n [\n route.deprecated ? \"Deprecated.\" : undefined,\n route.summary,\n route.description !== route.summary ? route.description : undefined,\n caveat,\n `${route.method.toUpperCase()} ${route.path}`,\n ]\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n/**\n * The document's own `info.version`, when it is one ViteMCP's server metadata\n * can carry. OpenAPI puts no constraint on the field, so documents version\n * themselves with dates and release names too.\n */\nconst semanticVersion = (\n version: string | undefined,\n): `${number}.${number}.${number}` =>\n version && /^\\d+\\.\\d+\\.\\d+$/.test(version)\n ? (version as `${number}.${number}.${number}`)\n : \"1.0.0\";\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/server/server/dist/openapi/index.cjs","../../src/openapi/parameters.ts","../../src/openapi/executeRequest.ts","../../src/openapi/loadSpec.ts","../../src/openapi/routes.ts","../../src/openapi/naming.ts","../../src/openapi/normalize.ts","../../src/openapi/schemas.ts","../../src/openapi/selection.ts","../../src/openapi/fromOpenAPI.ts"],"names":["resolve","readPointer","slugify","decodeSegment","properties"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B;AACA;ACEO,IAAM,qBAAA,EAAuB,CAClC,KAAA,EACA,SAAA,EACA,KAAA,EAAA,GACS;AACT,EAAA,MAAM,MAAA,mBAAQ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;AACE,EAAA;AACD,EAAA;AACD,EAAA;AACT;AAEM;AAeqB;AAGP,EAAA;AACD,EAAA;AACH,EAAA;AACK,EAAA;AAGjB,EAAA;AAEe,IAAA;AACC,IAAA;AACG,IAAA;AAClB,EAAA;AAEiB,EAAA;AACC,IAAA;AAER,IAAA;AACT,MAAA;AACF,IAAA;AAEgB,IAAA;AACd,MAAA;AACA,MAAA;AACQ,uBAAA;AACV,IAAA;AAIgB,IAAA;AACG,uBAAA;AACjB,MAAA;AACQ,MAAA;AACV,IAAA;AAEe,IAAA;AACA,MAAA;AACI,QAAA;AACA,QAAA;AACL,QAAA;AACZ,MAAA;AACa,MAAA;AACG,MAAA;AAEZ,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACW,QAAA;AACF,QAAA;AACT,QAAA;AAEe,QAAA;AACf,QAAA;AACD,MAAA;AACH,MAAA;AACc,MAAA;AAGF,MAAA;AACD,MAAA;AACZ,IAAA;AACH,EAAA;AAEO,EAAA;AACT;AAQoC;AAEb,EAAA;AACb,EAAA;AACgB,EAAA;AACtB,EAAA;AACgB,EAAA;AAGV;AAQR;ATs5BsB;AACA;AACA;AACA","file":"/home/runner/work/server/server/dist/openapi/index.cjs","sourcesContent":[null,"import type { OpenApiParameter } from \"./types.js\";\n\n/**\n * Serializes parameters the way the OpenAPI `style`/`explode` pair says to.\n *\n * Worth doing properly rather than stringifying: a `tags` array sent as\n * `?tags=a&tags=b` to an operation declaring `style: form, explode: false`\n * reaches a server that reads a single comma-joined value, and silently sees\n * only `a`. The default of `form` + `explode: true` is the common case, but it\n * is a default, not the rule.\n */\nexport const appendQueryParameter = (\n query: URLSearchParams,\n parameter: OpenApiParameter,\n value: unknown,\n): void => {\n const style = parameter.style ?? \"form\";\n const explode = parameter.explode ?? style === \"form\";\n const name = parameter.name;\n\n if (value === null || value === undefined) {\n return;\n }\n\n if (style === \"deepObject\") {\n if (isRecord(value)) {\n for (const [key, entry] of Object.entries(value)) {\n if (entry !== undefined) {\n query.append(`${name}[${key}]`, stringify(entry));\n }\n }\n }\n\n return;\n }\n\n if (explode) {\n if (Array.isArray(value)) {\n for (const entry of value) {\n query.append(name, stringify(entry));\n }\n\n return;\n }\n\n if (isRecord(value)) {\n for (const [key, entry] of Object.entries(value)) {\n if (entry !== undefined) {\n query.append(key, stringify(entry));\n }\n }\n\n return;\n }\n\n query.append(name, stringify(value));\n return;\n }\n\n const separator = DELIMITERS[style] ?? \",\";\n\n if (Array.isArray(value)) {\n query.append(name, value.map(stringify).join(separator));\n return;\n }\n\n if (isRecord(value)) {\n query.append(\n name,\n Object.entries(value)\n .flatMap(([key, entry]) =>\n entry === undefined ? [] : [key, stringify(entry)],\n )\n .join(separator),\n );\n return;\n }\n\n query.append(name, stringify(value));\n};\n\n/**\n * Renders the collected query parameters.\n *\n * `URLSearchParams` writes a space as `+`, which is the form-encoding rule\n * rather than the URL one; OpenAPI's `spaceDelimited` style means a literal\n * space. A `+` that was itself part of a value is already `%2B` by this point,\n * so every remaining one came from a space and can be rewritten safely.\n */\nexport const toQueryString = (query: URLSearchParams): string =>\n query.toString().replaceAll(\"+\", \"%20\");\n\n/**\n * Serializes a path parameter, percent-encoding the values but not the\n * delimiters that separate them — the delimiters are part of the path's\n * structure, and encoding them would hide it from the server.\n */\nexport const serializePathParameter = (\n parameter: OpenApiParameter,\n value: unknown,\n): string => {\n const style = parameter.style ?? \"simple\";\n const explode = parameter.explode ?? false;\n const body = serializeSimple(value, explode, parameter.name, style);\n\n if (style === \"label\") {\n return `.${body}`;\n }\n\n if (style === \"matrix\") {\n // An exploded matrix parameter already repeats `;name=` per entry.\n return explode && (Array.isArray(value) || isRecord(value))\n ? body\n : `;${parameter.name}=${body}`;\n }\n\n return body;\n};\n\n/**\n * Serializes a header or cookie parameter. Both default to a comma-joined\n * `simple` form; neither is percent-encoded, since header values are not a URL.\n */\nexport const serializeSimpleParameter = (\n parameter: OpenApiParameter,\n value: unknown,\n): string => {\n const explode = parameter.explode ?? false;\n\n if (Array.isArray(value)) {\n return value.map(stringify).join(\",\");\n }\n\n if (isRecord(value)) {\n return Object.entries(value)\n .flatMap(([key, entry]) =>\n entry === undefined\n ? []\n : [\n explode\n ? `${key}=${stringify(entry)}`\n : `${key},${stringify(entry)}`,\n ],\n )\n .join(\",\");\n }\n\n return stringify(value);\n};\n\nconst DELIMITERS: Record<string, string> = {\n form: \",\",\n pipeDelimited: \"|\",\n simple: \",\",\n spaceDelimited: \" \",\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst serializeSimple = (\n value: unknown,\n explode: boolean,\n name: string,\n style: string,\n): string => {\n const encode = (entry: unknown): string =>\n encodeURIComponent(stringify(entry));\n\n if (Array.isArray(value)) {\n if (style === \"matrix\" && explode) {\n return value.map((entry) => `;${name}=${encode(entry)}`).join(\"\");\n }\n\n if (style === \"label\" && explode) {\n return value.map(encode).join(\".\");\n }\n\n return value.map(encode).join(\",\");\n }\n\n if (isRecord(value)) {\n const entries = Object.entries(value).filter(\n ([, entry]) => entry !== undefined,\n );\n\n if (style === \"matrix\" && explode) {\n return entries.map(([key, entry]) => `;${key}=${encode(entry)}`).join(\"\");\n }\n\n if (explode) {\n return entries\n .map(([key, entry]) => `${encodeURIComponent(key)}=${encode(entry)}`)\n .join(style === \"label\" ? \".\" : \",\");\n }\n\n return entries\n .flatMap(([key, entry]) => [encodeURIComponent(key), encode(entry)])\n .join(\",\");\n }\n\n return encode(value);\n};\n\n/**\n * `JSON.stringify` for anything that is not already a primitive, so a nested\n * object reaching a scalar slot arrives as something a server can parse rather\n * than as `[object Object]`.\n */\nconst stringify = (value: unknown): string =>\n typeof value === \"object\" && value !== null\n ? JSON.stringify(value)\n : String(value);\n","import type {\n AudioContent,\n Context,\n ImageContent,\n StructuredResult,\n ViteMCPAuth,\n} from \"../ViteMCP.js\";\nimport type { ToolBinding } from \"./schemas.js\";\nimport type { ContextualHeaders, HttpRoute, OpenApiServer } from \"./types.js\";\n\nimport { UserError } from \"../ViteMCP.js\";\nimport {\n appendQueryParameter,\n serializePathParameter,\n serializeSimpleParameter,\n toQueryString,\n} from \"./parameters.js\";\n\nexport type ExecuteRequestOptions<T extends ViteMCPAuth> = {\n args: Record<string, unknown>;\n baseUrl: string;\n binding: ToolBinding;\n context: Context<T>;\n fetchImpl: typeof globalThis.fetch;\n headers?: ContextualHeaders<T>;\n maxResponseCharacters: number;\n query?: ContextualHeaders<T>;\n route: HttpRoute;\n};\n\nexport type ExecuteRequestResult =\n | AudioContent\n | ImageContent\n | string\n | StructuredResult<Record<string, unknown>>;\n\n/** Bodies over this are never treated as inline media, whatever the type. */\nconst MAX_INLINE_MEDIA_BYTES = 8 * 1024 * 1024;\n\nexport const executeRequest = async <T extends ViteMCPAuth>(\n options: ExecuteRequestOptions<T>,\n): Promise<ExecuteRequestResult> => {\n const { args, binding, context, route } = options;\n\n const pathValues = new Map<string, string>();\n const query = new URLSearchParams();\n const cookies: string[] = [];\n // `Headers` rather than an object, so that a header the operation names\n // `Content-Type` and one this function sets as `content-type` are recognised\n // as the same header instead of being sent twice.\n const headers = new Headers();\n const bodyValues: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(args)) {\n const binder = binding.parameters[key];\n\n if (!binder || value === undefined) {\n continue;\n }\n\n if (binder.kind === \"body\") {\n bodyValues[binder.name] = value;\n continue;\n }\n\n const { parameter } = binder;\n\n switch (parameter.in) {\n case \"cookie\":\n cookies.push(\n `${parameter.name}=${encodeCookieValue(\n serializeSimpleParameter(parameter, value),\n )}`,\n );\n break;\n case \"header\":\n setHeader(\n headers,\n parameter.name,\n serializeSimpleParameter(parameter, value),\n );\n break;\n case \"path\":\n pathValues.set(\n parameter.name,\n serializePathParameter(parameter, value),\n );\n break;\n case \"query\":\n appendQueryParameter(query, parameter, value);\n break;\n }\n }\n\n for (const [name, value] of Object.entries(\n await resolve(options.query, context),\n )) {\n query.delete(name);\n query.append(name, value);\n }\n\n if (cookies.length > 0) {\n setHeader(headers, \"cookie\", cookies.join(\"; \"));\n }\n\n const body = buildBody(binding, bodyValues, headers);\n\n // Applied last on purpose. These are the credentials the server was\n // configured with, and an operation that happens to declare a header or\n // query parameter of the same name must not let a model-supplied argument\n // replace them.\n for (const [name, value] of Object.entries(\n await resolve(options.headers, context),\n )) {\n setHeader(headers, name, value);\n }\n\n const url = new URL(buildPath(route.path, pathValues), `${options.baseUrl}/`);\n url.search = toQueryString(query);\n\n const response = await options.fetchImpl(url, {\n body,\n headers,\n method: route.method.toUpperCase(),\n // Forwarded so an abandoned tool call stops the upstream request too,\n // rather than leaving it running behind a settled promise.\n signal: context.signal,\n });\n\n return await readResponse(response, options);\n};\n\n/**\n * Resolves the address to send to: an explicit override, else the nearest\n * `servers` entry, with a relative URL joined against wherever the document\n * itself was loaded from.\n *\n * That last part is what makes documents like Swagger's own Petstore work —\n * its `servers` is `[{ url: \"/api/v3\" }]`, which a validator accepts and an\n * HTTP client cannot use.\n */\nexport const resolveBaseUrl = (\n servers: OpenApiServer[] | undefined,\n origin: string | undefined,\n override: string | undefined,\n): string => {\n if (override) {\n return trimSlash(override);\n }\n\n const server = servers?.[0];\n\n if (!server?.url) {\n throw new Error(\n \"The OpenAPI document declares no `servers`, so there is no address to call. Pass `baseUrl` to fromOpenAPI().\",\n );\n }\n\n let url = server.url;\n\n for (const [name, variable] of Object.entries(server.variables ?? {})) {\n url = url.replaceAll(`{${name}}`, variable.default);\n }\n\n try {\n return trimSlash(new URL(url).toString());\n } catch {\n if (!origin) {\n throw new Error(\n `The OpenAPI document's server URL (\"${url}\") is relative, and the document was not loaded from an http(s) URL, so there is nothing to resolve it against. Pass \\`baseUrl\\` to fromOpenAPI().`,\n );\n }\n\n return trimSlash(new URL(url, origin).toString());\n }\n};\n\n/**\n * Appends one form-encoded body property, bracketing anything nested.\n *\n * OpenAPI's `style`/`explode` pair only describes flat values, so a nested\n * object has no encoding the specification defines. Sending it as one JSON\n * string is the reading a server never expects: it wants fields. The bracket\n * convention — `metadata[order]=42`, as popularised by Stripe — is what the\n * APIs accepting nested form bodies actually parse, so it is what a nested\n * value serializes to here.\n */\nconst appendFormValue = (\n form: URLSearchParams,\n name: string,\n value: unknown,\n): void => {\n if (value === undefined) {\n return;\n }\n\n if (Array.isArray(value)) {\n // A flat array keeps OpenAPI's `explode: true` default and repeats the\n // key. Indices appear only once an entry is itself nested, where repeating\n // the key would run every entry's fields together into one.\n const nested = value.some(\n (entry) => typeof entry === \"object\" && entry !== null,\n );\n\n for (const [index, entry] of value.entries()) {\n appendFormValue(form, nested ? `${name}[${index}]` : name, entry);\n }\n\n return;\n }\n\n if (isRecord(value)) {\n for (const [key, entry] of Object.entries(value)) {\n appendFormValue(form, `${name}[${key}]`, entry);\n }\n\n return;\n }\n\n form.append(name, String(value));\n};\n\nconst buildBody = (\n binding: ToolBinding,\n values: Record<string, unknown>,\n headers: Headers,\n): string | undefined => {\n const encoding = binding.bodyEncoding;\n\n if (!encoding || Object.keys(values).length === 0) {\n return undefined;\n }\n\n const payload = binding.wholeBodyKey ? values[binding.wholeBodyKey] : values;\n\n if (payload === undefined) {\n return undefined;\n }\n\n if (!headers.has(\"content-type\")) {\n headers.set(\"content-type\", encoding.contentType);\n }\n\n if (encoding.kind === \"text\") {\n return typeof payload === \"string\" ? payload : JSON.stringify(payload);\n }\n\n if (encoding.kind === \"form\") {\n if (!isRecord(payload)) {\n return typeof payload === \"string\" ? payload : JSON.stringify(payload);\n }\n\n const form = new URLSearchParams();\n\n for (const [name, value] of Object.entries(payload)) {\n appendFormValue(form, name, value);\n }\n\n return form.toString();\n }\n\n return JSON.stringify(payload);\n};\n\n/**\n * Substitutes path parameters. Leading slash removed so the result is a\n * relative reference: resolved against a base of `https://host/api/v3/`, a\n * leading slash would discard the `/api/v3` prefix the document asked for.\n */\nconst buildPath = (template: string, values: Map<string, string>): string => {\n let path = template;\n\n for (const [name, value] of values) {\n path = path.replaceAll(`{${name}}`, value);\n }\n\n return path.replace(/^\\//, \"\");\n};\n\nconst resolve = async <T extends ViteMCPAuth>(\n source: ContextualHeaders<T> | undefined,\n context: Context<T>,\n): Promise<Record<string, string>> => {\n if (!source) {\n return {};\n }\n\n return typeof source === \"function\" ? await source(context) : source;\n};\n\nconst readResponse = async <T extends ViteMCPAuth>(\n response: Response,\n options: ExecuteRequestOptions<T>,\n): Promise<ExecuteRequestResult> => {\n const { binding, maxResponseCharacters, route } = options;\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const label = `${route.method.toUpperCase()} ${route.path}`;\n\n if (!response.ok) {\n throw new UserError(\n `${label} failed with ${response.status} ${response.statusText}: ${truncate(\n await response.text(),\n 2000,\n )}`,\n );\n }\n\n if (/^(?:audio|image)\\//.test(contentType) && !binding.outputSchema) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n\n if (bytes.byteLength <= MAX_INLINE_MEDIA_BYTES) {\n const mimeType = contentType.split(\";\")[0].trim();\n\n return contentType.startsWith(\"image/\")\n ? { data: toBase64(bytes), mimeType, type: \"image\" }\n : { data: toBase64(bytes), mimeType, type: \"audio\" };\n }\n\n throw new UserError(\n `${label} returned ${bytes.byteLength} bytes of ${contentType}, too large to return inline.`,\n );\n }\n\n const text = await response.text();\n const parsed = /\\bjson\\b/.test(contentType)\n ? tryParse(text.length <= maxResponseCharacters ? text : undefined)\n : undefined;\n\n // A JSON object goes back as structured content, which ViteMCP mirrors as\n // JSON text for clients that ignore it — so nothing is lost, and clients\n // that read it get a value instead of a string to re-parse.\n if (isRecord(parsed)) {\n return { structuredContent: parsed };\n }\n\n if (binding.outputSchema) {\n throw new UserError(\n `${label} declares a JSON object response but returned ${\n contentType || \"an untyped body\"\n }. Set \\`outputSchema: false\\` if this document's response schemas do not match the API.`,\n );\n }\n\n if (text === \"\") {\n return `${response.status} ${response.statusText}`.trim();\n }\n\n return parsed === undefined\n ? truncate(text, maxResponseCharacters)\n : truncate(JSON.stringify(parsed, null, 2), maxResponseCharacters);\n};\n\n/**\n * Escapes the characters RFC 6265 forbids in a cookie value, so an argument\n * containing `;` sets one cookie with a peculiar value rather than two\n * cookies. Everything else is left alone — `=` in particular, since base64\n * cookie values end in it.\n */\nconst encodeCookieValue = (value: string): string =>\n // eslint-disable-next-line no-control-regex\n value.replace(/[\\u0000-\\u001F\\u007F \",;\\\\]/g, (character) =>\n encodeURIComponent(character),\n );\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * `Headers` rejects a value containing a newline, which is the whole reason a\n * header parameter cannot be used to smuggle extra headers. Rethrown as a\n * `UserError` so a model that supplied one gets told what to fix instead of\n * the call failing as an internal error.\n */\nconst setHeader = (headers: Headers, name: string, value: string): void => {\n try {\n headers.set(name, value);\n } catch {\n throw new UserError(\n `\"${name}\" is not a valid header name, or the value given for it is not a valid header value.`,\n );\n }\n};\n\nconst toBase64 = (bytes: Uint8Array): string => {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(bytes).toString(\"base64\");\n }\n\n let binary = \"\";\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary);\n};\n\nconst trimSlash = (value: string): string => value.replace(/\\/+$/, \"\");\n\nconst truncate = (text: string, limit: number): string =>\n text.length <= limit\n ? text\n : `${text.slice(0, limit)}\\n\\n[truncated after ${limit} characters]`;\n\nconst tryParse = (text: string | undefined): unknown => {\n if (text === undefined) {\n return undefined;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n};\n","import type { OpenApiDocument } from \"./types.js\";\n\nimport { cancelResponseBody } from \"../cancelResponseBody.js\";\n\nexport type LoadedSpec = {\n document: OpenApiDocument;\n /**\n * The URL the document was loaded from, when it was loaded from one. Used to\n * resolve a relative `servers[0].url` against the document's own origin.\n */\n origin?: string;\n};\n\n/**\n * Loads an OpenAPI 3.x document, bundling external `$ref`s only when the\n * document actually has any.\n *\n * The bundler (`@apidevtools/swagger-parser`) is an optional peer dependency\n * imported on demand, not a hard one: it reaches for the filesystem and brings\n * its own JSON Schema stack with it. A single-file JSON document — which is\n * what most published specs are — needs neither, so the common path installs\n * and loads nothing extra. Multi-file documents and YAML are where the bundler\n * earns its weight, and only those pay for it.\n */\nexport const loadSpec = async (\n spec: Record<string, unknown> | string,\n): Promise<LoadedSpec> => {\n if (typeof spec !== \"string\") {\n return {\n document: hasExternalRef(spec)\n ? await bundle(spec)\n : assertOpenApi3(spec as OpenApiDocument),\n };\n }\n\n const origin = isHttpUrl(spec) ? spec : undefined;\n const parsed = parseJson(await readSpecText(spec));\n\n // Re-bundling from the original string rather than from `parsed` is\n // deliberate: external refs resolve against whichever document they were\n // found in, so handing the bundler an already-parsed object would resolve\n // every one of them against the process's working directory instead of the\n // document's own location.\n if (!parsed || hasExternalRef(parsed)) {\n return { document: await bundle(spec), origin };\n }\n\n return { document: assertOpenApi3(parsed), origin };\n};\n\nconst assertOpenApi3 = (document: OpenApiDocument): OpenApiDocument => {\n if (!document?.openapi?.startsWith(\"3.\")) {\n const found =\n document?.openapi ??\n (document?.swagger ? `Swagger ${document.swagger}` : undefined);\n\n throw new Error(\n `fromOpenAPI supports OpenAPI 3.x documents only (found ${\n found ?? \"no recognisable version field\"\n }). Convert a Swagger 2.0 document first — https://converter.swagger.io converts one in place.`,\n );\n }\n\n return document;\n};\n\nconst bundle = async (\n spec: Record<string, unknown> | string,\n): Promise<OpenApiDocument> => {\n let parser;\n\n try {\n parser = await import(\"@apidevtools/swagger-parser\");\n } catch {\n throw new Error(\n 'This document is YAML or has external $refs, which needs the \"@apidevtools/swagger-parser\" package. ' +\n \"Install it with: npm install @apidevtools/swagger-parser\",\n );\n }\n\n // The package ships CommonJS, so depending on the loader the class arrives\n // as the module namespace, as `.default`, or as `.default.default` — the\n // same unwrapping `jsonSchemaAdapter` does for AJV.\n const SwaggerParser = unwrapDefault(unwrapDefault(parser)) as {\n bundle: (spec: unknown) => Promise<unknown>;\n };\n\n return assertOpenApi3((await SwaggerParser.bundle(spec)) as OpenApiDocument);\n};\n\n/**\n * Reports whether any `$ref` in the document points outside it. Iterative\n * rather than recursive: a large document (Stripe's is ~200k lines) nests\n * deeply enough to matter, and this runs before anything else has looked at\n * it.\n */\nconst hasExternalRef = (root: unknown): boolean => {\n const seen = new WeakSet<object>();\n const stack: unknown[] = [root];\n\n while (stack.length > 0) {\n const node = stack.pop();\n\n if (!node || typeof node !== \"object\" || seen.has(node)) {\n continue;\n }\n\n seen.add(node);\n\n if (Array.isArray(node)) {\n // Pushed one at a time rather than spread: a document can hold an array\n // of tens of thousands of enum values, and spreading one of those into a\n // call exceeds the argument limit.\n for (const entry of node) {\n stack.push(entry);\n }\n\n continue;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (key === \"$ref\" && typeof value === \"string\") {\n if (!value.startsWith(\"#\")) {\n return true;\n }\n\n continue;\n }\n\n stack.push(value);\n }\n }\n\n return false;\n};\n\nconst isHttpUrl = (value: string): boolean =>\n value.startsWith(\"http://\") || value.startsWith(\"https://\");\n\nconst parseJson = (text: string): Record<string, unknown> | undefined => {\n try {\n const value: unknown = JSON.parse(text);\n return value && typeof value === \"object\"\n ? (value as Record<string, unknown>)\n : undefined;\n } catch {\n // Not JSON — YAML, most likely, which the bundler parses.\n return undefined;\n }\n};\n\nconst readSpecText = async (spec: string): Promise<string> => {\n if (isHttpUrl(spec)) {\n const response = await fetch(spec, {\n headers: { accept: \"application/json, text/yaml, */*\" },\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new Error(\n `Failed to fetch the OpenAPI document from ${spec}: ${response.status} ${response.statusText}`,\n );\n }\n\n return await response.text();\n }\n\n // Inline document text, rather than a path to one. Unambiguous for JSON;\n // YAML text is indistinguishable from a filename, so it is not accepted.\n if (spec.trimStart().startsWith(\"{\")) {\n return spec;\n }\n\n // Imported on demand so that bundling this module for a runtime without a\n // filesystem does not fail on an unused import.\n const { readFile } = await import(\"node:fs/promises\");\n\n return await readFile(spec, \"utf8\");\n};\n\nconst unwrapDefault = (value: unknown): unknown =>\n typeof value === \"object\" && value !== null && \"default\" in value\n ? (value as { default: unknown }).default\n : value;\n","import type {\n HttpMethod,\n HttpRoute,\n OpenApiDocument,\n OpenApiParameter,\n OpenApiPathItem,\n OpenApiRef,\n OpenApiRequestBody,\n OpenApiResponse,\n OperationSummary,\n} from \"./types.js\";\n\n/**\n * `head`, `options` and `trace` are omitted on purpose: they answer questions\n * about a resource rather than doing anything with it, so a tool built from\n * one gives a model nothing it can act on.\n */\nconst HTTP_METHODS: HttpMethod[] = [\"get\", \"post\", \"put\", \"patch\", \"delete\"];\n\n/** How many `$ref` hops to follow before assuming the document is cyclic. */\nconst MAX_REF_HOPS = 32;\n\n/**\n * Flattens a document's `paths` into a list of routes, resolving the\n * structural (non-schema) `$ref`s on path items, parameters, request bodies\n * and responses — `#/components/parameters/Limit` and the like.\n *\n * Every remaining `$ref` at this point is local (see `loadSpec`), so a plain\n * JSON Pointer lookup is enough. Schema `$ref`s are left alone: those are\n * handed to the client as part of the tool's input schema, where they are\n * resolved against `$defs` instead (see `schemas.ts`).\n */\nexport const extractRoutes = (document: OpenApiDocument): HttpRoute[] => {\n const routes: HttpRoute[] = [];\n\n for (const [path, declared] of Object.entries(document.paths ?? {})) {\n if (!declared || typeof declared !== \"object\") {\n continue;\n }\n\n const pathItem = resolvePathItem(document, declared);\n\n const pathLevelParameters = (pathItem.parameters ?? []).map((parameter) =>\n resolve<OpenApiParameter>(document, parameter),\n );\n\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n\n if (!operation) {\n continue;\n }\n\n const responses: Record<string, OpenApiResponse> = {};\n\n for (const [status, response] of Object.entries(\n operation.responses ?? {},\n )) {\n responses[status] = resolve<OpenApiResponse>(document, response) ?? {};\n }\n\n routes.push({\n deprecated: operation.deprecated ?? false,\n description: operation.description,\n method,\n operationId: operation.operationId,\n parameters: mergeParameters(\n pathLevelParameters,\n (operation.parameters ?? []).map((parameter) =>\n resolve<OpenApiParameter>(document, parameter),\n ),\n ),\n path,\n requestBody: operation.requestBody\n ? resolve<OpenApiRequestBody>(document, operation.requestBody)\n : undefined,\n responses,\n servers: operation.servers ?? pathItem.servers,\n summary: operation.summary,\n tags: operation.tags ?? [],\n });\n }\n }\n\n return routes;\n};\n\nexport const toOperationSummary = (route: HttpRoute): OperationSummary => ({\n deprecated: route.deprecated,\n description: route.description,\n method: route.method,\n operationId: route.operationId,\n path: route.path,\n summary: route.summary,\n tags: route.tags,\n});\n\n/**\n * An operation-level parameter overrides a path-level one with the same\n * name *and* location, per the OpenAPI specification — the pair is the\n * identity, so a `limit` in the query does not shadow a `limit` in the path.\n */\nconst mergeParameters = (\n pathLevel: OpenApiParameter[],\n operationLevel: OpenApiParameter[],\n): OpenApiParameter[] => {\n const overridden = new Set(\n operationLevel.map((parameter) => `${parameter.in}:${parameter.name}`),\n );\n\n return [\n ...pathLevel.filter(\n (parameter) => !overridden.has(`${parameter.in}:${parameter.name}`),\n ),\n ...operationLevel,\n ].filter((parameter) => parameter?.name && parameter.in);\n};\n\n/**\n * A path item with its `$ref` followed, chains included.\n *\n * What a referring item writes beside its `$ref` replaces the same field of\n * the item it points at, rather than merging with it. The bundler inlines a\n * shared item at its first referrer — that referrer's own fields folded in —\n * and turns each later referrer into a pointer at the first, so merging would\n * hand every path sharing the item the first path's parameters.\n *\n * A reference that points at nothing, or round in a circle, resolves to an\n * item with no operations and so to no routes, rather than throwing: one bad\n * pointer should cost its own path, not the document.\n */\nconst resolvePathItem = (\n document: OpenApiDocument,\n pathItem: OpenApiPathItem,\n): OpenApiPathItem => {\n const followed = new Set<string>();\n let resolved = pathItem;\n\n while (typeof resolved.$ref === \"string\" && !followed.has(resolved.$ref)) {\n followed.add(resolved.$ref);\n\n const { $ref, ...siblings } = resolved;\n const target = dereference(document, $ref);\n\n resolved = {\n ...(target && typeof target === \"object\" ? target : {}),\n ...siblings,\n };\n }\n\n return resolved;\n};\n\nconst resolve = <TValue>(\n document: OpenApiDocument,\n value: OpenApiRef | TValue,\n): TValue => {\n let node: unknown = value;\n\n for (let hop = 0; hop < MAX_REF_HOPS; hop++) {\n if (!node || typeof node !== \"object\" || !(\"$ref\" in node)) {\n return node as TValue;\n }\n\n node = dereference(document, (node as OpenApiRef).$ref);\n }\n\n throw new Error(\n `$ref chain longer than ${MAX_REF_HOPS} hops, which a cyclic document is the only way to produce.`,\n );\n};\n\n/** Reads what a local `$ref` points at, or `undefined` when nothing is there. */\nconst dereference = (document: OpenApiDocument, pointer: string): unknown => {\n if (!pointer.startsWith(\"#\")) {\n // Bundling turns every external ref into a local one; reaching here\n // means the bundler's output shape changed under us.\n throw new Error(`Unresolved external $ref after bundling: ${pointer}`);\n }\n\n return readPointer(document, pointer);\n};\n\n/**\n * Reads an RFC 6901 JSON Pointer written as a URI fragment, which is the form\n * the bundler emits — a path like `/pets/{petId}` becomes\n * `~1pets~1%7BpetId%7D`, so each segment needs percent-decoding *and* its\n * `~1`/`~0` escapes undone, in that order.\n */\nconst readPointer = (root: unknown, pointer: string): unknown => {\n const path = pointer.slice(1);\n\n if (path === \"\" || path === \"/\") {\n return root;\n }\n\n let node: unknown = root;\n\n for (const rawSegment of path.slice(1).split(\"/\")) {\n const segment = decodeSegment(rawSegment);\n node = (node as Record<string, unknown> | undefined)?.[segment];\n }\n\n return node;\n};\n\nconst decodeSegment = (segment: string): string => {\n let decoded = segment;\n\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n // A segment that is not valid percent-encoding is used verbatim, which is\n // what a document that never encoded it in the first place intended.\n }\n\n return decoded.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n};\n","import type { HttpRoute, OperationSummary } from \"./types.js\";\n\nimport { toOperationSummary } from \"./routes.js\";\n\n/**\n * Cap on a generated tool name. Nothing in MCP imposes one, but clients that\n * bridge to other tool-calling APIs do — 64 characters is the common limit —\n * and a name silently truncated by a client is worse than one shortened here.\n */\nconst MAX_NAME_LENGTH = 64;\n\n/** Leaves room for a `_<n>` collision suffix without exceeding the cap. */\nconst MAX_BASE_LENGTH = MAX_NAME_LENGTH - 5;\n\n/**\n * Assigns each route a unique tool name.\n *\n * Uniqueness is checked against the final name rather than the base, because a\n * document whose own `operationId`s already look suffixed — both `listPets`\n * and `listPets_2` — would otherwise produce two tools with the same name, and\n * only one of them would be reachable.\n */\nexport const generateToolNames = (\n routes: HttpRoute[],\n override: FromOpenAPIToolNames,\n): Map<HttpRoute, string> => {\n const names = new Map<HttpRoute, string>();\n const taken = new Set<string>();\n\n for (const route of routes) {\n const base = slugify(baseNameFor(route, override));\n let name = base;\n\n for (let suffix = 2; taken.has(name); suffix++) {\n name = `${base}_${suffix}`;\n }\n\n taken.add(name);\n names.set(route, name);\n }\n\n return names;\n};\n\ntype FromOpenAPIToolNames =\n | ((operation: OperationSummary) => string | undefined)\n | Record<string, string>\n | undefined;\n\nconst baseNameFor = (\n route: HttpRoute,\n override: FromOpenAPIToolNames,\n): string => {\n const explicit =\n typeof override === \"function\"\n ? override(toOperationSummary(route))\n : route.operationId\n ? override?.[route.operationId]\n : undefined;\n\n if (explicit) {\n return explicit;\n }\n\n if (route.operationId) {\n // Code generators — FastAPI's, notably — append the path and method to\n // the handler's own name behind a double underscore, producing\n // `read_item_items__item_id__get`. The prefix is the part a human wrote.\n return route.operationId.split(\"__\")[0];\n }\n\n return route.summary || `${route.method}_${route.path}`;\n};\n\nconst slugify = (value: string): string => {\n const slug = value\n .replace(/[^a-zA-Z0-9_-]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^[_-]+|[_-]+$/g, \"\")\n .slice(0, MAX_BASE_LENGTH)\n // Trimming again: the slice can land mid-word and leave a trailing\n // separator that the first trim had nothing to remove.\n .replace(/[_-]+$/, \"\");\n\n return slug || \"operation\";\n};\n","import type { OpenApiDocument, OpenApiSchema } from \"./types.js\";\n\nexport type SchemaNormalizer = {\n /**\n * Every definition hoisted so far, keyed by its `$defs` name. Grows as\n * schemas are normalized; `collectDefinitions` picks the subset one tool\n * actually references.\n */\n definitions: Record<string, OpenApiSchema>;\n /** Rewrites one document schema fragment into standalone JSON Schema. */\n normalize: (schema: unknown) => OpenApiSchema;\n};\n\n/**\n * Keywords whose *keys* are arbitrary names rather than keywords, so the map\n * itself is not a schema and must not be run through the keyword rewrites — a\n * property genuinely named `nullable` or `required` would otherwise be\n * mangled into the keyword of the same name and lost.\n */\nconst SCHEMA_MAP_KEYWORDS = new Set([\n \"$defs\",\n \"definitions\",\n \"dependentSchemas\",\n \"patternProperties\",\n \"properties\",\n]);\n\n/**\n * Keywords holding instance data rather than sub-schemas. Descending into\n * these would rewrite a `$ref`-shaped key inside somebody's example payload.\n */\nconst VALUE_KEYWORDS = new Set([\n \"const\",\n \"default\",\n \"enum\",\n \"example\",\n \"examples\",\n]);\n\n/**\n * Builds a normalizer that turns document schemas into JSON Schema the MCP\n * client — and AJV, via `jsonSchemaAdapter` — will accept.\n *\n * Two jobs. It hoists every local `$ref` into a flat `$defs` table under a\n * name safe to write in a pointer, so a tool's input schema stands alone once\n * detached from the document. And it reconciles the places where OpenAPI is\n * not quite JSON Schema (see `normalizeKeywords`), which real documents lean\n * on constantly.\n */\nexport const createSchemaNormalizer = (\n document: OpenApiDocument,\n): SchemaNormalizer => {\n const definitions: Record<string, OpenApiSchema> = {};\n const namesByPointer = new Map<string, string>();\n const takenNames = new Set<string>();\n\n /**\n * Hoists whatever `pointer` addresses into `$defs`, returning its name.\n *\n * Names are slugified rather than reused verbatim: a `components.schemas`\n * key may contain a space, a slash or a tilde, each of which has to be\n * escaped to survive a round trip through a `$ref` pointer. Renaming once,\n * here, is simpler than encoding correctly at every use.\n */\n const hoist = (pointer: string): string | undefined => {\n const existing = namesByPointer.get(pointer);\n\n if (existing !== undefined) {\n return existing;\n }\n\n const target = readPointer(document, pointer);\n\n if (!target || typeof target !== \"object\") {\n return undefined;\n }\n\n const segments = pointer.split(\"/\");\n const base =\n slugify(decodeSegment(segments[segments.length - 1] ?? \"\")) || \"schema\";\n let name = base;\n\n for (let suffix = 2; takenNames.has(name); suffix++) {\n name = `${base}_${suffix}`;\n }\n\n takenNames.add(name);\n // Registered before the target is normalized, so that a schema that\n // references itself finds the name already reserved instead of recursing\n // forever.\n namesByPointer.set(pointer, name);\n definitions[name] = {};\n definitions[name] = normalize(target);\n\n return name;\n };\n\n const normalize = (value: unknown): OpenApiSchema => {\n const rewritten = rewrite(value);\n\n return rewritten &&\n typeof rewritten === \"object\" &&\n !Array.isArray(rewritten)\n ? (rewritten as OpenApiSchema)\n : {};\n };\n\n const rewrite = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => rewrite(entry));\n }\n\n if (!value || typeof value !== \"object\") {\n return value;\n }\n\n const source = value as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n\n for (const [key, entry] of Object.entries(source)) {\n if (key === \"$ref\" && typeof entry === \"string\") {\n const name = entry.startsWith(\"#\")\n ? hoist(toPointer(entry))\n : undefined;\n\n // A dangling or external ref becomes an unconstrained schema rather\n // than a compile error: one bad pointer in a large document should\n // cost that one field its validation, not the whole server.\n if (name !== undefined) {\n result.$ref = `#/$defs/${name}`;\n }\n\n continue;\n }\n\n if (VALUE_KEYWORDS.has(key)) {\n result[key] = entry;\n continue;\n }\n\n if (SCHEMA_MAP_KEYWORDS.has(key) && entry && typeof entry === \"object\") {\n result[key] = Object.fromEntries(\n Object.entries(entry as Record<string, unknown>).map(\n ([name, schema]) => [name, rewrite(schema)],\n ),\n );\n continue;\n }\n\n result[key] = rewrite(entry);\n }\n\n return normalizeKeywords(result);\n };\n\n return { definitions, normalize };\n};\n\n/**\n * Returns the transitive closure of the `$defs` a schema references, or\n * `undefined` when it references none.\n *\n * Only the ones actually reached: attaching every definition in the document\n * to every tool would multiply the `tools/list` payload by the tool count for\n * no benefit, and on a large document that alone can run to megabytes.\n */\nexport const collectDefinitions = (\n schema: unknown,\n definitions: Record<string, OpenApiSchema>,\n): Record<string, OpenApiSchema> | undefined => {\n const referenced = new Set<string>();\n const stack: unknown[] = [schema];\n\n while (stack.length > 0) {\n const node = stack.pop();\n\n if (Array.isArray(node)) {\n // One at a time rather than spread: see `hasExternalRef` in loadSpec.ts.\n for (const entry of node) {\n stack.push(entry);\n }\n\n continue;\n }\n\n if (!node || typeof node !== \"object\") {\n continue;\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (key === \"$ref\" && typeof value === \"string\") {\n const name = value.startsWith(\"#/$defs/\")\n ? value.slice(\"#/$defs/\".length)\n : undefined;\n\n if (\n name !== undefined &&\n name in definitions &&\n !referenced.has(name)\n ) {\n referenced.add(name);\n stack.push(definitions[name]);\n }\n\n continue;\n }\n\n stack.push(value);\n }\n }\n\n if (referenced.size === 0) {\n return undefined;\n }\n\n return Object.fromEntries(\n [...referenced].sort().map((name) => [name, definitions[name]]),\n );\n};\n\n/**\n * Reconciles the three places OpenAPI diverges from the JSON Schema dialect\n * AJV compiles, each of which is common enough in published documents to be\n * worth handling rather than reporting.\n *\n * `nullable: true` widens a sibling `type` in OpenAPI 3.0 but is not itself a\n * JSON Schema keyword, and AJV rejects one that has no `type` to widen — which\n * documents do emit, as a sibling of `oneOf` or `$ref`. Draft-04's boolean\n * `exclusiveMinimum`/`exclusiveMaximum` qualify a sibling bound rather than\n * being one. And a `required: true` left over from draft-04 belongs on the\n * parent as a list, not on the property as a flag; there is nothing to\n * translate it into here, so it is dropped.\n */\nconst normalizeKeywords = (\n schema: Record<string, unknown>,\n): Record<string, unknown> => {\n if (\n !(\"nullable\" in schema) &&\n !(\"required\" in schema) &&\n typeof schema.exclusiveMaximum !== \"boolean\" &&\n typeof schema.exclusiveMinimum !== \"boolean\"\n ) {\n return schema;\n }\n\n const result = { ...schema };\n\n if (\"required\" in result && !Array.isArray(result.required)) {\n delete result.required;\n }\n\n for (const [flag, bound] of [\n [\"exclusiveMaximum\", \"maximum\"],\n [\"exclusiveMinimum\", \"minimum\"],\n ] as const) {\n if (typeof result[flag] !== \"boolean\") {\n continue;\n }\n\n const inclusive = result[bound];\n\n if (result[flag] === true && typeof inclusive === \"number\") {\n result[flag] = inclusive;\n delete result[bound];\n } else {\n delete result[flag];\n }\n }\n\n if (\"nullable\" in result) {\n const nullable = result.nullable;\n const type = result.type;\n\n delete result.nullable;\n\n if (nullable === true && typeof type === \"string\") {\n result.type = [type, \"null\"];\n } else if (nullable === true && Array.isArray(type)) {\n result.type = type.includes(\"null\") ? type : [...type, \"null\"];\n }\n }\n\n return result;\n};\n\n/**\n * Reads an RFC 6901 JSON Pointer, given as the path part of a fragment.\n *\n * Pointers are not followed through a `$ref` encountered mid-walk. They do not\n * need to be: a target that is itself a `$ref` normalizes into another `$ref`,\n * which hoists in turn, so chains resolve without a second traversal that a\n * cyclic document could trap.\n * Segments arrive percent-encoded (the bundler writes a path like\n * `/pets/{petId}` as `~1pets~1%7BpetId%7D`), so each needs decoding before its\n * `~1`/`~0` escapes are undone.\n */\nconst readPointer = (root: unknown, pointer: string): unknown => {\n if (pointer === \"\") {\n return root;\n }\n\n let node: unknown = root;\n\n for (const segment of pointer.split(\"/\").slice(1)) {\n node = (node as Record<string, unknown> | undefined)?.[\n decodeSegment(segment)\n ];\n }\n\n return node;\n};\n\n/**\n * Undoes the two encodings a pointer segment carries: percent-encoding, from\n * being written as a URI fragment, and then RFC 6901's `~1`/`~0` escapes.\n */\nconst decodeSegment = (segment: string): string => {\n let decoded = segment;\n\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n // Not valid percent-encoding, so it was never encoded: use it verbatim.\n }\n\n return decoded.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n};\n\nconst slugify = (value: string): string =>\n value\n .replace(/[^a-zA-Z0-9_.-]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst toPointer = (ref: string): string => ref.slice(1);\n","import type { JsonSchemaObject } from \"../jsonSchemaAdapter.js\";\nimport type { SchemaNormalizer } from \"./normalize.js\";\nimport type { HttpRoute, OpenApiParameter, OpenApiSchema } from \"./types.js\";\n\nimport { collectDefinitions } from \"./normalize.js\";\n\n/** Everything derived from one operation that building a request needs. */\nexport type ToolBinding = {\n /** How to encode the request body, when the operation takes one. */\n bodyEncoding?: BodyEncoding;\n /** A note about the operation, when part of it could not be modelled. */\n caveat?: string;\n inputSchema: JsonSchemaObject;\n outputSchema?: JsonSchemaObject;\n /** Tool argument name to where it belongs in the request. */\n parameters: Record<string, ParameterBinding>;\n /**\n * Set when the body is exposed as one argument rather than flattened into\n * several — an array body, or one the schema describes as a scalar.\n */\n wholeBodyKey?: string;\n};\n\ntype BodyEncoding = {\n contentType: string;\n kind: \"form\" | \"json\" | \"text\";\n};\n\ntype ParameterBinding =\n | { kind: \"body\"; name: string }\n | { kind: \"parameter\"; parameter: OpenApiParameter };\n\n/**\n * Flattens an operation's parameters and request body into the single object\n * schema an MCP tool takes, and records where each argument goes.\n *\n * Flattening is what makes these tools usable: a model filling one flat\n * argument list gets it right far more often than one asked to nest a body\n * under `body` and parameters under `params`. Names can collide across the\n * four parameter locations and the body, so a colliding parameter is suffixed\n * with its location (`id__query`) while a body property always keeps the bare\n * name — the body is the part a model is most likely to name correctly\n * unprompted.\n */\nexport const buildToolBinding = (\n route: HttpRoute,\n normalizer: SchemaNormalizer,\n withOutputSchema: boolean,\n): ToolBinding => {\n const body = describeBody(route, normalizer);\n const properties: Record<string, OpenApiSchema> = {};\n const parameters: Record<string, ParameterBinding> = {};\n const required: string[] = [];\n\n const byName = new Map<string, OpenApiParameter[]>();\n\n for (const parameter of route.parameters) {\n byName.set(parameter.name, [\n ...(byName.get(parameter.name) ?? []),\n parameter,\n ]);\n }\n\n for (const [name, occurrences] of byName) {\n const collides = occurrences.length > 1 || body.properties.has(name);\n\n for (const parameter of occurrences) {\n const key = collides ? `${name}__${parameter.in}` : name;\n\n properties[key] = describeParameter(parameter, normalizer);\n parameters[key] = { kind: \"parameter\", parameter };\n\n // The specification makes a path parameter required whether or not it\n // says so, since the URL cannot be built without it.\n if (parameter.in === \"path\" || parameter.required) {\n required.push(key);\n }\n }\n }\n\n for (const [name, property] of body.properties) {\n properties[name] = property.schema;\n parameters[name] = { kind: \"body\", name };\n\n if (property.required) {\n required.push(name);\n }\n }\n\n const inputSchema: JsonSchemaObject = {\n additionalProperties: false,\n properties,\n type: \"object\",\n ...(required.length > 0 ? { required: required.sort() } : {}),\n };\n\n const definitions = collectDefinitions(properties, normalizer.definitions);\n\n if (definitions) {\n inputSchema.$defs = definitions;\n }\n\n return {\n bodyEncoding: body.encoding,\n caveat: body.caveat,\n inputSchema,\n outputSchema: withOutputSchema\n ? buildOutputSchema(route, normalizer)\n : undefined,\n parameters,\n wholeBodyKey: body.wholeBodyKey,\n };\n};\n\ntype BodyProperty = { required: boolean; schema: OpenApiSchema };\n\ntype DescribedBody = {\n caveat?: string;\n encoding?: BodyEncoding;\n properties: Map<string, BodyProperty>;\n wholeBodyKey?: string;\n};\n\n/**\n * Picks the media type to send and turns its schema into tool arguments.\n *\n * `GET` is excluded outright. A body on a `GET` is legal in OpenAPI and\n * rejected by `fetch`, so a tool built from one would advertise arguments it\n * could never send; leaving them out states the limitation in the schema\n * instead of failing at call time.\n */\nconst describeBody = (\n route: HttpRoute,\n normalizer: SchemaNormalizer,\n): DescribedBody => {\n const properties = new Map<string, BodyProperty>();\n const content =\n route.method === \"get\" ? undefined : route.requestBody?.content;\n\n if (!content || Object.keys(content).length === 0) {\n return { properties };\n }\n\n const contentType = selectContentType(Object.keys(content));\n\n if (!contentType) {\n return {\n caveat: `This operation sends a ${Object.keys(content).sort().join(\" or \")} body, which this tool cannot construct.`,\n properties,\n };\n }\n\n const kind = encodingKindFor(contentType);\n const encoding = { contentType, kind };\n const required = route.requestBody?.required ?? false;\n const rawSchema = content[contentType]?.schema;\n const schema = rawSchema ? normalizer.normalize(rawSchema) : undefined;\n\n if (kind === \"text\") {\n properties.set(\"body\", { required, schema: schema ?? { type: \"string\" } });\n return { encoding, properties, wholeBodyKey: \"body\" };\n }\n\n if (!schema) {\n return { encoding, properties };\n }\n\n const object = flattenObject(schema, normalizer.definitions);\n\n // An object that declares no properties is not one without a body: it is a\n // dictionary, whose keys are the caller's to choose, or an object that must\n // be sent empty. Flattened, either would leave the tool no argument to carry\n // it in. Generators write a dictionary exactly this way, with an empty\n // `properties` beside `additionalProperties`.\n if (object && Object.keys(object.properties).length > 0) {\n for (const [name, property] of Object.entries(object.properties)) {\n properties.set(name, {\n required: object.required.has(name),\n schema: property,\n });\n }\n\n return { encoding, properties };\n }\n\n // An array body, a dictionary, or one the document describes only by `$ref`\n // or a composition keyword: there is nothing to flatten, so the whole body\n // becomes one argument.\n properties.set(\"body\", { required, schema });\n\n return { encoding, properties, wholeBodyKey: \"body\" };\n};\n\n/**\n * How many `$defs` one response schema may pull in before it is dropped.\n *\n * Response schemas reference the document's shared components far more freely\n * than request bodies do, and `tools/list` carries every tool's at once. On\n * Stripe's document the median operation reaches 868 definitions and roughly\n * 1MB, which is 362MB across the server — unsendable, and slow well before it\n * fails. The same document splits cleanly either side of this number: schemas\n * either stay under 50 definitions or jump past 500, nothing in between, so a\n * cap in that gap drops the runaway schemas and keeps every tractable one.\n */\nconst MAX_OUTPUT_SCHEMA_DEFINITIONS = 100;\n\n/**\n * Derives a tool's `outputSchema` from its first successful JSON response.\n *\n * Only an object-typed response qualifies: MCP requires `structuredContent` to\n * be an object, so declaring an array or scalar schema would promise a shape\n * the protocol has no way to carry.\n */\nconst buildOutputSchema = (\n route: HttpRoute,\n normalizer: SchemaNormalizer,\n): JsonSchemaObject | undefined => {\n const status = Object.keys(route.responses)\n .filter((code) => /^2\\d\\d$/.test(code))\n .sort()[0];\n\n const content = status ? route.responses[status]?.content : undefined;\n const contentType = content && findJsonContentType(Object.keys(content));\n const raw = contentType ? content?.[contentType]?.schema : undefined;\n\n if (!raw) {\n return undefined;\n }\n\n const schema = normalizer.normalize(raw);\n\n if (!resolvesToObject(schema, normalizer.definitions)) {\n return undefined;\n }\n\n const definitions = collectDefinitions(schema, normalizer.definitions);\n\n // Dropping the schema, rather than truncating its definitions, is what keeps\n // the result usable: a schema whose `$ref`s no longer resolve is worse than\n // no schema at all. The tool falls back to returning text, which is what it\n // does for every operation that declares no response schema.\n if (\n definitions &&\n Object.keys(definitions).length > MAX_OUTPUT_SCHEMA_DEFINITIONS\n ) {\n return undefined;\n }\n\n return {\n ...schema,\n type: \"object\",\n ...(definitions ? { $defs: definitions } : {}),\n } as JsonSchemaObject;\n};\n\n/**\n * A parameter's own `description` and `deprecated` live beside its schema\n * rather than inside it, so they have to be folded in here or they never reach\n * the model — and the description is the main thing it has to go on when\n * deciding what to put in the argument.\n */\nconst describeParameter = (\n parameter: OpenApiParameter,\n normalizer: SchemaNormalizer,\n): OpenApiSchema => {\n const schema = normalizer.normalize(parameter.schema ?? { type: \"string\" });\n const description = [\n parameter.deprecated ? \"Deprecated.\" : undefined,\n parameter.description ?? (schema.description as string | undefined),\n ]\n .filter(Boolean)\n .join(\" \");\n\n return description ? { ...schema, description } : schema;\n};\n\n/**\n * Finds the properties of the object a body schema describes, following\n * `$ref`s and merging an `allOf` composition.\n *\n * Following the reference is what makes flattening work at all in practice:\n * almost every document defines its request bodies as a `$ref` to a named\n * component, and stopping at the reference would put the entire body behind a\n * single opaque argument.\n */\nconst flattenObject = (\n schema: OpenApiSchema | undefined,\n definitions: Record<string, OpenApiSchema>,\n depth = 0,\n):\n | { properties: Record<string, OpenApiSchema>; required: Set<string> }\n | undefined => {\n if (!schema || depth > 8) {\n return undefined;\n }\n\n if (typeof schema.$ref === \"string\" && schema.$ref.startsWith(\"#/$defs/\")) {\n return flattenObject(\n definitions[schema.$ref.slice(\"#/$defs/\".length)],\n definitions,\n depth + 1,\n );\n }\n\n if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n const properties: Record<string, OpenApiSchema> = {};\n const required = new Set<string>();\n\n for (const branch of schema.allOf) {\n const part = flattenObject(\n branch as OpenApiSchema,\n definitions,\n depth + 1,\n );\n\n if (!part) {\n return undefined;\n }\n\n Object.assign(properties, part.properties);\n\n for (const name of part.required) {\n required.add(name);\n }\n }\n\n return { properties, required };\n }\n\n const properties = schema.properties;\n\n if (\n !properties ||\n typeof properties !== \"object\" ||\n Array.isArray(properties)\n ) {\n return undefined;\n }\n\n return {\n properties: properties as Record<string, OpenApiSchema>,\n required: new Set(\n Array.isArray(schema.required) ? (schema.required as string[]) : [],\n ),\n };\n};\n\nconst encodingKindFor = (contentType: string): BodyEncoding[\"kind\"] => {\n if (contentType === \"application/x-www-form-urlencoded\") {\n return \"form\";\n }\n\n return contentType.startsWith(\"text/\") || contentType.includes(\"xml\")\n ? \"text\"\n : \"json\";\n};\n\nconst findJsonContentType = (available: string[]): string | undefined =>\n available.find((type) => type === \"application/json\") ??\n available.find((type) => /^application\\/([\\w.+-]+\\+)?json\\b/.test(type));\n\n/**\n * Whether a schema describes a JSON object, following `$ref`s and accepting a\n * composition whose branches all do.\n */\nconst resolvesToObject = (\n schema: OpenApiSchema | undefined,\n definitions: Record<string, OpenApiSchema>,\n depth = 0,\n): boolean => {\n if (!schema || depth > 8) {\n return false;\n }\n\n if (typeof schema.$ref === \"string\" && schema.$ref.startsWith(\"#/$defs/\")) {\n return resolvesToObject(\n definitions[schema.$ref.slice(\"#/$defs/\".length)],\n definitions,\n depth + 1,\n );\n }\n\n for (const keyword of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n const branches = schema[keyword];\n\n if (Array.isArray(branches) && branches.length > 0) {\n return branches.every((branch) =>\n resolvesToObject(branch as OpenApiSchema, definitions, depth + 1),\n );\n }\n }\n\n return schema.type === \"object\" || schema.properties !== undefined;\n};\n\nconst selectContentType = (available: string[]): string | undefined =>\n findJsonContentType(available) ??\n available.find((type) => type === \"application/x-www-form-urlencoded\") ??\n available.find((type) => type.startsWith(\"text/\") || type.includes(\"xml\"));\n","import type { FromOpenAPIOptions, HttpMethod, HttpRoute } from \"./types.js\";\n\nimport { toOperationSummary } from \"./routes.js\";\n\n/**\n * The ceiling that applies when a caller gave no `include`, `exclude` or\n * `maxTools` at all. Past this, conversion stops and says so.\n */\nexport const DEFAULT_MAX_TOOLS = 40;\n\n/**\n * Read-first ordering. Combined with the throw on exceeding a limit it makes\n * the tool list stable across runs, so a document that gains an operation does\n * not reshuffle every name a client has already seen.\n */\nconst METHOD_ORDER: Record<HttpMethod, number> = {\n delete: 4,\n get: 0,\n patch: 3,\n post: 1,\n put: 2,\n};\n\n/**\n * Narrows the document's operations to the ones that become tools.\n *\n * Deprecated operations are dropped unless `include` asks for them back:\n * a document marks an operation deprecated to steer callers away from it, and\n * a model reading a tool list has no other way to know.\n *\n * Exceeding a limit throws rather than truncating. Silently dropping\n * operations the caller asked for is the failure this option exists to\n * prevent, and a tool list that quietly changes length as a document grows is\n * worse than one that stops and asks.\n */\nexport const selectRoutes = (\n routes: HttpRoute[],\n options: Pick<FromOpenAPIOptions, \"exclude\" | \"include\" | \"maxTools\">,\n): HttpRoute[] => {\n const { exclude, include, maxTools } = options;\n\n let selected = include\n ? routes.filter((route) => include(toOperationSummary(route)))\n : routes.filter((route) => !route.deprecated);\n\n if (exclude) {\n selected = selected.filter((route) => !exclude(toOperationSummary(route)));\n }\n\n selected.sort(\n (a, b) =>\n METHOD_ORDER[a.method] - METHOD_ORDER[b.method] ||\n a.path.localeCompare(b.path),\n );\n\n const limit =\n maxTools ?? (include || exclude ? undefined : DEFAULT_MAX_TOOLS);\n\n if (limit !== undefined && selected.length > limit) {\n throw new Error(\n `fromOpenAPI selected ${selected.length} operations, over the limit of ${limit}` +\n (maxTools === undefined\n ? \" that applies when no selection is given. Turning a large document into a tool per operation produces a list most clients cannot work with, so this stops rather than guessing. Pass `include`/`exclude` to choose the operations you want, or `maxTools` to raise the limit deliberately.\"\n : \". Narrow the selection with `include`/`exclude`, or raise `maxTools`.\"),\n );\n }\n\n return selected;\n};\n","import type { ToolAnnotations } from \"@modelcontextprotocol/server\";\n\nimport type { ViteMCPAuth } from \"../ViteMCP.js\";\nimport type { FromOpenAPIOptions, HttpMethod, HttpRoute } from \"./types.js\";\n\nimport { jsonSchemaAdapter } from \"../jsonSchemaAdapter.js\";\nimport { ViteMCP } from \"../ViteMCP.js\";\nimport { executeRequest, resolveBaseUrl } from \"./executeRequest.js\";\nimport { loadSpec } from \"./loadSpec.js\";\nimport { generateToolNames } from \"./naming.js\";\nimport { createSchemaNormalizer } from \"./normalize.js\";\nimport { extractRoutes } from \"./routes.js\";\nimport { buildToolBinding } from \"./schemas.js\";\nimport { selectRoutes } from \"./selection.js\";\n\n/**\n * How each HTTP method is described to a client, so the annotations say\n * something the model can act on rather than repeating the default.\n *\n * `openWorldHint` is true throughout: every one of these tools calls somebody\n * else's API.\n */\nconst ANNOTATIONS: Record<HttpMethod, ToolAnnotations> = {\n delete: { destructiveHint: true, idempotentHint: true, readOnlyHint: false },\n get: { idempotentHint: true, readOnlyHint: true },\n patch: { destructiveHint: true, idempotentHint: false, readOnlyHint: false },\n post: { destructiveHint: false, idempotentHint: false, readOnlyHint: false },\n put: { destructiveHint: true, idempotentHint: true, readOnlyHint: false },\n};\n\nconst DEFAULT_MAX_RESPONSE_CHARACTERS = 1_000_000;\n\n/**\n * Turns an OpenAPI 3.x document into an MCP server, one tool per operation.\n *\n * ```ts\n * const server = await fromOpenAPI({\n * headers: (context) => ({ authorization: `Bearer ${context.auth?.token}` }),\n * include: (operation) => operation.tags.includes(\"pet\"),\n * spec: \"https://petstore3.swagger.io/api/v3/openapi.json\",\n * });\n * ```\n *\n * See `docs/openapi.md` for the option reference and the known limits.\n */\nexport const fromOpenAPI = async <T extends ViteMCPAuth = ViteMCPAuth>(\n options: FromOpenAPIOptions<T>,\n): Promise<ViteMCP<T>> => {\n const { document, origin } = await loadSpec(options.spec);\n const selected = selectRoutes(extractRoutes(document), options);\n const names = generateToolNames(selected, options.toolNames);\n const normalizer = createSchemaNormalizer(document);\n\n const server =\n options.server ??\n new ViteMCP<T>({\n description: document.info?.description,\n name: options.name ?? document.info?.title ?? \"OpenAPI\",\n version: options.version ?? semanticVersion(document.info?.version),\n });\n\n for (const route of selected) {\n const name = names.get(route);\n\n if (!name) {\n continue;\n }\n\n const binding = buildToolBinding(\n route,\n normalizer,\n options.outputSchema ?? false,\n );\n\n // Resolved once, at build time: an unusable `servers` entry should fail\n // while the server is being built, not on the first call of one tool.\n const baseUrl = resolveBaseUrl(\n route.servers ?? document.servers,\n origin,\n options.baseUrl,\n );\n\n server.addTool({\n annotations: {\n ...ANNOTATIONS[route.method],\n openWorldHint: true,\n ...(route.summary ? { title: route.summary } : {}),\n },\n description: describe(route, binding.caveat),\n execute: (args, context) =>\n executeRequest({\n args: args as Record<string, unknown>,\n baseUrl,\n binding,\n context,\n fetchImpl: options.fetch ?? globalThis.fetch,\n headers: options.headers,\n maxResponseCharacters:\n options.maxResponseCharacters ?? DEFAULT_MAX_RESPONSE_CHARACTERS,\n query: options.query,\n route,\n }),\n name,\n outputSchema: binding.outputSchema\n ? jsonSchemaAdapter(binding.outputSchema)\n : undefined,\n parameters: jsonSchemaAdapter(binding.inputSchema),\n timeoutMs: options.timeoutMs,\n });\n }\n\n return server;\n};\n\n/**\n * The description a model reads before choosing this tool. Both `summary` and\n * `description` are kept — the first is the one-line \"what\", the second the\n * caveats — and the method and path are appended because two operations on\n * neighbouring paths often share a summary word for word.\n */\nconst describe = (route: HttpRoute, caveat: string | undefined): string =>\n [\n route.deprecated ? \"Deprecated.\" : undefined,\n route.summary,\n route.description !== route.summary ? route.description : undefined,\n caveat,\n `${route.method.toUpperCase()} ${route.path}`,\n ]\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n/**\n * The document's own `info.version`, when it is one ViteMCP's server metadata\n * can carry. OpenAPI puts no constraint on the field, so documents version\n * themselves with dates and release names too.\n */\nconst semanticVersion = (\n version: string | undefined,\n): `${number}.${number}.${number}` =>\n version && /^\\d+\\.\\d+\\.\\d+$/.test(version)\n ? (version as `${number}.${number}.${number}`)\n : \"1.0.0\";\n"]}
|
package/dist/openapi/index.d.cts
CHANGED
|
@@ -4,7 +4,7 @@ import '@standard-schema/spec';
|
|
|
4
4
|
import 'hono';
|
|
5
5
|
import 'hono/cors';
|
|
6
6
|
import 'timers/promises';
|
|
7
|
-
import '../OAuthProvider-
|
|
7
|
+
import '../OAuthProvider-BaPwgWny.cjs';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* A value that may depend on the calling request — a bearer token derived from
|
package/dist/openapi/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import '@standard-schema/spec';
|
|
|
4
4
|
import 'hono';
|
|
5
5
|
import 'hono/cors';
|
|
6
6
|
import 'timers/promises';
|
|
7
|
-
import '../OAuthProvider-
|
|
7
|
+
import '../OAuthProvider-BaPwgWny.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* A value that may depend on the calling request — a bearer token derived from
|
package/dist/openapi/index.js
CHANGED
|
@@ -3,8 +3,9 @@ import {
|
|
|
3
3
|
ViteMCP,
|
|
4
4
|
cancelResponseBody,
|
|
5
5
|
jsonSchemaAdapter
|
|
6
|
-
} from "../chunk-
|
|
7
|
-
import "../chunk-
|
|
6
|
+
} from "../chunk-IHX3AXKW.js";
|
|
7
|
+
import "../chunk-KKSDTVEW.js";
|
|
8
|
+
import "../chunk-4FH73ERY.js";
|
|
8
9
|
|
|
9
10
|
// src/openapi/parameters.ts
|
|
10
11
|
var appendQueryParameter = (query, parameter, value) => {
|
|
@@ -453,10 +454,11 @@ var HTTP_METHODS = ["get", "post", "put", "patch", "delete"];
|
|
|
453
454
|
var MAX_REF_HOPS = 32;
|
|
454
455
|
var extractRoutes = (document) => {
|
|
455
456
|
const routes = [];
|
|
456
|
-
for (const [path,
|
|
457
|
-
if (!
|
|
457
|
+
for (const [path, declared] of Object.entries(document.paths ?? {})) {
|
|
458
|
+
if (!declared || typeof declared !== "object") {
|
|
458
459
|
continue;
|
|
459
460
|
}
|
|
461
|
+
const pathItem = resolvePathItem(document, declared);
|
|
460
462
|
const pathLevelParameters = (pathItem.parameters ?? []).map(
|
|
461
463
|
(parameter) => resolve2(document, parameter)
|
|
462
464
|
);
|
|
@@ -513,22 +515,38 @@ var mergeParameters = (pathLevel, operationLevel) => {
|
|
|
513
515
|
...operationLevel
|
|
514
516
|
].filter((parameter) => parameter?.name && parameter.in);
|
|
515
517
|
};
|
|
518
|
+
var resolvePathItem = (document, pathItem) => {
|
|
519
|
+
const followed = /* @__PURE__ */ new Set();
|
|
520
|
+
let resolved = pathItem;
|
|
521
|
+
while (typeof resolved.$ref === "string" && !followed.has(resolved.$ref)) {
|
|
522
|
+
followed.add(resolved.$ref);
|
|
523
|
+
const { $ref, ...siblings } = resolved;
|
|
524
|
+
const target = dereference(document, $ref);
|
|
525
|
+
resolved = {
|
|
526
|
+
...target && typeof target === "object" ? target : {},
|
|
527
|
+
...siblings
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
return resolved;
|
|
531
|
+
};
|
|
516
532
|
var resolve2 = (document, value) => {
|
|
517
533
|
let node = value;
|
|
518
534
|
for (let hop = 0; hop < MAX_REF_HOPS; hop++) {
|
|
519
535
|
if (!node || typeof node !== "object" || !("$ref" in node)) {
|
|
520
536
|
return node;
|
|
521
537
|
}
|
|
522
|
-
|
|
523
|
-
if (!pointer.startsWith("#")) {
|
|
524
|
-
throw new Error(`Unresolved external $ref after bundling: ${pointer}`);
|
|
525
|
-
}
|
|
526
|
-
node = readPointer(document, pointer);
|
|
538
|
+
node = dereference(document, node.$ref);
|
|
527
539
|
}
|
|
528
540
|
throw new Error(
|
|
529
541
|
`$ref chain longer than ${MAX_REF_HOPS} hops, which a cyclic document is the only way to produce.`
|
|
530
542
|
);
|
|
531
543
|
};
|
|
544
|
+
var dereference = (document, pointer) => {
|
|
545
|
+
if (!pointer.startsWith("#")) {
|
|
546
|
+
throw new Error(`Unresolved external $ref after bundling: ${pointer}`);
|
|
547
|
+
}
|
|
548
|
+
return readPointer(document, pointer);
|
|
549
|
+
};
|
|
532
550
|
var readPointer = (root, pointer) => {
|
|
533
551
|
const path = pointer.slice(1);
|
|
534
552
|
if (path === "" || path === "/") {
|
|
@@ -826,7 +844,7 @@ var describeBody = (route, normalizer) => {
|
|
|
826
844
|
return { encoding, properties };
|
|
827
845
|
}
|
|
828
846
|
const object = flattenObject(schema, normalizer.definitions);
|
|
829
|
-
if (object) {
|
|
847
|
+
if (object && Object.keys(object.properties).length > 0) {
|
|
830
848
|
for (const [name, property] of Object.entries(object.properties)) {
|
|
831
849
|
properties.set(name, {
|
|
832
850
|
required: object.required.has(name),
|