@vitemcp/server 1.9.8 → 1.9.10

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ViteMCP.ts","../src/auth/router.ts","../src/cancelResponseBody.ts","../src/DiscoveryDocumentCache.ts","../src/jsonSchemaAdapter.ts"],"sourcesContent":["import {\n acceptedContent,\n bearerAuthChallengeResponse,\n type CacheScope,\n completable,\n createMcpHandler,\n getOAuthProtectedResourceMetadataUrl,\n type Icon,\n InMemoryServerEventBus,\n type InputRequest,\n inputRequired,\n type InputRequiredResult,\n localhostAllowedOrigins,\n LOG_LEVEL_META_KEY,\n type LoggingLevel,\n type McpHttpHandler,\n McpServer,\n OAuthError,\n OAuthErrorCode,\n originValidationResponse,\n ResourceTemplate as SDKResourceTemplate,\n type ToolAnnotations as SDKToolAnnotations,\n type ServerEventBus,\n UriTemplate,\n} from \"@modelcontextprotocol/server\";\nimport {\n serveStdio,\n type StdioServerHandle,\n} from \"@modelcontextprotocol/server/stdio\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport { readFile } from \"fs/promises\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport http from \"http\";\nimport https from \"https\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { setTimeout as delay } from \"timers/promises\";\nimport { fetch } from \"undici\";\nimport { toJsonSchema } from \"xsschema\";\nimport { z } from \"zod\";\n\nimport type { OAuthProxy } from \"./auth/OAuthProxy.js\";\nimport type {\n AuthProvider,\n OAuthSession,\n} from \"./auth/providers/AuthProvider.js\";\n\nimport { createOAuthRouter, OAUTH_PROXY_MAX_BODY_SIZE } from \"./auth/router.js\";\nimport { withoutTrailingSlash } from \"./auth/utils/trailingSlash.js\";\nimport { cancelResponseBody } from \"./cancelResponseBody.js\";\nimport { formatBytes } from \"./formatBytes.js\";\nimport { ownKeysOnly } from \"./ownKeysOnly.js\";\nimport {\n type JsonSchemaConverter,\n toSdkSchema,\n valibotToJsonSchema,\n} from \"./toSdkSchema.js\";\n\nexport interface Logger {\n debug: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport const MEDIA_FETCH_TIMEOUT_MS = 30000;\n\nexport type MediaSource = { timeoutMs?: number } & (\n | { buffer: Buffer }\n | { path: string }\n | { url: string }\n);\n\nexport abstract class ViteMCPError extends Error {\n public constructor(message?: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\nexport class UnexpectedStateError extends ViteMCPError {\n public extras?: Record<string, unknown>;\n\n public constructor(message: string, extras?: Record<string, unknown>) {\n super(message);\n this.name = new.target.name;\n this.extras = extras;\n }\n}\n\n/**\n * An error that is meant to be surfaced to the user, rather than logged as an\n * internal failure. Thrown from a tool handler, it becomes the tool's error\n * result rather than a protocol-level error.\n */\nexport class UserError extends UnexpectedStateError {}\n\n/**\n * What may come before an SVG's root element: a processing instruction — the\n * XML declaration, or one such as `<?xml-stylesheet?>` — a comment, or a\n * doctype, internal subset included, as Illustrator writes one.\n */\nconst XML_PROLOG_ITEM =\n /^(?:<\\?[\\s\\S]*?\\?>|<!--[\\s\\S]*?-->|<!DOCTYPE\\s[^[>]*(?:\\[[\\s\\S]*?\\])?\\s*>)/;\n\n/** Whether `data` is an SVG document: past any prolog, its root is `<svg>`. */\nconst isSvg = (data: Buffer): boolean => {\n // `trimStart` drops a byte order mark as well: U+FEFF is whitespace to it.\n let text = data.toString(\"utf8\").trimStart();\n let item = XML_PROLOG_ITEM.exec(text);\n\n while (item) {\n text = text.slice(item[0].length).trimStart();\n item = XML_PROLOG_ITEM.exec(text);\n }\n\n return /^<svg[\\s/>]/.test(text);\n};\n\n/**\n * The MIME type of a `kind` media block. What `file-type` sniffed in `data`\n * wins when it is of that kind, but it reads binary signatures only:\n *\n * - an SVG is text, so it sniffs as nothing, or as `application/xml` after an\n * XML declaration;\n * - WebM and MP4 sniff as video whatever they hold, though a browser's\n * MediaRecorder writes audio-only ones;\n * - headerless audio, such as raw PCM, sniffs as nothing.\n *\n * Past those, `declared` — the `Content-Type` a URL answered with — is used\n * when it is of the block's kind. A path or a buffer declares nothing.\n */\nconst mediaTypeOf = (\n data: Buffer,\n kind: \"audio\" | \"image\",\n sniffed: string | undefined,\n declared: null | string,\n): string => {\n if (sniffed?.startsWith(`${kind}/`)) {\n return sniffed;\n }\n\n if (kind === \"image\" && isSvg(data)) {\n return \"image/svg+xml\";\n }\n\n // Ahead of `declared`: the container is certain, and the caller has said\n // that what it holds is audio.\n if (\n kind === \"audio\" &&\n (sniffed === \"video/mp4\" || sniffed === \"video/webm\")\n ) {\n return sniffed.replace(\"video/\", \"audio/\");\n }\n\n // Without its parameters, since `audio/webm; codecs=opus` is still WebM, and\n // lowercased, since media types are case-insensitive.\n const declaredType = declared?.split(\";\")[0].trim().toLowerCase();\n\n if (declaredType?.startsWith(`${kind}/`)) {\n return declaredType;\n }\n\n return sniffed ?? (kind === \"image\" ? \"image/png\" : \"audio/mpeg\");\n};\n\nconst readMedia = async (\n source: MediaSource,\n kind: \"audio\" | \"image\",\n): Promise<{ data: string; mimeType: string }> => {\n let rawData: Buffer;\n let declared: null | string = null;\n\n try {\n if (\"url\" in source) {\n const response = await fetch(source.url, {\n signal: AbortSignal.timeout(source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n\n throw new Error(`Server responded with status: ${response.status}`);\n }\n\n declared = response.headers.get(\"content-type\");\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in source) {\n rawData = await readFile(source.path);\n } else if (\"buffer\" in source) {\n rawData = source.buffer;\n } else {\n throw new Error(\n `Invalid ${kind} source: provide one of url, path, or buffer`,\n );\n }\n } catch (error) {\n if (\"url\" in source) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `timed out after ${source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n\n throw new Error(\n `Failed to fetch ${kind} from URL (${source.url}): ${reason}`,\n );\n }\n\n if (error instanceof Error) {\n throw error;\n }\n\n throw new Error(`Unexpected error processing ${kind}: ${String(error)}`);\n }\n\n const { fileTypeFromBuffer } = await import(\"file-type\");\n const sniffed = await fileTypeFromBuffer(rawData);\n\n return {\n data: rawData.toString(\"base64\"),\n mimeType: mediaTypeOf(rawData, kind, sniffed?.mime, declared),\n };\n};\n\nexport const imageContent = async (\n source: MediaSource,\n): Promise<ImageContent> => {\n const { data, mimeType } = await readMedia(source, \"image\");\n return { data, mimeType, type: \"image\" } as const;\n};\n\nexport const audioContent = async (\n source: MediaSource,\n): Promise<AudioContent> => {\n const { data, mimeType } = await readMedia(source, \"audio\");\n return { data, mimeType, type: \"audio\" } as const;\n};\n\nexport enum ServerState {\n Error = \"error\",\n Running = \"running\",\n Starting = \"starting\",\n Stopped = \"stopped\",\n}\n\nexport type AudioContent = {\n data: string;\n mimeType: string;\n type: \"audio\";\n};\n\n/**\n * Per-request authentication hook for the HTTP transport.\n *\n * Resolve with the session to attach to `context.auth`. Resolving with `null`\n * or `undefined` **refuses** the request — the transport answers 401 and no\n * handler runs — because a hook that cannot identify the caller has not\n * authenticated them. Set `allowAnonymous` to have a nullish result mean\n * \"anonymous caller\" instead, for servers that deliberately mix public and\n * protected primitives.\n *\n * Throw a `Response` to refuse with an exact status and body of your choosing;\n * it is returned to the client verbatim.\n */\nexport type Authenticate<T> = (\n request: Request,\n) => Promise<null | T | undefined>;\n\n/**\n * Freshness hint attached to cacheable results (`tools/list`, `prompts/list`,\n * `resources/list`, `resources/templates/list`, `resources/read`). Required by\n * the 2026-07-28 revision's `CacheableResult`.\n */\nexport type CacheHint = {\n cacheScope?: CacheScope;\n ttlMs?: number;\n};\n\n/** The spec's completion payload. */\nexport type Completion = {\n hasMore?: boolean;\n total?: number;\n values: string[];\n};\n\nexport type Content =\n | AudioContent\n | ImageContent\n | ResourceContent\n | ResourceLink\n | TextContent;\n\nexport type ContentResult = {\n content: Content[];\n isError?: boolean;\n structuredContent?: unknown;\n};\n\n/**\n * Context handed to `execute` / `load`. Everything here is per-request: the\n * 2026-07-28 revision has no protocol session.\n */\nexport type Context<T extends ViteMCPAuth> = {\n /** Authentication result for this request, if an `authenticate` hook ran. */\n auth: T | undefined;\n\n /**\n * Builds an elicitation request for {@link Context.inputRequired}.\n *\n * A builder, not a promise — the server cannot block waiting for a reply.\n * The client re-issues the whole request with `inputResponses` populated.\n */\n elicit: (params: {\n message: string;\n requestedSchema: StandardSchemaV1;\n }) => InputRequest;\n\n /**\n * Reads one entry of `inputResponses` and validates it against the schema\n * used to request it. Returns `undefined` when the client declined or the\n * content does not match.\n */\n input: <S extends StandardSchemaV1>(\n key: string,\n schema: S,\n ) => StandardSchemaV1.InferOutput<S> | undefined;\n\n /**\n * Ask the client for more input and end this round.\n *\n * `requestState` round-trips through the client, so it is\n * attacker-controlled on return: sign it if it affects authorization.\n */\n inputRequired: (\n inputRequests: Record<string, InputRequest>,\n requestState?: string,\n ) => InputRequiredResult;\n\n /**\n * Present when the client is retrying a request that previously returned\n * `input_required`. Absent on the first call.\n */\n inputResponses?: Record<string, unknown>;\n\n /**\n * Emits `notifications/message`. The spec forbids emitting these unless the\n * request opted in via `_meta` log level, so these are dropped when the\n * client did not ask for logs, and below the level it asked for.\n */\n log: {\n debug: (message: string, data?: SerializableValue) => void;\n error: (message: string, data?: SerializableValue) => void;\n info: (message: string, data?: SerializableValue) => void;\n warn: (message: string, data?: SerializableValue) => void;\n };\n\n reportProgress: (progress: Progress) => Promise<void>;\n\n /** Request ID of the current MCP request. */\n requestId?: string;\n\n /** The `requestState` echoed back by the client on an MRTR retry. */\n requestState?: string;\n\n /**\n * Aborts when this call is cancelled: the client disconnected, a\n * `notifications/cancelled` arrived, or — for a tool with `timeoutMs` — the\n * deadline passed. Forward it to whatever the handler starts (a `fetch`, a\n * subprocess, a query) so that work stops with the request rather than\n * running on unobserved.\n *\n * Scoped to the handler: returning normally leaves it unaborted, so\n * `addEventListener(\"abort\", …)` is safe to use for rollback.\n *\n * Two caveats. `notifications/cancelled` is a no-op on the stateless HTTP\n * transport — a server is minted per request, so a cancellation for a call\n * already in flight has nothing to reach; disconnecting is what cancels\n * there. And `signal.reason` for a `timeoutMs` breach is the `UserError` the\n * caller receives, not a `DOMException`, so code branching on\n * `reason.name === \"AbortError\"` will not match.\n *\n * Always present: a context built outside a request (`embedded()`) carries\n * one that never fires, so callers never have to guard.\n */\n signal: AbortSignal;\n};\n\nexport type ImageContent = {\n data: string;\n mimeType: string;\n type: \"image\";\n};\n\nexport type LoadContext<T extends ViteMCPAuth> = Omit<\n Context<T>,\n \"reportProgress\"\n>;\n\n/**\n * A single loaded resource body. `uri` is optional: when omitted the server\n * fills it in from the resource (or the expanded template) that produced it.\n */\nexport type LoadedResource = {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri?: string;\n};\n\nexport type Progress = {\n message?: string;\n progress: number;\n total?: number;\n};\n\nexport type Prompt<T extends ViteMCPAuth> = {\n arguments?: PromptArgument[];\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any argument. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<{ messages: unknown[] } | string>;\n name: string;\n};\n\nexport type PromptArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n /** Constrains the argument to a fixed set of values. */\n enum?: string[];\n name: string;\n required?: boolean;\n};\n\nexport type Resource<T extends ViteMCPAuth> = {\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n load: (context: LoadContext<T>) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uri: string;\n};\n\nexport type ResourceContent = {\n resource: {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri: string;\n };\n type: \"resource\";\n};\n\nexport type ResourceLink = {\n description?: string;\n mimeType?: string;\n name: string;\n type: \"resource_link\";\n uri: string;\n};\n\nexport type ResourceTemplate<T extends ViteMCPAuth> = {\n arguments?: ResourceTemplateArgument[];\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any template variable. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uriTemplate: string;\n};\n\nexport type ResourceTemplateArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n name: string;\n required?: boolean;\n};\n\nexport type SerializableValue =\n | { [key: string]: SerializableValue }\n | Literal\n | SerializableValue[];\n\nexport type ServerOptions<T extends ViteMCPAuth> = {\n /**\n * Serve requests whose `authenticate` hook resolved with `null`/`undefined`\n * as anonymous — `context.auth` is `undefined` and `canAccess` is the only\n * gate — instead of refusing them with a 401.\n *\n * Off by default: a server that configures authentication and then answers\n * callers it could not identify exposes every tool, resource and prompt that\n * has no `canAccess` guard. Turn it on only for a server that is genuinely\n * public in part, and guard the rest with `canAccess`.\n */\n allowAnonymous?: boolean;\n auth?: AuthProvider<T extends OAuthSession ? T : OAuthSession>;\n authenticate?: Authenticate<T>;\n /**\n * What this server is, for a human reading a client's server list.\n *\n * Distinct from `instructions`, which is addressed to the model and tells it\n * how to use what this server exposes.\n */\n description?: string;\n health?: {\n enabled?: boolean;\n message?: string;\n path?: string;\n status?: number;\n };\n /**\n * Icons a client may show next to this server, most specific first.\n *\n * `src` is a URL the client fetches, so it must be reachable from wherever\n * the client runs — not only from the server.\n */\n icons?: Icon[];\n instructions?: string;\n logger?: Logger;\n name: string;\n oauth?: {\n authorizationServer?: Record<string, unknown>;\n enabled?: boolean;\n protectedResource?: Record<string, unknown>;\n proxy?: OAuthProxy;\n };\n /** Display name, for clients that prefer one over the identifier `name`. */\n title?: string;\n version: `${number}.${number}.${number}`;\n /** Homepage for this server, for clients that link to one. */\n websiteUrl?: string;\n};\n\n/**\n * The structured payload on its own, without the content fallback.\n *\n * Returning this is how a tool states outright that an object is its structured\n * result, for the cases where the shape alone cannot say so — a payload whose\n * own `content` field is an array reads as a list of content blocks otherwise.\n * ViteMCP writes the JSON text fallback, exactly as it does for a plain\n * structured return.\n */\nexport type StructuredResult<T = unknown> = {\n _meta?: Record<string, unknown>;\n isError?: boolean;\n structuredContent: T;\n};\n\nexport type TextContent = {\n text: string;\n type: \"text\";\n};\n\nexport type Tool<\n T extends ViteMCPAuth,\n Params extends ToolParameters = ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n> = {\n _meta?: Record<string, unknown>;\n annotations?: SDKToolAnnotations;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n execute: (\n args: StandardSchemaV1.InferOutput<Params>,\n context: Context<T>,\n ) => Promise<\n | AudioContent\n | ContentResult\n | ImageContent\n | InputRequiredResult\n | ResourceContent\n | ResourceLink\n | StandardSchemaV1.InferOutput<OutputParams>\n | string\n | StructuredResult<StandardSchemaV1.InferOutput<OutputParams>>\n | TextContent\n | void\n >;\n name: string;\n outputSchema?: OutputParams;\n parameters?: Params;\n timeoutMs?: number;\n};\n\nexport type ToolParameters = StandardSchemaV1;\n\nexport type ViteMCPAuth = Record<string, unknown> | undefined;\n\ntype Literal = boolean | null | number | string | undefined;\n\n/**\n * Name and URI of the placeholder registered — and immediately removed — to\n * latch a primitive family's request handlers when `canAccess` hid every\n * member of it from this caller. See `#buildServer`. Never reaches the wire.\n *\n * The name holds to the SEP tool-name charset (`A-Za-z0-9._-`) even though it\n * is never listed: the SDK validates on registration, so a `/` in here would\n * put a five-line naming warning on every fully-filtered request.\n */\nconst LATCH_NAME = \"vitemcp.internal.capability-latch\";\nconst LATCH_URI = \"vitemcp-internal:capability-latch\";\n\n/**\n * The spec's log levels, least severe first. A request's\n * `io.modelcontextprotocol/logLevel` names the least severe one it wants.\n */\nconst LOG_LEVELS: readonly LoggingLevel[] = [\n \"debug\",\n \"info\",\n \"notice\",\n \"warning\",\n \"error\",\n \"critical\",\n \"alert\",\n \"emergency\",\n];\n\n/** A tool's schemas in the form the SDK registers them. */\ntype SdkToolSchemas = { inputSchema: unknown; outputSchema: unknown };\n\n/** The default logger when stdout carries the protocol: every level to stderr. */\nconst stderrLogger: Logger = {\n debug: (...args) => console.error(...args),\n error: (...args) => console.error(...args),\n info: (...args) => console.error(...args),\n log: (...args) => console.error(...args),\n warn: (...args) => console.warn(...args),\n};\n\nexport class ViteMCP<T extends ViteMCPAuth = ViteMCPAuth> {\n /**\n * The `auth` provider this server was constructed with, or `undefined` when\n * OAuth was configured through the `oauth` option instead (or not at all).\n *\n * Exposed so a caller who inlined the provider into the options — the way\n * every example does — can still reach it at shutdown. The provider holds an\n * `OAuthProxy` with two cleanup timers, and `stop()` deliberately leaves them\n * running: the server does not own the provider, and a stopped server can be\n * started again. Terminal teardown is therefore the caller's call:\n *\n * ```ts\n * await server.stop();\n * server.authProvider?.destroy();\n * ```\n *\n * In that order — `destroy()` is terminal, and a request still draining would\n * throw against a destroyed provider.\n */\n public get authProvider():\n | AuthProvider<T extends OAuthSession ? T : OAuthSession>\n | undefined {\n return this.#options.auth;\n }\n\n /**\n * The port the HTTP server is actually listening on, or `null` when it is\n * not running over HTTP. Pass `httpStream.port: 0` to let the OS assign a\n * free port and read it back here — this avoids the race inherent in\n * picking a port first and binding it afterwards.\n */\n public get port(): null | number {\n const address = this.#httpServer?.address();\n return address && typeof address === \"object\" ? address.port : null;\n }\n\n public get serverState(): ServerState {\n return this.#serverState;\n }\n #authenticate: Authenticate<T> | undefined;\n /**\n * Carries the `authenticate` result from the HTTP route into the per-request\n * server factory. The SDK invokes that factory from within `handler.fetch`,\n * so the running store is always the one this request established — whereas\n * a field on `this` would be shared by every concurrent request.\n */\n #authStore = new AsyncLocalStorage<{ auth: T | undefined }>();\n #connectedServers: McpServer[] = [];\n #corsMiddleware: null | ReturnType<typeof cors> = null;\n #handler: McpHttpHandler | null = null;\n #honoApp = new Hono();\n #httpServer: http.Server | https.Server | null = null;\n #logger: Logger;\n #options: ServerOptions<T>;\n #prompts: Prompt<T>[] = [];\n /**\n * The RFC 9728 protected-resource document this server publishes, if it\n * publishes one — what a 401 points a client at. Latched when the routes are\n * mounted rather than read back from `auth` per rejection: the provider's\n * config getter builds its proxy on demand and refuses once destroyed.\n */\n #protectedResource: { resource?: unknown } | undefined;\n #resources: Resource<T>[] = [];\n #resourceTemplates: ResourceTemplate<T>[] = [];\n #serverState: ServerState = ServerState.Stopped;\n #stdioHandle: null | StdioServerHandle = null;\n\n #tools: Tool<T>[] = [];\n /** Each tool's schemas, as `#sdkSchemasFor` converted them. */\n #toolSchemas = new WeakMap<Tool<T>, Promise<SdkToolSchemas | undefined>>();\n\n public constructor(options: ServerOptions<T>) {\n this.#options = options;\n this.#logger = options.logger ?? console;\n\n // An AuthProvider supplies the authenticate hook. Resolved here rather\n // than inside the HTTP path so the wiring is not silently absent on\n // stdio / `connect()`.\n const provider = options.auth;\n this.#authenticate =\n options.authenticate ??\n (provider\n ? (((request: Request) =>\n provider.authenticate(request)) as unknown as Authenticate<T>)\n : undefined);\n\n this.#honoApp = this.#freshApp();\n }\n\n // An entry added under a key already in use replaces the one there: the SDK\n // refuses to register a key twice, and as the server is rebuilt for every\n // request, a duplicate failed every request, not only its own. Keys are the\n // SDK's — a resource's URI, and every other entry's name.\n public addPrompt(prompt: Prompt<T>) {\n this.#prompts = this.#prompts.filter((p) => p.name !== prompt.name);\n this.#prompts.push(prompt);\n this.#notifyListChanged(\"prompts\");\n }\n\n public addPrompts(prompts: Prompt<T>[]) {\n for (const prompt of prompts) {\n this.#prompts = this.#prompts.filter((p) => p.name !== prompt.name);\n this.#prompts.push(prompt);\n }\n this.#notifyListChanged(\"prompts\");\n }\n\n public addResource(resource: Resource<T>) {\n this.#resources = this.#resources.filter((r) => r.uri !== resource.uri);\n this.#resources.push(resource);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResources(resources: Resource<T>[]) {\n for (const resource of resources) {\n this.#resources = this.#resources.filter((r) => r.uri !== resource.uri);\n this.#resources.push(resource);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplate(template: ResourceTemplate<T>) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== template.name,\n );\n this.#resourceTemplates.push(template);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplates(templates: ResourceTemplate<T>[]) {\n for (const template of templates) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== template.name,\n );\n this.#resourceTemplates.push(template);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addTool<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tool: Tool<T, Params, OutputParams>) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools = this.#tools.filter((t) => t.name !== tool.name);\n this.#tools.push(tool as unknown as Tool<T>);\n this.#notifyListChanged(\"tools\");\n }\n\n public addTools<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tools: Tool<T, Params, OutputParams>[]) {\n // All checked before any is added: a batch that throws leaves the tools as\n // they were, rather than serving those ahead of the one it threw over.\n for (const tool of tools) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n }\n\n for (const tool of tools) {\n this.#tools = this.#tools.filter((t) => t.name !== tool.name);\n this.#tools.push(tool as unknown as Tool<T>);\n }\n this.#notifyListChanged(\"tools\");\n }\n\n /**\n * Connects the server to an arbitrary transport — used for in-memory unit\n * testing, where a linked transport pair replaces a real socket.\n */\n public async connect(\n transport: Parameters<McpServer[\"connect\"]>[0],\n ): Promise<McpServer> {\n const server = await this.#buildServer(undefined);\n await server.connect(transport);\n this.#connectedServers.push(server);\n this.#serverState = ServerState.Running;\n return server;\n }\n\n /**\n * Resolves a resource (or resource template) URI to an embeddable resource\n * body, for returning inline from a tool.\n */\n public async embedded(uri: string): Promise<LoadedResource> {\n const direct = this.#resources.find((resource) => resource.uri === uri);\n\n if (direct) {\n // No `release()` here or below: a context built outside a request has no\n // source signals to stop mirroring.\n const loaded = await direct.load(\n this.#makeContext(undefined, undefined).context,\n );\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(`Resource loaded no content: ${uri}`, {\n uri,\n });\n }\n\n return {\n ...first,\n mimeType: first.mimeType ?? direct.mimeType,\n uri: first.uri ?? uri,\n };\n }\n\n for (const template of this.#resourceTemplates) {\n // Matched as `resources/read` matches it, so a URI reaches the same\n // template, with the same arguments, whichever way it is asked for. A\n // matcher that let `{id}` take a `/` had `docs://{id}` claim\n // `docs://x/history` from `docs://{id}/history`, and handed its loader a\n // path it never declared.\n const params = new UriTemplate(template.uriTemplate).match(uri);\n\n if (!params) {\n continue;\n }\n\n const loaded = await template.load(\n params as Record<string, string>,\n this.#makeContext(undefined, undefined).context,\n );\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(\n `Resource template loaded no content: ${uri}`,\n { uri },\n );\n }\n\n return {\n ...first,\n mimeType: first.mimeType ?? template.mimeType,\n uri: first.uri ?? uri,\n };\n }\n\n throw new UnexpectedStateError(`Resource not found: ${uri}`, { uri });\n }\n\n /** The Hono app serving the HTTP transport, for mounting custom routes. */\n public getApp(): Hono {\n return this.#honoApp;\n }\n\n /**\n * Publishes `notifications/resources/updated` for a URI to any subscription\n * that opted in to it and whose caller may read it. HTTP only: a stdio\n * client is never reached.\n */\n public notifyResourceUpdated(uri: string): void {\n this.#handler?.notify.resourceUpdated(uri);\n }\n\n public removePrompt(name: string) {\n this.#prompts = this.#prompts.filter((p) => p.name !== name);\n this.#notifyListChanged(\"prompts\");\n }\n\n public removePrompts(names: string[]) {\n this.#prompts = this.#prompts.filter((p) => !names.includes(p.name));\n this.#notifyListChanged(\"prompts\");\n }\n\n public removeResource(name: string) {\n this.#resources = this.#resources.filter((r) => r.name !== name);\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResources(names: string[]) {\n this.#resources = this.#resources.filter((r) => !names.includes(r.name));\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplate(name: string) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== name,\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplates(names: string[]) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => !names.includes(r.name),\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeTool(name: string) {\n this.#tools = this.#tools.filter((t) => t.name !== name);\n this.#notifyListChanged(\"tools\");\n }\n\n public removeTools(names: string[]) {\n this.#tools = this.#tools.filter((t) => !names.includes(t.name));\n this.#notifyListChanged(\"tools\");\n }\n\n public async start(\n options:\n | {\n httpStream: {\n /** Origins permitted to reach the MCP endpoint (DNS-rebinding guard). */\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n /**\n * Whether to also serve 2025-era clients. Defaults to\n * `\"stateless\"`: the SDK client negotiates 2025 unless given\n * `versionNegotiation: { mode: \"auto\" }`. `\"reject\"` serves only\n * 2026-07-28 and enforces `Mcp-Method`/`Mcp-Name`.\n */\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n };\n transportType: \"httpStream\";\n }\n | { transportType: \"stdio\" },\n ): Promise<void> {\n // Starting a transport again replaced its handle, and `stop()` closes only\n // the handle it holds: the first went on running after `stop()` returned —\n // an HTTP listener holding its port, and the process, open.\n if (\n options.transportType === \"stdio\" ? this.#stdioHandle : this.#httpServer\n ) {\n throw new UnexpectedStateError(\n `ViteMCP is already running on ${\n options.transportType === \"stdio\" ? \"stdio\" : \"HTTP\"\n }; call stop() before starting it again`,\n );\n }\n\n this.#serverState = ServerState.Starting;\n\n try {\n if (options.transportType === \"stdio\") {\n // stdout is the transport here, and the default console logger writes\n // info, log and debug to it — straight into the stream the client\n // parses as JSON-RPC. A logger passed in is the caller's to direct.\n this.#logger = this.#options.logger ?? stderrLogger;\n this.#stdioHandle = serveStdio(({ era }) =>\n this.#buildServer(undefined, { era }),\n );\n this.#logger.info(`[ViteMCP info] server is running on stdio`);\n } else {\n await this.#startHttp(options.httpStream);\n }\n\n this.#serverState = ServerState.Running;\n } catch (error) {\n this.#serverState = ServerState.Error;\n throw error;\n }\n }\n\n public async stop(): Promise<void> {\n // Hono seals its matcher once used, so a restarted server needs a fresh\n // app; the routes are re-registered by the next `start()`.\n this.#honoApp = this.#freshApp();\n this.#corsMiddleware = null;\n\n for (const server of this.#connectedServers) {\n await server.close().catch(() => {});\n }\n this.#connectedServers = [];\n\n await this.#stdioHandle?.close?.();\n this.#stdioHandle = null;\n\n await this.#handler?.close();\n this.#handler = null;\n\n if (this.#httpServer) {\n await new Promise<void>((resolve) =>\n this.#httpServer!.close(() => resolve()),\n );\n this.#httpServer = null;\n }\n\n this.#serverState = ServerState.Stopped;\n }\n\n /**\n * Runs the `authenticate` hook and decides whether the exchange may proceed,\n * returning either the store to run it under or the `Response` refusing it.\n *\n * Deliberately *not* done inside the per-request server factory: that\n * factory's only return channel is an `McpServer`, so a refusal raised there\n * is indistinguishable from a crash and reaches the client as a 500 with no\n * `WWW-Authenticate` — the one header that tells an MCP client where to log\n * in. Doing it here also covers the legacy fallback, which shares the same\n * route, so no transport can be reached without passing this.\n */\n async #authenticateRequest(\n request: Request,\n ): Promise<{ auth: T | undefined } | Response> {\n if (!this.#authenticate) {\n return { auth: undefined };\n }\n\n let auth: null | T | undefined;\n\n try {\n auth = await this.#authenticate(request);\n } catch (error) {\n // A hook may throw the exact response it wants sent — the documented way\n // to refuse with a specific status, body or challenge.\n if (error instanceof Response) {\n return error;\n }\n\n // Anything else is a fault in the hook. Fail closed: a hook that threw\n // did not authorise anyone, so this must never fall through to the\n // handler. Reported here because the throw no longer reaches the SDK's\n // `onerror`, which used to be what logged it.\n this.#logger.error(\"[ViteMCP error]\", error);\n\n return bearerAuthChallengeResponse(\n new OAuthError(OAuthErrorCode.ServerError, \"Internal Server Error\"),\n );\n }\n\n // A falsy result means the hook could not identify the caller, which is a\n // refusal and not an anonymous session: `AuthProvider.authenticate`\n // returns `undefined` for a missing, malformed or revoked bearer token.\n // Serving those requests anyway would hand every primitive that has no\n // `canAccess` guard to callers who presented no credentials at all.\n // Tested for falsiness rather than nullishness because a session is always\n // an object here, so nothing legitimate is caught — but an untyped hook\n // returning `false` is caught, and it plainly means \"no\".\n if (!auth) {\n return this.#options.allowAnonymous\n ? { auth: undefined }\n : this.#unauthorized(request);\n }\n\n return { auth };\n }\n\n /**\n * `era` is the protocol era the server will speak, where it is known: one\n * built for `connect()` speaks whichever the client picks.\n * `resourceSubscriptions` declares `resources.subscribe`. Set it only where\n * `notifyResourceUpdated` delivers: to 2026-07-28 HTTP clients.\n */\n async #buildServer(\n auth: T | undefined,\n {\n era,\n resourceSubscriptions = false,\n }: { era?: \"legacy\" | \"modern\"; resourceSubscriptions?: boolean } = {},\n ): Promise<McpServer> {\n const server = new McpServer(\n {\n description: this.#options.description,\n icons: this.#options.icons,\n name: this.#options.name,\n title: this.#options.title,\n version: this.#options.version,\n websiteUrl: this.#options.websiteUrl,\n },\n {\n // Without it the SDK refuses to send `notifications/message`, and\n // `log.*` swallows the refusal, so every log line vanished silently.\n // Left out for a 2025-era client: `log.*` answers only the 2026-07-28\n // per-request opt-in, so the `logging/setLevel` it would promise that\n // client could never take effect.\n capabilities: era === \"legacy\" ? {} : { logging: {} },\n instructions: this.#options.instructions,\n },\n );\n\n const visible = <\n P extends { canAccess?: (auth: T | undefined) => boolean },\n >(\n all: readonly P[],\n ): P[] => all.filter((entry) => !entry.canAccess || entry.canAccess(auth));\n\n // A tool whose schemas cannot be converted is left out rather than allowed\n // to fail the request: every request builds the whole server, so one such\n // tool would otherwise take down every method, not just itself.\n const tools = (\n await Promise.all(\n visible(this.#tools).map(async (tool) => {\n const schemas = await this.#sdkSchemasFor(tool);\n\n return schemas && { schemas, tool };\n }),\n )\n ).filter((entry) => entry !== undefined);\n const resources = visible(this.#resources);\n const resourceTemplates = visible(this.#resourceTemplates);\n const prompts = visible(this.#prompts);\n\n for (const { schemas, tool } of tools) {\n const call = async (args: unknown, ctx: unknown) => {\n // Paired so the deadline reaches `execute` through `context.signal`\n // as well as rejecting the caller — a timeout the tool cannot see\n // leaves its work running behind an already-settled promise.\n const timeout = tool.timeoutMs\n ? { controller: new AbortController(), ms: tool.timeoutMs }\n : undefined;\n const { context, release } = this.#makeContext(\n auth,\n ctx,\n timeout?.controller.signal,\n );\n\n try {\n const result = await (timeout\n ? withTimeout(tool.execute(args, context), timeout, tool.name)\n : tool.execute(args, context));\n return normalizeToolResult(result, tool.outputSchema !== undefined);\n } catch (error) {\n if (error instanceof UserError) {\n // The SDK checks a success's structured content against the\n // output schema, not an error's, but a client may check both — the\n // v1 SDK's does. Extras that did not match had that client throw\n // the message away, as a -32602, so they are sent only if they do.\n const structuredContent =\n error.extras &&\n (await matchesOutputSchema(schemas.outputSchema, error.extras))\n ? error.extras\n : undefined;\n\n return {\n content: [{ text: error.message, type: \"text\" }],\n isError: true,\n ...(structuredContent ? { structuredContent } : {}),\n };\n }\n throw error;\n } finally {\n release();\n }\n };\n\n server.registerTool(\n tool.name,\n {\n _meta: tool._meta,\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: schemas.inputSchema as never,\n outputSchema: schemas.outputSchema as never,\n },\n // The SDK passes arguments only to a tool that declares an input\n // schema; one that does not is called with the request context alone.\n // Registering `call` as it stands would take that context for `args`\n // and leave the tool without one: no progress, no logs, no request id\n // and a `signal` that never fires.\n (schemas.inputSchema\n ? call\n : (ctx: unknown) => call(undefined, ctx)) as never,\n );\n }\n\n for (const resource of resources) {\n server.registerResource(\n resource.name,\n resource.uri,\n {\n cacheHint: resource.cache,\n description: resource.description,\n mimeType: resource.mimeType,\n },\n (async (uri: URL, ctx: unknown) => {\n const { context, release } = this.#makeContext(auth, ctx);\n\n try {\n const loaded = await resource.load(context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n } finally {\n release();\n }\n }) as never,\n );\n }\n\n for (const template of resourceTemplates) {\n // No prototype, because the SDK looks a variable's completer up here by\n // name: on a plain object, asking to complete a variable called\n // `constructor` or `toString` found `Object.prototype`'s, called it, and\n // failed the request instead of answering with nothing.\n const complete: Record<string, (value: string) => Promise<string[]>> =\n Object.create(null);\n for (const arg of template.arguments ?? []) {\n const completer =\n arg.complete ??\n (template.complete\n ? (value: string) => template.complete!(arg.name, value)\n : undefined);\n\n if (completer) {\n complete[arg.name] = async (value: string) =>\n (await completer(value)).values;\n }\n }\n\n server.registerResource(\n template.name,\n new SDKResourceTemplate(template.uriTemplate, {\n complete: complete as never,\n list: undefined,\n }),\n {\n cacheHint: template.cache,\n description: template.description,\n mimeType: template.mimeType,\n },\n (async (uri: URL, args: Record<string, string>, ctx: unknown) => {\n const { context, release } = this.#makeContext(auth, ctx);\n\n try {\n const loaded = await template.load(args ?? {}, context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? template.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n } finally {\n release();\n }\n }) as never,\n );\n }\n\n for (const prompt of prompts) {\n const argsSchema = promptArgsSchema(prompt);\n\n const load = async (\n args: Record<string, string> | undefined,\n ctx: unknown,\n ) => {\n const { context, release } = this.#makeContext(auth, ctx);\n\n try {\n const loaded = await prompt.load(args ?? {}, context);\n\n if (typeof loaded !== \"string\") {\n return loaded;\n }\n\n return {\n messages: [\n {\n content: { text: loaded, type: \"text\" },\n role: \"user\" as const,\n },\n ],\n };\n } finally {\n release();\n }\n };\n\n server.registerPrompt(\n prompt.name,\n { argsSchema, description: prompt.description } as never,\n // As for tools: without `argsSchema` the SDK passes the request\n // context alone.\n (argsSchema ? load : (ctx: unknown) => load(undefined, ctx)) as never,\n );\n }\n\n // `canAccess` is documented to filter rejected primitives out of the list,\n // so a caller who may see none of them is owed an empty list. The SDK\n // registers a family's request handlers — and its capability — on the\n // first `registerTool`/`registerResource`/`registerPrompt`, so a request\n // that registered nothing never got them and `tools/list` came back\n // `-32601 Method not found`: the method does not exist, rather than the\n // caller may see nothing in it. Registering a placeholder and removing it\n // latches the handlers without the placeholder ever being listed or\n // callable — and it cannot collide, because this runs only when nothing\n // else in the family registered. A server carrying none of a primitive at\n // all still advertises nothing, so `-32601` stays correct there.\n if (this.#tools.length > 0 && tools.length === 0) {\n server\n .registerTool(LATCH_NAME, {}, (() => ({ content: [] })) as never)\n .remove();\n }\n\n // One registration latches `resources/list`, `resources/templates/list`\n // and `resources/read` together, so the two resource families share it.\n if (\n this.#resources.length + this.#resourceTemplates.length > 0 &&\n resources.length + resourceTemplates.length === 0\n ) {\n server\n .registerResource(LATCH_NAME, LATCH_URI, {}, (() => ({\n contents: [],\n })) as never)\n .remove();\n }\n\n if (this.#prompts.length > 0 && prompts.length === 0) {\n server\n .registerPrompt(LATCH_NAME, {}, (() => ({ messages: [] })) as never)\n .remove();\n }\n\n // The SDK drops `resourceSubscriptions` from a `subscriptions/listen`\n // filter unless the server declares `resources.subscribe`, so without it\n // no update ever reached a client. Added to a resources capability that\n // registration declared, never in place of one: a server without resources\n // must not advertise the family.\n if (resourceSubscriptions && server.server.getCapabilities().resources) {\n server.server.registerCapabilities({ resources: { subscribe: true } });\n }\n\n return server;\n }\n\n /**\n * Whether `resources/read` would serve `uri` to this caller: a resource of\n * that URI, or a template matching it, that `canAccess` leaves visible.\n */\n #canRead(uri: string, auth: T | undefined): boolean {\n const visible = (entry: { canAccess?: (auth: T | undefined) => boolean }) =>\n !entry.canAccess || entry.canAccess(auth);\n\n return (\n this.#resources.some(\n (resource) => resource.uri === uri && visible(resource),\n ) ||\n this.#resourceTemplates.some(\n (template) =>\n visible(template) &&\n new UriTemplate(template.uriTemplate).match(uri) !== null,\n )\n );\n }\n\n /**\n * The bus `notifyResourceUpdated` publishes to and `subscriptions/listen`\n * streams read from, narrowed per stream to updates its caller could read.\n *\n * `canAccess` keeps a resource out of `resources/read`, so its updates must\n * not reach that caller either, or subscribing to the URI would reveal what\n * reading it cannot. The SDK subscribes a stream while serving its listen\n * request, so that caller's auth is still in scope here.\n */\n #eventBus(): ServerEventBus {\n const events = new InMemoryServerEventBus((error) =>\n this.#logger.error(\"[ViteMCP error]\", error),\n );\n\n return {\n publish: (event) => events.publish(event),\n subscribe: (listener) => {\n const auth = this.#authStore.getStore()?.auth;\n\n return events.subscribe((event) => {\n if (\n event.kind !== \"resource_updated\" ||\n this.#canRead(event.uri, auth)\n ) {\n listener(event);\n }\n });\n },\n };\n }\n\n /** Builds the Hono app with the CORS shim installed ahead of user routes. */\n #freshApp(): Hono {\n const app = new Hono();\n\n app.use(\"*\", (c, next) =>\n this.#corsMiddleware ? this.#corsMiddleware(c, next) : next(),\n );\n\n return app;\n }\n\n /**\n * Bridges the v2 per-request context onto ViteMCP's `Context`.\n *\n * `timeoutSignal` is folded into `context.signal` for a tool that declares\n * `timeoutMs`; everything else mirrors the SDK's request signal alone. Call\n * `release()` once the handler has settled — see {@link requestScope}. It\n * also ends the context's notifications, as an abort does.\n */\n #makeContext(\n auth: T | undefined,\n rawCtx: unknown,\n timeoutSignal?: AbortSignal,\n ): { context: Context<T>; release: () => void } {\n const ctx = rawCtx as {\n mcpReq?: {\n _meta?: {\n progressToken?: number | string;\n };\n /**\n * The reserved `io.modelcontextprotocol/*` keys, which the SDK moves\n * here out of `_meta`.\n */\n envelope?: { [LOG_LEVEL_META_KEY]?: LoggingLevel };\n id?: string;\n inputResponses?: Record<string, unknown>;\n notify?: (n: unknown) => Promise<void>;\n requestState?: <T>() => T | undefined;\n signal?: AbortSignal;\n };\n };\n const mcpReq = ctx?.mcpReq;\n const scope = requestScope(mcpReq?.signal, timeoutSignal);\n let settled = false;\n\n // A request's notifications stop with it: once it is cancelled, times out\n // or has been answered, nothing is left for them to belong to. One sent\n // anyway reached a client that had let its progress token go, which\n // reports it as unknown; over HTTP the request's stream is gone, and the\n // send threw \"Not connected\" into the handler.\n const notify = async (notification: unknown): Promise<void> => {\n if (settled || scope.signal.aborted) {\n return;\n }\n\n await mcpReq?.notify?.(notification);\n };\n\n // The spec forbids `notifications/message` for a request that did not opt\n // in via `_meta`, and the level it opts in with is a floor: a client that\n // asks for `error` wants errors, not everything. Failures are swallowed: a\n // log line must never take down the request.\n const requestedLevel = mcpReq?.envelope?.[LOG_LEVEL_META_KEY];\n\n const emit = (\n level: LoggingLevel,\n message: string,\n data?: SerializableValue,\n ) => {\n if (\n !requestedLevel ||\n LOG_LEVELS.indexOf(level) < LOG_LEVELS.indexOf(requestedLevel)\n ) {\n return;\n }\n\n void notify({\n method: \"notifications/message\",\n params: { data: { context: data, message }, level },\n }).catch(() => {});\n };\n\n return {\n context: {\n auth,\n elicit: (params) =>\n inputRequired.elicit({\n message: params.message,\n requestedSchema: params.requestedSchema as never,\n }),\n input: (key, schema) =>\n acceptedContent(\n mcpReq?.inputResponses,\n key,\n schema as never,\n ) as never,\n inputRequired: (inputRequests, requestState) =>\n inputRequired({ inputRequests, requestState }),\n inputResponses: mcpReq?.inputResponses,\n log: {\n debug: (m, d) => emit(\"debug\", m, d),\n error: (m, d) => emit(\"error\", m, d),\n info: (m, d) => emit(\"info\", m, d),\n warn: (m, d) => emit(\"warning\", m, d),\n },\n reportProgress: async (progress) => {\n const progressToken = mcpReq?._meta?.progressToken;\n\n // No token means the client did not ask for progress on this request;\n // emitting anyway would be an uncorrelatable notification.\n if (progressToken === undefined) {\n return;\n }\n\n await notify({\n method: \"notifications/progress\",\n params: {\n message: progress.message,\n progress: progress.progress,\n progressToken,\n total: progress.total,\n },\n });\n },\n requestId: mcpReq?.id,\n // The SDK exposes this as an accessor; call it so callers get the\n // value.\n requestState: mcpReq?.requestState?.<string>(),\n signal: scope.signal,\n },\n release: () => {\n settled = true;\n scope.release();\n },\n };\n }\n\n /**\n * Publishes a change event to any open `subscriptions/listen` stream. This\n * replaces the 2025-era `notifications/*_list_changed` broadcast, which had\n * no addressee on a stateless transport.\n */\n #notifyListChanged(kind: \"prompts\" | \"resources\" | \"tools\") {\n // Typed on purpose: a cast here once let wrong method names no-op.\n const notifier = this.#handler?.notify;\n\n if (!notifier) {\n return;\n }\n\n if (kind === \"tools\") notifier.toolsChanged();\n if (kind === \"prompts\") notifier.promptsChanged();\n if (kind === \"resources\") notifier.resourcesChanged();\n }\n\n /**\n * A tool's schemas in the form the SDK registers them, or `undefined` for a\n * tool whose schemas cannot be converted — reported when that is found.\n *\n * Converted once per tool: `#buildServer` runs on every request, so a tool\n * that cannot be served would otherwise be reported on each of them.\n */\n #sdkSchemasFor(tool: Tool<T>): Promise<SdkToolSchemas | undefined> {\n let schemas = this.#toolSchemas.get(tool);\n\n if (!schemas) {\n schemas = Promise.all([\n this.#toSdkSchema(\n tool.parameters,\n `Tool \"${tool.name}\" parameters`,\n \"input\",\n ),\n this.#toSdkSchema(\n tool.outputSchema,\n `Tool \"${tool.name}\" outputSchema`,\n \"output\",\n ),\n ]).then(\n ([inputSchema, outputSchema]) => ({ inputSchema, outputSchema }),\n (error: unknown) => {\n this.#logger.error(\n `[ViteMCP error] Tool \"${tool.name}\" is not served:`,\n error,\n );\n\n return undefined;\n },\n );\n this.#toolSchemas.set(tool, schemas);\n }\n\n return schemas;\n }\n\n async #startHttp(config: {\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n }): Promise<void> {\n this.#handler = createMcpHandler(\n // Authentication has already run in the route below, which is the only\n // place that can turn a refusal into an HTTP status. What reaches here\n // is either an authenticated session or a deliberately anonymous one.\n async ({ era }) =>\n this.#buildServer(this.#authStore.getStore()?.auth, {\n era,\n // A 2025-era client reads `resources.subscribe` as a promise of\n // `resources/subscribe`, which is not served.\n resourceSubscriptions: era === \"modern\",\n }),\n {\n bus: this.#eventBus(),\n // Tradeoff: `server/discover` advertises only 2026-07-28, so legacy\n // requests are answered unadvertised and skip Mcp-* validation.\n legacy: config.legacy ?? \"stateless\",\n ...(config.enableJsonResponse ? { responseMode: \"json\" as const } : {}),\n onerror: (error) => this.#logger.error(\"[ViteMCP error]\", error),\n },\n );\n\n this.#corsMiddleware = config.cors === false ? null : cors(config.cors);\n\n // An explicit `oauth` config is served as written. A provider's cannot be\n // complete until the endpoint is known, which is here.\n const provider = this.#options.auth;\n const oauth =\n this.#options.oauth ??\n (provider &&\n withEndpointAsResource(\n provider.getOAuthConfig(),\n config.endpoint ?? \"/mcp\",\n ));\n\n if (\n oauth?.enabled !== false &&\n (oauth?.proxy ?? oauth?.authorizationServer ?? oauth?.protectedResource)\n ) {\n this.#honoApp.route(\n \"/\",\n createOAuthRouter({\n authorizationServer: oauth.authorizationServer,\n basePath: config.basePath,\n endpoint: config.endpoint ?? \"/mcp\",\n protectedResource: oauth.protectedResource,\n proxy: oauth.proxy,\n }),\n );\n\n this.#protectedResource = oauth.protectedResource;\n }\n\n const health = this.#options.health;\n if (health?.enabled !== false) {\n this.#honoApp.get(health?.path ?? \"/health\", (c) =>\n c.text(health?.message ?? \"ok\", (health?.status ?? 200) as 200),\n );\n }\n\n const endpoint = `${config.basePath ?? \"\"}${config.endpoint ?? \"/mcp\"}`;\n const handler = this.#handler;\n const host = config.host ?? \"127.0.0.1\";\n const isLoopback = [\"::1\", \"127.0.0.1\", \"localhost\"].includes(host);\n\n // Default-deny on loopback (the DNS-rebinding case); a routable bind is\n // assumed deliberate and must configure its own origins.\n const allowedOrigins =\n config.allowedOrigins ?? (isLoopback ? localhostAllowedOrigins() : []);\n\n if (!config.allowedOrigins && !isLoopback) {\n this.#logger.warn(\n `[ViteMCP warning] no 'allowedOrigins' configured while bound to ${host}; browser origins will be rejected`,\n );\n }\n\n // A Hono route, not a pre-routing short-circuit, so CORS covers it.\n // Routing around Hono 405'd every preflight — and this revision makes\n // every POST preflighted via `Mcp-Method`/`Mcp-Name`.\n this.#honoApp.all(endpoint, async (c) => {\n // Transport security (MUST): a present-but-unrecognised Origin is 403.\n // Stops DNS rebinding; requests with no Origin are unaffected.\n const rejected = originValidationResponse(c.req.raw, allowedOrigins);\n\n if (rejected) {\n return rejected;\n }\n\n const authenticated = await this.#authenticateRequest(c.req.raw);\n\n if (authenticated instanceof Response) {\n return authenticated;\n }\n\n return this.#authStore.run(authenticated, () => handler.fetch(c.req.raw));\n });\n\n const app = this.#honoApp;\n const maxBodySize = config.maxBodySize ?? OAUTH_PROXY_MAX_BODY_SIZE;\n\n const useTls = Boolean(config.sslCert && config.sslKey);\n\n const requestListener = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ) => {\n void (async () => {\n try {\n // The cap must apply before conversion: reading first and\n // measuring after is the DoS this guards against.\n const body = await readCappedNodeBody(req, maxBodySize);\n\n if (body === OVERSIZE) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n // Drain rather than pause (pausing stalls the response), then\n // half-close once the 400 has flushed. A forced destroy would RST\n // while the client is still writing and discard the response.\n req.resume();\n res.once(\"finish\", () => res.socket?.end());\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: `Request body exceeds ${formatBytes(maxBodySize)}`,\n }),\n );\n return;\n }\n\n // Node req/res go through as Hono's env so custom routes can still\n // reach `c.env.incoming`.\n const response = await app.fetch(\n nodeToWebRequest(req, body, useTls, clientDisconnectSignal(res)),\n {\n incoming: req,\n outgoing: res,\n },\n );\n\n res.writeHead(response.status, toNodeHeaders(response.headers));\n\n if (!response.body) {\n res.end();\n return;\n }\n\n // Node holds the head back until the first body byte, which for an\n // SSE stream means the client's `fetch` stays pending until the\n // first event — and a stream that fails before then is a bare\n // socket close with no status to read.\n res.flushHeaders();\n\n // Piped, not buffered: `arrayBuffer()` withholds every byte until\n // the handler is done, which collapses an SSE stream into a single\n // delivery at the end — `reportProgress` then lands with the tool\n // result instead of during the call. `pipeline` also carries a\n // client disconnect back into the body, so an abandoned stream\n // stops producing.\n await pipeline(Readable.fromWeb(response.body), res);\n } catch (error) {\n // Past `writeHead` the exchange is committed: no status is left to\n // send, and ending cleanly would frame a truncated body as a whole\n // one. Abort so the client reads it as the failure it is.\n if (res.headersSent) {\n // A client that hung up first is routine, and its own doing.\n const disconnected =\n (error as NodeJS.ErrnoException).code ===\n \"ERR_STREAM_PREMATURE_CLOSE\";\n\n if (disconnected) {\n this.#logger.debug(\n `[ViteMCP debug] client disconnected mid-response:`,\n error,\n );\n } else {\n this.#logger.error(\n `[ViteMCP error] response stream failed:`,\n error,\n );\n }\n\n res.destroy();\n return;\n }\n\n // A body that aborts mid-stream rejects here. Settle with a 400\n // rather than leaving the exchange pending forever.\n this.#logger.debug(`[ViteMCP debug] request failed:`, error);\n\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: \"Request body could not be read\",\n }),\n );\n }\n })();\n };\n\n // TLS is terminated here when certs are supplied, rather than assuming a\n // proxy in front.\n this.#httpServer = useTls\n ? https.createServer(\n {\n ...(config.sslCa ? { ca: await readFile(config.sslCa) } : {}),\n cert: await readFile(config.sslCert!),\n key: await readFile(config.sslKey!),\n },\n requestListener,\n )\n : http.createServer(requestListener);\n\n await new Promise<void>((resolve) =>\n this.#httpServer!.listen(\n config.port,\n config.host ?? \"127.0.0.1\",\n resolve,\n ),\n );\n\n this.#logger.info(\n `[ViteMCP info] server is running on ${useTls ? \"HTTPS\" : \"HTTP\"} at ${\n useTls ? \"https\" : \"http\"\n }://${config.host ?? \"127.0.0.1\"}:${this.port ?? config.port}${endpoint}`,\n );\n }\n\n /**\n * A tool schema in the form the SDK registers it — see `toSdkSchema` — with\n * a failed conversion reported under the tool's own name.\n */\n async #toSdkSchema(\n schema: unknown,\n label: string,\n io: \"input\" | \"output\",\n ): Promise<unknown> {\n try {\n return await toSdkSchema(schema, io, convertToJsonSchema);\n } catch (error) {\n throw new UnexpectedStateError(\n `${label} is not a supported Standard Schema: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { label },\n );\n }\n }\n\n /**\n * The RFC 6750 §3 challenge sent when `authenticate` refuses a request.\n *\n * `resource_metadata` (RFC 9728 §5.1) is the parameter that turns a bare\n * rejection into a login: it points the client at this server's\n * protected-resource document, from which it discovers the authorization\n * server and starts the flow. It is omitted when this server publishes no\n * such document.\n *\n * The URL is formed from the resource that document names: the address the\n * server was configured as, which is the one a client can reach. The\n * request's own URL is not that address behind a proxy that terminates TLS —\n * it carries the listener's scheme and whatever Host was forwarded, so a\n * challenge built from it sent clients to `http://`, or to an internal host.\n * It is the fallback only, for a document that names no resource.\n */\n #unauthorized(request: Request): Response {\n const published = this.#protectedResource;\n\n return bearerAuthChallengeResponse(\n new OAuthError(OAuthErrorCode.InvalidToken, \"Authentication required\"),\n published\n ? {\n resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(\n toUrl(published.resource) ?? new URL(request.url),\n ),\n }\n : {},\n );\n }\n}\n\n/** `value` as a URL, or `undefined` when it is not an absolute one. */\nconst toUrl = (value: unknown): undefined | URL =>\n typeof value === \"string\" && URL.canParse(value) ? new URL(value) : undefined;\n\n/**\n * An auth provider's OAuth config, naming the MCP endpoint as the protected\n * resource rather than the provider's base URL.\n *\n * RFC 9728 §3.3: the document served at\n * `/.well-known/oauth-protected-resource<endpoint>` must name the URL that\n * path was derived from, and strict clients discard one that does not. The\n * base URL already carries any `basePath`, as the proxy's own endpoints do.\n */\nconst withEndpointAsResource = <\n C extends { protectedResource: { resource: string } },\n>(\n config: C,\n endpoint: string,\n): C => ({\n ...config,\n protectedResource: {\n ...config.protectedResource,\n resource: `${withoutTrailingSlash(config.protectedResource.resource)}${endpoint}`,\n },\n});\n\n/**\n * Builds a web-standard Request from a Node request whose body is already\n * consumed. The SDK's `toWebRequest` would either re-read the drained stream\n * or JSON-stringify the body a second time.\n */\nconst nodeToWebRequest = (\n req: http.IncomingMessage,\n body: Buffer,\n secure: boolean,\n signal: AbortSignal,\n): Request => {\n const host = req.headers.host ?? \"localhost\";\n // Scheme has to follow the listener, or absolute URLs derived from\n // `c.req.url` (issuers, redirect URIs) come out as http:// under TLS.\n const url = `${secure ? \"https\" : \"http\"}://${host}${req.url ?? \"/\"}`;\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(req.headers)) {\n if (value === undefined || name.startsWith(\":\")) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, value);\n }\n }\n\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body.byteLength > 0;\n\n return new Request(url, {\n headers,\n method,\n signal,\n ...(hasBody ? { body } : {}),\n });\n};\n\n/**\n * A response's headers in the form Node writes them.\n *\n * `Headers` folds a repeated header into one comma-joined value, except\n * `Set-Cookie`: a cookie's own `Expires` contains a comma, so it yields an\n * entry per cookie instead. An object keyed by header name keeps only the last\n * of those, which dropped every cookie but one. Given an array, Node writes a\n * header line for each entry.\n */\nconst toNodeHeaders = (headers: Headers): http.OutgoingHttpHeaders => {\n const cookies = headers.getSetCookie();\n\n return {\n ...Object.fromEntries(headers),\n ...(cookies.length > 0 ? { \"set-cookie\": cookies } : {}),\n };\n};\n\n/**\n * Aborts when the client goes away before the response is written.\n *\n * The SDK reads `Request.signal` to tear the exchange down and abort in-flight\n * handlers, and a hand-built `Request` otherwise carries one that never fires\n * — so on Node this has to be wired to the socket. Edge runtimes supply their\n * own and need none of this.\n *\n * Keyed off `res`, not `req`: the request stream is fully drained before this\n * runs, so its `close` has already fired and says nothing about the client.\n */\nconst clientDisconnectSignal = (res: http.ServerResponse): AbortSignal => {\n const controller = new AbortController();\n\n // A completed response emits `close` too; only a premature one is a\n // disconnect.\n const abortIfPremature = () => {\n if (!res.writableEnded) {\n controller.abort(new Error(\"Client disconnected\"));\n }\n };\n\n // Subscribing to an already-closed response would never fire, leaving the\n // handler unaware the caller is gone. Not reachable today — nothing awaits\n // between the body read and here — but one `await` away from being so.\n if (res.closed) {\n abortIfPremature();\n } else {\n res.once(\"close\", abortIfPremature);\n }\n\n return controller.signal;\n};\n\n/**\n * Rejects if a tool outruns its `timeoutMs`, and aborts `timeout.controller`\n * first so `execute` — which reaches that signal through `context.signal` —\n * can abandon whatever it started instead of running on unobserved.\n */\nconst withTimeout = <T>(\n work: Promise<T>,\n timeout: { controller: AbortController; ms: number },\n toolName: string,\n): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n const error = new UserError(\n `Tool '${toolName}' timed out after ${timeout.ms}ms`,\n { timeoutMs: timeout.ms, toolName },\n );\n\n // Abort before rejecting so the reason `execute` observes is the same\n // error the caller receives.\n timeout.controller.abort(error);\n reject(error);\n }, timeout.ms);\n\n work.then(resolve, reject).finally(() => clearTimeout(timer));\n });\n\n/**\n * Builds `context.signal` — never `undefined`, so callers can forward it to\n * `fetch` without a guard — and bounds it to a single handler run.\n *\n * Handing the SDK's request signal straight through would abort on *success*\n * too: the per-request transport is torn down as soon as the result is sent,\n * which aborts every controller it owns. A signal that always ends aborted is\n * useless for the one idiom that matters here — `addEventListener(\"abort\",\n * cleanup)` would roll back every completed call. So the sources are mirrored\n * only while the handler is in flight, and `release()` stops the mirroring.\n *\n * A context built outside a request (`embedded()`) has no sources at all and\n * gets a signal that never fires.\n */\nconst requestScope = (\n ...sources: (AbortSignal | undefined)[]\n): { release: () => void; signal: AbortSignal } => {\n const controller = new AbortController();\n const detach = new AbortController();\n\n for (const source of sources) {\n if (source === undefined) {\n continue;\n }\n\n if (source.aborted) {\n controller.abort(source.reason);\n break;\n }\n\n source.addEventListener(\"abort\", () => controller.abort(source.reason), {\n once: true,\n signal: detach.signal,\n });\n }\n\n return { release: () => detach.abort(), signal: controller.signal };\n};\n\n/** Sentinel returned when a request body exceeds the configured cap. */\nconst OVERSIZE = Symbol(\"oversize\");\n\n/**\n * Reads a Node request body with a hard cap, bailing out as soon as the limit\n * is crossed rather than after the fact. A declared `Content-Length` over the\n * cap short-circuits before any chunk is read.\n */\nconst readCappedNodeBody = async (\n req: http.IncomingMessage,\n maxBytes: number,\n): Promise<Buffer | typeof OVERSIZE> => {\n const declared = Number(req.headers[\"content-length\"] ?? 0);\n\n if (declared > maxBytes) {\n return OVERSIZE;\n }\n\n let size = 0;\n const chunks: Buffer[] = [];\n\n for await (const chunk of req) {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);\n size += buf.byteLength;\n\n if (size > maxBytes) {\n return OVERSIZE;\n }\n\n chunks.push(buf);\n }\n\n return Buffer.concat(chunks);\n};\n\n/**\n * JSON Schema for a Standard Schema that has none of its own, for advertising:\n * Valibot's own converter for Valibot, and xsschema for every other library.\n */\nconst convertToJsonSchema: JsonSchemaConverter = async (schema, io) =>\n schema[\"~standard\"].vendor === \"valibot\"\n ? valibotToJsonSchema(schema, io)\n : toJsonSchema(schema);\n\n/** Rejects non-Standard-Schema at registration, not on first call. */\nconst assertStandardSchema = (\n schema: unknown,\n toolName: string,\n field: \"outputSchema\" | \"parameters\",\n) => {\n if (schema === undefined) {\n return;\n }\n\n const standard = (schema as { \"~standard\"?: { validate?: unknown } })?.[\n \"~standard\"\n ];\n\n if (typeof standard?.validate !== \"function\") {\n throw new UnexpectedStateError(\n `Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,\n { toolName },\n );\n }\n};\n\n/**\n * Whether `value` passes a tool's output schema, as the SDK registered it. No\n * schema passes anything, and one that throws passes nothing.\n */\nconst matchesOutputSchema = async (\n schema: unknown,\n value: unknown,\n): Promise<boolean> => {\n if (!schema) {\n return true;\n }\n\n try {\n const result = await (schema as StandardSchemaV1)[\"~standard\"].validate(\n value,\n );\n\n return !result.issues;\n } catch {\n return false;\n }\n};\n\nconst promptArgsSchema = <T extends ViteMCPAuth>(prompt: Prompt<T>) => {\n const args = prompt.arguments;\n\n if (!args?.length) {\n return undefined;\n }\n\n const shape: Record<string, z.ZodType> = {};\n for (const arg of args) {\n const explicitCompleter =\n arg.complete ??\n (prompt.complete\n ? (value: string) => prompt.complete!(arg.name, value)\n : undefined);\n\n // An enum completes itself unless the author said otherwise. The spec's\n // prompt argument carries only name/description/required, so `prompts/list`\n // has nowhere to put the permitted values and completion is the one channel\n // that can reach the client — without this the argument is validated\n // against a set the client is never shown.\n const enumValues = arg.enum;\n const completer =\n explicitCompleter ??\n (enumValues?.length\n ? async (value: string): Promise<Completion> => ({\n // An empty value is how an editor asks for the whole set before the\n // user has typed anything; filtering it would answer with nothing.\n values: value\n ? enumValues.filter((option) =>\n option.toLowerCase().includes(value.toLowerCase()),\n )\n : [...enumValues],\n })\n : undefined);\n\n // The enum belongs on the schema too: that is what `prompts/get` checks the\n // incoming argument against.\n const valueSchema = enumValues?.length\n ? z.enum(enumValues as [string, ...string[]])\n : z.string();\n const described = arg.description\n ? valueSchema.describe(arg.description)\n : valueSchema;\n const base = completer\n ? completable(\n described,\n (async (value: string) => (await completer(value)).values) as never,\n )\n : described;\n shape[arg.name] = (arg.required ? base : base.optional()) as z.ZodType;\n }\n\n return ownKeysOnly(z.object(shape));\n};\n\n/** The `StructuredResult` wrapper and nothing else — see `normalizeToolResult`. */\nconst isStructuredResult = (\n value: Record<string, unknown>,\n): value is StructuredResult => {\n // Own properties only: an inherited `structuredContent` — a getter on a model\n // or ORM prototype, say — is not a nomination.\n if (\n !Object.hasOwn(value, \"structuredContent\") ||\n value.structuredContent === undefined\n ) {\n return false;\n }\n\n // The companions are copied into the result envelope as they stand, so a\n // wrongly typed one would put an unserializable value on the wire and fail\n // the call itself. Declining the wrapper leaves the whole object to be read\n // as a payload, which costs a tool error at worst.\n if (value.isError !== undefined && typeof value.isError !== \"boolean\") {\n return false;\n }\n\n if (\n value._meta !== undefined &&\n (typeof value._meta !== \"object\" ||\n value._meta === null ||\n Array.isArray(value._meta))\n ) {\n return false;\n }\n\n // A key with no value cannot be what makes this a payload rather than a\n // wrapper — it never reaches the wire either way, so `{ structuredContent,\n // trace: debug ? id : undefined }` is still a wrapper.\n return Object.keys(value).every(\n (key) =>\n key === \"structuredContent\" ||\n key === \"isError\" ||\n key === \"_meta\" ||\n value[key] === undefined,\n );\n};\n\n/**\n * Normalizes the several shapes `execute` may return into a CallToolResult.\n *\n * Most of these shapes are told apart by inspecting the returned value, which\n * is a guess: a structured payload is an arbitrary object and can carry the\n * same keys the shorthands are recognized by. `hasOutputSchema` narrows that\n * guess — a tool that declared an output schema returns its structured payload\n * directly — and `structuredContent` settles what remains, since the one\n * genuinely ambiguous shape cannot be resolved by inspection at all.\n */\nconst normalizeToolResult = (\n result: unknown,\n hasOutputSchema: boolean,\n): unknown => {\n if (result === undefined || result === null) {\n return { content: [] };\n }\n\n if (typeof result === \"string\") {\n return { content: [{ text: result, type: \"text\" }] };\n }\n\n if (typeof result === \"object\") {\n const value = result as Record<string, unknown>;\n\n // Already an input_required (MRTR) or a full content result — pass through.\n //\n // A structured payload with its own array-valued `content` field is\n // indistinguishable from content blocks here, and loses: inspecting the\n // elements would only move the guess, and an empty array carries nothing to\n // inspect. Such a tool returns `{ structuredContent }` instead.\n if (value.resultType === \"input_required\" || Array.isArray(value.content)) {\n return value;\n }\n\n // Stated outright, so no guessing: the payload is whatever `execute`\n // nominated, and the fallback below is written for it as usual. Passing the\n // value through unread would nest it under a second `structuredContent`.\n //\n // Only the bare wrapper counts. Anything carrying keys of its own is a\n // payload that happens to have a `structuredContent` field, and unwrapping\n // it would both drop those keys and put them on the wire, where a field\n // `execute` meant for itself does not belong.\n if (isStructuredResult(value)) {\n return {\n content: [\n {\n // `undefined` is excluded already; this covers what else JSON\n // declines to represent, so a broken payload stays a tool error\n // rather than an unserializable content block.\n text: JSON.stringify(value.structuredContent) ?? \"null\",\n type: \"text\",\n },\n ],\n structuredContent: value.structuredContent,\n ...(value.isError === undefined ? {} : { isError: value.isError }),\n ...(value._meta === undefined ? {} : { _meta: value._meta }),\n };\n }\n\n // The single-content-block shorthand, off once an output schema is declared:\n // a structured payload discriminated on `type` is the ordinary way to write\n // a union, and reading one as a content block would drop the payload the\n // schema promised. Such a tool cannot be after the shorthand anyway — a\n // declared schema makes `structuredContent` mandatory.\n if (\n !hasOutputSchema &&\n (value.type === \"text\" ||\n value.type === \"image\" ||\n value.type === \"audio\" ||\n value.type === \"resource\" ||\n value.type === \"resource_link\")\n ) {\n return { content: [value] };\n }\n\n // Also carry serialized JSON as text, for clients that ignore\n // `structuredContent`.\n return {\n content: [{ text: JSON.stringify(value), type: \"text\" }],\n structuredContent: value,\n };\n }\n\n return { content: [{ text: String(result), type: \"text\" }] };\n};\n\nexport { delay };\n\n// Convenience re-exports so the common auth surface is reachable from the\n// package root; `@vitemcp/server/auth` remains the full module.\nexport {\n AuthProvider,\n AzureProvider,\n getAuthSession,\n GitHubProvider,\n GoogleProvider,\n OAuthProvider,\n requireAll,\n requireAny,\n requireAuth,\n requireRole,\n requireScopes,\n} from \"./auth/index.js\";\n\nexport type {\n AuthProviderConfig,\n AzureProviderConfig,\n AzureSession,\n GenericOAuthProviderConfig,\n GitHubSession,\n GoogleSession,\n OAuthSession,\n} from \"./auth/index.js\";\n\n// `ServerOptions.oauth.proxy` is typed as this, so it must be nameable here.\nexport { OAuthProxy, OAuthProxyError } from \"./auth/OAuthProxy.js\";\n\nexport { DiscoveryDocumentCache } from \"./DiscoveryDocumentCache.js\";\n\nexport {\n jsonSchemaAdapter,\n type JsonSchemaObject,\n type JsonSchemaStandardSchema,\n} from \"./jsonSchemaAdapter.js\";\n\n// Re-exported because they appear in this package's public signatures and\n// `@modelcontextprotocol/server` is only a transitive dependency for consumers.\nexport type {\n CacheScope,\n Icon,\n InputRequest,\n InputRequiredResult,\n ToolAnnotations,\n} from \"@modelcontextprotocol/server\";\n","/** OAuth proxy HTTP routes, as a Hono router. */\nimport { Hono } from \"hono\";\n\nimport type { OAuthProxy } from \"./OAuthProxy.js\";\n\n/** Bodies larger than this are rejected before parsing (DoS guard). */\nexport const OAUTH_PROXY_MAX_BODY_SIZE = 1024 * 1024;\n\ntype OAuthErrorish = {\n statusCode?: number;\n toJSON?: () => unknown;\n};\n\nconst errorResponse = (error: unknown) => {\n const err = error as OAuthErrorish;\n return {\n body: err.toJSON?.() ?? { error: \"invalid_request\" },\n status: (err.statusCode ?? 400) as 400,\n };\n};\n\n/**\n * Reads a body under a hard cap, enforced *while* reading — measuring after\n * buffering would let a client push arbitrary bytes into memory.\n *\n * Returns `null` when the body is too large, aborted, or unreadable.\n */\nconst readCappedBody = async (request: Request): Promise<null | string> => {\n const declared = request.headers.get(\"content-length\");\n\n if (declared && Number(declared) > OAUTH_PROXY_MAX_BODY_SIZE) {\n return null;\n }\n\n if (!request.body) {\n try {\n const text = await request.text();\n return text.length > OAUTH_PROXY_MAX_BODY_SIZE ? null : text;\n } catch {\n return null;\n }\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > OAUTH_PROXY_MAX_BODY_SIZE) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n } catch {\n // Aborted or errored mid-body: settle rather than leaving it pending.\n return null;\n }\n\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\nconst readJsonBody = async (request: Request): Promise<null | unknown> => {\n const text = await readCappedBody(request);\n\n if (text === null) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\nconst tooLarge = {\n error: \"invalid_request\",\n error_description: `Request body exceeds ${OAUTH_PROXY_MAX_BODY_SIZE / (1024 * 1024)} MiB`,\n};\n\n/**\n * RFC 6749 §5.1 mandates these on token endpoint responses, and RFC 7591\n * §3.2.1 on a registration response carrying `client_secret`: without them a\n * CDN, a forward proxy or the browser is free to retain the credential.\n *\n * Applied to every response from those two endpoints, error paths included —\n * an error is exactly the response an intermediary is most likely to consider\n * cacheable, and the endpoint should not vary in cacheability by outcome.\n * `authorize`, `callback` and `consent` are left alone: they redirect, and\n * carry no credential in the body.\n */\nconst noStore = {\n \"Cache-Control\": \"no-store\",\n Pragma: \"no-cache\",\n};\n\n/**\n * RFC 8414 / 9728 metadata is snake_case on the wire; config is camelCase.\n * Top-level keys only — nested values are caller-defined payloads.\n */\nconst toSnakeCase = (value: unknown): unknown => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([k, v]) => [\n k.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase(),\n v,\n ]),\n );\n};\n\nexport type OAuthRouterOptions = {\n authorizationServer?: unknown;\n /** Path prefix the server is mounted under, e.g. \"/issuer1\". */\n basePath?: string;\n /** MCP endpoint path, e.g. \"/mcp\". */\n endpoint?: string;\n protectedResource?: unknown;\n /** Optional: discovery metadata can be served without a proxy. */\n proxy?: OAuthProxy;\n};\n\nexport const createOAuthRouter = (options: OAuthRouterOptions): Hono => {\n const app = new Hono();\n const { proxy } = options;\n\n const basePath = options.basePath ?? \"\";\n const endpoint = options.endpoint ?? \"\";\n\n // RFC 8414 §3 / 9728 §3: exact routes, not wildcards — an unrelated suffix\n // must 404 rather than serve metadata.\n const serve = (path: string, body: unknown) =>\n app.get(path, (c) => c.json(body as never));\n\n if (options.authorizationServer) {\n // Issuer-scoped: under a base path, the bare root is not valid.\n serve(\n `/.well-known/oauth-authorization-server${basePath}`,\n toSnakeCase(options.authorizationServer),\n );\n }\n\n if (options.protectedResource) {\n const body = toSnakeCase(options.protectedResource);\n const scoped = `/.well-known/oauth-protected-resource${basePath}${endpoint}`;\n\n // Sub-path takes priority; root stays as the documented fallback.\n serve(scoped, body);\n\n if (scoped !== \"/.well-known/oauth-protected-resource\") {\n serve(\"/.well-known/oauth-protected-resource\", body);\n }\n }\n\n if (!proxy) {\n return app;\n }\n\n // RFC 7591 Dynamic Client Registration.\n app.post(`${basePath}/oauth/register`, async (c) => {\n const body = await readJsonBody(c.req.raw);\n\n if (body === null) {\n return c.json(tooLarge, 400, noStore);\n }\n\n try {\n return c.json(await proxy.registerClient(body as never), 201, noStore);\n } catch (error) {\n const { body: errBody, status } = errorResponse(error);\n return c.json(errBody as never, status, noStore);\n }\n });\n\n app.get(`${basePath}/oauth/authorize`, async (c) => {\n try {\n const params = Object.fromEntries(\n new URL(c.req.url).searchParams.entries(),\n );\n return await proxy.authorize(params as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.post(`${basePath}/oauth/token`, async (c) => {\n const raw = c.req.raw;\n const text = await readCappedBody(raw);\n\n if (text === null) {\n return c.json(tooLarge, 400, noStore);\n }\n\n try {\n const params = Object.fromEntries(new URLSearchParams(text).entries());\n\n // RFC 6749 §2.3.1: credentials may arrive via Basic auth. Body wins.\n const authHeader = raw.headers.get(\"authorization\");\n\n if (authHeader?.toLowerCase().startsWith(\"basic \")) {\n const decoded = Buffer.from(authHeader.slice(6), \"base64\").toString(\n \"utf8\",\n );\n const separator = decoded.indexOf(\":\");\n\n if (separator !== -1) {\n params.client_id ||= decodeURIComponent(decoded.slice(0, separator));\n params.client_secret ||= decodeURIComponent(\n decoded.slice(separator + 1),\n );\n }\n }\n\n const result =\n params.grant_type === \"refresh_token\"\n ? await proxy.exchangeRefreshToken(params as never)\n : await proxy.exchangeAuthorizationCode(params as never);\n\n return c.json(result as never, 200, noStore);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status, noStore);\n }\n });\n\n app.get(`${basePath}/oauth/callback`, async (c) =>\n proxy.handleCallback(c.req.raw),\n );\n\n app.all(`${basePath}/oauth/consent`, async (c) =>\n proxy.handleConsent(c.req.raw),\n );\n\n return app;\n};\n","/**\n * Releases a response whose body we are about to discard.\n *\n * Throwing on a non-2xx without touching the body leaves an unread stream, and\n * the connection stays checked out until GC finalizes it. Cancellation failures\n * are swallowed so the caller still reports the original HTTP status, which is\n * the useful diagnostic.\n *\n * Typed structurally rather than as `Response` because callers use both\n * undici's fetch and the global one.\n */\nexport const cancelResponseBody = async (response: {\n body?: { cancel: () => Promise<unknown> } | null;\n}): Promise<void> => {\n if (!response.body) {\n return;\n }\n\n try {\n await response.body.cancel();\n } catch {\n // Nothing to report: the HTTP failure is what the caller cares about.\n }\n};\n","import { cancelResponseBody } from \"./cancelResponseBody.js\";\n\nexport class DiscoveryDocumentCache {\n public get size(): number {\n return this.#cache.size;\n }\n\n #cache: Map<\n string,\n {\n data: unknown;\n expiresAt: number;\n }\n > = new Map();\n\n #generation = 0;\n\n #inFlight: Map<string, Promise<unknown>> = new Map();\n\n #timeoutMs: number;\n\n #ttl: number;\n\n #urlGenerations: Map<string, number> = new Map();\n\n /**\n * @param options - configuration options\n * @param options.timeoutMs - timeout in miliseconds for the upstream fetch\n * @param options.ttl - time-to-live in miliseconds\n */\n public constructor(options: { timeoutMs?: number; ttl?: number } = {}) {\n this.#timeoutMs = options.timeoutMs ?? 10000; // default 10 seconds\n this.#ttl = options.ttl ?? 3600000; // default 1 hour\n }\n\n /**\n * @param url - optional URL to clear. if omitted, clears all cached documents.\n */\n public clear(url?: string): void {\n if (url) {\n this.#cache.delete(url);\n this.#inFlight.delete(url);\n this.#urlGenerations.set(url, (this.#urlGenerations.get(url) ?? 0) + 1);\n } else {\n this.#cache.clear();\n this.#inFlight.clear();\n this.#urlGenerations.clear();\n this.#generation++;\n }\n }\n\n /**\n * fetches a discovery document from the given URL.\n * uses cached value if available and not expired.\n * coalesces concurrent requests for the same URL to prevent duplicate fetches.\n *\n * @param url - the discovery document URL (e.g., /.well-known/openid-configuration)\n * @returns the discovery document as a JSON object\n * @throws Error if the fetch fails or returns non-OK status\n */\n public async get(url: string): Promise<unknown> {\n const now = Date.now();\n const cached = this.#cache.get(url);\n\n // return cached value if still valid\n if (cached && cached.expiresAt > now) {\n return cached.data;\n }\n\n // check if there’s already an in-flight request for this URL\n const inFlight = this.#inFlight.get(url);\n\n if (inFlight) {\n return inFlight;\n }\n\n // create a new fetch promise and store it\n const fetchPromise = this.#fetchAndCache(\n url,\n this.#generation,\n this.#urlGenerations.get(url) ?? 0,\n );\n\n this.#inFlight.set(url, fetchPromise);\n\n try {\n const data = await fetchPromise;\n return data;\n } finally {\n // clean up in-flight promise after completion\n // (success or failure)\n if (this.#inFlight.get(url) === fetchPromise) {\n this.#inFlight.delete(url);\n }\n }\n }\n\n /**\n * @param url - the URL to check\n * @returns true if the URL is cached and nott expired\n */\n public has(url: string): boolean {\n const cached = this.#cache.get(url);\n\n if (!cached) {\n return false;\n }\n\n const now = Date.now();\n\n if (cached.expiresAt <= now) {\n // expired, remove from cache\n this.#cache.delete(url);\n return false;\n }\n\n return true;\n }\n\n async #fetchAndCache(\n url: string,\n generation: number,\n urlGeneration: number,\n ): Promise<unknown> {\n // fetch fresh document, bounded by the configured timeout\n let res: Response;\n try {\n res = await fetch(url, {\n signal: AbortSignal.timeout(this.#timeoutMs),\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n ) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: timed out after ${this.#timeoutMs}ms`,\n );\n }\n throw error;\n }\n\n if (!res.ok) {\n await cancelResponseBody(res);\n\n throw new Error(\n `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`,\n );\n }\n\n const data = await res.json();\n // calculate expiration time AFTER fetch completes\n const expiresAt = Date.now() + this.#ttl;\n\n // A clear that occurred while the fetch was pending invalidates its result.\n if (\n this.#generation === generation &&\n (this.#urlGenerations.get(url) ?? 0) === urlGeneration\n ) {\n this.#cache.set(url, {\n data,\n expiresAt,\n });\n }\n\n return data;\n }\n}\n","import { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * A plain JSON Schema object descriptor.\n */\nexport type JsonSchemaObject = {\n [key: string]: unknown;\n $schema?: string;\n additionalProperties?: boolean | Record<string, unknown>;\n properties?: Record<string, unknown>;\n required?: string[];\n type: string;\n};\n\n/**\n * A Standard Schema that also carries the JSON Schema it was built from.\n *\n * `~standard.jsonSchema` is the Standard JSON Schema extension. Anything that\n * knows about it — including the `xsschema` conversion ViteMCP uses to build\n * `tools/list` — reads the schema straight off the object instead of trying to\n * derive one from a validation library it does not recognise.\n */\nexport interface JsonSchemaStandardSchema extends StandardSchemaV1 {\n readonly \"~standard\": {\n readonly jsonSchema: {\n readonly input: () => JsonSchemaObject;\n readonly output: () => JsonSchemaObject;\n };\n } & StandardSchemaV1.Props;\n}\n\ninterface AjvErrorObject {\n instancePath: string;\n keyword: string;\n message?: string;\n params?: Record<string, unknown>;\n}\n\ntype AjvValidateFunction = {\n errors?: AjvErrorObject[] | null;\n (data: unknown): boolean;\n};\n\n/**\n * Wraps a plain JSON Schema object for use as a tool's `parameters` or\n * `outputSchema`, without pulling in Zod or Valibot.\n *\n * Validation uses AJV, an optional peer dependency — install `ajv` (plus\n * `ajv-formats` for `format` keywords). It is imported on first validation, so\n * servers that never call it pay nothing.\n *\n * @example\n * ```ts\n * server.addTool({\n * name: \"greet\",\n * parameters: jsonSchemaAdapter({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * required: [\"name\"],\n * }),\n * execute: async ({ name }) => `Hello, ${name}!`,\n * });\n * ```\n */\nexport function jsonSchemaAdapter(\n schema: JsonSchemaObject,\n): JsonSchemaStandardSchema {\n // Compiling a schema makes AJV generate and evaluate JavaScript, so it has\n // to happen once rather than per call. The promise is memoised, not just the\n // result, so concurrent first calls share a single compilation.\n let compiled: Promise<AjvValidateFunction> | undefined;\n\n const getValidator = (): Promise<AjvValidateFunction> => {\n compiled ??= compileSchema(schema).catch((error: unknown) => {\n // Do not memoise a failure: a missing dependency should be reported on\n // every call, not swallowed after the first.\n compiled = undefined;\n throw error;\n });\n\n return compiled;\n };\n\n return {\n \"~standard\": {\n jsonSchema: {\n input: () => schema,\n output: () => schema,\n },\n validate: async (\n data: unknown,\n ): Promise<StandardSchemaV1.Result<unknown>> => {\n const validate = await getValidator();\n\n if (validate(data)) {\n return { value: data };\n }\n\n return { issues: (validate.errors ?? []).map(toIssue) };\n },\n vendor: \"json-schema\",\n version: 1,\n },\n };\n}\n\n/**\n * The JSON Schema dialect a schema is validated in, read from its `$schema` as\n * the MCP SDK reads it: 2020-12 when there is none (SEP-1613), and draft-07 for\n * draft-06, which draft-07 only added to.\n *\n * Clients validate structured content in that dialect, so validating in\n * another has the two disagree. AJV's default engine is draft-07's, which read\n * 2020-12's `items: false` beside `prefixItems` as \"no items at all\", and\n * failed to compile a schema declaring 2020-12.\n */\nconst dialectOf = ($schema: unknown): \"2019-09\" | \"2020-12\" | \"draft-07\" => {\n if (typeof $schema !== \"string\") {\n return \"2020-12\";\n }\n\n switch ($schema.replace(/^https?:\\/\\//, \"\").replace(/#$/, \"\")) {\n case \"json-schema.org/draft-06/schema\":\n case \"json-schema.org/draft-07/schema\":\n return \"draft-07\";\n case \"json-schema.org/draft/2019-09/schema\":\n return \"2019-09\";\n case \"json-schema.org/draft/2020-12/schema\":\n return \"2020-12\";\n }\n\n throw new Error(\n `JSON Schema declares an unsupported dialect (\"$schema\": \"${$schema}\"). ` +\n \"jsonSchemaAdapter validates 2020-12, 2019-09, draft-07 and draft-06.\",\n );\n};\n\nasync function compileSchema(\n schema: JsonSchemaObject,\n): Promise<AjvValidateFunction> {\n // `$schema` picks the engine, and the engine checks the schema against its\n // own dialect's meta-schema. Left in, `$schema` would have to use the scheme\n // AJV registered that meta-schema under — `http:` for draft-07, `https:` for\n // the rest — or compiling fails as \"no schema with key or ref\". What is\n // advertised is `schema`, `$schema` and all.\n const { $schema, ...body } = schema;\n const dialect = dialectOf($schema);\n let ajvModule;\n\n try {\n ajvModule =\n dialect === \"2020-12\"\n ? await import(\"ajv/dist/2020.js\")\n : dialect === \"2019-09\"\n ? await import(\"ajv/dist/2019.js\")\n : await import(\"ajv\");\n } catch {\n throw new Error(\n 'The \"ajv\" package is required to validate JSON Schema tool parameters. ' +\n \"Install it with: npm install ajv\",\n );\n }\n\n // ajv ships CommonJS, so depending on the loader the class arrives as the\n // module namespace, as `.default`, or as `.default.default`.\n const Ajv = unwrapDefault(unwrapDefault(ajvModule)) as unknown as new (\n options: Record<string, unknown>,\n ) => {\n compile: (schema: unknown) => AjvValidateFunction;\n };\n\n // A key counts as present only if the data has it of its own. AJV otherwise\n // reads `data[key]`, which finds `Object.prototype`'s members, so leaving\n // out an optional `toString` or `constructor` failed as \"must be string\".\n const ajv = new Ajv({ allErrors: true, ownProperties: true, strict: false });\n\n try {\n const formatsModule = await import(\"ajv-formats\");\n const addFormats = unwrapDefault(\n unwrapDefault(formatsModule),\n ) as unknown as (ajv: unknown) => void;\n\n addFormats(ajv);\n } catch {\n // ajv-formats is optional; `format` keywords are simply not enforced.\n }\n\n return ajv.compile(body);\n}\n\nfunction toIssue(error: AjvErrorObject): StandardSchemaV1.Issue {\n // Only the first split element is the empty string before the leading `/`.\n // Any other empty segment is a property named \"\", which is a legal key.\n const path = error.instancePath\n .split(\"/\")\n .slice(1)\n // JSON Pointer escapes, per RFC 6901.\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"))\n .map((segment): number | string => {\n const index = Number(segment);\n return /^(?:0|[1-9]\\d*)$/.test(segment) && Number.isSafeInteger(index)\n ? index\n : segment;\n });\n\n // AJV reports a missing property against its parent object, with the name in\n // `params`. Appending it points the issue at the field the user has to fix.\n const missingProperty = error.params?.missingProperty;\n\n if (error.keyword === \"required\" && typeof missingProperty === \"string\") {\n path.push(missingProperty);\n }\n\n return {\n message: error.message || \"Validation error\",\n path,\n };\n}\n\nfunction unwrapDefault(value: unknown): unknown {\n return typeof value === \"object\" && value !== null && \"default\" in value\n ? (value as { default: unknown }).default\n : value;\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAoB;AAAA,EAGpB;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAEK;AAEP,SAAS,yBAAyB;AAClC,SAAS,gBAAgB;AACzB,SAAS,QAAAA,aAAY;AACrB,SAAS,YAAY;AACrB,OAAO,UAAU;AACjB,OAAO,WAAW;AAClB,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,SAAS,cAAc,aAAa;AACpC,SAAS,SAAAC,cAAa;AACtB,SAAS,oBAAoB;AAC7B,SAAS,SAAS;;;ACxClB,SAAS,YAAY;AAKd,IAAM,4BAA4B,OAAO;AAOhD,IAAM,gBAAgB,CAAC,UAAmB;AACxC,QAAM,MAAM;AACZ,SAAO;AAAA,IACL,MAAM,IAAI,SAAS,KAAK,EAAE,OAAO,kBAAkB;AAAA,IACnD,QAAS,IAAI,cAAc;AAAA,EAC7B;AACF;AAQA,IAAM,iBAAiB,OAAO,YAA6C;AACzE,QAAM,WAAW,QAAQ,QAAQ,IAAI,gBAAgB;AAErD,MAAI,YAAY,OAAO,QAAQ,IAAI,2BAA2B;AAC5D,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,QAAQ,MAAM;AACjB,QAAI;AACF,YAAM,OAAO,MAAM,QAAQ,KAAK;AAChC,aAAO,KAAK,SAAS,4BAA4B,OAAO;AAAA,IAC1D,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,QAAM,SAAS,QAAQ,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AG;AACzE,aAAO;AAAA,IACT;AAUA,QAAI,mBAAmB,KAAK,GAAG;AAC7B,aAAO;AAAA,QACL,SAAS;AAAA,UACP;AAAA;AAAA;AAAA;AAAA,YAIE,MAAM,KAAK,UAAU,MAAM,iBAAiB,KAAK;AAAA,YACjD,MAAM;AAAA,UACR;AAAA,QACF;AAAA,QACA,mBAAmB,MAAM;AAAA,QACzB,GAAI,MAAM,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;AAAA,QAChE,GAAI,MAAM,UAAU,SAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;AAAA,MAC5D;AAAA,IACF;AAOA,QACE,CAAC,oBACA,MAAM,SAAS,UACd,MAAM,SAAS,WACf,MAAM,SAAS,WACf,MAAM,SAAS,cACf,MAAM,SAAS,kBACjB;AACA,aAAO,EAAE,SAAS,CAAC,KAAK,EAAE;AAAA,IAC5B;AAIA,WAAO;AAAA,MACL,SAAS,CAAC,EAAE,MAAM,KAAK,UAAU,KAAK,GAAG,MAAM,OAAO,CAAC;AAAA,MACvD,mBAAmB;AAAA,IACrB;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,OAAO,MAAM,GAAG,MAAM,OAAO,CAAC,EAAE;AAC7D;","names":["Hono","fetch","fetch","ServerState","Hono"]}
1
+ {"version":3,"sources":["../src/ViteMCP.ts","../src/auth/router.ts","../src/cancelResponseBody.ts","../src/DiscoveryDocumentCache.ts","../src/jsonSchemaAdapter.ts"],"sourcesContent":["import {\n acceptedContent,\n bearerAuthChallengeResponse,\n type CacheScope,\n completable,\n createMcpHandler,\n getOAuthProtectedResourceMetadataUrl,\n type Icon,\n InMemoryServerEventBus,\n type InputRequest,\n inputRequired,\n type InputRequiredResult,\n localhostAllowedOrigins,\n LOG_LEVEL_META_KEY,\n type LoggingLevel,\n type McpHttpHandler,\n McpServer,\n OAuthError,\n OAuthErrorCode,\n originValidationResponse,\n ResourceTemplate as SDKResourceTemplate,\n type ToolAnnotations as SDKToolAnnotations,\n type ServerEventBus,\n UriTemplate,\n} from \"@modelcontextprotocol/server\";\nimport {\n serveStdio,\n type StdioServerHandle,\n} from \"@modelcontextprotocol/server/stdio\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport { readFile } from \"fs/promises\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport http from \"http\";\nimport https from \"https\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { setTimeout as delay } from \"timers/promises\";\nimport { fetch } from \"undici\";\nimport { toJsonSchema } from \"xsschema\";\nimport { z } from \"zod\";\n\nimport type { OAuthProxy } from \"./auth/OAuthProxy.js\";\nimport type {\n AuthProvider,\n OAuthSession,\n} from \"./auth/providers/AuthProvider.js\";\n\nimport { createOAuthRouter, OAUTH_PROXY_MAX_BODY_SIZE } from \"./auth/router.js\";\nimport { withoutTrailingSlash } from \"./auth/utils/trailingSlash.js\";\nimport { cancelResponseBody } from \"./cancelResponseBody.js\";\nimport { formatBytes } from \"./formatBytes.js\";\nimport { ownKeysOnly } from \"./ownKeysOnly.js\";\nimport {\n type JsonSchemaConverter,\n toSdkSchema,\n valibotToJsonSchema,\n} from \"./toSdkSchema.js\";\n\nexport interface Logger {\n debug: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport const MEDIA_FETCH_TIMEOUT_MS = 30000;\n\nexport type MediaSource = { timeoutMs?: number } & (\n | { buffer: Buffer }\n | { path: string }\n | { url: string }\n);\n\nexport abstract class ViteMCPError extends Error {\n public constructor(message?: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\nexport class UnexpectedStateError extends ViteMCPError {\n public extras?: Record<string, unknown>;\n\n public constructor(message: string, extras?: Record<string, unknown>) {\n super(message);\n this.name = new.target.name;\n this.extras = extras;\n }\n}\n\n/**\n * An error that is meant to be surfaced to the user, rather than logged as an\n * internal failure. Thrown from a tool handler, it becomes the tool's error\n * result rather than a protocol-level error.\n */\nexport class UserError extends UnexpectedStateError {}\n\n/**\n * What may come before an SVG's root element: a processing instruction — the\n * XML declaration, or one such as `<?xml-stylesheet?>` — a comment, or a\n * doctype, internal subset included, as Illustrator writes one.\n */\nconst XML_PROLOG_ITEM =\n /^(?:<\\?[\\s\\S]*?\\?>|<!--[\\s\\S]*?-->|<!DOCTYPE\\s[^[>]*(?:\\[[\\s\\S]*?\\])?\\s*>)/;\n\n/** Whether `data` is an SVG document: past any prolog, its root is `<svg>`. */\nconst isSvg = (data: Buffer): boolean => {\n // `trimStart` drops a byte order mark as well: U+FEFF is whitespace to it.\n let text = data.toString(\"utf8\").trimStart();\n let item = XML_PROLOG_ITEM.exec(text);\n\n while (item) {\n text = text.slice(item[0].length).trimStart();\n item = XML_PROLOG_ITEM.exec(text);\n }\n\n return /^<svg[\\s/>]/.test(text);\n};\n\n/**\n * The MIME type of a `kind` media block. What `file-type` sniffed in `data`\n * wins when it is of that kind, but it reads binary signatures only:\n *\n * - an SVG is text, so it sniffs as nothing, or as `application/xml` after an\n * XML declaration;\n * - WebM and MP4 sniff as video whatever they hold, though a browser's\n * MediaRecorder writes audio-only ones;\n * - headerless audio, such as raw PCM, sniffs as nothing.\n *\n * Past those, `declared` — the `Content-Type` a URL answered with — is used\n * when it is of the block's kind. A path or a buffer declares nothing.\n */\nconst mediaTypeOf = (\n data: Buffer,\n kind: \"audio\" | \"image\",\n sniffed: string | undefined,\n declared: null | string,\n): string => {\n if (sniffed?.startsWith(`${kind}/`)) {\n return sniffed;\n }\n\n if (kind === \"image\" && isSvg(data)) {\n return \"image/svg+xml\";\n }\n\n // Ahead of `declared`: the container is certain, and the caller has said\n // that what it holds is audio.\n if (\n kind === \"audio\" &&\n (sniffed === \"video/mp4\" || sniffed === \"video/webm\")\n ) {\n return sniffed.replace(\"video/\", \"audio/\");\n }\n\n // Without its parameters, since `audio/webm; codecs=opus` is still WebM, and\n // lowercased, since media types are case-insensitive.\n const declaredType = declared?.split(\";\")[0].trim().toLowerCase();\n\n if (declaredType?.startsWith(`${kind}/`)) {\n return declaredType;\n }\n\n return sniffed ?? (kind === \"image\" ? \"image/png\" : \"audio/mpeg\");\n};\n\nconst readMedia = async (\n source: MediaSource,\n kind: \"audio\" | \"image\",\n): Promise<{ data: string; mimeType: string }> => {\n let rawData: Buffer;\n let declared: null | string = null;\n\n try {\n if (\"url\" in source) {\n const response = await fetch(source.url, {\n signal: AbortSignal.timeout(source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n await cancelResponseBody(response);\n\n throw new Error(`Server responded with status: ${response.status}`);\n }\n\n declared = response.headers.get(\"content-type\");\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in source) {\n rawData = await readFile(source.path);\n } else if (\"buffer\" in source) {\n rawData = source.buffer;\n } else {\n throw new Error(\n `Invalid ${kind} source: provide one of url, path, or buffer`,\n );\n }\n } catch (error) {\n if (\"url\" in source) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `timed out after ${source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n\n throw new Error(\n `Failed to fetch ${kind} from URL (${source.url}): ${reason}`,\n );\n }\n\n if (error instanceof Error) {\n throw error;\n }\n\n throw new Error(`Unexpected error processing ${kind}: ${String(error)}`);\n }\n\n const { fileTypeFromBuffer } = await import(\"file-type\");\n const sniffed = await fileTypeFromBuffer(rawData);\n\n return {\n data: rawData.toString(\"base64\"),\n mimeType: mediaTypeOf(rawData, kind, sniffed?.mime, declared),\n };\n};\n\nexport const imageContent = async (\n source: MediaSource,\n): Promise<ImageContent> => {\n const { data, mimeType } = await readMedia(source, \"image\");\n return { data, mimeType, type: \"image\" } as const;\n};\n\nexport const audioContent = async (\n source: MediaSource,\n): Promise<AudioContent> => {\n const { data, mimeType } = await readMedia(source, \"audio\");\n return { data, mimeType, type: \"audio\" } as const;\n};\n\nexport enum ServerState {\n Error = \"error\",\n Running = \"running\",\n Starting = \"starting\",\n Stopped = \"stopped\",\n}\n\nexport type AudioContent = {\n data: string;\n mimeType: string;\n type: \"audio\";\n};\n\n/**\n * Per-request authentication hook for the HTTP transport.\n *\n * Resolve with the session to attach to `context.auth`. Resolving with `null`\n * or `undefined` **refuses** the request — the transport answers 401 and no\n * handler runs — because a hook that cannot identify the caller has not\n * authenticated them. Set `allowAnonymous` to have a nullish result mean\n * \"anonymous caller\" instead, for servers that deliberately mix public and\n * protected primitives.\n *\n * Throw a `Response` to refuse with an exact status and body of your choosing;\n * it is returned to the client verbatim.\n */\nexport type Authenticate<T> = (\n request: Request,\n) => Promise<null | T | undefined>;\n\n/**\n * Freshness hint attached to cacheable results (`tools/list`, `prompts/list`,\n * `resources/list`, `resources/templates/list`, `resources/read`). Required by\n * the 2026-07-28 revision's `CacheableResult`.\n */\nexport type CacheHint = {\n cacheScope?: CacheScope;\n ttlMs?: number;\n};\n\n/** The spec's completion payload. */\nexport type Completion = {\n hasMore?: boolean;\n total?: number;\n values: string[];\n};\n\nexport type Content =\n | AudioContent\n | ImageContent\n | ResourceContent\n | ResourceLink\n | TextContent;\n\nexport type ContentResult = {\n content: Content[];\n isError?: boolean;\n structuredContent?: unknown;\n};\n\n/**\n * Context handed to `execute` / `load`. Everything here is per-request: the\n * 2026-07-28 revision has no protocol session.\n */\nexport type Context<T extends ViteMCPAuth> = {\n /** Authentication result for this request, if an `authenticate` hook ran. */\n auth: T | undefined;\n\n /**\n * Builds an elicitation request for {@link Context.inputRequired}.\n *\n * A builder, not a promise — the server cannot block waiting for a reply.\n * The client re-issues the whole request with `inputResponses` populated.\n */\n elicit: (params: {\n message: string;\n requestedSchema: StandardSchemaV1;\n }) => InputRequest;\n\n /**\n * Reads one entry of `inputResponses` and validates it against the schema\n * used to request it. Returns `undefined` when the client declined or the\n * content does not match.\n */\n input: <S extends StandardSchemaV1>(\n key: string,\n schema: S,\n ) => StandardSchemaV1.InferOutput<S> | undefined;\n\n /**\n * Ask the client for more input and end this round.\n *\n * `requestState` round-trips through the client, so it is\n * attacker-controlled on return: sign it if it affects authorization.\n */\n inputRequired: (\n inputRequests: Record<string, InputRequest>,\n requestState?: string,\n ) => InputRequiredResult;\n\n /**\n * Present when the client is retrying a request that previously returned\n * `input_required`. Absent on the first call.\n */\n inputResponses?: Record<string, unknown>;\n\n /**\n * Emits `notifications/message`. The spec forbids emitting these unless the\n * request opted in via `_meta` log level, so these are dropped when the\n * client did not ask for logs, and below the level it asked for.\n */\n log: {\n debug: (message: string, data?: SerializableValue) => void;\n error: (message: string, data?: SerializableValue) => void;\n info: (message: string, data?: SerializableValue) => void;\n warn: (message: string, data?: SerializableValue) => void;\n };\n\n reportProgress: (progress: Progress) => Promise<void>;\n\n /** Request ID of the current MCP request. */\n requestId?: string;\n\n /** The `requestState` echoed back by the client on an MRTR retry. */\n requestState?: string;\n\n /**\n * Aborts when this call is cancelled: the client disconnected, a\n * `notifications/cancelled` arrived, or — for a tool with `timeoutMs` — the\n * deadline passed. Forward it to whatever the handler starts (a `fetch`, a\n * subprocess, a query) so that work stops with the request rather than\n * running on unobserved.\n *\n * Scoped to the handler: returning normally leaves it unaborted, so\n * `addEventListener(\"abort\", …)` is safe to use for rollback.\n *\n * Two caveats. `notifications/cancelled` is a no-op on the stateless HTTP\n * transport — a server is minted per request, so a cancellation for a call\n * already in flight has nothing to reach; disconnecting is what cancels\n * there. And `signal.reason` for a `timeoutMs` breach is the `UserError` the\n * caller receives, not a `DOMException`, so code branching on\n * `reason.name === \"AbortError\"` will not match.\n *\n * Always present: a context built outside a request (`embedded()`) carries\n * one that never fires, so callers never have to guard.\n */\n signal: AbortSignal;\n};\n\nexport type ImageContent = {\n data: string;\n mimeType: string;\n type: \"image\";\n};\n\nexport type LoadContext<T extends ViteMCPAuth> = Omit<\n Context<T>,\n \"reportProgress\"\n>;\n\n/**\n * A single loaded resource body. `uri` is optional: when omitted the server\n * fills it in from the resource (or the expanded template) that produced it.\n */\nexport type LoadedResource = {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri?: string;\n};\n\nexport type Progress = {\n message?: string;\n progress: number;\n total?: number;\n};\n\nexport type Prompt<T extends ViteMCPAuth> = {\n arguments?: PromptArgument[];\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any argument. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<{ messages: unknown[] } | string>;\n name: string;\n};\n\nexport type PromptArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n /** Constrains the argument to a fixed set of values. */\n enum?: string[];\n name: string;\n required?: boolean;\n};\n\nexport type Resource<T extends ViteMCPAuth> = {\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n load: (context: LoadContext<T>) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uri: string;\n};\n\nexport type ResourceContent = {\n resource: {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri: string;\n };\n type: \"resource\";\n};\n\nexport type ResourceLink = {\n description?: string;\n mimeType?: string;\n name: string;\n type: \"resource_link\";\n uri: string;\n};\n\nexport type ResourceTemplate<T extends ViteMCPAuth> = {\n arguments?: ResourceTemplateArgument[];\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any template variable. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uriTemplate: string;\n};\n\nexport type ResourceTemplateArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n name: string;\n required?: boolean;\n};\n\nexport type SerializableValue =\n | { [key: string]: SerializableValue }\n | Literal\n | SerializableValue[];\n\nexport type ServerOptions<T extends ViteMCPAuth> = {\n /**\n * Serve requests whose `authenticate` hook resolved with `null`/`undefined`\n * as anonymous — `context.auth` is `undefined` and `canAccess` is the only\n * gate — instead of refusing them with a 401.\n *\n * Off by default: a server that configures authentication and then answers\n * callers it could not identify exposes every tool, resource and prompt that\n * has no `canAccess` guard. Turn it on only for a server that is genuinely\n * public in part, and guard the rest with `canAccess`.\n */\n allowAnonymous?: boolean;\n auth?: AuthProvider<T extends OAuthSession ? T : OAuthSession>;\n authenticate?: Authenticate<T>;\n /**\n * What this server is, for a human reading a client's server list.\n *\n * Distinct from `instructions`, which is addressed to the model and tells it\n * how to use what this server exposes.\n */\n description?: string;\n health?: {\n enabled?: boolean;\n message?: string;\n path?: string;\n status?: number;\n };\n /**\n * Icons a client may show next to this server, most specific first.\n *\n * `src` is a URL the client fetches, so it must be reachable from wherever\n * the client runs — not only from the server.\n */\n icons?: Icon[];\n instructions?: string;\n logger?: Logger;\n name: string;\n oauth?: {\n authorizationServer?: Record<string, unknown>;\n enabled?: boolean;\n protectedResource?: Record<string, unknown>;\n proxy?: OAuthProxy;\n };\n /** Display name, for clients that prefer one over the identifier `name`. */\n title?: string;\n version: `${number}.${number}.${number}`;\n /** Homepage for this server, for clients that link to one. */\n websiteUrl?: string;\n};\n\n/**\n * The structured payload on its own, without the content fallback.\n *\n * Returning this is how a tool states outright that an object is its structured\n * result, for the cases where the shape alone cannot say so — a payload whose\n * own `content` field is an array reads as a list of content blocks otherwise.\n * ViteMCP writes the JSON text fallback, exactly as it does for a plain\n * structured return.\n */\nexport type StructuredResult<T = unknown> = {\n _meta?: Record<string, unknown>;\n isError?: boolean;\n structuredContent: T;\n};\n\nexport type TextContent = {\n text: string;\n type: \"text\";\n};\n\nexport type Tool<\n T extends ViteMCPAuth,\n Params extends ToolParameters = ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n> = {\n _meta?: Record<string, unknown>;\n annotations?: SDKToolAnnotations;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n execute: (\n args: StandardSchemaV1.InferOutput<Params>,\n context: Context<T>,\n ) => Promise<\n | AudioContent\n | ContentResult\n | ImageContent\n | InputRequiredResult\n | ResourceContent\n | ResourceLink\n | StandardSchemaV1.InferOutput<OutputParams>\n | string\n | StructuredResult<StandardSchemaV1.InferOutput<OutputParams>>\n | TextContent\n | void\n >;\n name: string;\n outputSchema?: OutputParams;\n parameters?: Params;\n timeoutMs?: number;\n};\n\nexport type ToolParameters = StandardSchemaV1;\n\nexport type ViteMCPAuth = Record<string, unknown> | undefined;\n\ntype Literal = boolean | null | number | string | undefined;\n\n/**\n * Name and URI of the placeholder registered — and immediately removed — to\n * latch a primitive family's request handlers when `canAccess` hid every\n * member of it from this caller. See `#buildServer`. Never reaches the wire.\n *\n * The name holds to the SEP tool-name charset (`A-Za-z0-9._-`) even though it\n * is never listed: the SDK validates on registration, so a `/` in here would\n * put a five-line naming warning on every fully-filtered request.\n */\nconst LATCH_NAME = \"vitemcp.internal.capability-latch\";\nconst LATCH_URI = \"vitemcp-internal:capability-latch\";\n\n/**\n * The spec's log levels, least severe first. A request's\n * `io.modelcontextprotocol/logLevel` names the least severe one it wants.\n */\nconst LOG_LEVELS: readonly LoggingLevel[] = [\n \"debug\",\n \"info\",\n \"notice\",\n \"warning\",\n \"error\",\n \"critical\",\n \"alert\",\n \"emergency\",\n];\n\n/** A tool's schemas in the form the SDK registers them. */\ntype SdkToolSchemas = { inputSchema: unknown; outputSchema: unknown };\n\n/** The default logger when stdout carries the protocol: every level to stderr. */\nconst stderrLogger: Logger = {\n debug: (...args) => console.error(...args),\n error: (...args) => console.error(...args),\n info: (...args) => console.error(...args),\n log: (...args) => console.error(...args),\n warn: (...args) => console.warn(...args),\n};\n\nexport class ViteMCP<T extends ViteMCPAuth = ViteMCPAuth> {\n /**\n * The `auth` provider this server was constructed with, or `undefined` when\n * OAuth was configured through the `oauth` option instead (or not at all).\n *\n * Exposed so a caller who inlined the provider into the options — the way\n * every example does — can still reach it at shutdown. The provider holds an\n * `OAuthProxy` with two cleanup timers, and `stop()` deliberately leaves them\n * running: the server does not own the provider, and a stopped server can be\n * started again. Terminal teardown is therefore the caller's call:\n *\n * ```ts\n * await server.stop();\n * server.authProvider?.destroy();\n * ```\n *\n * In that order — `destroy()` is terminal, and a request still draining would\n * throw against a destroyed provider.\n */\n public get authProvider():\n | AuthProvider<T extends OAuthSession ? T : OAuthSession>\n | undefined {\n return this.#options.auth;\n }\n\n /**\n * The port the HTTP server is actually listening on, or `null` when it is\n * not running over HTTP. Pass `httpStream.port: 0` to let the OS assign a\n * free port and read it back here — this avoids the race inherent in\n * picking a port first and binding it afterwards.\n */\n public get port(): null | number {\n const address = this.#httpServer?.address();\n return address && typeof address === \"object\" ? address.port : null;\n }\n\n public get serverState(): ServerState {\n return this.#serverState;\n }\n #authenticate: Authenticate<T> | undefined;\n /**\n * Carries the `authenticate` result from the HTTP route into the per-request\n * server factory. The SDK invokes that factory from within `handler.fetch`,\n * so the running store is always the one this request established — whereas\n * a field on `this` would be shared by every concurrent request.\n */\n #authStore = new AsyncLocalStorage<{ auth: T | undefined }>();\n #connectedServers: McpServer[] = [];\n #corsMiddleware: null | ReturnType<typeof cors> = null;\n #handler: McpHttpHandler | null = null;\n #honoApp = new Hono();\n #httpServer: http.Server | https.Server | null = null;\n #logger: Logger;\n #options: ServerOptions<T>;\n #prompts: Prompt<T>[] = [];\n /**\n * The RFC 9728 protected-resource document this server publishes, if it\n * publishes one — what a 401 points a client at. Latched when the routes are\n * mounted rather than read back from `auth` per rejection: the provider's\n * config getter builds its proxy on demand and refuses once destroyed.\n */\n #protectedResource: { resource?: unknown } | undefined;\n #resources: Resource<T>[] = [];\n #resourceTemplates: ResourceTemplate<T>[] = [];\n #serverState: ServerState = ServerState.Stopped;\n #stdioHandle: null | StdioServerHandle = null;\n\n #tools: Tool<T>[] = [];\n /** Each tool's schemas, as `#sdkSchemasFor` converted them. */\n #toolSchemas = new WeakMap<Tool<T>, Promise<SdkToolSchemas | undefined>>();\n\n public constructor(options: ServerOptions<T>) {\n this.#options = options;\n this.#logger = options.logger ?? console;\n\n // An AuthProvider supplies the authenticate hook. Resolved here rather\n // than inside the HTTP path so the wiring is not silently absent on\n // stdio / `connect()`.\n const provider = options.auth;\n this.#authenticate =\n options.authenticate ??\n (provider\n ? (((request: Request) =>\n provider.authenticate(request)) as unknown as Authenticate<T>)\n : undefined);\n\n this.#honoApp = this.#freshApp();\n }\n\n // An entry added under a key already in use replaces the one there: the SDK\n // refuses to register a key twice, and as the server is rebuilt for every\n // request, a duplicate failed every request, not only its own. Keys are the\n // SDK's — a resource's URI, and every other entry's name.\n public addPrompt(prompt: Prompt<T>) {\n this.#prompts = this.#prompts.filter((p) => p.name !== prompt.name);\n this.#prompts.push(prompt);\n this.#notifyListChanged(\"prompts\");\n }\n\n public addPrompts(prompts: Prompt<T>[]) {\n for (const prompt of prompts) {\n this.#prompts = this.#prompts.filter((p) => p.name !== prompt.name);\n this.#prompts.push(prompt);\n }\n this.#notifyListChanged(\"prompts\");\n }\n\n public addResource(resource: Resource<T>) {\n this.#resources = this.#resources.filter((r) => r.uri !== resource.uri);\n this.#resources.push(resource);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResources(resources: Resource<T>[]) {\n for (const resource of resources) {\n this.#resources = this.#resources.filter((r) => r.uri !== resource.uri);\n this.#resources.push(resource);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplate(template: ResourceTemplate<T>) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== template.name,\n );\n this.#resourceTemplates.push(template);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplates(templates: ResourceTemplate<T>[]) {\n for (const template of templates) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== template.name,\n );\n this.#resourceTemplates.push(template);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addTool<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tool: Tool<T, Params, OutputParams>) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools = this.#tools.filter((t) => t.name !== tool.name);\n this.#tools.push(tool as unknown as Tool<T>);\n this.#notifyListChanged(\"tools\");\n }\n\n public addTools<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tools: Tool<T, Params, OutputParams>[]) {\n // All checked before any is added: a batch that throws leaves the tools as\n // they were, rather than serving those ahead of the one it threw over.\n for (const tool of tools) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n }\n\n for (const tool of tools) {\n this.#tools = this.#tools.filter((t) => t.name !== tool.name);\n this.#tools.push(tool as unknown as Tool<T>);\n }\n this.#notifyListChanged(\"tools\");\n }\n\n /**\n * Connects the server to an arbitrary transport — used for in-memory unit\n * testing, where a linked transport pair replaces a real socket.\n */\n public async connect(\n transport: Parameters<McpServer[\"connect\"]>[0],\n ): Promise<McpServer> {\n const server = await this.#buildServer(undefined);\n await server.connect(transport);\n this.#connectedServers.push(server);\n this.#serverState = ServerState.Running;\n return server;\n }\n\n /**\n * Resolves a resource (or resource template) URI to an embeddable resource\n * body, for returning inline from a tool.\n */\n public async embedded(uri: string): Promise<LoadedResource> {\n const direct = this.#resources.find((resource) => resource.uri === uri);\n\n if (direct) {\n // No `release()` here or below: a context built outside a request has no\n // source signals to stop mirroring.\n const loaded = await direct.load(\n this.#makeContext(undefined, undefined).context,\n );\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(`Resource loaded no content: ${uri}`, {\n uri,\n });\n }\n\n return {\n ...first,\n mimeType: first.mimeType ?? direct.mimeType,\n uri: first.uri ?? uri,\n };\n }\n\n for (const template of this.#resourceTemplates) {\n // Matched as `resources/read` matches it, so a URI reaches the same\n // template, with the same arguments, whichever way it is asked for. A\n // matcher that let `{id}` take a `/` had `docs://{id}` claim\n // `docs://x/history` from `docs://{id}/history`, and handed its loader a\n // path it never declared.\n const params = new UriTemplate(template.uriTemplate).match(uri);\n\n if (!params) {\n continue;\n }\n\n const loaded = await template.load(\n params as Record<string, string>,\n this.#makeContext(undefined, undefined).context,\n );\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(\n `Resource template loaded no content: ${uri}`,\n { uri },\n );\n }\n\n return {\n ...first,\n mimeType: first.mimeType ?? template.mimeType,\n uri: first.uri ?? uri,\n };\n }\n\n throw new UnexpectedStateError(`Resource not found: ${uri}`, { uri });\n }\n\n /** The Hono app serving the HTTP transport, for mounting custom routes. */\n public getApp(): Hono {\n return this.#honoApp;\n }\n\n /**\n * Publishes `notifications/resources/updated` for a URI to any subscription\n * that opted in to it and whose caller may read it. HTTP only: a stdio\n * client is never reached.\n */\n public notifyResourceUpdated(uri: string): void {\n this.#handler?.notify.resourceUpdated(uri);\n }\n\n public removePrompt(name: string) {\n this.#prompts = this.#prompts.filter((p) => p.name !== name);\n this.#notifyListChanged(\"prompts\");\n }\n\n public removePrompts(names: string[]) {\n this.#prompts = this.#prompts.filter((p) => !names.includes(p.name));\n this.#notifyListChanged(\"prompts\");\n }\n\n public removeResource(name: string) {\n this.#resources = this.#resources.filter((r) => r.name !== name);\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResources(names: string[]) {\n this.#resources = this.#resources.filter((r) => !names.includes(r.name));\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplate(name: string) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== name,\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplates(names: string[]) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => !names.includes(r.name),\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeTool(name: string) {\n this.#tools = this.#tools.filter((t) => t.name !== name);\n this.#notifyListChanged(\"tools\");\n }\n\n public removeTools(names: string[]) {\n this.#tools = this.#tools.filter((t) => !names.includes(t.name));\n this.#notifyListChanged(\"tools\");\n }\n\n public async start(\n options:\n | {\n httpStream: {\n /** Origins permitted to reach the MCP endpoint (DNS-rebinding guard). */\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n /**\n * Whether to also serve 2025-era clients. Defaults to\n * `\"stateless\"`: the SDK client negotiates 2025 unless given\n * `versionNegotiation: { mode: \"auto\" }`. `\"reject\"` serves only\n * 2026-07-28 and enforces `Mcp-Method`/`Mcp-Name`.\n */\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n };\n transportType: \"httpStream\";\n }\n | { transportType: \"stdio\" },\n ): Promise<void> {\n // Starting a transport again replaced its handle, and `stop()` closes only\n // the handle it holds: the first went on running after `stop()` returned —\n // an HTTP listener holding its port, and the process, open.\n if (\n options.transportType === \"stdio\" ? this.#stdioHandle : this.#httpServer\n ) {\n throw new UnexpectedStateError(\n `ViteMCP is already running on ${\n options.transportType === \"stdio\" ? \"stdio\" : \"HTTP\"\n }; call stop() before starting it again`,\n );\n }\n\n this.#serverState = ServerState.Starting;\n\n try {\n if (options.transportType === \"stdio\") {\n // stdout is the transport here, and the default console logger writes\n // info, log and debug to it — straight into the stream the client\n // parses as JSON-RPC. A logger passed in is the caller's to direct.\n this.#logger = this.#options.logger ?? stderrLogger;\n this.#stdioHandle = serveStdio(({ era }) =>\n this.#buildServer(undefined, { era }),\n );\n this.#logger.info(`[ViteMCP info] server is running on stdio`);\n } else {\n await this.#startHttp(options.httpStream);\n }\n\n this.#serverState = ServerState.Running;\n } catch (error) {\n this.#serverState = ServerState.Error;\n throw error;\n }\n }\n\n public async stop(): Promise<void> {\n // Hono seals its matcher once used, so a restarted server needs a fresh\n // app; the routes are re-registered by the next `start()`.\n this.#honoApp = this.#freshApp();\n this.#corsMiddleware = null;\n\n for (const server of this.#connectedServers) {\n await server.close().catch(() => {});\n }\n this.#connectedServers = [];\n\n await this.#stdioHandle?.close?.();\n this.#stdioHandle = null;\n\n await this.#handler?.close();\n this.#handler = null;\n\n if (this.#httpServer) {\n await new Promise<void>((resolve) =>\n this.#httpServer!.close(() => resolve()),\n );\n this.#httpServer = null;\n }\n\n this.#serverState = ServerState.Stopped;\n }\n\n /**\n * Runs the `authenticate` hook and decides whether the exchange may proceed,\n * returning either the store to run it under or the `Response` refusing it.\n *\n * Deliberately *not* done inside the per-request server factory: that\n * factory's only return channel is an `McpServer`, so a refusal raised there\n * is indistinguishable from a crash and reaches the client as a 500 with no\n * `WWW-Authenticate` — the one header that tells an MCP client where to log\n * in. Doing it here also covers the legacy fallback, which shares the same\n * route, so no transport can be reached without passing this.\n */\n async #authenticateRequest(\n request: Request,\n ): Promise<{ auth: T | undefined } | Response> {\n if (!this.#authenticate) {\n return { auth: undefined };\n }\n\n let auth: null | T | undefined;\n\n try {\n auth = await this.#authenticate(request);\n } catch (error) {\n // A hook may throw the exact response it wants sent — the documented way\n // to refuse with a specific status, body or challenge.\n if (error instanceof Response) {\n return error;\n }\n\n // Anything else is a fault in the hook. Fail closed: a hook that threw\n // did not authorise anyone, so this must never fall through to the\n // handler. Reported here because the throw no longer reaches the SDK's\n // `onerror`, which used to be what logged it.\n this.#logger.error(\"[ViteMCP error]\", error);\n\n return bearerAuthChallengeResponse(\n new OAuthError(OAuthErrorCode.ServerError, \"Internal Server Error\"),\n );\n }\n\n // A falsy result means the hook could not identify the caller, which is a\n // refusal and not an anonymous session: `AuthProvider.authenticate`\n // returns `undefined` for a missing, malformed or revoked bearer token.\n // Serving those requests anyway would hand every primitive that has no\n // `canAccess` guard to callers who presented no credentials at all.\n // Tested for falsiness rather than nullishness because a session is always\n // an object here, so nothing legitimate is caught — but an untyped hook\n // returning `false` is caught, and it plainly means \"no\".\n if (!auth) {\n return this.#options.allowAnonymous\n ? { auth: undefined }\n : this.#unauthorized(request);\n }\n\n return { auth };\n }\n\n /**\n * `era` is the protocol era the server will speak, where it is known: one\n * built for `connect()` speaks whichever the client picks.\n * `resourceSubscriptions` declares `resources.subscribe`. Set it only where\n * `notifyResourceUpdated` delivers: to 2026-07-28 HTTP clients.\n */\n async #buildServer(\n auth: T | undefined,\n {\n era,\n resourceSubscriptions = false,\n }: { era?: \"legacy\" | \"modern\"; resourceSubscriptions?: boolean } = {},\n ): Promise<McpServer> {\n const server = new McpServer(\n {\n description: this.#options.description,\n icons: this.#options.icons,\n name: this.#options.name,\n title: this.#options.title,\n version: this.#options.version,\n websiteUrl: this.#options.websiteUrl,\n },\n {\n // Without it the SDK refuses to send `notifications/message`, and\n // `log.*` swallows the refusal, so every log line vanished silently.\n // Left out for a 2025-era client: `log.*` answers only the 2026-07-28\n // per-request opt-in, so the `logging/setLevel` it would promise that\n // client could never take effect.\n capabilities: era === \"legacy\" ? {} : { logging: {} },\n instructions: this.#options.instructions,\n },\n );\n\n const visible = <\n P extends { canAccess?: (auth: T | undefined) => boolean },\n >(\n all: readonly P[],\n ): P[] => all.filter((entry) => !entry.canAccess || entry.canAccess(auth));\n\n // A tool whose schemas cannot be converted is left out rather than allowed\n // to fail the request: every request builds the whole server, so one such\n // tool would otherwise take down every method, not just itself.\n const tools = (\n await Promise.all(\n visible(this.#tools).map(async (tool) => {\n const schemas = await this.#sdkSchemasFor(tool);\n\n return schemas && { schemas, tool };\n }),\n )\n ).filter((entry) => entry !== undefined);\n const resources = visible(this.#resources);\n const resourceTemplates = visible(this.#resourceTemplates);\n const prompts = visible(this.#prompts);\n\n for (const { schemas, tool } of tools) {\n const call = async (args: unknown, ctx: unknown) => {\n // Paired so the deadline reaches `execute` through `context.signal`\n // as well as rejecting the caller — a timeout the tool cannot see\n // leaves its work running behind an already-settled promise.\n const timeout = tool.timeoutMs\n ? { controller: new AbortController(), ms: tool.timeoutMs }\n : undefined;\n const { context, release } = this.#makeContext(\n auth,\n ctx,\n timeout?.controller.signal,\n );\n\n try {\n const result = await (timeout\n ? withTimeout(tool.execute(args, context), timeout, tool.name)\n : tool.execute(args, context));\n return normalizeToolResult(result, tool.outputSchema !== undefined);\n } catch (error) {\n if (error instanceof UserError) {\n // The SDK checks a success's structured content against the\n // output schema, not an error's, but a client may check both — the\n // v1 SDK's does. Extras that did not match had that client throw\n // the message away, as a -32602, so they are sent only if they do.\n const structuredContent =\n error.extras &&\n (await matchesOutputSchema(schemas.outputSchema, error.extras))\n ? error.extras\n : undefined;\n\n return {\n content: [{ text: error.message, type: \"text\" }],\n isError: true,\n ...(structuredContent ? { structuredContent } : {}),\n };\n }\n throw error;\n } finally {\n release();\n }\n };\n\n server.registerTool(\n tool.name,\n {\n _meta: tool._meta,\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: schemas.inputSchema as never,\n outputSchema: schemas.outputSchema as never,\n },\n // The SDK passes arguments only to a tool that declares an input\n // schema; one that does not is called with the request context alone.\n // Registering `call` as it stands would take that context for `args`\n // and leave the tool without one: no progress, no logs, no request id\n // and a `signal` that never fires.\n (schemas.inputSchema\n ? call\n : (ctx: unknown) => call(undefined, ctx)) as never,\n );\n }\n\n for (const resource of resources) {\n server.registerResource(\n resource.name,\n resource.uri,\n {\n cacheHint: resource.cache,\n description: resource.description,\n mimeType: resource.mimeType,\n },\n (async (uri: URL, ctx: unknown) => {\n const { context, release } = this.#makeContext(auth, ctx);\n\n try {\n const loaded = await resource.load(context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n } finally {\n release();\n }\n }) as never,\n );\n }\n\n for (const template of resourceTemplates) {\n // No prototype, because the SDK looks a variable's completer up here by\n // name: on a plain object, asking to complete a variable called\n // `constructor` or `toString` found `Object.prototype`'s, called it, and\n // failed the request instead of answering with nothing.\n const complete: Record<string, (value: string) => Promise<string[]>> =\n Object.create(null);\n for (const arg of template.arguments ?? []) {\n const completer =\n arg.complete ??\n (template.complete\n ? (value: string) => template.complete!(arg.name, value)\n : undefined);\n\n if (completer) {\n complete[arg.name] = async (value: string) =>\n (await completer(value)).values;\n }\n }\n\n server.registerResource(\n template.name,\n new SDKResourceTemplate(template.uriTemplate, {\n complete: complete as never,\n list: undefined,\n }),\n {\n cacheHint: template.cache,\n description: template.description,\n mimeType: template.mimeType,\n },\n (async (uri: URL, args: Record<string, string>, ctx: unknown) => {\n const { context, release } = this.#makeContext(auth, ctx);\n\n try {\n const loaded = await template.load(args ?? {}, context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? template.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n } finally {\n release();\n }\n }) as never,\n );\n }\n\n for (const prompt of prompts) {\n const argsSchema = promptArgsSchema(prompt);\n\n const load = async (\n args: Record<string, string> | undefined,\n ctx: unknown,\n ) => {\n const { context, release } = this.#makeContext(auth, ctx);\n\n try {\n const loaded = await prompt.load(args ?? {}, context);\n\n if (typeof loaded !== \"string\") {\n return loaded;\n }\n\n return {\n messages: [\n {\n content: { text: loaded, type: \"text\" },\n role: \"user\" as const,\n },\n ],\n };\n } finally {\n release();\n }\n };\n\n server.registerPrompt(\n prompt.name,\n { argsSchema, description: prompt.description } as never,\n // As for tools: without `argsSchema` the SDK passes the request\n // context alone.\n (argsSchema ? load : (ctx: unknown) => load(undefined, ctx)) as never,\n );\n }\n\n // `canAccess` is documented to filter rejected primitives out of the list,\n // so a caller who may see none of them is owed an empty list. The SDK\n // registers a family's request handlers — and its capability — on the\n // first `registerTool`/`registerResource`/`registerPrompt`, so a request\n // that registered nothing never got them and `tools/list` came back\n // `-32601 Method not found`: the method does not exist, rather than the\n // caller may see nothing in it. Registering a placeholder and removing it\n // latches the handlers without the placeholder ever being listed or\n // callable — and it cannot collide, because this runs only when nothing\n // else in the family registered. A server carrying none of a primitive at\n // all still advertises nothing, so `-32601` stays correct there.\n if (this.#tools.length > 0 && tools.length === 0) {\n server\n .registerTool(LATCH_NAME, {}, (() => ({ content: [] })) as never)\n .remove();\n }\n\n // One registration latches `resources/list`, `resources/templates/list`\n // and `resources/read` together, so the two resource families share it.\n if (\n this.#resources.length + this.#resourceTemplates.length > 0 &&\n resources.length + resourceTemplates.length === 0\n ) {\n server\n .registerResource(LATCH_NAME, LATCH_URI, {}, (() => ({\n contents: [],\n })) as never)\n .remove();\n }\n\n if (this.#prompts.length > 0 && prompts.length === 0) {\n server\n .registerPrompt(LATCH_NAME, {}, (() => ({ messages: [] })) as never)\n .remove();\n }\n\n // The SDK drops `resourceSubscriptions` from a `subscriptions/listen`\n // filter unless the server declares `resources.subscribe`, so without it\n // no update ever reached a client. Added to a resources capability that\n // registration declared, never in place of one: a server without resources\n // must not advertise the family.\n if (resourceSubscriptions && server.server.getCapabilities().resources) {\n server.server.registerCapabilities({ resources: { subscribe: true } });\n }\n\n return server;\n }\n\n /**\n * Whether `resources/read` would serve `uri` to this caller: a resource of\n * that URI, or a template matching it, that `canAccess` leaves visible.\n */\n #canRead(uri: string, auth: T | undefined): boolean {\n const visible = (entry: { canAccess?: (auth: T | undefined) => boolean }) =>\n !entry.canAccess || entry.canAccess(auth);\n\n return (\n this.#resources.some(\n (resource) => resource.uri === uri && visible(resource),\n ) ||\n this.#resourceTemplates.some(\n (template) =>\n visible(template) &&\n new UriTemplate(template.uriTemplate).match(uri) !== null,\n )\n );\n }\n\n /**\n * The bus `notifyResourceUpdated` publishes to and `subscriptions/listen`\n * streams read from, narrowed per stream to updates its caller could read.\n *\n * `canAccess` keeps a resource out of `resources/read`, so its updates must\n * not reach that caller either, or subscribing to the URI would reveal what\n * reading it cannot. The SDK subscribes a stream while serving its listen\n * request, so that caller's auth is still in scope here.\n */\n #eventBus(): ServerEventBus {\n const events = new InMemoryServerEventBus((error) =>\n this.#logger.error(\"[ViteMCP error]\", error),\n );\n\n return {\n publish: (event) => events.publish(event),\n subscribe: (listener) => {\n const auth = this.#authStore.getStore()?.auth;\n\n return events.subscribe((event) => {\n if (\n event.kind !== \"resource_updated\" ||\n this.#canRead(event.uri, auth)\n ) {\n listener(event);\n }\n });\n },\n };\n }\n\n /** Builds the Hono app with the CORS shim installed ahead of user routes. */\n #freshApp(): Hono {\n const app = new Hono();\n\n app.use(\"*\", (c, next) =>\n this.#corsMiddleware ? this.#corsMiddleware(c, next) : next(),\n );\n\n return app;\n }\n\n /**\n * Bridges the v2 per-request context onto ViteMCP's `Context`.\n *\n * `timeoutSignal` is folded into `context.signal` for a tool that declares\n * `timeoutMs`; everything else mirrors the SDK's request signal alone. Call\n * `release()` once the handler has settled — see {@link requestScope}. It\n * also ends the context's notifications, as an abort does.\n */\n #makeContext(\n auth: T | undefined,\n rawCtx: unknown,\n timeoutSignal?: AbortSignal,\n ): { context: Context<T>; release: () => void } {\n const ctx = rawCtx as {\n mcpReq?: {\n _meta?: {\n progressToken?: number | string;\n };\n /**\n * The reserved `io.modelcontextprotocol/*` keys, which the SDK moves\n * here out of `_meta`.\n */\n envelope?: { [LOG_LEVEL_META_KEY]?: LoggingLevel };\n id?: string;\n inputResponses?: Record<string, unknown>;\n notify?: (n: unknown) => Promise<void>;\n requestState?: <T>() => T | undefined;\n signal?: AbortSignal;\n };\n };\n const mcpReq = ctx?.mcpReq;\n const scope = requestScope(mcpReq?.signal, timeoutSignal);\n let settled = false;\n\n // A request's notifications stop with it: once it is cancelled, times out\n // or has been answered, nothing is left for them to belong to. One sent\n // anyway reached a client that had let its progress token go, which\n // reports it as unknown; over HTTP the request's stream is gone, and the\n // send threw \"Not connected\" into the handler.\n const notify = async (notification: unknown): Promise<void> => {\n if (settled || scope.signal.aborted) {\n return;\n }\n\n await mcpReq?.notify?.(notification);\n };\n\n // The spec forbids `notifications/message` for a request that did not opt\n // in via `_meta`, and the level it opts in with is a floor: a client that\n // asks for `error` wants errors, not everything. Failures are swallowed: a\n // log line must never take down the request.\n const requestedLevel = mcpReq?.envelope?.[LOG_LEVEL_META_KEY];\n\n const emit = (\n level: LoggingLevel,\n message: string,\n data?: SerializableValue,\n ) => {\n if (\n !requestedLevel ||\n LOG_LEVELS.indexOf(level) < LOG_LEVELS.indexOf(requestedLevel)\n ) {\n return;\n }\n\n void notify({\n method: \"notifications/message\",\n params: { data: { context: data, message }, level },\n }).catch(() => {});\n };\n\n return {\n context: {\n auth,\n elicit: (params) =>\n inputRequired.elicit({\n message: params.message,\n requestedSchema: params.requestedSchema as never,\n }),\n input: (key, schema) =>\n acceptedContent(\n mcpReq?.inputResponses,\n key,\n schema as never,\n ) as never,\n inputRequired: (inputRequests, requestState) =>\n inputRequired({ inputRequests, requestState }),\n inputResponses: mcpReq?.inputResponses,\n log: {\n debug: (m, d) => emit(\"debug\", m, d),\n error: (m, d) => emit(\"error\", m, d),\n info: (m, d) => emit(\"info\", m, d),\n warn: (m, d) => emit(\"warning\", m, d),\n },\n reportProgress: async (progress) => {\n const progressToken = mcpReq?._meta?.progressToken;\n\n // No token means the client did not ask for progress on this request;\n // emitting anyway would be an uncorrelatable notification.\n if (progressToken === undefined) {\n return;\n }\n\n await notify({\n method: \"notifications/progress\",\n params: {\n message: progress.message,\n progress: progress.progress,\n progressToken,\n total: progress.total,\n },\n });\n },\n requestId: mcpReq?.id,\n // The SDK exposes this as an accessor; call it so callers get the\n // value.\n requestState: mcpReq?.requestState?.<string>(),\n signal: scope.signal,\n },\n release: () => {\n settled = true;\n scope.release();\n },\n };\n }\n\n /**\n * Publishes a change event to any open `subscriptions/listen` stream. This\n * replaces the 2025-era `notifications/*_list_changed` broadcast, which had\n * no addressee on a stateless transport.\n */\n #notifyListChanged(kind: \"prompts\" | \"resources\" | \"tools\") {\n // Typed on purpose: a cast here once let wrong method names no-op.\n const notifier = this.#handler?.notify;\n\n if (!notifier) {\n return;\n }\n\n if (kind === \"tools\") notifier.toolsChanged();\n if (kind === \"prompts\") notifier.promptsChanged();\n if (kind === \"resources\") notifier.resourcesChanged();\n }\n\n /**\n * A tool's schemas in the form the SDK registers them, or `undefined` for a\n * tool whose schemas cannot be converted — reported when that is found.\n *\n * Converted once per tool: `#buildServer` runs on every request, so a tool\n * that cannot be served would otherwise be reported on each of them.\n */\n #sdkSchemasFor(tool: Tool<T>): Promise<SdkToolSchemas | undefined> {\n let schemas = this.#toolSchemas.get(tool);\n\n if (!schemas) {\n schemas = Promise.all([\n this.#toSdkSchema(\n tool.parameters,\n `Tool \"${tool.name}\" parameters`,\n \"input\",\n ),\n this.#toSdkSchema(\n tool.outputSchema,\n `Tool \"${tool.name}\" outputSchema`,\n \"output\",\n ),\n ]).then(\n ([inputSchema, outputSchema]) => ({ inputSchema, outputSchema }),\n (error: unknown) => {\n this.#logger.error(\n `[ViteMCP error] Tool \"${tool.name}\" is not served:`,\n error,\n );\n\n return undefined;\n },\n );\n this.#toolSchemas.set(tool, schemas);\n }\n\n return schemas;\n }\n\n async #startHttp(config: {\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n }): Promise<void> {\n this.#handler = createMcpHandler(\n // Authentication has already run in the route below, which is the only\n // place that can turn a refusal into an HTTP status. What reaches here\n // is either an authenticated session or a deliberately anonymous one.\n async ({ era }) =>\n this.#buildServer(this.#authStore.getStore()?.auth, {\n era,\n // A 2025-era client reads `resources.subscribe` as a promise of\n // `resources/subscribe`, which is not served.\n resourceSubscriptions: era === \"modern\",\n }),\n {\n bus: this.#eventBus(),\n // Tradeoff: `server/discover` advertises only 2026-07-28, so legacy\n // requests are answered unadvertised and skip Mcp-* validation.\n legacy: config.legacy ?? \"stateless\",\n ...(config.enableJsonResponse ? { responseMode: \"json\" as const } : {}),\n onerror: (error) => this.#logger.error(\"[ViteMCP error]\", error),\n },\n );\n\n this.#corsMiddleware = config.cors === false ? null : cors(config.cors);\n\n // An explicit `oauth` config is served as written. A provider's cannot be\n // complete until the endpoint is known, which is here.\n const provider = this.#options.auth;\n const oauth =\n this.#options.oauth ??\n (provider &&\n withEndpointAsResource(\n provider.getOAuthConfig(),\n config.endpoint ?? \"/mcp\",\n ));\n\n if (\n oauth?.enabled !== false &&\n (oauth?.proxy ?? oauth?.authorizationServer ?? oauth?.protectedResource)\n ) {\n this.#honoApp.route(\n \"/\",\n createOAuthRouter({\n authorizationServer: oauth.authorizationServer,\n basePath: config.basePath,\n endpoint: config.endpoint ?? \"/mcp\",\n protectedResource: oauth.protectedResource,\n proxy: oauth.proxy,\n }),\n );\n\n this.#protectedResource = oauth.protectedResource;\n }\n\n const health = this.#options.health;\n if (health?.enabled !== false) {\n this.#honoApp.get(health?.path ?? \"/health\", (c) =>\n c.text(health?.message ?? \"ok\", (health?.status ?? 200) as 200),\n );\n }\n\n const endpoint = `${config.basePath ?? \"\"}${config.endpoint ?? \"/mcp\"}`;\n const handler = this.#handler;\n const host = config.host ?? \"127.0.0.1\";\n const isLoopback = [\"::1\", \"127.0.0.1\", \"localhost\"].includes(host);\n\n // Default-deny on loopback (the DNS-rebinding case); a routable bind is\n // assumed deliberate and must configure its own origins.\n const allowedOrigins =\n config.allowedOrigins ?? (isLoopback ? localhostAllowedOrigins() : []);\n\n if (!config.allowedOrigins && !isLoopback) {\n this.#logger.warn(\n `[ViteMCP warning] no 'allowedOrigins' configured while bound to ${host}; browser origins will be rejected`,\n );\n }\n\n // A Hono route, not a pre-routing short-circuit, so CORS covers it.\n // Routing around Hono 405'd every preflight — and this revision makes\n // every POST preflighted via `Mcp-Method`/`Mcp-Name`.\n this.#honoApp.all(endpoint, async (c) => {\n // Transport security (MUST): a present-but-unrecognised Origin is 403.\n // Stops DNS rebinding; requests with no Origin are unaffected.\n const rejected = originValidationResponse(c.req.raw, allowedOrigins);\n\n if (rejected) {\n return rejected;\n }\n\n const authenticated = await this.#authenticateRequest(c.req.raw);\n\n if (authenticated instanceof Response) {\n return authenticated;\n }\n\n return this.#authStore.run(authenticated, () => handler.fetch(c.req.raw));\n });\n\n const app = this.#honoApp;\n const maxBodySize = config.maxBodySize ?? OAUTH_PROXY_MAX_BODY_SIZE;\n\n const useTls = Boolean(config.sslCert && config.sslKey);\n\n const requestListener = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ) => {\n void (async () => {\n try {\n // The cap must apply before conversion: reading first and\n // measuring after is the DoS this guards against.\n const body = await readCappedNodeBody(req, maxBodySize);\n\n if (body === OVERSIZE) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n // Drain rather than pause (pausing stalls the response), then\n // half-close once the 400 has flushed. A forced destroy would RST\n // while the client is still writing and discard the response.\n req.resume();\n res.once(\"finish\", () => res.socket?.end());\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: `Request body exceeds ${formatBytes(maxBodySize)}`,\n }),\n );\n return;\n }\n\n // Node req/res go through as Hono's env so custom routes can still\n // reach `c.env.incoming`.\n const response = await app.fetch(\n nodeToWebRequest(req, body, useTls, clientDisconnectSignal(res)),\n {\n incoming: req,\n outgoing: res,\n },\n );\n\n res.writeHead(response.status, toNodeHeaders(response.headers));\n\n if (!response.body) {\n res.end();\n return;\n }\n\n // Node holds the head back until the first body byte, which for an\n // SSE stream means the client's `fetch` stays pending until the\n // first event — and a stream that fails before then is a bare\n // socket close with no status to read.\n res.flushHeaders();\n\n // Piped, not buffered: `arrayBuffer()` withholds every byte until\n // the handler is done, which collapses an SSE stream into a single\n // delivery at the end — `reportProgress` then lands with the tool\n // result instead of during the call. `pipeline` also carries a\n // client disconnect back into the body, so an abandoned stream\n // stops producing.\n await pipeline(Readable.fromWeb(response.body), res);\n } catch (error) {\n // Past `writeHead` the exchange is committed: no status is left to\n // send, and ending cleanly would frame a truncated body as a whole\n // one. Abort so the client reads it as the failure it is.\n if (res.headersSent) {\n // A client that hung up first is routine, and its own doing.\n const disconnected =\n (error as NodeJS.ErrnoException).code ===\n \"ERR_STREAM_PREMATURE_CLOSE\";\n\n if (disconnected) {\n this.#logger.debug(\n `[ViteMCP debug] client disconnected mid-response:`,\n error,\n );\n } else {\n this.#logger.error(\n `[ViteMCP error] response stream failed:`,\n error,\n );\n }\n\n res.destroy();\n return;\n }\n\n // A body that aborts mid-stream rejects here. Settle with a 400\n // rather than leaving the exchange pending forever.\n this.#logger.debug(`[ViteMCP debug] request failed:`, error);\n\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: \"Request body could not be read\",\n }),\n );\n }\n })();\n };\n\n // TLS is terminated here when certs are supplied, rather than assuming a\n // proxy in front.\n this.#httpServer = useTls\n ? https.createServer(\n {\n ...(config.sslCa ? { ca: await readFile(config.sslCa) } : {}),\n cert: await readFile(config.sslCert!),\n key: await readFile(config.sslKey!),\n },\n requestListener,\n )\n : http.createServer(requestListener);\n\n await new Promise<void>((resolve) =>\n this.#httpServer!.listen(\n config.port,\n config.host ?? \"127.0.0.1\",\n resolve,\n ),\n );\n\n this.#logger.info(\n `[ViteMCP info] server is running on ${useTls ? \"HTTPS\" : \"HTTP\"} at ${\n useTls ? \"https\" : \"http\"\n }://${config.host ?? \"127.0.0.1\"}:${this.port ?? config.port}${endpoint}`,\n );\n }\n\n /**\n * A tool schema in the form the SDK registers it — see `toSdkSchema` — with\n * a failed conversion reported under the tool's own name.\n */\n async #toSdkSchema(\n schema: unknown,\n label: string,\n io: \"input\" | \"output\",\n ): Promise<unknown> {\n try {\n return await toSdkSchema(schema, io, convertToJsonSchema);\n } catch (error) {\n throw new UnexpectedStateError(\n `${label} is not a supported Standard Schema: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { label },\n );\n }\n }\n\n /**\n * The RFC 6750 §3 challenge sent when `authenticate` refuses a request.\n *\n * `resource_metadata` (RFC 9728 §5.1) is the parameter that turns a bare\n * rejection into a login: it points the client at this server's\n * protected-resource document, from which it discovers the authorization\n * server and starts the flow. It is omitted when this server publishes no\n * such document.\n *\n * The URL is formed from the resource that document names: the address the\n * server was configured as, which is the one a client can reach. The\n * request's own URL is not that address behind a proxy that terminates TLS —\n * it carries the listener's scheme and whatever Host was forwarded, so a\n * challenge built from it sent clients to `http://`, or to an internal host.\n * It is the fallback only, for a document that names no resource.\n */\n #unauthorized(request: Request): Response {\n const published = this.#protectedResource;\n\n return bearerAuthChallengeResponse(\n new OAuthError(OAuthErrorCode.InvalidToken, \"Authentication required\"),\n published\n ? {\n resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(\n toUrl(published.resource) ?? new URL(request.url),\n ),\n }\n : {},\n );\n }\n}\n\n/** `value` as a URL, or `undefined` when it is not an absolute one. */\nconst toUrl = (value: unknown): undefined | URL =>\n typeof value === \"string\" && URL.canParse(value) ? new URL(value) : undefined;\n\n/**\n * An auth provider's OAuth config, naming the MCP endpoint as the protected\n * resource rather than the provider's base URL.\n *\n * RFC 9728 §3.3: the document served at\n * `/.well-known/oauth-protected-resource<endpoint>` must name the URL that\n * path was derived from, and strict clients discard one that does not. The\n * base URL already carries any `basePath`, as the proxy's own endpoints do.\n */\nconst withEndpointAsResource = <\n C extends { protectedResource: { resource: string } },\n>(\n config: C,\n endpoint: string,\n): C => ({\n ...config,\n protectedResource: {\n ...config.protectedResource,\n resource: `${withoutTrailingSlash(config.protectedResource.resource)}${endpoint}`,\n },\n});\n\n/**\n * Builds a web-standard Request from a Node request whose body is already\n * consumed. The SDK's `toWebRequest` would either re-read the drained stream\n * or JSON-stringify the body a second time.\n */\nconst nodeToWebRequest = (\n req: http.IncomingMessage,\n body: Buffer,\n secure: boolean,\n signal: AbortSignal,\n): Request => {\n const host = req.headers.host ?? \"localhost\";\n // Scheme has to follow the listener, or absolute URLs derived from\n // `c.req.url` (issuers, redirect URIs) come out as http:// under TLS.\n const url = `${secure ? \"https\" : \"http\"}://${host}${req.url ?? \"/\"}`;\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(req.headers)) {\n if (value === undefined || name.startsWith(\":\")) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, value);\n }\n }\n\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body.byteLength > 0;\n\n return new Request(url, {\n headers,\n method,\n signal,\n ...(hasBody ? { body } : {}),\n });\n};\n\n/**\n * A response's headers in the form Node writes them.\n *\n * `Headers` folds a repeated header into one comma-joined value, except\n * `Set-Cookie`: a cookie's own `Expires` contains a comma, so it yields an\n * entry per cookie instead. An object keyed by header name keeps only the last\n * of those, which dropped every cookie but one. Given an array, Node writes a\n * header line for each entry.\n */\nconst toNodeHeaders = (headers: Headers): http.OutgoingHttpHeaders => {\n const cookies = headers.getSetCookie();\n\n return {\n ...Object.fromEntries(headers),\n ...(cookies.length > 0 ? { \"set-cookie\": cookies } : {}),\n };\n};\n\n/**\n * Aborts when the client goes away before the response is written.\n *\n * The SDK reads `Request.signal` to tear the exchange down and abort in-flight\n * handlers, and a hand-built `Request` otherwise carries one that never fires\n * — so on Node this has to be wired to the socket. Edge runtimes supply their\n * own and need none of this.\n *\n * Keyed off `res`, not `req`: the request stream is fully drained before this\n * runs, so its `close` has already fired and says nothing about the client.\n */\nconst clientDisconnectSignal = (res: http.ServerResponse): AbortSignal => {\n const controller = new AbortController();\n\n // A completed response emits `close` too; only a premature one is a\n // disconnect.\n const abortIfPremature = () => {\n if (!res.writableEnded) {\n controller.abort(new Error(\"Client disconnected\"));\n }\n };\n\n // Subscribing to an already-closed response would never fire, leaving the\n // handler unaware the caller is gone. Not reachable today — nothing awaits\n // between the body read and here — but one `await` away from being so.\n if (res.closed) {\n abortIfPremature();\n } else {\n res.once(\"close\", abortIfPremature);\n }\n\n return controller.signal;\n};\n\n/**\n * Rejects if a tool outruns its `timeoutMs`, and aborts `timeout.controller`\n * first so `execute` — which reaches that signal through `context.signal` —\n * can abandon whatever it started instead of running on unobserved.\n */\nconst withTimeout = <T>(\n work: Promise<T>,\n timeout: { controller: AbortController; ms: number },\n toolName: string,\n): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n const error = new UserError(\n `Tool '${toolName}' timed out after ${timeout.ms}ms`,\n { timeoutMs: timeout.ms, toolName },\n );\n\n // Abort before rejecting so the reason `execute` observes is the same\n // error the caller receives.\n timeout.controller.abort(error);\n reject(error);\n }, timeout.ms);\n\n work.then(resolve, reject).finally(() => clearTimeout(timer));\n });\n\n/**\n * Builds `context.signal` — never `undefined`, so callers can forward it to\n * `fetch` without a guard — and bounds it to a single handler run.\n *\n * Handing the SDK's request signal straight through would abort on *success*\n * too: the per-request transport is torn down as soon as the result is sent,\n * which aborts every controller it owns. A signal that always ends aborted is\n * useless for the one idiom that matters here — `addEventListener(\"abort\",\n * cleanup)` would roll back every completed call. So the sources are mirrored\n * only while the handler is in flight, and `release()` stops the mirroring.\n *\n * A context built outside a request (`embedded()`) has no sources at all and\n * gets a signal that never fires.\n */\nconst requestScope = (\n ...sources: (AbortSignal | undefined)[]\n): { release: () => void; signal: AbortSignal } => {\n const controller = new AbortController();\n const detach = new AbortController();\n\n for (const source of sources) {\n if (source === undefined) {\n continue;\n }\n\n if (source.aborted) {\n controller.abort(source.reason);\n break;\n }\n\n source.addEventListener(\"abort\", () => controller.abort(source.reason), {\n once: true,\n signal: detach.signal,\n });\n }\n\n return { release: () => detach.abort(), signal: controller.signal };\n};\n\n/** Sentinel returned when a request body exceeds the configured cap. */\nconst OVERSIZE = Symbol(\"oversize\");\n\n/**\n * Reads a Node request body with a hard cap, bailing out as soon as the limit\n * is crossed rather than after the fact. A declared `Content-Length` over the\n * cap short-circuits before any chunk is read.\n */\nconst readCappedNodeBody = async (\n req: http.IncomingMessage,\n maxBytes: number,\n): Promise<Buffer | typeof OVERSIZE> => {\n const declared = Number(req.headers[\"content-length\"] ?? 0);\n\n if (declared > maxBytes) {\n return OVERSIZE;\n }\n\n let size = 0;\n const chunks: Buffer[] = [];\n\n for await (const chunk of req) {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);\n size += buf.byteLength;\n\n if (size > maxBytes) {\n return OVERSIZE;\n }\n\n chunks.push(buf);\n }\n\n return Buffer.concat(chunks);\n};\n\n/**\n * JSON Schema for a Standard Schema that has none of its own, for advertising:\n * Valibot's own converter for Valibot, and xsschema for every other library.\n */\nconst convertToJsonSchema: JsonSchemaConverter = async (schema, io) =>\n schema[\"~standard\"].vendor === \"valibot\"\n ? valibotToJsonSchema(schema, io)\n : toJsonSchema(schema);\n\n/** Rejects non-Standard-Schema at registration, not on first call. */\nconst assertStandardSchema = (\n schema: unknown,\n toolName: string,\n field: \"outputSchema\" | \"parameters\",\n) => {\n if (schema === undefined) {\n return;\n }\n\n const standard = (schema as { \"~standard\"?: { validate?: unknown } })?.[\n \"~standard\"\n ];\n\n if (typeof standard?.validate !== \"function\") {\n throw new UnexpectedStateError(\n `Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,\n { toolName },\n );\n }\n};\n\n/**\n * Whether `value` passes a tool's output schema, as the SDK registered it. No\n * schema passes anything, and one that throws passes nothing.\n */\nconst matchesOutputSchema = async (\n schema: unknown,\n value: unknown,\n): Promise<boolean> => {\n if (!schema) {\n return true;\n }\n\n try {\n const result = await (schema as StandardSchemaV1)[\"~standard\"].validate(\n value,\n );\n\n return !result.issues;\n } catch {\n return false;\n }\n};\n\nconst promptArgsSchema = <T extends ViteMCPAuth>(prompt: Prompt<T>) => {\n const args = prompt.arguments;\n\n if (!args?.length) {\n return undefined;\n }\n\n const shape: Record<string, z.ZodType> = {};\n for (const arg of args) {\n const explicitCompleter =\n arg.complete ??\n (prompt.complete\n ? (value: string) => prompt.complete!(arg.name, value)\n : undefined);\n\n // An enum completes itself unless the author said otherwise. The spec's\n // prompt argument carries only name/description/required, so `prompts/list`\n // has nowhere to put the permitted values and completion is the one channel\n // that can reach the client — without this the argument is validated\n // against a set the client is never shown.\n const enumValues = arg.enum;\n const completer =\n explicitCompleter ??\n (enumValues?.length\n ? async (value: string): Promise<Completion> => ({\n // An empty value is how an editor asks for the whole set before the\n // user has typed anything; filtering it would answer with nothing.\n values: value\n ? enumValues.filter((option) =>\n option.toLowerCase().includes(value.toLowerCase()),\n )\n : [...enumValues],\n })\n : undefined);\n\n // The enum belongs on the schema too: that is what `prompts/get` checks the\n // incoming argument against.\n const valueSchema = enumValues?.length\n ? z.enum(enumValues as [string, ...string[]])\n : z.string();\n const described = arg.description\n ? valueSchema.describe(arg.description)\n : valueSchema;\n const base = completer\n ? completable(\n described,\n (async (value: string) => (await completer(value)).values) as never,\n )\n : described;\n shape[arg.name] = (arg.required ? base : base.optional()) as z.ZodType;\n }\n\n return ownKeysOnly(z.object(shape));\n};\n\n/** The `StructuredResult` wrapper and nothing else — see `normalizeToolResult`. */\nconst isStructuredResult = (\n value: Record<string, unknown>,\n): value is StructuredResult => {\n // Own properties only: an inherited `structuredContent` — a getter on a model\n // or ORM prototype, say — is not a nomination.\n if (\n !Object.hasOwn(value, \"structuredContent\") ||\n value.structuredContent === undefined\n ) {\n return false;\n }\n\n // The companions are copied into the result envelope as they stand, so a\n // wrongly typed one would put an unserializable value on the wire and fail\n // the call itself. Declining the wrapper leaves the whole object to be read\n // as a payload, which costs a tool error at worst.\n if (value.isError !== undefined && typeof value.isError !== \"boolean\") {\n return false;\n }\n\n if (\n value._meta !== undefined &&\n (typeof value._meta !== \"object\" ||\n value._meta === null ||\n Array.isArray(value._meta))\n ) {\n return false;\n }\n\n // A key with no value cannot be what makes this a payload rather than a\n // wrapper — it never reaches the wire either way, so `{ structuredContent,\n // trace: debug ? id : undefined }` is still a wrapper.\n return Object.keys(value).every(\n (key) =>\n key === \"structuredContent\" ||\n key === \"isError\" ||\n key === \"_meta\" ||\n value[key] === undefined,\n );\n};\n\n/**\n * Normalizes the several shapes `execute` may return into a CallToolResult.\n *\n * Most of these shapes are told apart by inspecting the returned value, which\n * is a guess: a structured payload is an arbitrary object and can carry the\n * same keys the shorthands are recognized by. `hasOutputSchema` narrows that\n * guess — a tool that declared an output schema returns its structured payload\n * directly — and `structuredContent` settles what remains, since the one\n * genuinely ambiguous shape cannot be resolved by inspection at all.\n */\nconst normalizeToolResult = (\n result: unknown,\n hasOutputSchema: boolean,\n): unknown => {\n if (result === undefined || result === null) {\n return { content: [] };\n }\n\n if (typeof result === \"string\") {\n return { content: [{ text: result, type: \"text\" }] };\n }\n\n if (typeof result === \"object\") {\n const value = result as Record<string, unknown>;\n\n // Already an input_required (MRTR) or a full content result — pass through.\n //\n // A structured payload with its own array-valued `content` field is\n // indistinguishable from content blocks here, and loses: inspecting the\n // elements would only move the guess, and an empty array carries nothing to\n // inspect. Such a tool returns `{ structuredContent }` instead.\n if (value.resultType === \"input_required\" || Array.isArray(value.content)) {\n return value;\n }\n\n // Stated outright, so no guessing: the payload is whatever `execute`\n // nominated, and the fallback below is written for it as usual. Passing the\n // value through unread would nest it under a second `structuredContent`.\n //\n // Only the bare wrapper counts. Anything carrying keys of its own is a\n // payload that happens to have a `structuredContent` field, and unwrapping\n // it would both drop those keys and put them on the wire, where a field\n // `execute` meant for itself does not belong.\n if (isStructuredResult(value)) {\n return {\n content: [\n {\n // `undefined` is excluded already; this covers what else JSON\n // declines to represent, so a broken payload stays a tool error\n // rather than an unserializable content block.\n text: JSON.stringify(value.structuredContent) ?? \"null\",\n type: \"text\",\n },\n ],\n structuredContent: value.structuredContent,\n ...(value.isError === undefined ? {} : { isError: value.isError }),\n ...(value._meta === undefined ? {} : { _meta: value._meta }),\n };\n }\n\n // The single-content-block shorthand, off once an output schema is declared:\n // a structured payload discriminated on `type` is the ordinary way to write\n // a union, and reading one as a content block would drop the payload the\n // schema promised. Such a tool cannot be after the shorthand anyway — a\n // declared schema makes `structuredContent` mandatory.\n if (\n !hasOutputSchema &&\n (value.type === \"text\" ||\n value.type === \"image\" ||\n value.type === \"audio\" ||\n value.type === \"resource\" ||\n value.type === \"resource_link\")\n ) {\n return { content: [value] };\n }\n\n // Also carry serialized JSON as text, for clients that ignore\n // `structuredContent`.\n return {\n content: [{ text: JSON.stringify(value), type: \"text\" }],\n structuredContent: value,\n };\n }\n\n return { content: [{ text: String(result), type: \"text\" }] };\n};\n\nexport { delay };\n\n// Convenience re-exports so the common auth surface is reachable from the\n// package root; `@vitemcp/server/auth` remains the full module.\nexport {\n AuthProvider,\n AzureProvider,\n getAuthSession,\n GitHubProvider,\n GoogleProvider,\n OAuthProvider,\n requireAll,\n requireAny,\n requireAuth,\n requireRole,\n requireScopes,\n} from \"./auth/index.js\";\n\nexport type {\n AuthProviderConfig,\n AzureProviderConfig,\n AzureSession,\n GenericOAuthProviderConfig,\n GitHubSession,\n GoogleSession,\n OAuthSession,\n} from \"./auth/index.js\";\n\n// `ServerOptions.oauth.proxy` is typed as this, so it must be nameable here.\nexport { OAuthProxy, OAuthProxyError } from \"./auth/OAuthProxy.js\";\n\nexport { DiscoveryDocumentCache } from \"./DiscoveryDocumentCache.js\";\n\nexport {\n jsonSchemaAdapter,\n type JsonSchemaObject,\n type JsonSchemaStandardSchema,\n} from \"./jsonSchemaAdapter.js\";\n\n// Re-exported because they appear in this package's public signatures and\n// `@modelcontextprotocol/server` is only a transitive dependency for consumers.\nexport type {\n CacheScope,\n Icon,\n InputRequest,\n InputRequiredResult,\n ToolAnnotations,\n} from \"@modelcontextprotocol/server\";\n","/** OAuth proxy HTTP routes, as a Hono router. */\nimport { Hono } from \"hono\";\n\nimport type { OAuthProxy } from \"./OAuthProxy.js\";\n\n/** Bodies larger than this are rejected before parsing (DoS guard). */\nexport const OAUTH_PROXY_MAX_BODY_SIZE = 1024 * 1024;\n\ntype OAuthErrorish = {\n statusCode?: number;\n toJSON?: () => unknown;\n};\n\nconst errorResponse = (error: unknown) => {\n const err = error as OAuthErrorish;\n return {\n body: err.toJSON?.() ?? { error: \"invalid_request\" },\n status: (err.statusCode ?? 400) as 400,\n };\n};\n\n/**\n * Reads a body under a hard cap, enforced *while* reading — measuring after\n * buffering would let a client push arbitrary bytes into memory.\n *\n * Returns `null` when the body is too large, aborted, or unreadable.\n */\nconst readCappedBody = async (request: Request): Promise<null | string> => {\n const declared = request.headers.get(\"content-length\");\n\n if (declared && Number(declared) > OAUTH_PROXY_MAX_BODY_SIZE) {\n return null;\n }\n\n if (!request.body) {\n try {\n const text = await request.text();\n return text.length > OAUTH_PROXY_MAX_BODY_SIZE ? null : text;\n } catch {\n return null;\n }\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > OAUTH_PROXY_MAX_BODY_SIZE) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n } catch {\n // Aborted or errored mid-body: settle rather than leaving it pending.\n return null;\n }\n\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\nconst readJsonBody = async (request: Request): Promise<null | unknown> => {\n const text = await readCappedBody(request);\n\n if (text === null) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\nconst tooLarge = {\n error: \"invalid_request\",\n error_description: `Request body exceeds ${OAUTH_PROXY_MAX_BODY_SIZE / (1024 * 1024)} MiB`,\n};\n\n/**\n * RFC 6749 §5.1 mandates these on token endpoint responses, and RFC 7591\n * §3.2.1 on a registration response carrying `client_secret`: without them a\n * CDN, a forward proxy or the browser is free to retain the credential.\n *\n * Applied to every response from those two endpoints, error paths included —\n * an error is exactly the response an intermediary is most likely to consider\n * cacheable, and the endpoint should not vary in cacheability by outcome.\n * `authorize`, `callback` and `consent` are left alone: they redirect, and\n * carry no credential in the body.\n */\nconst noStore = {\n \"Cache-Control\": \"no-store\",\n Pragma: \"no-cache\",\n};\n\n/**\n * RFC 6749 §5.2: a client authentication failure is a 401 when the client\n * tried the Authorization header, and RFC 9110 §15.5.2 requires every 401 to\n * carry a challenge. Sent for every `invalid_client` from the token endpoint,\n * which the spec allows, so the status does not depend on where the\n * credentials were.\n */\nconst invalidClientHeaders = {\n ...noStore,\n \"WWW-Authenticate\": 'Basic realm=\"oauth\", charset=\"UTF-8\"',\n};\n\n/**\n * RFC 6749 §2.3.1: `client_id:client_secret`, each form-urlencoded, then\n * base64. Returns `null` for a header that does not decode to that shape.\n */\nconst parseBasicCredentials = (\n authorization: string,\n): { clientId: string; clientSecret: string } | null => {\n const decoded = Buffer.from(authorization.slice(6).trim(), \"base64\").toString(\n \"utf8\",\n );\n const separator = decoded.indexOf(\":\");\n\n if (separator <= 0) {\n return null;\n }\n\n try {\n return {\n clientId: decodeURIComponent(decoded.slice(0, separator)),\n clientSecret: decodeURIComponent(decoded.slice(separator + 1)),\n };\n } catch {\n return null;\n }\n};\n\n/**\n * RFC 8414 / 9728 metadata is snake_case on the wire; config is camelCase.\n * Top-level keys only — nested values are caller-defined payloads.\n */\nconst toSnakeCase = (value: unknown): unknown => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([k, v]) => [\n k.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase(),\n v,\n ]),\n );\n};\n\nexport type OAuthRouterOptions = {\n authorizationServer?: unknown;\n /** Path prefix the server is mounted under, e.g. \"/issuer1\". */\n basePath?: string;\n /** MCP endpoint path, e.g. \"/mcp\". */\n endpoint?: string;\n protectedResource?: unknown;\n /** Optional: discovery metadata can be served without a proxy. */\n proxy?: OAuthProxy;\n};\n\nexport const createOAuthRouter = (options: OAuthRouterOptions): Hono => {\n const app = new Hono();\n const { proxy } = options;\n\n const basePath = options.basePath ?? \"\";\n const endpoint = options.endpoint ?? \"\";\n\n // RFC 8414 §3 / 9728 §3: exact routes, not wildcards — an unrelated suffix\n // must 404 rather than serve metadata.\n const serve = (path: string, body: unknown) =>\n app.get(path, (c) => c.json(body as never));\n\n if (options.authorizationServer) {\n // Issuer-scoped: under a base path, the bare root is not valid.\n serve(\n `/.well-known/oauth-authorization-server${basePath}`,\n toSnakeCase(options.authorizationServer),\n );\n }\n\n if (options.protectedResource) {\n const body = toSnakeCase(options.protectedResource);\n const scoped = `/.well-known/oauth-protected-resource${basePath}${endpoint}`;\n\n // Sub-path takes priority; root stays as the documented fallback.\n serve(scoped, body);\n\n if (scoped !== \"/.well-known/oauth-protected-resource\") {\n serve(\"/.well-known/oauth-protected-resource\", body);\n }\n }\n\n if (!proxy) {\n return app;\n }\n\n // RFC 7591 Dynamic Client Registration.\n app.post(`${basePath}/oauth/register`, async (c) => {\n const body = await readJsonBody(c.req.raw);\n\n if (body === null) {\n return c.json(tooLarge, 400, noStore);\n }\n\n try {\n return c.json(await proxy.registerClient(body as never), 201, noStore);\n } catch (error) {\n const { body: errBody, status } = errorResponse(error);\n return c.json(errBody as never, status, noStore);\n }\n });\n\n app.get(`${basePath}/oauth/authorize`, async (c) => {\n try {\n const params = Object.fromEntries(\n new URL(c.req.url).searchParams.entries(),\n );\n return await proxy.authorize(params as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.post(`${basePath}/oauth/token`, async (c) => {\n const raw = c.req.raw;\n const text = await readCappedBody(raw);\n\n if (text === null) {\n return c.json(tooLarge, 400, noStore);\n }\n\n try {\n const params = Object.fromEntries(new URLSearchParams(text).entries());\n\n // RFC 6749 §2.3.1: credentials may arrive via HTTP Basic instead of the\n // body. The proxy verifies whichever was sent.\n const authHeader = raw.headers.get(\"authorization\");\n\n if (authHeader?.toLowerCase().startsWith(\"basic \")) {\n const credentials = parseBasicCredentials(authHeader);\n\n if (!credentials) {\n return c.json(\n {\n error: \"invalid_client\",\n error_description: \"Malformed Basic Authorization header\",\n },\n 401,\n invalidClientHeaders,\n );\n }\n\n // RFC 6749 §2.3: one authentication method per request. Merging the\n // two used to let the body supply a client_id the header's secret\n // was then tried against.\n if (params.client_secret !== undefined) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description:\n \"Send client credentials in the Authorization header or the request body, not both\",\n },\n 400,\n noStore,\n );\n }\n\n if (\n params.client_id !== undefined &&\n params.client_id !== credentials.clientId\n ) {\n return c.json(\n {\n error: \"invalid_request\",\n error_description:\n \"client_id in the request body does not match the Authorization header\",\n },\n 400,\n noStore,\n );\n }\n\n params.client_id = credentials.clientId;\n params.client_secret = credentials.clientSecret;\n }\n\n const result =\n params.grant_type === \"refresh_token\"\n ? await proxy.exchangeRefreshToken(params as never)\n : await proxy.exchangeAuthorizationCode(params as never);\n\n return c.json(result as never, 200, noStore);\n } catch (error) {\n const { body, status } = errorResponse(error);\n\n if ((body as { error?: unknown }).error === \"invalid_client\") {\n return c.json(body as never, 401, invalidClientHeaders);\n }\n\n return c.json(body as never, status, noStore);\n }\n });\n\n app.get(`${basePath}/oauth/callback`, async (c) =>\n proxy.handleCallback(c.req.raw),\n );\n\n app.all(`${basePath}/oauth/consent`, async (c) =>\n proxy.handleConsent(c.req.raw),\n );\n\n return app;\n};\n","/**\n * Releases a response whose body we are about to discard.\n *\n * Throwing on a non-2xx without touching the body leaves an unread stream, and\n * the connection stays checked out until GC finalizes it. Cancellation failures\n * are swallowed so the caller still reports the original HTTP status, which is\n * the useful diagnostic.\n *\n * Typed structurally rather than as `Response` because callers use both\n * undici's fetch and the global one.\n */\nexport const cancelResponseBody = async (response: {\n body?: { cancel: () => Promise<unknown> } | null;\n}): Promise<void> => {\n if (!response.body) {\n return;\n }\n\n try {\n await response.body.cancel();\n } catch {\n // Nothing to report: the HTTP failure is what the caller cares about.\n }\n};\n","import { cancelResponseBody } from \"./cancelResponseBody.js\";\n\nexport class DiscoveryDocumentCache {\n public get size(): number {\n return this.#cache.size;\n }\n\n #cache: Map<\n string,\n {\n data: unknown;\n expiresAt: number;\n }\n > = new Map();\n\n #generation = 0;\n\n #inFlight: Map<string, Promise<unknown>> = new Map();\n\n #timeoutMs: number;\n\n #ttl: number;\n\n #urlGenerations: Map<string, number> = new Map();\n\n /**\n * @param options - configuration options\n * @param options.timeoutMs - timeout in miliseconds for the upstream fetch\n * @param options.ttl - time-to-live in miliseconds\n */\n public constructor(options: { timeoutMs?: number; ttl?: number } = {}) {\n this.#timeoutMs = options.timeoutMs ?? 10000; // default 10 seconds\n this.#ttl = options.ttl ?? 3600000; // default 1 hour\n }\n\n /**\n * @param url - optional URL to clear. if omitted, clears all cached documents.\n */\n public clear(url?: string): void {\n if (url) {\n this.#cache.delete(url);\n this.#inFlight.delete(url);\n this.#urlGenerations.set(url, (this.#urlGenerations.get(url) ?? 0) + 1);\n } else {\n this.#cache.clear();\n this.#inFlight.clear();\n this.#urlGenerations.clear();\n this.#generation++;\n }\n }\n\n /**\n * fetches a discovery document from the given URL.\n * uses cached value if available and not expired.\n * coalesces concurrent requests for the same URL to prevent duplicate fetches.\n *\n * @param url - the discovery document URL (e.g., /.well-known/openid-configuration)\n * @returns the discovery document as a JSON object\n * @throws Error if the fetch fails or returns non-OK status\n */\n public async get(url: string): Promise<unknown> {\n const now = Date.now();\n const cached = this.#cache.get(url);\n\n // return cached value if still valid\n if (cached && cached.expiresAt > now) {\n return cached.data;\n }\n\n // check if there’s already an in-flight request for this URL\n const inFlight = this.#inFlight.get(url);\n\n if (inFlight) {\n return inFlight;\n }\n\n // create a new fetch promise and store it\n const fetchPromise = this.#fetchAndCache(\n url,\n this.#generation,\n this.#urlGenerations.get(url) ?? 0,\n );\n\n this.#inFlight.set(url, fetchPromise);\n\n try {\n const data = await fetchPromise;\n return data;\n } finally {\n // clean up in-flight promise after completion\n // (success or failure)\n if (this.#inFlight.get(url) === fetchPromise) {\n this.#inFlight.delete(url);\n }\n }\n }\n\n /**\n * @param url - the URL to check\n * @returns true if the URL is cached and nott expired\n */\n public has(url: string): boolean {\n const cached = this.#cache.get(url);\n\n if (!cached) {\n return false;\n }\n\n const now = Date.now();\n\n if (cached.expiresAt <= now) {\n // expired, remove from cache\n this.#cache.delete(url);\n return false;\n }\n\n return true;\n }\n\n async #fetchAndCache(\n url: string,\n generation: number,\n urlGeneration: number,\n ): Promise<unknown> {\n // fetch fresh document, bounded by the configured timeout\n let res: Response;\n try {\n res = await fetch(url, {\n signal: AbortSignal.timeout(this.#timeoutMs),\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n ) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: timed out after ${this.#timeoutMs}ms`,\n );\n }\n throw error;\n }\n\n if (!res.ok) {\n await cancelResponseBody(res);\n\n throw new Error(\n `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`,\n );\n }\n\n const data = await res.json();\n // calculate expiration time AFTER fetch completes\n const expiresAt = Date.now() + this.#ttl;\n\n // A clear that occurred while the fetch was pending invalidates its result.\n if (\n this.#generation === generation &&\n (this.#urlGenerations.get(url) ?? 0) === urlGeneration\n ) {\n this.#cache.set(url, {\n data,\n expiresAt,\n });\n }\n\n return data;\n }\n}\n","import { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * A plain JSON Schema object descriptor.\n */\nexport type JsonSchemaObject = {\n [key: string]: unknown;\n $schema?: string;\n additionalProperties?: boolean | Record<string, unknown>;\n properties?: Record<string, unknown>;\n required?: string[];\n type: string;\n};\n\n/**\n * A Standard Schema that also carries the JSON Schema it was built from.\n *\n * `~standard.jsonSchema` is the Standard JSON Schema extension. Anything that\n * knows about it — including the `xsschema` conversion ViteMCP uses to build\n * `tools/list` — reads the schema straight off the object instead of trying to\n * derive one from a validation library it does not recognise.\n */\nexport interface JsonSchemaStandardSchema extends StandardSchemaV1 {\n readonly \"~standard\": {\n readonly jsonSchema: {\n readonly input: () => JsonSchemaObject;\n readonly output: () => JsonSchemaObject;\n };\n } & StandardSchemaV1.Props;\n}\n\ninterface AjvErrorObject {\n instancePath: string;\n keyword: string;\n message?: string;\n params?: Record<string, unknown>;\n}\n\ntype AjvValidateFunction = {\n errors?: AjvErrorObject[] | null;\n (data: unknown): boolean;\n};\n\n/**\n * Wraps a plain JSON Schema object for use as a tool's `parameters` or\n * `outputSchema`, without pulling in Zod or Valibot.\n *\n * Validation uses AJV, an optional peer dependency — install `ajv` (plus\n * `ajv-formats` for `format` keywords). It is imported on first validation, so\n * servers that never call it pay nothing.\n *\n * @example\n * ```ts\n * server.addTool({\n * name: \"greet\",\n * parameters: jsonSchemaAdapter({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * required: [\"name\"],\n * }),\n * execute: async ({ name }) => `Hello, ${name}!`,\n * });\n * ```\n */\nexport function jsonSchemaAdapter(\n schema: JsonSchemaObject,\n): JsonSchemaStandardSchema {\n // Compiling a schema makes AJV generate and evaluate JavaScript, so it has\n // to happen once rather than per call. The promise is memoised, not just the\n // result, so concurrent first calls share a single compilation.\n let compiled: Promise<AjvValidateFunction> | undefined;\n\n const getValidator = (): Promise<AjvValidateFunction> => {\n compiled ??= compileSchema(schema).catch((error: unknown) => {\n // Do not memoise a failure: a missing dependency should be reported on\n // every call, not swallowed after the first.\n compiled = undefined;\n throw error;\n });\n\n return compiled;\n };\n\n return {\n \"~standard\": {\n jsonSchema: {\n input: () => schema,\n output: () => schema,\n },\n validate: async (\n data: unknown,\n ): Promise<StandardSchemaV1.Result<unknown>> => {\n const validate = await getValidator();\n\n if (validate(data)) {\n return { value: data };\n }\n\n return { issues: (validate.errors ?? []).map(toIssue) };\n },\n vendor: \"json-schema\",\n version: 1,\n },\n };\n}\n\n/**\n * The JSON Schema dialect a schema is validated in, read from its `$schema` as\n * the MCP SDK reads it: 2020-12 when there is none (SEP-1613), and draft-07 for\n * draft-06, which draft-07 only added to.\n *\n * Clients validate structured content in that dialect, so validating in\n * another has the two disagree. AJV's default engine is draft-07's, which read\n * 2020-12's `items: false` beside `prefixItems` as \"no items at all\", and\n * failed to compile a schema declaring 2020-12.\n */\nconst dialectOf = ($schema: unknown): \"2019-09\" | \"2020-12\" | \"draft-07\" => {\n if (typeof $schema !== \"string\") {\n return \"2020-12\";\n }\n\n switch ($schema.replace(/^https?:\\/\\//, \"\").replace(/#$/, \"\")) {\n case \"json-schema.org/draft-06/schema\":\n case \"json-schema.org/draft-07/schema\":\n return \"draft-07\";\n case \"json-schema.org/draft/2019-09/schema\":\n return \"2019-09\";\n case \"json-schema.org/draft/2020-12/schema\":\n return \"2020-12\";\n }\n\n throw new Error(\n `JSON Schema declares an unsupported dialect (\"$schema\": \"${$schema}\"). ` +\n \"jsonSchemaAdapter validates 2020-12, 2019-09, draft-07 and draft-06.\",\n );\n};\n\nasync function compileSchema(\n schema: JsonSchemaObject,\n): Promise<AjvValidateFunction> {\n // `$schema` picks the engine, and the engine checks the schema against its\n // own dialect's meta-schema. Left in, `$schema` would have to use the scheme\n // AJV registered that meta-schema under — `http:` for draft-07, `https:` for\n // the rest — or compiling fails as \"no schema with key or ref\". What is\n // advertised is `schema`, `$schema` and all.\n const { $schema, ...body } = schema;\n const dialect = dialectOf($schema);\n let ajvModule;\n\n try {\n ajvModule =\n dialect === \"2020-12\"\n ? await import(\"ajv/dist/2020.js\")\n : dialect === \"2019-09\"\n ? await import(\"ajv/dist/2019.js\")\n : await import(\"ajv\");\n } catch {\n throw new Error(\n 'The \"ajv\" package is required to validate JSON Schema tool parameters. ' +\n \"Install it with: npm install ajv\",\n );\n }\n\n // ajv ships CommonJS, so depending on the loader the class arrives as the\n // module namespace, as `.default`, or as `.default.default`.\n const Ajv = unwrapDefault(unwrapDefault(ajvModule)) as unknown as new (\n options: Record<string, unknown>,\n ) => {\n compile: (schema: unknown) => AjvValidateFunction;\n };\n\n // A key counts as present only if the data has it of its own. AJV otherwise\n // reads `data[key]`, which finds `Object.prototype`'s members, so leaving\n // out an optional `toString` or `constructor` failed as \"must be string\".\n const ajv = new Ajv({ allErrors: true, ownProperties: true, strict: false });\n\n try {\n const formatsModule = await import(\"ajv-formats\");\n const addFormats = unwrapDefault(\n unwrapDefault(formatsModule),\n ) as unknown as (ajv: unknown) => void;\n\n addFormats(ajv);\n } catch {\n // ajv-formats is optional; `format` keywords are simply not enforced.\n }\n\n return ajv.compile(body);\n}\n\nfunction toIssue(error: AjvErrorObject): StandardSchemaV1.Issue {\n // Only the first split element is the empty string before the leading `/`.\n // Any other empty segment is a property named \"\", which is a legal key.\n const path = error.instancePath\n .split(\"/\")\n .slice(1)\n // JSON Pointer escapes, per RFC 6901.\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"))\n .map((segment): number | string => {\n const index = Number(segment);\n return /^(?:0|[1-9]\\d*)$/.test(segment) && Number.isSafeInteger(index)\n ? index\n : segment;\n });\n\n // AJV reports a missing property against its parent object, with the name in\n // `params`. Appending it points the issue at the field the user has to fix.\n const missingProperty = error.params?.missingProperty;\n\n if (error.keyword === \"required\" && typeof missingProperty === \"string\") {\n path.push(missingProperty);\n }\n\n return {\n message: error.message || \"Validation error\",\n path,\n };\n}\n\nfunction unwrapDefault(value: unknown): unknown {\n return typeof value === \"object\" && value !== null && \"default\" in value\n ? (value as { default: unknown }).default\n : value;\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAoB;AAAA,EAGpB;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAEK;AAEP,SAAS,yBAAyB;AAClC,SAAS,gBAAgB;AACzB,SAAS,QAAAA,aAAY;AACrB,SAAS,YAAY;AACrB,OAAO,UAAU;AACjB,OAAO,WAAW;AAClB,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,SAAS,cAAc,aAAa;AACpC,SAAS,SAAAC,cAAa;AACtB,SAAS,oBAAoB;AAC7B,SAAS,SAAS;;;ACxClB,SAAS,YAAY;AAKd,IAAM,4BAA4B,OAAO;AAOhD,IAAM,gBAAgB,CAAC,UAAmB;AACxC,QAAM,MAAM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