{"version":3,"file":"mcp-BumlNux0.cjs","names":["COMPLETABLE_SYMBOL: unique symbol","onerror?: (error: Error) => void","honored: SubscriptionFilter","SUBSCRIPTION_ID_META_KEY","codecForVersion","MODERN_WIRE_REVISION","controller!: ReadableStreamDefaultController<Uint8Array>","unsubscribe: (() => void) | undefined","keepAliveTimer: ReturnType<typeof setInterval> | undefined","abortCleanup: (() => void) | undefined","SERVER_INFO_META_KEY","CHANGE_NOTIFICATION_METHODS: ReadonlySet<string>","_maxSubscriptions: number","uriParam: unknown","out: NotificationBody[]","out: ListenCloseFrame[]","OAuthError","OAuthErrorCode","OAuthError","OAuthErrorCode","OAuthError","OAuthErrorCode","ProtocolError","ProtocolErrorCode","requiredClientCapabilitiesForInputRequest","_host: LegacyInputRequiredShimHost","inputRequiredRoundsExceededMessage","responses: Record<string, unknown> | undefined","coerced: [string, CoercedEmbeddedInputRequest][]","missingClientCapabilities","linkedRoundAbort","legOptions: RequestOptions","sleep","REQUEST_STATE_ONLY_LEG_PACING_MS","ctxNext: ServerContext","requestStateAccessor","withRequestStateValue","isInputRequiredResult","INPUT_REQUIRED_CAPABLE_METHODS: ReadonlySet<string>","writeClientIdentity: (server: Server, identity: PerRequestClientIdentity) => void","installDiscoverHandler: (server: Server, servedModernVersions: readonly string[]) => void","readServerIdentity: (server: Server) => Implementation","Protocol","_serverInfo: Implementation","DefaultJsonSchemaValidator","modernProtocolVersions","SdkError","SdkErrorCode","transportSessionId: string | undefined","parseSchema","LoggingLevelSchema","threshold: LoggingLevel | undefined","LOG_LEVEL_META_KEY","mergeCapabilities","isInputRequiredResult","ProtocolError","ProtocolErrorCode","attachCacheHintFallback","codecForVersion","normalizeContentlessToolResult","isModernProtocolVersion","rawRequestState: unknown","withRequestStateValue","result: Result","LATEST_PROTOCOL_VERSION","missingClientCapabilities","MissingRequiredClientCapabilityError","CLIENT_CAPABILITIES_META_KEY","legacyProtocolVersions","formParams: ElicitRequestFormParams","stack: unknown[]","standardSchemaToJsonSchema","uri: URL","toolDefinition: Tool","ProtocolError","ProtocolErrorCode","isInputRequiredResult","validateStandardSchema","templateResources: Resource[]","attachCacheHintFallback","ResourceNotFoundError","promptArgumentsFromStandardSchema","metadata: ResourceMetadata","registeredResource: RegisteredResource","registeredResourceTemplate: RegisteredResourceTemplate","registeredPrompt: RegisteredPrompt","outputSchemaJson: Record<string, unknown> | undefined","registeredTool: RegisteredTool","normalizeRawShapeSchema","_callbacks: {\n            /**\n             * A callback to list all resources matching this template. This is required to be specified, even if `undefined`, to avoid accidentally forgetting resource listing.\n             */\n            list: ListResourcesCallback | undefined;\n\n            /**\n             * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values.\n             */\n            complete?: {\n                [variable: string]: CompleteResourceTemplateCallback;\n            };\n        }","UriTemplate","callback","scanXMcpHeaderDeclarations","EMPTY_COMPLETION_RESULT: CompleteResult"],"sources":["../src/server/completable.ts","../src/server/sseKeepAlive.ts","../src/server/serverEventBus.ts","../src/server/listenRouter.ts","../src/server/middleware/bearerAuth.ts","../src/server/middleware/oauthMetadata.ts","../src/server/scopeChallenge.ts","../src/server/legacyInputRequiredShim.ts","../src/server/server.ts","../src/server/mcp.ts"],"sourcesContent":["import type { StandardSchemaV1 } from '@modelcontextprotocol/core-internal';\n\nexport const COMPLETABLE_SYMBOL: unique symbol = Symbol.for('mcp.completable');\n\nexport type CompleteCallback<T extends StandardSchemaV1 = StandardSchemaV1> = (\n    value: StandardSchemaV1.InferInput<T>,\n    context?: {\n        arguments?: Record<string, string>;\n    }\n) => StandardSchemaV1.InferInput<T>[] | Promise<StandardSchemaV1.InferInput<T>[]>;\n\nexport type CompletableMeta<T extends StandardSchemaV1 = StandardSchemaV1> = {\n    complete: CompleteCallback<T>;\n};\n\nexport type CompletableSchema<T extends StandardSchemaV1> = T & {\n    [COMPLETABLE_SYMBOL]: CompletableMeta<T>;\n};\n\n/**\n * Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP.\n *\n * @example\n * ```ts source=\"./completable.examples.ts#completable_basicUsage\"\n * server.registerPrompt(\n *     'review-code',\n *     {\n *         title: 'Code Review',\n *         argsSchema: z.object({\n *             language: completable(z.string().describe('Programming language'), value =>\n *                 ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value))\n *             )\n *         })\n *     },\n *     ({ language }) => ({\n *         messages: [\n *             {\n *                 role: 'user' as const,\n *                 content: {\n *                     type: 'text' as const,\n *                     text: `Review this ${language} code.`\n *                 }\n *             }\n *         ]\n *     })\n * );\n * ```\n *\n * @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions\n */\nexport function completable<T extends StandardSchemaV1>(schema: T, complete: CompleteCallback<T>): CompletableSchema<T> {\n    Object.defineProperty(schema as object, COMPLETABLE_SYMBOL, {\n        value: { complete } as CompletableMeta<T>,\n        enumerable: false,\n        writable: false,\n        configurable: false\n    });\n    return schema as CompletableSchema<T>;\n}\n\n/**\n * Checks if a schema is completable (has completion metadata).\n */\nexport function isCompletable(schema: unknown): schema is CompletableSchema<StandardSchemaV1> {\n    return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in (schema as object);\n}\n\n/**\n * Gets the completer callback from a completable schema, if it exists.\n */\nexport function getCompleter<T extends StandardSchemaV1>(schema: T): CompleteCallback<T> | undefined {\n    const meta = (schema as unknown as { [COMPLETABLE_SYMBOL]?: CompletableMeta<T> })[COMPLETABLE_SYMBOL];\n    return meta?.complete as CompleteCallback<T> | undefined;\n}\n","/** Default interval between SSE keep-alive comment frames. */\nexport const DEFAULT_SSE_KEEP_ALIVE_MS = 15_000;\n\nconst MAX_TIMER_DELAY_MS = 2 ** 31 - 1;\n\n/** Arms an unref'd timer, or disables keep-alive for invalid delays. */\nexport function armSseKeepAlive(intervalMs: number, onTick: () => void): ReturnType<typeof setInterval> | undefined {\n    if (!Number.isFinite(intervalMs) || intervalMs < 1) {\n        return undefined;\n    }\n\n    const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS));\n    (timer as { unref?: () => void }).unref?.();\n    return timer;\n}\n","import type { ServerCapabilities, SubscriptionFilter } from '@modelcontextprotocol/core-internal';\n\n/**\n * A change event a server publishes for delivery on open `subscriptions/listen`\n * streams. Each variant maps onto exactly one notification method:\n *\n * - `tools_list_changed` → `notifications/tools/list_changed`\n * - `prompts_list_changed` → `notifications/prompts/list_changed`\n * - `resources_list_changed` → `notifications/resources/list_changed`\n * - `resource_updated` → `notifications/resources/updated` (carries the URI)\n *\n * The bus carries the EVENT, not the wire shape — the entry's listen router\n * owns subscription-id stamping and per-stream filtering.\n */\nexport type ServerEvent =\n    | { kind: 'tools_list_changed' }\n    | { kind: 'prompts_list_changed' }\n    | { kind: 'resources_list_changed' }\n    | { kind: 'resource_updated'; uri: string };\n\n/**\n * The server-side change-event seam for `subscriptions/listen`.\n *\n * The serving entry (`createMcpHandler`) owns the per-stream listen router:\n * each open `subscriptions/listen` stream registers a listener via\n * `subscribe()`, and consumer code (typically via `handler.notify.*` sugar)\n * publishes change events via `publish()`. In-process servers can use the\n * default {@linkcode InMemoryServerEventBus}; multi-process deployments\n * implement this interface over their own pub/sub.\n *\n * The SDK owns wire semantics (ack-first, filtering, subscription-id\n * stamping, teardown); a `ServerEventBus` only sources the events. It MUST\n * NOT echo back to the listener that published an event when called from\n * inside that listener (no surprise here — the default delivers\n * synchronously and listeners never publish).\n */\nexport interface ServerEventBus {\n    /**\n     * Publish a change event to every registered listener.\n     */\n    publish(event: ServerEvent): void;\n    /**\n     * Register a listener; returns an idempotent unsubscribe function.\n     */\n    subscribe(listener: (event: ServerEvent) => void): () => void;\n}\n\n/**\n * A `ServerEventBus` backed by an in-process listener set.\n *\n * `publish()` delivers synchronously to the live listener set (a listener\n * unsubscribing itself mid-dispatch is safe; the entry's listen-router\n * listeners never unsubscribe peers). A throwing listener does not stop\n * delivery to the others.\n */\nexport class InMemoryServerEventBus implements ServerEventBus {\n    private readonly _listeners = new Set<(event: ServerEvent) => void>();\n\n    /**\n     * @param onerror - Optional callback for errors thrown by listeners\n     *   during dispatch.\n     */\n    constructor(private readonly onerror?: (error: Error) => void) {}\n\n    publish(event: ServerEvent): void {\n        for (const listener of this._listeners) {\n            try {\n                listener(event);\n            } catch (error) {\n                this.onerror?.(error instanceof Error ? error : new Error(String(error)));\n            }\n        }\n    }\n\n    subscribe(listener: (event: ServerEvent) => void): () => void {\n        this._listeners.add(listener);\n        let live = true;\n        return () => {\n            if (!live) return;\n            live = false;\n            this._listeners.delete(listener);\n        };\n    }\n\n    /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */\n    get listenerCount(): number {\n        return this._listeners.size;\n    }\n}\n\n/**\n * Typed publish-side facade over `bus.publish` returned by `createMcpHandler`:\n * each method publishes the corresponding {@linkcode ServerEvent}. Prefer this\n * over calling `bus.publish` directly — the names match the wire methods.\n */\nexport interface ServerNotifier {\n    /** Publish `notifications/tools/list_changed` to every open subscription that opted in. */\n    toolsChanged(): void;\n    /** Publish `notifications/prompts/list_changed` to every open subscription that opted in. */\n    promptsChanged(): void;\n    /** Publish `notifications/resources/list_changed` to every open subscription that opted in. */\n    resourcesChanged(): void;\n    /** Publish `notifications/resources/updated` for `uri` to every open subscription that opted in to that URI. */\n    resourceUpdated(uri: string): void;\n}\n\n/** Build a {@linkcode ServerNotifier} over a bus. */\nexport function createServerNotifier(bus: ServerEventBus): ServerNotifier {\n    return {\n        toolsChanged: () => bus.publish({ kind: 'tools_list_changed' }),\n        promptsChanged: () => bus.publish({ kind: 'prompts_list_changed' }),\n        resourcesChanged: () => bus.publish({ kind: 'resources_list_changed' }),\n        resourceUpdated: (uri: string) => bus.publish({ kind: 'resource_updated', uri })\n    };\n}\n\n/**\n * Whether a `subscriptions/listen` filter accepts a given change event.\n *\n * Pure: no I/O, no mutation. The filter governs ONLY the four\n * subscription-gated change types — non-gated notifications never reach the\n * bus and are not modeled here.\n *\n * `resource_updated` matches only when `resourceSubscriptions` is present and\n * contains the event's URI exactly (per the spec: \"for these resource URIs\").\n */\nexport function listenFilterAccepts(filter: SubscriptionFilter, event: ServerEvent): boolean {\n    switch (event.kind) {\n        case 'tools_list_changed': {\n            return filter.toolsListChanged === true;\n        }\n        case 'prompts_list_changed': {\n            return filter.promptsListChanged === true;\n        }\n        case 'resources_list_changed': {\n            return filter.resourcesListChanged === true;\n        }\n        case 'resource_updated': {\n            return filter.resourceSubscriptions !== undefined && filter.resourceSubscriptions.includes(event.uri);\n        }\n    }\n}\n\n/**\n * The honored subset of a requested filter: keeps only the fields the client\n * explicitly opted in to (drops `false` and absent fields), narrowed against\n * the server's declared capabilities when supplied. The serving entry sends\n * this back in `notifications/subscriptions/acknowledged` so the ack reflects\n * what the server can actually deliver.\n *\n * - `toolsListChanged` is honored only when `capabilities.tools.listChanged`\n *   is advertised; likewise `promptsListChanged` / `resourcesListChanged`.\n * - `resourceSubscriptions` is honored only when\n *   `capabilities.resources.subscribe` is advertised.\n *\n * `capabilities` is optional on this pure helper for test convenience only —\n * both wired routers REQUIRE capabilities at the call site (the HTTP router's\n * `serve()` takes a required parameter; `StdioListenRouter.serve()` throws\n * before `setServerCapabilities()` was called), so the fail-open\n * `undefined → honor everything` branch is never reachable on a wired entry.\n */\nexport function honoredSubset(requested: SubscriptionFilter, capabilities?: ServerCapabilities): SubscriptionFilter {\n    const honored: SubscriptionFilter = {};\n    const allow = (bit: unknown): boolean => capabilities === undefined || bit === true;\n    if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true;\n    if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true;\n    if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true;\n    if (\n        requested.resourceSubscriptions !== undefined &&\n        requested.resourceSubscriptions.length > 0 &&\n        allow(capabilities?.resources?.subscribe)\n    ) {\n        honored.resourceSubscriptions = [...requested.resourceSubscriptions];\n    }\n    return honored;\n}\n\n/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */\nexport function serverEventToNotification(event: ServerEvent): { method: string; params?: { uri: string } } {\n    switch (event.kind) {\n        case 'tools_list_changed': {\n            return { method: 'notifications/tools/list_changed' };\n        }\n        case 'prompts_list_changed': {\n            return { method: 'notifications/prompts/list_changed' };\n        }\n        case 'resources_list_changed': {\n            return { method: 'notifications/resources/list_changed' };\n        }\n        case 'resource_updated': {\n            return { method: 'notifications/resources/updated', params: { uri: event.uri } };\n        }\n    }\n}\n","/**\n * The entry-handled `subscriptions/listen` router for the HTTP serving entry.\n *\n * `createMcpHandler` recognizes a modern-classified `subscriptions/listen`\n * request and routes it here: the entry owns ack-first, per-stream filtering,\n * subscription-id stamping, keepalive, capacity guarding, and teardown. The\n * consumer's factory IS constructed for listen, to read the instance's\n * declared `ServerCapabilities` only — the probe instance is never connected\n * and is closed immediately after the capabilities read. Token verification\n * and any per-request authorization still belong at the middleware layer\n * mounted in front of `createMcpHandler` (the entry's documented authz\n * posture).\n *\n * Per the spec at protocol revision 2026-07-28:\n * - The acknowledged notification is the FIRST message on the stream and\n *   carries the honored subset of the requested filter.\n * - Every notification on the stream (including the ack) carries the listen\n *   request's JSON-RPC id under `_meta['io.modelcontextprotocol/subscriptionId']`.\n * - The server MUST NOT deliver a notification type the client did not request.\n * - Server-side graceful close (`closeAll()`) emits the empty\n *   `subscriptions/listen` JSON-RPC result (the `SubscriptionsListenResult` —\n *   `_meta` carries the subscription id) before closing the stream; an abrupt\n *   transport close carries no response and the client treats it as a\n *   disconnect.\n */\nimport type {\n    Implementation,\n    JSONRPCRequest,\n    RequestId,\n    ServerCapabilities,\n    SubscriptionFilter\n} from '@modelcontextprotocol/core-internal';\nimport { codecForVersion, MODERN_WIRE_REVISION, SERVER_INFO_META_KEY, SUBSCRIPTION_ID_META_KEY } from '@modelcontextprotocol/core-internal';\n\nimport type { ServerEventBus } from './serverEventBus';\nimport { honoredSubset, listenFilterAccepts, serverEventToNotification } from './serverEventBus';\nimport { armSseKeepAlive, DEFAULT_SSE_KEEP_ALIVE_MS } from './sseKeepAlive';\n\n/** Default capacity guard: refuse a new subscription when this many are already open. */\nexport const DEFAULT_MAX_SUBSCRIPTIONS = 1024;\n\n/** Options for {@linkcode createListenRouter}. */\nexport interface ListenRouterOptions {\n    /** The event bus listen streams subscribe to. */\n    bus: ServerEventBus;\n    /** Reject a new listen with `-32603` when this many subscriptions are already open (default 1024). */\n    maxSubscriptions?: number;\n    /** SSE comment-frame keepalive interval; `0` disables keepalive (default 15000). */\n    keepAliveMs?: number;\n    /** Out-of-band error reporting (never alters the response). */\n    onerror?: (error: Error) => void;\n}\n\n/**\n * A wire-shape notification body (method + loose params).\n * @internal\n */\nexport interface NotificationBody {\n    method: string;\n    params: { _meta?: Record<string, unknown>; [key: string]: unknown };\n}\n\nfunction jsonRpcError(id: RequestId | null, code: number, message: string): Response {\n    return Response.json({ jsonrpc: '2.0', error: { code, message }, id }, { status: 200 });\n}\n\n/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */\nfunction stampSubscriptionId(\n    notification: { method: string; params?: { _meta?: Record<string, unknown>; [key: string]: unknown } },\n    subscriptionId: RequestId\n): NotificationBody {\n    return {\n        method: notification.method,\n        params: {\n            ...notification.params,\n            _meta: { ...notification.params?._meta, [SUBSCRIPTION_ID_META_KEY]: subscriptionId }\n        }\n    };\n}\n\n/**\n * Read the requested filter off a `subscriptions/listen` request body.\n * Returns the validated filter, or `undefined` when `params.notifications`\n * is absent or fails the schema (the caller answers `-32602` — the spec\n * marks `notifications` REQUIRED on the listen request).\n */\nexport function parseListenFilter(message: JSONRPCRequest): SubscriptionFilter | undefined {\n    // `subscriptions/listen` is 2026-only vocabulary; route through the era\n    // codec's request validator (the wire layer owns the filter schema).\n    const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest('subscriptions/listen', message);\n    return outcome.ok ? outcome.value.params?.notifications : undefined;\n}\n\n/**\n * The HTTP listen router: holds the set of open subscriptions and serves\n * each listen request as an SSE response.\n */\nexport interface ListenRouter {\n    /**\n     * Serve one `subscriptions/listen` request and return the SSE `Response`\n     * (or, on capacity / params rejection, the in-band JSON-RPC error\n     * `Response`). The ack notification is the first SSE frame.\n     *\n     * `capabilities` is required: the acknowledged filter is always narrowed\n     * against what the serving instance advertises (honoring a filter without\n     * capabilities would fail open and deliver unadvertised types).\n     * `serverInfo` is the serving instance's identity, stamped onto the\n     * graceful-close result's `_meta` (the spec's `SubscriptionsListenResultMetaObject`\n     * extends `ResultMetaObject`, so the serverInfo SHOULD applies there too).\n     */\n    serve(message: JSONRPCRequest, signal: AbortSignal | undefined, capabilities: ServerCapabilities, serverInfo: Implementation): Response;\n    /**\n     * Gracefully close every open subscription stream: emits the empty\n     * `subscriptions/listen` JSON-RPC result (the spec's graceful-close\n     * signal) as the final SSE frame, then closes the stream.\n     */\n    closeAll(): void;\n    /** The number of currently open subscription streams (for tests / introspection). */\n    readonly openCount: number;\n}\n\nexport function createListenRouter(options: ListenRouterOptions): ListenRouter {\n    const { bus, onerror } = options;\n    const maxSubscriptions = options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS;\n    const keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS;\n\n    const open = new Set<(graceful: boolean) => void>();\n\n    function serve(\n        message: JSONRPCRequest,\n        signal: AbortSignal | undefined,\n        capabilities: ServerCapabilities,\n        serverInfo: Implementation\n    ): Response {\n        // Capacity guard, pre-ack: in-band -32603 on HTTP 200.\n        if (open.size >= maxSubscriptions) {\n            onerror?.(new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`));\n            return jsonRpcError(message.id, -32_603, 'Subscription limit reached');\n        }\n        const filter = parseListenFilter(message);\n        if (filter === undefined) {\n            return jsonRpcError(message.id, -32_602, \"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter\");\n        }\n        const honored = honoredSubset(filter, capabilities);\n        // The spec carries the listen request's JSON-RPC id verbatim as the\n        // subscription id; demux is per-connection (each HTTP listen has its\n        // own SSE stream) so client-chosen ids cannot route across requests.\n        const subscriptionId = message.id;\n\n        const encoder = new TextEncoder();\n        let controller!: ReadableStreamDefaultController<Uint8Array>;\n        let closed = false;\n        let unsubscribe: (() => void) | undefined;\n        let keepAliveTimer: ReturnType<typeof setInterval> | undefined;\n        let abortCleanup: (() => void) | undefined;\n\n        const writeFrame = (frame: string) => {\n            if (closed) return;\n            try {\n                controller.enqueue(encoder.encode(frame));\n            } catch (error) {\n                onerror?.(error instanceof Error ? error : new Error(String(error)));\n            }\n        };\n        const writeNotification = (method: string, params: { _meta?: Record<string, unknown>; [key: string]: unknown }) => {\n            writeFrame(`event: message\\ndata: ${JSON.stringify({ jsonrpc: '2.0', method, params })}\\n\\n`);\n        };\n\n        const teardown = (graceful: boolean) => {\n            if (closed) return;\n            if (graceful) {\n                // Server-side graceful close: emit the empty\n                // `subscriptions/listen` JSON-RPC result before closing the\n                // stream so the client distinguishes graceful end from a\n                // transport drop. Written before `closed = true` so writeFrame\n                // still enqueues.\n                writeFrame(\n                    `event: message\\ndata: ${JSON.stringify({\n                        jsonrpc: '2.0',\n                        id: subscriptionId,\n                        result: {\n                            resultType: 'complete',\n                            _meta: { [SUBSCRIPTION_ID_META_KEY]: subscriptionId, [SERVER_INFO_META_KEY]: serverInfo }\n                        }\n                    })}\\n\\n`\n                );\n            }\n            closed = true;\n            try {\n                unsubscribe?.();\n            } catch (error) {\n                onerror?.(error instanceof Error ? error : new Error(String(error)));\n            }\n            if (keepAliveTimer !== undefined) clearInterval(keepAliveTimer);\n            abortCleanup?.();\n            open.delete(teardown);\n            try {\n                controller.close();\n            } catch {\n                // Already closed/cancelled by the consumer.\n            }\n        };\n\n        const readable = new ReadableStream<Uint8Array>({\n            start(streamController) {\n                controller = streamController;\n\n                // Ack-first MUST: the acknowledged notification is the first\n                // frame on the stream, stamped with the subscription id.\n                const ack = stampSubscriptionId(\n                    { method: 'notifications/subscriptions/acknowledged', params: { notifications: honored } },\n                    subscriptionId\n                );\n                writeNotification(ack.method, ack.params);\n\n                // Nothing honored means nothing can ever be delivered: complete the subscription instead of holding the stream.\n                if (Object.keys(honored).length === 0) {\n                    teardown(true);\n                    return;\n                }\n\n                // Only after the ack frame is enqueued does delivery activate.\n                unsubscribe = bus.subscribe(event => {\n                    if (closed || !listenFilterAccepts(honored, event)) return;\n                    const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId);\n                    writeNotification(note.method, note.params);\n                });\n\n                keepAliveTimer = armSseKeepAlive(keepAliveMs, () => writeFrame(': keepalive\\n\\n'));\n\n                open.add(teardown);\n            },\n            cancel() {\n                // The client closed the SSE stream — the spec's HTTP cancel\n                // signal. Not a server-side graceful close, so no listen\n                // result is written (and the consumer is gone anyway).\n                teardown(false);\n            }\n        });\n\n        if (signal !== undefined) {\n            if (signal.aborted) {\n                teardown(false);\n            } else {\n                const onAbort = () => teardown(false);\n                signal.addEventListener('abort', onAbort, { once: true });\n                abortCleanup = () => signal.removeEventListener('abort', onAbort);\n            }\n        }\n\n        return new Response(readable, {\n            status: 200,\n            headers: {\n                'Content-Type': 'text/event-stream',\n                'Cache-Control': 'no-cache, no-transform',\n                Connection: 'keep-alive',\n                'X-Accel-Buffering': 'no'\n            }\n        });\n    }\n\n    return {\n        serve,\n        closeAll() {\n            for (const teardown of open) teardown(true);\n        },\n        get openCount() {\n            return open.size;\n        }\n    };\n}\n\n/* ------------------------------------------------------------------------ *\n * Stdio listen router\n * ------------------------------------------------------------------------ */\n\n/** A graceful-close `subscriptions/listen` result frame emitted by {@linkcode StdioListenRouter.teardownAll}. */\nexport interface ListenCloseFrame {\n    jsonrpc: '2.0';\n    id: RequestId;\n    result: {\n        resultType: 'complete';\n        _meta: { [SUBSCRIPTION_ID_META_KEY]: RequestId; [SERVER_INFO_META_KEY]?: Implementation };\n    };\n}\n\nconst CHANGE_NOTIFICATION_METHODS: ReadonlySet<string> = new Set([\n    'notifications/tools/list_changed',\n    'notifications/prompts/list_changed',\n    'notifications/resources/list_changed',\n    'notifications/resources/updated'\n]);\n\n/**\n * Per-connection listen state for the stdio entry. One instance is held by\n * `serveStdio` for the connection lifetime; it routes inbound\n * `subscriptions/listen` / `notifications/cancelled` and rewrites outbound\n * change notifications onto the active subscriptions. No bus — the long-lived\n * pinned instance's existing `send*ListChanged()` calls feed straight into\n * `routeOutbound()`.\n */\nexport class StdioListenRouter {\n    /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */\n    private readonly _subs = new Map<RequestId, SubscriptionFilter>();\n    /**\n     * The serving instance's declared capabilities. Filled in by the entry\n     * once the modern instance is constructed (the router is created before\n     * the instance exists), so the acknowledged filter is narrowed against\n     * what the server can actually deliver.\n     */\n    private _serverCapabilities: ServerCapabilities | undefined;\n    /**\n     * The serving instance's identity, stamped onto the graceful-close\n     * results' `_meta` (the spec's `SubscriptionsListenResultMetaObject` extends\n     * `ResultMetaObject`). Handed over together with the capabilities.\n     */\n    private _serverInfo: Implementation | undefined;\n\n    constructor(\n        private readonly _maxSubscriptions: number = DEFAULT_MAX_SUBSCRIPTIONS,\n        serverCapabilities?: ServerCapabilities,\n        serverInfo?: Implementation\n    ) {\n        this._serverCapabilities = serverCapabilities;\n        this._serverInfo = serverInfo;\n    }\n\n    /**\n     * Record the serving instance's declared capabilities and identity once\n     * it has been constructed. Called by `serveStdio`'s connect path;\n     * subsequent `serve()` calls narrow the honored filter against the\n     * capabilities, and `teardownAll()` stamps the identity.\n     */\n    setServerCapabilities(capabilities: ServerCapabilities, serverInfo?: Implementation): void {\n        this._serverCapabilities = capabilities;\n        if (serverInfo !== undefined) this._serverInfo = serverInfo;\n    }\n\n    /** Whether `id` is an active listen subscription on this connection. */\n    has(id: RequestId): boolean {\n        return this._subs.has(id);\n    }\n\n    /**\n     * Serve one inbound `subscriptions/listen` request: registers the\n     * subscription and returns the stamped acknowledged notification (or, on\n     * capacity / params rejection, the in-band JSON-RPC error response).\n     *\n     * @throws when called before {@linkcode setServerCapabilities} (or the\n     * constructor) has supplied the serving instance's capabilities. Honoring a\n     * filter without knowing the server's advertised capabilities would fail\n     * open (deliver unadvertised types); the entry guarantees capabilities are\n     * set before any listen request is routed here.\n     */\n    serve(message: JSONRPCRequest): NotificationBody | { jsonrpc: '2.0'; id: RequestId; error: { code: number; message: string } } {\n        if (this._serverCapabilities === undefined) {\n            throw new Error(\n                'StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities'\n            );\n        }\n        if (this._subs.size >= this._maxSubscriptions) {\n            return { jsonrpc: '2.0', id: message.id, error: { code: -32_603, message: 'Subscription limit reached' } };\n        }\n        const filter = parseListenFilter(message);\n        if (filter === undefined) {\n            return {\n                jsonrpc: '2.0',\n                id: message.id,\n                error: { code: -32_602, message: \"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter\" }\n            };\n        }\n        const honored = honoredSubset(filter, this._serverCapabilities);\n        this._subs.set(message.id, honored);\n        return stampSubscriptionId({ method: 'notifications/subscriptions/acknowledged', params: { notifications: honored } }, message.id);\n    }\n\n    /**\n     * Tear down one subscription (inbound `notifications/cancelled`). Returns\n     * `true` when a subscription was removed. After this call NOTHING further\n     * is delivered for that subscription id (the post-cancel hardening).\n     */\n    cancel(id: RequestId): boolean {\n        return this._subs.delete(id);\n    }\n\n    /**\n     * Route an outbound notification through the active subscriptions.\n     *\n     * - For a subscription-gated change notification, returns one stamped copy\n     *   per subscription that opted in to it (an empty array means it is\n     *   dropped — the modern era never delivers an un-requested change type).\n     * - For any other outbound message, returns `'passthrough'` (the entry\n     *   forwards it as-is).\n     */\n    routeOutbound(message: { method: string; params?: { [key: string]: unknown } }): NotificationBody[] | 'passthrough' {\n        if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) {\n            return 'passthrough';\n        }\n        const uriParam: unknown = message.params?.['uri'];\n        const uri = typeof uriParam === 'string' ? uriParam : undefined;\n        const event = notificationToServerEvent(message.method, uri);\n        const out: NotificationBody[] = [];\n        for (const [subscriptionId, filter] of this._subs) {\n            if (listenFilterAccepts(filter, event)) {\n                out.push(stampSubscriptionId({ method: message.method, params: message.params ?? {} }, subscriptionId));\n            }\n        }\n        return out;\n    }\n\n    /**\n     * Server-side graceful teardown of every active subscription: returns the\n     * empty `subscriptions/listen` JSON-RPC result for each subscription id —\n     * the spec's graceful-close signal, `_meta` carrying the subscription id\n     * and the serving instance's identity — for the entry to emit before\n     * closing the wire. Clears the set so nothing further is delivered.\n     */\n    teardownAll(): ListenCloseFrame[] {\n        const out: ListenCloseFrame[] = [];\n        for (const id of this._subs.keys()) {\n            out.push({\n                jsonrpc: '2.0',\n                id,\n                result: {\n                    resultType: 'complete',\n                    _meta: {\n                        [SUBSCRIPTION_ID_META_KEY]: id,\n                        ...(this._serverInfo !== undefined && { [SERVER_INFO_META_KEY]: this._serverInfo })\n                    }\n                }\n            });\n        }\n        this._subs.clear();\n        return out;\n    }\n}\n\nfunction notificationToServerEvent(method: string, uri: string | undefined): import('./serverEventBus').ServerEvent {\n    switch (method) {\n        case 'notifications/tools/list_changed': {\n            return { kind: 'tools_list_changed' };\n        }\n        case 'notifications/prompts/list_changed': {\n            return { kind: 'prompts_list_changed' };\n        }\n        case 'notifications/resources/list_changed': {\n            return { kind: 'resources_list_changed' };\n        }\n        default: {\n            return { kind: 'resource_updated', uri: uri ?? '' };\n        }\n    }\n}\n","import type { AuthInfo } from '@modelcontextprotocol/core-internal';\nimport { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/core-internal';\n\n/**\n * Minimal token-verifier interface for MCP servers acting as an OAuth 2.0\n * Resource Server. Implementations introspect or locally validate an access\n * token and return the resulting {@link AuthInfo}, which the serving entry\n * surfaces to MCP request handlers via `ctx.http.authInfo`.\n *\n * This is intentionally narrower than a full OAuth Authorization Server\n * provider — it only covers the verification step a Resource Server needs.\n */\nexport interface OAuthTokenVerifier {\n    /**\n     * Verifies an access token and returns information about it.\n     *\n     * Implementations should throw an {@link OAuthError} with\n     * `OAuthErrorCode.InvalidToken` when the token is unknown, revoked, or\n     * otherwise invalid; the bearer-auth helpers map that to a `401` with a\n     * `WWW-Authenticate` challenge.\n     *\n     * Note: bearer-auth verification rejects tokens whose\n     * `AuthInfo.expiresAt` is unset (matches v1 behavior). Ensure your\n     * verifier populates it (e.g. from RFC 7662 introspection `exp` or the\n     * JWT `exp` claim).\n     */\n    verifyAccessToken(token: string): Promise<AuthInfo>;\n}\n\n/**\n * Options for {@link verifyBearerToken}, {@link requireBearerAuth}, and\n * {@link bearerAuthChallengeResponse}.\n */\nexport interface BearerAuthOptions {\n    /**\n     * A verifier used to validate access tokens.\n     */\n    verifier: OAuthTokenVerifier;\n\n    /**\n     * Optional scopes that the token must have. When any are missing the\n     * request is refused with `403 insufficient_scope`.\n     */\n    requiredScopes?: string[];\n\n    /**\n     * Optional Protected Resource Metadata URL to advertise in the\n     * `WWW-Authenticate` header on 401/403 responses, per\n     * {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728}.\n     *\n     * Typically built with `getOAuthProtectedResourceMetadataUrl`, exported\n     * from this package.\n     *\n     * When verification succeeds the value is also stamped onto the returned\n     * {@link AuthInfo} (`authInfo.resourceMetadataUrl`, unless the verifier\n     * already set one), so challenges built after authentication — such as\n     * per-operation `insufficient_scope` scope challenges — advertise the\n     * same document without being configured separately.\n     */\n    resourceMetadataUrl?: string;\n}\n\n/**\n * Options for {@link verifyBearerToken} and {@link requireBearerAuth}:\n * {@link BearerAuthOptions} plus `expectedResource`.\n */\nexport interface VerifyBearerTokenOptions extends BearerAuthOptions {\n    /**\n     * Accept only tokens issued for this resource (the token's audience):\n     * the value your authorization server puts into tokens meant for this\n     * server, usually the server's URL (its\n     * {@link https://datatracker.ietf.org/doc/html/rfc8707 | RFC 8707}\n     * resource identifier).\n     *\n     * When set, a token is accepted only if the verifier reports that value\n     * in `AuthInfo.resource`. The two are compared as strings, ignoring a\n     * fragment and one trailing slash. A token reported for another value, or\n     * for none, is refused with `401 invalid_token`, so the verifier has to\n     * fill `AuthInfo.resource`, for example from the token's `aud` claim.\n     * When unset, `AuthInfo.resource` is not compared with anything.\n     */\n    expectedResource?: URL;\n}\n\n// The serialized value without its fragment and without one trailing slash.\nfunction comparableResource(value: URL): string {\n    const text = String(value);\n    const hash = text.indexOf('#');\n    return (hash === -1 ? text : text.slice(0, hash)).replace(/\\/$/, '');\n}\n\n// A reported resource matches when it serializes to the same string as the expected one, fragment and one trailing slash aside.\nfunction sameResource(reported: URL | undefined, expected: URL): boolean {\n    if (!reported) return false;\n    return comparableResource(reported) === comparableResource(expected);\n}\n\nfunction headerQuotedValue(value: string): string {\n    // HTTP quoted-string per RFC 7235: escape backslash and double quote, and\n    // replace characters a header cannot carry (controls, anything beyond\n    // printable ASCII) so a verifier-authored message can never make the\n    // challenge Response constructor throw.\n    return value.replaceAll(/[\\\\\"]/g, String.raw`\\$&`).replaceAll(/[^\\u0020-\\u007E]/g, ' ');\n}\n\n/**\n * Build a `WWW-Authenticate: Bearer …` challenge header value (RFC 6750).\n *\n * The single formatter behind every challenge this package emits — the\n * bearer-auth 401/403 answers and the per-operation scope-challenge 403 — so\n * all challenges from one server agree on parameter order and quoting. Every\n * parameter value is emitted as an HTTP quoted-string with `\\` and `\"`\n * escaped and non-printable characters replaced.\n */\nexport function buildWwwAuthenticateHeader(\n    errorCode: string,\n    description: string,\n    requiredScopes: readonly string[],\n    resourceMetadataUrl: string | undefined\n): string {\n    let header = `Bearer error=\"${headerQuotedValue(errorCode)}\", error_description=\"${headerQuotedValue(description)}\"`;\n    if (requiredScopes.length > 0) {\n        header += `, scope=\"${headerQuotedValue(requiredScopes.join(' '))}\"`;\n    }\n    if (resourceMetadataUrl) {\n        header += `, resource_metadata=\"${headerQuotedValue(resourceMetadataUrl)}\"`;\n    }\n    return header;\n}\n\n/**\n * Validate a raw `Authorization` header value as a Bearer token and return\n * the verified {@link AuthInfo}.\n *\n * The runtime-neutral core of Bearer authentication: it parses the header,\n * runs the verifier, compares the token's resource with `expectedResource`,\n * enforces `requiredScopes`, and rejects tokens without an\n * expiration or past it. On any failure it throws an {@link OAuthError} —\n * pass that to {@link bearerAuthChallengeResponse} for the matching HTTP\n * answer, or use {@link requireBearerAuth} to get both steps as one call.\n *\n * Framework adapters build on this: `requireBearerAuth` from\n * `@modelcontextprotocol/express` feeds it `req.headers.authorization`.\n */\nexport async function verifyBearerToken(\n    authorizationHeader: string | null | undefined,\n    options: VerifyBearerTokenOptions\n): Promise<AuthInfo> {\n    const { verifier, requiredScopes = [], expectedResource } = options;\n\n    if (!authorizationHeader) {\n        throw new OAuthError(OAuthErrorCode.InvalidToken, 'Missing Authorization header');\n    }\n\n    const [type, token] = authorizationHeader.split(' ');\n    if (type?.toLowerCase() !== 'bearer' || !token) {\n        throw new OAuthError(OAuthErrorCode.InvalidToken, \"Invalid Authorization header format, expected 'Bearer TOKEN'\");\n    }\n\n    const authInfo = await verifier.verifyAccessToken(token);\n\n    // Check if the token was issued for this server (if configured)\n    if (expectedResource !== undefined && !sameResource(authInfo.resource, expectedResource)) {\n        throw new OAuthError(OAuthErrorCode.InvalidToken, 'Token was not issued for this resource');\n    }\n\n    // Check if token has the required scopes (if any)\n    if (requiredScopes.length > 0) {\n        const hasAllScopes = requiredScopes.every(scope => authInfo.scopes.includes(scope));\n        if (!hasAllScopes) {\n            throw new OAuthError(OAuthErrorCode.InsufficientScope, 'Insufficient scope');\n        }\n    }\n\n    // Check if the token is set to expire or if it is expired\n    if (typeof authInfo.expiresAt !== 'number' || Number.isNaN(authInfo.expiresAt)) {\n        throw new OAuthError(OAuthErrorCode.InvalidToken, 'Token has no expiration time');\n    } else if (authInfo.expiresAt < Date.now() / 1000) {\n        throw new OAuthError(OAuthErrorCode.InvalidToken, 'Token has expired');\n    }\n\n    // Hand the gate's discovery configuration inward with the verified token,\n    // so challenges built after authentication (per-operation scope\n    // challenges) advertise the same metadata document. A verifier-set value\n    // wins over the gate's configuration.\n    if (options.resourceMetadataUrl !== undefined && authInfo.resourceMetadataUrl === undefined) {\n        return { ...authInfo, resourceMetadataUrl: options.resourceMetadataUrl };\n    }\n\n    return authInfo;\n}\n\n/**\n * Build the HTTP answer for a Bearer authentication failure.\n *\n * Maps an {@link OAuthError} to its status — `401` for `invalid_token` and\n * `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …`\n * challenge, with `resource_metadata` when configured so clients can discover\n * the Authorization Server), `500` for `server_error`, `400` for anything\n * else. A non-`OAuthError` value answers `500 server_error`. The body is the\n * OAuth error JSON.\n */\nexport function bearerAuthChallengeResponse(\n    error: unknown,\n    options?: Pick<BearerAuthOptions, 'requiredScopes' | 'resourceMetadataUrl'>\n): Response {\n    const { requiredScopes = [], resourceMetadataUrl } = options ?? {};\n\n    if (!(error instanceof OAuthError)) {\n        const serverError = new OAuthError(OAuthErrorCode.ServerError, 'Internal Server Error');\n        return Response.json(serverError.toResponseObject(), { status: 500 });\n    }\n\n    switch (error.code) {\n        case OAuthErrorCode.InvalidToken: {\n            const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl);\n            return Response.json(error.toResponseObject(), { status: 401, headers: { 'WWW-Authenticate': challenge } });\n        }\n        case OAuthErrorCode.InsufficientScope: {\n            const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl);\n            return Response.json(error.toResponseObject(), { status: 403, headers: { 'WWW-Authenticate': challenge } });\n        }\n        case OAuthErrorCode.ServerError: {\n            return Response.json(error.toResponseObject(), { status: 500 });\n        }\n        default: {\n            return Response.json(error.toResponseObject(), { status: 400 });\n        }\n    }\n}\n\n/**\n * Require a valid Bearer token on web-standard requests.\n *\n * The framework-free counterpart of `requireBearerAuth` from\n * `@modelcontextprotocol/express`, for hosts whose HTTP surface is a\n * `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The\n * returned gate resolves to the verified {@link AuthInfo}, or to the\n * ready-to-return challenge `Response` when the request must be refused.\n *\n * @example\n * ```ts source=\"./bearerAuth.examples.ts#requireBearerAuth_fetchGate\"\n * const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] });\n *\n * async function fetchHandler(request: Request): Promise<Response> {\n *     const auth: AuthInfo | Response = await gate(request);\n *     if (auth instanceof Response) return auth;\n *     return handler.fetch(request, { authInfo: auth });\n * }\n * ```\n */\nexport function requireBearerAuth(options: VerifyBearerTokenOptions): (request: Request) => Promise<AuthInfo | Response> {\n    // Destructure at creation so a plain-JS caller passing undefined or\n    // malformed options crashes at startup, not on the first request.\n    const { verifier, requiredScopes = [], resourceMetadataUrl, expectedResource } = options;\n    const resolved = { verifier, requiredScopes, resourceMetadataUrl, expectedResource };\n    return async request => {\n        // Outside the try: a wrong-framework misuse (no web-standard Request)\n        // should throw loudly, not surface as a 500 challenge. Fetch's\n        // Headers.get comma-joins repeated headers where Node keeps the\n        // first; take the first segment so both adapters agree (the token68\n        // alphabet has no comma, so this is lossless).\n        const [authorizationHeader] = (request.headers.get('authorization') ?? '').split(',');\n        try {\n            return await verifyBearerToken(authorizationHeader || undefined, resolved);\n        } catch (error) {\n            return bearerAuthChallengeResponse(error, resolved);\n        }\n    };\n}\n","import type { OAuthMetadata, OAuthProtectedResourceMetadata } from '@modelcontextprotocol/core-internal';\nimport { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/core-internal';\n\n/**\n * Options for {@link oauthMetadataResponse} and\n * {@link buildOAuthProtectedResourceMetadata}.\n */\nexport interface AuthMetadataOptions {\n    /**\n     * Authorization Server metadata (RFC 8414) for the AS this MCP server\n     * relies on. Served at `/.well-known/oauth-authorization-server` so\n     * legacy clients that probe the resource origin still discover the AS.\n     */\n    oauthMetadata: OAuthMetadata;\n\n    /**\n     * The public URL of this MCP server, used as the `resource` value in the\n     * Protected Resource Metadata document. Any path component is reflected\n     * in the well-known route per RFC 9728.\n     */\n    resourceServerUrl: URL;\n\n    /**\n     * Optional documentation URL advertised as `resource_documentation`.\n     */\n    serviceDocumentationUrl?: URL;\n\n    /**\n     * Optional list of scopes this MCP server understands, advertised as\n     * `scopes_supported`.\n     */\n    scopesSupported?: string[];\n\n    /**\n     * Optional human-readable name advertised as `resource_name`.\n     */\n    resourceName?: string;\n\n    /**\n     * Allow a non-HTTPS issuer URL. Local testing only — never enable in\n     * production. The Express adapter maps its\n     * `MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL` environment variable here.\n     */\n    dangerouslyAllowInsecureIssuerUrl?: boolean;\n}\n\nfunction checkIssuerUrl(issuer: URL, allowInsecure: boolean | undefined): void {\n    // RFC 8414 technically does not permit a localhost HTTPS exemption, but it is necessary for local testing.\n    if (issuer.protocol !== 'https:' && issuer.hostname !== 'localhost' && issuer.hostname !== '127.0.0.1' && !allowInsecure) {\n        throw new Error('Issuer URL must be HTTPS');\n    }\n    if (issuer.hash) {\n        throw new Error(`Issuer URL must not have a fragment: ${issuer}`);\n    }\n    if (issuer.search) {\n        throw new Error(`Issuer URL must not have a query string: ${issuer}`);\n    }\n}\n\n/**\n * Derive the RFC 9728 Protected Resource Metadata document from\n * {@link AuthMetadataOptions}, validating the Authorization Server issuer URL\n * (HTTPS required outside localhost) in the process.\n *\n * `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build\n * on this; use it directly when serving the document through your own\n * routing — or call it once at startup to fail fast on a misconfigured\n * issuer before any request arrives.\n */\nexport function buildOAuthProtectedResourceMetadata(options: AuthMetadataOptions): OAuthProtectedResourceMetadata {\n    checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl);\n    return {\n        resource: options.resourceServerUrl.href,\n        authorization_servers: [options.oauthMetadata.issuer],\n        scopes_supported: options.scopesSupported,\n        resource_name: options.resourceName,\n        resource_documentation: options.serviceDocumentationUrl?.href\n    };\n}\n\n/**\n * Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server\n * URL by inserting `/.well-known/oauth-protected-resource` ahead of the path.\n *\n * @example\n * ```ts\n * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp'))\n * // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp'\n * ```\n */\nexport function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): string {\n    const metadataUrl = new URL(serverUrl);\n    metadataUrl.pathname = protectedResourceMetadataPath(serverUrl);\n    metadataUrl.hash = '';\n    return metadataUrl.href;\n}\n\n/** The RFC 9728 path-aware well-known path for a resource URL. */\nfunction protectedResourceMetadataPath(resourceServerUrl: URL): string {\n    // Normalized like the request path in `oauthMetadataResponse`: a resource\n    // URL with a trailing slash must not make its own PRM route unreachable.\n    const rsPath = stripTrailingSlash(resourceServerUrl.pathname);\n    return `/.well-known/oauth-protected-resource${rsPath === '/' ? '' : rsPath}`;\n}\n\nfunction stripTrailingSlash(path: string): string {\n    return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n}\n\nconst ALLOWED_METHODS = 'GET, HEAD, OPTIONS';\n\nfunction metadataDocumentResponse(request: Request, metadata: OAuthMetadata | OAuthProtectedResourceMetadata): Response {\n    // Metadata documents must be fetchable from web-based MCP clients on any\n    // origin, so every response carries permissive CORS headers.\n    if (request.method === 'OPTIONS') {\n        const requestedHeaders = request.headers.get('access-control-request-headers');\n        return new Response(null, {\n            status: 204,\n            headers: {\n                'Access-Control-Allow-Origin': '*',\n                'Access-Control-Allow-Methods': ALLOWED_METHODS,\n                // The reflected allow-list makes the response vary by request:\n                // without this a shared cache would replay one preflight's\n                // allow-list against another's headers.\n                ...(requestedHeaders === null\n                    ? {}\n                    : { 'Access-Control-Allow-Headers': requestedHeaders, Vary: 'Access-Control-Request-Headers' })\n            }\n        });\n    }\n    if (request.method !== 'GET' && request.method !== 'HEAD') {\n        const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`);\n        return Response.json(error.toResponseObject(), {\n            status: 405,\n            headers: { Allow: ALLOWED_METHODS, 'Access-Control-Allow-Origin': '*' }\n        });\n    }\n    const response = Response.json(metadata, { headers: { 'Access-Control-Allow-Origin': '*' } });\n    // RFC 9110: HEAD is GET without the body, same headers.\n    return request.method === 'HEAD' ? new Response(null, { status: response.status, headers: response.headers }) : response;\n}\n\n/**\n * Serve the two OAuth discovery documents an MCP server acting as a Resource\n * Server exposes, from a web-standard `fetch(request)` handler:\n *\n *  - `/.well-known/oauth-protected-resource[/<path>]` — RFC 9728 Protected\n *    Resource Metadata, derived from the supplied options (path-aware: the\n *    resource URL's path is reflected in the route).\n *  - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization\n *    Server Metadata, passed through verbatim.\n *\n * Returns the matched document `Response` (JSON with permissive CORS, `405`\n * with an `Allow` header for non-GET methods, `204` for CORS preflight), or\n * `undefined` when the request path is neither well-known route — fall\n * through to your own routing. The framework-free counterpart of\n * `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with\n * `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so\n * unauthenticated clients can discover the AS from the `401` challenge.\n *\n * @example\n * ```ts source=\"./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler\"\n * async function fetchHandler(request: Request): Promise<Response> {\n *     return oauthMetadataResponse(request, options) ?? serveMcp(request);\n * }\n * ```\n */\nexport function oauthMetadataResponse(request: Request, options: AuthMetadataOptions): Response | undefined {\n    // Match before building: unmatched traffic must fall through untouched,\n    // even when the options are misconfigured — a bad issuer surfaces on the\n    // discovery routes (or at startup via buildOAuthProtectedResourceMetadata),\n    // never on the host's own traffic.\n    // Tolerate a single trailing slash, as path-mounted routers do.\n    const requestPath = stripTrailingSlash(new URL(request.url).pathname);\n    if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) {\n        return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options));\n    }\n    if (requestPath === '/.well-known/oauth-authorization-server') {\n        buildOAuthProtectedResourceMetadata(options); // issuer validation\n        return metadataDocumentResponse(request, options.oauthMetadata);\n    }\n    return undefined;\n}\n","import type { AuthInfo, JSONRPCRequest } from '@modelcontextprotocol/core-internal';\nimport { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/core-internal';\n\nimport { bearerAuthChallengeResponse } from './middleware/bearerAuth';\nimport { getOAuthProtectedResourceMetadataUrl } from './middleware/oauthMetadata';\n\n/** OAuth scopes to request before handling an MCP request. */\nexport interface ScopeChallenge {\n    /** The exact, complete scope set to include in the challenge. Each scope must satisfy the OAuth `scope-token` grammar. */\n    scopes: readonly [string, ...string[]];\n    /** Optional human-readable detail satisfying the RFC 6750 `error-description` grammar. */\n    errorDescription?: string;\n}\n\n/** Determines whether an MCP request needs an OAuth scope challenge. */\nexport type ScopeChallengeHandler = (context: {\n    request: JSONRPCRequest;\n    authInfo?: AuthInfo;\n}) => ScopeChallenge | undefined | Promise<ScopeChallenge | undefined>;\n\n/** @internal */\nexport function supportsScopeChallengeResolver(\n    transport: unknown\n): transport is { setScopeChallengeResolver(resolver: ScopeChallengeHandler): void } {\n    return (\n        typeof transport === 'object' &&\n        transport !== null &&\n        'setScopeChallengeResolver' in transport &&\n        typeof (transport as { setScopeChallengeResolver: unknown }).setScopeChallengeResolver === 'function'\n    );\n}\n\nfunction assertScope(scope: unknown, location: string): asserts scope is string {\n    if (typeof scope !== 'string' || !/^[\\u0021\\u0023-\\u005B\\u005D-\\u007E]+$/.test(scope)) {\n        throw new TypeError(`${location} must satisfy the OAuth scope-token grammar`);\n    }\n}\n\nfunction validateScopeChallenge(challenge: ScopeChallenge): ScopeChallenge {\n    if (challenge === null || typeof challenge !== 'object' || !Array.isArray(challenge.scopes) || challenge.scopes.length === 0) {\n        throw new TypeError('scope challenge must contain at least one scope');\n    }\n    for (const [index, scope] of challenge.scopes.entries()) {\n        assertScope(scope, `scope challenge scopes[${index}]`);\n    }\n    if (challenge.errorDescription !== undefined && typeof challenge.errorDescription !== 'string') {\n        throw new TypeError('scope challenge errorDescription must be a string');\n    }\n    if (challenge.errorDescription !== undefined && !/^[\\u0020-\\u0021\\u0023-\\u005B\\u005D-\\u007E]+$/.test(challenge.errorDescription)) {\n        throw new TypeError('scope challenge errorDescription must satisfy the RFC 6750 error-description grammar');\n    }\n    return challenge;\n}\n\n/**\n * Creates a handler that requires every supplied scope exactly.\n *\n * Requests without authentication are left to the server's authentication gate.\n */\nexport function requireScopes(...scopes: readonly [string, ...string[]]): ScopeChallengeHandler {\n    if (scopes.length === 0) {\n        throw new TypeError('requireScopes must contain at least one scope');\n    }\n    for (const [index, scope] of scopes.entries()) {\n        assertScope(scope, `requireScopes scope[${index}]`);\n    }\n    const requiredScopes = [...scopes] as [string, ...string[]];\n    return ({ authInfo }) => {\n        if (authInfo === undefined) return;\n        const activeScopes = new Set(authInfo.scopes);\n        if (requiredScopes.every(scope => activeScopes.has(scope))) return;\n        return { scopes: requiredScopes };\n    };\n}\n\n/** @internal */\nexport async function findScopeChallenge(\n    requests: readonly JSONRPCRequest[],\n    authInfo: AuthInfo | undefined,\n    resolve: ScopeChallengeHandler\n): Promise<ScopeChallenge | undefined> {\n    for (const request of requests) {\n        const challenge = await resolve({ request, ...(authInfo !== undefined && { authInfo }) });\n        if (challenge !== undefined) {\n            return validateScopeChallenge(challenge);\n        }\n    }\n    return undefined;\n}\n\n/**\n * The RFC 9728 Protected Resource Metadata URL to advertise on a scope\n * challenge, derived from the verified {@link AuthInfo}: the URL the\n * authentication gate stamped (`authInfo.resourceMetadataUrl`, set by the\n * bearer-auth helpers from their `resourceMetadataUrl` option), falling back\n * to the well-known location for an HTTP(S) RFC 8707 `resource` identifier, or\n * `undefined` when neither is available (the `resource_metadata` parameter is\n * then omitted, matching the bearer-auth challenges).\n *\n * @internal\n */\nexport function scopeChallengeResourceMetadataUrl(authInfo: AuthInfo | undefined): string | undefined {\n    if (authInfo?.resourceMetadataUrl !== undefined) {\n        return authInfo.resourceMetadataUrl;\n    }\n    if (authInfo?.resource?.protocol === 'https:' || authInfo?.resource?.protocol === 'http:') {\n        return getOAuthProtectedResourceMetadataUrl(authInfo.resource);\n    }\n    return undefined;\n}\n\n/** @internal */\nexport function createScopeChallengeResponse(challenge: ScopeChallenge, resourceMetadataUrl: string | undefined): Response {\n    return bearerAuthChallengeResponse(\n        new OAuthError(OAuthErrorCode.InsufficientScope, challenge.errorDescription ?? 'Insufficient scope'),\n        {\n            requiredScopes: [...challenge.scopes],\n            resourceMetadataUrl\n        }\n    );\n}\n","/**\n * The legacy `input_required` shim: serves write-once handlers on 2025-era\n * sessions. `Server` holds one instance and delegates to it from the\n * multi-round-trip seam when a handler returns an input-required result on a\n * 2025-era request: each embedded request goes out as a real server→client\n * request (`elicitation/create` / `sampling/createMessage` / `roots/list`,\n * stamped with the originating request id for stream association), and the\n * handler is re-entered with the collected `inputResponses` until it returns\n * a final result or the round cap is exhausted.\n *\n * Semantics mirror the modern client driver so a handler cannot tell which\n * era fulfilled it: per-round REPLACED `inputResponses`, byte-exact\n * `requestState` echo (re-verified by the configured hook each round), paced\n * requestState-only rounds. The loop lives inside the originating request's\n * lifetime — nothing is parked, cancellation chains through every leg.\n * Failures surface per family: tools/call → `isError` tool results,\n * prompts/resources → JSON-RPC errors; malformed results fail loudly as\n * server bugs. Package-internal — not exported from the index.\n */\nimport type {\n    ClientCapabilities,\n    CreateMessageRequest,\n    ElicitRequestFormParams,\n    ElicitRequestURLParams,\n    JSONRPCRequest,\n    RequestOptions,\n    Result,\n    ServerContext\n} from '@modelcontextprotocol/core-internal';\nimport {\n    inputRequiredRoundsExceededMessage,\n    isInputRequiredResult,\n    linkedRoundAbort,\n    missingClientCapabilities,\n    ProtocolError,\n    ProtocolErrorCode,\n    REQUEST_STATE_ONLY_LEG_PACING_MS,\n    requestStateAccessor,\n    requiredClientCapabilitiesForInputRequest,\n    sleep,\n    withRequestStateValue\n} from '@modelcontextprotocol/core-internal';\n\n/**\n * Default handler re-entries per originating request — tighter than the\n * client driver's 10 because the shim holds a live wire request open.\n */\nconst DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8;\n\n/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */\nconst DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 600_000;\n\n/** The `ServerOptions.inputRequired` bag with defaults applied. */\nexport interface ResolvedLegacyShimOptions {\n    maxRounds: number;\n    roundTimeoutMs: number;\n    legacyShim: boolean;\n}\n\n/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */\nexport function resolveLegacyShimOptions(\n    options: { maxRounds?: number; roundTimeoutMs?: number; legacyShim?: boolean } | undefined\n): ResolvedLegacyShimOptions {\n    if (options?.maxRounds !== undefined && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) {\n        throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`);\n    }\n    if (options?.roundTimeoutMs !== undefined && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) {\n        throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`);\n    }\n    return {\n        maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS,\n        roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS,\n        legacyShim: options?.legacyShim ?? true\n    };\n}\n\n/** The embedded input-request kinds the 2026-07-28 revision defines. */\nexport type EmbeddedInputRequestMethod = 'elicitation/create' | 'sampling/createMessage' | 'roots/list';\n\n/** A coerced `inputRequests` entry: the kind-narrowed embedded request. */\nexport interface CoercedEmbeddedInputRequest {\n    method: EmbeddedInputRequestMethod;\n    params?: Record<string, unknown>;\n}\n\n/**\n * Validates one `inputRequests` entry: malformed or unknown kinds are server\n * bugs and fail loudly on both eras. Shared by the modern seam's capability\n * check and the shim's gate.\n */\nexport function coerceEmbeddedInputRequest(\n    method: string,\n    key: string,\n    entry: unknown\n): { embedded: CoercedEmbeddedInputRequest; required: ClientCapabilities } {\n    if (entry === null || typeof entry !== 'object' || typeof (entry as { method?: unknown }).method !== 'string') {\n        throw new ProtocolError(\n            ProtocolErrorCode.InternalError,\n            `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an ` +\n                `embedded elicitation/create, sampling/createMessage, or roots/list request`\n        );\n    }\n    const embedded = entry as { method: string; params?: Record<string, unknown> };\n    const required = requiredClientCapabilitiesForInputRequest(embedded);\n    if (required === undefined) {\n        throw new ProtocolError(\n            ProtocolErrorCode.InternalError,\n            `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an ` +\n                `embedded request the 2026-07-28 revision defines`\n        );\n    }\n    return { embedded: embedded as CoercedEmbeddedInputRequest, required };\n}\n\n/**\n * The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026\n * in-band shape has none, so URL legs mint one (CSPRNG-backed, with a\n * getRandomValues fallback for runtimes without `randomUUID`).\n */\nfunction syntheticElicitationId(): string {\n    const webCrypto = globalThis.crypto;\n    if (webCrypto?.randomUUID !== undefined) {\n        return webCrypto.randomUUID();\n    }\n    const bytes = new Uint8Array(16);\n    webCrypto.getRandomValues(bytes);\n    bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n    bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n    const hex = [...bytes].map(byte => byte.toString(16).padStart(2, '0')).join('');\n    return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */\nfunction legacyShimFailure(method: string, message: string): Result {\n    if (method === 'tools/call') {\n        return { content: [{ type: 'text', text: message }], isError: true };\n    }\n    throw new ProtocolError(ProtocolErrorCode.InternalError, message);\n}\n\n/**\n * Everything the shim needs from `Server`: the knobs, the per-request\n * resolved capability view (initialize state on sessionful legacy; empty on\n * per-request stateless instances), the requestState verify runner\n * (deny-on-error → the frozen `-32602`), and the 2025-era senders. The\n * shim's own gate is authoritative; elicitation accepted content passes\n * through UNVALIDATED for parity with the modern client driver.\n */\nexport interface LegacyInputRequiredShimHost {\n    readonly maxRounds: number;\n    readonly roundTimeoutMs: number;\n    resolvedClientCapabilities(ctx: ServerContext): ClientCapabilities | undefined;\n    verifyRequestState(state: string, ctx: ServerContext, method: string): Promise<unknown>;\n    sendElicitation(params: ElicitRequestFormParams | ElicitRequestURLParams, options: RequestOptions): Promise<unknown>;\n    sendSampling(params: CreateMessageRequest['params'], options: RequestOptions): Promise<unknown>;\n    listRoots(params: Record<string, unknown> | undefined, options: RequestOptions): Promise<unknown>;\n}\n\n/** The fulfilment loop — see the module doc for the contract. */\nexport class LegacyInputRequiredShim {\n    constructor(private readonly _host: LegacyInputRequiredShimHost) {}\n\n    async fulfill(\n        method: string,\n        handler: (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result>,\n        request: JSONRPCRequest,\n        ctx: ServerContext,\n        firstResult: Result\n    ): Promise<Result> {\n        const { maxRounds, roundTimeoutMs } = this._host;\n        const outerSignal = ctx.mcpReq.signal;\n        let current = firstResult;\n        let round = 0;\n\n        // eslint-disable-next-line no-constant-condition\n        while (true) {\n            round += 1;\n            if (round > maxRounds) {\n                return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds));\n            }\n\n            // At-least-one re-check per round (server bug → loud, as on modern).\n            const inputRequests = current.inputRequests as Record<string, unknown> | null | undefined;\n            const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0;\n            const requestState = typeof current.requestState === 'string' ? current.requestState : undefined;\n            if (!hasInputRequests && requestState === undefined) {\n                throw new ProtocolError(\n                    ProtocolErrorCode.InternalError,\n                    `Handler for ${method} returned an input-required result with neither inputRequests nor requestState ` +\n                        `(every InputRequiredResult must include at least one of the two)`\n                );\n            }\n\n            let responses: Record<string, unknown> | undefined;\n            if (hasInputRequests) {\n                // The shim's own capability pre-check (never gated on\n                // enforceStrictCapabilities). The whole round gates before\n                // any wire traffic, so a refusal has no side effects.\n                const declared = this._host.resolvedClientCapabilities(ctx);\n                const coerced: [string, CoercedEmbeddedInputRequest][] = [];\n                for (const [key, entry] of Object.entries(inputRequests!)) {\n                    const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry);\n                    // Request-carrying kinds need params; absent = server bug.\n                    if (embedded.method !== 'roots/list' && embedded.params === undefined) {\n                        throw new ProtocolError(\n                            ProtocolErrorCode.InternalError,\n                            `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`\n                        );\n                    }\n                    const missing = missingClientCapabilities(required, declared);\n                    if (missing !== undefined) {\n                        return legacyShimFailure(\n                            method,\n                            `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not ` +\n                                `declare the required capability${declared === undefined ? ' (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)' : ''}`\n                        );\n                    }\n                    coerced.push([key, embedded]);\n                }\n\n                // Fulfil concurrently (driver parity); first failure aborts siblings.\n                const roundAbort = linkedRoundAbort(outerSignal);\n                try {\n                    const legOptions: RequestOptions = {\n                        relatedRequestId: ctx.mcpReq.id,\n                        timeout: roundTimeoutMs,\n                        resetTimeoutOnProgress: true,\n                        // The no-op handler stamps a progressToken on the leg —\n                        // without one, resetTimeoutOnProgress could never fire.\n                        onprogress: () => {},\n                        signal: roundAbort.signal\n                    };\n                    const fulfilled = await Promise.all(\n                        coerced.map(async ([key, embedded]) => {\n                            try {\n                                return [key, await this._dispatchLeg(embedded, legOptions)] as const;\n                            } catch (error) {\n                                roundAbort.abort(error);\n                                throw error;\n                            }\n                        })\n                    );\n                    responses = Object.fromEntries(fulfilled);\n                } catch (error) {\n                    if (outerSignal.aborted) {\n                        // Cancelled requests are never answered — propagate.\n                        throw error;\n                    }\n                    return legacyShimFailure(\n                        method,\n                        `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`\n                    );\n                } finally {\n                    roundAbort.dispose();\n                }\n            } else {\n                // requestState-only round: paced so the loop never hot-spins\n                // (driver parity); counted in the same round cap.\n                await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS, outerSignal);\n            }\n\n            // Byte-exact requestState echo: build the round's context first,\n            // verify against it (the order and view a modern wire retry\n            // gets), then swap in the decoded payload. Deny-on-error → -32602.\n            let ctxNext: ServerContext = {\n                ...ctx,\n                mcpReq: {\n                    ...ctx.mcpReq,\n                    // REPLACE semantics: this round's responses only — multi-step\n                    // flows thread earlier answers through requestState.\n                    inputResponses: responses,\n                    droppedInputResponseKeys: undefined,\n                    requestState: requestStateAccessor(requestState)\n                }\n            };\n            if (requestState !== undefined) {\n                const decoded = await this._host.verifyRequestState(requestState, ctxNext, method);\n                if (decoded !== undefined) {\n                    ctxNext = withRequestStateValue(ctxNext, decoded);\n                }\n            }\n\n            // Re-entry hits the same stored handler a wire retry would\n            // (for McpServer: the full funnel).\n            const next = await handler(request, ctxNext);\n            if (!isInputRequiredResult(next)) {\n                return next;\n            }\n            current = next;\n        }\n    }\n\n    /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */\n    private async _dispatchLeg(embedded: CoercedEmbeddedInputRequest, options: RequestOptions): Promise<unknown> {\n        switch (embedded.method) {\n            case 'elicitation/create': {\n                let params = embedded.params as ElicitRequestFormParams | ElicitRequestURLParams;\n                if (params.mode === 'url' && (params as ElicitRequestURLParams).elicitationId === undefined) {\n                    params = { ...(params as ElicitRequestURLParams), elicitationId: syntheticElicitationId() };\n                }\n                return await this._host.sendElicitation(params, options);\n            }\n            case 'sampling/createMessage': {\n                return await this._host.sendSampling(embedded.params as CreateMessageRequest['params'], options);\n            }\n            case 'roots/list': {\n                return await this._host.listRoots(embedded.params, options);\n            }\n        }\n    }\n}\n","import type {\n    BaseContext,\n    CacheableResultMethod,\n    CacheHint,\n    CallToolResult,\n    ClientCapabilities,\n    CreateMessageRequest,\n    CreateMessageRequestParamsBase,\n    CreateMessageRequestParamsWithTools,\n    CreateMessageResult,\n    CreateMessageResultWithTools,\n    DiscoverResult,\n    ElicitRequestFormParams,\n    ElicitRequestURLParams,\n    ElicitResult,\n    EmptyResult,\n    Implementation,\n    InitializeRequest,\n    InitializeResult,\n    JSONRPCRequest,\n    JsonSchemaType,\n    jsonSchemaValidator,\n    ListRootsRequest,\n    ListRootsResult,\n    LoggingLevel,\n    LoggingMessageNotification,\n    MessageExtraInfo,\n    NotificationMethod,\n    NotificationOptions,\n    ProtocolOptions,\n    RequestMethod,\n    RequestOptions,\n    ResourceUpdatedNotification,\n    Result,\n    ServerCapabilities,\n    ServerContext,\n    ToolResultContent,\n    ToolUseContent,\n    Transport\n} from '@modelcontextprotocol/core-internal';\nimport {\n    assertValidCacheHint,\n    attachCacheHintFallback,\n    CLIENT_CAPABILITIES_META_KEY,\n    codecForVersion,\n    isInputRequiredResult,\n    isModernProtocolVersion,\n    LATEST_PROTOCOL_VERSION,\n    legacyProtocolVersions,\n    LOG_LEVEL_META_KEY,\n    LoggingLevelSchema,\n    mergeCapabilities,\n    missingClientCapabilities,\n    MissingRequiredClientCapabilityError,\n    modernProtocolVersions,\n    normalizeContentlessToolResult,\n    parseSchema,\n    Protocol,\n    ProtocolError,\n    ProtocolErrorCode,\n    SdkError,\n    SdkErrorCode,\n    withRequestStateValue\n} from '@modelcontextprotocol/core-internal';\nimport { DefaultJsonSchemaValidator } from '@modelcontextprotocol/server/_shims';\n\nimport { coerceEmbeddedInputRequest, LegacyInputRequiredShim, resolveLegacyShimOptions } from './legacyInputRequiredShim';\n\n/**\n * The request methods whose 2026-07-28 result vocabulary includes\n * `input_required` (the multi round-trip methods). Returning an\n * input-required result from any other handler is a server bug.\n */\nconst INPUT_REQUIRED_CAPABLE_METHODS: ReadonlySet<string> = new Set(['tools/call', 'prompts/get', 'resources/read']);\n\nexport type ServerOptions = ProtocolOptions & {\n    /**\n     * Capabilities to advertise as being supported by this server.\n     *\n     * Note: per the MCP spec, a server that declares a capability MUST respond to that\n     * capability's requests (e.g. `tools/list` for `tools`) — potentially with an empty\n     * result — rather than with a \"Method not found\" error. {@linkcode server/mcp.McpServer | McpServer}\n     * handles this automatically for capabilities declared here; when using the low-level\n     * {@linkcode Server} directly, you are responsible for registering a request handler for\n     * every capability you declare.\n     */\n    capabilities?: ServerCapabilities;\n\n    /**\n     * Optional instructions describing how to use the server and its features.\n     */\n    instructions?: string;\n\n    /**\n     * JSON Schema validator for elicitation response validation.\n     *\n     * The validator is used to validate user input returned from elicitation\n     * requests against the requested schema.\n     *\n     * @default Runtime-selected validator (AJV-backed on Node.js, `@cfworker/json-schema`-backed on browser/workerd runtimes)\n     */\n    jsonSchemaValidator?: jsonSchemaValidator;\n\n    /**\n     * Cache hints for the cacheable results of the 2026-07-28 protocol\n     * revision (`ttlMs` / `cacheScope`), keyed by operation. The cacheable\n     * operations are `tools/list`, `prompts/list`, `resources/list`,\n     * `resources/templates/list`, `resources/read` and `server/discover`. The\n     * hint is used when the result for that operation does not provide its own\n     * cache fields — most useful for the list results and `server/discover`,\n     * which the SDK builds itself. A hint registered with an individual\n     * resource (`registerResource(..., { cacheHint })`) takes precedence for\n     * that resource's `resources/read` results, field by field: a field the\n     * per-resource hint leaves unset still falls back to the per-operation\n     * hint configured here.\n     *\n     * Absent hints (or omitting this option entirely) keep today's behavior:\n     * cacheable 2026-07-28 results are emitted with `ttlMs: 0` and\n     * `cacheScope: 'private'`. Responses to 2025-era requests are never\n     * affected. Invalid values throw a `RangeError` at construction time.\n     */\n    cacheHints?: Partial<Record<CacheableResultMethod, CacheHint>>;\n\n    /**\n     * Multi-round-trip serving knobs. On 2026-era requests the client\n     * fulfils `input_required` returns; on 2025-era connections the SDK's\n     * legacy shim fulfils them server-side (real server→client requests +\n     * handler re-entry), so handlers are written once and serve both eras.\n     */\n    inputRequired?: {\n        /**\n         * Handler re-entries per originating request before the shim fails\n         * (tools/call: `isError` result; prompts/resources: JSON-RPC error).\n         * @default 8\n         */\n        maxRounds?: number;\n\n        /**\n         * Per-leg timeout (ms) for the shim's embedded server→client\n         * requests, sent with `resetTimeoutOnProgress: true`. Human-paced —\n         * deliberately far above the 60s protocol default.\n         * @default 600_000\n         */\n        roundTimeoutMs?: number;\n\n        /**\n         * `false` disables the shim: an `input_required` return on a\n         * 2025-era request fails loudly (the pre-shim behavior).\n         * @default true\n         */\n        legacyShim?: boolean;\n    };\n\n    /**\n     * Multi-round-trip `requestState` integrity hook (protocol revision\n     * 2026-07-28).\n     */\n    requestState?: {\n        /**\n         * Called on every multi-round-trip request round whose echoed\n         * `requestState` is a string (i.e. whenever\n         * `ctx.mcpReq.requestState()` would return one), BEFORE the handler\n         * runs — including the legacy shim's in-process rounds. Throw or\n         * reject to refuse the request: the seam answers with a wire-level\n         * `-32602` Invalid Params error whose message is frozen to\n         * `\"Invalid or expired requestState\"` and whose `data.reason` is\n         * `'invalid_request_state'` — the thrown reason is surfaced via the\n         * server's `onerror` callback only and never reaches the wire.\n         *\n         * This is the place to put HMAC or AEAD verification of\n         * `requestState`. The spec MUST for integrity-protecting state that\n         * influences authorization, resource access, or business logic is on\n         * the server author (basic/patterns/mrtr, server requirements 4–5);\n         * the SDK provides NO default verification —\n         * {@linkcode server/requestStateCodec.createRequestStateCodec | createRequestStateCodec}\n         * is the SDK-provided HMAC helper whose `verify` drops in here\n         * directly. Leaving this option unconfigured keeps the passthrough\n         * behavior — `ctx.mcpReq.requestState()` returns the raw wire string,\n         * which MUST be treated as attacker-controlled input.\n         *\n         * The resolved value is LOAD-BEARING: when the hook resolves with a\n         * non-`undefined` value — as\n         * {@linkcode server/requestStateCodec.RequestStateCodec | RequestStateCodec}`.verify`\n         * does (the decoded payload) — the seam hands THAT value to the\n         * handler via the typed `ctx.mcpReq.requestState<T>()` accessor, so a\n         * codec-using handler reads its verified state with no second decode\n         * call. A verifier that is not also the decoder should resolve\n         * `undefined` (return nothing) to keep the accessor on the raw wire\n         * string — resolving an incidental value (e.g. a boolean\n         * verification flag) would replace what the handler reads.\n         */\n        verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;\n    };\n};\n\n/*\n * Package-internal hooks for the 2026-07-28 serving entries (the per-request\n * HTTP entry `createMcpHandler` and the connection-pinned stdio entry\n * `serveStdio`).\n *\n * The connection-scoped client-identity fields and the modern-only handler set are\n * private to `Server`; the serving entries in this package need to write/install\n * them on the fresh instance they get from a consumer factory. The static initializer\n * below hands these module-scoped closures privileged access; the exported wrappers\n * are imported by sibling modules in this package only and are deliberately NOT\n * re-exported from the package index (they are not public API).\n */\nlet writeClientIdentity: (server: Server, identity: PerRequestClientIdentity) => void;\nlet installDiscoverHandler: (server: Server, servedModernVersions: readonly string[]) => void;\nlet readServerIdentity: (server: Server) => Implementation;\n\n/** Connection-scoped client-identity fields backfilled per request from a validated `_meta` envelope. */\nexport interface PerRequestClientIdentity {\n    /** The client's name/version information, when the envelope carried it. */\n    clientInfo?: Implementation;\n    /** The client's declared capabilities, when the envelope carried them. */\n    clientCapabilities?: ClientCapabilities;\n}\n\n/**\n * Package-internal: backfills the connection-scoped client-identity fields of a\n * per-request server instance from the request's validated `_meta` envelope, so the\n * (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion}\n * accessors keep answering on instances that never see an `initialize` handshake.\n * Not public API.\n */\nexport function seedClientIdentityFromEnvelope(server: Server, identity: PerRequestClientIdentity): void {\n    writeClientIdentity(server, identity);\n}\n\n/**\n * Package-internal: installs the modern-only `server/discover` handler on an instance\n * the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern\n * revisions the entry serves appear in the instance's supported-versions list (so the\n * discover advertisement and version-mismatch errors name them). Idempotent.\n * Hand-constructed instances are unaffected: nothing else calls this, so they keep\n * answering `-32601` unless their own supported-versions list opts into a modern\n * revision. Not public API.\n */\nexport function installModernOnlyHandlers(server: Server, servedModernVersions: readonly string[]): void {\n    installDiscoverHandler(server, servedModernVersions);\n}\n\n/**\n * Package-internal: the instance's implementation identity, for the serving\n * entries to stamp onto entry-built results (the `subscriptions/listen`\n * graceful-close result — built outside the encode seam, but the spec's\n * `SubscriptionsListenResultMetaObject` extends `ResultMetaObject`, so it carries\n * the serverInfo SHOULD like every other result). Not public API.\n */\nexport function serverIdentityOf(server: Server): Implementation {\n    return readServerIdentity(server);\n}\n\n/**\n * An MCP server on top of a pluggable transport.\n *\n * This server will automatically respond to the initialization flow as initiated from the client.\n *\n * @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases.\n */\nexport class Server extends Protocol<ServerContext> {\n    private _clientCapabilities?: ClientCapabilities;\n    private _clientVersion?: Implementation;\n\n    static {\n        writeClientIdentity = (server, identity) => {\n            if (identity.clientCapabilities !== undefined) {\n                server._clientCapabilities = identity.clientCapabilities;\n            }\n            if (identity.clientInfo !== undefined) {\n                server._clientVersion = identity.clientInfo;\n            }\n        };\n        installDiscoverHandler = (server, servedModernVersions) => {\n            const missing = servedModernVersions.filter(version => !server._supportedProtocolVersions.includes(version));\n            if (missing.length > 0) {\n                // Never mutate the existing array in place: the default supported-versions\n                // list is a shared module constant.\n                server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing];\n            }\n            server.setRequestHandler('server/discover', () => server._ondiscover());\n        };\n        readServerIdentity = server => server._serverInfo;\n    }\n    private _capabilities: ServerCapabilities;\n    private _instructions?: string;\n    private _jsonSchemaValidator: jsonSchemaValidator;\n    private _cacheHints?: ServerOptions['cacheHints'];\n    private _requestStateVerify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;\n    private _inputRequiredServing: { maxRounds: number; roundTimeoutMs: number; legacyShim: boolean };\n    private _legacyShim?: LegacyInputRequiredShim;\n\n    /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */\n    private _legacyInputRequiredShim(): LegacyInputRequiredShim {\n        return (this._legacyShim ??= new LegacyInputRequiredShim({\n            maxRounds: this._inputRequiredServing.maxRounds,\n            roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs,\n            resolvedClientCapabilities: ctx => this._inputRequestCapabilityView(ctx),\n            verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method),\n            sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }),\n            sendSampling: (params, options) => this.createMessage(params, options),\n            listRoots: (params, options) => this.listRoots(params, options)\n        }));\n    }\n\n    /**\n     * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification).\n     */\n    oninitialized?: () => void;\n\n    /**\n     * Initializes this server with the given name and version information.\n     */\n    constructor(\n        private _serverInfo: Implementation,\n        options?: ServerOptions\n    ) {\n        super(options);\n        this._capabilities = options?.capabilities ? { ...options.capabilities } : {};\n        this._instructions = options?.instructions;\n        this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new DefaultJsonSchemaValidator();\n        this._requestStateVerify = options?.requestState?.verify;\n\n        this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired);\n\n        // Configured cache hints fail loudly at construction time (before any\n        // handler registration consults them).\n        if (options?.cacheHints !== undefined) {\n            for (const [operation, hint] of Object.entries(options.cacheHints)) {\n                if (hint !== undefined) {\n                    assertValidCacheHint(hint, `cacheHints['${operation}']`);\n                }\n            }\n            this._cacheHints = options.cacheHints;\n        }\n\n        this.setRequestHandler('initialize', request => this._oninitialize(request));\n        this.setNotificationHandler('notifications/initialized', () => this.oninitialized?.());\n\n        // server/discover is installed only when the supported-versions list\n        // carries a modern revision: a legacy-only server keeps answering -32601.\n        // A hand-constructed instance is never era-bound, so the handler stays\n        // unreachable behind the era gate until a serving entry (createMcpHandler,\n        // serveStdio) marks the instance as serving the 2026-07-28 era.\n        if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) {\n            this.setRequestHandler('server/discover', () => this._ondiscover());\n        }\n\n        if (this._capabilities.logging) {\n            this._registerLoggingHandler();\n        }\n    }\n\n    /** Attaches to the given transport; rejects while this instance is connected to another one. */\n    override async connect(transport: Transport): Promise<void> {\n        if (this.transport !== undefined) {\n            throw new SdkError(\n                SdkErrorCode.AlreadyConnected,\n                'Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.'\n            );\n        }\n        await super.connect(transport);\n    }\n\n    /**\n     * Registers the built-in `logging/setLevel` request handler.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n     * Remains functional during the deprecation window (at least twelve months).\n     * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n     */\n    private _registerLoggingHandler(): void {\n        this.setRequestHandler('logging/setLevel', async (request, ctx) => {\n            const transportSessionId: string | undefined =\n                ctx.sessionId || (ctx.http?.req?.headers.get('mcp-session-id') as string) || undefined;\n            const { level } = request.params;\n            const parseResult = parseSchema(LoggingLevelSchema, level);\n            if (parseResult.success) {\n                this._loggingLevels.set(transportSessionId, parseResult.data);\n            }\n            return {};\n        });\n    }\n\n    protected override buildContext(ctx: BaseContext, transportInfo?: MessageExtraInfo): ServerContext {\n        // Only create http when there's actual HTTP transport info or auth info\n        const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream;\n        return {\n            ...ctx,\n            mcpReq: {\n                ...ctx.mcpReq,\n                // Deprecated as of protocol version 2026-07-28 (SEP-2577): `log` and\n                // `requestSampling` remain functional during the deprecation window\n                // (at least twelve months). See ServerContext for migration guidance.\n                log: (level, data, logger) => {\n                    if (!this._capabilities.logging) {\n                        return Promise.resolve();\n                    }\n                    // Level filter: on a 2026-era request the client declares its\n                    // threshold per request via the `_meta.logLevel` envelope key\n                    // (the modern equivalent of `logging/setLevel`, which is not a\n                    // request method on that revision). The spec at 2026-07-28\n                    // says an absent key means the server MUST NOT send\n                    // `notifications/message` for the request — so an absent key\n                    // suppresses, it does not mean \"send everything\". On\n                    // 2025-era connections the session-scoped level set via\n                    // `logging/setLevel` applies exactly as before (an absent\n                    // session level there continues to mean no filter).\n                    let threshold: LoggingLevel | undefined;\n                    if (this._servedModernEra()) {\n                        threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY] as LoggingLevel | undefined;\n                        if (threshold === undefined) {\n                            return Promise.resolve();\n                        }\n                    } else {\n                        threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(undefined);\n                    }\n                    if (threshold !== undefined && this.LOG_LEVEL_SEVERITY.get(level)! < this.LOG_LEVEL_SEVERITY.get(threshold)!) {\n                        return Promise.resolve();\n                    }\n                    // Emit request-related (like progress and `ctx.mcpReq.notify`)\n                    // so the notification rides the in-flight exchange. Without the\n                    // related-request stamp, per-request hosting (`createMcpHandler`,\n                    // either era) silently drops the message because it has no\n                    // session-wide stream to deliver it on.\n                    return ctx.mcpReq.notify({ method: 'notifications/message', params: { level, data, logger } });\n                },\n                elicitInput: (params, options) => this.elicitInput(params, options),\n                requestSampling: (params, options) => this.createMessage(params, options)\n            },\n            http: hasHttpInfo\n                ? {\n                      ...ctx.http,\n                      req: transportInfo?.request,\n                      closeSSE: transportInfo?.closeSSEStream,\n                      closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream\n                  }\n                : undefined\n        };\n    }\n\n    // Map log levels by session id\n    private _loggingLevels = new Map<string | undefined, LoggingLevel>();\n\n    // Map LogLevelSchema to severity index\n    private readonly LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));\n\n    // Is a message with the given level ignored in the log level set for the given session id?\n    private isMessageIgnored = (level: LoggingLevel, sessionId?: string): boolean => {\n        const currentLevel = this._loggingLevels.get(sessionId);\n        return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level)! < this.LOG_LEVEL_SEVERITY.get(currentLevel)! : false;\n    };\n\n    /**\n     * Registers new capabilities. This can only be called before connecting to a transport.\n     *\n     * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n     */\n    public registerCapabilities(capabilities: ServerCapabilities): void {\n        if (this.transport) {\n            throw new SdkError(SdkErrorCode.AlreadyConnected, 'Cannot register capabilities after connecting to transport');\n        }\n        const hadLogging = !!this._capabilities.logging;\n        this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n        if (!hadLogging && this._capabilities.logging) {\n            this._registerLoggingHandler();\n        }\n    }\n\n    /**\n     * Enforces server-side validation for `tools/call` results regardless of how the\n     * handler was registered, attaches the configured per-operation cache hint\n     * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope`\n     * for results that do not provide their own, and owns the multi-round-trip\n     * seam: on the methods whose 2026-07-28 result vocabulary includes\n     * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an\n     * input-required return skips result-schema validation and is checked\n     * against the served era, the at-least-one rule, and the request's own\n     * declared client capabilities; on every other method an input-required\n     * return is a server bug and fails loudly. The hint rides a symbol-keyed\n     * property that is never serialized, so 2025-era responses are unaffected.\n     */\n    protected override _wrapHandler(\n        method: string,\n        handler: (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result>\n    ): (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result> {\n        if (method !== 'tools/call') {\n            const cacheHint = (this._cacheHints as Record<string, CacheHint | undefined> | undefined)?.[method];\n            const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method);\n            if (cacheHint === undefined && !isInputRequiredCapable) {\n                // Server-bug guard: an input-required return from a method\n                // whose result vocabulary does not include it is never\n                // mis-typed onto the wire.\n                return async (request, ctx) => {\n                    const result = await handler(request, ctx);\n                    if (isInputRequiredResult(result)) {\n                        throw new ProtocolError(\n                            ProtocolErrorCode.InternalError,\n                            `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and ` +\n                                `resources/read support input_required (protocol revision 2026-07-28)`\n                        );\n                    }\n                    return result;\n                };\n            }\n            return async (request, ctx) => {\n                const result = isInputRequiredCapable\n                    ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx)\n                    : await handler(request, ctx);\n                if (isInputRequiredResult(result)) {\n                    if (!isInputRequiredCapable) {\n                        throw new ProtocolError(\n                            ProtocolErrorCode.InternalError,\n                            `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and ` +\n                                `resources/read support input_required (protocol revision 2026-07-28)`\n                        );\n                    }\n                    // Never cache-stamped (the encode contract skips\n                    // non-complete results); the hint is not attached.\n                    return result;\n                }\n                return cacheHint === undefined ? result : attachCacheHintFallback(result, cacheHint);\n            };\n        }\n        return async (request, ctx) => {\n            // Era-exact validation via the function-only WireCodec contract:\n            // resolved from the instance era at dispatch time (the era gate\n            // guarantees tools/call exists on the serving era, so the\n            // `not-in-era` arm is an internal error). The era registry entry\n            // IS the plain CallToolResult schema (the result map is aligned\n            // to the typed map — no widened unions), so no narrower surface\n            // is needed.\n            const codec = codecForVersion(this._negotiatedProtocolVersion);\n            const validatedRequest = codec.validateRequest('tools/call', request);\n            if (!validatedRequest.ok) {\n                throw new ProtocolError(\n                    validatedRequest.reason === 'not-in-era' ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,\n                    validatedRequest.reason === 'not-in-era'\n                        ? 'No wire schema for tools/call in the resolved era'\n                        : `Invalid tools/call request: ${validatedRequest.message}`\n                );\n            }\n\n            const result = await this._invokeInputRequiredCapableHandler('tools/call', handler, request, ctx);\n            if (isInputRequiredResult(result)) {\n                // Already checked by the seam; the CallToolResult schema does\n                // not apply to it (no widening — InputRequiredResult travels\n                // alongside).\n                return result;\n            }\n\n            // v1-parity authoring affordance, era-independent: a content-less\n            // handler result normalizes to content: [] before era validation.\n            // Other result families' bodies stay un-normalized and fail loudly.\n            const normalizedResult = normalizeContentlessToolResult(result);\n\n            const validationResult = codec.validateResult('tools/call', normalizedResult);\n            if (!validationResult.ok) {\n                throw new ProtocolError(\n                    validationResult.reason === 'not-in-era' ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,\n                    validationResult.reason === 'not-in-era'\n                        ? 'No wire schema for tools/call in the resolved era'\n                        : `Invalid tools/call result: ${validationResult.message}`\n                );\n            }\n\n            return validationResult.value;\n        };\n    }\n\n    /**\n     * Whether this instance is bound to a 2026-07-28-or-later protocol\n     * revision. Era is instance state — a serving entry (`createMcpHandler`,\n     * `serveStdio`) marks the instance modern at construction; a 2025-era\n     * `initialize` handshake binds it legacy. The multi-round-trip seam reads\n     * this directly: there is no per-request era consult.\n     */\n    private _servedModernEra(): boolean {\n        return this._negotiatedProtocolVersion !== undefined && isModernProtocolVersion(this._negotiatedProtocolVersion);\n    }\n\n    /**\n     * Invokes a handler for one of the multi-round-trip methods and applies\n     * the input-required seam:\n     *\n     * - a `UrlElicitationRequiredError` (or any 2025-style server→client\n     *   request idiom) escaping the handler on a request served on the\n     *   2026-07-28 era fails LOUDLY with a clear steer to\n     *   `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the\n     *   2026-07-28 wire and the throw is not silently converted. Requests\n     *   served on the 2025 era keep today's `-32042` behavior byte-exact (the\n     *   error is rethrown unchanged).\n     * - an input-required RETURN toward a 2026-07-28 request must satisfy\n     *   the at-least-one rule, and every embedded request must be covered by\n     *   the capabilities declared on the request's envelope (violations\n     *   answer the typed `-32021` error). Toward a 2025-era request the\n     *   return is fulfilled by the default-on legacy shim, whose own gate\n     *   consults the initialize-declared capabilities and surfaces\n     *   violations per family; `inputRequired.legacyShim: false` restores\n     *   the pre-shim loud failure.\n     */\n    private async _invokeInputRequiredCapableHandler(\n        method: string,\n        handler: (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result>,\n        request: JSONRPCRequest,\n        ctx: ServerContext\n    ): Promise<Result> {\n        const servedModern = this._servedModernEra();\n\n        // The configured requestState.verify hook runs above the handler (and\n        // therefore above the McpServer tools/call funnel), so a rejection\n        // reaches the wire as a real JSON-RPC error rather than an `isError`\n        // tool result. The wire message is FROZEN — the thrown reason is\n        // surfaced via `onerror` only. A non-string `requestState` value (the\n        // wire field is `string | undefined`) is treated as invalid regardless\n        // of whether a hook is configured, so a malformed value cannot bypass\n        // verification.\n        const rawRequestState: unknown = ctx.mcpReq.requestState();\n        if (rawRequestState !== undefined && typeof rawRequestState !== 'string') {\n            throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {\n                reason: 'invalid_request_state'\n            });\n        }\n        let ctxForHandler = ctx;\n        if (typeof rawRequestState === 'string') {\n            const decoded = await this._verifyRequestState(rawRequestState, ctx, method);\n            if (decoded !== undefined) {\n                ctxForHandler = withRequestStateValue(ctx, decoded);\n            }\n        }\n\n        let result: Result;\n        try {\n            result = await handler(request, ctxForHandler);\n        } catch (error) {\n            if (error instanceof ProtocolError && error.code === ProtocolErrorCode.UrlElicitationRequired) {\n                if (!servedModern) {\n                    // 2025-era behavior is frozen: the error reaches the wire\n                    // exactly as it does today.\n                    throw error;\n                }\n                // 2026-era requests do not carry the -32042 surface. A\n                // 2025-style throw fails loudly with a clear steer rather than\n                // being converted: the handler should return\n                // inputRequired.elicitUrl(...) instead.\n                throw new ProtocolError(\n                    ProtocolErrorCode.InternalError,\n                    `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ` +\n                        `${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) ` +\n                        `from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not ` +\n                        `available on this revision.`\n                );\n            }\n            throw error;\n        }\n\n        if (!isInputRequiredResult(result)) {\n            return result;\n        }\n\n        if (!servedModern) {\n            if (!this._inputRequiredServing.legacyShim) {\n                // The escape hatch (`inputRequired.legacyShim: false`)\n                // restores the pre-shim posture: the 2025-era wire has no\n                // input_required vocabulary, so fail loudly rather than\n                // putting a mis-typed result on the wire.\n                throw new ProtocolError(\n                    ProtocolErrorCode.InternalError,\n                    `Handler for ${method} returned an input-required result, but this request is served on protocol revision ` +\n                        `${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`\n                );\n            }\n            // Write-once handlers served to deployed 2025 clients.\n            return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result);\n        }\n\n        // F7 at-least-one re-check (hand-built results are legal; the rule is\n        // re-checked at the seam).\n        const inputRequests = result.inputRequests as Record<string, unknown> | null | undefined;\n        const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0;\n        const hasRequestState = typeof result.requestState === 'string';\n        if (!hasInputRequests && !hasRequestState) {\n            throw new ProtocolError(\n                ProtocolErrorCode.InternalError,\n                `Handler for ${method} returned an input-required result with neither inputRequests nor requestState ` +\n                    `(every InputRequiredResult must include at least one of the two)`\n            );\n        }\n\n        // Per-embedded-request capability check against the request's own\n        // envelope declaration (-32021 on violation).\n        if (hasInputRequests) {\n            const declared = this._inputRequestCapabilityView(ctx);\n            for (const [key, entry] of Object.entries(inputRequests)) {\n                const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry);\n                const missing = missingClientCapabilities(required, declared);\n                if (missing !== undefined) {\n                    throw new MissingRequiredClientCapabilityError(\n                        { requiredCapabilities: missing },\n                        `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare ` +\n                            `the required capability`\n                    );\n                }\n            }\n        }\n\n        return result;\n    }\n\n    /**\n     * Runs the configured `requestState.verify` hook and returns its\n     * resolved value (`undefined` when unconfigured or the hook returns\n     * nothing). Deny-on-error: any hook failure answers the frozen `-32602`;\n     * the reason goes to `onerror` only.\n     */\n    private async _verifyRequestState(state: string, ctx: ServerContext, method: string): Promise<unknown> {\n        if (this._requestStateVerify === undefined) {\n            return undefined;\n        }\n        try {\n            return await this._requestStateVerify(state, ctx);\n        } catch (error) {\n            this.onerror?.(\n                new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)\n            );\n            throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {\n                reason: 'invalid_request_state'\n            });\n        }\n    }\n\n    /**\n     * The per-request resolved client-capabilities view: the request's own\n     * `_meta` envelope on the 2026 era; the `initialize`-declared state on a\n     * 2025-era connection. Per-request instances that never saw an\n     * initialize (stateless legacy) hold nothing, so gates refuse there.\n     */\n    private _inputRequestCapabilityView(ctx: ServerContext): ClientCapabilities | undefined {\n        return this._servedModernEra()\n            ? (ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY] as ClientCapabilities | undefined)\n            : this._clientCapabilities;\n    }\n\n    /**\n     * Guard for the push-style server→client request APIs ({@linkcode createMessage},\n     * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a\n     * modern-era instance: the 2026-07-28 revision has no server→client request\n     * channel, so the call fails before any wire traffic with a typed error\n     * whose message steers to `inputRequired(...)`. The base era gate would\n     * also reject it; this guard runs first to carry the steer.\n     */\n    private _assertPushApiInServedEra(method: string): void {\n        if (this._servedModernEra()) {\n            throw new SdkError(\n                SdkErrorCode.MethodNotSupportedByProtocolVersion,\n                `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: ` +\n                    `'${method}' cannot be sent while serving a request on that revision. ` +\n                    `Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded ` +\n                    `requests and retries the original request (multi round-trip requests).`,\n                { method, era: '2026-07-28' }\n            );\n        }\n    }\n\n    protected assertCapabilityForMethod(method: RequestMethod | string): void {\n        switch (method) {\n            case 'sampling/createMessage': {\n                if (!this._clientCapabilities?.sampling) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'elicitation/create': {\n                if (!this._clientCapabilities?.elicitation) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'roots/list': {\n                if (!this._clientCapabilities?.roots) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Client does not support listing roots (required for ${method})`\n                    );\n                }\n                break;\n            }\n\n            case 'ping': {\n                // No specific capability required for ping\n                break;\n            }\n        }\n    }\n\n    protected assertNotificationCapability(method: NotificationMethod | string): void {\n        switch (method) {\n            case 'notifications/message': {\n                if (!this._capabilities.logging) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'notifications/resources/updated':\n            case 'notifications/resources/list_changed': {\n                if (!this._capabilities.resources) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Server does not support notifying about resources (required for ${method})`\n                    );\n                }\n                break;\n            }\n\n            case 'notifications/tools/list_changed': {\n                if (!this._capabilities.tools) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Server does not support notifying of tool list changes (required for ${method})`\n                    );\n                }\n                break;\n            }\n\n            case 'notifications/prompts/list_changed': {\n                if (!this._capabilities.prompts) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Server does not support notifying of prompt list changes (required for ${method})`\n                    );\n                }\n                break;\n            }\n\n            case 'notifications/elicitation/complete': {\n                if (!this._clientCapabilities?.elicitation?.url) {\n                    throw new SdkError(\n                        SdkErrorCode.CapabilityNotSupported,\n                        `Client does not support URL elicitation (required for ${method})`\n                    );\n                }\n                break;\n            }\n\n            case 'notifications/cancelled': {\n                // Cancellation notifications are always allowed\n                break;\n            }\n\n            case 'notifications/progress': {\n                // Progress notifications are always allowed\n                break;\n            }\n        }\n    }\n\n    protected assertRequestHandlerCapability(method: string): void {\n        switch (method) {\n            case 'completion/complete': {\n                if (!this._capabilities.completions) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'logging/setLevel': {\n                if (!this._capabilities.logging) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'prompts/get':\n            case 'prompts/list': {\n                if (!this._capabilities.prompts) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'resources/list':\n            case 'resources/templates/list':\n            case 'resources/read': {\n                if (!this._capabilities.resources) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'tools/call':\n            case 'tools/list': {\n                if (!this._capabilities.tools) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`);\n                }\n                break;\n            }\n\n            case 'ping':\n            case 'initialize': {\n                // No specific capability required for these methods\n                break;\n            }\n        }\n    }\n\n    private async _oninitialize(request: InitializeRequest): Promise<InitializeResult> {\n        const requestedVersion = request.params.protocolVersion;\n\n        this._clientCapabilities = request.params.capabilities;\n        this._clientVersion = request.params.clientInfo;\n\n        // A 2026-07-28-or-later revision is NEVER negotiated via the legacy\n        // `initialize` handshake — only ever selected through `server/discover` —\n        // so the accept check and counter-offer consult only the legacy subset.\n        const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions);\n        const protocolVersion = legacyVersions.includes(requestedVersion)\n            ? requestedVersion\n            : (legacyVersions[0] ?? LATEST_PROTOCOL_VERSION);\n\n        // The negotiated version is the instance's connection state — it IS\n        // the wire-era selection for everything this instance sends and\n        // receives from here on (legacy handshake ⇒ a legacy-era version).\n        this._negotiatedProtocolVersion = protocolVersion;\n        this.transport?.setProtocolVersion?.(protocolVersion);\n\n        return {\n            protocolVersion,\n            capabilities: this.getCapabilities(),\n            serverInfo: this._serverInfo,\n            ...(this._instructions && { instructions: this._instructions })\n        };\n    }\n\n    /**\n     * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions`\n     * lists only modern revisions (2025-era versions are negotiated via `initialize`);\n     * the capabilities are advertised as-is, listChanged/subscribe bits included\n     * (see {@linkcode discoverAdvertisedCapabilities}).\n     */\n    private _ondiscover(): DiscoverResult {\n        // Server identity is not a body field: the encode seam stamps it into\n        // the result `_meta` via `_outboundServerInfo` (spec PR #3002).\n        return {\n            supportedVersions: modernProtocolVersions(this._supportedProtocolVersions),\n            capabilities: discoverAdvertisedCapabilities(this.getCapabilities()),\n            ...(this._instructions && { instructions: this._instructions })\n        };\n    }\n\n    /**\n     * The identity the 2026-era encode seam stamps into every outbound\n     * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR\n     * #3002: servers SHOULD identify themselves on every response).\n     */\n    protected override _outboundServerInfo(): Implementation | undefined {\n        return this._serverInfo;\n    }\n\n    /**\n     * After initialization has completed, this will be populated with the client's reported capabilities.\n     *\n     * @deprecated Read client identity from the per-request handler context instead: on\n     * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's\n     * declared capabilities, while on 2025-era connections this accessor keeps returning the\n     * `initialize`-scoped value. The accessor remains functional — instances serving the\n     * 2026-07-28 era are backfilled per request from the validated envelope.\n     */\n    getClientCapabilities(): ClientCapabilities | undefined {\n        return this._clientCapabilities;\n    }\n\n    /**\n     * After initialization has completed, this will be populated with information about the client's name and version.\n     *\n     * @deprecated Read client identity from the per-request handler context instead: on\n     * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's\n     * name and version, while on 2025-era connections this accessor keeps returning the\n     * `initialize`-scoped value. The accessor remains functional — instances serving the\n     * 2026-07-28 era are backfilled per request from the validated envelope.\n     */\n    getClientVersion(): Implementation | undefined {\n        return this._clientVersion;\n    }\n\n    /**\n     * After initialization has completed, this will be populated with the protocol version negotiated\n     * with the client (the version the server responded with during the initialize handshake), or\n     * `undefined` before initialization.\n     *\n     * @deprecated Read the protocol revision from the per-request handler context instead: on\n     * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the\n     * request was sent for, while on 2025-era connections this accessor keeps returning the\n     * `initialize`-negotiated version. The accessor remains functional — instances serving the\n     * 2026-07-28 era report that revision.\n     */\n    getNegotiatedProtocolVersion(): string | undefined {\n        return this._negotiatedProtocolVersion;\n    }\n\n    /**\n     * Project a `tools/call` result through this instance's negotiated wire\n     * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on\n     * the 2025 era the `{result:…}` wrap when `structuredContent` is a\n     * non-object value or the advertised `outputSchema` had a non-object root.\n     * Identity for object-shaped `structuredContent` on the 2026 era.\n     *\n     * `McpServer`'s built-in `tools/call` handler routes through this method.\n     * Low-level `setRequestHandler('tools/call', …)` authors call it\n     * themselves so the projection lives in one place (the codec) and the\n     * server-side handler stays era-blind.\n     *\n     * This is the only codec function exposed on `Server` — the full\n     * `WireCodec` is intentionally not part of the public surface.\n     */\n    public projectCallToolResult(\n        result: CallToolResult,\n        advertisedOutputSchema: Readonly<Record<string, unknown>> | undefined\n    ): CallToolResult {\n        return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema);\n    }\n\n    /**\n     * Returns the current server capabilities.\n     */\n    public getCapabilities(): ServerCapabilities {\n        return this._capabilities;\n    }\n\n    /**\n     * Sends a `ping` request to the connected client.\n     *\n     * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance.\n     * If your factory serves both eras, this only works on the legacy path.\n     */\n    async ping(): Promise<EmptyResult> {\n        this._assertPushApiInServedEra('ping');\n        return this.request({ method: 'ping' });\n    }\n\n    /**\n     * Request LLM sampling from the client (without tools).\n     * Returns single content block for backwards compatibility.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n     * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead,\n     * or migrate to calling LLM provider APIs directly. The 2025 push-style server-to-client\n     * request model is replaced by input_required results in the 2026-07-28 protocol. If your\n     * factory serves both eras, this only works on the legacy path.\n     */\n    async createMessage(params: CreateMessageRequestParamsBase, options?: RequestOptions): Promise<CreateMessageResult>;\n\n    /**\n     * Request LLM sampling from the client with tool support.\n     * Returns content that may be a single block or array (for parallel tool calls).\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n     * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead,\n     * or migrate to calling LLM provider APIs directly. The 2025 push-style server-to-client\n     * request model is replaced by input_required results in the 2026-07-28 protocol. If your\n     * factory serves both eras, this only works on the legacy path.\n     */\n    async createMessage(params: CreateMessageRequestParamsWithTools, options?: RequestOptions): Promise<CreateMessageResultWithTools>;\n\n    /**\n     * Request LLM sampling from the client.\n     * When tools may or may not be present, returns the union type.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n     * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead,\n     * or migrate to calling LLM provider APIs directly. The 2025 push-style server-to-client\n     * request model is replaced by input_required results in the 2026-07-28 protocol. If your\n     * factory serves both eras, this only works on the legacy path.\n     */\n    async createMessage(\n        params: CreateMessageRequest['params'],\n        options?: RequestOptions\n    ): Promise<CreateMessageResult | CreateMessageResultWithTools>;\n\n    // Implementation\n    async createMessage(\n        params: CreateMessageRequest['params'],\n        options?: RequestOptions\n    ): Promise<CreateMessageResult | CreateMessageResultWithTools> {\n        this._assertPushApiInServedEra('sampling/createMessage');\n        // Capability check - only required when tools/toolChoice are provided\n        if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) {\n            throw new SdkError(SdkErrorCode.CapabilityNotSupported, 'Client does not support sampling tools capability.');\n        }\n\n        // Message structure validation - always validate tool_use/tool_result pairs.\n        // These may appear even without tools/toolChoice in the current request when\n        // a previous sampling request returned tool_use and this is a follow-up with results.\n        if (params.messages.length > 0) {\n            const lastMessage = params.messages.at(-1)!;\n            const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];\n            const hasToolResults = lastContent.some(c => c.type === 'tool_result');\n\n            const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : undefined;\n            const previousContent = previousMessage\n                ? Array.isArray(previousMessage.content)\n                    ? previousMessage.content\n                    : [previousMessage.content]\n                : [];\n            const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');\n\n            if (hasToolResults) {\n                if (lastContent.some(c => c.type !== 'tool_result')) {\n                    throw new ProtocolError(\n                        ProtocolErrorCode.InvalidParams,\n                        'The last message must contain only tool_result content if any is present'\n                    );\n                }\n                if (!hasPreviousToolUse) {\n                    throw new ProtocolError(\n                        ProtocolErrorCode.InvalidParams,\n                        'tool_result blocks are not matching any tool_use from the previous message'\n                    );\n                }\n            }\n            if (hasPreviousToolUse) {\n                const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => (c as ToolUseContent).id));\n                const toolResultIds = new Set(\n                    lastContent.filter(c => c.type === 'tool_result').map(c => (c as ToolResultContent).toolUseId)\n                );\n                if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {\n                    throw new ProtocolError(\n                        ProtocolErrorCode.InvalidParams,\n                        'ids of tool_result blocks and tool_use blocks from previous message do not match'\n                    );\n                }\n            }\n        }\n\n        // The result schema depends on the REQUEST params (tools vs no tools),\n        // which a method-keyed registry entry cannot express — the era codec's\n        // `samplingResultVariant` owns the with-tools/plain pair. The funnel's\n        // registry-result path runs first (era-gated: sampling/createMessage\n        // is not a wire request on the 2026 era, so a modern-era instance\n        // fails with the typed era error before anything reaches the\n        // transport), then the variant validator narrows the wide result.\n        const hasTools = Boolean(params.tools || params.toolChoice);\n        const wide = await this.request({ method: 'sampling/createMessage', params }, options);\n        const outcome = this._wireCodec().samplingResultVariant(hasTools, wide);\n        if (!outcome.ok) {\n            // `not-in-era` is unreachable on the path that gets here (the era\n            // gate above filters out 2026 instances); `invalid` is a peer bug.\n            throw new SdkError(\n                SdkErrorCode.InvalidResult,\n                `Invalid sampling/createMessage result: ${outcome.reason === 'invalid' ? outcome.message : outcome.reason}`\n            );\n        }\n        return outcome.value;\n    }\n\n    /**\n     * Creates an elicitation request for the given parameters.\n     * For backwards compatibility, `mode` may be omitted for form requests and will default to `\"form\"`.\n     * @param params The parameters for the elicitation request.\n     * @param options Optional request options.\n     * @returns The result of the elicitation request.\n     *\n     * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip)\n     * instead. The 2025 push-style server-to-client request model is replaced by input_required\n     * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the\n     * legacy path.\n     */\n    async elicitInput(params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions): Promise<ElicitResult> {\n        this._assertPushApiInServedEra('elicitation/create');\n        const mode = (params.mode ?? 'form') as 'form' | 'url';\n\n        switch (mode) {\n            case 'url': {\n                if (!this._clientCapabilities?.elicitation?.url) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, 'Client does not support url elicitation.');\n                }\n                break;\n            }\n            case 'form': {\n                if (!this._clientCapabilities?.elicitation?.form) {\n                    throw new SdkError(SdkErrorCode.CapabilityNotSupported, 'Client does not support form elicitation.');\n                }\n                break;\n            }\n        }\n\n        return this._sendElicitationLeg(params, options);\n    }\n\n    /**\n     * The capability-check-free core of {@linkcode elicitInput}. The shim\n     * uses it because its gate differs from the public checks: a bare\n     * `elicitation: {}` counts as form support (the pre-mode rule), and\n     * accepted content passes through unvalidated for parity with the\n     * modern client driver (handlers validate via the schema-aware\n     * `acceptedContent` overload and can re-ask).\n     */\n    private async _sendElicitationLeg(\n        params: ElicitRequestFormParams | ElicitRequestURLParams,\n        options?: RequestOptions,\n        behavior?: { validateAcceptedContent: boolean }\n    ): Promise<ElicitResult> {\n        const mode = (params.mode ?? 'form') as 'form' | 'url';\n        const validateAcceptedContent = behavior?.validateAcceptedContent ?? true;\n\n        switch (mode) {\n            case 'url': {\n                const urlParams = params as ElicitRequestURLParams;\n                // Method-keyed request(): the era registry's plain\n                // ElicitResult schema is exactly the narrow surface.\n                return this.request({ method: 'elicitation/create', params: urlParams }, options);\n            }\n            case 'form': {\n                const formParams: ElicitRequestFormParams =\n                    params.mode === 'form' ? (params as ElicitRequestFormParams) : { ...(params as ElicitRequestFormParams), mode: 'form' };\n\n                const result = await this.request({ method: 'elicitation/create', params: formParams }, options);\n\n                if (validateAcceptedContent && result.action === 'accept' && result.content && formParams.requestedSchema) {\n                    try {\n                        const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema as JsonSchemaType);\n                        const validationResult = validator(result.content);\n\n                        if (!validationResult.valid) {\n                            throw new ProtocolError(\n                                ProtocolErrorCode.InvalidParams,\n                                `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`\n                            );\n                        }\n                    } catch (error) {\n                        if (error instanceof ProtocolError) {\n                            throw error;\n                        }\n                        throw new ProtocolError(\n                            ProtocolErrorCode.InternalError,\n                            `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`\n                        );\n                    }\n                }\n                return result;\n            }\n        }\n    }\n\n    /**\n     * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`\n     * notification for the specified elicitation ID.\n     *\n     * The notification (and the `elicitationId` it references) exists only on protocol revision\n     * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the\n     * returned callback rejects with a typed local error before anything reaches the transport\n     * (the method is not part of that revision's wire registry).\n     *\n     * @param elicitationId The ID of the elicitation to mark as complete.\n     * @param options Optional notification options. Useful when the completion notification should be related to a prior request.\n     * @returns A function that emits the completion notification when awaited.\n     */\n    createElicitationCompletionNotifier(elicitationId: string, options?: NotificationOptions): () => Promise<void> {\n        if (!this._clientCapabilities?.elicitation?.url) {\n            throw new SdkError(\n                SdkErrorCode.CapabilityNotSupported,\n                'Client does not support URL elicitation (required for notifications/elicitation/complete)'\n            );\n        }\n\n        return () =>\n            this.notification(\n                {\n                    method: 'notifications/elicitation/complete',\n                    params: {\n                        elicitationId\n                    }\n                },\n                options\n            );\n    }\n\n    /**\n     * Requests the list of roots from the client.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n     * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead,\n     * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025\n     * push-style server-to-client request model is replaced by input_required results in the\n     * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path.\n     */\n    async listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<ListRootsResult> {\n        this._assertPushApiInServedEra('roots/list');\n        return this.request({ method: 'roots/list', params }, options);\n    }\n\n    /**\n     * Sends a logging message to the client, if connected.\n     * Note: You only need to send the parameters object, not the entire JSON-RPC message.\n     * @see {@linkcode LoggingMessageNotification}\n     * @param params\n     * @param sessionId Optional for stateless transports and backward compatibility.\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n     * Remains functional during the deprecation window (at least twelve months).\n     * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n     */\n    async sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string) {\n        if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) {\n            return this.notification({ method: 'notifications/message', params });\n        }\n    }\n\n    async sendResourceUpdated(params: ResourceUpdatedNotification['params']) {\n        return this.notification({\n            method: 'notifications/resources/updated',\n            params\n        });\n    }\n\n    async sendResourceListChanged() {\n        return this.notification({\n            method: 'notifications/resources/list_changed'\n        });\n    }\n\n    async sendToolListChanged() {\n        return this.notification({ method: 'notifications/tools/list_changed' });\n    }\n\n    async sendPromptListChanged() {\n        return this.notification({ method: 'notifications/prompts/list_changed' });\n    }\n}\n\n/**\n * The capability set a server advertises on `server/discover`. Pure — never\n * mutates the input; the legacy `initialize` advertisement is untouched.\n *\n * The serving entries serve `subscriptions/listen` themselves, so the\n * `listChanged` and `resources.subscribe` capability bits are advertised\n * as-is: a modern-era client uses them to decide which notification types to\n * request on its listen filter.\n */\nexport function discoverAdvertisedCapabilities(capabilities: ServerCapabilities): ServerCapabilities {\n    return { ...capabilities };\n}\n","import type {\n    BaseMetadata,\n    CacheHint,\n    CallToolResult,\n    CompleteRequestPrompt,\n    CompleteRequestResourceTemplate,\n    CompleteResult,\n    GetPromptResult,\n    Icon,\n    Implementation,\n    InputRequiredResult,\n    ListPromptsResult,\n    ListResourcesResult,\n    ListToolsResult,\n    LoggingMessageNotification,\n    Prompt,\n    PromptReference,\n    ReadResourceResult,\n    Resource,\n    ResourceTemplateReference,\n    Result,\n    ServerContext,\n    StandardSchemaWithJSON,\n    Tool,\n    ToolAnnotations,\n    ToolExecution,\n    Transport,\n    Variables\n} from '@modelcontextprotocol/core-internal';\nimport {\n    assertCompleteRequestPrompt,\n    assertCompleteRequestResourceTemplate,\n    assertValidCacheHint,\n    attachCacheHintFallback,\n    isInputRequiredResult,\n    normalizeRawShapeSchema,\n    promptArgumentsFromStandardSchema,\n    ProtocolError,\n    ProtocolErrorCode,\n    ResourceNotFoundError,\n    scanXMcpHeaderDeclarations,\n    standardSchemaToJsonSchema,\n    UriTemplate,\n    validateAndWarnToolName,\n    validateStandardSchema\n} from '@modelcontextprotocol/core-internal';\nimport type * as z from 'zod/v4';\n\nimport { getCompleter, isCompletable } from './completable';\nimport type { ScopeChallengeHandler } from './scopeChallenge';\nimport { supportsScopeChallengeResolver } from './scopeChallenge';\nimport type { ServerOptions } from './server';\nimport { Server } from './server';\n\n// Counts array elements and object members in `value`, stopping once the running total passes `max`.\nfunction toolInputElementCount(value: unknown, max: number): number {\n    let count = 0;\n    const stack: unknown[] = [value];\n    while (stack.length > 0) {\n        const node = stack.pop();\n        if (node === null || typeof node !== 'object') continue;\n        if (Array.isArray(node)) {\n            for (const child of node) {\n                if (++count > max) return count;\n                if (child !== null && typeof child === 'object') stack.push(child);\n            }\n        } else {\n            for (const key in node) {\n                if (!Object.prototype.hasOwnProperty.call(node, key)) continue;\n                if (++count > max) return count;\n                const child = (node as Record<string, unknown>)[key];\n                if (child !== null && typeof child === 'object') stack.push(child);\n            }\n        }\n    }\n    return count;\n}\n\n// Resolves the configured element ceiling: no limit when unset or Infinity, else a number of at least 1.\nfunction resolveMaxToolInputElements(value: number | undefined): number | undefined {\n    if (value === undefined || value === Infinity) return undefined;\n    if (typeof value !== 'number' || Number.isNaN(value) || value < 1) {\n        throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);\n    }\n    return value;\n}\n\n/**\n * Options for {@linkcode McpServer}: everything {@linkcode ServerOptions} accepts, plus `maxToolInputElements`.\n */\nexport type McpServerOptions = ServerOptions & {\n    /**\n     * Largest combined number of array elements and object members a single `tools/call` `arguments` payload may contain.\n     * A number of at least 1; unset or `Infinity` means no limit.\n     */\n    maxToolInputElements?: number;\n};\n\n/**\n * High-level MCP server that provides a simpler API for working with resources, tools, and prompts.\n * For advanced usage (like sending notifications or setting custom request handlers), use the underlying\n * {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property.\n *\n * @example\n * ```ts source=\"./mcp.examples.ts#McpServer_basicUsage\"\n * const server = new McpServer({\n *     name: 'my-server',\n *     version: '1.0.0'\n * });\n * ```\n */\nexport class McpServer {\n    /**\n     * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications.\n     */\n    public readonly server: Server;\n\n    private readonly _maxToolInputElements: number | undefined;\n\n    private _registeredResources: { [uri: string]: RegisteredResource } = {};\n    private _registeredResourceTemplates: {\n        [name: string]: RegisteredResourceTemplate;\n    } = {};\n    private _registeredTools: { [name: string]: RegisteredTool } = {};\n    private _registeredPrompts: { [name: string]: RegisteredPrompt } = {};\n    /** Per-tool JSON-converted `inputSchema`, filled on first use by `toolInputSchemaJson()`. */\n    private _toolInputSchemaJson: { [name: string]: Record<string, unknown> } = {};\n\n    /**\n     * The JSON-serialized `inputSchema` of a registered tool, or `undefined`\n     * when no such tool is registered. Used by the HTTP entry's pre-dispatch\n     * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema\n     * `tools/list` would emit, before dispatch reaches the handler).\n     *\n     * @internal\n     */\n    toolInputSchemaJson(name: string): Record<string, unknown> | undefined {\n        const tool = this._registeredTools[name];\n        if (tool === undefined || !tool.enabled) return undefined;\n        if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name];\n        if (tool.inputSchema === undefined) return EMPTY_OBJECT_JSON_SCHEMA;\n        // A conversion failure returns `undefined` so it surfaces where it always has (`tools/list`).\n        try {\n            const json = standardSchemaToJsonSchema(tool.inputSchema, 'input');\n            this._toolInputSchemaJson[name] = json;\n            return json;\n        } catch {\n            return undefined;\n        }\n    }\n\n    constructor(serverInfo: Implementation, options?: McpServerOptions) {\n        this.server = new Server(serverInfo, options);\n        this._maxToolInputElements = resolveMaxToolInputElements(options?.maxToolInputElements);\n\n        // Per the MCP spec, a server that declares a primitive capability MUST respond to its\n        // list method (potentially with an empty result) rather than \"Method not found\" — even\n        // if nothing has been registered yet. Handlers are normally installed lazily on first\n        // registration, so eagerly install them here for any capability declared up front.\n        // (Users of the low-level `Server` class remain responsible for their own handlers.)\n        if (options?.capabilities?.tools) {\n            this.setToolRequestHandlers();\n        }\n        if (options?.capabilities?.resources) {\n            this.setResourceRequestHandlers();\n        }\n        if (options?.capabilities?.prompts) {\n            this.setPromptRequestHandlers();\n        }\n    }\n\n    /**\n     * Attaches to the given transport, starts it, and starts listening for messages.\n     *\n     * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward.\n     *\n     * @example\n     * ```ts source=\"./mcp.examples.ts#McpServer_connect_stdio\"\n     * const server = new McpServer({ name: 'my-server', version: '1.0.0' });\n     * const transport = new StdioServerTransport();\n     * await server.connect(transport);\n     * ```\n     */\n    async connect(transport: Transport): Promise<void> {\n        if (supportsScopeChallengeResolver(transport)) {\n            transport.setScopeChallengeResolver(context => this.resolveScopeChallenge(context));\n        }\n        return await this.server.connect(transport);\n    }\n\n    /**\n     * Closes the connection.\n     */\n    async close(): Promise<void> {\n        await this.server.close();\n    }\n\n    /** @internal */\n    resolveScopeChallenge: ScopeChallengeHandler = context => {\n        switch (context.request.method) {\n            case 'tools/call': {\n                const toolName = (context.request.params as { name?: unknown } | undefined)?.name;\n                if (typeof toolName !== 'string') return;\n                const tool = this._registeredTools[toolName];\n                if (tool === undefined || !tool.enabled) return;\n                return tool.scopeChallenge?.(context);\n            }\n            case 'resources/read': {\n                const resourceUri = (context.request.params as { uri?: unknown } | undefined)?.uri;\n                if (typeof resourceUri !== 'string') return;\n\n                let uri: URL;\n                try {\n                    uri = new URL(resourceUri);\n                } catch {\n                    return;\n                }\n\n                const resource = this._registeredResources[uri.toString()];\n                if (resource !== undefined) {\n                    return resource.enabled ? resource.scopeChallenge?.(context) : undefined;\n                }\n\n                for (const template of Object.values(this._registeredResourceTemplates)) {\n                    const variables = template.resourceTemplate.uriTemplate.match(uri.toString());\n                    if (variables) {\n                        return template.enabled ? template.scopeChallenge?.(context) : undefined;\n                    }\n                }\n                return;\n            }\n            case 'prompts/get': {\n                const promptName = (context.request.params as { name?: unknown } | undefined)?.name;\n                if (typeof promptName !== 'string') return;\n                const prompt = this._registeredPrompts[promptName];\n                if (prompt === undefined || !prompt.enabled) return;\n                return prompt.scopeChallenge?.(context);\n            }\n            default: {\n                return;\n            }\n        }\n    };\n\n    private _toolHandlersInitialized = false;\n\n    private setToolRequestHandlers() {\n        if (this._toolHandlersInitialized) {\n            return;\n        }\n\n        this.server.assertCanSetRequestHandler('tools/list');\n        this.server.assertCanSetRequestHandler('tools/call');\n\n        this.server.registerCapabilities({\n            tools: {\n                listChanged: this.server.getCapabilities().tools?.listChanged ?? true\n            }\n        });\n\n        // Note: tools are listed in registration (insertion) order, which keeps the ordering\n        // deterministic across requests when the underlying tool set has not changed, as\n        // recommended by the spec.\n        this.server.setRequestHandler(\n            'tools/list',\n            (): ListToolsResult => ({\n                tools: Object.entries(this._registeredTools)\n                    .filter(([, tool]) => tool.enabled)\n                    .map(([name, tool]): Tool => {\n                        const toolDefinition: Tool = {\n                            name,\n                            title: tool.title,\n                            description: tool.description,\n                            inputSchema: tool.inputSchema\n                                ? (convertListedInputSchema(name, tool.inputSchema) as Tool['inputSchema'])\n                                : EMPTY_OBJECT_JSON_SCHEMA,\n                            annotations: tool.annotations,\n                            icons: tool.icons,\n                            execution: tool.execution,\n                            _meta: tool._meta\n                        };\n\n                        if (tool.outputSchema) {\n                            // SEP-2106 legacy interop (non-object outputSchema roots wrapped in\n                            // `{type:'object',properties:{result:<natural>},required:['result']}` toward\n                            // 2025-era clients) lives in the 2025 wire codec's `encodeResult('tools/list', …)`\n                            // — this handler is era-blind and emits the natural converted schema.\n                            toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, 'output') as Tool['outputSchema'];\n                        }\n\n                        return toolDefinition;\n                    })\n            })\n        );\n\n        this.server.setRequestHandler('tools/call', async (request, ctx): Promise<CallToolResult | InputRequiredResult> => {\n            const tool = this._registeredTools[request.params.name];\n            if (!tool) {\n                throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`);\n            }\n            if (!tool.enabled) {\n                throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);\n            }\n\n            try {\n                const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);\n                const result = await this.executeToolHandler(tool, args, ctx);\n                await this.validateToolOutput(tool, result, request.params.name);\n                if (isInputRequiredResult(result)) return result;\n                // SEP-2106 result-side projection (the era-agnostic TextContent auto-append; the\n                // `{result:…}` wrap on the 2025 era) lives behind the wire codec's\n                // `projectCallToolResult`. The codec receives the SAME advertised JSON Schema\n                // `tools/list` emits (and that the codec's `encodeResult('tools/list', …)` may have\n                // wrapped) so the listing and the call cannot diverge.\n                return this.server.projectCallToolResult(result, tool.outputSchemaJson);\n            } catch (error) {\n                if (error instanceof ProtocolError && error.code === ProtocolErrorCode.UrlElicitationRequired) {\n                    throw error; // Return the error to the caller without wrapping in CallToolResult\n                }\n                return this.createToolError(error instanceof Error ? error.message : String(error));\n            }\n        });\n\n        this._toolHandlersInitialized = true;\n    }\n\n    /**\n     * Creates a tool error result.\n     *\n     * @param errorMessage - The error message.\n     * @returns The tool error result.\n     */\n    private createToolError(errorMessage: string): CallToolResult {\n        return {\n            content: [\n                {\n                    type: 'text',\n                    text: errorMessage\n                }\n            ],\n            isError: true\n        };\n    }\n\n    /**\n     * Validates tool input arguments against the tool's input schema.\n     */\n    private async validateToolInput<\n        ToolType extends RegisteredTool,\n        Args extends ToolType['inputSchema'] extends infer InputSchema\n            ? InputSchema extends StandardSchemaWithJSON\n                ? StandardSchemaWithJSON.InferOutput<InputSchema>\n                : undefined\n            : undefined\n    >(tool: ToolType, args: Args, toolName: string): Promise<Args> {\n        if (\n            this._maxToolInputElements !== undefined &&\n            toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements\n        ) {\n            throw new ProtocolError(\n                ProtocolErrorCode.InvalidParams,\n                `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`\n            );\n        }\n\n        if (!tool.inputSchema) {\n            return undefined as Args;\n        }\n\n        const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {});\n        if (!parseResult.success) {\n            throw new ProtocolError(\n                ProtocolErrorCode.InvalidParams,\n                `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`\n            );\n        }\n\n        return parseResult.data as unknown as Args;\n    }\n\n    /**\n     * Validates tool output against the tool's output schema.\n     */\n    private async validateToolOutput(tool: RegisteredTool, result: CallToolResult | InputRequiredResult, toolName: string): Promise<void> {\n        if (!tool.outputSchema) {\n            return;\n        }\n\n        // An input-required result is not the tool's final output: structured\n        // content is only required (and validated) on the completing result.\n        if (isInputRequiredResult(result)) {\n            return;\n        }\n\n        if (result.isError) {\n            return;\n        }\n\n        // SEP-2106: `structuredContent` may legally be any JSON value including `null`, `0`,\n        // `false`, `\"\"`. The presence check is therefore `=== undefined` (not falsy); when present,\n        // the value is ALWAYS validated against the output schema — a falsy value against an\n        // object-typed schema fails validation, so this is not a guard weakening.\n        if (result.structuredContent === undefined) {\n            throw new ProtocolError(\n                ProtocolErrorCode.InvalidParams,\n                `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`\n            );\n        }\n\n        // if the tool has an output schema, validate structured content\n        const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent);\n        if (!parseResult.success) {\n            throw new ProtocolError(\n                ProtocolErrorCode.InvalidParams,\n                `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`\n            );\n        }\n    }\n\n    /**\n     * Executes a tool handler.\n     */\n    private async executeToolHandler(\n        tool: RegisteredTool,\n        args: unknown,\n        ctx: ServerContext\n    ): Promise<CallToolResult | InputRequiredResult> {\n        // Executor encapsulates handler invocation with proper types\n        return tool.executor(args, ctx);\n    }\n\n    private _completionHandlerInitialized = false;\n\n    private setCompletionRequestHandler() {\n        if (this._completionHandlerInitialized) {\n            return;\n        }\n\n        this.server.assertCanSetRequestHandler('completion/complete');\n\n        this.server.registerCapabilities({\n            completions: {}\n        });\n\n        this.server.setRequestHandler('completion/complete', async (request): Promise<CompleteResult> => {\n            switch (request.params.ref.type) {\n                case 'ref/prompt': {\n                    assertCompleteRequestPrompt(request);\n                    return this.handlePromptCompletion(request, request.params.ref);\n                }\n\n                case 'ref/resource': {\n                    assertCompleteRequestResourceTemplate(request);\n                    return this.handleResourceCompletion(request, request.params.ref);\n                }\n\n                default: {\n                    throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);\n                }\n            }\n        });\n\n        this._completionHandlerInitialized = true;\n    }\n\n    private async handlePromptCompletion(request: CompleteRequestPrompt, ref: PromptReference): Promise<CompleteResult> {\n        const prompt = this._registeredPrompts[ref.name];\n        if (!prompt) {\n            throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`);\n        }\n\n        if (!prompt.enabled) {\n            throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);\n        }\n\n        if (!prompt.argsSchema) {\n            return EMPTY_COMPLETION_RESULT;\n        }\n\n        const promptShape = getSchemaShape(prompt.argsSchema);\n        const field = unwrapOptionalSchema(promptShape?.[request.params.argument.name]);\n        if (!isCompletable(field)) {\n            return EMPTY_COMPLETION_RESULT;\n        }\n\n        const completer = getCompleter(field);\n        if (!completer) {\n            return EMPTY_COMPLETION_RESULT;\n        }\n\n        const suggestions = await completer(request.params.argument.value, request.params.context);\n        return createCompletionResult(suggestions);\n    }\n\n    private async handleResourceCompletion(\n        request: CompleteRequestResourceTemplate,\n        ref: ResourceTemplateReference\n    ): Promise<CompleteResult> {\n        const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri);\n\n        if (!template) {\n            if (this._registeredResources[ref.uri]) {\n                // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be).\n                return EMPTY_COMPLETION_RESULT;\n            }\n\n            throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);\n        }\n\n        const completer = template.resourceTemplate.completeCallback(request.params.argument.name);\n        if (!completer) {\n            return EMPTY_COMPLETION_RESULT;\n        }\n\n        const suggestions = await completer(request.params.argument.value, request.params.context);\n        return createCompletionResult(suggestions);\n    }\n\n    private _resourceHandlersInitialized = false;\n\n    private setResourceRequestHandlers() {\n        if (this._resourceHandlersInitialized) {\n            return;\n        }\n\n        this.server.assertCanSetRequestHandler('resources/list');\n        this.server.assertCanSetRequestHandler('resources/templates/list');\n        this.server.assertCanSetRequestHandler('resources/read');\n\n        this.server.registerCapabilities({\n            resources: {\n                listChanged: this.server.getCapabilities().resources?.listChanged ?? true\n            }\n        });\n\n        this.server.setRequestHandler('resources/list', async (_request, ctx) => {\n            const resources = Object.entries(this._registeredResources)\n                .filter(([_, resource]) => resource.enabled)\n                .map(([uri, resource]) => ({\n                    uri,\n                    name: resource.name,\n                    ...resource.metadata\n                }));\n\n            const templateResources: Resource[] = [];\n            for (const template of Object.values(this._registeredResourceTemplates)) {\n                if (!template.resourceTemplate.listCallback) {\n                    continue;\n                }\n\n                const result = await template.resourceTemplate.listCallback(ctx);\n                for (const resource of result.resources) {\n                    templateResources.push({\n                        ...template.metadata,\n                        // the defined resource metadata should override the template metadata if present\n                        ...resource\n                    });\n                }\n            }\n\n            return { resources: [...resources, ...templateResources] };\n        });\n\n        this.server.setRequestHandler('resources/templates/list', async () => {\n            const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({\n                name,\n                uriTemplate: template.resourceTemplate.uriTemplate.toString(),\n                ...template.metadata\n            }));\n\n            return { resourceTemplates };\n        });\n\n        this.server.setRequestHandler('resources/read', async (request, ctx) => {\n            let uri: URL;\n            try {\n                uri = new URL(request.params.uri);\n            } catch {\n                throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, {\n                    uri: request.params.uri,\n                    reason: 'invalid_uri'\n                });\n            }\n\n            // First check for exact resource match\n            const resource = this._registeredResources[uri.toString()];\n            if (resource) {\n                if (!resource.enabled) {\n                    throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`);\n                }\n                // A per-resource cache hint is the most specific configured\n                // author for this result's 2026-07-28 cache fields; it rides a\n                // never-serialized carrier and is resolved at the encode seam.\n                return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint);\n            }\n\n            // Then check templates\n            for (const template of Object.values(this._registeredResourceTemplates)) {\n                const variables = template.resourceTemplate.uriTemplate.match(uri.toString());\n                if (variables) {\n                    if (!template.enabled) {\n                        throw new ProtocolError(\n                            ProtocolErrorCode.InvalidParams,\n                            `Resource template ${template.resourceTemplate.uriTemplate} disabled`\n                        );\n                    }\n                    return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);\n                }\n            }\n\n            // Domain layer throws one neutral resource-not-found error; the\n            // era-aware encode seam (WireCodec.encodeErrorCode) selects the\n            // wire code (−32602 on every era).\n            throw new ResourceNotFoundError(request.params.uri);\n        });\n\n        this._resourceHandlersInitialized = true;\n    }\n\n    private _promptHandlersInitialized = false;\n\n    private setPromptRequestHandlers() {\n        if (this._promptHandlersInitialized) {\n            return;\n        }\n\n        this.server.assertCanSetRequestHandler('prompts/list');\n        this.server.assertCanSetRequestHandler('prompts/get');\n\n        this.server.registerCapabilities({\n            prompts: {\n                listChanged: this.server.getCapabilities().prompts?.listChanged ?? true\n            }\n        });\n\n        this.server.setRequestHandler(\n            'prompts/list',\n            (): ListPromptsResult => ({\n                prompts: Object.entries(this._registeredPrompts)\n                    .filter(([, prompt]) => prompt.enabled)\n                    .map(([name, prompt]): Prompt => {\n                        return {\n                            name,\n                            title: prompt.title,\n                            description: prompt.description,\n                            arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : undefined,\n                            icons: prompt.icons,\n                            _meta: prompt._meta\n                        };\n                    })\n            })\n        );\n\n        this.server.setRequestHandler('prompts/get', async (request, ctx): Promise<GetPromptResult | InputRequiredResult> => {\n            const prompt = this._registeredPrompts[request.params.name];\n            if (!prompt) {\n                throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);\n            }\n\n            if (!prompt.enabled) {\n                throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);\n            }\n\n            // Handler encapsulates parsing and callback invocation with proper types\n            return prompt.handler(request.params.arguments, ctx);\n        });\n\n        this._promptHandlersInitialized = true;\n    }\n\n    /**\n     * Registers a resource with a config object and callback.\n     * For static resources, use a URI string. For dynamic resources, use a {@linkcode ResourceTemplate}.\n     *\n     * @example\n     * ```ts source=\"./mcp.examples.ts#McpServer_registerResource_static\"\n     * server.registerResource(\n     *     'config',\n     *     'config://app',\n     *     {\n     *         title: 'Application Config',\n     *         mimeType: 'text/plain'\n     *     },\n     *     async uri => ({\n     *         contents: [{ uri: uri.href, text: 'App configuration here' }]\n     *     })\n     * );\n     * ```\n     */\n    registerResource(\n        name: string,\n        uriOrTemplate: string,\n        config: ResourceMetadata & { cacheHint?: CacheHint; scopeChallenge?: ScopeChallengeHandler },\n        readCallback: ReadResourceCallback\n    ): RegisteredResource;\n    registerResource(\n        name: string,\n        uriOrTemplate: ResourceTemplate,\n        config: ResourceMetadata & { cacheHint?: CacheHint; scopeChallenge?: ScopeChallengeHandler },\n        readCallback: ReadResourceTemplateCallback\n    ): RegisteredResourceTemplate;\n    registerResource(\n        name: string,\n        uriOrTemplate: string | ResourceTemplate,\n        config: ResourceMetadata & { cacheHint?: CacheHint; scopeChallenge?: ScopeChallengeHandler },\n        readCallback: ReadResourceCallback | ReadResourceTemplateCallback\n    ): RegisteredResource | RegisteredResourceTemplate {\n        // These options configure request handling and are not advertised as\n        // resource metadata by `resources/list`.\n        const { cacheHint, scopeChallenge, ...resourceMetadata } = config;\n        const metadata: ResourceMetadata = resourceMetadata;\n        if (cacheHint !== undefined) {\n            assertValidCacheHint(cacheHint, `resource ${name}`);\n        }\n\n        if (typeof uriOrTemplate === 'string') {\n            if (this._registeredResources[uriOrTemplate]) {\n                throw new Error(`Resource ${uriOrTemplate} is already registered`);\n            }\n\n            const registeredResource = this._createRegisteredResource(\n                name,\n                (config as BaseMetadata).title,\n                uriOrTemplate,\n                metadata,\n                scopeChallenge,\n                readCallback as ReadResourceCallback\n            );\n            if (cacheHint !== undefined) {\n                registeredResource.cacheHint = cacheHint;\n            }\n\n            this.setResourceRequestHandlers();\n            this.sendResourceListChanged();\n            return registeredResource;\n        } else {\n            if (this._registeredResourceTemplates[name]) {\n                throw new Error(`Resource template ${name} is already registered`);\n            }\n\n            const registeredResourceTemplate = this._createRegisteredResourceTemplate(\n                name,\n                (config as BaseMetadata).title,\n                uriOrTemplate,\n                metadata,\n                scopeChallenge,\n                readCallback as ReadResourceTemplateCallback\n            );\n            if (cacheHint !== undefined) {\n                registeredResourceTemplate.cacheHint = cacheHint;\n            }\n\n            this.setResourceRequestHandlers();\n            this.sendResourceListChanged();\n            return registeredResourceTemplate;\n        }\n    }\n\n    private _createRegisteredResource(\n        name: string,\n        title: string | undefined,\n        uri: string,\n        metadata: ResourceMetadata | undefined,\n        scopeChallenge: ScopeChallengeHandler | undefined,\n        readCallback: ReadResourceCallback\n    ): RegisteredResource {\n        const registeredResource: RegisteredResource = {\n            name,\n            title,\n            metadata,\n            readCallback,\n            scopeChallenge,\n            enabled: true,\n            disable: () => registeredResource.update({ enabled: false }),\n            enable: () => registeredResource.update({ enabled: true }),\n            remove: () => registeredResource.update({ uri: null }),\n            update: updates => {\n                if (updates.uri !== undefined && updates.uri !== uri) {\n                    delete this._registeredResources[uri];\n                    if (updates.uri) this._registeredResources[updates.uri] = registeredResource;\n                }\n                if (updates.name !== undefined) registeredResource.name = updates.name;\n                if (updates.title !== undefined) registeredResource.title = updates.title;\n                if (updates.metadata !== undefined) registeredResource.metadata = updates.metadata;\n                if (updates.callback !== undefined) registeredResource.readCallback = updates.callback;\n                if (updates.scopeChallenge !== undefined) {\n                    registeredResource.scopeChallenge = updates.scopeChallenge === null ? undefined : updates.scopeChallenge;\n                }\n                if (updates.enabled !== undefined) registeredResource.enabled = updates.enabled;\n                this.sendResourceListChanged();\n            }\n        };\n        this._registeredResources[uri] = registeredResource;\n        return registeredResource;\n    }\n\n    private _createRegisteredResourceTemplate(\n        name: string,\n        title: string | undefined,\n        template: ResourceTemplate,\n        metadata: ResourceMetadata | undefined,\n        scopeChallenge: ScopeChallengeHandler | undefined,\n        readCallback: ReadResourceTemplateCallback\n    ): RegisteredResourceTemplate {\n        const registeredResourceTemplate: RegisteredResourceTemplate = {\n            resourceTemplate: template,\n            title,\n            metadata,\n            readCallback,\n            scopeChallenge,\n            enabled: true,\n            disable: () => registeredResourceTemplate.update({ enabled: false }),\n            enable: () => registeredResourceTemplate.update({ enabled: true }),\n            remove: () => registeredResourceTemplate.update({ name: null }),\n            update: updates => {\n                if (updates.name !== undefined && updates.name !== name) {\n                    delete this._registeredResourceTemplates[name];\n                    if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;\n                }\n                if (updates.title !== undefined) registeredResourceTemplate.title = updates.title;\n                if (updates.template !== undefined) registeredResourceTemplate.resourceTemplate = updates.template;\n                if (updates.metadata !== undefined) registeredResourceTemplate.metadata = updates.metadata;\n                if (updates.callback !== undefined) registeredResourceTemplate.readCallback = updates.callback;\n                if (updates.scopeChallenge !== undefined) {\n                    registeredResourceTemplate.scopeChallenge = updates.scopeChallenge === null ? undefined : updates.scopeChallenge;\n                }\n                if (updates.enabled !== undefined) registeredResourceTemplate.enabled = updates.enabled;\n                this.sendResourceListChanged();\n            }\n        };\n        this._registeredResourceTemplates[name] = registeredResourceTemplate;\n\n        // If the resource template has any completion callbacks, enable completions capability\n        const variableNames = template.uriTemplate.variableNames;\n        const hasCompleter = Array.isArray(variableNames) && variableNames.some(v => !!template.completeCallback(v));\n        if (hasCompleter) {\n            this.setCompletionRequestHandler();\n        }\n\n        return registeredResourceTemplate;\n    }\n\n    private _createRegisteredPrompt(\n        name: string,\n        title: string | undefined,\n        description: string | undefined,\n        argsSchema: StandardSchemaWithJSON | undefined,\n        callback: PromptCallback<StandardSchemaWithJSON | undefined>,\n        icons: Icon[] | undefined,\n        scopeChallenge: ScopeChallengeHandler | undefined,\n        _meta: Record<string, unknown> | undefined\n    ): RegisteredPrompt {\n        // Track current schema and callback for handler regeneration\n        let currentArgsSchema = argsSchema;\n        let currentCallback = callback;\n\n        const registeredPrompt: RegisteredPrompt = {\n            title,\n            description,\n            argsSchema,\n            icons,\n            scopeChallenge,\n            _meta,\n            handler: createPromptHandler(name, argsSchema, callback),\n            enabled: true,\n            disable: () => registeredPrompt.update({ enabled: false }),\n            enable: () => registeredPrompt.update({ enabled: true }),\n            remove: () => registeredPrompt.update({ name: null }),\n            update: updates => {\n                if (updates.name !== undefined && updates.name !== name) {\n                    delete this._registeredPrompts[name];\n                    if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt;\n                }\n                if (updates.title !== undefined) registeredPrompt.title = updates.title;\n                if (updates.description !== undefined) registeredPrompt.description = updates.description;\n                if (updates.icons !== undefined) registeredPrompt.icons = updates.icons;\n                if (updates.scopeChallenge !== undefined) {\n                    registeredPrompt.scopeChallenge = updates.scopeChallenge === null ? undefined : updates.scopeChallenge;\n                }\n                if (updates._meta !== undefined) registeredPrompt._meta = updates._meta;\n\n                // Track if we need to regenerate the handler\n                let needsHandlerRegen = false;\n                if (updates.argsSchema !== undefined) {\n                    registeredPrompt.argsSchema = updates.argsSchema;\n                    currentArgsSchema = updates.argsSchema;\n                    needsHandlerRegen = true;\n                }\n                if (updates.callback !== undefined) {\n                    currentCallback = updates.callback as PromptCallback<StandardSchemaWithJSON | undefined>;\n                    needsHandlerRegen = true;\n                }\n                if (needsHandlerRegen) {\n                    registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback);\n                }\n\n                if (updates.enabled !== undefined) registeredPrompt.enabled = updates.enabled;\n                this.sendPromptListChanged();\n            }\n        };\n        this._registeredPrompts[name] = registeredPrompt;\n\n        // If any argument uses a Completable schema, enable completions capability\n        if (argsSchema) {\n            const shape = getSchemaShape(argsSchema);\n            if (shape) {\n                const hasCompletable = Object.values(shape).some(field => {\n                    const inner = unwrapOptionalSchema(field);\n                    return isCompletable(inner);\n                });\n                if (hasCompletable) {\n                    this.setCompletionRequestHandler();\n                }\n            }\n        }\n\n        return registeredPrompt;\n    }\n\n    private _createRegisteredTool(\n        name: string,\n        title: string | undefined,\n        description: string | undefined,\n        inputSchema: StandardSchemaWithJSON | undefined,\n        outputSchema: StandardSchemaWithJSON | undefined,\n        annotations: ToolAnnotations | undefined,\n        icons: Icon[] | undefined,\n        execution: ToolExecution | undefined,\n        scopeChallenge: ScopeChallengeHandler | undefined,\n        _meta: Record<string, unknown> | undefined,\n        handler: AnyToolHandler<StandardSchemaWithJSON | undefined>\n    ): RegisteredTool {\n        // Validate tool name according to SEP specification\n        validateAndWarnToolName(name);\n\n        // Track current handler for executor regeneration\n        let currentHandler = handler;\n\n        let outputSchemaJson: Record<string, unknown> | undefined;\n        const registeredTool: RegisteredTool = {\n            title,\n            description,\n            inputSchema,\n            outputSchema,\n            get outputSchemaJson() {\n                return (outputSchemaJson ??= convertOutputSchemaJson(registeredTool.outputSchema));\n            },\n            set outputSchemaJson(value) {\n                outputSchemaJson = value;\n            },\n            annotations,\n            icons,\n            execution,\n            scopeChallenge,\n            _meta,\n            handler: handler,\n            executor: createToolExecutor(inputSchema, handler),\n            enabled: true,\n            disable: () => registeredTool.update({ enabled: false }),\n            enable: () => registeredTool.update({ enabled: true }),\n            remove: () => registeredTool.update({ name: null }),\n            update: updates => {\n                // The closure's `name` tracks the CURRENT registry key, not\n                // the original registration name — renaming reassigns it so\n                // subsequent paramsSchema/rename invalidations evict the live\n                // `_toolInputSchemaJson` slot rather than the original.\n                if (updates.name !== undefined && updates.name !== name) {\n                    if (typeof updates.name === 'string') {\n                        validateAndWarnToolName(updates.name);\n                    }\n                    delete this._registeredTools[name];\n                    delete this._toolInputSchemaJson[name];\n                    if (updates.name) {\n                        // The TARGET key may already be occupied by another\n                        // tool (rename has no duplicate-name guard) — drop\n                        // its memo too, otherwise `toolInputSchemaJson()`\n                        // returns the displaced tool's converted schema and\n                        // the SEP-2243 pre-dispatch validation runs against\n                        // the wrong schema for this name.\n                        delete this._toolInputSchemaJson[updates.name];\n                        this._registeredTools[updates.name] = registeredTool;\n                        name = updates.name;\n                    }\n                }\n                if (updates.title !== undefined) registeredTool.title = updates.title;\n                if (updates.description !== undefined) registeredTool.description = updates.description;\n\n                // Track if we need to regenerate the executor\n                let needsExecutorRegen = false;\n                if (updates.paramsSchema !== undefined) {\n                    registeredTool.inputSchema = updates.paramsSchema;\n                    delete this._toolInputSchemaJson[name];\n                    needsExecutorRegen = true;\n                }\n                if (updates.callback !== undefined) {\n                    registeredTool.handler = updates.callback;\n                    currentHandler = updates.callback as AnyToolHandler<StandardSchemaWithJSON | undefined>;\n                    needsExecutorRegen = true;\n                }\n                if (needsExecutorRegen) {\n                    registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler);\n                }\n\n                if (updates.outputSchema !== undefined) {\n                    registeredTool.outputSchema = updates.outputSchema;\n                    registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema);\n                }\n                if (updates.annotations !== undefined) registeredTool.annotations = updates.annotations;\n                if (updates.icons !== undefined) registeredTool.icons = updates.icons;\n                if (updates.scopeChallenge !== undefined) {\n                    registeredTool.scopeChallenge = updates.scopeChallenge === null ? undefined : updates.scopeChallenge;\n                }\n                if (updates._meta !== undefined) registeredTool._meta = updates._meta;\n                if (updates.enabled !== undefined) registeredTool.enabled = updates.enabled;\n                this.sendToolListChanged();\n            }\n        };\n        this._registeredTools[name] = registeredTool;\n\n        this.setToolRequestHandlers();\n        this.sendToolListChanged();\n\n        return registeredTool;\n    }\n\n    /**\n     * Registers a tool with a config object and callback.\n     *\n     * @example\n     * ```ts source=\"./mcp.examples.ts#McpServer_registerTool_basic\"\n     * server.registerTool(\n     *     'calculate-bmi',\n     *     {\n     *         title: 'BMI Calculator',\n     *         description: 'Calculate Body Mass Index',\n     *         inputSchema: z.object({\n     *             weightKg: z.number(),\n     *             heightM: z.number()\n     *         }),\n     *         outputSchema: z.object({ bmi: z.number() })\n     *     },\n     *     async ({ weightKg, heightM }) => {\n     *         const output = { bmi: weightKg / (heightM * heightM) };\n     *         return {\n     *             content: [{ type: 'text', text: JSON.stringify(output) }],\n     *             structuredContent: output\n     *         };\n     *     }\n     * );\n     * ```\n     */\n    registerTool<OutputArgs extends StandardSchemaWithJSON, InputArgs extends StandardSchemaWithJSON | undefined = undefined>(\n        name: string,\n        config: {\n            title?: string;\n            description?: string;\n            inputSchema?: InputArgs;\n            outputSchema?: OutputArgs;\n            annotations?: ToolAnnotations;\n            icons?: Icon[];\n            /** Determines whether this tool call needs an OAuth scope challenge. */\n            scopeChallenge?: ScopeChallengeHandler;\n            _meta?: Record<string, unknown>;\n        },\n        cb: ToolCallback<InputArgs>\n    ): RegisteredTool;\n    /** @deprecated Wrap with `z.object({...})` instead. Raw-shape form: `inputSchema`/`outputSchema` may be a plain `{ field: z.string() }` record; it is auto-wrapped with `z.object()`. */\n    registerTool<InputArgs extends ZodRawShape, OutputArgs extends ZodRawShape | StandardSchemaWithJSON | undefined = undefined>(\n        name: string,\n        config: {\n            title?: string;\n            description?: string;\n            inputSchema?: InputArgs;\n            outputSchema?: OutputArgs;\n            annotations?: ToolAnnotations;\n            icons?: Icon[];\n            scopeChallenge?: ScopeChallengeHandler;\n            _meta?: Record<string, unknown>;\n        },\n        cb: LegacyToolCallback<InputArgs>\n    ): RegisteredTool;\n    registerTool(\n        name: string,\n        config: {\n            title?: string;\n            description?: string;\n            inputSchema?: StandardSchemaWithJSON | ZodRawShape;\n            outputSchema?: StandardSchemaWithJSON | ZodRawShape;\n            annotations?: ToolAnnotations;\n            icons?: Icon[];\n            scopeChallenge?: ScopeChallengeHandler;\n            _meta?: Record<string, unknown>;\n        },\n        cb: ToolCallback<StandardSchemaWithJSON | undefined> | LegacyToolCallback<ZodRawShape>\n    ): RegisteredTool {\n        if (this._registeredTools[name]) {\n            throw new Error(`Tool ${name} is already registered`);\n        }\n\n        const { title, description, inputSchema, outputSchema, annotations, icons, scopeChallenge, _meta } = config;\n        return this._createRegisteredTool(\n            name,\n            title,\n            description,\n            normalizeRawShapeSchema(inputSchema),\n            normalizeRawShapeSchema(outputSchema),\n            annotations,\n            icons,\n            undefined,\n            scopeChallenge,\n            _meta,\n            cb as ToolCallback<StandardSchemaWithJSON | undefined>\n        );\n    }\n\n    /**\n     * Registers a prompt with a config object and callback.\n     *\n     * @example\n     * ```ts source=\"./mcp.examples.ts#McpServer_registerPrompt_basic\"\n     * server.registerPrompt(\n     *     'review-code',\n     *     {\n     *         title: 'Code Review',\n     *         description: 'Review code for best practices',\n     *         argsSchema: z.object({ code: z.string() })\n     *     },\n     *     ({ code }) => ({\n     *         messages: [\n     *             {\n     *                 role: 'user' as const,\n     *                 content: {\n     *                     type: 'text' as const,\n     *                     text: `Please review this code:\\n\\n${code}`\n     *                 }\n     *             }\n     *         ]\n     *     })\n     * );\n     * ```\n     */\n    registerPrompt(\n        name: string,\n        config: {\n            title?: string;\n            description?: string;\n            argsSchema?: undefined;\n            icons?: Icon[];\n            /** Determines whether this prompt retrieval needs an OAuth scope challenge. */\n            scopeChallenge?: ScopeChallengeHandler;\n            _meta?: Record<string, unknown>;\n        },\n        cb: PromptCallback\n    ): RegisteredPrompt;\n    registerPrompt<Args extends StandardSchemaWithJSON>(\n        name: string,\n        config: {\n            title?: string;\n            description?: string;\n            argsSchema?: Args;\n            icons?: Icon[];\n            /** Determines whether this prompt retrieval needs an OAuth scope challenge. */\n            scopeChallenge?: ScopeChallengeHandler;\n            _meta?: Record<string, unknown>;\n        },\n        cb: PromptCallback<Args>\n    ): RegisteredPrompt;\n    /** @deprecated Wrap with `z.object({...})` instead. Raw-shape form: `argsSchema` may be a plain `{ field: z.string() }` record; it is auto-wrapped with `z.object()`. */\n    registerPrompt<Args extends ZodRawShape>(\n        name: string,\n        config: {\n            title?: string;\n            description?: string;\n            argsSchema?: Args;\n            icons?: Icon[];\n            scopeChallenge?: ScopeChallengeHandler;\n            _meta?: Record<string, unknown>;\n        },\n        cb: LegacyPromptCallback<Args>\n    ): RegisteredPrompt;\n    registerPrompt(\n        name: string,\n        config: {\n            title?: string;\n            description?: string;\n            argsSchema?: StandardSchemaWithJSON | ZodRawShape;\n            icons?: Icon[];\n            scopeChallenge?: ScopeChallengeHandler;\n            _meta?: Record<string, unknown>;\n        },\n        cb: PromptCallback | PromptCallback<StandardSchemaWithJSON> | LegacyPromptCallback<ZodRawShape>\n    ): RegisteredPrompt {\n        if (this._registeredPrompts[name]) {\n            throw new Error(`Prompt ${name} is already registered`);\n        }\n\n        const { title, description, argsSchema, icons, scopeChallenge, _meta } = config;\n\n        const registeredPrompt = this._createRegisteredPrompt(\n            name,\n            title,\n            description,\n            normalizeRawShapeSchema(argsSchema),\n            cb as PromptCallback<StandardSchemaWithJSON | undefined>,\n            icons,\n            scopeChallenge,\n            _meta\n        );\n\n        this.setPromptRequestHandlers();\n        this.sendPromptListChanged();\n\n        return registeredPrompt;\n    }\n\n    /**\n     * Checks if the server is connected to a transport.\n     * @returns `true` if the server is connected\n     */\n    isConnected() {\n        return this.server.transport !== undefined;\n    }\n\n    /**\n     * Sends a logging message to the client, if connected.\n     * Note: You only need to send the parameters object, not the entire JSON-RPC message.\n     * @see {@linkcode LoggingMessageNotification}\n     * @param params\n     * @param sessionId Optional for stateless transports and backward compatibility.\n     *\n     * @example\n     * ```ts source=\"./mcp.examples.ts#McpServer_sendLoggingMessage_basic\"\n     * await server.sendLoggingMessage({\n     *     level: 'info',\n     *     data: 'Processing complete'\n     * });\n     * ```\n     *\n     * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n     * Remains functional during the deprecation window (at least twelve months).\n     * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n     */\n    async sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string) {\n        return this.server.sendLoggingMessage(params, sessionId);\n    }\n    /**\n     * Sends a resource list changed event to the client, if connected.\n     */\n    sendResourceListChanged() {\n        if (this.isConnected()) {\n            this.server.sendResourceListChanged();\n        }\n    }\n\n    /**\n     * Sends a tool list changed event to the client, if connected.\n     */\n    sendToolListChanged() {\n        if (this.isConnected()) {\n            this.server.sendToolListChanged();\n        }\n    }\n\n    /**\n     * Sends a prompt list changed event to the client, if connected.\n     */\n    sendPromptListChanged() {\n        if (this.isConnected()) {\n            this.server.sendPromptListChanged();\n        }\n    }\n}\n\n/**\n * A callback to complete one variable within a resource template's URI template.\n */\nexport type CompleteResourceTemplateCallback = (\n    value: string,\n    context?: {\n        arguments?: Record<string, string>;\n    }\n) => string[] | Promise<string[]>;\n\n/**\n * A resource template combines a URI pattern with optional functionality to enumerate\n * all resources matching that pattern.\n */\nexport class ResourceTemplate {\n    private _uriTemplate: UriTemplate;\n\n    constructor(\n        uriTemplate: string | UriTemplate,\n        private _callbacks: {\n            /**\n             * A callback to list all resources matching this template. This is required to be specified, even if `undefined`, to avoid accidentally forgetting resource listing.\n             */\n            list: ListResourcesCallback | undefined;\n\n            /**\n             * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values.\n             */\n            complete?: {\n                [variable: string]: CompleteResourceTemplateCallback;\n            };\n        }\n    ) {\n        this._uriTemplate = typeof uriTemplate === 'string' ? new UriTemplate(uriTemplate) : uriTemplate;\n    }\n\n    /**\n     * Gets the URI template pattern.\n     */\n    get uriTemplate(): UriTemplate {\n        return this._uriTemplate;\n    }\n\n    /**\n     * Gets the list callback, if one was provided.\n     */\n    get listCallback(): ListResourcesCallback | undefined {\n        return this._callbacks.list;\n    }\n\n    /**\n     * Gets the callback for completing a specific URI template variable, if one was provided.\n     */\n    completeCallback(variable: string): CompleteResourceTemplateCallback | undefined {\n        return this._callbacks.complete?.[variable];\n    }\n}\n\n/**\n * A plain record of Zod field schemas, e.g. `{ name: z.string() }`. Accepted by\n * `registerTool`/`registerPrompt` as a shorthand; auto-wrapped with `z.object()`.\n * Zod schemas only — `z.object()` cannot wrap other Standard Schema libraries.\n */\nexport type ZodRawShape = Record<string, z.ZodType>;\n\n/** Infers the parsed-output type of a {@linkcode ZodRawShape}. */\nexport type InferRawShape<S extends ZodRawShape> = z.infer<z.ZodObject<S>>;\n\n/** {@linkcode ToolCallback} variant used when `inputSchema` is a {@linkcode ZodRawShape}. */\nexport type LegacyToolCallback<Args extends ZodRawShape | undefined> = Args extends ZodRawShape\n    ? (\n          args: InferRawShape<Args>,\n          ctx: ServerContext\n      ) => CallToolResult | InputRequiredResult | Promise<CallToolResult | InputRequiredResult>\n    : (ctx: ServerContext) => CallToolResult | InputRequiredResult | Promise<CallToolResult | InputRequiredResult>;\n\n/** {@linkcode PromptCallback} variant used when `argsSchema` is a {@linkcode ZodRawShape}. */\nexport type LegacyPromptCallback<Args extends ZodRawShape | undefined> = Args extends ZodRawShape\n    ? (\n          args: InferRawShape<Args>,\n          ctx: ServerContext\n      ) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>\n    : (ctx: ServerContext) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>;\n\nexport type BaseToolCallback<\n    SendResultT extends Result,\n    Ctx extends ServerContext,\n    Args extends StandardSchemaWithJSON | undefined\n> = Args extends StandardSchemaWithJSON\n    ? (args: StandardSchemaWithJSON.InferOutput<Args>, ctx: Ctx) => SendResultT | Promise<SendResultT>\n    : (ctx: Ctx) => SendResultT | Promise<SendResultT>;\n\n/**\n * Callback for a tool handler registered with {@linkcode McpServer.registerTool}.\n */\nexport type ToolCallback<Args extends StandardSchemaWithJSON | undefined = undefined> = BaseToolCallback<\n    CallToolResult | InputRequiredResult,\n    ServerContext,\n    Args\n>;\n\n/**\n * Tool handler callback type.\n */\nexport type AnyToolHandler<Args extends StandardSchemaWithJSON | undefined = undefined> = ToolCallback<Args>;\n\n/**\n * Internal executor type that encapsulates handler invocation with proper types.\n */\ntype ToolExecutor = (args: unknown, ctx: ServerContext) => Promise<CallToolResult | InputRequiredResult>;\n\nexport type RegisteredTool = {\n    title?: string;\n    description?: string;\n    inputSchema?: StandardSchemaWithJSON;\n    outputSchema?: StandardSchemaWithJSON;\n    /**\n     * @hidden\n     * The converted JSON Schema of `outputSchema`, memoised on first use (and on\n     * `update({outputSchema})`) so the `tools/call` handler passes the SAME advertised schema\n     * `tools/list` emits to the wire codec's `projectCallToolResult` — the SEP-2106 `{result:…}`\n     * wrap predicate follows the schema's root, never the runtime value shape. `undefined` when\n     * no `outputSchema` is registered or its conversion threw (see {@link convertOutputSchemaJson}).\n     */\n    outputSchemaJson?: Record<string, unknown>;\n    annotations?: ToolAnnotations;\n    icons?: Icon[];\n    execution?: ToolExecution;\n    scopeChallenge?: ScopeChallengeHandler;\n    _meta?: Record<string, unknown>;\n    handler: AnyToolHandler<StandardSchemaWithJSON | undefined>;\n    /** @hidden */\n    executor: ToolExecutor;\n    enabled: boolean;\n    enable(): void;\n    disable(): void;\n    update(updates: {\n        name?: string | null;\n        title?: string;\n        description?: string;\n        paramsSchema?: StandardSchemaWithJSON;\n        outputSchema?: StandardSchemaWithJSON;\n        annotations?: ToolAnnotations;\n        icons?: Icon[];\n        scopeChallenge?: ScopeChallengeHandler | null;\n        _meta?: Record<string, unknown>;\n        callback?: ToolCallback<StandardSchemaWithJSON>;\n        enabled?: boolean;\n    }): void;\n    remove(): void;\n};\n\n/**\n * Creates an executor that invokes the handler with the appropriate arguments.\n * When `inputSchema` is defined, the handler is called with `(args, ctx)`.\n * When `inputSchema` is undefined, the handler is called with just `(ctx)`.\n */\nfunction createToolExecutor(\n    inputSchema: StandardSchemaWithJSON | undefined,\n    handler: AnyToolHandler<StandardSchemaWithJSON | undefined>\n): ToolExecutor {\n    if (inputSchema) {\n        const callback = handler as ToolCallbackInternal;\n        return async (args, ctx) => callback(args, ctx);\n    }\n\n    // When no inputSchema, call with just ctx (the handler expects (ctx) signature)\n    const callback = handler as (\n        ctx: ServerContext\n    ) => CallToolResult | InputRequiredResult | Promise<CallToolResult | InputRequiredResult>;\n    return async (_args, ctx) => callback(ctx);\n}\n\nconst EMPTY_OBJECT_JSON_SCHEMA = {\n    type: 'object' as const,\n    properties: {}\n};\n\n/** Converts a tool's `inputSchema` for `tools/list` and warns on an invalid SEP-2243 `x-mcp-header` declaration. */\nfunction convertListedInputSchema(name: string, inputSchema: StandardSchemaWithJSON): Record<string, unknown> {\n    const json = standardSchemaToJsonSchema(inputSchema, 'input');\n    const scan = scanXMcpHeaderDeclarations(json);\n    if (!scan.valid) {\n        console.warn(\n            `[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by ` +\n                `conforming Streamable HTTP clients: ${scan.reason}`\n        );\n    }\n    return json;\n}\n\n/**\n * Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson}\n * so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that\n * `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion\n * failure yields `undefined` so the failure surfaces where it always has (`tools/list`).\n */\nfunction convertOutputSchemaJson(outputSchema: StandardSchemaWithJSON | undefined): Record<string, unknown> | undefined {\n    if (outputSchema === undefined) return undefined;\n    try {\n        return standardSchemaToJsonSchema(outputSchema, 'output');\n    } catch {\n        return undefined;\n    }\n}\n\n/**\n * Additional, optional information for annotating a resource.\n */\nexport type ResourceMetadata = Omit<Resource, 'uri' | 'name'>;\n\n/**\n * Callback to list all resources matching a given template.\n */\nexport type ListResourcesCallback = (ctx: ServerContext) => ListResourcesResult | Promise<ListResourcesResult>;\n\n/**\n * Callback to read a resource at a given URI.\n */\nexport type ReadResourceCallback = (\n    uri: URL,\n    ctx: ServerContext\n) => ReadResourceResult | InputRequiredResult | Promise<ReadResourceResult | InputRequiredResult>;\n\nexport type RegisteredResource = {\n    name: string;\n    title?: string;\n    metadata?: ResourceMetadata;\n    /** Cache hint applied to this resource's `resources/read` results on the 2026-07-28 revision. */\n    cacheHint?: CacheHint;\n    scopeChallenge?: ScopeChallengeHandler;\n    readCallback: ReadResourceCallback;\n    enabled: boolean;\n    enable(): void;\n    disable(): void;\n    update(updates: {\n        name?: string;\n        title?: string;\n        uri?: string | null;\n        metadata?: ResourceMetadata;\n        scopeChallenge?: ScopeChallengeHandler | null;\n        callback?: ReadResourceCallback;\n        enabled?: boolean;\n    }): void;\n    remove(): void;\n};\n\n/**\n * Callback to read a resource at a given URI, following a filled-in URI template.\n */\nexport type ReadResourceTemplateCallback = (\n    uri: URL,\n    variables: Variables,\n    ctx: ServerContext\n) => ReadResourceResult | InputRequiredResult | Promise<ReadResourceResult | InputRequiredResult>;\n\nexport type RegisteredResourceTemplate = {\n    resourceTemplate: ResourceTemplate;\n    title?: string;\n    metadata?: ResourceMetadata;\n    /** Cache hint applied to this template's `resources/read` results on the 2026-07-28 revision. */\n    cacheHint?: CacheHint;\n    scopeChallenge?: ScopeChallengeHandler;\n    readCallback: ReadResourceTemplateCallback;\n    enabled: boolean;\n    enable(): void;\n    disable(): void;\n    update(updates: {\n        name?: string | null;\n        title?: string;\n        template?: ResourceTemplate;\n        metadata?: ResourceMetadata;\n        scopeChallenge?: ScopeChallengeHandler | null;\n        callback?: ReadResourceTemplateCallback;\n        enabled?: boolean;\n    }): void;\n    remove(): void;\n};\n\nexport type PromptCallback<Args extends StandardSchemaWithJSON | undefined = undefined> = Args extends StandardSchemaWithJSON\n    ? (\n          args: StandardSchemaWithJSON.InferOutput<Args>,\n          ctx: ServerContext\n      ) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>\n    : (ctx: ServerContext) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>;\n\n/**\n * Internal handler type that encapsulates parsing and callback invocation.\n * This allows type-safe handling without runtime type assertions.\n */\ntype PromptHandler = (args: Record<string, unknown> | undefined, ctx: ServerContext) => Promise<GetPromptResult | InputRequiredResult>;\n\ntype ToolCallbackInternal = (\n    args: unknown,\n    ctx: ServerContext\n) => CallToolResult | InputRequiredResult | Promise<CallToolResult | InputRequiredResult>;\n\nexport type RegisteredPrompt = {\n    title?: string;\n    description?: string;\n    argsSchema?: StandardSchemaWithJSON;\n    icons?: Icon[];\n    scopeChallenge?: ScopeChallengeHandler;\n    _meta?: Record<string, unknown>;\n    /** @hidden */\n    handler: PromptHandler;\n    enabled: boolean;\n    enable(): void;\n    disable(): void;\n    update<Args extends StandardSchemaWithJSON>(updates: {\n        name?: string | null;\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        icons?: Icon[];\n        scopeChallenge?: ScopeChallengeHandler | null;\n        _meta?: Record<string, unknown>;\n        callback?: PromptCallback<Args>;\n        enabled?: boolean;\n    }): void;\n    remove(): void;\n};\n\n/**\n * Creates a type-safe prompt handler that captures the schema and callback in a closure.\n * This eliminates the need for type assertions at the call site.\n */\nfunction createPromptHandler(\n    name: string,\n    argsSchema: StandardSchemaWithJSON | undefined,\n    callback: PromptCallback<StandardSchemaWithJSON | undefined>\n): PromptHandler {\n    if (argsSchema) {\n        const typedCallback = callback as (\n            args: unknown,\n            ctx: ServerContext\n        ) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>;\n\n        return async (args, ctx) => {\n            const parseResult = await validateStandardSchema(argsSchema, args ?? {});\n            if (!parseResult.success) {\n                throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`);\n            }\n            return typedCallback(parseResult.data, ctx);\n        };\n    } else {\n        const typedCallback = callback as (\n            ctx: ServerContext\n        ) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>;\n\n        return async (_args, ctx) => {\n            return typedCallback(ctx);\n        };\n    }\n}\n\nfunction createCompletionResult(suggestions: readonly unknown[]): CompleteResult {\n    const values = suggestions.map(String).slice(0, 100);\n    return {\n        completion: {\n            values,\n            total: suggestions.length,\n            hasMore: suggestions.length > 100\n        }\n    };\n}\n\nconst EMPTY_COMPLETION_RESULT: CompleteResult = {\n    completion: {\n        values: [],\n        hasMore: false\n    }\n};\n\n/** @internal Gets the shape of a Zod object schema */\nfunction getSchemaShape(schema: unknown): Record<string, unknown> | undefined {\n    const candidate = schema as { shape?: unknown };\n    if (candidate.shape && typeof candidate.shape === 'object') {\n        return candidate.shape as Record<string, unknown>;\n    }\n    return undefined;\n}\n\n/** @internal Checks if a Zod schema is optional */\nfunction isOptionalSchema(schema: unknown): boolean {\n    const candidate = schema as { type?: string } | null | undefined;\n    return candidate?.type === 'optional';\n}\n\n/** @internal Unwraps an optional Zod schema */\nfunction unwrapOptionalSchema(schema: unknown): unknown {\n    if (!isOptionalSchema(schema)) {\n        return schema;\n    }\n    const candidate = schema as { def?: { innerType?: unknown } };\n    return candidate.def?.innerType ?? schema;\n}\n"],"mappings":";;;;;;AAEA,MAAaA,qBAAoC,OAAO,IAAI,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgD9E,SAAgB,YAAwC,QAAW,UAAqD;AACpH,QAAO,eAAe,QAAkB,oBAAoB;EACxD,OAAO,EAAE,UAAU;EACnB,YAAY;EACZ,UAAU;EACV,cAAc;EACjB,CAAC;AACF,QAAO;;;;;AAMX,SAAgB,cAAc,QAAgE;AAC1F,QAAO,CAAC,CAAC,UAAU,OAAO,WAAW,YAAY,sBAAuB;;;;;AAM5E,SAAgB,aAAyC,QAA4C;AAEjG,QADc,OAAoE,qBACrE;;;;;;ACvEjB,MAAa,4BAA4B;AAEzC,MAAM,qBAAqB,KAAK,KAAK;;AAGrC,SAAgB,gBAAgB,YAAoB,QAAgE;AAChH,KAAI,CAAC,OAAO,SAAS,WAAW,IAAI,aAAa,EAC7C;CAGJ,MAAM,QAAQ,YAAY,QAAQ,KAAK,IAAI,YAAY,mBAAmB,CAAC;AAC3E,CAAC,MAAiC,SAAS;AAC3C,QAAO;;;;;;;;;;;;;AC0CX,IAAa,yBAAb,MAA8D;CAC1D,AAAiB,6BAAa,IAAI,KAAmC;;;;;CAMrE,YAAY,AAAiBC,SAAkC;EAAlC;;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