import type { CallToolRequest, CallToolResult, ClientCapabilities, ClientMessage, ClientNotifications, ClientRequests, ClientResult, CompleteRequest, CompleteResult, CreateTaskResult, DetailedTask, DiscoverResult, GetPromptRequest, GetPromptResult, Implementation, InitializeRequest, InitializeResult, InputRequest, InputRequiredResult, InputResponse, ListPromptsRequest, ListPromptsResult, ListResourcesRequest, ListResourcesResult, ListResourceTemplatesRequest, ListResourceTemplatesResult, ListToolsRequest, ListToolsResult, Log, LoggingLevel, ProgressNotification, ProtocolDefinition, ProtocolVersion, ReadResourceRequest, ReadResourceResult, RequestID, Result, Root, ServerCapabilities, ServerMessage, ServerNotification, ServerRequest, SetLevelRequest, SubscriptionFilter, TasksAcknowledgement, TasksGetResult, } from '@mokei/context-protocol' import { INPUT_REQUEST_CAPABILITIES, INVALID_REQUEST, inferSchemaDraft, isCreateTaskResult, isHandshakeRequired, isSupportedProtocolVersion, META_SUBSCRIPTION_ID, METHOD_NOT_FOUND, MOKEI_VERSION, PROTOCOL_VERSIONS, PROTOCOLS, serverMessage, TASKS_EXTENSION, UNSUPPORTED_PROTOCOL_VERSION, } from '@mokei/context-protocol' import { ContextRPC, type RequestOptions, RequestTimeoutError, RPCError, splitRequestOptions, TransportClosedError, type WithRequestOptions, } from '@mokei/context-rpc' import { getMokeiLogger } from '@mokei/logger' import type { SpanContext } from '@opentelemetry/api' import { ROOT_CONTEXT, trace } from '@opentelemetry/api' import { lazy } from '@sozai/async' import { withActiveContext } from '@sozai/otel' import { createValidator, type Schema, type Validator } from '@sozai/schema' import { type ClientTracing, createExchangeTracer, type TerminationReason, } from './client-tracing.js' import { CapabilityNotDeclaredError, InputRequiredNotSupportedError, ListMaxPagesError, MethodNotInRevisionError, MRTRNotSupportedError, StructuredContentValidationError, TaskInterruptedError, UnsupportedProtocolVersionError, } from './errors.js' import { DEFAULT_MAX_ROUNDS, isInputRequiredResult, linkedAbort, MRTR_METHODS, runInputRequiredFlow, } from './mrtr.js' import { capturePayload, type MessageDirection } from './observation.js' import { SetupReader } from './setup-reader.js' import { ACKNOWLEDGED_METHOD, type ListenHandle, type ListenHandlers, type ListenSettle, SubscriptionDriver, type SubscriptionNotification, SubscriptionProtocolError, type SubscriptionRetry, } from './subscriptions.js' import { TaskWaiter, type WaitForTaskParams } from './task-waiter.js' import { currentTraceMeta } from './trace.js' import { transportFailureOf } from './transport-failure.js' import { type ClientParams, type ContextTypes, type CreateMessageHandler, type ElicitHandler, type ListParams, type ListRootsHandler, type PerRequestElicit, type PromptParams, type ResourceSubscriptionParams, splitListOptions, type ToolParams, type UnknownContextTypes, } from './types.js' /** * Inbound wire validators, one per revision. Which one applies is decided per connection by * `#validateServerMessage` once the revision is resolved -- a `2026-07-28` server cannot legally * send `ping`, `sampling/createMessage`, `elicitation/create` or * `notifications/elicitation/complete`, and the wire parser is where a peer producing something * its own revision forbids has to be refused. * * Both entries read the revision's own `serverMessage` off its `ProtocolDefinition`: each * revision now owns its server-side unions under `versions/`. The package still exports the * unqualified `ServerMessage` / `ServerRequest` / `ServerResult` types from `server.js` as a * cross-revision convenience, but the per-connection validator is wired from the resolved * revision, never from those. */ const SERVER_MESSAGE_VALIDATORS: Record> = { '2025-11-25': createValidator(PROTOCOLS['2025-11-25'].serverMessage), '2026-07-28': createValidator(PROTOCOLS['2026-07-28'].serverMessage), } /** * The cross-revision union, used only while `protocolVersion: 'auto'` is still unresolved: with * no revision there is no per-revision union to apply. Unreachable in practice -- the read loop * only starts once `#setup()` has settled `#protocol` -- but the fallback keeps the validator * total rather than making the read loop depend on that ordering. */ const validateAnyServerMessage = createValidator(serverMessage) export const DEFAULT_CLIENT_INFO: Implementation = { name: 'Mokei', version: MOKEI_VERSION, } // '2025-11-25' rather than the latest protocol version: it is the only supported revision // that has an `initialize` handshake at all. '2026-07-28' has no `initialize` request // (`isHandshakeRequired` is `false`), so declaring it here would describe a handshake no // revision can legitimately send. `#initialize()` always overrides this with the resolved // protocol's own version before sending, so this default is never sent as-is. export const DEFAULT_INITIALIZE_PARAMS: InitializeRequest['params'] = { capabilities: {}, clientInfo: DEFAULT_CLIENT_INFO, protocolVersion: '2025-11-25', } export const DEFAULT_SETUP_TIMEOUT = 30_000 /** Default cap on pages fetched by a single list walk. */ export const DEFAULT_LIST_MAX_PAGES = 100 /** Max notifications buffered once a reader is attached; oldest dropped past this. */ const NOTIFICATION_BUFFER_CAP = 256 /** * The revision an `'auto'` probe speaks before it knows what the server speaks: the newest * registered revision that both needs no handshake and has `server/discover` to send. * * Derived from the registry rather than named, so a future handshake-less revision is probed * with its own envelope instead of an older one's -- `PROTOCOL_VERSIONS` is newest-first. * * The stamp this produces is a *guess*, and deliberately so: a probe is by definition sent * before the revision is agreed, and a server that speaks something else answers with an error, * which is precisely the signal `#probe()` falls back on. This is the one place in this file * where stamping a revision the peer may not speak is correct -- every other outgoing frame * stamps the revision that was actually resolved. * * `null` when no registered revision qualifies, rather than a throw. This is module-level, so * throwing here would crash the *import* of this package for every consumer -- including one * pinned to a handshake revision that never probes -- the moment the registry stopped carrying a * handshake-less revision. `#probe()` treats `null` as "nothing to probe with" and falls through * to the handshake, which is the same place a refused probe lands and is always a live option: * `'auto'` degrades to the behaviour of a pinned older client instead of taking the package down. */ const PROBE_PROTOCOL: ProtocolDefinition | null = (() => { const version = PROTOCOL_VERSIONS.find((candidate) => { const protocol = PROTOCOLS[candidate] return !isHandshakeRequired(protocol) && protocol.clientMethods.has('server/discover') }) return version == null ? null : PROTOCOLS[version] })() /** Notifications that invalidate whatever the client learned from `server/discover`. */ const LIST_CHANGED_NOTIFICATIONS: ReadonlySet = new Set([ 'notifications/prompts/list_changed', 'notifications/resources/list_changed', 'notifications/tools/list_changed', ]) /** * Maps each `*_list_changed` subscription-stream method onto the dataless `ClientEvents` member * it surfaces, so a consumer can observe a list changing without inspecting raw frames. Keyed by * the wire method; every member of {@link LIST_CHANGED_NOTIFICATIONS} appears here. */ const LIST_CHANGED_EVENTS: Record< string, 'toolsListChanged' | 'promptsListChanged' | 'resourcesListChanged' > = { 'notifications/tools/list_changed': 'toolsListChanged', 'notifications/prompts/list_changed': 'promptsListChanged', 'notifications/resources/list_changed': 'resourcesListChanged', } /** * Bounds how long an auto-opened or reconnecting `subscriptions/listen` candidate waits for its * `acknowledged` frame before failing, when a `subscribeResource`/`unsubscribeResource` caller * passes no `timeout` of its own. Without a bound a server that opens the stream but never acks * would wedge the driver's single mutation queue forever -- a reconnect candidate especially, as * no caller supplies its timeout. See {@link SubscriptionDriverParams.ackTimeoutMs}. */ const SUBSCRIPTION_ACK_TIMEOUT_MS = 30_000 /** * Correlator handed to the RPC base as `routeStreamNotification` (SEP-1391): a `2026-07-28` server * fans subscription notifications out of band, each carrying the listen request's id in * `params._meta['io.modelcontextprotocol/subscriptionId']`. A notification carrying that key is * routed into the matching listen stream exchange as a `progress` frame; one without it falls * through to normal notification handling (`null`); a present-but-wrong-typed id is a protocol * error the RPC base reports and consumes. * * Verbatim from the design brief; the only adaptation is the inline `frame` type in place of the * exported `StreamFrame` name (its `progress` member), to keep the change inside this package. */ function routeSubscriptionNotification( notification: ServerNotification, ): { id: RequestID; frame: { type: 'progress'; value: ServerNotification } } | null { const meta = (notification as { params?: { _meta?: Record } }).params?._meta if (meta == null || !Object.hasOwn(meta, META_SUBSCRIPTION_ID)) { return null } const value = (meta as Record)[META_SUBSCRIPTION_ID] if (typeof value !== 'string' && !(typeof value === 'number' && Number.isInteger(value))) { throw new RPCError({ code: INVALID_REQUEST, message: 'Invalid subscriptionId metadata' }) } return { id: value as RequestID, frame: { type: 'progress', value: notification } } } function toError(value: unknown): Error { return value instanceof Error ? value : new Error(String(value)) } export type ClientEvents = { closed: { error?: Error } /** * Emitted when a `2025-11-25` server sends `notifications/elicitation/complete` for a URL-mode * elicitation, carrying its `elicitationId`. */ elicitationComplete: { elicitationId: string } initialized: InitializeResult log: Log /** * Emitted when the server signals its prompts list changed over the `subscriptions/listen` * stream (SEP-1391), alongside the existing internal `_resetDiscovery()` routing. Dataless. */ promptsListChanged: undefined /** * Emitted when the server signals a subscribed resource's content changed over the * `subscriptions/listen` stream (SEP-1391), carrying the changed resource's URI. Emitted in * addition to the per-URI `onResourceUpdated` listeners and the `notifications` buffer push. */ resourceUpdated: { uri: string } /** * Emitted when the server signals its resources list changed over the `subscriptions/listen` * stream (SEP-1391), alongside the existing internal `_resetDiscovery()` routing. Dataless. */ resourcesListChanged: undefined /** Emitted before each `subscriptions/listen` reconnect attempt (SEP-1391). */ subscriptionRetry: SubscriptionRetry /** * Emitted when the server signals its tools list changed over the `subscriptions/listen` * stream (SEP-1391), alongside the existing internal `_resetDiscovery()` routing. Dataless. */ toolsListChanged: undefined } export type ClientTasks = { get(taskID: string): Promise update( taskID: string, inputResponses: Record, ): Promise cancel(taskID: string): Promise wait( taskID: string, options?: { signal?: AbortSignal onStatus?: (status: DetailedTask) => void toolName?: string }, ): Promise } type HandleNotification = ProgressNotification | ServerNotification type ClientTypes = { Events: ClientEvents MessageIn: ServerMessage MessageOut: ClientMessage HandleNotification: HandleNotification HandleRequest: ServerRequest SendNotifications: ClientNotifications SendRequests: ClientRequests SendResult: ClientResult } type PagedResult = { nextCursor?: string } & Record const FIRST_EXCHANGE = Symbol('firstExchange') const ROUND = Symbol('round') type TracedRequestOptions = RequestOptions & { [FIRST_EXCHANGE]?: SpanContext; [ROUND]?: number } export class ContextClient< T extends ContextTypes = UnknownContextTypes, > extends ContextRPC { #tracing?: ClientTracing #exchangeTracer = createExchangeTracer(() => this.#tracing) #capabilities: ClientCapabilities // Aborted once the transport closes, so an input-required flow waiting on a handler settles. #closed = new AbortController() #clientInfo: Implementation #createMessage?: CreateMessageHandler #discovered: { result: DiscoverResult; expiresAt: number } | null = null #discovering: Promise | null = null #elicit?: ElicitHandler #initialized: PromiseLike #initializationResult: InitializeResult | undefined #inputRequired: { autoFulfill: boolean; maxRounds: number } #listMaxPages: number #listRoots?: Array | ListRootsHandler #logLevel?: LoggingLevel // Passed to the RPC base and to the subscription driver / terminal verification so protocol // errors on a listen stream reach the consumer. The RPC base keeps its own private copy for // its own reporting; this is the client's handle on the same callback. #onError?: (error: Error) => void // Lazily created on auto-open (or a first `subscribeResource`), then reused. Owns the client's // one `subscriptions/listen` state machine (SEP-1391). #subscriptionDriver: SubscriptionDriver | null = null // Per-URI `resources/updated` listeners registered via `onResourceUpdated`. #resourceListeners: Map void>> = new Map() // The filter the server acknowledged on the most recent listen, from the `acknowledged` frame. #honoredFilter: SubscriptionFilter | null = null #notificationBuffer: Array = [] #notificationPull: (() => void) | null = null #hasNotificationReader = false #notifications: ReadableStream // The one outstanding low-level read shared by `#sendDiscover()` and `#initialize()` via // `SetupReader`'s `#readMatching()`. See that method's own comment in `setup-reader.ts` for why // this must not become two independent `reader.read()` calls. #pendingSetupRead: Promise> | null = null #protocol: ProtocolDefinition | null #reading = false #ready: PromiseLike #serverCapabilities: InitializeResult['capabilities'] = {} // Session-lifetime snapshot of the discovered server capabilities, used only for gating on a // revision without a handshake (`isHandshakeRequired` is `false`). Populated once by // `#requireServerCapabilityAsync` and never re-fetched afterward: without a handshake, a live // connection's *declared* capabilities cannot change except via a `*_list_changed` // notification -- which `_handleNotification` acts on, so the exception is enforced rather // than merely documented. That makes a connection-lifetime snapshot sound for gating even // though it ignores `discover()`'s own `ttlMs`. Distinct from `#discovered`, which still // honours `ttlMs` for callers who explicitly want a fresh answer from `discover()` itself. Do // not merge these two caches back together -- that reintroduces the bug this split fixes. // Whatever clears one must clear the other, so neither outlives the connection state that // produced it -- see `#resetDiscovery()`. #serverCapabilitySnapshot: ServerCapabilities | null = null // Drives the `initialize` / `server/discover` setup exchanges over the narrow `SetupIO` // adapter constructed below, which closes over `#setupBuffer` / `#pendingSetupRead` -- see // `setup-reader.ts`'s own class comment for the split of responsibility. #setupReader: SetupReader #setupTimeout: number // Messages read during setup (probe and/or handshake) that didn't match the waiter that read // them -- buffered here rather than dropped, so a later waiter with a different predicate // (e.g. the handshake reading past a message the probe already consumed) can still claim // them. See `setup-reader.ts`'s `#readMatching()`. Anything still here once setup finishes (e.g. a notification that // arrived mid-setup and matched no setup-phase waiter) is drained by the overridden `_read()` // as the read loop's first reads, so nothing buffered here is retained past that point. #setupBuffer: Array = [] #toolOutputSchemas = new Map>() #taskWaiter: TaskWaiter | null = null #tasks: ClientTasks = { get: (taskID) => this.request('tasks/get', { taskId: taskID }), update: (taskID, inputResponses) => this.request('tasks/update', { taskId: taskID, inputResponses }), cancel: (taskID) => this.request('tasks/cancel', { taskId: taskID }), wait: (taskID, options) => this.waitForTask({ taskID, ...options }), } get tasks(): ClientTasks { return this.#tasks } setTracing(binding: ClientTracing): void { this.#tracing = binding if (this.#discovered != null) this.#traceServerInfo(this.#discovered.result) } endTracing(reason: TerminationReason): void { this.#exchangeTracer.settleAll(reason) } constructor(params: ClientParams) { // Indirected through a method so the validator tracks the resolved revision rather than // being frozen at construction, which `protocolVersion: 'auto'` requires. super({ defaultRequestTimeout: params.requestTimeout, validateMessageIn: (message) => this.#validateServerMessage(message), transport: params.transport, maxConcurrentRequests: params.maxConcurrentRequests, maxQueuedRequests: params.maxQueuedRequests, onError: params.onError, routeStreamNotification: (notification) => { const routed = routeSubscriptionNotification(notification as ServerNotification) if (routed !== null) { this.#traceNotification(notification.method, 'server', notification.params) } return routed }, }) this.#onError = params.onError this.#createMessage = params.createMessage this.#elicit = params.elicit this.#listRoots = params.listRoots // `isSupportedProtocolVersion` before indexing: `PROTOCOLS[unknown]` is `undefined`, which // is nullish, so an unvalidated string used to skip the handler check below and reach // `#setup()` as though `'auto'` had been asked for -- silently probing instead of failing. if (params.protocolVersion !== 'auto' && !isSupportedProtocolVersion(params.protocolVersion)) { throw new UnsupportedProtocolVersionError({ received: params.protocolVersion }) } // Derived from `serverMethods` and `inputRequestMethods`, not a hardcoded version check: a // handler is refused exactly when the configured revision can invoke its method neither // way -- the client-side mirror of what `@mokei/context-server` does per capability on the // server side. Skipped here when the revision is still `'auto'`: the revision isn't known // yet, so `#setup()` re-runs this same check (`#refuseUnsupportedHandlers`) once the probe // resolves it -- a handler accepted here because the revision was unknown must still be // refused if the probe lands on a revision that can reach its method neither way. const protocol = params.protocolVersion === 'auto' ? null : PROTOCOLS[params.protocolVersion] if (protocol != null) { this.#refuseUnsupportedHandlers(protocol) } const capabilities: ClientCapabilities = {} if (params.elicit != null) { capabilities.elicitation = {} } if (params.createMessage != null) { capabilities.sampling = {} } if (params.listRoots != null) { capabilities.roots = {} } this.#capabilities = capabilities this.#tracing = params.tracing this.#clientInfo = params.clientInfo ?? DEFAULT_CLIENT_INFO this.#initialized = lazy(() => this.#initialize()) this.#listMaxPages = params.listMaxPages ?? DEFAULT_LIST_MAX_PAGES this.#inputRequired = { autoFulfill: params.inputRequired?.autoFulfill ?? true, maxRounds: params.inputRequired?.maxRounds ?? DEFAULT_MAX_ROUNDS, } this.#logLevel = params.logLevel this.#protocol = protocol this.#ready = lazy(() => this.#setup()) this.#setupTimeout = params.setupTimeout ?? DEFAULT_SETUP_TIMEOUT // The `SetupIO` closures are the only place `#setupBuffer` / `#pendingSetupRead` are touched // outside the `_read()` override below -- see `setup-reader.ts`'s `SetupIO` comment for why // each closure is shaped the way it is. this.#setupReader = new SetupReader({ io: { trace: (method, id, params) => { const exchange = this.#exchangeTracer.startOutgoing(method, params) exchange.setID(id) return exchange }, allocateID: () => this._getNextRequestID(), write: (message) => super._write(message), takeBuffered: (matches) => { const index = this.#setupBuffer.findIndex(matches) if (index === -1) { return undefined } const [message] = this.#setupBuffer.splice(index, 1) return message }, readNextFrame: () => { // Reuse a still-pending read left behind by an earlier, timed-out waiter rather than // issuing a fresh one -- see `setup-reader.ts`'s `SetupIO.readNextFrame` comment for // why a second concurrent read here would risk stealing the message this or a later // waiter needs. this.#pendingSetupRead ??= super._read().finally(() => { this.#pendingSetupRead = null }) return this.#pendingSetupRead }, handBackFrame: (message) => { this.#setupBuffer.push(message) }, }, setupTimeout: this.#setupTimeout, }) this.#notifications = new ReadableStream( { pull: (controller) => { const next = this.#notificationBuffer.shift() if (next != null) { controller.enqueue(next) return } // No buffered item: park until the next notification arrives. return new Promise((resolve) => { this.#notificationPull = () => { this.#notificationPull = null const queued = this.#notificationBuffer.shift() if (queued != null) { controller.enqueue(queued) } resolve() } }) }, cancel: () => { this.#hasNotificationReader = false this.#notificationBuffer = [] this.#notificationPull = null }, }, new CountQueuingStrategy({ highWaterMark: 0 }), ) } /** Validates an inbound frame against the resolved revision's own server-message union. */ #validateServerMessage(message: unknown): ReturnType> { const protocol = this.#protocol return protocol == null ? validateAnyServerMessage(message) : SERVER_MESSAGE_VALIDATORS[protocol.version](message) } /** * Throws when a handler is configured (`createMessage`/`elicit`/`listRoots`) whose method * (`sampling/createMessage`/`elicitation/create`/`roots/list`) is reachable neither as a * server-initiated request (`serverMethods`) nor as an MRTR input request * (`inputRequestMethods`) in `protocol`. Derived from the method tables, never a version * literal. Called once at construction for a fixed `protocolVersion`, and again from `#setup()` * once an `'auto'` probe resolves the revision. * * Both current revisions carry all three methods one way or the other, so this refuses nothing * today. It stays because the two tables are what make that true, and a future revision that * dropped one would otherwise silently accept a handler it can never invoke. */ #refuseUnsupportedHandlers(protocol: ProtocolDefinition): void { const reachable = (method: string): boolean => { return protocol.serverMethods.has(method) || protocol.inputRequestMethods.has(method) } if (this.#createMessage != null && !reachable('sampling/createMessage')) { throw new MRTRNotSupportedError({ handler: 'createMessage', version: protocol.version }) } if (this.#elicit != null && !reachable('elicitation/create')) { throw new MRTRNotSupportedError({ handler: 'elicit', version: protocol.version }) } if (this.#listRoots != null && !reachable('roots/list')) { throw new MRTRNotSupportedError({ handler: 'listRoots', version: protocol.version }) } } // Decorate every outgoing request with this revision's protocol envelope (`decorateRequest`) // and inject W3C trace context (SEP-414) into `_meta`; the latter is a no-op when no // OpenTelemetry SDK is active. Drives MRTR (SEP-2322) rounds for an `input_required` result on // a method that can suspend: dispatches the embedded requests and retries, unless the caller // passed `allowInputRequired` (which hands the raw suspension back instead) or // `inputRequired.autoFulfill` is off (which throws `InputRequiredNotSupportedError`). A // suspension the revision or method cannot legally produce always throws, regardless of either // opt-out. // // Awaits `#ready` first (not just `#requireProtocol()`): `getPrompt`, `readResource` and // `callTool` call `request()` directly with no `#ready` await of their own, so under // `protocolVersion: 'auto'` this is the only thing that runs the probe before they'd // otherwise throw "not resolved yet". Safe against `#initialize()`, which never calls // `request()` -- it writes/reads the transport directly via `super._write`/`SetupReader`'s // `#readMatching` -- so awaiting `#ready` here cannot deadlock against the handshake `#ready` // itself is waiting on. // // Behaviour change this introduces, deliberately not reverted: `ContextRPC.request()` // allocates the request ID synchronously, so awaiting `#ready` first means the *first* call // through this method now gets a higher ID than `#initialize()`'s own request -- e.g. a // `2025-11-25` client whose first call is `getPrompt()` now sends `initialize` as id 0 and // `prompts/get` as id 1, where it used to be the other way around. Frame *order* on the wire // is unaffected (that's still `initialize` then `prompts/get`); only which integer each frame // carries changes. This is fine to accept rather than restore: request IDs are opaque // correlators that any conforming server matches by value, not by magnitude, and monotonic // allocation (setup always first) is strictly better than the old, inverted numbering. The // same reordering also means a caller-supplied `options.timeout` now starts only after setup // completes rather than covering it too -- also fine, since `#setupTimeout` already bounds the // handshake/probe on its own, and a per-request timeout has no business being spent on // connection setup it didn't ask for. Hoisting this await into `getPrompt`/`readResource`/ // `callTool` instead would not preserve the old numbering either: it would still await // readiness before `request()` allocates the ID, producing the identical result. async request( method: Method, params: ClientTypes['SendRequests'][Method]['Params'], options?: RequestOptions & PerRequestElicit, ): Promise { await this.#ready const protocol = this.#requireProtocol() // A method absent from the resolved revision's table is a local error, not a round-trip. // `ClientRequests` spans both revisions, so `request()` accepts `initialize`, // `logging/setLevel` and `server/discover` whatever revision is in play; the typed wrappers // for those three refuse the wrong revision themselves, but nothing stops a caller from // reaching past them to `request()`, and letting one through turns a clear "this revision // does not have that" into an opaque `-32601` from the peer. // // Placed after the `#ready` await so an `'auto'` client is gated on the revision it // resolved, never on an unresolved one. That cannot starve the probe that resolves it: // `#sendDiscover()` writes `server/discover` through `super._write` rather than through // this method. if (!protocol.clientMethods.has(method as string)) { throw new MethodNotInRevisionError({ method: method as string, version: protocol.version }) } const traced = options as TracedRequestOptions | undefined const firstContext = traced?.[FIRST_EXCHANGE] const exchange = this.#exchangeTracer.startOutgoing(method as string, params, { links: firstContext === undefined ? [] : [{ context: firstContext }], traceAttributes: options?.traceAttributes, round: traced?.[ROUND], }) const first = firstContext ?? exchange.span.spanContext() return withActiveContext(exchange.context, async () => { const trace = currentTraceMeta() const base = params != null && typeof params === 'object' ? { ...(params as Record) } : {} if (trace.traceparent != null) { base._meta = { ...(base._meta as Record | undefined), ...trace } } const decorated = protocol.decorateRequest(base, { capabilities: this.#capabilitiesFor(protocol), clientInfo: this.#clientInfo, logLevel: this.#logLevel, }) // Charges the leg below against `maxTotalTimeout` too: that budget is documented (and, via // `runInputRequiredFlow`'s `startedAt`, implemented) as covering the leg that produced the // first suspension, not just the retries after it. const startedAt = Date.now() let result: ClientTypes['SendRequests'][Method]['Result'] try { result = await super.request(method, decorated as typeof params, { ...options, onRequestID: (id) => { exchange.setID(id) options?.onRequestID?.(id) }, }) exchange.succeed(result) } catch (cause) { const error = toError(cause) // An abort reason can itself be an RPCError; caller cancellation takes precedence. if ( cause instanceof RequestTimeoutError || options?.signal?.aborted || error.name === 'AbortError' ) { exchange.fail('cancelled', error.message) } else if (cause instanceof RPCError) { exchange.failRPC(cause) } else { exchange.fail( cause instanceof TransportClosedError ? 'context.lost' : '_OTHER', error.message, ) } throw cause } if (!isInputRequiredResult(result)) { return result } // A suspension the resolved revision or this method can never legally produce is a // nonconforming peer, not a suspension to drive or hand back -- refused unconditionally, the // same as every `input_required` result was refused before MRTR existed. Mirrors // `ContextServer._handleRequest`'s own two-part gate (`server.ts`'s `inputRequestMethods.size` // and `MRTR_METHODS` checks) so a `2025-11-25` peer or a non-MRTR method on `2026-07-28` (e.g. // `tools/list`) cannot talk this client into driving rounds `MRTR_METHODS` never grants it. // The first leg settled as suspended (no `execute_tool`), so a refusal records the local // failure span the logical call would otherwise lack. const refuse = (error: InputRequiredNotSupportedError): InputRequiredNotSupportedError => { if (method === 'tools/call') { this.#exchangeTracer.recordLocalFailure({ method, params, links: [{ context: first }], traceAttributes: options?.traceAttributes, round: 0, error, }) } return error } if (protocol.inputRequestMethods.size === 0 || !MRTR_METHODS.has(method as string)) { throw refuse( new InputRequiredNotSupportedError({ reason: protocol.inputRequestMethods.size === 0 ? `protocol version ${protocol.version} has no multi round-trip requests` : `${method as string} cannot suspend on input`, }), ) } // The opt-in path: hand the suspension back and let the caller drive its own rounds. Also how // the driver below reads each retry leg, so the loop lives in exactly one place. if (options?.allowInputRequired) { return result as ClientTypes['SendRequests'][Method]['Result'] } if (!this.#inputRequired.autoFulfill) { throw refuse( new InputRequiredNotSupportedError({ reason: 'auto-fulfilment is disabled (pass `allowInputRequired` to receive it, or enable `inputRequired.autoFulfill`)', }), ) } // `legs` is the next retry's round index; `suspended` is true while no retry leg is in // flight and the last settled round was `input_required`, i.e. when a rejection is local. let legs = 1 let suspended = true const flowAbort = linkedAbort([options?.signal, this.#closed.signal]) try { return (await runInputRequiredFlow({ method: method as string, first: result, maxRounds: this.#inputRequired.maxRounds, timeout: options?.timeout, maxTotalTimeout: options?.maxTotalTimeout, startedAt, signal: flowAbort.signal, dispatch: (key, inputRequest, signal) => this.#fulfilInputRequest(key, inputRequest, signal, options?.elicit), retry: async (retryParams, timeout) => { const round = legs++ suspended = false const retried = await this.request( method, { ...(params as object), ...retryParams } as typeof params, { ...options, allowInputRequired: true, timeout, [FIRST_EXCHANGE]: first, [ROUND]: round, } as TracedRequestOptions, ) suspended = isInputRequiredResult(retried) return retried }, })) as ClientTypes['SendRequests'][Method]['Result'] } catch (cause) { // A wire failure on a retry leg already settled that leg's span with `execute_tool`. if (suspended && method === 'tools/call') { this.#exchangeTracer.recordLocalFailure({ method, params, links: [{ context: first }], traceAttributes: options?.traceAttributes, round: legs - 1, error: cause, ...(options?.signal?.aborted && cause === options.signal.reason ? { errorType: 'cancelled' } : {}), }) } throw cause } finally { flowAbort.dispose() } }) } /** * Stamp outgoing notifications with the resolved revision; `ContextRPC.notify()` * bypasses request decoration. An unstamped `notifications/cancelled` on a * handshake-free revision can leave the peer's handler running. * `decorateNotification` is identity on `2025-11-25`. Awaiting `#ready` is safe: * setup sends `notifications/initialized` through `super._write`. */ async notify( event: Event, params: ClientTypes['SendNotifications'][Event]['params'], ): Promise { await this.#ready const protocol = this.#requireProtocol() // `ClientNotifications` spans revisions, so locally refuse unsupported methods // (e.g. `initialized` on `2026-07-28`) before a peer rejects them. Compare // the full wire name; `ContextRPC.notify` adds the `notifications/` prefix. const method = `notifications/${event}` if (!protocol.clientNotifications.has(method)) { throw new MethodNotInRevisionError({ method: method, version: protocol.version }) } const decorated = protocol.decorateNotification(params) this.#traceNotification(method, 'client', decorated) await super.notify(event, decorated as typeof params) } /** * After `SetupReader.driveInitialize` reads the handshake, reject and dispose * if the negotiated revision differs from the one this client speaks. */ async #initialize(): Promise { // The revision this client is configured to speak -- not `LATEST_PROTOCOL_VERSION`: this // client implements exactly one revision's wire behaviour, so declaring anything else in // the handshake would misrepresent what it can actually speak. const protocol = this.#requireProtocol() const { result, negotiatedRevision } = await this.#setupReader.driveInitialize({ protocolVersion: protocol.version, clientInfo: this.#clientInfo, capabilities: this.#capabilities, }) // Reject a negotiated version other than the one this client is configured to speak. This // `dispose()` runs twice -- the throw propagates into `#setup()`'s blanket catch, which // disposes again -- but `Disposer.dispose()` is idempotent. if (negotiatedRevision !== protocol.version) { await this.dispose() throw new UnsupportedProtocolVersionError({ received: negotiatedRevision, expected: protocol.version, }) } // Store server capabilities for client-side gating. this.#serverCapabilities = result.capabilities // Start listening for incoming messages this.#startReadLoop() // Notify the server with `notifications/initialized`. this.#traceNotification('notifications/initialized', 'client', undefined) await super._write({ jsonrpc: '2.0', method: 'notifications/initialized' }) this.#initializationResult = result this.events.emit('initialized', result) return result } /** * Dispose on every setup failure: `#ready` caches rejection, so an open stdio * transport would leak its spawned server. Recheck unsupported handlers after * `'auto'` resolves, since the constructor could not know the revision. */ async #setup(): Promise { try { // `#probe()` already issued (and seeded from) a `server/discover` of its own, so a // resolved `'auto'` connection must not send a second one here. const probed = this.#protocol == null const protocol = this.#protocol ?? (await this.#probe()) this.#protocol = protocol this.#refuseUnsupportedHandlers(protocol) if (isHandshakeRequired(protocol)) { await this.#initialized return } if (!probed) { await this.#setupDiscover() } this.#startReadLoop() this.#maybeAutoOpenSubscriptions() } catch (cause) { await this.dispose() throw cause } } /** * Auto-opens the one `subscriptions/listen` stream (SEP-1391) after setup, gated on the server * actually advertising resource subscriptions. Opt-in is narrow: the base filter carries only * the listChanged types this client acts on *and* the server advertises, so the client never * asks to be woken for a notification it does nothing with. * * Fire-and-forget: the open is enqueued on the driver's mutation queue and its failure surfaces * through the driver's `onError`/reconnect, never through setup readiness -- a server that * refuses the listen must not fail the connection. */ #maybeAutoOpenSubscriptions(): void { const protocol = this.#protocol if (protocol == null || !protocol.clientMethods.has('subscriptions/listen')) { return } if (this.#serverCapabilitySnapshot?.resources?.subscribe !== true) { return } this.#ensureSubscriptionDriver() .open() .catch(() => {}) } /** * Bound setup on handshake-free revisions: otherwise a silent server can hang * forever because only handshake and `'auto'` probe paths use `#setupTimeout`. * `#seedDiscovery` avoids a duplicate first gated call; ungated clients pay * one extra request per connection. * * An error response proves liveness even if discovery is unsupported; only * silence or disconnect fails setup. Stamp the resolved `#requireProtocol()` * revision, not {@link PROBE_PROTOCOL}, which may differ in future. */ async #setupDiscover(): Promise { let result: DiscoverResult try { result = await this.#sendDiscover(this.#requireProtocol()) } catch (cause) { if (cause instanceof RPCError) { return } throw cause } this.#seedDiscovery(result) } /** * Seeds both discover-derived caches from a `server/discover` answered during setup, so the * first gated call does not issue a second identical request. `#discovered` honours the * server's own `ttlMs` exactly as `discover()` would; `#serverCapabilitySnapshot` is seeded * unconditionally, per the connection-lifetime argument on that field. */ #seedDiscovery(result: DiscoverResult): void { const ttlMs = typeof result.ttlMs === 'number' && result.ttlMs > 0 ? result.ttlMs : 0 this.#discovered = { result, expiresAt: Date.now() + ttlMs } this.#serverCapabilitySnapshot = result.capabilities ?? {} this.#traceServerInfo(result) } #traceServerInfo(result: DiscoverResult): void { const serverInfo = result._meta?.['io.modelcontextprotocol/serverInfo'] if ( serverInfo != null && typeof serverInfo === 'object' && 'name' in serverInfo && typeof serverInfo.name === 'string' ) { this.#tracing?.contextSpan?.setAttribute('mokei.server.name', serverInfo.name) } } #capabilitiesFor(protocol: ProtocolDefinition): ClientCapabilities { if (protocol.version !== '2026-07-28') return this.#capabilities return { ...this.#capabilities, extensions: { ...this.#capabilities.extensions, [TASKS_EXTENSION]: {} }, } } /** * Resolve `'auto'` through `server/discover` per * `specification/2026-07-28/basic/transports/stdio#backward-compatibility`. * On failure, `-32022`'s `data.supported` selects the newest shared revision; * otherwise use the `2025-11-25` handshake. * * Every fallback must require a handshake. It consumes `#pendingSetupRead` * before `#startReadLoop()`; a handshake-free fallback could race that read * and revive the FIFO-steal bug guarded by `SetupReader`. */ async #probe(): Promise { const candidate = PROBE_PROTOCOL if (candidate == null) { // Without a discover-capable revision, fall back to the handshake; an eager // module-scope failure would also break consumers that never probe. return this.#fallBackFromProbe([], null) } try { // Seeded, not discarded: the probe's answer is a full `DiscoverResult`, and throwing it // away made every `'auto'` connection send `server/discover` a second time on its first // gated call -- a redundant POST per connection over HTTP. this.#seedDiscovery(await this.#sendDiscover(candidate)) return candidate } catch (cause) { const supported = cause instanceof RPCError && cause.code === UNSUPPORTED_PROTOCOL_VERSION ? ((cause.data as { supported?: Array } | undefined)?.supported ?? []) : [] return this.#fallBackFromProbe(supported, candidate.version) } } /** * Settles on a handshake revision when the probe cannot resolve one, and returns it. * * `supported` is whatever the server named in a `-32022` (empty for any other failure); * `refused` is the revision the probe just tried, excluded from the result even if the * server's own `data.supported` erroneously lists it -- the caller only reaches here because * the server rejected that exact version, so re-selecting it would hand back a revision with * no handshake that the server has already refused to speak, leaving every gated call * re-issuing `server/discover` forever with no way to make progress. */ #fallBackFromProbe( supported: Array, refused: ProtocolVersion | null, ): ProtocolDefinition { const agreed = PROTOCOL_VERSIONS.find( (version) => version !== refused && supported.includes(version), ) this.#protocol = agreed == null ? PROTOCOLS['2025-11-25'] : PROTOCOLS[agreed] // A capability snapshot or cached discover() result taken from the failed probe must not // survive into the connection that replaces it. this.#resetDiscovery() return this.#protocol } /** * Use `#setupReader` before `#startReadLoop()` exists. Its shared bounded-read * state prevents a timed-out probe from stealing the following handshake frame. * `protocol` is resolved for setup discovery but {@link PROBE_PROTOCOL} during * probing; hardcoding either could stamp a future revision incorrectly. */ async #sendDiscover(protocol: ProtocolDefinition): Promise { const { result } = await this.#setupReader.driveDiscover({ protocol, clientInfo: this.#clientInfo, capabilities: this.#capabilitiesFor(protocol), logLevel: this.#logLevel, }) return result } /** * Clears both discover-derived caches together: `#discovered` (`discover()`'s own * `ttlMs`-governed cache) and `#serverCapabilitySnapshot` (the connection-lifetime gating * snapshot). Two callers: `#probe()`'s fallback path, so a result cached from the failed * `2026-07-28` probe attempt cannot leak into the `2025-11-25` connection that replaces it, * and `_handleNotification` on a `*_list_changed` notification, the one way a live * connection's declared capabilities change -- see the field comment on * `#serverCapabilitySnapshot`. */ #resetDiscovery(): void { this.#discovered = null this.#serverCapabilitySnapshot = null } /** The resolved protocol record. Throws while an `'auto'` probe is still pending. */ #requireProtocol(): ProtocolDefinition { if (this.#protocol == null) { throw new Error("The 'auto' protocol version has not been resolved yet") } return this.#protocol } /** * Starts `ContextRPC`'s read loop exactly once, across probe and handshake. * * Asserts `#pendingSetupRead == null`: the read loop and `setup-reader.ts`'s `#readMatching()` * must never have an outstanding low-level read in flight at the same time, or the FIFO-steal * bug `#readMatching()` exists to prevent returns -- a read meant for `#readMatching()`'s caller * could instead resolve * whichever `_read()` call `ContextRPC`'s read loop just issued, and vice versa. Every setup * path that reaches here has already consumed `#pendingSetupRead` down to `null` via the * response that unblocked its own bounded read -- the initialize response for `#initialize()`, * the `server/discover` response for `#setupDiscover()` and `#probe()` -- each immediately * before this method runs. A bounded read that instead *times out* leaves the field set, but * also throws, so `#setup()` disposes rather than reaching here. See `#probe()`'s comment for * the one assumption this depends on. */ #startReadLoop(): void { if (this.#reading) { return } if (this.#pendingSetupRead != null) { throw new Error( '#startReadLoop() invariant violated: a setup-phase read is still outstanding', ) } this.#reading = true this._handle() } /** * Serves `#setupBuffer`'s leftovers before touching the transport. `ContextRPC`'s read loop * (`#readLoop` in `rpc.ts`) calls `this._read()` in an unconditional loop once * `#startReadLoop()` starts it, with no knowledge of `#setupBuffer`'s existence -- this * override is what makes that safe. Anything left in `#setupBuffer` once setup finishes (a * notification or server request that arrived during the probe/handshake window and matched * no setup-phase waiter's predicate) is drained here as the read loop's first reads, in * arrival order, before it ever reaches `super._read()` for genuinely new data. This is the * single place `#setupBuffer` is drained for that purpose -- * `setup-reader.ts`'s `#readMatching()` * deliberately does not call this override for its own reads (see its comment for why doing so * would deadlock). */ async _read(): Promise> { if (this.#setupBuffer.length > 0) { const value = this.#setupBuffer.shift() as ServerMessage return { done: false, value } } return await super._read() } /** * Runs on an explicit `dispose()` before the transport closes: tears down the subscription * driver (and any in-flight listen exchange) so no reconnect is scheduled as the outbound listen * exchange is ended by the close that follows. Idempotent with the `_onTransportClosed` teardown * that also covers a peer EOF. */ _beforeTransportClose(_reason: Error): void { this.#subscriptionDriver?.dispose() } _onTransportClosed(reason?: Error): void { this.#closed.abort(reason ?? new TransportClosedError()) this.#exchangeTracer.settleAll('lost') // Covers a peer EOF (which never runs `_beforeTransportClose`): suppress reconnect so a dead // transport is not retried. `dispose()` is idempotent. this.#subscriptionDriver?.dispose() this.events.emit('closed', { error: reason }) } // Override _write to ensure the client is set up (handshake or read loop start) before // sending messages. async _write(message: ClientMessage): Promise { await this.#ready await super._write(message) } #traceNotification(method: string, direction: MessageDirection, params: unknown): void { const binding = this.#tracing const span = binding?.contextSpan if (span === undefined) return withActiveContext(trace.setSpan(ROOT_CONTEXT, span), () => { const captured = span.isRecording() ? capturePayload(params, binding?.payloads) : undefined getMokeiLogger('mcp') .getChild('notification') .debug('MCP notification {method}', { method, direction, ...(captured === undefined ? {} : { payload: captured.payload }), ...(captured?.truncated ? { 'mokei.payload.truncated': true } : {}), }) }) } _handleMessage(message: ServerMessage): ReturnType['_handleMessage']> { // RPC consumes cancellation before dispatching notifications to the subclass. if ( message.id == null && message.method === 'notifications/cancelled' && this.#validateServerMessage(message).issues == null ) { this.#traceNotification(message.method, 'server', message.params) } return super._handleMessage(message) } _handleNotification(notification: HandleNotification): void { this.#traceNotification(notification.method, 'server', notification.params) if (notification.method === 'notifications/message') { this.events.emit('log', notification.params) } if (notification.method === 'notifications/elicitation/complete') { const { elicitationId } = notification.params void this.events.emit('elicitationComplete', { elicitationId }).catch(() => {}) } // Clear tool output schemas cache on tools/list_changed notification if (notification.method === 'notifications/tools/list_changed') { this.#toolOutputSchemas.clear() } // The one thing that can change a live connection's declared capabilities without a // handshake -- the exception `#serverCapabilitySnapshot`'s soundness argument rests on. Both // discover-derived caches go, or the gate and `discover()` disagree for the rest of the // connection. if (LIST_CHANGED_NOTIFICATIONS.has(notification.method)) { this.#resetDiscovery() } this.#pushNotification(notification) } /** Buffers a notification for the `notifications` reader; drops until one attaches, keeps CAP. */ #pushNotification(notification: HandleNotification): void { // Drop until a reader attaches, then keep only the most recent CAP. if (!this.#hasNotificationReader) { return } this.#notificationBuffer.push(notification) if (this.#notificationBuffer.length > NOTIFICATION_BUFFER_CAP) { this.#notificationBuffer.shift() } this.#notificationPull?.() } // --- subscriptions (SEP-1391) ---------------------------------------------- /** * Subscribe to `resources/updated` for a URI over the `subscriptions/listen` stream. Resolves * once the server acknowledges the updated filter. Delegates to the driver, which opens a new * candidate carrying the URI, awaits its ack, and only then retires the previous stream. */ async subscribeResource(params: ResourceSubscriptionParams): Promise { await this.#ready const protocol = this.#requireProtocol() if (!protocol.clientMethods.has('subscriptions/listen')) { throw new MethodNotInRevisionError({ method: 'subscriptions/listen', version: protocol.version, }) } await this.#ensureSubscriptionDriver().subscribeResource(params) } /** Unsubscribe from `resources/updated` for a URI. Resolves once the updated filter is acked. */ async unsubscribeResource(params: ResourceSubscriptionParams): Promise { await this.#ready const protocol = this.#requireProtocol() if (!protocol.clientMethods.has('subscriptions/listen')) { throw new MethodNotInRevisionError({ method: 'subscriptions/listen', version: protocol.version, }) } await this.#ensureSubscriptionDriver().unsubscribeResource(params) } /** * Register a per-URI `resources/updated` listener. Returns an unsubscribe function. Independent * of {@link ContextClient.subscribeResource}, which opens the server-side subscription: a * listener only receives updates once its URI is actually subscribed (and the update arrives). * Every delivered update also lands on the `notifications` stream. */ onResourceUpdated( uri: string, listener: (notification: SubscriptionNotification) => void, ): () => void { let listeners = this.#resourceListeners.get(uri) if (listeners == null) { listeners = new Set() this.#resourceListeners.set(uri, listeners) } listeners.add(listener) return () => { const set = this.#resourceListeners.get(uri) if (set != null) { set.delete(listener) if (set.size === 0) { this.#resourceListeners.delete(uri) } } } } /** * The server capabilities discovered on this connection (`2026-07-28`, read without a request), * or `null` before discovery and on revisions with a handshake (see `initializationResult`). */ get discoveredCapabilities(): ServerCapabilities | null { return this.#serverCapabilitySnapshot } /** The notification filter the server acknowledged on the current listen, or `null`. */ get subscriptionFilter(): SubscriptionFilter | null { return this.#honoredFilter } #ensureSubscriptionDriver(): SubscriptionDriver { let driver = this.#subscriptionDriver if (driver == null) { driver = new SubscriptionDriver({ openListen: (filter, handlers) => this.#openResourceListen(filter, handlers), filter: this.#autoOpenFilter(), onNotification: (notification) => this.#handleSubscriptionNotification(notification), onError: (error) => this.#reportSubscriptionError(error), onRetry: (retry) => { void this.events.emit('subscriptionRetry', retry).catch(() => {}) }, ackTimeoutMs: SUBSCRIPTION_ACK_TIMEOUT_MS, }) this.#subscriptionDriver = driver } return driver } /** Base listen filter: the listChanged types this client acts on that the server advertises. */ #autoOpenFilter(): SubscriptionFilter { const caps = this.#serverCapabilitySnapshot const filter: SubscriptionFilter = {} if (caps?.tools?.listChanged === true) { filter.toolsListChanged = true } if (caps?.prompts?.listChanged === true) { filter.promptsListChanged = true } if (caps?.resources?.listChanged === true) { filter.resourcesListChanged = true } return filter } #openResourceListen(filter: SubscriptionFilter, handlers: ListenHandlers): ListenHandle { return this.#openListen(filter, { ...handlers, onNotification: (notification) => { if ((notification as { method?: unknown }).method === ACKNOWLEDGED_METHOD) { const honored = (notification as { params?: { notifications?: SubscriptionFilter } }) .params?.notifications if (honored != null) this.#honoredFilter = honored } handlers.onNotification(notification) }, }) } /** * Opens one `subscriptions/listen` exchange and verifies its terminal subscriptionId. * Resource filter state belongs to `#openResourceListen`, while task acknowledgements go * directly to the task waiter. */ #openListen(filter: SubscriptionFilter, handlers: ListenHandlers): ListenHandle { const traced = this.#exchangeTracer.startOutgoing('subscriptions/listen', { notifications: filter, }) return withActiveContext(traced.context, () => { const protocol = this.#requireProtocol() const trace = currentTraceMeta() const base: Record = { notifications: filter } if (trace.traceparent != null) { base._meta = { ...trace } } const params = protocol.decorateRequest(base, { capabilities: this.#capabilitiesFor(protocol), clientInfo: this.#clientInfo, logLevel: this.#logLevel, }) const controller = new AbortController() let subscriptionId: RequestID | undefined const exchange = this._registerStreamExchange( 'subscriptions/listen', params, { onProgress: (value) => { const notification = value as SubscriptionNotification if ((notification as { method?: unknown }).method === ACKNOWLEDGED_METHOD) { const meta = (notification as { params?: { _meta?: Record } }).params ?._meta const id = meta?.[META_SUBSCRIPTION_ID] if (typeof id === 'string' || typeof id === 'number') { subscriptionId = id } } handlers.onNotification(notification) }, onSettle: (settle) => { if (settle.reason === 'result') { // The terminal body lives only on the exchange promise (resolved just before this // settle fired); read it back to verify the subscriptionId before the driver treats // the settle as a graceful teardown. exchange.then( (value) => { const verified = this.#verifyTerminal(value, subscriptionId) if (verified.reason === 'result') traced.succeed(value) else traced.fail('_OTHER', verified.error?.message) handlers.onSettle(verified) }, () => {}, ) } else { if (settle.reason === 'error' && settle.error instanceof RPCError) { traced.failRPC(settle.error) } else { traced.fail( settle.reason === 'cancel' ? 'cancelled' : settle.reason === 'closed' ? 'context.lost' : '_OTHER', settle.error?.message, ) } handlers.onSettle(settle) } }, }, { signal: controller.signal, onRequestID: (id) => traced.setID(id) }, ) exchange.catch(() => {}) return { exchange, abort: (reason?: Error) => controller.abort(reason), } }) } /** Confirms a terminal listen result's `_meta` subscriptionId matches the listen request id. */ #verifyTerminal(value: unknown, subscriptionId: RequestID | undefined): ListenSettle { const meta = (value as { _meta?: Record } | null | undefined)?._meta const id = meta?.[META_SUBSCRIPTION_ID] if (subscriptionId != null && id !== subscriptionId) { const error = new SubscriptionProtocolError({ message: `Terminal subscriptions/listen result subscriptionId (${String(id)}) does not match the listen request id (${String(subscriptionId)})`, }) this.#reportSubscriptionError(error) return { reason: 'error', error } } return { reason: 'result' } } /** Routes a delivered (non-`acknowledged`) subscription notification. */ #handleSubscriptionNotification(notification: SubscriptionNotification): void { const method = (notification as { method?: string }).method if (method === 'notifications/tools/list_changed') { this.#toolOutputSchemas.clear() } if (method != null && LIST_CHANGED_NOTIFICATIONS.has(method)) { this.#resetDiscovery() // Surface the internal `_resetDiscovery()` routing as an observable client event so a // consumer (e.g. `@mokei/host`) can react to a list changing. Additive: `#resetDiscovery()` // above still runs. Fire-and-forget like `subscriptionRetry`, so a listener failure never // breaks subscription frame handling. const listChangedEvent = LIST_CHANGED_EVENTS[method] if (listChangedEvent != null) { void this.events.emit(listChangedEvent).catch(() => {}) } } if (method === 'notifications/resources/updated') { const uri = (notification as { params?: { uri?: string } }).params?.uri if (uri != null) { const listeners = this.#resourceListeners.get(uri) if (listeners != null) { for (const listener of listeners) { try { listener(notification) } catch (error) { this.#reportSubscriptionError(toError(error)) } } } // Emitted in addition to the per-URI listeners above and the `#notifications` buffer push // below, so a consumer wiring on the client rather than per-URI still sees every update. void this.events.emit('resourceUpdated', { uri }).catch(() => {}) } } this.#pushNotification(notification) } #reportSubscriptionError(error: Error): void { try { this.#onError?.(error) } catch { // A consumer's error handler must not break subscription handling. } } /** * Fulfils one embedded MRTR input request with this client's own handler. * * The same three handlers `_handleRequest` uses for `2025-11-25`'s server-initiated requests -- * one handler, both revisions, which is the whole point of driving MRTR here rather than * exposing it to callers. */ async #fulfilInputRequest( key: string, request: InputRequest, signal: AbortSignal, elicit?: ElicitHandler, ): Promise { switch (request.method) { case 'sampling/createMessage': if (this.#createMessage != null) { return await this.#createMessage({ params: request.params, signal }) } break case 'elicitation/create': if (this.#elicit != null) { return await (elicit ?? this.#elicit)({ params: request.params, signal }) } break case 'roots/list': if (this.#listRoots != null) { const roots = Array.isArray(this.#listRoots) ? this.#listRoots : await this.#listRoots({ signal }) return { roots } } break } throw new InputRequiredNotSupportedError({ reason: `no handler is configured for the "${request.method}" input request "${key}" (declare the "${INPUT_REQUEST_CAPABILITIES[request.method]}" capability by passing its handler to the client)`, }) } async _handleRequest(request: ServerRequest, signal: AbortSignal): Promise { const exchange = this.#exchangeTracer.startIncoming( request.method, request.params, request.id, request.params?._meta, ) // Transport teardown settles all spans synchronously after aborting handlers. const abort = () => queueMicrotask(() => exchange.fail('cancelled')) if (signal.aborted) abort() else signal.addEventListener('abort', abort, { once: true }) return withActiveContext(exchange.context, async () => { try { const result = await this.#dispatchRequest(request, signal) exchange.succeed(result) return result } catch (cause) { if (!signal.aborted && cause instanceof RPCError) exchange.failRPC(cause) else { exchange.fail( signal.aborted ? 'cancelled' : cause instanceof TransportClosedError ? 'context.lost' : '_OTHER', cause instanceof Error ? cause.message : String(cause), ) } throw cause } finally { signal.removeEventListener('abort', abort) } }) } async #dispatchRequest(request: ServerRequest, signal: AbortSignal): Promise { // Answered here rather than in `ContextRPC`, which stays MCP-version-agnostic: `ping` exists // only in the revisions whose `serverMethods` carries it, and the spec makes answering it a // MUST there. Gated on the method table, not a version literal, and mirroring // `ContextServer._handleRequest`'s own `ping` case. if (request.method === 'ping' && this.#requireProtocol().serverMethods.has('ping')) { return {} } switch (request.method) { case 'elicitation/create': { if (this.#elicit != null) { return await this.#elicit({ params: request.params, signal }) } break } case 'roots/list': { if (this.#listRoots == null) { throw new RPCError({ code: METHOD_NOT_FOUND, message: 'roots capability not supported' }) } const roots = Array.isArray(this.#listRoots) ? this.#listRoots : await this.#listRoots({ signal }) return { roots } } case 'sampling/createMessage': if (this.#createMessage != null) { return await this.#createMessage({ params: request.params, signal }) } } throw new RPCError({ code: METHOD_NOT_FOUND, message: 'Method not implemented' }) } // Guard: throws synchronously when the server did not declare the given capability. // Only meaningful after initialize() completes; #serverCapabilities is {} until then. // Narrowed to 'logging': the handshake-only gate, still reading #serverCapabilities directly. // 'tools' and 'completions' route through #requireServerCapabilityAsync instead, which reads // the discover-backed snapshot on a revision without a handshake. #requireServerCapability(capability: 'logging'): void { if (this.#serverCapabilities[capability] == null) { throw new CapabilityNotDeclaredError({ capability: capability }) } } // Guard: throws when the server did not declare the given capability, reading from whichever // source this revision actually populates. `2025-11-25` has a handshake, so `#serverCapabilities` // is authoritative. `2026-07-28` has none, so the only way to learn what the server supports is // `discover()` -- but calling `discover()` on every gated call would mean sending // `server/discover` before every `tools/list`/`completion/complete` forever (an unconfigured // server's `ttlMs` defaults to 0, so `discover()`'s own cache never hits). Since a revision // without a handshake also has no way for a live connection's declared capabilities to change // except via a `*_list_changed` notification, it's sound to call `discover()` at most once per // connection here and snapshot the result for the connection's lifetime, independent of // `discover()`'s `ttlMs`-governed cache. async #requireServerCapabilityAsync( capability: 'tools' | 'completions', options?: RequestOptions, ): Promise { const protocol = this.#requireProtocol() let capabilities: ServerCapabilities if (isHandshakeRequired(protocol)) { capabilities = this.#serverCapabilities } else { if (this.#serverCapabilitySnapshot == null) { const result = await this.discover(options) this.#serverCapabilitySnapshot = result.capabilities } capabilities = this.#serverCapabilitySnapshot } if (capabilities[capability] == null) { throw new CapabilityNotDeclaredError({ capability: capability }) } } get notifications(): ReadableStream { this.#hasNotificationReader = true return this.#notifications as ReadableStream } /** The resolved protocol revision. Throws while an `'auto'` probe is still pending. */ get protocolVersion(): ProtocolVersion { return this.#requireProtocol().version } /** * The `2025-11-25` handshake result -- server capabilities and identity. * * Awaits `#ready` like every other public method here: under `'auto'` the revision stays * unresolved until `#setup()` runs the probe, so without it `#requireProtocol()` threw "not * resolved yet" on every first call. No deadlock -- `#initialize()` writes and reads the * transport directly rather than through `request()`. * * Two accepted costs: on a handshake-less revision setup runs before the throw below, and a * failed handshake now disposes the transport. */ async initialize(): Promise { await this.#ready const protocol = this.#requireProtocol() if (!isHandshakeRequired(protocol)) { throw new Error( `initialize() is not applicable to protocol version ${protocol.version}: it does not require a handshake`, ) } return await this.#initialized } /** The completed handshake result, without starting initialization. */ get initializationResult(): InitializeResult | undefined { return this.#initializationResult } /** * Queries a server's supported protocol versions, capabilities and identity -- the * `2026-07-28` replacement for the `initialize` handshake. Result is cached per the * server's own `ttlMs`; concurrent callers while a request is in flight collapse onto it. * `cacheScope` is read implicitly, not explicitly: this cache lives on one client instance, * so it is inherently private, and `'private'` is honoured by construction regardless of what * the server sends. * * Awaits `#ready` like every other public method here (`setLoggingLevel`, `complete`, * `listTools`, `#listPaged`), so a first call under `protocolVersion: 'auto'` probes rather * than throwing "not resolved yet". * * This is the `ttlMs`-governed cache for direct callers. `#requireServerCapabilityAsync` * does not use it for gating -- see `#serverCapabilitySnapshot`. */ async discover(options?: RequestOptions): Promise { await this.#ready const protocol = this.#requireProtocol() if (isHandshakeRequired(protocol)) { throw new Error( `server/discover does not exist in protocol version ${protocol.version}; use initialize()`, ) } if (this.#discovered != null && Date.now() < this.#discovered.expiresAt) { return this.#discovered.result } // Collapse concurrent callers onto one in-flight request. Note the coupling this creates: // whichever caller's invocation wins this `??=` imposes its own `options` (signal, timeout) // on every other concurrent awaiter, so one caller's abort/timeout rejects another caller's // `discover()` too, even though that caller passed different (or no) options. this.#discovering ??= this.request('server/discover', {}, options) .then((result) => { const ttlMs = typeof result.ttlMs === 'number' && result.ttlMs > 0 ? result.ttlMs : 0 this.#discovered = { result, expiresAt: Date.now() + ttlMs } this.#traceServerInfo(result) return result }) .finally(() => { this.#discovering = null }) return await this.#discovering } async setLoggingLevel(params: WithRequestOptions): Promise { await this.#ready const protocol = this.#requireProtocol() // Derived from `clientMethods`, not a version literal: refuses exactly when this // revision's method table has no `logging/setLevel` to send. Deliberately does not route // through `discover()`'s capabilities -- `2026-07-28` still advertises `logging: {}` even // though the method itself is gone, so gating on capabilities would let this through and // earn a METHOD_NOT_FOUND from the server instead of this clearer, client-side refusal. if (!protocol.clientMethods.has('logging/setLevel')) { throw new MethodNotInRevisionError({ method: 'logging/setLevel', version: protocol.version, hint: 'the log level travels per request via _meta instead (see ClientParams.logLevel)', }) } this.#requireServerCapability('logging') const [wireParams, options] = splitRequestOptions(params) return await this.request('logging/setLevel', wireParams, options) } async complete(params: WithRequestOptions): Promise { await this.#ready const [wireParams, options] = splitRequestOptions(params) await this.#requireServerCapabilityAsync('completions', options) return await this.request('completion/complete', wireParams, options) } /** * Walks a paginated list method until the server stops returning a cursor. * * Takes the caller's merged params and separates the wire params from the pagination * and transport options, so the list methods never hand the latter to `request`. * * When `cursor` is set the caller is driving pagination: a single request is issued and * its page returned verbatim, `nextCursor` intact. */ async #listPaged( method: string, key: string, send: (params: Record, options: RequestOptions) => Promise, listParams: ListParams>, ): Promise { await this.#ready const [params, { maxPages: maxPagesParam, ...options }] = splitListOptions(listParams) if (params.cursor != null) { return await send(params, options) } const maxPages = maxPagesParam ?? this.#listMaxPages const items: Array = [] let cursor: string | undefined let pages = 0 while (true) { const page = await send(cursor == null ? params : { ...params, cursor }, options) pages += 1 const pageItems = page[key] if (Array.isArray(pageItems)) { items.push(...pageItems) } if (page.nextCursor == null) { const { nextCursor: _nextCursor, ...rest } = page return { ...rest, [key]: items } } if (pages >= maxPages) { throw new ListMaxPagesError({ method: method, pages: pages, cursor: page.nextCursor, results: items, }) } cursor = page.nextCursor } } async listPrompts( params: ListParams = {}, ): Promise { const result = await this.#listPaged( 'prompts/list', 'prompts', (pageParams, options) => { return this.request( 'prompts/list', pageParams as ListPromptsRequest['params'], options, ) as Promise }, params, ) return result as ListPromptsResult } getPrompt( params: WithRequestOptions> & PerRequestElicit & { allowInputRequired?: false }, ): Promise getPrompt( params: WithRequestOptions> & PerRequestElicit & { allowInputRequired: true }, ): Promise getPrompt( params: WithRequestOptions> & PerRequestElicit & { allowInputRequired: boolean }, ): Promise getPrompt( params: WithRequestOptions> & PerRequestElicit, ): Promise { const { elicit, ...requestParams } = params const [wireParams, options] = splitRequestOptions(requestParams) return this.request('prompts/get', wireParams as GetPromptRequest['params'], { ...options, elicit, }) } async listResources( params: ListParams = {}, ): Promise { const result = await this.#listPaged( 'resources/list', 'resources', (pageParams, options) => { return this.request( 'resources/list', pageParams as ListResourcesRequest['params'], options, ) as Promise }, params, ) return result as ListResourcesResult } async listResourceTemplates( params: ListParams = {}, ): Promise { const result = await this.#listPaged( 'resources/templates/list', 'resourceTemplates', (pageParams, options) => { return this.request( 'resources/templates/list', pageParams as ListResourceTemplatesRequest['params'], options, ) as Promise }, params, ) return result as ListResourceTemplatesResult } readResource( params: WithRequestOptions & PerRequestElicit & { allowInputRequired?: false }, ): Promise readResource( params: WithRequestOptions & PerRequestElicit & { allowInputRequired: true }, ): Promise readResource( params: WithRequestOptions & PerRequestElicit & { allowInputRequired: boolean }, ): Promise readResource( params: WithRequestOptions & PerRequestElicit, ): Promise { const { elicit, ...requestParams } = params const [wireParams, options] = splitRequestOptions(requestParams) return this.request('resources/read', wireParams, { ...options, elicit }) } async listTools(params: ListParams = {}): Promise { await this.#ready const [, gateOptions] = splitRequestOptions(params) await this.#requireServerCapabilityAsync('tools', gateOptions) const result = (await this.#listPaged( 'tools/list', 'tools', (pageParams, options) => { return this.request( 'tools/list', pageParams as ListToolsRequest['params'], options, ) as Promise }, params, )) as ListToolsResult this._cacheToolOutputSchemas(result.tools) return result } /** @internal Memoises validators for tools that advertise an outputSchema. */ _cacheToolOutputSchemas(tools: ListToolsResult['tools']): void { for (const tool of tools) { if (tool.outputSchema == null) { this.#toolOutputSchemas.delete(tool.name) continue } const schema = tool.outputSchema as Schema this.#toolOutputSchemas.set( tool.name, createValidator(schema, { draft: inferSchemaDraft(schema), strict: false }), ) } } waitForTask(params: WaitForTaskParams): Promise { this.#taskWaiter ??= new TaskWaiter({ request: async (method, requestParams) => { if (method === 'tasks/get') { return await this.request('tasks/get', { taskId: requestParams.taskId }) } if (method === 'tasks/update') { return await this.request('tasks/update', { taskId: requestParams.taskId, inputResponses: requestParams.inputResponses ?? {}, }) } return await this.request('tasks/cancel', { taskId: requestParams.taskId }) }, openListen: (filter, handlers) => this.#openListen(filter, handlers), fulfil: async (key, request, signal, elicit) => { return await this.#fulfilInputRequest(key, request, signal, elicit) }, validate: (result, toolName) => this.#validateToolOutput(result, toolName), }) return this.#taskWaiter.wait(params) } #validateToolOutput(result: CallToolResult, toolName: string): CallToolResult { const validate = this.#toolOutputSchemas.get(toolName) if (validate == null || result.structuredContent == null) { return result } const outcome = validate(result.structuredContent) if (outcome.issues != null) { throw new StructuredContentValidationError({ toolName, issues: outcome.issues.map((issue) => { return { message: issue.message, path: issue.path?.map((segment) => { return typeof segment === 'object' && segment != null ? segment.key : segment }), } }), }) } return result } callTool( params: WithRequestOptions> & PerRequestElicit & { task?: undefined; allowInputRequired?: false }, ): Promise callTool( params: WithRequestOptions> & PerRequestElicit & { task?: undefined; allowInputRequired: true }, ): Promise callTool( params: WithRequestOptions> & PerRequestElicit & { task?: undefined; allowInputRequired: boolean }, ): Promise callTool( params: WithRequestOptions> & PerRequestElicit & { task: 'handle'; allowInputRequired?: false }, ): Promise callTool( params: WithRequestOptions> & PerRequestElicit & { task: 'handle'; allowInputRequired: true }, ): Promise callTool( params: WithRequestOptions> & PerRequestElicit & { task: 'handle'; allowInputRequired: boolean }, ): Promise async callTool( params: WithRequestOptions> & PerRequestElicit & { task?: 'handle' }, ): Promise { const { task, elicit, ...requestParams } = params const [wireParams, options] = splitRequestOptions(requestParams) const timeout = options?.timeout const deadline = timeout == null ? undefined : new AbortController() const timer = deadline == null ? undefined : setTimeout(() => { deadline.abort( new RequestTimeoutError({ message: `Request timed out after ${timeout}ms` }), ) }, timeout) const signal = deadline == null ? options?.signal : options?.signal == null ? deadline.signal : AbortSignal.any([options.signal, deadline.signal]) try { const result = await this.request('tools/call', wireParams as CallToolRequest['params'], { ...options, signal, elicit, }) if (isInputRequiredResult(result)) return result if (isCreateTaskResult(result)) { if (task === 'handle') return result try { return await this.waitForTask({ taskID: result.taskId, signal, toolName: params.name, cancelOnAbort: true, elicit, }) } catch (error) { // The connection went away after the server accepted the task: never replay it. const failure = transportFailureOf(error)?.kind if ( error instanceof TransportClosedError || failure === 'network' || failure === 'session-expired' ) { // biome-ignore lint/style/useErrorCause: the cause is passed through the params object throw new TaskInterruptedError({ taskID: result.taskId, cause: error }) } throw error } } return this.#validateToolOutput(result, params.name) } finally { clearTimeout(timer) } } }