@orkestrel/mcp 0.0.12 → 0.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -1
- package/dist/src/browser/index.d.ts +36 -24
- package/dist/src/browser/index.js +19 -13
- package/dist/src/browser/index.js.map +1 -1
- package/dist/src/core/index.cjs +4061 -983
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +4024 -1069
- package/dist/src/core/index.d.ts +4024 -1069
- package/dist/src/core/index.js +3982 -973
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +264 -108
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +220 -76
- package/dist/src/server/index.d.ts +220 -76
- package/dist/src/server/index.js +265 -112
- package/dist/src/server/index.js.map +1 -1
- package/package.json +7 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#handlers","#emitter","#options","#methods","#limits","#register","#modern","#legacy","#runTool","#discover","#list","#call","#subscribe","#input","#required","#subscription","#subscriptions","#emitter","#transport","#identity","#capabilities","#pin","#timeout","#probe","#pending","#offer","#receive","#connected","#version","#era","#initialize","#request","#settle","#tool","#text","#nextId","#timeoutRequest"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/parsers.ts","../../../src/core/inferers.ts","../../../src/core/helpers.ts","../../../src/core/MCPMethodManager.ts","../../../src/core/MCPServer.ts","../../../src/core/MCPClient.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { MCPVersion } from './types.js'\n\n// MCP protocol revisions, reserved modern `_meta` keys, and protocol error codes.\n// Transport-level header names (session / version headers) belong to the HTTP\n// transport, not core.\n\n/**\n * The revision offered and defaulted to in the legacy `initialize` handshake.\n *\n * @remarks\n * This is deliberately a legacy revision, and the newest one supported. 2026-07-28 is stateless\n * and defines no `initialize`, so it can never be the handshake's version — a client that offers\n * it is asking to negotiate a revision with no negotiation.\n */\nexport const MCP_PROTOCOL_VERSION: MCPVersion = '2025-11-25'\n\n/** The legacy fallback anchor used when an initialize request cannot be accepted as modern. */\nexport const MCP_LEGACY_VERSION: MCPVersion = '2025-06-18'\n\n/** The modern revision offered by an unpinned client during discovery. */\nexport const MCP_MODERN_VERSION: MCPVersion = '2026-07-28'\n\n/**\n * The MCP protocol revisions this server can negotiate.\n *\n * @remarks\n * `initialize` echoes the client's requested `protocolVersion` when it appears in\n * this list. Frozen in client-preference and discovery-advertisement order. The\n * package does not advertise `2025-03-26` because that revision mandates JSON-RPC\n * batching, while this package accepts only individual JSON-RPC messages.\n */\nexport const SUPPORTED_PROTOCOL_VERSIONS: readonly MCPVersion[] = Object.freeze([\n\t'2026-07-28',\n\t'2025-11-25',\n\t'2025-06-18',\n])\n\n/** Reserved modern `_meta` key carrying the request's protocol revision. */\nexport const MCP_META_VERSION = 'io.modelcontextprotocol/protocolVersion'\n\n/** Reserved modern `_meta` key carrying the client's open capability record. */\nexport const MCP_META_CAPABILITIES = 'io.modelcontextprotocol/clientCapabilities'\n\n/** Reserved modern `_meta` key carrying the optional client identity. */\nexport const MCP_META_CLIENT = 'io.modelcontextprotocol/clientInfo'\n\n/** Reserved modern `_meta` key carrying the server identity on results. */\nexport const MCP_META_SERVER = 'io.modelcontextprotocol/serverInfo'\n\n/** Reserved modern `_meta` key carrying a `subscriptions/listen` request id. */\nexport const MCP_META_SUBSCRIPTION = 'io.modelcontextprotocol/subscriptionId'\n\n/** MCP reserved error: required HTTP metadata does not match the request body. */\nexport const MCP_HEADER_MISMATCH = -32020\n\n/** MCP reserved error: an operation needs a client capability that was not declared. */\nexport const MCP_MISSING_CAPABILITY = -32021\n\n/** MCP reserved error: a request names an unsupported protocol revision. */\nexport const MCP_UNSUPPORTED_VERSION = -32022\n\n/**\n * Default modern result freshness lifetime in milliseconds.\n *\n * @remarks\n * `ttlMs` is required on cacheable results, while zero means immediately stale\n * rather than uncached, so the neutral usable default is one minute.\n */\nexport const DEFAULT_MCP_CACHE_TTL = 60_000\n\n/**\n * Secure server bounds used when the matching `limit` option leaf is absent or malformed.\n *\n * @remarks\n * One MiB admits ordinary JSON-RPC requests and substantial tool arguments; 16 KiB admits\n * extension-rich modern metadata and signed multi-round state; four MiB admits substantial\n * JSON tool output without allowing an unconfigured service to serialize arbitrary process\n * memory; 64 metadata keys admits the reserved keys plus many extensions; 128 concurrent\n * streams admits a busy service while bounding retained producers; depth 32 admits ordinary\n * JSON documents while rejecting stack-hostile nesting. Frozen so callers cannot alter the\n * defaults observed by later servers.\n */\nexport const DEFAULT_MCP_LIMITS = Object.freeze({\n\tmessage: 1_048_576,\n\tmetadata: 16_384,\n\tkeys: 64,\n\tstate: 16_384,\n\tcontent: 4_194_304,\n\tsubscriptions: 128,\n\tdepth: 32,\n})\n\n/** JSON-RPC 2.0 reserved error: invalid JSON was received (the message did not parse). */\nexport const JSONRPC_PARSE_ERROR = -32700\n\n/** JSON-RPC 2.0 reserved error: the payload was not a valid Request object. */\nexport const JSONRPC_INVALID_REQUEST = -32600\n\n/** JSON-RPC 2.0 reserved error: the requested method does not exist. */\nexport const JSONRPC_METHOD_NOT_FOUND = -32601\n\n/** JSON-RPC 2.0 reserved error: the method's parameters were invalid. */\nexport const JSONRPC_INVALID_PARAMS = -32602\n\n/** JSON-RPC 2.0 implementation-defined server error (the `-32000` to `-32099` range). */\nexport const JSONRPC_SERVER_ERROR = -32000\n\n// MCP CLIENT defaults — the identity an `MCPClient` reports in the `initialize`\n// handshake (`clientInfo`) and the per-request deadline, when the caller supplies\n// none. The egress mirror of the server's protocol-version constants above.\n\n/** The default client name reported in the MCP `initialize` handshake (`clientInfo.name`). */\nexport const DEFAULT_MCP_CLIENT_NAME = 'taverna'\n\n/** The default client version reported in the MCP `initialize` handshake (`clientInfo.version`). */\nexport const DEFAULT_MCP_CLIENT_VERSION = '1.0.0'\n\n/**\n * The default per-request deadline (ms) an `MCPClient` applies when `options.timeout`\n * is unset — a request the remote server does not answer within it rejects.\n */\nexport const DEFAULT_MCP_REQUEST_TIMEOUT = 30_000\n\n/** The maximum discovery-probe deadline used when a client deadline is configured. */\nexport const DEFAULT_MCP_PROBE_TIMEOUT = 50\n","/**\n * A remote Model Context Protocol JSON-RPC error, preserving its machine-readable\n * numeric code and optional structured context.\n *\n * @remarks\n * {@link MCPClient} throws this error only for a remote JSON-RPC `error` response.\n * Local lifecycle and transport conditions such as disconnects and request timeouts\n * remain plain `Error`s. `context` carries the response's optional `error.data`\n * unchanged and is `undefined` when the peer omitted it. This includes the modern\n * reserved paths: `-32020` carries no context, `-32021` may carry\n * `requiredCapabilities`, and `-32022` carries the peer's `supported` revisions and\n * `requested` revision for negotiation recovery.\n *\n * @example\n * ```ts\n * const error = new MCPError('Unsupported protocol version', -32022, {\n * \tsupported: ['2026-07-28'],\n * \trequested: '2024-11-05',\n * })\n * error.code // -32022\n * error.context // { supported: ['2026-07-28'], requested: '2024-11-05' }\n * ```\n */\nexport class MCPError extends Error {\n\toverride readonly name = 'MCPError'\n\treadonly code: number\n\treadonly context: unknown\n\n\t/**\n\t * Create a remote MCP protocol error.\n\t *\n\t * @param message - The human-readable JSON-RPC error message\n\t * @param code - The machine-readable numeric JSON-RPC error code\n\t * @param context - The optional JSON-RPC `error.data` payload\n\t */\n\tconstructor(message: string, code: number, context?: unknown) {\n\t\tsuper(message)\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/**\n * Determine whether an unknown value is an {@link MCPError}.\n *\n * @param value - The unknown value to inspect\n * @returns `true` only when the value is an `MCPError`\n *\n * @example\n * ```ts\n * isMCPError(new MCPError('Method not found', -32601)) // true\n * isMCPError(new Error('Method not found')) // false\n * ```\n */\nexport function isMCPError(value: unknown): value is MCPError {\n\ttry {\n\t\t// A revoked Proxy or a hostile prototype can make `instanceof` throw — this guard\n\t\t// must stay total, so the check is wrapped rather than left to escape.\n\t\treturn value instanceof MCPError\n\t} catch {\n\t\treturn false\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type {\n\tElicitRequest,\n\tElicitRequestFormParams,\n\tElicitRequestURLParams,\n\tElicitPrimitiveSchema,\n\tElicitResult,\n\tInputRequest,\n\tInputRequiredResult,\n\tInputRequests,\n\tJSONRPCMessage,\n\tJSONRPCRequest,\n\tJSONRPCResponse,\n\tMCPJSONLimitOptions,\n\tMCPVersion,\n\tSubscriptionFilter,\n} from './types.js'\nimport {\n\tarrayOf,\n\tattempt,\n\tenumerableKeys,\n\tisBoolean,\n\tisNumber,\n\tisRecord,\n\tisString,\n\tisUndefined,\n\tsanitizeBudget,\n} from '@orkestrel/contract'\nimport { MCP_META_VERSION, SUPPORTED_PROTOCOL_VERSIONS } from './constants.js'\n\n// AGENTS §14: every guard here is a TOTAL function over the already-`JSON.parse`d\n// value — adversarial input returns `false`, never throws. The raw-string\n// `JSON.parse` (which CAN throw) happens in `MCPServer.handle` inside a try/catch;\n// these guards only ever see a parsed `unknown`. Recursive structure is walked\n// iteratively with explicit ancestor/depth bounds, and callback-capable boundaries use\n// `attempt`, so totality is preserved without relying on the JavaScript call stack.\n\n/**\n * Determine whether a value is a string within a UTF-8 byte bound.\n *\n * @param value - The unknown value to inspect\n * @param bytes - The maximum accepted encoded bytes\n * @returns `true` only for a string whose UTF-8 representation fits the bound\n *\n * @example\n * ```ts\n * isBoundedString('€', 3) // true\n * isBoundedString('€', 2) // false\n * ```\n */\nexport function isBoundedString(value: unknown, bytes: number): value is string {\n\tif (!isString(value) || !Number.isFinite(bytes) || !Number.isInteger(bytes) || bytes < 0) {\n\t\treturn false\n\t}\n\tlet measured = 0\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst code = value.charCodeAt(index)\n\t\tif (code <= 0x7f) measured += 1\n\t\telse if (code <= 0x7ff) measured += 2\n\t\telse if (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = value.charCodeAt(index + 1)\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\tmeasured += 4\n\t\t\t\tindex += 1\n\t\t\t} else measured += 3\n\t\t} else measured += 3\n\t\tif (measured > bytes) return false\n\t}\n\treturn true\n}\n\n/**\n * Determine whether a value is bounded, cycle-free JSON with safe property names.\n *\n * @remarks\n * Traversal is iterative, ancestor-aware, and contained by {@link attempt}; deep input,\n * cycles, accessors, hostile proxies, `Map`/`Set`, and the prototype-pollution keys\n * `__proto__`, `constructor`, and `prototype` return `false` rather than throwing.\n * The byte count matches `JSON.stringify` without first allocating the serialization.\n *\n * @param value - The unknown value to inspect\n * @param limits - Serialized byte, optional key, and nesting-depth bounds\n * @returns `true` only for safe JSON satisfying every bound\n *\n * @example\n * ```ts\n * isBoundedJSON({ ok: true }, { bytes: 16, keys: 1, depth: 1 }) // true\n * ```\n */\nexport function isBoundedJSON<T>(value: T, limits: MCPJSONLimitOptions): value is T & JSONValue {\n\tconst outcome = attempt(() => {\n\t\tconst limit = sanitizeBudget(limits.bytes, 0)\n\t\tconst depth = sanitizeBudget(limits.depth, 0)\n\t\tconst breadth = limits.keys === undefined ? undefined : sanitizeBudget(limits.keys, 0)\n\t\tlet bytes = 0\n\t\tlet keys = 0\n\t\tconst ancestors = new WeakSet<object>()\n\t\tconst pending: { value: unknown; depth: number; closing: boolean }[] = [\n\t\t\t{ value, depth: 0, closing: false },\n\t\t]\n\t\twhile (pending.length > 0) {\n\t\t\tconst frame = pending.pop()\n\t\t\tif (frame === undefined) return false\n\t\t\tconst entry = frame.value\n\t\t\tif (frame.closing) {\n\t\t\t\tif (typeof entry !== 'object' || entry === null) return false\n\t\t\t\tancestors.delete(entry)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (frame.depth > depth) return false\n\t\t\tif (entry === null) bytes += 4\n\t\t\telse if (isBoolean(entry)) bytes += entry ? 4 : 5\n\t\t\t// A non-finite number is still serializable: `JSON.stringify` writes `NaN` and\n\t\t\t// ±`Infinity` as `null`, so they cost four bytes rather than being rejected. Only\n\t\t\t// `undefined` is genuinely absent from JSON, and it stays rejected below.\n\t\t\telse if (isNumber(entry)) bytes += Number.isFinite(entry) ? String(entry).length : 4\n\t\t\telse if (isString(entry)) {\n\t\t\t\tbytes += 2\n\t\t\t\tif (bytes > limit) return false\n\t\t\t\tfor (let index = 0; index < entry.length; index += 1) {\n\t\t\t\t\tconst code = entry.charCodeAt(index)\n\t\t\t\t\tif (\n\t\t\t\t\t\tcode === 0x22 ||\n\t\t\t\t\t\tcode === 0x5c ||\n\t\t\t\t\t\tcode === 0x08 ||\n\t\t\t\t\t\tcode === 0x09 ||\n\t\t\t\t\t\tcode === 0x0a ||\n\t\t\t\t\t\tcode === 0x0c ||\n\t\t\t\t\t\tcode === 0x0d\n\t\t\t\t\t) {\n\t\t\t\t\t\tbytes += 2\n\t\t\t\t\t} else if (code <= 0x1f) bytes += 6\n\t\t\t\t\telse if (code <= 0x7f) bytes += 1\n\t\t\t\t\telse if (code <= 0x7ff) bytes += 2\n\t\t\t\t\telse if (code >= 0xd800 && code <= 0xdbff) {\n\t\t\t\t\t\tconst next = entry.charCodeAt(index + 1)\n\t\t\t\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\t\t\t\tbytes += 4\n\t\t\t\t\t\t\tindex += 1\n\t\t\t\t\t\t} else bytes += 6\n\t\t\t\t\t} else if (code >= 0xdc00 && code <= 0xdfff) bytes += 6\n\t\t\t\t\telse bytes += 3\n\t\t\t\t\tif (bytes > limit) return false\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t} else if (typeof entry === 'object') {\n\t\t\t\tif (ancestors.has(entry)) return false\n\t\t\t\tconst names = enumerableKeys(entry)\n\t\t\t\tif (names === undefined) return false\n\t\t\t\tfor (const name of names) {\n\t\t\t\t\tif (name === '__proto__' || name === 'constructor' || name === 'prototype') {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (Array.isArray(entry)) {\n\t\t\t\t\tbytes += 2 + Math.max(0, entry.length - 1)\n\t\t\t\t\tif (bytes > limit || names.length !== entry.length) return false\n\t\t\t\t\tancestors.add(entry)\n\t\t\t\t\tpending.push({ value: entry, depth: frame.depth, closing: true })\n\t\t\t\t\tfor (let index = entry.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(entry, String(index))\n\t\t\t\t\t\tif (descriptor === undefined || !Object.hasOwn(descriptor, 'value')) return false\n\t\t\t\t\t\tpending.push({ value: descriptor.value, depth: frame.depth + 1, closing: false })\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (!isRecord(entry)) return false\n\t\t\t\tkeys += names.length\n\t\t\t\tif (breadth !== undefined && keys > breadth) return false\n\t\t\t\tbytes += 2 + Math.max(0, names.length - 1) + names.length\n\t\t\t\tif (bytes > limit) return false\n\t\t\t\tancestors.add(entry)\n\t\t\t\tpending.push({ value: entry, depth: frame.depth, closing: true })\n\t\t\t\tfor (let index = names.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tconst name = names[index]\n\t\t\t\t\tif (name === undefined) return false\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(entry, name)\n\t\t\t\t\tif (descriptor === undefined || !Object.hasOwn(descriptor, 'value')) return false\n\t\t\t\t\tpending.push({ value: descriptor.value, depth: frame.depth + 1, closing: false })\n\t\t\t\t\tpending.push({ value: name, depth: frame.depth, closing: false })\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t} else return false\n\t\t\tif (bytes > limit) return false\n\t\t}\n\t\treturn bytes <= limit\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/**\n * Determine whether a value is a valid JSON-RPC REQUEST `id` — a string, a number,\n * or absent.\n *\n * @remarks\n * A request id is a string, a number, or `undefined` (its ABSENCE marks a\n * NOTIFICATION). `null` is NOT a valid request id — it is valid only on a RESPONSE.\n * Total (§14): any other input returns `false`.\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a string, a number, or `undefined`\n *\n * @example\n * ```ts\n * isRequestId(1) // true\n * isRequestId('abc') // true\n * isRequestId(undefined) // true — a notification\n * isRequestId(null) // false — valid only on a response\n * ```\n */\nexport function isRequestId(value: unknown): value is string | number | undefined {\n\treturn isUndefined(value) || isString(value) || isNumber(value)\n}\n\n/**\n * Determine whether a value is a supported {@link MCPVersion}.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when the value is one of {@link SUPPORTED_PROTOCOL_VERSIONS}\n */\nexport function isMCPVersion(value: unknown): value is MCPVersion {\n\treturn isString(value) && SUPPORTED_PROTOCOL_VERSIONS.some((version) => version === value)\n}\n\n/**\n * Determine whether a value is an MCP {@link SubscriptionFilter}.\n *\n * @remarks\n * Every filter field is optional. Boolean notification families accept only booleans, and\n * `resourceSubscriptions` accepts only an array of string URIs. Unknown fields remain open\n * for protocol extensions and are ignored by the built-in subscription matcher. Total over\n * hostile input.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when every recognized filter field has its protocol shape\n */\nexport function isSubscriptionFilter(value: unknown): value is SubscriptionFilter {\n\tif (!isRecord(value)) return false\n\tconst tools = value['toolsListChanged']\n\tif (!isUndefined(tools) && !isBoolean(tools)) return false\n\tconst prompts = value['promptsListChanged']\n\tif (!isUndefined(prompts) && !isBoolean(prompts)) return false\n\tconst resources = value['resourcesListChanged']\n\tif (!isUndefined(resources) && !isBoolean(resources)) return false\n\tconst subscriptions = value['resourceSubscriptions']\n\treturn isUndefined(subscriptions) || arrayOf(isString)(subscriptions)\n}\n\n/**\n * Determine whether a client capability record declares form-mode elicitation.\n *\n * @remarks\n * The protocol's empty `elicitation` object is the implicit form-only declaration.\n * A non-empty declaration must carry a record-valued `form` member; URL-only support\n * does not authorize a form request. Total over hostile input.\n *\n * @param value - The client capability record to inspect\n * @returns `true` when form-mode elicitation is declared\n *\n * @example\n * ```ts\n * isFormElicitationSupported({ elicitation: {} }) // true — implicit form mode\n * isFormElicitationSupported({ elicitation: { url: {} } }) // false\n * ```\n */\nexport function isFormElicitationSupported(value: unknown): boolean {\n\ttry {\n\t\tif (!isRecord(value)) return false\n\t\tconst elicitation = value['elicitation']\n\t\tif (!isRecord(elicitation)) return false\n\t\tif (isRecord(elicitation['form'])) return true\n\t\treturn Object.keys(elicitation).length === 0\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one restricted primitive form-elicitation schema.\n *\n * @param value - The unknown value to inspect\n * @returns `true` for a supported boolean, numeric, string, or string-array schema\n *\n * @example\n * ```ts\n * isElicitPrimitiveSchema({ type: 'boolean', default: true }) // true\n * isElicitPrimitiveSchema({ type: 'object' }) // false\n * ```\n */\nexport function isElicitPrimitiveSchema(value: unknown): value is ElicitPrimitiveSchema {\n\ttry {\n\t\tif (!isRecord(value)) return false\n\t\tconst title = value['title']\n\t\tconst description = value['description']\n\t\tif (!isUndefined(title) && !isString(title)) return false\n\t\tif (!isUndefined(description) && !isString(description)) return false\n\n\t\tconst fallback = value['default']\n\t\tif (value['type'] === 'boolean') return isUndefined(fallback) || isBoolean(fallback)\n\t\tif (value['type'] === 'number' || value['type'] === 'integer') {\n\t\t\tconst minimum = value['minimum']\n\t\t\tconst maximum = value['maximum']\n\t\t\treturn (\n\t\t\t\t(isUndefined(minimum) || isNumber(minimum)) &&\n\t\t\t\t(isUndefined(maximum) || isNumber(maximum)) &&\n\t\t\t\t(isUndefined(fallback) || isNumber(fallback))\n\t\t\t)\n\t\t}\n\t\tif (value['type'] === 'string') {\n\t\t\tconst minimum = value['minLength']\n\t\t\tconst maximum = value['maxLength']\n\t\t\tconst format = value['format']\n\t\t\tconst choices = value['enum']\n\t\t\tconst names = value['enumNames']\n\t\t\tconst titled = value['oneOf']\n\t\t\treturn (\n\t\t\t\t(isUndefined(minimum) || isNumber(minimum)) &&\n\t\t\t\t(isUndefined(maximum) || isNumber(maximum)) &&\n\t\t\t\t(isUndefined(format) ||\n\t\t\t\t\tformat === 'uri' ||\n\t\t\t\t\tformat === 'email' ||\n\t\t\t\t\tformat === 'date' ||\n\t\t\t\t\tformat === 'date-time') &&\n\t\t\t\t(isUndefined(fallback) || isString(fallback)) &&\n\t\t\t\t(isUndefined(choices) || arrayOf(isString)(choices)) &&\n\t\t\t\t(isUndefined(names) || arrayOf(isString)(names)) &&\n\t\t\t\t(isUndefined(titled) ||\n\t\t\t\t\t(arrayOf(isRecord)(titled) &&\n\t\t\t\t\t\ttitled.every((choice) => isString(choice['const']) && isString(choice['title']))))\n\t\t\t)\n\t\t}\n\t\tif (value['type'] !== 'array') return false\n\t\tconst minimum = value['minItems']\n\t\tconst maximum = value['maxItems']\n\t\tconst items = value['items']\n\t\tif (\n\t\t\t(!isUndefined(minimum) && !isNumber(minimum)) ||\n\t\t\t(!isUndefined(maximum) && !isNumber(maximum)) ||\n\t\t\t(!isUndefined(fallback) && !arrayOf(isString)(fallback)) ||\n\t\t\t!isRecord(items)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (items['type'] === 'string') return arrayOf(isString)(items['enum'])\n\t\tconst choices = items['anyOf']\n\t\treturn (\n\t\t\tarrayOf(isRecord)(choices) &&\n\t\t\tchoices.every((choice) => isString(choice['const']) && isString(choice['title']))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is a form-mode elicitation parameter object.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when `value` has the restricted form elicitation shape\n *\n * @example\n * ```ts\n * isElicitRequestFormParams({\n * message: 'Continue?',\n * requestedSchema: { type: 'object', properties: {} },\n * }) // true\n * ```\n */\nexport function isElicitRequestFormParams(value: unknown): value is ElicitRequestFormParams {\n\ttry {\n\t\tif (!isRecord(value)) return false\n\t\tconst mode = value['mode']\n\t\tif (!isUndefined(mode) && mode !== 'form') return false\n\t\tif (!isString(value['message'])) return false\n\t\tconst schema = value['requestedSchema']\n\t\tif (!isRecord(schema) || schema['type'] !== 'object' || !isRecord(schema['properties'])) {\n\t\t\treturn false\n\t\t}\n\t\tconst dialect = schema['$schema']\n\t\tif (!isUndefined(dialect) && !isString(dialect)) return false\n\t\tconst required = schema['required']\n\t\treturn (\n\t\t\t(isUndefined(required) || arrayOf(isString)(required)) &&\n\t\t\tObject.values(schema['properties']).every((property) => isElicitPrimitiveSchema(property))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is a URL-mode elicitation parameter object.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when `value` has the URL elicitation shape\n *\n * @example\n * ```ts\n * isElicitRequestURLParams({ mode: 'url', message: 'Authenticate', url: 'https://example.test' })\n * ```\n */\nexport function isElicitRequestURLParams(value: unknown): value is ElicitRequestURLParams {\n\treturn (\n\t\tisRecord(value) &&\n\t\tvalue['mode'] === 'url' &&\n\t\tisString(value['message']) &&\n\t\tisString(value['url'])\n\t)\n}\n\n/**\n * Determine whether a value is an embedded `elicitation/create` request.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when `value` is a form- or URL-mode elicitation request\n *\n * @example\n * ```ts\n * isElicitRequest({\n * method: 'elicitation/create',\n * params: { message: 'Continue?', requestedSchema: { type: 'object', properties: {} } },\n * }) // true\n * ```\n */\nexport function isElicitRequest(value: unknown): value is ElicitRequest {\n\tif (!isRecord(value) || value['method'] !== 'elicitation/create') return false\n\treturn isElicitRequestFormParams(value['params']) || isElicitRequestURLParams(value['params'])\n}\n\n/**\n * Determine whether a value is one legal embedded multi-round-trip request.\n *\n * @param value - The unknown value to inspect\n * @returns `true` for elicitation, deprecated sampling, or deprecated roots requests\n *\n * @example\n * ```ts\n * isInputRequest({ method: 'roots/list' }) // true — legal but not produced by this package\n * ```\n */\nexport function isInputRequest(value: unknown): value is InputRequest {\n\tif (isElicitRequest(value)) return true\n\tif (!isRecord(value)) return false\n\tconst params = value['params']\n\tif (value['method'] === 'sampling/createMessage') return isRecord(params)\n\treturn value['method'] === 'roots/list' && (isUndefined(params) || isRecord(params))\n}\n\n/**\n * Determine whether a value is a server-keyed map of embedded input requests.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when every own value is a legal {@link InputRequest}\n *\n * @example\n * ```ts\n * isInputRequests({ confirm: { method: 'roots/list' } }) // true; maps, never arrays\n * ```\n */\nexport function isInputRequests(value: unknown): value is InputRequests {\n\ttry {\n\t\treturn isRecord(value) && Object.values(value).every((request) => isInputRequest(request))\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one elicitation response.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when action/content have the protocol shape\n *\n * @example\n * ```ts\n * isElicitResult({ action: 'accept', content: { approved: true } }) // true\n * ```\n */\nexport function isElicitResult(value: unknown): value is ElicitResult {\n\ttry {\n\t\tif (!isRecord(value)) return false\n\t\tconst action = value['action']\n\t\tif (action !== 'accept' && action !== 'decline' && action !== 'cancel') return false\n\t\tconst content = value['content']\n\t\tif (isUndefined(content)) return true\n\t\tif (!isRecord(content)) return false\n\t\treturn Object.values(content).every(\n\t\t\t(item) => isString(item) || isNumber(item) || isBoolean(item) || arrayOf(isString)(item),\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is an MCP input-required result.\n *\n * @remarks\n * Enforces the at-least-one-of rule at runtime: `inputRequests`, `requestState`, or\n * both must be present and valid. Total over hostile input.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when `value` is a valid input-required result\n *\n * @example\n * ```ts\n * isInputRequiredResult({ resultType: 'input_required', requestState: 'opaque' }) // true\n * isInputRequiredResult({ resultType: 'input_required' }) // false\n * ```\n */\nexport function isInputRequiredResult(value: unknown): value is InputRequiredResult {\n\ttry {\n\t\tif (!isRecord(value) || value['resultType'] !== 'input_required') return false\n\t\tconst inputRequests = value['inputRequests']\n\t\tconst requestState = value['requestState']\n\t\tif (!isUndefined(inputRequests) && !isInputRequests(inputRequests)) return false\n\t\tif (!isUndefined(requestState) && !isString(requestState)) return false\n\t\treturn !isUndefined(inputRequests) || !isUndefined(requestState)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCRequest}.\n *\n * @remarks\n * A request is a record with `jsonrpc === '2.0'` and a string `method`. `id`, when\n * present, must be a string or number; its ABSENCE is valid — that marks a\n * NOTIFICATION (a fire-and-forget request that yields no response). `params`, when\n * present, must be a record. Total (§14): any other input returns `false`.\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC request\n *\n * @example\n * ```ts\n * isJSONRPCRequest({ jsonrpc: '2.0', method: 'ping', id: 1 }) // true\n * isJSONRPCRequest({ jsonrpc: '2.0', method: 'notifications/initialized' }) // true — a notification\n * isJSONRPCRequest({ jsonrpc: '1.0', method: 'ping' }) // false\n * ```\n */\nexport function isJSONRPCRequest(value: unknown): value is JSONRPCRequest {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\tif (value['jsonrpc'] !== '2.0' || !isString(value['method'])) {\n\t\treturn false\n\t}\n\tif (!isRequestId(value['id'])) {\n\t\treturn false\n\t}\n\tconst params = value['params']\n\treturn isUndefined(params) || isRecord(params)\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCResponse}.\n *\n * @remarks\n * A response is a record with `jsonrpc === '2.0'`, an `id` that is a string,\n * number, or `null`, and EXACTLY ONE of a `result` (any value, including\n * `undefined`'s absence) or an `error` (a record with a numeric `code` and string\n * `message`). Total (§14).\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC response\n */\nexport function isJSONRPCResponse(value: unknown): value is JSONRPCResponse {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\tif (value['jsonrpc'] !== '2.0') {\n\t\treturn false\n\t}\n\tconst id = value['id']\n\tif (id !== null && !isString(id) && !isNumber(id)) {\n\t\treturn false\n\t}\n\tconst hasResult = Object.hasOwn(value, 'result')\n\tconst error = value['error']\n\tconst hasError = !isUndefined(error)\n\t// Exactly one of result / error — never both, never neither.\n\tif (hasResult === hasError) {\n\t\treturn false\n\t}\n\tif (hasError) {\n\t\treturn isRecord(error) && isNumber(error['code']) && isString(error['message'])\n\t}\n\treturn true\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCMessage} — a request or a\n * response.\n *\n * @remarks\n * The union of {@link isJSONRPCRequest} and {@link isJSONRPCResponse}. Total (§14).\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC request or response\n */\nexport function isJSONRPCMessage(value: unknown): value is JSONRPCMessage {\n\treturn isJSONRPCRequest(value) || isJSONRPCResponse(value)\n}\n\n/**\n * Determine whether a parsed value is an MCP `initialize` request — a\n * {@link JSONRPCRequest} whose `method` is `'initialize'`.\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid `initialize` request\n *\n * @example\n * ```ts\n * isInitializeRequest({ jsonrpc: '2.0', method: 'initialize', id: 1 }) // true\n * isInitializeRequest({ jsonrpc: '2.0', method: 'ping', id: 1 }) // false\n * ```\n */\nexport function isInitializeRequest(value: unknown): value is JSONRPCRequest {\n\treturn isJSONRPCRequest(value) && value.method === 'initialize'\n}\n\n/**\n * Determine whether a JSON-RPC request uses the modern per-request MCP wire shape.\n *\n * @remarks\n * Presence routes and validity answers: this guard checks only that\n * `params._meta` carries the reserved protocol-version key. The key's value is\n * deliberately not narrowed here, so a present non-string version remains modern\n * and is rejected later by `parseRequestContext` rather than falling through to\n * legacy dispatch. Total over hostile and malformed input.\n *\n * @param value - The already-parsed value to inspect\n * @returns `true` when the value is a request carrying the reserved version key\n */\nexport function isModernRequest(value: unknown): value is JSONRPCRequest {\n\ttry {\n\t\tif (!isJSONRPCRequest(value)) return false\n\t\tconst metadata = value.params?.['_meta']\n\t\treturn isRecord(metadata) && Object.hasOwn(metadata, MCP_META_VERSION)\n\t} catch {\n\t\treturn false\n\t}\n}\n","import type { JSONRPCMessage, MCPInputState, MCPRequestContext } from './types.js'\nimport { isNumber, isRecord, isString, isUndefined } from '@orkestrel/contract'\nimport { MCP_META_CAPABILITIES, MCP_META_CLIENT, MCP_META_VERSION } from './constants.js'\nimport { isJSONRPCMessage, isModernRequest } from './validators.js'\n\n/**\n * Narrow an already-parsed value to a {@link JSONRPCMessage}, or `undefined` when\n * it is not one.\n *\n * @remarks\n * Total (§14) — a non-message returns `undefined`, never throws. The input must\n * ALREADY be `JSON.parse`d: the raw-string parse (which can throw on malformed\n * JSON) happens in `MCPServer.handle` inside a try/catch that maps a parse failure\n * to a `-32700` response. Sound with {@link isJSONRPCMessage}: a guard-valid input\n * is returned unchanged, and every non-`undefined` output satisfies the guard.\n *\n * @param value - The already-parsed value to narrow\n * @returns The value as a {@link JSONRPCMessage}, or `undefined`\n *\n * @example\n * ```ts\n * parseJSONRPCMessage({ jsonrpc: '2.0', method: 'ping', id: 1 }) // the request\n * parseJSONRPCMessage({ method: 'ping' }) // undefined — missing jsonrpc\n * ```\n */\nexport function parseJSONRPCMessage(value: unknown): JSONRPCMessage | undefined {\n\treturn isJSONRPCMessage(value) ? value : undefined\n}\n\n/**\n * Parse the reserved modern request metadata into an {@link MCPRequestContext}.\n *\n * @remarks\n * This is the validity step after {@link isModernRequest}: a defined result can\n * only come from a guard-positive request, while a guard-positive request returns\n * `undefined` exactly when its required modern metadata is malformed. The version\n * must be a string but need not be supported; unsupported strings belong to the\n * dedicated protocol-version error path. Client identity is optional, but when\n * present it must carry string `name` and `version` members. Total over hostile and\n * malformed input.\n *\n * @param value - The already-parsed request candidate to coerce\n * @returns The validated modern request context, or `undefined`\n */\nexport function parseRequestContext(value: unknown): MCPRequestContext | undefined {\n\ttry {\n\t\tif (!isModernRequest(value)) return undefined\n\t\tconst metadata = value.params?.['_meta']\n\t\tif (!isRecord(metadata)) return undefined\n\t\tconst version = metadata[MCP_META_VERSION]\n\t\tconst capabilities = metadata[MCP_META_CAPABILITIES]\n\t\tif (!isString(version) || !isRecord(capabilities)) return undefined\n\t\tconst client = metadata[MCP_META_CLIENT]\n\t\tif (client === undefined) return { version, capabilities }\n\t\tif (!isRecord(client)) return undefined\n\t\tconst name = client['name']\n\t\tconst clientVersion = client['version']\n\t\tif (!isString(name) || !isString(clientVersion)) return undefined\n\t\treturn {\n\t\t\tversion,\n\t\t\tcapabilities,\n\t\t\tidentity: { name, version: clientVersion },\n\t\t}\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Parse the verified value embedded in an opaque signed `requestState` token.\n *\n * @remarks\n * This parser does not verify the HMAC; {@link import('@orkestrel/server').verifyToken}\n * performs that boundary first and returns the JSON string parsed here. The protected\n * payload binds the authenticated principal, token lifetime, originating request id,\n * server-assigned input key, tool name, and optional consumer state. Total over malformed\n * or hostile input.\n *\n * @param value - The HMAC-verified token value to parse\n * @returns The protected input state, or `undefined` when malformed\n *\n * @example\n * ```ts\n * parseMCPInputState('{\"principal\":\"user-1\",\"ttl\":1000,\"origin\":1,\"key\":\"k\",\"name\":\"reply\"}')\n * // { principal: 'user-1', ttl: 1000, origin: 1, key: 'k', name: 'reply' }\n * ```\n */\nexport function parseMCPInputState(value: unknown): MCPInputState | undefined {\n\ttry {\n\t\tif (!isString(value)) return undefined\n\t\tconst parsed: unknown = JSON.parse(value)\n\t\tif (!isRecord(parsed)) return undefined\n\t\tconst principal = parsed['principal']\n\t\tconst ttl = parsed['ttl']\n\t\tconst origin = parsed['origin']\n\t\tconst key = parsed['key']\n\t\tconst name = parsed['name']\n\t\tconst state = parsed['state']\n\t\tif (!isString(principal) || !isNumber(ttl) || !Number.isFinite(ttl)) return undefined\n\t\tif (!isString(origin) && !isNumber(origin)) return undefined\n\t\tif (!isString(key) || !isString(name)) return undefined\n\t\tif (!isUndefined(state) && !isString(state)) return undefined\n\t\treturn {\n\t\t\tprincipal,\n\t\t\tttl,\n\t\t\torigin,\n\t\t\tkey,\n\t\t\tname,\n\t\t\t...(isString(state) ? { state } : {}),\n\t\t}\n\t} catch {\n\t\treturn undefined\n\t}\n}\n","import type { MCPEra, MCPVersion } from './types.js'\nimport { SUPPORTED_PROTOCOL_VERSIONS } from './constants.js'\n\n/**\n * Infer the wire era for an MCP protocol revision.\n *\n * @param version - The protocol revision to classify\n * @returns `'modern'` for `2026-07-28`, `'legacy'` for either supported legacy\n * revision, or `undefined` when the revision is unsupported\n */\nexport function inferEra(version: string): MCPEra | undefined {\n\tswitch (version) {\n\t\tcase '2026-07-28':\n\t\t\treturn 'modern'\n\t\tcase '2025-11-25':\n\t\tcase '2025-06-18':\n\t\t\treturn 'legacy'\n\t\tdefault:\n\t\t\treturn undefined\n\t}\n}\n\n/**\n * Infer the newest supported protocol revision present in a peer's offer.\n *\n * @param offered - The protocol revisions offered by the peer\n * @returns The newest locally supported offered revision, or `undefined`\n */\nexport function inferVersion(offered: readonly string[]): MCPVersion | undefined {\n\tfor (const version of SUPPORTED_PROTOCOL_VERSIONS) {\n\t\tif (offered.includes(version)) return version\n\t}\n\treturn undefined\n}\n","import type { ToolManagerInterface, ToolResult } from '@orkestrel/tool'\nimport type {\n\tJSONRPCRequest,\n\tJSONRPCResponse,\n\tMCPCallResult,\n\tMCPClientInterface,\n\tMCPDiscoverResult,\n\tMCPIdentity,\n\tMCPServerInterface,\n\tMCPServerOptions,\n\tMCPStream,\n\tMCPTextStream,\n\tMCPToolDescriptor,\n\tMCPTransportInterface,\n\tSubscriptionFilter,\n\tSubscriptionsListenResult,\n\tSubscriptionsListenResultMetaObject,\n} from './types.js'\nimport { isRecord } from '@orkestrel/contract'\nimport {\n\tDEFAULT_MCP_CACHE_TTL,\n\tMCP_LEGACY_VERSION,\n\tMCP_META_SERVER,\n\tMCP_META_SUBSCRIPTION,\n\tSUPPORTED_PROTOCOL_VERSIONS,\n} from './constants.js'\nimport { inferEra } from './inferers.js'\nimport { parseJSONRPCMessage } from './parsers.js'\nimport { isMCPVersion } from './validators.js'\n\n// Pure dispatch builders (AGENTS §5: the dispatch branches stay exported helpers,\n// not hidden privates). Each turns a piece of MCP state into the JSON-RPC `result`\n// payload (or a response envelope) the server returns — independently testable.\n\n/**\n * Build a JSON-RPC success {@link JSONRPCResponse} — the `id` echoed, the method's\n * value as `result`.\n *\n * @param id - The request's id (`null` only for a parse / invalid-request error)\n * @param result - The method's return value\n * @returns The success response envelope\n */\nexport function buildJSONRPCResult(id: string | number | null, result: unknown): JSONRPCResponse {\n\treturn { jsonrpc: '2.0', id, result }\n}\n\n/**\n * Build a JSON-RPC error {@link JSONRPCResponse} — the `id` echoed, the failure as\n * an `error` object.\n *\n * @param id - The request's id (`null` for a parse / invalid-request error)\n * @param code - One of the reserved JSON-RPC codes (see `./constants.js`)\n * @param message - A short human description of the failure\n * @param data - An OPTIONAL machine-readable payload (omitted from the envelope when absent)\n * @returns The error response envelope\n */\nexport function buildJSONRPCError(\n\tid: string | number | null,\n\tcode: number,\n\tmessage: string,\n\tdata?: unknown,\n): JSONRPCResponse {\n\treturn {\n\t\tjsonrpc: '2.0',\n\t\tid,\n\t\terror: data === undefined ? { code, message } : { code, message, data },\n\t}\n}\n\n/**\n * Map a {@link ToolManagerInterface}'s definitions to MCP `tools/list` descriptors\n * — renaming `parameters` to the wire's `inputSchema`.\n *\n * @remarks\n * Each {@link import('@orkestrel/tool').ToolDefinition} carries through its\n * `name` and (when present) `description`; its open JSON-Schema `parameters`\n * becomes `inputSchema`, defaulting to an empty object schema (`{ type: 'object' }`)\n * when a tool declares none (MCP requires an `inputSchema`).\n *\n * @param manager - The tool registry to describe\n * @returns One {@link MCPToolDescriptor} per registered tool, in registry order\n */\nexport function buildToolDescriptors(manager: ToolManagerInterface): readonly MCPToolDescriptor[] {\n\treturn manager.definitions().map((definition) => {\n\t\tconst descriptor: {\n\t\t\tname: string\n\t\t\tdescription?: string\n\t\t\tinputSchema: Readonly<Record<string, unknown>>\n\t\t} = {\n\t\t\tname: definition.name,\n\t\t\tinputSchema: definition.parameters ?? { type: 'object' },\n\t\t}\n\t\tif (definition.description !== undefined) descriptor.description = definition.description\n\t\treturn descriptor\n\t})\n}\n\n/**\n * Map an executed tool's {@link ToolResult} to an MCP {@link MCPCallResult} — the\n * value as structured content plus a backwards-compatible `text` block, or the\n * error as a `text` block.\n *\n * @remarks\n * The {@link ToolManagerInterface} already isolates a thrown tool into a\n * `success: false` result (so the server adds NO try/catch around `execute`):\n * that branch builds an `isError: true` result carrying `result.error`, so the\n * model sees the failure as a tool result it can react to rather than a protocol\n * error; a valued `success: true` branch carries `result.value` unchanged as\n * `structuredContent` and serializes it (via `JSON.stringify`) into one `text`\n * block. A value-less success retains the required empty `content` block and\n * omits `structuredContent`.\n *\n * @param result - The tool's execution outcome\n * @returns The MCP tool-call result\n */\nexport function buildCallResult(result: ToolResult): MCPCallResult {\n\tif (!result.success) {\n\t\treturn { content: [{ type: 'text', text: result.error }], isError: true }\n\t}\n\t// A content block must carry a string `text`; `JSON.stringify(undefined)` is the value\n\t// `undefined` (which serializes away), so a value-less result becomes an empty text block.\n\tif (result.value === undefined) return { content: [{ type: 'text', text: '' }] }\n\treturn {\n\t\tcontent: [{ type: 'text', text: JSON.stringify(result.value) }],\n\t\tstructuredContent: result.value,\n\t}\n}\n\n/**\n * Stamp a result with the modern complete-result discriminator and server\n * metadata, plus cache fields when the result is cacheable.\n *\n * @remarks\n * This is the single stamping site shared by modern result builders. Supplying\n * `ttl` adds both schema-coupled fields (`ttlMs` and `cacheScope`); omitting it\n * adds neither, which keeps `tools/call` distinct from cacheable results.\n *\n * @param result - The unstamped result payload\n * @param identity - The server identity carried under the reserved `_meta` key\n * @param ttl - Required freshness lifetime for a cacheable result; omit for a non-cacheable result\n * @param scope - The cache visibility, defaulting to `'private'` when `ttl` is supplied\n * @returns A copy of the payload with its modern stamps\n */\nexport function buildModernResult<T extends object>(\n\tresult: T,\n\tidentity: MCPIdentity,\n\tttl: number,\n\tscope?: 'public' | 'private',\n): T & {\n\treadonly resultType: 'complete'\n\treadonly _meta: Readonly<Record<string, unknown>>\n\treadonly ttlMs: number\n\treadonly cacheScope: 'public' | 'private'\n}\nexport function buildModernResult<T extends object>(\n\tresult: T,\n\tidentity: MCPIdentity,\n): T & {\n\treadonly resultType: 'complete'\n\treadonly _meta: Readonly<Record<string, unknown>>\n}\nexport function buildModernResult<T extends object>(\n\tresult: T,\n\tidentity: MCPIdentity,\n\tttl?: number,\n\tscope?: 'public' | 'private',\n): T & {\n\treadonly resultType: 'complete'\n\treadonly _meta: Readonly<Record<string, unknown>>\n\treadonly ttlMs?: number\n\treadonly cacheScope?: 'public' | 'private'\n} {\n\tconst currentMetadata = isRecord(result) ? result['_meta'] : undefined\n\tconst metadata = {\n\t\t...(isRecord(currentMetadata) ? currentMetadata : {}),\n\t\t[MCP_META_SERVER]: identity,\n\t}\n\tif (ttl === undefined) return { ...result, resultType: 'complete', _meta: metadata }\n\treturn {\n\t\t...result,\n\t\tresultType: 'complete',\n\t\tttlMs: ttl,\n\t\tcacheScope: scope ?? 'private',\n\t\t_meta: metadata,\n\t}\n}\n\n/**\n * Intersect a requested subscription filter with the notification families a server supports.\n *\n * @param requested - The notification families requested by the client\n * @param supported - The notification families the server can actually produce\n * @returns The exact subset the server will honour\n */\nexport function buildSubscriptionFilter(\n\trequested: SubscriptionFilter,\n\tsupported: SubscriptionFilter,\n): SubscriptionFilter {\n\tconst toolsListChanged =\n\t\trequested.toolsListChanged === true && supported.toolsListChanged === true\n\tconst promptsListChanged =\n\t\trequested.promptsListChanged === true && supported.promptsListChanged === true\n\tconst resourcesListChanged =\n\t\trequested.resourcesListChanged === true && supported.resourcesListChanged === true\n\tconst supportedResources = new Set(supported.resourceSubscriptions ?? [])\n\tconst resourceSubscriptions = requested.resourceSubscriptions?.filter((uri) =>\n\t\tsupportedResources.has(uri),\n\t)\n\treturn {\n\t\t...(toolsListChanged ? { toolsListChanged: true } : {}),\n\t\t...(promptsListChanged ? { promptsListChanged: true } : {}),\n\t\t...(resourcesListChanged ? { resourcesListChanged: true } : {}),\n\t\t...(resourceSubscriptions !== undefined && resourceSubscriptions.length > 0\n\t\t\t? { resourceSubscriptions }\n\t\t\t: {}),\n\t}\n}\n\n/**\n * Determine whether a produced notification belongs to an honoured subscription filter.\n *\n * @param notification - The server notification offered by the configured producer\n * @param filter - The filter acknowledged to the client\n * @returns `true` when the notification belongs on this subscription stream\n */\nexport function matchesSubscriptionNotification(\n\tnotification: JSONRPCRequest,\n\tfilter: SubscriptionFilter,\n): boolean {\n\tif (notification.method === 'notifications/tools/list_changed') {\n\t\treturn filter.toolsListChanged === true\n\t}\n\tif (notification.method === 'notifications/prompts/list_changed') {\n\t\treturn filter.promptsListChanged === true\n\t}\n\tif (notification.method === 'notifications/resources/list_changed') {\n\t\treturn filter.resourcesListChanged === true\n\t}\n\tif (notification.method !== 'notifications/resources/updated') return false\n\tconst uri = notification.params?.['uri']\n\treturn typeof uri === 'string' && filter.resourceSubscriptions?.includes(uri) === true\n}\n\n/**\n * Stamp a subscription notification with the request id reserved for its held-open stream.\n *\n * @param notification - The notification to copy and stamp\n * @param id - The `subscriptions/listen` request id\n * @returns The stamped notification, preserving its other params and metadata\n */\nexport function stampSubscriptionNotification(\n\tnotification: JSONRPCRequest,\n\tid: string | number,\n): JSONRPCRequest {\n\tconst metadata = notification.params?.['_meta']\n\treturn {\n\t\tjsonrpc: notification.jsonrpc,\n\t\tmethod: notification.method,\n\t\tparams: {\n\t\t\t...notification.params,\n\t\t\t_meta: {\n\t\t\t\t...(isRecord(metadata) ? metadata : {}),\n\t\t\t\t[MCP_META_SUBSCRIPTION]: id,\n\t\t\t},\n\t\t},\n\t}\n}\n\n/**\n * Build the first notification carrying a subscription id for a listen request.\n *\n * @param notifications - The exact notification filter the server will honour\n * @param id - The `subscriptions/listen` request id\n * @returns The stamped subscription acknowledgement notification\n */\nexport function buildSubscriptionAcknowledgement(\n\tnotifications: SubscriptionFilter,\n\tid: string | number,\n): JSONRPCRequest {\n\treturn stampSubscriptionNotification(\n\t\t{\n\t\t\tjsonrpc: '2.0',\n\t\t\tmethod: 'notifications/subscriptions/acknowledged',\n\t\t\tparams: { notifications },\n\t\t},\n\t\tid,\n\t)\n}\n\n/**\n * Build the terminating response for a subscription source that closes gracefully.\n *\n * @param id - The `subscriptions/listen` request id\n * @param identity - The server identity included by the modern result stamping site\n * @returns The complete modern result carrying the required subscription id metadata\n */\nexport function buildSubscriptionResult(\n\tid: string | number,\n\tidentity: MCPIdentity,\n): JSONRPCResponse {\n\tconst metadata: SubscriptionsListenResultMetaObject = { [MCP_META_SUBSCRIPTION]: id }\n\tconst result: SubscriptionsListenResult = buildModernResult({ _meta: metadata }, identity)\n\treturn buildJSONRPCResult(id, result)\n}\n\n/**\n * Build the mandatory modern `server/discover` result.\n *\n * @param options - The server identity, instructions, and cache configuration\n * @returns The supported revisions, tools capability, and required modern cache stamps\n */\nexport function buildDiscoverResult(options: MCPServerOptions): MCPDiscoverResult {\n\treturn buildModernResult(\n\t\t{\n\t\t\tsupportedVersions: SUPPORTED_PROTOCOL_VERSIONS.filter(isMCPVersion),\n\t\t\tcapabilities: { tools: {} },\n\t\t\t...(options.instructions === undefined ? {} : { instructions: options.instructions }),\n\t\t},\n\t\toptions.identity,\n\t\toptions.cache?.ttl ?? DEFAULT_MCP_CACHE_TTL,\n\t\toptions.cache?.scope,\n\t)\n}\n\n/**\n * Build the MCP `initialize` result — the negotiated protocol version, the\n * advertised capabilities, and the server identity.\n *\n * @remarks\n * Version negotiation echoes the client's `requested` version when it is one of the\n * supported legacy revisions. A modern or unsupported request receives the newest\n * supported legacy revision; the client decides whether to continue.\n * `capabilities.tools` is an empty object — this server advertises the tools\n * capability with no sub-options (no list-changed notification yet).\n *\n * @param name - The server name (echoed in `serverInfo`)\n * @param version - The server version (echoed in `serverInfo`)\n * @param requested - The client's requested protocol version (negotiated when supported)\n * @returns The `initialize` result payload\n */\nexport function buildInitializeResult(\n\tname: string,\n\tversion: string,\n\trequested?: string,\n): Readonly<Record<string, unknown>> {\n\tconst newestLegacy =\n\t\tSUPPORTED_PROTOCOL_VERSIONS.find((candidate) => inferEra(candidate) === 'legacy') ??\n\t\tMCP_LEGACY_VERSION\n\tconst protocolVersion =\n\t\tisMCPVersion(requested) && inferEra(requested) === 'legacy' ? requested : newestLegacy\n\treturn {\n\t\tprotocolVersion,\n\t\tcapabilities: { tools: {} },\n\t\tserverInfo: { name, version },\n\t}\n}\n\n// Held-open stream leaves — the two pure transformations that carry an\n// {@link MCPStream} across the string boundary and onto a transport. Both consume the\n// generator MANUALLY rather than with `for await`, because `for await` discards the\n// `return` value and the terminating response IS that value.\n\n/**\n * Serialize a typed {@link MCPStream} into its string mirror — each yielded\n * notification and the terminating response, already `JSON.stringify`d.\n *\n * @remarks\n * The string-boundary half of the held-open arm: `handle` returns this so a transport\n * writes each message with no second parse, exactly as it writes a unary reply string.\n * The terminating response arrives as the returned generator's OWN `return` value, so a\n * consumer distinguishes \"one more notification\" from \"this is the answer\" without a\n * sentinel.\n *\n * @param stream - The typed held-open result to serialize\n * @returns The same sequence with every message serialized to a string\n *\n * @example\n * ```ts\n * const text = serializeStream(stream)\n * for (let next = await text.next(); ; next = await text.next()) {\n * \tif (next.done === true) return next.value // the terminating response, serialized\n * \tlog(next.value) // one serialized notification\n * }\n * ```\n */\nexport async function* serializeStream(stream: MCPStream): MCPTextStream {\n\tlet next = await stream.next()\n\twhile (!next.done) {\n\t\tyield JSON.stringify(next.value)\n\t\tnext = await stream.next()\n\t}\n\treturn JSON.stringify(next.value)\n}\n\n/**\n * Pump an {@link MCPTextStream} onto a transport — every notification in order, then the\n * terminating response.\n *\n * @remarks\n * The generator's `return` value is a message like any other on the wire: it is sent\n * LAST and closes the exchange. Sends are awaited one at a time so the transport\n * receives the sequence in the order the method produced it.\n *\n * @param stream - The serialized held-open result to write out\n * @param transport - The duplex channel to write each message to\n * @returns Resolves once the terminating response has been sent\n *\n * @example\n * ```ts\n * const answer = await server.handle(message)\n * if (typeof answer !== 'string') await sendStream(answer, transport)\n * ```\n */\nexport async function sendStream(\n\tstream: MCPTextStream,\n\ttransport: MCPTransportInterface,\n): Promise<void> {\n\tlet next = await stream.next()\n\twhile (!next.done) {\n\t\tawait transport.send(next.value)\n\t\tnext = await stream.next()\n\t}\n\tawait transport.send(next.value)\n}\n\n// The environment-agnostic PORT binders — the keystone that lets an\n// {@link MCPServerInterface} / {@link MCPClientInterface} run over ANY\n// {@link MCPTransportInterface} (a Node stdio pair, a browser MessagePort, a Web\n// Worker `self`) with no per-environment dispatch/correlation wiring duplicated at\n// each face. Both are TOTAL: a `send` throw or rejection is caught and never\n// escapes as an unhandled rejection.\n\n/**\n * Pipe an {@link MCPTransportInterface} into an {@link MCPServerInterface} — every\n * inbound message runs through `server.handle`, and a defined reply is written back\n * via `transport.send`.\n *\n * @remarks\n * `server.handle` already turns a malformed message into a serialized `-32700` /\n * `-32600` reply and a notification into `undefined` (no reply), so this binder adds\n * no parsing of its own. A HELD-OPEN reply arrives as an\n * {@link import('./types.js').MCPTextStream} instead of a string: this is the one place\n * that pumps it, writing each notification in order and then the generator's returned\n * terminating response ({@link sendStream}). A `transport.send` throw or rejection —\n * mid-stream included — is caught and routed\n * to `server.emitter`'s `error` event (never rethrown, never an unhandled rejection);\n * a listener on that event that itself throws is swallowed (the end of the line —\n * the caller's own bug, never this binder's). The returned unbind DETACHES this\n * binder (further inbound messages and the transport's `closed` signal are ignored)\n * WITHOUT closing the transport — closing is the caller's decision.\n *\n * `listen`/`closed` are REPLACE semantics (§ port contract): the returned unbind\n * DETACHES by replacing this binder's own handlers with no-ops, so a subsequent\n * `bindServer` call on the SAME transport is never double-dispatched by a stale\n * subscription left behind — an unbind→rebind cycle yields exactly one reply per\n * request.\n *\n * @param server - The transport-agnostic server to dispatch inbound messages over\n * @param transport - The duplex channel to pipe the server over\n * @returns Detach this binder from the transport (does not close it)\n *\n * @example\n * ```ts\n * const unbind = bindServer(server, transport)\n * // ... later, detach without closing:\n * unbind()\n * ```\n */\nexport function bindServer(\n\tserver: MCPServerInterface,\n\ttransport: MCPTransportInterface,\n): () => void {\n\tlet active = true\n\ttransport.listen(async (message) => {\n\t\tif (!active) return\n\t\ttry {\n\t\t\tconst answer = await server.handle(message)\n\t\t\tif (answer === undefined) return\n\t\t\tif (typeof answer === 'string') await transport.send(answer)\n\t\t\telse await sendStream(answer, transport)\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tserver.emitter.emit('error', error)\n\t\t\t} catch {\n\t\t\t\t// A throwing `error` listener is the caller's own bug — the end of the line.\n\t\t\t}\n\t\t}\n\t})\n\ttransport.closed(() => {\n\t\tactive = false\n\t})\n\treturn () => {\n\t\tactive = false\n\t\ttransport.listen(() => {})\n\t\ttransport.closed(() => {})\n\t}\n}\n\n/**\n * Pipe an {@link MCPTransportInterface} into an {@link MCPClientInterface} — every\n * inbound message is decoded and delivered onto the client's OWN transport\n * (`client.transport.emitter`'s `message` / `close` events), resolving/rejecting the\n * client's correlated pending requests exactly as a direct reply would.\n *\n * @remarks\n * The client's outbound writes flow through `client.transport.send` — its existing,\n * unmodified request/response correlation — so `client` must have been constructed\n * with a {@link import('./types.js').ClientTransportInterface} that itself carries\n * the SAME `transport` (see {@link import('./factories.js').createDuplexClientTransport},\n * the additive factory that adapts an {@link MCPTransportInterface} into that shape);\n * this binder then completes the inbound half by decoding each message and pushing it\n * onto `client.transport.emitter` (an {@link import('@orkestrel/emitter').EmitterInterface}\n * exposes `emit`, so no client modification is needed). A malformed / non-JSON-RPC\n * inbound message is DROPPED (§14, total — never throws); a delivery fault is routed to\n * `client.transport.emitter`'s `error` event (never rethrown). The returned unbind\n * DETACHES this binder (further inbound messages and the transport's `closed` signal are\n * ignored) WITHOUT closing the transport.\n *\n * `listen`/`closed` are REPLACE semantics (§ port contract): the returned unbind\n * DETACHES by replacing this binder's own handlers with no-ops, so a subsequent\n * `bindClient` call on the SAME transport is never double-dispatched by a stale\n * subscription left behind — an unbind→rebind cycle delivers exactly one `message`\n * emit per inbound reply.\n *\n * @param client - The transport-agnostic client whose transport to deliver messages onto\n * @param transport - The duplex channel to pipe the client over\n * @returns Detach this binder from the transport (does not close it)\n *\n * @example\n * ```ts\n * const client = createMCPClient({ transport: createDuplexClientTransport(transport) })\n * const unbind = bindClient(client, transport)\n * await client.connect()\n * // ... later, detach without closing:\n * unbind()\n * ```\n */\nexport function bindClient(\n\tclient: MCPClientInterface,\n\ttransport: MCPTransportInterface,\n): () => void {\n\tlet active = true\n\ttransport.listen((message) => {\n\t\tif (!active) return\n\t\tlet parsed: unknown\n\t\ttry {\n\t\t\tparsed = JSON.parse(message)\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\t\tconst decoded = parseJSONRPCMessage(parsed)\n\t\tif (decoded === undefined) return\n\t\ttry {\n\t\t\tclient.transport.emitter.emit('message', decoded)\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tclient.transport.emitter.emit('error', error)\n\t\t\t} catch {\n\t\t\t\t// A throwing `error` listener is the caller's own bug — the end of the line.\n\t\t\t}\n\t\t}\n\t})\n\ttransport.closed(() => {\n\t\tif (!active) return\n\t\tactive = false\n\t\ttry {\n\t\t\tclient.transport.emitter.emit('close')\n\t\t} catch {\n\t\t\t// A throwing `close` listener is the caller's own bug — the end of the line.\n\t\t}\n\t})\n\treturn () => {\n\t\tactive = false\n\t\ttransport.listen(() => {})\n\t\ttransport.closed(() => {})\n\t}\n}\n","import type { MCPMethodHandler, MCPMethodManagerInterface } from './types.js'\n\n/**\n * The modern method registry an {@link import('./types.js').MCPServerInterface}\n * dispatches through — a name-keyed store of {@link MCPMethodHandler}s that owns its\n * map rather than exposing one.\n *\n * @remarks\n * - **One seam.** The server registers its built-in modern methods here at construction\n * and resolves EVERY modern method from here, so a consumer's method and a built-in\n * are the same kind of thing on the same path.\n * - **Registration is a write, not a merge.** `add` under a name already present\n * REPLACES it, which is how a consumer overrides a built-in; there is no precedence\n * rule to remember.\n * - **A narrower contract than a `Map`.** Callers register and resolve; they cannot\n * iterate, clear, or otherwise reach the server's internal state through it.\n *\n * @example\n * ```ts\n * const methods = new MCPMethodManager()\n * methods.add('tools/list', async (request) => buildJSONRPCResult(request.id ?? null, { tools: [] }))\n * methods.method('tools/list') // the handler\n * methods.method('tools/nope') // undefined → the dispatch branch answers -32601\n * ```\n */\nexport class MCPMethodManager implements MCPMethodManagerInterface {\n\treadonly #handlers = new Map<string, MCPMethodHandler>()\n\n\tadd(name: string, handler: MCPMethodHandler): void {\n\t\tthis.#handlers.set(name, handler)\n\t}\n\n\tmethod(name: string): MCPMethodHandler | undefined {\n\t\treturn this.#handlers.get(name)\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tJSONRPCRequest,\n\tJSONRPCResponse,\n\tMCPElicitation,\n\tMCPCallResult,\n\tMCPDispatchOptions,\n\tMCPIdentity,\n\tMCPLimitOptions,\n\tMCPMethodManagerInterface,\n\tMCPServerEventMap,\n\tMCPServerInterface,\n\tMCPServerOptions,\n\tMCPStream,\n\tMCPTextStream,\n\tSubscriptionFilter,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { attempt, isRecord, isString, sanitizeBudget } from '@orkestrel/contract'\nimport { signToken, verifyToken } from '@orkestrel/server'\nimport {\n\tDEFAULT_MCP_CACHE_TTL,\n\tDEFAULT_MCP_LIMITS,\n\tJSONRPC_INVALID_PARAMS,\n\tJSONRPC_INVALID_REQUEST,\n\tJSONRPC_METHOD_NOT_FOUND,\n\tJSONRPC_PARSE_ERROR,\n\tJSONRPC_SERVER_ERROR,\n\tMCP_META_SERVER,\n\tMCP_MISSING_CAPABILITY,\n\tMCP_UNSUPPORTED_VERSION,\n\tSUPPORTED_PROTOCOL_VERSIONS,\n} from './constants.js'\nimport {\n\tbuildCallResult,\n\tbuildDiscoverResult,\n\tbuildInitializeResult,\n\tbuildJSONRPCError,\n\tbuildJSONRPCResult,\n\tbuildModernResult,\n\tbuildSubscriptionAcknowledgement,\n\tbuildSubscriptionFilter,\n\tbuildSubscriptionResult,\n\tbuildToolDescriptors,\n\tmatchesSubscriptionNotification,\n\tserializeStream,\n\tstampSubscriptionNotification,\n} from './helpers.js'\nimport { inferEra } from './inferers.js'\nimport { MCPMethodManager } from './MCPMethodManager.js'\nimport { parseJSONRPCMessage, parseMCPInputState, parseRequestContext } from './parsers.js'\nimport {\n\tisElicitRequestFormParams,\n\tisElicitResult,\n\tisBoundedJSON,\n\tisBoundedString,\n\tisFormElicitationSupported,\n\tisModernRequest,\n\tisSubscriptionFilter,\n} from './validators.js'\n\n/**\n * A transport-agnostic Model Context Protocol server — dispatches JSON-RPC 2.0\n * requests over a live {@link ToolManagerInterface}, with NO transport coupling.\n *\n * @remarks\n * - **Two entry points.** `dispatch(request)` runs an already-parsed request and\n * resolves a {@link JSONRPCResponse} — or `undefined` for a NOTIFICATION (a\n * request with no `id`). `handle(message)` is the string boundary: it\n * `JSON.parse`s the raw message (a failure → a `-32700` response), narrows it to\n * a request (a non-request → a `-32600` response), dispatches, and serializes the\n * response back to a string (`undefined` for a notification).\n * - **Dual-era dispatch.** A request carrying the reserved modern version key uses\n * modern metadata validation and the registered method seam. Every other request\n * uses the legacy `initialize` / `ping` / `tools/list` / `tools/call` switch. The\n * wire era is selected per request and never stored.\n * - **One modern seam.** `server/discover`, `tools/list`, `tools/call`, and\n * `subscriptions/listen` are\n * registered on `methods` at construction and resolved from it on every dispatch —\n * the same path a later method or a consumer's own takes, with an unregistered\n * method still answering `-32601`.\n * - **Provider-agnostic.** Imports only core siblings — JSON-RPC + the tool registry,\n * no HTTP, no model. Wire fields are narrowed via the contracts guards (no `as`).\n * - **Observable (§13).** The owned `emitter` fires `request` at the top of every\n * dispatch; the emitter isolates a listener throw and routes it to its `error` handler\n * (the `error` option), so a listener throw can never escape the dispatch.\n *\n * @example\n * ```ts\n * const tools = createToolManager()\n * tools.add(createTool({ name: 'add', execute: (a) => Number(a.x) + Number(a.y) }))\n * const server = new MCPServer({ identity: { name: 'demo', version: '1.0.0' }, tools })\n * await server.handle('{\"jsonrpc\":\"2.0\",\"method\":\"ping\",\"id\":1}') // '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}'\n * ```\n */\nexport class MCPServer implements MCPServerInterface {\n\treadonly #emitter: Emitter<MCPServerEventMap>\n\treadonly #options: MCPServerOptions\n\treadonly #methods: MCPMethodManager\n\treadonly #limits: Required<MCPLimitOptions>\n\t#subscriptions = 0\n\n\tconstructor(options: MCPServerOptions) {\n\t\tthis.#emitter = new Emitter<MCPServerEventMap>({\n\t\t\t...(options.on !== undefined ? { on: options.on } : {}),\n\t\t\t...(options.error !== undefined ? { error: options.error } : {}),\n\t\t})\n\t\tthis.#options = options\n\t\tthis.#limits = {\n\t\t\tmessage: sanitizeBudget(options.limit?.message, DEFAULT_MCP_LIMITS.message),\n\t\t\tmetadata: sanitizeBudget(options.limit?.metadata, DEFAULT_MCP_LIMITS.metadata),\n\t\t\tkeys: sanitizeBudget(options.limit?.keys, DEFAULT_MCP_LIMITS.keys),\n\t\t\tstate: sanitizeBudget(options.limit?.state, DEFAULT_MCP_LIMITS.state),\n\t\t\tcontent: sanitizeBudget(options.limit?.content, DEFAULT_MCP_LIMITS.content),\n\t\t\tsubscriptions: sanitizeBudget(options.limit?.subscriptions, DEFAULT_MCP_LIMITS.subscriptions),\n\t\t\tdepth: sanitizeBudget(options.limit?.depth, DEFAULT_MCP_LIMITS.depth),\n\t\t}\n\t\tthis.#methods = new MCPMethodManager()\n\t\tthis.#register()\n\t}\n\n\tget emitter(): EmitterInterface<MCPServerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget identity(): MCPIdentity {\n\t\treturn this.#options.identity\n\t}\n\n\tget methods(): MCPMethodManagerInterface {\n\t\treturn this.#methods\n\t}\n\n\tasync dispatch(\n\t\trequest: JSONRPCRequest,\n\t\toptions: MCPDispatchOptions = {},\n\t): Promise<JSONRPCResponse | MCPStream | undefined> {\n\t\tconst id = request.id ?? null\n\t\tconst modern = isModernRequest(request)\n\t\tconst era = modern ? 'modern' : 'legacy'\n\t\tthis.#emitter.emit('request', request.method, id, era)\n\t\t// JSON-RPC: a request with NO `id` is a NOTIFICATION — it is handled (the\n\t\t// `request` event already fired) but NEVER produces a response, whatever its\n\t\t// method (`notifications/initialized`, a fire-and-forget `ping`, an unknown\n\t\t// method — all silent). So short-circuit here, and the branches below only ever\n\t\t// run for an id-bearing request that expects a reply.\n\t\tif (request.id === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst metadata = request.params?.['_meta']\n\t\tif (\n\t\t\tmetadata !== undefined &&\n\t\t\t!isBoundedJSON(metadata, {\n\t\t\t\tbytes: this.#limits.metadata,\n\t\t\t\tkeys: this.#limits.keys,\n\t\t\t\tdepth: this.#limits.depth,\n\t\t\t})\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `_meta` exceeds the configured limit or contains an unsafe value',\n\t\t\t)\n\t\t}\n\t\treturn modern ? this.#modern(request, id, options) : this.#legacy(request, id, options)\n\t}\n\n\tasync handle(\n\t\tmessage: string,\n\t\toptions?: MCPDispatchOptions,\n\t): Promise<string | MCPTextStream | undefined> {\n\t\tif (!isBoundedString(message, this.#limits.message)) {\n\t\t\treturn JSON.stringify(buildJSONRPCError(null, JSONRPC_PARSE_ERROR, 'Parse error'))\n\t\t}\n\t\tlet parsed: unknown\n\t\ttry {\n\t\t\tparsed = JSON.parse(message)\n\t\t} catch {\n\t\t\treturn JSON.stringify(buildJSONRPCError(null, JSONRPC_PARSE_ERROR, 'Parse error'))\n\t\t}\n\t\tconst decoded = parseJSONRPCMessage(parsed)\n\t\t// Only a REQUEST is dispatchable — a response (or any non-message) is invalid input.\n\t\tif (decoded === undefined || !('method' in decoded)) {\n\t\t\treturn JSON.stringify(buildJSONRPCError(null, JSONRPC_INVALID_REQUEST, 'Invalid Request'))\n\t\t}\n\t\tconst answer = await this.dispatch(decoded, options)\n\t\tif (answer === undefined) return undefined\n\t\t// The ONE narrowing point (§4.3): a held-open answer becomes the string mirror of\n\t\t// itself, so the string boundary stays a mirror of the typed core.\n\t\treturn Symbol.asyncIterator in answer ? serializeStream(answer) : JSON.stringify(answer)\n\t}\n\n\tasync #legacy(\n\t\trequest: JSONRPCRequest,\n\t\tid: string | number | null,\n\t\toptions: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tswitch (request.method) {\n\t\t\tcase 'initialize': {\n\t\t\t\tconst requested = request.params?.['protocolVersion']\n\t\t\t\treturn buildJSONRPCResult(\n\t\t\t\t\tid,\n\t\t\t\t\tbuildInitializeResult(\n\t\t\t\t\t\tthis.#options.identity.name,\n\t\t\t\t\t\tthis.#options.identity.version,\n\t\t\t\t\t\tisString(requested) ? requested : undefined,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t\tcase 'ping':\n\t\t\t\treturn buildJSONRPCResult(id, {})\n\t\t\tcase 'tools/list':\n\t\t\t\treturn buildJSONRPCResult(id, {\n\t\t\t\t\ttools: buildToolDescriptors(this.#options.tools),\n\t\t\t\t})\n\t\t\tcase 'tools/call': {\n\t\t\t\tconst result = await this.#runTool(request, id, options)\n\t\t\t\treturn 'jsonrpc' in result ? result : buildJSONRPCResult(id, result)\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn buildJSONRPCError(\n\t\t\t\t\tid,\n\t\t\t\t\tJSONRPC_METHOD_NOT_FOUND,\n\t\t\t\t\t`Method not found: ${request.method}`,\n\t\t\t\t)\n\t\t}\n\t}\n\n\t// Register the built-in modern methods on the seam `#modern` resolves from — the\n\t// point of the seam is that these four are not special: they are the first four\n\t// registrations, and a later one (or a consumer's) replaces or joins them in place.\n\t#register(): void {\n\t\tthis.#methods.add('server/discover', (request) => this.#discover(request))\n\t\tthis.#methods.add('tools/list', (request) => this.#list(request))\n\t\tthis.#methods.add('tools/call', (request, options) => this.#call(request, options))\n\t\tthis.#methods.add('subscriptions/listen', (request, options) =>\n\t\t\tthis.#subscribe(request, options),\n\t\t)\n\t}\n\n\tasync #modern(\n\t\trequest: JSONRPCRequest,\n\t\tid: string | number | null,\n\t\toptions: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | MCPStream | undefined> {\n\t\tconst context = parseRequestContext(request)\n\t\tif (context === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: malformed modern request metadata',\n\t\t\t)\n\t\t}\n\t\tif (inferEra(context.version) === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tMCP_UNSUPPORTED_VERSION,\n\t\t\t\t`Unsupported protocol version: ${context.version}`,\n\t\t\t\t{ supported: SUPPORTED_PROTOCOL_VERSIONS, requested: context.version },\n\t\t\t)\n\t\t}\n\t\tconst handler = this.#methods.method(request.method)\n\t\tif (handler === undefined) {\n\t\t\treturn buildJSONRPCError(id, JSONRPC_METHOD_NOT_FOUND, `Method not found: ${request.method}`)\n\t\t}\n\t\treturn handler(request, options)\n\t}\n\n\t// The built-in `server/discover` handler.\n\tasync #discover(request: JSONRPCRequest): Promise<JSONRPCResponse> {\n\t\treturn buildJSONRPCResult(request.id ?? null, buildDiscoverResult(this.#options))\n\t}\n\n\t// The built-in modern `tools/list` handler — a cacheable result, so it carries both\n\t// schema-coupled cache stamps.\n\tasync #list(request: JSONRPCRequest): Promise<JSONRPCResponse> {\n\t\treturn buildJSONRPCResult(\n\t\t\trequest.id ?? null,\n\t\t\tbuildModernResult(\n\t\t\t\t{ tools: buildToolDescriptors(this.#options.tools) },\n\t\t\t\tthis.#options.identity,\n\t\t\t\tthis.#options.cache?.ttl ?? DEFAULT_MCP_CACHE_TTL,\n\t\t\t\tthis.#options.cache?.scope,\n\t\t\t),\n\t\t)\n\t}\n\n\t// The built-in modern `tools/call` handler — stamped, and NOT cacheable, so it\n\t// carries no cache fields.\n\tasync #call(request: JSONRPCRequest, options: MCPDispatchOptions = {}): Promise<JSONRPCResponse> {\n\t\tconst id = request.id ?? null\n\t\tconst input = await this.#input(request, options)\n\t\tif (input !== undefined) return input\n\t\tconst result = await this.#runTool(request, id, options)\n\t\treturn 'jsonrpc' in result\n\t\t\t? result\n\t\t\t: buildJSONRPCResult(id, buildModernResult(result, this.#options.identity))\n\t}\n\n\t// The built-in modern `tools/call` input mechanism. It is deliberately reachable\n\t// only from `#call`: the other modern handlers cannot produce `input_required`.\n\tasync #input(\n\t\trequest: JSONRPCRequest,\n\t\toptions: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | undefined> {\n\t\tconst configured = this.#options.input\n\t\tif (configured === undefined) return undefined\n\t\tconst id = request.id\n\t\tif (id === undefined) return undefined\n\t\tconst params = request.params\n\t\tconst name = params?.['name']\n\t\tif (!isString(name)) return undefined\n\t\tconst rawArguments = params?.['arguments']\n\t\tconst args = isRecord(rawArguments) ? rawArguments : {}\n\t\tconst requestState = params?.['requestState']\n\t\tconst inputResponses = params?.['inputResponses']\n\t\tif (requestState === undefined && inputResponses === undefined) {\n\t\t\tconst elicitation = await configured.elicit({ request, name, arguments: args }, options)\n\t\t\tif (elicitation === undefined) return undefined\n\t\t\tconst principal = await configured.principal(request, options)\n\t\t\treturn this.#required(request, name, elicitation, principal)\n\t\t}\n\t\tif (!isBoundedString(requestState, this.#limits.state) || !isRecord(inputResponses)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `inputResponses` and `requestState` are required together',\n\t\t\t)\n\t\t}\n\t\tconst verified = await verifyToken(requestState, configured.secret)\n\t\tconst state = parseMCPInputState(verified)\n\t\tconst principal = await configured.principal(request, options)\n\t\tif (\n\t\t\tstate === undefined ||\n\t\t\tstate.principal !== principal ||\n\t\t\tstate.ttl !== configured.ttl ||\n\t\t\tstate.origin === id ||\n\t\t\tstate.name !== name ||\n\t\t\t!Object.hasOwn(inputResponses, state.key)\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state could not be verified for this retry',\n\t\t\t)\n\t\t}\n\t\tconst response = inputResponses[state.key]\n\t\tif (!isElicitResult(response)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: the elicitation response is missing or malformed',\n\t\t\t)\n\t\t}\n\t\tconst elicitation = await configured.elicit(\n\t\t\t{\n\t\t\t\trequest,\n\t\t\t\tname,\n\t\t\t\targuments: args,\n\t\t\t\tresponse,\n\t\t\t\t...(state.state !== undefined ? { state: state.state } : {}),\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\treturn elicitation === undefined\n\t\t\t? undefined\n\t\t\t: this.#required(request, name, elicitation, principal)\n\t}\n\n\t// Build one form-mode round and seal the call-in-hand state. The random map key is\n\t// minted here, never accepted from the consumer, and is carried inside the HMAC payload.\n\tasync #required(\n\t\trequest: JSONRPCRequest,\n\t\tname: string,\n\t\telicitation: MCPElicitation,\n\t\tprincipal: string,\n\t): Promise<JSONRPCResponse> {\n\t\tconst id = request.id\n\t\tif (id === undefined) {\n\t\t\treturn buildJSONRPCError(null, JSONRPC_INVALID_REQUEST, 'Invalid Request')\n\t\t}\n\t\tconst context = parseRequestContext(request)\n\t\tif (context === undefined || !isFormElicitationSupported(context.capabilities)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tMCP_MISSING_CAPABILITY,\n\t\t\t\t'Server requires the elicitation capability for this request',\n\t\t\t\t{ requiredCapabilities: { elicitation: {} } },\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\t!isElicitRequestFormParams(elicitation.request) ||\n\t\t\tprincipal.length === 0 ||\n\t\t\t!Number.isFinite(this.#options.input?.ttl) ||\n\t\t\t(this.#options.input?.ttl ?? 0) <= 0\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: elicitation policy returned an invalid form or signing context',\n\t\t\t)\n\t\t}\n\t\tconst configured = this.#options.input\n\t\tif (configured === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: input is not configured',\n\t\t\t)\n\t\t}\n\t\tconst key = crypto.randomUUID()\n\t\tconst protectedState = {\n\t\t\tprincipal,\n\t\t\tttl: configured.ttl,\n\t\t\torigin: id,\n\t\t\tkey,\n\t\t\tname,\n\t\t\t...(elicitation.state !== undefined ? { state: elicitation.state } : {}),\n\t\t}\n\t\tif (\n\t\t\t!isBoundedJSON(protectedState, {\n\t\t\t\tbytes: this.#limits.state,\n\t\t\t\tdepth: this.#limits.depth,\n\t\t\t})\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state exceeds the configured limit',\n\t\t\t)\n\t\t}\n\t\tconst requestState = await signToken(JSON.stringify(protectedState), {\n\t\t\tsecret: configured.secret,\n\t\t\tttl: configured.ttl,\n\t\t})\n\t\tif (!isBoundedString(requestState, this.#limits.state)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state exceeds the configured limit',\n\t\t\t)\n\t\t}\n\t\treturn buildJSONRPCResult(id, {\n\t\t\tresultType: 'input_required',\n\t\t\tinputRequests: {\n\t\t\t\t[key]: {\n\t\t\t\t\tmethod: 'elicitation/create',\n\t\t\t\t\tparams: { ...elicitation.request, mode: 'form' },\n\t\t\t\t},\n\t\t\t},\n\t\t\trequestState,\n\t\t\t_meta: { [MCP_META_SERVER]: this.#options.identity },\n\t\t})\n\t}\n\n\t// The built-in modern `subscriptions/listen` handler validates the client's filter,\n\t// then returns the event-driven generator that owns acknowledgement and closure order.\n\tasync #subscribe(\n\t\trequest: JSONRPCRequest,\n\t\toptions: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | MCPStream> {\n\t\tconst id = request.id\n\t\tif (id === undefined) {\n\t\t\treturn buildJSONRPCError(null, JSONRPC_INVALID_REQUEST, 'Invalid Request')\n\t\t}\n\t\tconst requested = request.params?.['notifications']\n\t\tif (!isSubscriptionFilter(requested)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: a valid `notifications` filter is required',\n\t\t\t)\n\t\t}\n\t\treturn this.#subscription(requested, id, options)\n\t}\n\n\tasync *#subscription(\n\t\trequested: SubscriptionFilter,\n\t\tid: string | number,\n\t\toptions: MCPDispatchOptions,\n\t): MCPStream {\n\t\tif (this.#subscriptions >= this.#limits.subscriptions) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_SERVER_ERROR,\n\t\t\t\t'Server limit reached: too many live subscriptions',\n\t\t\t)\n\t\t}\n\t\tthis.#subscriptions += 1\n\t\ttry {\n\t\t\tconst configured = this.#options.subscription\n\t\t\tconst notifications = buildSubscriptionFilter(requested, configured?.notifications ?? {})\n\t\t\tyield buildSubscriptionAcknowledgement(notifications, id)\n\t\t\tif (configured !== undefined) {\n\t\t\t\tconst source = await configured.listen(notifications, options)\n\t\t\t\tfor await (const notification of source) {\n\t\t\t\t\tif (matchesSubscriptionNotification(notification, notifications)) {\n\t\t\t\t\t\tyield stampSubscriptionNotification(notification, id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn buildSubscriptionResult(id, this.#options.identity)\n\t\t} finally {\n\t\t\tthis.#subscriptions -= 1\n\t\t}\n\t}\n\n\t// Run a `tools/call`: narrow `params.name` (string) + `params.arguments` (record,\n\t// default `{}`) with no `as`, execute the tool (the manager isolates a throw into\n\t// `success: false`), conditionally carry asserted caller context on the ToolCall,\n\t// and map the result to an MCP tool-call result. Shared by both eras — only the result\n\t// STAMPING differs between them.\n\tasync #runTool(\n\t\trequest: JSONRPCRequest,\n\t\tid: string | number | null,\n\t\toptions: MCPDispatchOptions,\n\t): Promise<MCPCallResult | JSONRPCResponse> {\n\t\tconst params = request.params\n\t\tconst name = params?.['name']\n\t\tif (!isString(name)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: a string `name` is required',\n\t\t\t)\n\t\t}\n\t\tconst rawArguments = params?.['arguments']\n\t\tconst args = isRecord(rawArguments) ? rawArguments : {}\n\t\tconst callId = request.id === undefined ? crypto.randomUUID() : String(request.id)\n\t\tconst result = await this.#options.tools.execute({\n\t\t\tid: callId,\n\t\t\tname,\n\t\t\targuments: args,\n\t\t\t...(options.caller === undefined ? {} : { caller: options.caller }),\n\t\t})\n\t\tif (!result.success && !isBoundedString(result.error, this.#limits.content)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_SERVER_ERROR,\n\t\t\t\t'Server limit exceeded: tool content is too large',\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\tresult.success &&\n\t\t\tresult.value !== undefined &&\n\t\t\t!isBoundedJSON(result.value, {\n\t\t\t\tbytes: this.#limits.content,\n\t\t\t\tdepth: this.#limits.depth,\n\t\t\t})\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_SERVER_ERROR,\n\t\t\t\t'Server limit exceeded: tool content is too large or unsafe',\n\t\t\t)\n\t\t}\n\t\tconst built = attempt(() => buildCallResult(result))\n\t\treturn built.success\n\t\t\t? built.value\n\t\t\t: buildJSONRPCError(id, JSONRPC_SERVER_ERROR, 'Server could not serialize tool content')\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { ToolInterface } from '@orkestrel/tool'\nimport type {\n\tClientTransportInterface,\n\tJSONRPCMessage,\n\tJSONRPCRequest,\n\tMCPClientEventMap,\n\tMCPClientInterface,\n\tMCPClientOptions,\n\tMCPDiscoverResult,\n\tMCPEra,\n\tMCPIdentity,\n\tMCPVersion,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { Tool } from '@orkestrel/tool'\nimport { isArray, isNumber, isRecord, isString } from '@orkestrel/contract'\nimport {\n\tDEFAULT_MCP_CLIENT_NAME,\n\tDEFAULT_MCP_CLIENT_VERSION,\n\tDEFAULT_MCP_PROBE_TIMEOUT,\n\tDEFAULT_MCP_REQUEST_TIMEOUT,\n\tJSONRPC_INVALID_PARAMS,\n\tJSONRPC_INVALID_REQUEST,\n\tJSONRPC_METHOD_NOT_FOUND,\n\tMCP_META_CAPABILITIES,\n\tMCP_META_CLIENT,\n\tMCP_META_VERSION,\n\tMCP_MODERN_VERSION,\n\tMCP_PROTOCOL_VERSION,\n\tMCP_UNSUPPORTED_VERSION,\n} from './constants.js'\nimport { MCPError, isMCPError } from './errors.js'\nimport { inferEra, inferVersion } from './inferers.js'\nimport { isJSONRPCResponse, isMCPVersion, isRequestId } from './validators.js'\n\n/**\n * A transport-agnostic Model Context Protocol CLIENT — connects to a REMOTE MCP server\n * over an injected {@link ClientTransportInterface}, negotiates the modern or legacy\n * wire era, and exposes the server's tools as local {@link ToolInterface}s an agent can run.\n *\n * @remarks\n * - **The mirror of `MCPServer`.** The server DISPATCHES requests over a tool registry;\n * this client ISSUES them over a transport. `connect` probes `server/discover` unless\n * pinned legacy, falls back to `initialize` only for a legacy peer, and exposes the\n * negotiated `version`; `tools()` lists the remote tools and wraps each as a\n * local {@link ToolInterface} whose `execute` calls back through `call`; `call` runs a\n * remote `tools/call` and returns the tool's value (a remote `isError: true` throws\n * locally, so an agent's {@link import('@orkestrel/tool').ToolManagerInterface}\n * isolates it into a `success: false` result just like a local throw).\n * - **Request↔response correlation.** Each request is tagged with a monotonic numeric\n * `id` ({@link #nextId}); a single transport `message` subscription resolves / rejects\n * the matching {@link #pending} entry by `id`. A message that is NOT a response to a\n * pending request is a server NOTIFICATION — re-surfaced on the `notification` event.\n * - **Per-request deadline.** Each `#request` receives its own deadline: ordinary calls use\n * `this.#timeout`, while an explicitly bounded discovery uses the shorter probe deadline.\n * `AbortSignal.timeout` (never a raw `setTimeout`) rejects only that pending request.\n * - **Transport-agnostic.** Imports only core siblings (JSON-RPC + the tool vocabulary);\n * the concrete transport is injected. Wire fields are narrowed via the contracts\n * guards (no `as`).\n * - **Observable (§13).** The owned `emitter` fires `connect` / `disconnect` /\n * `notification` / `error`; the emitter isolates a listener throw and routes it to its\n * `error` handler (the `error` option), so a listener throw can never escape.\n *\n * @example\n * ```ts\n * const client = new MCPClient({ transport, identity: { name: 'agent', version: '1.0.0' } })\n * await client.connect()\n * const tools = await client.tools()\n * agent.context.tools.add(tools) // the remote tools are now the agent's\n * const value = await client.call('search', { query: 'mcp' })\n * ```\n */\nexport class MCPClient implements MCPClientInterface {\n\treadonly #emitter: Emitter<MCPClientEventMap>\n\treadonly #transport: ClientTransportInterface\n\treadonly #identity: MCPIdentity\n\treadonly #capabilities: Readonly<Record<string, unknown>>\n\treadonly #pin: MCPVersion | undefined\n\treadonly #timeout: number\n\treadonly #probe: number | undefined\n\t// The in-flight requests, keyed by JSON-RPC id, each holding its promise settlers —\n\t// resolved on the matching response, rejected on an error response, the deadline, or\n\t// `disconnect`. Genuinely private glue (§5): the settler shape lives inline here.\n\treadonly #pending = new Map<\n\t\tstring | number,\n\t\t{\n\t\t\treadonly resolve: (value: unknown) => void\n\t\t\treadonly reject: (reason?: unknown) => void\n\t\t\treadonly method: string\n\t\t\treadonly deadline?: AbortSignal\n\t\t\treadonly timeout?: () => void\n\t\t}\n\t>()\n\t#nextId = 0\n\t#connected = false\n\t#version: MCPVersion | undefined = undefined\n\t#era: MCPEra | undefined = undefined\n\t#offer: MCPVersion\n\n\tconstructor(options: MCPClientOptions) {\n\t\tthis.#emitter = new Emitter<MCPClientEventMap>({\n\t\t\t...(options.on !== undefined ? { on: options.on } : {}),\n\t\t\t...(options.error !== undefined ? { error: options.error } : {}),\n\t\t})\n\t\tthis.#transport = options.transport\n\t\tthis.#identity = options.identity ?? {\n\t\t\tname: DEFAULT_MCP_CLIENT_NAME,\n\t\t\tversion: DEFAULT_MCP_CLIENT_VERSION,\n\t\t}\n\t\tthis.#capabilities = options.capabilities ?? {}\n\t\tthis.#pin = options.version\n\t\tthis.#offer = options.version ?? MCP_MODERN_VERSION\n\t\tthis.#timeout = options.timeout ?? DEFAULT_MCP_REQUEST_TIMEOUT\n\t\tthis.#probe =\n\t\t\toptions.timeout === undefined\n\t\t\t\t? undefined\n\t\t\t\t: Math.min(options.timeout, DEFAULT_MCP_PROBE_TIMEOUT)\n\t\t// One message subscription for the client's whole life: a response settles its\n\t\t// pending request by id; anything else is a server notification.\n\t\tthis.#transport.emitter.on('message', (message) => this.#receive(message))\n\t}\n\n\tget emitter(): EmitterInterface<MCPClientEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget connected(): boolean {\n\t\treturn this.#connected\n\t}\n\n\tget version(): MCPVersion | undefined {\n\t\treturn this.#version\n\t}\n\n\tget transport(): ClientTransportInterface {\n\t\treturn this.#transport\n\t}\n\n\ton<K extends keyof MCPClientEventMap>(\n\t\tevent: K,\n\t\thandler: (...args: MCPClientEventMap[K]) => void,\n\t): void {\n\t\tthis.#emitter.on(event, handler)\n\t}\n\n\tasync connect(): Promise<void> {\n\t\tif (this.#connected) return\n\t\tawait this.#transport.start()\n\t\tif (this.#era === 'legacy' || (this.#pin !== undefined && inferEra(this.#pin) === 'legacy')) {\n\t\t\tawait this.#initialize(this.#pin ?? MCP_PROTOCOL_VERSION)\n\t\t\treturn\n\t\t}\n\n\t\tlet discovery: MCPDiscoverResult\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tdiscovery = await this.discover()\n\t\t\t} catch (error) {\n\t\t\t\tif (!isMCPError(error) || error.code !== MCP_UNSUPPORTED_VERSION) throw error\n\t\t\t\tif (this.#pin !== undefined) throw error\n\t\t\t\tconst supported = isRecord(error.context) ? error.context['supported'] : undefined\n\t\t\t\tconst retry = isArray(supported)\n\t\t\t\t\t? inferVersion(supported.filter((version): version is string => isString(version)))\n\t\t\t\t\t: undefined\n\t\t\t\tif (retry === undefined) throw error\n\t\t\t\tthis.#offer = retry\n\t\t\t\tdiscovery = await this.discover()\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst fallback =\n\t\t\t\tthis.#pin !== MCP_MODERN_VERSION &&\n\t\t\t\tthis.#era === undefined &&\n\t\t\t\t(!isMCPError(error) || error.code !== MCP_UNSUPPORTED_VERSION)\n\t\t\tif (!fallback) throw error\n\t\t\tawait this.#initialize(MCP_PROTOCOL_VERSION)\n\t\t\treturn\n\t\t}\n\n\t\tconst version = inferVersion(discovery.supportedVersions)\n\t\tif (version === undefined) {\n\t\t\tthrow new MCPError(\n\t\t\t\t'MCP server supports no compatible protocol version',\n\t\t\t\tMCP_UNSUPPORTED_VERSION,\n\t\t\t\t{\n\t\t\t\t\tsupported: discovery.supportedVersions,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tthis.#version = version\n\t\tthis.#era = 'modern'\n\t\tthis.#connected = true\n\t\tthis.#emitter.emit('connect')\n\t}\n\n\tasync discover(): Promise<MCPDiscoverResult> {\n\t\tconst result = await this.#request(\n\t\t\t'server/discover',\n\t\t\tundefined,\n\t\t\tthis.#probe,\n\t\t\tthis.#version ?? this.#offer,\n\t\t)\n\t\tif (!isRecord(result)) {\n\t\t\tthrow new MCPError(\n\t\t\t\t'MCP server returned a malformed discovery result',\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\tresult,\n\t\t\t)\n\t\t}\n\t\tconst advertised = result['supportedVersions']\n\t\tconst capabilities = result['capabilities']\n\t\tconst ttl = result['ttlMs']\n\t\tconst scope = result['cacheScope']\n\t\tconst instructions = result['instructions']\n\t\tconst metadata = result['_meta']\n\t\tconst resultType = result['resultType']\n\t\tif (\n\t\t\t!isArray(advertised) ||\n\t\t\t!isRecord(capabilities) ||\n\t\t\t!isNumber(ttl) ||\n\t\t\t(scope !== 'public' && scope !== 'private') ||\n\t\t\t(resultType !== undefined && resultType !== 'complete') ||\n\t\t\t(instructions !== undefined && !isString(instructions)) ||\n\t\t\t(metadata !== undefined && !isRecord(metadata))\n\t\t) {\n\t\t\tthrow new MCPError(\n\t\t\t\t'MCP server returned a malformed discovery result',\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\tresult,\n\t\t\t)\n\t\t}\n\t\tconst supportedVersions: MCPVersion[] = []\n\t\tfor (const version of advertised) {\n\t\t\tif (isMCPVersion(version)) supportedVersions.push(version)\n\t\t}\n\t\treturn {\n\t\t\tsupportedVersions,\n\t\t\tcapabilities,\n\t\t\tresultType: resultType ?? 'complete',\n\t\t\tttlMs: ttl,\n\t\t\tcacheScope: scope,\n\t\t\t...(instructions === undefined ? {} : { instructions }),\n\t\t\t...(metadata === undefined ? {} : { _meta: metadata }),\n\t\t}\n\t}\n\n\tasync disconnect(): Promise<void> {\n\t\tif (!this.#connected) return\n\t\tthis.#connected = false\n\t\tthis.#version = undefined\n\t\t// Reject every still-pending request so no caller hangs past a disconnect, then\n\t\t// clear the map and tear the transport down.\n\t\tfor (const id of this.#pending.keys()) {\n\t\t\tthis.#settle(id, new Error('MCP client disconnected'), true)\n\t\t}\n\t\tawait this.#transport.close()\n\t\tthis.#emitter.emit('disconnect')\n\t}\n\n\tasync tools(): Promise<readonly ToolInterface[]> {\n\t\tconst result = await this.#request('tools/list', undefined, this.#timeout)\n\t\t// The wire shape is `{ tools: MCPToolDescriptor[] }` — narrow it (§14): a\n\t\t// non-record / non-array `tools` yields no tools rather than throwing.\n\t\tif (!isRecord(result) || !isArray(result['tools'])) return []\n\t\tconst tools: ToolInterface[] = []\n\t\tfor (const descriptor of result['tools']) {\n\t\t\tif (!isRecord(descriptor) || !isString(descriptor['name'])) continue\n\t\t\tconst name = descriptor['name']\n\t\t\ttools.push(this.#tool(name, descriptor))\n\t\t}\n\t\treturn tools\n\t}\n\n\tasync call(name: string, args: Readonly<Record<string, unknown>>): Promise<unknown> {\n\t\tconst result = await this.#request('tools/call', { name, arguments: args }, this.#timeout)\n\t\t// The inverse of the server's `buildCallResult`: concat the result's text blocks,\n\t\t// then either throw (a remote `isError`) or parse the JSON value.\n\t\tconst text = this.#text(result)\n\t\tif (isRecord(result) && result['isError'] === true) {\n\t\t\tthrow new Error(text.length > 0 ? text : `MCP tool '${name}' failed`)\n\t\t}\n\t\t// A success carries the value JSON-serialized into the text block(s); parse it,\n\t\t// falling back to the raw string when it is not JSON (the inverse of the server's\n\t\t// `JSON.stringify`, whose value-less result is an empty text block).\n\t\tif (text.length === 0) return undefined\n\t\ttry {\n\t\t\treturn JSON.parse(text)\n\t\t} catch {\n\t\t\treturn text\n\t\t}\n\t}\n\n\t// Issue a request and await its correlated response, bounded by the per-request\n\t// deadline. A monotonic numeric id keys the pending settlers; `AbortSignal.timeout`\n\t// (the taverna idiom — never a raw setTimeout) rejects the pending request if the\n\t// server never answers. The transport `send` is awaited so a write failure rejects\n\t// here rather than leaving a pending request to time out.\n\t#request(\n\t\tmethod: string,\n\t\tparams: Readonly<Record<string, unknown>> | undefined,\n\t\tdeadline: number | undefined,\n\t\tversion?: MCPVersion,\n\t): Promise<unknown> {\n\t\tthis.#nextId += 1\n\t\tconst id = this.#nextId\n\t\tconst timeout = deadline\n\t\tconst modern = version ?? (this.#era === 'modern' ? this.#version : undefined)\n\t\tconst stamped =\n\t\t\tmodern === undefined\n\t\t\t\t? params\n\t\t\t\t: {\n\t\t\t\t\t\t...(params ?? {}),\n\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t[MCP_META_VERSION]: modern,\n\t\t\t\t\t\t\t[MCP_META_CAPABILITIES]: this.#capabilities,\n\t\t\t\t\t\t\t[MCP_META_CLIENT]: this.#identity,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\tconst request: JSONRPCRequest = {\n\t\t\tjsonrpc: '2.0',\n\t\t\tid,\n\t\t\tmethod,\n\t\t\t...(stamped === undefined ? {} : { params: stamped }),\n\t\t}\n\t\treturn new Promise<unknown>((resolve, reject) => {\n\t\t\tif (timeout === undefined) {\n\t\t\t\tthis.#pending.set(id, { resolve, reject, method })\n\t\t\t\tthis.#transport.send(request).catch((error: unknown) => {\n\t\t\t\t\tthis.#settle(id, error instanceof Error ? error : new Error(String(error)), true)\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst signal = AbortSignal.timeout(timeout)\n\t\t\tconst abort = this.#timeoutRequest.bind(this, id, method, timeout)\n\t\t\tsignal.addEventListener('abort', abort, { once: true })\n\t\t\tthis.#pending.set(id, { resolve, reject, method, deadline: signal, timeout: abort })\n\t\t\tthis.#transport.send(request).catch((error: unknown) => {\n\t\t\t\tthis.#settle(id, error instanceof Error ? error : new Error(String(error)), true)\n\t\t\t})\n\t\t})\n\t}\n\n\t// Handle one inbound transport message: a response settles its pending request by\n\t// id (an error response rejects, a result resolves); anything else (a message with\n\t// no matching pending id) is a server-initiated notification, re-surfaced on the\n\t// `notification` event.\n\t#receive(message: JSONRPCMessage): void {\n\t\tif (isJSONRPCResponse(message) && isRequestId(message.id)) {\n\t\t\tconst pending = this.#pending.get(message.id)\n\t\t\tif (pending !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\tpending.method === 'server/discover' &&\n\t\t\t\t\t(message.error === undefined ||\n\t\t\t\t\t\t(message.error.code !== JSONRPC_METHOD_NOT_FOUND &&\n\t\t\t\t\t\t\tmessage.error.code !== JSONRPC_INVALID_REQUEST))\n\t\t\t\t) {\n\t\t\t\t\tthis.#era = 'modern'\n\t\t\t\t}\n\t\t\t\tif (message.error !== undefined) {\n\t\t\t\t\tthis.#settle(\n\t\t\t\t\t\tmessage.id,\n\t\t\t\t\t\tnew MCPError(message.error.message, message.error.code, message.error.data),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tconst resultType = isRecord(message.result) ? message.result['resultType'] : undefined\n\t\t\t\t\tif (\n\t\t\t\t\t\tisRecord(message.result) &&\n\t\t\t\t\t\tObject.hasOwn(message.result, 'resultType') &&\n\t\t\t\t\t\tresultType !== 'complete'\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.#settle(\n\t\t\t\t\t\t\tmessage.id,\n\t\t\t\t\t\t\tnew MCPError(\n\t\t\t\t\t\t\t\t`MCP result type '${String(resultType)}' is not supported`,\n\t\t\t\t\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t\t\t\t\t{ resultType },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.#settle(message.id, message.result, false)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// Not a correlated response — a server notification (or an unsolicited response).\n\t\tthis.#emitter.emit('notification', message)\n\t}\n\n\t// Wrap one remote tool descriptor as a local tool: map `inputSchema` → `parameters`\n\t// (the inverse of the server's rename, no `as`), carry `description` when present,\n\t// and bind `execute` to a remote `tools/call` via `call`.\n\t#tool(name: string, descriptor: Readonly<Record<string, unknown>>): ToolInterface {\n\t\tconst inputSchema = descriptor['inputSchema']\n\t\tconst description = descriptor['description']\n\t\tconst options: {\n\t\t\tname: string\n\t\t\tdescription?: string\n\t\t\tparameters?: Readonly<Record<string, unknown>>\n\t\t\texecute: (args: Readonly<Record<string, unknown>>) => Promise<unknown>\n\t\t} = {\n\t\t\tname,\n\t\t\texecute: this.call.bind(this, name),\n\t\t}\n\t\tif (isString(description)) options.description = description\n\t\tif (isRecord(inputSchema)) options.parameters = inputSchema\n\t\treturn new Tool(options)\n\t}\n\n\t// Concatenate an MCP tool-call result's text content blocks into one string — the\n\t// inverse of the server splitting a value into text block(s). Total (§14): a\n\t// non-record result, a non-array `content`, or a non-string `text` contributes\n\t// nothing rather than throwing.\n\t#text(result: unknown): string {\n\t\tif (!isRecord(result) || !isArray(result['content'])) return ''\n\t\tconst parts: string[] = []\n\t\tfor (const block of result['content']) {\n\t\t\tif (isRecord(block) && isString(block['text'])) parts.push(block['text'])\n\t\t}\n\t\treturn parts.join('\\n')\n\t}\n\n\tasync #initialize(version: MCPVersion): Promise<void> {\n\t\tconst result = await this.#request(\n\t\t\t'initialize',\n\t\t\t{\n\t\t\t\tprotocolVersion: version,\n\t\t\t\tcapabilities: {},\n\t\t\t\tclientInfo: this.#identity,\n\t\t\t},\n\t\t\tthis.#timeout,\n\t\t)\n\t\tconst protocol = isRecord(result) ? result['protocolVersion'] : undefined\n\t\tif (protocol === undefined) {\n\t\t\tawait this.#transport.close()\n\t\t\tthrow new Error('MCP server returned no protocol version')\n\t\t}\n\t\tif (!isString(protocol)) {\n\t\t\tawait this.#transport.close()\n\t\t\tthrow new Error('MCP server returned a malformed protocol version')\n\t\t}\n\t\tif (!isMCPVersion(protocol) || inferEra(protocol) !== 'legacy') {\n\t\t\tawait this.#transport.close()\n\t\t\tthrow new Error(`MCP server negotiated unsupported protocol version '${protocol}'`)\n\t\t}\n\t\tthis.#version = protocol\n\t\tthis.#era = 'legacy'\n\t\tthis.#connected = true\n\t\tawait this.#transport.send({ jsonrpc: '2.0', method: 'notifications/initialized' })\n\t\tthis.#emitter.emit('connect')\n\t}\n\n\t#timeoutRequest(id: string | number, method: string, timeout: number): void {\n\t\tthis.#settle(id, new Error(`MCP request '${method}' timed out after ${timeout}ms`), true)\n\t}\n\n\t#settle(id: string | number, value: unknown, failed: boolean): void {\n\t\tconst pending = this.#pending.get(id)\n\t\tif (pending === undefined) return\n\t\tthis.#pending.delete(id)\n\t\tif (pending.deadline !== undefined && pending.timeout !== undefined) {\n\t\t\tpending.deadline.removeEventListener('abort', pending.timeout)\n\t\t}\n\t\tif (failed) pending.reject(value)\n\t\telse pending.resolve(value)\n\t}\n}\n","import type {\n\tClientTransportEventMap,\n\tClientTransportInterface,\n\tJSONRPCMessage,\n\tMCPClientInterface,\n\tMCPClientOptions,\n\tMCPServerInterface,\n\tMCPServerOptions,\n\tMCPTransportInterface,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { MCPClient } from './MCPClient.js'\nimport { MCPServer } from './MCPServer.js'\n\n/**\n * Create a transport-agnostic Model Context Protocol server — exposes a live\n * {@link import('@orkestrel/tool').ToolManagerInterface} over JSON-RPC 2.0\n * (`initialize` / `ping` / `tools/list` / `tools/call`).\n *\n * @remarks\n * Pump raw message strings through `handle` (parse → dispatch → serialize) from a\n * transport, or call the typed `dispatch` directly with an already-parsed request.\n * The server is provider-agnostic — JSON-RPC plus the tool registry, with no HTTP\n * and no model. The {@link import('@orkestrel/tool').ToolManagerInterface} already\n * isolates a thrown tool into a `success: false` result (surfaced as an MCP\n * `isError: true` tool result), so a misbehaving tool never crashes a dispatch. Subscribe to the\n * `request` event via `server.emitter.on('request', …)` for tracing.\n *\n * @param options - `identity` (the server identity), `tools` (the live\n * registry to expose), optional `instructions`, and the reserved `on`\n * {@link import('@orkestrel/emitter').EmitterHooks} (see {@link MCPServerOptions})\n * @returns A working {@link MCPServerInterface}\n *\n * @example\n * ```ts\n * import { createMCPServer, createTool, createToolManager } from '@src/core'\n *\n * const tools = createToolManager()\n * tools.add(createTool({ name: 'add', execute: (a) => Number(a.x) + Number(a.y) }))\n *\n * const server = createMCPServer({ identity: { name: 'calculator', version: '1.0.0' }, tools })\n * server.emitter.on('request', (method, id) => log(method, id))\n *\n * // A transport pumps message strings through `handle`:\n * const reply = await server.handle('{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"id\":1}')\n * // reply → '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"tools\":[{\"name\":\"add\",\"inputSchema\":{\"type\":\"object\"}}]}}'\n * ```\n */\nexport function createMCPServer(options: MCPServerOptions): MCPServerInterface {\n\treturn new MCPServer(options)\n}\n\n/**\n * Create a transport-agnostic Model Context Protocol CLIENT — connects to a REMOTE\n * MCP server over an injected {@link import('./types.js').ClientTransportInterface},\n * runs the `initialize` handshake, and exposes the server's tools as local\n * {@link import('@orkestrel/tool').ToolInterface}s an agent can run.\n *\n * @remarks\n * The egress mirror of {@link createMCPServer}: where the server exposes a local tool\n * registry over MCP, the client USES a remote server's tools. `connect()` handshakes,\n * validates and exposes the negotiated protocol, `tools()` lists + wraps the remote\n * tools (each `execute` calls back over the wire),\n * and `call(name, args)` runs a remote `tools/call` (a remote tool failure throws\n * locally, so an agent's {@link import('@orkestrel/tool').ToolManagerInterface}\n * isolates it). The transport is injected — a concrete one (the HTTP transport over\n * `fetch`) lives in `@src/server`; the client itself is provider-agnostic. Subscribe\n * to `connect` / `disconnect` / `notification` via `client.on(...)` (or\n * `client.emitter.on(...)`).\n *\n * @param options - `transport` (the carrier; REQUIRED), an optional `identity`\n * (the client identity), `timeout` (the per-request deadline), and the reserved `on`\n * {@link import('@orkestrel/emitter').EmitterHooks} (see {@link MCPClientOptions})\n * @returns A working {@link MCPClientInterface}\n *\n * @example\n * ```ts\n * import { createMCPClient } from '@src/core'\n * import { createHTTPClientTransport } from '@src/server'\n *\n * const client = createMCPClient({\n * \ttransport: createHTTPClientTransport({ url: 'http://localhost:3000/mcp' }),\n * })\n * await client.connect()\n * agent.context.tools.add(await client.tools()) // give the agent the remote tools\n * const value = await client.call('search', { query: 'mcp' })\n * ```\n */\nexport function createMCPClient(options: MCPClientOptions): MCPClientInterface {\n\treturn new MCPClient(options)\n}\n\n/**\n * Adapt an {@link MCPTransportInterface} (the environment-agnostic duplex message\n * channel) into a {@link ClientTransportInterface} — the additive bridge that lets\n * `createMCPClient` run over the new port without any change to `MCPClient`'s\n * existing shape.\n *\n * @remarks\n * Hand the RESULT to `createMCPClient({ transport })`, then pass the SAME\n * `transport` to {@link import('./helpers.js').bindClient} to complete the inbound\n * wiring: `send` serializes each outbound {@link JSONRPCMessage} and writes it via\n * `transport.send`; `close` closes the underlying\n * `transport`; `start` is a no-op (the duplex channel is already open by the time\n * it is handed in — there is no separate connect step at this layer); `session` is\n * always `undefined` (session correlation is a higher-level concern the duplex port\n * does not carry). Inbound delivery (`emitter`'s `message` / `close` events) is\n * `bindClient`'s job, not this factory's — the returned object exposes a `message`-\n * capable emitter for `bindClient` to push onto.\n *\n * @param transport - The duplex channel to adapt\n * @returns A {@link ClientTransportInterface} `createMCPClient` can drive\n *\n * @example\n * ```ts\n * const client = createMCPClient({ transport: createDuplexClientTransport(transport) })\n * const unbind = bindClient(client, transport)\n * await client.connect()\n * ```\n */\nexport function createDuplexClientTransport(\n\ttransport: MCPTransportInterface,\n): ClientTransportInterface {\n\tconst emitter = new Emitter<ClientTransportEventMap>()\n\treturn {\n\t\temitter,\n\t\tsession: undefined,\n\t\tasync start(): Promise<void> {\n\t\t\t// The duplex channel is already open by the time it is handed in — no separate\n\t\t\t// connect step at this layer.\n\t\t},\n\t\tasync send(message: JSONRPCMessage): Promise<void> {\n\t\t\tawait transport.send(JSON.stringify(message))\n\t\t},\n\t\tasync close(): Promise<void> {\n\t\t\tawait transport.close()\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,IAAa,uBAAmC;;AAGhD,IAAa,qBAAiC;;AAG9C,IAAa,qBAAiC;;;;;;;;;;AAW9C,IAAa,8BAAqD,OAAO,OAAO;CAC/E;CACA;CACA;AACD,CAAC;;AAGD,IAAa,mBAAmB;;AAGhC,IAAa,wBAAwB;;AAGrC,IAAa,kBAAkB;;AAG/B,IAAa,kBAAkB;;AAG/B,IAAa,wBAAwB;;AAGrC,IAAa,sBAAsB;;AAGnC,IAAa,yBAAyB;;AAGtC,IAAa,0BAA0B;;;;;;;;AASvC,IAAa,wBAAwB;;;;;;;;;;;;;AAcrC,IAAa,qBAAqB,OAAO,OAAO;CAC/C,SAAS;CACT,UAAU;CACV,MAAM;CACN,OAAO;CACP,SAAS;CACT,eAAe;CACf,OAAO;AACR,CAAC;;AAGD,IAAa,sBAAsB;;AAGnC,IAAa,0BAA0B;;AAGvC,IAAa,2BAA2B;;AAGxC,IAAa,yBAAyB;;AAGtC,IAAa,uBAAuB;;AAOpC,IAAa,0BAA0B;;AAGvC,IAAa,6BAA6B;;;;;AAM1C,IAAa,8BAA8B;;AAG3C,IAAa,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;ACrGzC,IAAa,WAA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#last","#value","#consumed","#waiter","#requireSoleConsumer","#stopped","#source","#signal","#closure","#listener","#abort","#fail","#closed","#exhausted","#waiter","#complete","#terminal","#release","#error","#stream","#options","#legacy","#forward","#unsupported","#project","#capability","#emitter","#options","#methods","#limits","#register","#dispatch","#modern","#contain","#discover","#list","#call","#subscribe","#resources","#read","#templates","#prompts","#prompt","#suggest","#task","#update","#abort","#input","#defer","#progress","#execute","#normalize","#retry","#form","#required","#subscription","#subscriptions","#named","#request","#timeout","#emitter","#transport","#identity","#capabilities","#pin","#timeout","#probe","#tasks","#pending","#offer","#request","#receive","#connected","#version","#disconnecting","#connecting","#owner","#teardown","#generation","#negotiate","#tool","#nextId","#era","#timeoutRequest","#abortRequest","#settle","#reportProgress","#execute","#initialize","#closeTransport","#closeConnection","#supersession","#closing","#discharge"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/inferers.ts","../../../src/core/cloners.ts","../../../src/core/parsers.ts","../../../src/core/helpers.ts","../../../src/core/validators.ts","../../../src/core/MCPMethodManager.ts","../../../src/core/MCPProgressReporter.ts","../../../src/core/MCPStreamController.ts","../../../src/core/MCPTextStreamController.ts","../../../src/core/MCPLegacy.ts","../../../src/core/MCPServer.ts","../../../src/core/MCPTaskClient.ts","../../../src/core/MCPClient.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { MCPVersion } from './types.js'\n\n// MCP protocol revisions, reserved modern `_meta` keys, and protocol error codes.\n// Transport-level header names (session / version headers) belong to the HTTP\n// transport, not core.\n\n/**\n * The revision offered and defaulted to in the legacy `initialize` handshake.\n *\n * @remarks\n * This is deliberately a legacy revision, and the newest one supported. 2026-07-28 is stateless\n * and defines no `initialize`, so it can never be the handshake's version — a client that offers\n * it is asking to negotiate a revision with no negotiation.\n */\nexport const MCP_PROTOCOL_VERSION: MCPVersion = '2025-11-25'\n\n/** The legacy fallback anchor used when an initialize request cannot be accepted as modern. */\nexport const MCP_LEGACY_VERSION: MCPVersion = '2025-06-18'\n\n/** The modern revision offered by an unpinned client during discovery. */\nexport const MCP_MODERN_VERSION: MCPVersion = '2026-07-28'\n\n/**\n * The MCP protocol revisions this server can negotiate.\n *\n * @remarks\n * `initialize` echoes the client's requested `protocolVersion` when it appears in\n * this list. Frozen in client-preference and discovery-advertisement order. The\n * package does not advertise `2025-03-26` because that revision mandates JSON-RPC\n * batching, while this package accepts only individual JSON-RPC messages.\n */\nexport const SUPPORTED_PROTOCOL_VERSIONS: readonly MCPVersion[] = Object.freeze([\n\t'2026-07-28',\n\t'2025-11-25',\n\t'2025-06-18',\n])\n\n/** Reserved modern `_meta` key carrying the request's protocol revision. */\nexport const MCP_META_VERSION = 'io.modelcontextprotocol/protocolVersion'\n\n/** Reserved modern `_meta` key carrying the client's open capability record. */\nexport const MCP_META_CAPABILITIES = 'io.modelcontextprotocol/clientCapabilities'\n\n/** Reserved modern `_meta` key carrying the optional client identity. */\nexport const MCP_META_CLIENT = 'io.modelcontextprotocol/clientInfo'\n\n/** Reserved modern `_meta` key carrying the server identity on results. */\nexport const MCP_META_SERVER = 'io.modelcontextprotocol/serverInfo'\n\n/** Reserved modern `_meta` key carrying a `subscriptions/listen` request id. */\nexport const MCP_META_SUBSCRIPTION = 'io.modelcontextprotocol/subscriptionId'\n\n/**\n * The reserved extension key identifying the draft Tasks extension.\n *\n * @remarks\n * The ONE spelling of it in this package. A client declares it per REQUEST, under\n * `_meta['io.modelcontextprotocol/clientCapabilities'].extensions`; a server advertises it\n * under `server/discover`'s `capabilities.extensions`. Both sides carry an empty object —\n * the extension defines no options, so presence is the entire declaration.\n */\nexport const MCP_EXTENSION_TASKS = 'io.modelcontextprotocol/tasks'\n\n/** MCP reserved error: required HTTP metadata does not match the request body. */\nexport const MCP_HEADER_MISMATCH = -32020\n\n/**\n * MCP reserved error: an operation needs a client capability that was not declared.\n *\n * @remarks\n * The GENERIC code for the whole condition, not one capability's code. This server answers\n * it in two places — a `tools/call` that needs `elicitation`, and a `tasks/*` request whose\n * client never declared `io.modelcontextprotocol/tasks` — and the two are told apart by\n * `error.data.requiredCapabilities` alone (`{ elicitation: {} }` against\n * `{ extensions: { 'io.modelcontextprotocol/tasks': {} } }`). They are two instances of one\n * condition, so a second numeral would describe the same fact twice. The Tasks extension's\n * own draft prose still shows `-32003` in examples; the dated core schema fixes this code,\n * and the dated schema is what a peer implements against.\n */\nexport const MCP_MISSING_CAPABILITY = -32021\n\n/** MCP reserved error: a request names an unsupported protocol revision. */\nexport const MCP_UNSUPPORTED_VERSION = -32022\n\n/**\n * Default modern result freshness lifetime in milliseconds.\n *\n * @remarks\n * `ttlMs` is required on cacheable results, while zero means immediately stale\n * rather than uncached, so the neutral usable default is one minute.\n */\nexport const DEFAULT_MCP_CACHE_TTL = 60_000\n\n/**\n * Secure server bounds used when the matching `limit` option leaf is absent or malformed.\n *\n * @remarks\n * One MiB admits ordinary JSON-RPC requests and substantial tool arguments; 16 KiB admits\n * extension-rich modern metadata and signed multi-round state; four MiB admits substantial\n * JSON tool output without allowing an unconfigured service to serialize arbitrary process\n * memory; 64 metadata keys admits the reserved keys plus many extensions; 128 concurrent\n * streams admits a busy service while bounding retained producers; depth 32 admits ordinary\n * JSON documents while rejecting stack-hostile nesting. Frozen so callers cannot alter the\n * defaults observed by later servers.\n */\nexport const DEFAULT_MCP_LIMITS = Object.freeze({\n\tmessage: 1_048_576,\n\tmetadata: 16_384,\n\tkeys: 64,\n\tstate: 16_384,\n\tcontent: 4_194_304,\n\tsubscriptions: 128,\n\tdepth: 32,\n})\n\n/**\n * The one empty argument record every argument-less modern `tools/call` runs with.\n *\n * @remarks\n * Frozen and null-prototype, and SHARED: two calls that name no `arguments` receive the same\n * reference, so nothing a tool writes into its own `arguments` can survive into the next\n * call — the write fails instead. That failure is a tool-domain failure like any other: the\n * registry isolates it into a `success: false` result, which reaches the peer as an\n * `isError: true` tool result rather than as a protocol error, because refusing a mutation\n * of server-owned input is not a protocol fault.\n *\n * The null prototype means an inherited key is never mistaken for a supplied argument:\n * `arguments.constructor` is `undefined` here rather than a function.\n */\nexport const EMPTY_MCP_ARGUMENTS: Readonly<Record<string, unknown>> = Object.freeze(\n\tObject.create(null),\n)\n\n/** JSON-RPC 2.0 reserved error: invalid JSON was received (the message did not parse). */\nexport const JSONRPC_PARSE_ERROR = -32700\n\n/** JSON-RPC 2.0 reserved error: the payload was not a valid Request object. */\nexport const JSONRPC_INVALID_REQUEST = -32600\n\n/** JSON-RPC 2.0 reserved error: the requested method does not exist. */\nexport const JSONRPC_METHOD_NOT_FOUND = -32601\n\n/** JSON-RPC 2.0 reserved error: the method's parameters were invalid. */\nexport const JSONRPC_INVALID_PARAMS = -32602\n\n/**\n * JSON-RPC 2.0 reserved error: the server failed while handling an otherwise valid request.\n *\n * @remarks\n * The code every MODERN internal fault answers with — a provider, handler, continuation,\n * capacity, stream-source, normalization, or serialization failure the server contained.\n * It is detail-free on the wire: the caught value reaches the application through the\n * server's `error` event and never through the response.\n */\nexport const JSONRPC_INTERNAL_ERROR = -32603\n\n/**\n * JSON-RPC 2.0 implementation-defined server error (the `-32000` to `-32099` range).\n *\n * @remarks\n * Retained for the LEGACY branch alone. A modern fault answers\n * {@link JSONRPC_INTERNAL_ERROR}; this code survives only where an old-wire peer was\n * already characterized against it.\n */\nexport const JSONRPC_SERVER_ERROR = -32000\n\n// MCP CLIENT defaults — the identity an `MCPClient` reports in the `initialize`\n// handshake (`clientInfo`) and the per-request deadline, when the caller supplies\n// none. The egress mirror of the server's protocol-version constants above.\n\n/** The default client name reported in the MCP `initialize` handshake (`clientInfo.name`). */\nexport const DEFAULT_MCP_CLIENT_NAME = 'taverna'\n\n/** The default client version reported in the MCP `initialize` handshake (`clientInfo.version`). */\nexport const DEFAULT_MCP_CLIENT_VERSION = '1.0.0'\n\n/**\n * The default per-request deadline (ms) an `MCPClient` applies when `options.timeout`\n * is unset — a request the remote server does not answer within it rejects.\n */\nexport const DEFAULT_MCP_REQUEST_TIMEOUT = 30_000\n\n/** The maximum discovery-probe deadline used when a client deadline is configured. */\nexport const DEFAULT_MCP_PROBE_TIMEOUT = 50\n","/**\n * A remote Model Context Protocol JSON-RPC error, preserving its machine-readable\n * numeric code and optional structured context.\n *\n * @remarks\n * {@link MCPClient} throws this error only for a remote JSON-RPC `error` response.\n * Local lifecycle and transport conditions such as disconnects and request timeouts\n * remain plain `Error`s. `context` carries the response's optional `error.data`\n * unchanged and is `undefined` when the peer omitted it. This includes the modern\n * reserved paths: `-32020` carries no context, `-32021` may carry\n * `requiredCapabilities`, and `-32022` carries the peer's `supported` revisions and\n * `requested` revision for negotiation recovery.\n *\n * @example\n * ```ts\n * const error = new MCPError('Unsupported protocol version', -32022, {\n * \tsupported: ['2026-07-28'],\n * \trequested: '2024-11-05',\n * })\n * error.code // -32022\n * error.context // { supported: ['2026-07-28'], requested: '2024-11-05' }\n * ```\n */\nexport class MCPError extends Error {\n\toverride readonly name = 'MCPError'\n\treadonly code: number\n\treadonly context: unknown\n\n\t/**\n\t * Create a remote MCP protocol error.\n\t *\n\t * @param message - The human-readable JSON-RPC error message\n\t * @param code - The machine-readable numeric JSON-RPC error code\n\t * @param context - The optional JSON-RPC `error.data` payload\n\t */\n\tconstructor(message: string, code: number, context?: unknown) {\n\t\tsuper(message)\n\t\tthis.code = code\n\t\tthis.context = context\n\t}\n}\n\n/**\n * Determine whether an unknown value is an {@link MCPError}.\n *\n * @param value - The unknown value to inspect\n * @returns `true` only when the value is an `MCPError`\n *\n * @example\n * ```ts\n * isMCPError(new MCPError('Method not found', -32601)) // true\n * isMCPError(new Error('Method not found')) // false\n * ```\n */\nexport function isMCPError(value: unknown): value is MCPError {\n\ttry {\n\t\t// A revoked Proxy or a hostile prototype can make `instanceof` throw — this guard\n\t\t// must stay total, so the check is wrapped rather than left to escape.\n\t\treturn value instanceof MCPError\n\t} catch {\n\t\treturn false\n\t}\n}\n","import type { JSONRPCMessage, MCPEra, MCPVersion } from './types.js'\nimport { isModernRequest } from './validators.js'\nimport { isRecord, isString } from '@orkestrel/contract'\nimport { MCP_META_VERSION, SUPPORTED_PROTOCOL_VERSIONS } from './constants.js'\n\n/**\n * Infer the wire era for an MCP protocol revision.\n *\n * @param version - The protocol revision to classify\n * @returns `'modern'` for `2026-07-28`, `'legacy'` for either supported legacy\n * revision, or `undefined` when the revision is unsupported\n */\nexport function inferEra(version: string): MCPEra | undefined {\n\tswitch (version) {\n\t\tcase '2026-07-28':\n\t\t\treturn 'modern'\n\t\tcase '2025-11-25':\n\t\tcase '2025-06-18':\n\t\t\treturn 'legacy'\n\t\tdefault:\n\t\t\treturn undefined\n\t}\n}\n\n/**\n * Infer the newest supported protocol revision present in a peer's offer.\n *\n * @param offered - The protocol revisions offered by the peer\n * @returns The newest locally supported offered revision, or `undefined`\n */\nexport function inferVersion(offered: readonly string[]): MCPVersion | undefined {\n\tfor (const version of SUPPORTED_PROTOCOL_VERSIONS) {\n\t\tif (offered.includes(version)) return version\n\t}\n\treturn undefined\n}\n\n/**\n * Infer the protocol version an outbound message announces itself with — the ONE\n * projection every HTTP client transport stamps `mcp-protocol-version` from.\n *\n * @remarks\n * This is deliberately the SAME read the server's own expectation performs\n * ({@link import('@src/server').inferHeaderIssue}): a modern request's reserved\n * `_meta` version, accepted whenever it is a string. It is NOT\n * {@link import('./parsers.js').parseRequestContext}, and the difference is the whole\n * point. That parser answers a different question — is the modern metadata WELL FORMED —\n * and refuses a request whose capability declaration or logging level is malformed. Such a\n * request is still modern (era is fixed by key presence) and the server still demands the\n * header for it, so projecting through the parser withholds a header the peer requires and\n * earns `-32602` instead of the `-32602` the malformed metadata itself deserves.\n *\n * A non-modern message projects nothing: a legacy request's version comes from the\n * `initialize` handshake the transport captured, not from the message.\n *\n * Header NAMES stay with the transports that own the wire (see `constants.ts`); core owns\n * the value this projection derives, which is the part the two faces disagreed about.\n *\n * @param message - The outbound message about to be written\n * @returns The version to announce, or `undefined` when the message announces none\n *\n * @example\n * ```ts\n * inferRequestVersion({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: { _meta: meta } })\n * ```\n */\nexport function inferRequestVersion(message: JSONRPCMessage): string | undefined {\n\tif (!isModernRequest(message)) return undefined\n\tconst metadata = isRecord(message.params?.['_meta']) ? message.params['_meta'] : undefined\n\tconst version = metadata?.[MCP_META_VERSION]\n\treturn isString(version) ? version : undefined\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type { ToolResult } from '@orkestrel/tool'\nimport type { MCPJSONLimitOptions } from './types.js'\nimport { attempt, cloneJSONValue, isRecord, isString } from '@orkestrel/contract'\nimport { serializeJSON } from './helpers.js'\n\n/**\n * Snapshot one bounded exact JSON value together with its canonical wire serialization.\n *\n * The returned value is an owned, deeply frozen graph reconstructed from the canonical text;\n * the frozen tuple shares no mutable structure with the input. Invalid exact-JSON shapes,\n * hostile reflection, serialization failures, and values outside the byte, key, or depth limits\n * return `undefined`.\n *\n * @param value - The unknown value to snapshot\n * @param limits - The canonical serialization byte, key, and depth bounds\n * @returns A frozen owned value/text tuple, or `undefined` when the value cannot be bounded\n *\n * @example\n * ```ts\n * import { snapshotJSON } from '@orkestrel/mcp'\n *\n * snapshotJSON({ beta: 2, alpha: 1 }, { bytes: 64, keys: 2, depth: 1 })\n * // [{ alpha: 1, beta: 2 }, '{\"alpha\":1,\"beta\":2}']\n * ```\n */\nexport function snapshotJSON(\n\tvalue: unknown,\n\tlimits: MCPJSONLimitOptions,\n): readonly [value: JSONValue, text: string] | undefined {\n\tconst text = serializeJSON(value, limits)\n\tif (text === undefined) return undefined\n\tconst parsed = attempt((): unknown => JSON.parse(text))\n\tif (!parsed.success) return undefined\n\tconst owned = attempt(() => cloneJSONValue(parsed.value))\n\tif (!owned.success) return undefined\n\tconst snapshot: [value: JSONValue, text: string] = [owned.value, text]\n\treturn Object.freeze(snapshot)\n}\n\n/**\n * Snapshot one exact Tool result and the canonical wire text of a defined success value.\n *\n * A success must have exactly four own enumerable data properties: `id`, `name`, `success: true`,\n * and `value`. A failure must instead have exactly `id`, `name`, `success: false`, and a string\n * `error`. The returned result and tuple are frozen. Only a defined success value crosses the\n * bounded JSON ownership seam; it becomes an owned deeply frozen value and receives canonical\n * text. Value-less successes and failures pair with `undefined` text. Non-records, symbol keys,\n * accessors, hidden or extra properties, malformed discriminants or fields, hostile reflection,\n * and unbounded defined success values return `undefined`.\n *\n * @param value - The unknown Tool result candidate to snapshot\n * @param limits - The byte, key, and depth bounds for a defined successful value\n * @returns A frozen owned result/text tuple, or `undefined` when the result is malformed\n *\n * @example\n * ```ts\n * import { snapshotToolResult } from '@orkestrel/mcp'\n *\n * snapshotToolResult(\n * \t{ id: '1', name: 'search', success: true, value: { count: 1 } },\n * \t{ bytes: 64, keys: 1, depth: 1 },\n * )\n * // [{ id: '1', name: 'search', success: true, value: { count: 1 } }, '{\"count\":1}']\n * ```\n */\nexport function snapshotToolResult(\n\tvalue: unknown,\n\tlimits: MCPJSONLimitOptions,\n): readonly [result: ToolResult, text: string | undefined] | undefined {\n\tconst captured = attempt(() => {\n\t\tif (!isRecord(value)) return undefined\n\t\tconst names = Reflect.ownKeys(value)\n\t\tconst descriptors = new Map<string, PropertyDescriptor>()\n\t\tfor (const name of names) {\n\t\t\tif (!isString(name)) return undefined\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, name)\n\t\t\tif (\n\t\t\t\tdescriptor === undefined ||\n\t\t\t\tdescriptor.enumerable !== true ||\n\t\t\t\t!Object.hasOwn(descriptor, 'value')\n\t\t\t)\n\t\t\t\treturn undefined\n\t\t\tdescriptors.set(name, descriptor)\n\t\t}\n\t\tconst id = descriptors.get('id')?.value\n\t\tconst name = descriptors.get('name')?.value\n\t\tconst success = descriptors.get('success')?.value\n\t\tif (!isString(id) || !isString(name) || (success !== true && success !== false)) {\n\t\t\treturn undefined\n\t\t}\n\t\tif (success) {\n\t\t\tif (\n\t\t\t\tdescriptors.size !== 4 ||\n\t\t\t\t!descriptors.has('id') ||\n\t\t\t\t!descriptors.has('name') ||\n\t\t\t\t!descriptors.has('success') ||\n\t\t\t\t!descriptors.has('value')\n\t\t\t)\n\t\t\t\treturn undefined\n\t\t\tconst resultValue = descriptors.get('value')?.value\n\t\t\tif (resultValue === undefined) {\n\t\t\t\tconst result: ToolResult = Object.freeze({ id, name, success: true, value: undefined })\n\t\t\t\tconst snapshot: [result: ToolResult, text: undefined] = [result, undefined]\n\t\t\t\treturn Object.freeze(snapshot)\n\t\t\t}\n\t\t\tconst owned = snapshotJSON(resultValue, limits)\n\t\t\tif (owned === undefined) return undefined\n\t\t\tconst result: ToolResult = Object.freeze({ id, name, success: true, value: owned[0] })\n\t\t\tconst snapshot: [result: ToolResult, text: string] = [result, owned[1]]\n\t\t\treturn Object.freeze(snapshot)\n\t\t}\n\t\tif (\n\t\t\tdescriptors.size !== 4 ||\n\t\t\t!descriptors.has('id') ||\n\t\t\t!descriptors.has('name') ||\n\t\t\t!descriptors.has('success') ||\n\t\t\t!descriptors.has('error')\n\t\t)\n\t\t\treturn undefined\n\t\tconst error = descriptors.get('error')?.value\n\t\tif (!isString(error)) return undefined\n\t\tconst result: ToolResult = Object.freeze({ id, name, success: false, error })\n\t\tconst snapshot: [result: ToolResult, text: undefined] = [result, undefined]\n\t\treturn Object.freeze(snapshot)\n\t})\n\treturn captured.success ? captured.value : undefined\n}\n","import type {\n\tJSONRPCMessage,\n\tMCPInputState,\n\tMCPJSONLimitOptions,\n\tMCPRequestContext,\n} from './types.js'\nimport {\n\tisInteger,\n\tisJSONValue,\n\tisNumber,\n\tisRecord,\n\tisString,\n\tisUndefined,\n} from '@orkestrel/contract'\nimport { snapshotJSON } from './cloners.js'\nimport {\n\tDEFAULT_MCP_LIMITS,\n\tMCP_META_CAPABILITIES,\n\tMCP_META_CLIENT,\n\tMCP_META_VERSION,\n} from './constants.js'\nimport {\n\tisJSONRPCId,\n\tisJSONRPCMessage,\n\tisMCPClientCapabilities,\n\tisMCPElicitSchema,\n\tisMCPIdentity,\n\tisMCPLoggingLevel,\n\tisMCPMetaObject,\n\tisModernRequest,\n} from './validators.js'\n\n/**\n * Narrow an already-parsed value to a {@link JSONRPCMessage}, or `undefined` when\n * it is not one.\n *\n * @remarks\n * Total (§14) — a non-message returns `undefined`, never throws. The input must\n * ALREADY be `JSON.parse`d: the raw-string parse (which can throw on malformed\n * JSON) happens in `MCPServer.handle` inside a try/catch that maps a parse failure\n * to a `-32700` response.\n *\n * A defined result is an OWNED CANONICAL SNAPSHOT, never the input reference: it is\n * rebuilt from the canonical text and deeply frozen, so `-0` arrives as `0`. Every record\n * was SERIALIZED with its keys sorted, but the rebuilt object enumerates its own keys the\n * way JavaScript does, so an integer-like `'9'` still precedes `'10'`: the result's key\n * order is neither promised nor generally the canonical one. A caller who needs canonical\n * BYTES takes them from `serializeJSON`/`snapshotJSON` rather than re-stringifying this\n * result. Identity is not preserved and is not promised.\n *\n * The parser's sound partner is the COMPOSITE `isJSONRPCMessage(value) &&\n * isBoundedJSON(value, limits)`, and against it both halves of the §15 soundness law\n * hold by construction:\n *\n * - Every non-`undefined` result satisfies {@link isJSONRPCMessage}, because the guard\n * is applied to the exact frozen reference returned.\n * - Every input satisfying the composite is admitted rather than rejected, because\n * `isBoundedJSON` is this parser's own admission test — the same canonical\n * serializer under the same `limits` — so the two cannot disagree about the bound.\n *\n * {@link isJSONRPCMessage} ALONE is not that partner. It is clone-backed and so already\n * exact about shape, but it carries no size or depth bound — so guard-valid values\n * exist that this parser rejects: a message nested deeper than `limits.depth`, and one\n * whose canonical text exceeds `limits.bytes`. Those are named causes, NOT a complete\n * boundary. Among values `isJSONRPCMessage` already admits, the admitted set is exactly\n * what canonical serialization accepts under `limits`, so a caller who needs that line\n * tests it with `isBoundedJSON` rather than inferring it from this list.\n *\n * @param value - The already-parsed value to narrow\n * @param limits - Canonical byte and nesting-depth bounds; defaults to the MCP content\n * and depth limits, which impose no key-count cap unless the caller supplies one\n * @returns The value as a {@link JSONRPCMessage}, or `undefined`\n *\n * @example\n * ```ts\n * parseJSONRPCMessage({ jsonrpc: '2.0', method: 'ping', id: 1 }) // the request\n * parseJSONRPCMessage({ method: 'ping' }) // undefined — missing jsonrpc\n * ```\n */\nexport function parseJSONRPCMessage(\n\tvalue: unknown,\n\tlimits: MCPJSONLimitOptions = {\n\t\tbytes: DEFAULT_MCP_LIMITS.content,\n\t\tdepth: DEFAULT_MCP_LIMITS.depth,\n\t},\n): JSONRPCMessage | undefined {\n\tconst snapshot = snapshotJSON(value, limits)\n\treturn snapshot !== undefined && isJSONRPCMessage(snapshot[0]) ? snapshot[0] : undefined\n}\n\n/**\n * Parse the reserved modern request metadata into an {@link MCPRequestContext}.\n *\n * @remarks\n * This is the validity step after {@link isModernRequest}: a defined result can\n * only come from a guard-positive request, while a guard-positive request returns\n * `undefined` when its required modern metadata is malformed — and also when the\n * request falls outside the bound this parser INHERITS by routing through\n * {@link parseJSONRPCMessage} under the same `limits`. The version\n * must be a string but need not be supported; unsupported strings belong to the\n * dedicated protocol-version error path. Client identity is optional, but when\n * present it must carry string `name` and `version` members. Total over hostile and\n * malformed input.\n *\n * @param value - The already-parsed request candidate to coerce\n * @param limits - Canonical byte and nesting-depth bounds, forwarded to\n * {@link parseJSONRPCMessage}; defaults to the MCP content and depth limits\n * @returns The validated modern request context, or `undefined`\n */\nexport function parseRequestContext(\n\tvalue: unknown,\n\tlimits: MCPJSONLimitOptions = {\n\t\tbytes: DEFAULT_MCP_LIMITS.content,\n\t\tdepth: DEFAULT_MCP_LIMITS.depth,\n\t},\n): MCPRequestContext | undefined {\n\ttry {\n\t\tconst request = parseJSONRPCMessage(value, limits)\n\t\tif (request === undefined || !('method' in request) || !isModernRequest(request))\n\t\t\treturn undefined\n\t\tconst metadata = request.params?.['_meta']\n\t\tif (!isMCPMetaObject(metadata)) return undefined\n\t\tconst version = metadata[MCP_META_VERSION]\n\t\tconst capabilities = metadata[MCP_META_CAPABILITIES]\n\t\tif (!isString(version) || !isMCPClientCapabilities(capabilities)) return undefined\n\t\tconst level = metadata['io.modelcontextprotocol/logLevel']\n\t\tif (!isUndefined(level) && !isMCPLoggingLevel(level)) return undefined\n\t\tconst progress = metadata['progressToken']\n\t\tif (!isUndefined(progress) && !isString(progress) && !isInteger(progress)) return undefined\n\t\tconst client = metadata[MCP_META_CLIENT]\n\t\tif (client === undefined) return Object.freeze({ version, capabilities })\n\t\tif (!isMCPIdentity(client)) return undefined\n\t\treturn Object.freeze({ version, capabilities, identity: client })\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Parse the opened value carried by an opaque `requestState` continuation.\n *\n * @remarks\n * This parser does not open the opaque continuation carrier; the configured\n * continuation port performs that boundary first. The protected\n * payload binds the authenticated principal, absolute expiry, ORIGINAL request id, version,\n * method, server-assigned key, tool name, argument digest, the exact issued elicitation\n * schema, and optional application state. Every member is required except application state:\n * a payload missing its schema cannot have its accepted response enforced, so it is refused\n * rather than admitted unenforced. Total over malformed or hostile input.\n *\n * @param value - The opened canonical continuation value to parse\n * @returns The protected input state, or `undefined` when malformed\n *\n * @example\n * ```ts\n * parseMCPInputState('{\"principal\":\"user-1\",\"expiry\":2000,\"id\":1,\"version\":\"2026-07-28\",\"method\":\"tools/call\",\"key\":\"k\",\"name\":\"reply\",\"digest\":\"abc\",\"schema\":{\"type\":\"object\",\"properties\":{}}}')\n * ```\n */\nexport function parseMCPInputState(value: unknown): MCPInputState | undefined {\n\ttry {\n\t\tif (!isString(value)) return undefined\n\t\tconst parsed: unknown = JSON.parse(value)\n\t\tif (!isRecord(parsed)) return undefined\n\t\tconst principal = parsed['principal']\n\t\tconst expiry = parsed['expiry']\n\t\tconst id = parsed['id']\n\t\tconst version = parsed['version']\n\t\tconst method = parsed['method']\n\t\tconst key = parsed['key']\n\t\tconst name = parsed['name']\n\t\tconst digest = parsed['digest']\n\t\tconst schema = parsed['schema']\n\t\tconst state = parsed['state']\n\t\tif (\n\t\t\t!isString(principal) ||\n\t\t\tprincipal.length === 0 ||\n\t\t\t!isNumber(expiry) ||\n\t\t\t!Number.isFinite(expiry)\n\t\t) {\n\t\t\treturn undefined\n\t\t}\n\t\tif (!isJSONRPCId(id)) return undefined\n\t\tif (!isString(version) || !isString(method) || !isString(key) || !isString(name)) {\n\t\t\treturn undefined\n\t\t}\n\t\tif (!isString(digest) || (!isUndefined(state) && !isJSONValue(state))) return undefined\n\t\tif (!isMCPElicitSchema(schema)) return undefined\n\t\treturn {\n\t\t\tprincipal,\n\t\t\texpiry,\n\t\t\tid,\n\t\t\tversion,\n\t\t\tmethod,\n\t\t\tkey,\n\t\t\tname,\n\t\t\tdigest,\n\t\t\tschema,\n\t\t\t...(isUndefined(state) ? {} : { state }),\n\t\t}\n\t} catch {\n\t\treturn undefined\n\t}\n}\n","import type { ToolCall, ToolManagerInterface } from '@orkestrel/tool'\nimport type {\n\tJSONRPCErrorResponse,\n\tJSONRPCId,\n\tJSONRPCMessage,\n\tJSONRPCNotification,\n\tJSONRPCRequest,\n\tJSONRPCResultResponse,\n\tMCPCallOutcome,\n\tMCPClientInterface,\n\tMCPDiscoverResult,\n\tMCPDispatchOptions,\n\tMCPIdentity,\n\tMCPJSONLimitOptions,\n\tMCPLegacyResult,\n\tMCPMethodOptions,\n\tMCPProgress,\n\tMCPResult,\n\tMCPResultMetaObject,\n\tMCPDispatcherInterface,\n\tMCPServerOptions,\n\tMCPSubscriptionFilter,\n\tMCPTextStreamControllerInterface,\n\tMCPToolDescriptor,\n\tMCPTransportInterface,\n\tSubscriptionsListenResult,\n\tSubscriptionsListenResultMetaObject,\n} from './types.js'\nimport {\n\tattempt,\n\tisArray,\n\tisBoolean,\n\tisJSONValue,\n\tisNumber,\n\tisRecord,\n\tisString,\n} from '@orkestrel/contract'\nimport {\n\tDEFAULT_MCP_CACHE_TTL,\n\tJSONRPC_INVALID_PARAMS,\n\tMCP_EXTENSION_TASKS,\n\tMCP_LEGACY_VERSION,\n\tMCP_META_SERVER,\n\tMCP_META_SUBSCRIPTION,\n\tSUPPORTED_PROTOCOL_VERSIONS,\n} from './constants.js'\nimport { MCPError } from './errors.js'\nimport { inferEra } from './inferers.js'\nimport { parseJSONRPCMessage } from './parsers.js'\nimport {\n\tisBoundedString,\n\tisJSONRPCId,\n\tisJSONRPCNotification,\n\tisMCPInputResult,\n\tisMCPMetaObject,\n\tisMCPTaskResult,\n\tisMCPVersion,\n} from './validators.js'\n\n/**\n * Deterministically serialize one exact JSON value within explicit bounds.\n *\n * @param value - The unknown value to validate and serialize\n * @param limits - Serialized byte, key, and depth limits\n * @returns Canonical JSON, or `undefined` when invalid or out of bounds\n */\nexport function serializeJSON(value: unknown, limits: MCPJSONLimitOptions): string | undefined {\n\tconst serialized = attempt(() => {\n\t\tconst limit = limits.bytes\n\t\tconst depth = limits.depth\n\t\tconst breadth = limits.keys\n\t\tif (!Number.isFinite(limit) || !Number.isInteger(limit) || limit < 0) return undefined\n\t\tif (!Number.isFinite(depth) || !Number.isInteger(depth) || depth < 0) return undefined\n\t\tif (\n\t\t\tbreadth !== undefined &&\n\t\t\t(!Number.isFinite(breadth) || !Number.isInteger(breadth) || breadth < 0)\n\t\t)\n\t\t\treturn undefined\n\n\t\tlet bytes = 0\n\t\tlet keys = 0\n\t\tconst chunks: string[] = []\n\t\tconst ancestors = new WeakSet<object>()\n\t\tconst pending: (\n\t\t\t| { readonly operation: 'value'; readonly value: unknown; readonly depth: number }\n\t\t\t| { readonly operation: 'string'; readonly value: string; readonly output: string[] }\n\t\t\t| { readonly operation: 'text'; readonly text: string }\n\t\t\t| { readonly operation: 'close'; readonly value: object; readonly text: string }\n\t\t\t| {\n\t\t\t\t\treadonly operation: 'record'\n\t\t\t\t\treadonly value: object\n\t\t\t\t\treadonly names: readonly string[]\n\t\t\t\t\treadonly encoded: string[]\n\t\t\t\t\treadonly index: number\n\t\t\t\t\treadonly depth: number\n\t\t\t }\n\t\t)[] = [{ operation: 'value', value, depth: 0 }]\n\n\t\twhile (pending.length > 0) {\n\t\t\tconst frame = pending.pop()\n\t\t\tif (frame === undefined) return undefined\n\t\t\tif (frame.operation === 'text') {\n\t\t\t\tchunks.push(frame.text)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (frame.operation === 'close') {\n\t\t\t\tancestors.delete(frame.value)\n\t\t\t\tchunks.push(frame.text)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (frame.operation === 'string') {\n\t\t\t\tlet encodedBytes = 2\n\t\t\t\tfor (let index = 0; index < frame.value.length; index += 1) {\n\t\t\t\t\tconst code = frame.value.charCodeAt(index)\n\t\t\t\t\tif (code === 0x22 || code === 0x5c) encodedBytes += 2\n\t\t\t\t\telse if (\n\t\t\t\t\t\tcode === 0x08 ||\n\t\t\t\t\t\tcode === 0x09 ||\n\t\t\t\t\t\tcode === 0x0a ||\n\t\t\t\t\t\tcode === 0x0c ||\n\t\t\t\t\t\tcode === 0x0d\n\t\t\t\t\t)\n\t\t\t\t\t\tencodedBytes += 2\n\t\t\t\t\telse if (code < 0x20) encodedBytes += 6\n\t\t\t\t\telse if (code < 0x80) encodedBytes += 1\n\t\t\t\t\telse if (code < 0x800) encodedBytes += 2\n\t\t\t\t\telse if (code >= 0xd800 && code <= 0xdbff) {\n\t\t\t\t\t\tconst next = index + 1 < frame.value.length ? frame.value.charCodeAt(index + 1) : 0\n\t\t\t\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\t\t\t\tencodedBytes += 4\n\t\t\t\t\t\t\tindex += 1\n\t\t\t\t\t\t} else encodedBytes += 6\n\t\t\t\t\t} else if (code >= 0xdc00 && code <= 0xdfff) encodedBytes += 6\n\t\t\t\t\telse encodedBytes += 3\n\t\t\t\t\tif (bytes + encodedBytes > limit) return undefined\n\t\t\t\t}\n\t\t\t\tbytes += encodedBytes\n\t\t\t\tif (bytes > limit) return undefined\n\t\t\t\tconst text = JSON.stringify(frame.value)\n\t\t\t\tif (!isString(text)) return undefined\n\t\t\t\tframe.output.push(text)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (frame.operation === 'record') {\n\t\t\t\tconst name = frame.names[frame.index]\n\t\t\t\tif (name !== undefined) {\n\t\t\t\t\tpending.push({ ...frame, index: frame.index + 1 })\n\t\t\t\t\tpending.push({ operation: 'string', value: name, output: frame.encoded })\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst entries: { readonly text: string; readonly value: unknown }[] = []\n\t\t\t\tfor (let index = 0; index < frame.names.length; index += 1) {\n\t\t\t\t\tconst key = frame.names[index]\n\t\t\t\t\tconst text = frame.encoded[index]\n\t\t\t\t\tif (key === undefined || text === undefined) return undefined\n\t\t\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(frame.value, key)\n\t\t\t\t\tif (\n\t\t\t\t\t\tdescriptor === undefined ||\n\t\t\t\t\t\tdescriptor.enumerable !== true ||\n\t\t\t\t\t\t!Object.hasOwn(descriptor, 'value')\n\t\t\t\t\t)\n\t\t\t\t\t\treturn undefined\n\t\t\t\t\tentries.push({ text, value: descriptor.value })\n\t\t\t\t}\n\t\t\t\tancestors.add(frame.value)\n\t\t\t\tchunks.push('{')\n\t\t\t\tpending.push({ operation: 'close', value: frame.value, text: '}' })\n\t\t\t\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tconst property = entries[index]\n\t\t\t\t\tif (property === undefined) return undefined\n\t\t\t\t\tpending.push({ operation: 'value', value: property.value, depth: frame.depth + 1 })\n\t\t\t\t\tpending.push({ operation: 'text', text: ':' })\n\t\t\t\t\tpending.push({ operation: 'text', text: property.text })\n\t\t\t\t\tif (index > 0) pending.push({ operation: 'text', text: ',' })\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (frame.depth > depth) return undefined\n\t\t\tconst entry = frame.value\n\t\t\tif (entry === null || isBoolean(entry)) {\n\t\t\t\tconst text = entry === null ? 'null' : entry ? 'true' : 'false'\n\t\t\t\tbytes += text.length\n\t\t\t\tif (bytes > limit) return undefined\n\t\t\t\tchunks.push(text)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (isNumber(entry)) {\n\t\t\t\tif (!Number.isFinite(entry)) return undefined\n\t\t\t\tconst text = JSON.stringify(entry)\n\t\t\t\tif (!isString(text)) return undefined\n\t\t\t\tbytes += text.length\n\t\t\t\tif (bytes > limit) return undefined\n\t\t\t\tchunks.push(text)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (isString(entry)) {\n\t\t\t\tpending.push({ operation: 'string', value: entry, output: chunks })\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (typeof entry !== 'object' || ancestors.has(entry)) return undefined\n\t\t\tif (Array.isArray(entry)) {\n\t\t\t\tconst lengthDescriptor = Reflect.getOwnPropertyDescriptor(entry, 'length')\n\t\t\t\tif (\n\t\t\t\t\tlengthDescriptor === undefined ||\n\t\t\t\t\t!Object.hasOwn(lengthDescriptor, 'value') ||\n\t\t\t\t\t!isNumber(lengthDescriptor.value) ||\n\t\t\t\t\t!Number.isInteger(lengthDescriptor.value) ||\n\t\t\t\t\tlengthDescriptor.value < 0 ||\n\t\t\t\t\tlengthDescriptor.value > 0xffff_ffff ||\n\t\t\t\t\tlengthDescriptor.enumerable === true ||\n\t\t\t\t\tlengthDescriptor.configurable === true\n\t\t\t\t)\n\t\t\t\t\treturn undefined\n\t\t\t\tconst length = lengthDescriptor.value\n\t\t\t\tkeys += length\n\t\t\t\tbytes += 2 + (length === 0 ? 0 : length - 1)\n\t\t\t\tif (bytes > limit || (breadth !== undefined && keys > breadth)) return undefined\n\t\t\t\tif (length > 0 && frame.depth >= depth) return undefined\n\t\t\t\tconst names = Reflect.ownKeys(entry)\n\t\t\t\tif (names.length !== length + 1) return undefined\n\t\t\t\tlet foundLength = false\n\t\t\t\tfor (const name of names) {\n\t\t\t\t\tif (!isString(name)) return undefined\n\t\t\t\t\tif (name === 'length') {\n\t\t\t\t\t\tif (foundLength) return undefined\n\t\t\t\t\t\tfoundLength = true\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst index = Number(name)\n\t\t\t\t\tif (!Number.isInteger(index) || index < 0 || index >= length || String(index) !== name)\n\t\t\t\t\t\treturn undefined\n\t\t\t\t}\n\t\t\t\tif (!foundLength) return undefined\n\t\t\t\tconst values: unknown[] = []\n\t\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(entry, String(index))\n\t\t\t\t\tif (\n\t\t\t\t\t\tdescriptor === undefined ||\n\t\t\t\t\t\tdescriptor.enumerable !== true ||\n\t\t\t\t\t\t!Object.hasOwn(descriptor, 'value')\n\t\t\t\t\t)\n\t\t\t\t\t\treturn undefined\n\t\t\t\t\tvalues.push(descriptor.value)\n\t\t\t\t}\n\t\t\t\tancestors.add(entry)\n\t\t\t\tchunks.push('[')\n\t\t\t\tpending.push({ operation: 'close', value: entry, text: ']' })\n\t\t\t\tfor (let index = values.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tconst item = values[index]\n\t\t\t\t\tpending.push({ operation: 'value', value: item, depth: frame.depth + 1 })\n\t\t\t\t\tif (index > 0) pending.push({ operation: 'text', text: ',' })\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (!isRecord(entry)) return undefined\n\t\t\tconst ownKeys = Reflect.ownKeys(entry)\n\t\t\tkeys += ownKeys.length\n\t\t\tbytes += 2 + (ownKeys.length === 0 ? 0 : ownKeys.length - 1) + ownKeys.length\n\t\t\tif (bytes > limit || (breadth !== undefined && keys > breadth)) return undefined\n\t\t\tif (ownKeys.length > 0 && frame.depth >= depth) return undefined\n\t\t\tconst names: string[] = []\n\t\t\tfor (const key of ownKeys) {\n\t\t\t\tif (!isString(key)) return undefined\n\t\t\t\tnames.push(key)\n\t\t\t}\n\t\t\tnames.sort()\n\t\t\tpending.push({\n\t\t\t\toperation: 'record',\n\t\t\t\tvalue: entry,\n\t\t\t\tnames,\n\t\t\t\tencoded: [],\n\t\t\t\tindex: 0,\n\t\t\t\tdepth: frame.depth,\n\t\t\t})\n\t\t}\n\t\treturn chunks.join('')\n\t})\n\treturn serialized.success ? serialized.value : undefined\n}\n\n/**\n * Compute a lowercase host-neutral SHA-256 digest of one bounded canonical JSON value.\n *\n * @param value - The unknown value to validate and digest\n * @param limits - Serialized byte, key, and depth limits\n * @returns The lowercase hexadecimal digest, or `undefined` when invalid\n */\nexport async function digestJSON(\n\tvalue: unknown,\n\tlimits: MCPJSONLimitOptions,\n): Promise<string | undefined> {\n\tconst serialized = serializeJSON(value, limits)\n\tif (serialized === undefined) return undefined\n\tconst digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized))\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Build one official progress notification for the original request stream.\n *\n * @param token - The request's original opaque progress token\n * @param progress - The finite progress payload\n * @returns The official `notifications/progress` request\n */\nexport function buildProgressNotification(\n\ttoken: string | number,\n\tprogress: MCPProgress,\n): JSONRPCNotification {\n\treturn {\n\t\tjsonrpc: '2.0',\n\t\tmethod: 'notifications/progress',\n\t\tparams: {\n\t\t\tprogressToken: token,\n\t\t\tprogress: progress.progress,\n\t\t\t...(progress.total === undefined ? {} : { total: progress.total }),\n\t\t\t...(progress.message === undefined ? {} : { message: progress.message }),\n\t\t},\n\t}\n}\n\n/**\n * Build one official cancellation notification for a request already sent.\n *\n * @remarks\n * `requestId` and `reason` are WIRE SPELLINGS carried verbatim from the dated schema's\n * `CancelledNotificationParams`, and so is the `cancelled` in the method name — this\n * package's own vocabulary says `abort`, but the method is the protocol's and does not\n * change. The notification is FIRE-AND-FORGET in the strongest sense: it carries no id,\n * so nothing answers it, and every receiver obligation the spec states is `SHOULD` or\n * `MAY`. A peer may ignore it for a request it never saw, has already answered, or cannot\n * interrupt, and the sender must treat a late answer to the cancelled request as ordinary\n * rather than as a violation.\n *\n * Only write one on a carrier that accepts a client-initiated notification — see\n * {@link import('./types.js').MCPClientTransportInterface.duplex}. On Streamable HTTP the\n * dated revision defines no such frame, and closing the response stream is the\n * cancellation signal instead.\n *\n * @param id - The JSON-RPC id of the request being cancelled\n * @param reason - An optional human-readable reason for the cancellation\n * @returns The official `notifications/cancelled` notification\n *\n * @example\n * ```ts\n * buildCancelledNotification(7, 'caller aborted')\n * // → { jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: 7, reason: 'caller aborted' } }\n * ```\n */\nexport function buildCancelledNotification(id: JSONRPCId, reason?: string): JSONRPCNotification {\n\treturn {\n\t\tjsonrpc: '2.0',\n\t\tmethod: 'notifications/cancelled',\n\t\tparams: {\n\t\t\trequestId: id,\n\t\t\t...(reason === undefined ? {} : { reason }),\n\t\t},\n\t}\n}\n\n/**\n * Determine whether one method may answer with a given modern `resultType`.\n *\n * @remarks\n * The dated protocol lets a `tools/call` answer three ways — it COMPLETED, it became a\n * durable task, or it needs another round trip — while every other method this client\n * issues has exactly one legal answer. So the arm a peer chose is only meaningful beside\n * the method it answers, and this is the one place that pairing is decided.\n *\n * The rule is deliberately a WHITELIST: an unrecognized `resultType` is refused for every\n * method, including `tools/call`. A client that carried an arm it cannot name would hand\n * its caller a value whose meaning it invented.\n *\n * @param method - The method the pending request was issued for\n * @param resultType - The unknown `resultType` the peer answered with\n * @returns Whether that method may legally answer with that `resultType`\n *\n * @example\n * ```ts\n * matchesResultType('tools/call', 'task') // true\n * matchesResultType('tools/list', 'task') // false\n * matchesResultType('tools/call', 'future') // false\n * ```\n */\nexport function matchesResultType(method: string, resultType: unknown): boolean {\n\tif (resultType === 'complete') return true\n\tif (method !== 'tools/call') return false\n\treturn resultType === 'task' || resultType === 'input_required'\n}\n\n/**\n * Concatenate an MCP tool-call result's text content blocks into one string.\n *\n * @remarks\n * The inverse of a server splitting a value into text block(s), and TOTAL: a non-record\n * result, a non-array `content`, or a non-string `text` contributes nothing rather than\n * throwing. What it returns is a RENDERING — the prose a model reads — and not the tool's\n * value, which travels as `structuredContent` whenever the peer sent one.\n *\n * @param result - The unknown result payload to read content blocks from\n * @returns Every text block joined by newlines, or an empty string when there are none\n *\n * @example\n * ```ts\n * extractContentText({ content: [{ type: 'text', text: 'hi' }] }) // 'hi'\n * extractContentText('not a result') // ''\n * ```\n */\nexport function extractContentText(result: unknown): string {\n\tif (!isRecord(result) || !isArray(result['content'])) return ''\n\tconst parts: string[] = []\n\tfor (const block of result['content']) {\n\t\tif (isRecord(block) && isString(block['text'])) parts.push(block['text'])\n\t}\n\treturn parts.join('\\n')\n}\n\n/**\n * Narrow one `tools/call` answer to the arm the peer chose.\n *\n * @remarks\n * The three arms {@link matchesResultType} admits are the whole space this sees, because a\n * `resultType` the client cannot name is refused at correlation. What is left is validating\n * the two arms the protocol gives a shape to, and deriving the tool's value from the one it\n * does not:\n *\n * - A peer's `structuredContent` is PREFERRED over the content blocks, because it is the\n * tool's value in its original structure while the blocks are a rendering beside it. Its\n * mere presence decides — an explicit `null` is a value the tool returned, not an absence.\n * - With no structured value the legacy shape applies: the value was JSON-serialized into\n * the text block(s), so parse them and fall back to the raw string when they are not JSON.\n * - A remote tool FAILURE (`isError: true`) THROWS the error text, so an agent's tool\n * registry isolates it into a failure result exactly as it would a local throw.\n *\n * @param name - The tool's name, used only to describe a failure that carried no text\n * @param result - The already-owned result payload the peer answered with\n * @returns The arm the peer answered with, frozen\n * @throws MCPError when a task or input arm's payload does not match its schema\n * @throws Error when the remote tool failed\n *\n * @example\n * ```ts\n * buildCallOutcome('search', { resultType: 'complete', structuredContent: { count: 3 } })\n * // → { resultType: 'complete', value: { count: 3 } }\n * ```\n */\nexport function buildCallOutcome(name: string, result: unknown): MCPCallOutcome {\n\tconst resultType = isRecord(result) ? result['resultType'] : undefined\n\tif (resultType === 'task') {\n\t\tif (!isMCPTaskResult(result)) {\n\t\t\tthrow new MCPError(\n\t\t\t\t'MCP server returned a malformed task result',\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\tresult,\n\t\t\t)\n\t\t}\n\t\treturn Object.freeze(result)\n\t}\n\tif (resultType === 'input_required') {\n\t\tif (!isMCPInputResult(result)) {\n\t\t\tthrow new MCPError(\n\t\t\t\t'MCP server returned a malformed input request',\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\tresult,\n\t\t\t)\n\t\t}\n\t\treturn Object.freeze(result)\n\t}\n\tconst text = extractContentText(result)\n\tif (isRecord(result) && result['isError'] === true) {\n\t\tthrow new Error(text.length > 0 ? text : `MCP tool '${name}' failed`)\n\t}\n\tlet value: unknown\n\tif (isRecord(result) && Object.hasOwn(result, 'structuredContent')) {\n\t\tvalue = result['structuredContent']\n\t} else if (text.length > 0) {\n\t\ttry {\n\t\t\tvalue = JSON.parse(text)\n\t\t} catch {\n\t\t\tvalue = text\n\t\t}\n\t}\n\tconst outcome: MCPCallOutcome = { resultType: 'complete', value }\n\treturn Object.freeze(outcome)\n}\n\n/**\n * Build the canonical Tool call for one validated MCP `tools/call` request.\n *\n * @param request - The original MCP request\n * @param caller - Optional consumer-asserted caller context\n * @param args - Optional once-validated modern arguments; omission retains legacy normalization\n * @returns The canonical call, or `undefined` when the name is invalid\n */\nexport function buildToolCall(\n\trequest: JSONRPCRequest,\n\tcaller?: unknown,\n\targs?: Readonly<Record<string, unknown>>,\n): ToolCall | undefined {\n\tconst name = request.params?.['name']\n\tif (typeof name !== 'string') return undefined\n\tconst rawArguments = request.params?.['arguments']\n\treturn {\n\t\tid: String(request.id),\n\t\tname,\n\t\targuments: args ?? (isRecord(rawArguments) ? rawArguments : {}),\n\t\t...(caller === undefined ? {} : { caller }),\n\t}\n}\n\n// Pure dispatch builders (AGENTS §5: the dispatch branches stay exported helpers,\n// not hidden privates). Each turns a piece of MCP state into the JSON-RPC `result`\n// payload (or a response envelope) the server returns — independently testable.\n\n/**\n * Build a JSON-RPC success {@link JSONRPCResultResponse} — the `id` echoed, the\n * method's value as `result`.\n *\n * @remarks\n * A result answers a request, and a request always carries a readable id, so `id` is\n * required here. The failure arm is the only one that can lack one.\n *\n * @param id - The request's id\n * @param result - The method's return value\n * @returns The success response envelope\n */\nexport function buildJSONRPCResult(\n\tid: JSONRPCId,\n\tresult: MCPResult | MCPLegacyResult,\n): JSONRPCResultResponse {\n\treturn { jsonrpc: '2.0', id, result }\n}\n\n/**\n * Build a JSON-RPC error {@link JSONRPCErrorResponse} — the `id` echoed, the failure\n * as an `error` object.\n *\n * @remarks\n * An `undefined` `id` is OMITTED from the envelope rather than serialized as `null`:\n * MCP overrides the base specification here, so a peer that could not have its id\n * read receives a response with no `id` member at all.\n *\n * @param id - The failed request's id, or `undefined` when none could be read\n * @param code - One of the reserved JSON-RPC codes (see `./constants.js`)\n * @param message - A short human description of the failure\n * @param data - An OPTIONAL machine-readable payload (omitted from the envelope when absent)\n * @returns The error response envelope\n */\nexport function buildJSONRPCError(\n\tid: JSONRPCId | undefined,\n\tcode: number,\n\tmessage: string,\n\tdata?: unknown,\n): JSONRPCErrorResponse {\n\treturn {\n\t\tjsonrpc: '2.0',\n\t\t...(id === undefined ? {} : { id }),\n\t\terror: data === undefined ? { code, message } : { code, message, data },\n\t}\n}\n\n/**\n * Resolve the caller-facing dispatch options into the options a dispatched method\n * receives.\n *\n * @remarks\n * The ONE place a cancellation signal is resolved. A caller may have no signal to\n * offer; a dispatched method always has one to observe, so a missing signal becomes\n * a real signal rather than an absence every downstream handler would have to case on.\n *\n * The resolved signal is the request's LIFETIME, which is strictly wider than the\n * caller's: it composes the caller's signal, when there is one, with the `lifetime`\n * dispatch owns and aborts once the answer this request produced is finished. That is\n * what wakes a stream producer parked on an event that will never arrive after its\n * consumer walked away — a caller-only signal would leave it parked forever.\n *\n * `caller` is carried by identity and omitted when absent — this package never\n * inspects, validates, clones, or serializes it.\n *\n * @param options - The caller-facing per-request options\n * @param lifetime - The request-scoped signal dispatch aborts when the answer is finished\n * @returns The resolved per-request method options\n *\n * @example\n * ```ts\n * const lifetime = new AbortController()\n * buildMethodOptions({}, lifetime.signal).signal.aborted // false — until the answer ends\n * ```\n */\nexport function buildMethodOptions(\n\toptions: MCPDispatchOptions,\n\tlifetime: AbortSignal,\n): MCPMethodOptions {\n\treturn {\n\t\tsignal: options.signal === undefined ? lifetime : AbortSignal.any([options.signal, lifetime]),\n\t\t...(options.caller === undefined ? {} : { caller: options.caller }),\n\t}\n}\n\n/**\n * Map a {@link ToolManagerInterface}'s definitions to MCP `tools/list` descriptors\n * — renaming `parameters` to the wire's `inputSchema`.\n *\n * @remarks\n * Each {@link import('@orkestrel/tool').ToolDefinition} carries through its\n * `name` and (when present) `description`; its open JSON-Schema `parameters`\n * becomes `inputSchema`, defaulting to an empty object schema (`{ type: 'object' }`)\n * when a tool declares none (MCP requires an `inputSchema`).\n *\n * @param manager - The tool registry to describe\n * @returns One {@link MCPToolDescriptor} per registered tool, in registry order\n */\nexport function buildToolDescriptors(manager: ToolManagerInterface): readonly MCPToolDescriptor[] {\n\treturn manager.definitions().map((definition) => {\n\t\tconst descriptor: {\n\t\t\tname: string\n\t\t\tdescription?: string\n\t\t\tinputSchema: Readonly<Record<string, unknown>>\n\t\t} = {\n\t\t\tname: definition.name,\n\t\t\tinputSchema: definition.parameters ?? { type: 'object' },\n\t\t}\n\t\tif (definition.description !== undefined) descriptor.description = definition.description\n\t\treturn descriptor\n\t})\n}\n\n/**\n * Stamp a result with the modern complete-result discriminator and server\n * metadata, plus cache fields when the result is cacheable.\n *\n * @remarks\n * This is the single stamping site shared by modern result builders. Supplying\n * `ttl` adds both schema-coupled fields (`ttlMs` and `cacheScope`); omitting it\n * adds neither, which keeps `tools/call` distinct from cacheable results.\n *\n * @param result - The unstamped result payload\n * @param identity - The server identity carried under the reserved `_meta` key\n * @param ttl - Required freshness lifetime for a cacheable result; omit for a non-cacheable result\n * @param scope - The cache visibility, defaulting to `'private'` when `ttl` is supplied\n * @returns A copy of the payload with its modern stamps\n */\nexport function buildModernResult<T extends object>(\n\tresult: T,\n\tidentity: MCPIdentity,\n\tttl: number,\n\tscope?: 'public' | 'private',\n): T & {\n\treadonly resultType: 'complete'\n\treadonly _meta: MCPResultMetaObject\n\treadonly ttlMs: number\n\treadonly cacheScope: 'public' | 'private'\n}\nexport function buildModernResult<T extends object>(\n\tresult: T,\n\tidentity: MCPIdentity,\n): T & {\n\treadonly resultType: 'complete'\n\treadonly _meta: MCPResultMetaObject\n}\nexport function buildModernResult<T extends object>(\n\tresult: T,\n\tidentity: MCPIdentity,\n\tttl?: number,\n\tscope?: 'public' | 'private',\n): T & {\n\treadonly resultType: 'complete'\n\treadonly _meta: MCPResultMetaObject\n\treadonly ttlMs?: number\n\treadonly cacheScope?: 'public' | 'private'\n} {\n\tconst currentMetadata = isRecord(result) ? result['_meta'] : undefined\n\tif (!isJSONValue(identity)) throw new TypeError('MCP identity must be exact JSON')\n\tconst metadata = {\n\t\t...(isMCPMetaObject(currentMetadata) ? currentMetadata : {}),\n\t\t[MCP_META_SERVER]: identity,\n\t}\n\tif (ttl === undefined) return { ...result, resultType: 'complete', _meta: metadata }\n\treturn {\n\t\t...result,\n\t\tresultType: 'complete',\n\t\tttlMs: ttl,\n\t\tcacheScope: scope ?? 'private',\n\t\t_meta: metadata,\n\t}\n}\n\n/**\n * Intersect a requested subscription filter with the notification families a server supports.\n *\n * @param requested - The notification families requested by the client\n * @param supported - The notification families the server can actually produce\n * @returns The exact subset the server will honour\n */\nexport function buildSubscriptionFilter(\n\trequested: MCPSubscriptionFilter,\n\tsupported: MCPSubscriptionFilter,\n): MCPSubscriptionFilter {\n\tconst toolsListChanged =\n\t\trequested.toolsListChanged === true && supported.toolsListChanged === true\n\tconst promptsListChanged =\n\t\trequested.promptsListChanged === true && supported.promptsListChanged === true\n\tconst resourcesListChanged =\n\t\trequested.resourcesListChanged === true && supported.resourcesListChanged === true\n\tconst supportedResources = new Set(supported.resourceSubscriptions ?? [])\n\tconst resourceSubscriptions = requested.resourceSubscriptions?.filter((uri) =>\n\t\tsupportedResources.has(uri),\n\t)\n\treturn {\n\t\t...(toolsListChanged ? { toolsListChanged: true } : {}),\n\t\t...(promptsListChanged ? { promptsListChanged: true } : {}),\n\t\t...(resourcesListChanged ? { resourcesListChanged: true } : {}),\n\t\t...(resourceSubscriptions !== undefined && resourceSubscriptions.length > 0\n\t\t\t? { resourceSubscriptions }\n\t\t\t: {}),\n\t}\n}\n\n/**\n * Determine whether a produced notification belongs to an honoured subscription filter.\n *\n * @param notification - The server notification offered by the configured producer\n * @param filter - The filter acknowledged to the client\n * @returns `true` when the notification belongs on this subscription stream\n */\nexport function matchesSubscriptionNotification(\n\tnotification: JSONRPCNotification,\n\tfilter: MCPSubscriptionFilter,\n): boolean {\n\tif (notification.method === 'notifications/tools/list_changed') {\n\t\treturn filter.toolsListChanged === true\n\t}\n\tif (notification.method === 'notifications/prompts/list_changed') {\n\t\treturn filter.promptsListChanged === true\n\t}\n\tif (notification.method === 'notifications/resources/list_changed') {\n\t\treturn filter.resourcesListChanged === true\n\t}\n\tif (notification.method !== 'notifications/resources/updated') return false\n\tconst uri = notification.params?.['uri']\n\treturn typeof uri === 'string' && filter.resourceSubscriptions?.includes(uri) === true\n}\n\n/**\n * Stamp a subscription notification with the request id reserved for its held-open stream.\n *\n * @param notification - The notification to copy and stamp\n * @param id - The `subscriptions/listen` request id\n * @returns The stamped notification, preserving its other params and metadata\n */\nexport function stampSubscriptionNotification(\n\tnotification: JSONRPCNotification,\n\tid: JSONRPCId,\n): JSONRPCNotification {\n\tconst metadata = notification.params?.['_meta']\n\treturn {\n\t\tjsonrpc: notification.jsonrpc,\n\t\tmethod: notification.method,\n\t\tparams: {\n\t\t\t...notification.params,\n\t\t\t_meta: {\n\t\t\t\t...(isRecord(metadata) ? metadata : {}),\n\t\t\t\t[MCP_META_SUBSCRIPTION]: id,\n\t\t\t},\n\t\t},\n\t}\n}\n\n/**\n * Build the first notification carrying a subscription id for a listen request.\n *\n * @param notifications - The exact notification filter the server will honour\n * @param id - The `subscriptions/listen` request id\n * @returns The stamped subscription acknowledgement notification\n */\nexport function buildSubscriptionAcknowledgement(\n\tnotifications: MCPSubscriptionFilter,\n\tid: JSONRPCId,\n): JSONRPCNotification {\n\treturn stampSubscriptionNotification(\n\t\t{\n\t\t\tjsonrpc: '2.0',\n\t\t\tmethod: 'notifications/subscriptions/acknowledged',\n\t\t\tparams: { notifications },\n\t\t},\n\t\tid,\n\t)\n}\n\n/**\n * Build the terminating response for a subscription source that closes gracefully.\n *\n * @param id - The `subscriptions/listen` request id\n * @param identity - The server identity included by the modern result stamping site\n * @returns The complete modern result carrying the required subscription id metadata\n */\nexport function buildSubscriptionResult(\n\tid: JSONRPCId,\n\tidentity: MCPIdentity,\n): JSONRPCResultResponse {\n\tconst metadata: SubscriptionsListenResultMetaObject = { [MCP_META_SUBSCRIPTION]: id }\n\tconst result: SubscriptionsListenResult = buildModernResult({ _meta: metadata }, identity)\n\treturn buildJSONRPCResult(id, result)\n}\n\n/**\n * Build the mandatory modern `server/discover` result.\n *\n * @remarks\n * `capabilities.resources` and `capabilities.prompts` appear only for servers with their\n * respective managers and derive notification flags from the configured subscription filter.\n * `capabilities.completions` is independent and appears only with a completion provider.\n * `capabilities.extensions` appears only for a server that CONFIGURED the extension it\n * would name. An advertisement is a promise a client is entitled to act on, so a server\n * with no `task` policy omits the member entirely rather than advertising an empty\n * record — and its discovery answer stays byte-for-byte what it was before the extension\n * existed.\n *\n * @param options - The server identity, instructions, cache, and extension configuration\n * @returns The supported revisions, capabilities, and required modern cache stamps\n */\nexport function buildDiscoverResult(options: MCPServerOptions): MCPDiscoverResult {\n\treturn buildModernResult(\n\t\t{\n\t\t\tsupportedVersions: SUPPORTED_PROTOCOL_VERSIONS.filter(isMCPVersion),\n\t\t\tcapabilities: {\n\t\t\t\ttools: {},\n\t\t\t\t...(options.resources === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tresources: {\n\t\t\t\t\t\t\t\t...(options.subscription?.notifications.resourceSubscriptions === undefined\n\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t: { subscribe: true }),\n\t\t\t\t\t\t\t\t...(options.subscription?.notifications.resourcesListChanged === true\n\t\t\t\t\t\t\t\t\t? { listChanged: true }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t...(options.prompts === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tprompts: {\n\t\t\t\t\t\t\t\t...(options.subscription?.notifications.promptsListChanged === true\n\t\t\t\t\t\t\t\t\t? { listChanged: true }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t...(options.completion === undefined ? {} : { completions: {} }),\n\t\t\t\t...(options.task === undefined ? {} : { extensions: { [MCP_EXTENSION_TASKS]: {} } }),\n\t\t\t},\n\t\t\t...(options.instructions === undefined ? {} : { instructions: options.instructions }),\n\t\t},\n\t\toptions.identity,\n\t\toptions.cache?.ttl ?? DEFAULT_MCP_CACHE_TTL,\n\t\toptions.cache?.scope,\n\t)\n}\n\n/**\n * Build the MCP `initialize` result — the negotiated protocol version, the\n * advertised capabilities, and the server identity.\n *\n * @remarks\n * Version negotiation echoes the client's `requested` version when it is one of the\n * supported legacy revisions. A modern or unsupported request receives the newest\n * supported legacy revision; the client decides whether to continue.\n * `capabilities.tools` is an empty object — this server advertises the tools\n * capability with no sub-options (no list-changed notification yet).\n *\n * @param name - The server name (echoed in `serverInfo`)\n * @param version - The server version (echoed in `serverInfo`)\n * @param requested - The client's requested protocol version (negotiated when supported)\n * @returns The `initialize` result payload\n */\nexport function buildInitializeResult(\n\tname: string,\n\tversion: string,\n\trequested?: string,\n): MCPLegacyResult {\n\tconst newestLegacy =\n\t\tSUPPORTED_PROTOCOL_VERSIONS.find((candidate) => inferEra(candidate) === 'legacy') ??\n\t\tMCP_LEGACY_VERSION\n\tconst protocolVersion =\n\t\tisMCPVersion(requested) && inferEra(requested) === 'legacy' ? requested : newestLegacy\n\treturn {\n\t\tprotocolVersion,\n\t\tcapabilities: { tools: {} },\n\t\tserverInfo: { name, version },\n\t}\n}\n\n/**\n * Decode one raw inbound message within an explicit bound — the decode a binder performs\n * before it hands the string on.\n *\n * @remarks\n * The bound is checked FIRST, against the raw string, so an oversized message is never\n * `JSON.parse`d at all: a decoder that parses before it measures has already spent the work\n * the bound exists to refuse. A message over the bound, malformed JSON, and a well-formed\n * value that is not a JSON-RPC message are one answer — `undefined` — because a binder does\n * exactly the same thing with all three: nothing, and let\n * {@link import('./types.js').MCPServerInterface.handle} produce the wire refusal from the\n * same bound.\n *\n * Total (§14) — never throws, whatever the input.\n *\n * @param message - The raw inbound JSON-RPC message string\n * @param limits - The byte and depth bounds to decode within (the server's own, via `limit`)\n * @returns The decoded message, or `undefined` when it is over the bound or is not one\n *\n * @example\n * ```ts\n * decodeBoundedMessage(raw, { bytes: server.limit.message, depth: server.limit.depth })\n * ```\n */\nexport function decodeBoundedMessage(\n\tmessage: string,\n\tlimits: MCPJSONLimitOptions,\n): JSONRPCMessage | undefined {\n\tif (!isBoundedString(message, limits.bytes)) return undefined\n\tconst parsed = attempt<unknown>(() => JSON.parse(message))\n\treturn parsed.success ? parseJSONRPCMessage(parsed.value, limits) : undefined\n}\n\n/**\n * Read the request id an inbound `notifications/cancelled` names — the inverse of\n * {@link buildCancelledNotification}.\n *\n * @remarks\n * `requestId` is the WIRE SPELLING carried verbatim from the dated schema, and it must be a\n * real {@link JSONRPCId}: `null` is not one, and neither is an absent member, so a\n * malformed frame reads as \"cancels nothing\" rather than as an error. Anything that is not a\n * `notifications/cancelled` notification — a response, a request that happens to use the\n * method name, another notification — reads the same way. Total (§14).\n *\n * @param message - The decoded inbound message to read\n * @returns The id of the request being cancelled, or `undefined` when the message cancels nothing\n *\n * @example\n * ```ts\n * readCancelledId(buildCancelledNotification(7)) // → 7\n * ```\n */\nexport function readCancelledId(message: JSONRPCMessage): JSONRPCId | undefined {\n\tif (!isJSONRPCNotification(message) || message.method !== 'notifications/cancelled') {\n\t\treturn undefined\n\t}\n\tconst requested = message.params?.['requestId']\n\treturn isJSONRPCId(requested) ? requested : undefined\n}\n\n// The held-open stream leaf: the pump that writes a serialized exchange onto a transport. It\n// consumes the stream MANUALLY rather than with `for await`, because `for await` discards the\n// `return` value and the terminating response IS that value.\n\n/**\n * Pump a controlled serialized exchange onto a transport — every notification in order, then\n * the terminating response — and END the exchange however the pump leaves.\n *\n * @remarks\n * The generator's `return` value is a message like any other on the wire: it is sent\n * LAST and closes the exchange. Sends are awaited one at a time so the transport\n * receives the sequence in the order the method produced it.\n *\n * The first parameter is the CONTROLLED arm rather than a bare\n * {@link import('./types.js').MCPTextStream}, and that is the whole point of it: this pump is\n * an owner, and an owner needs a lifecycle member to discharge its obligation with. A bare\n * generator has none, so an exit where nothing was cancelled — a `send` that threw two\n * messages in, a transport that closed underneath the loop — would leave the producer, the\n * request lifetime, and any live server slot behind it held with no signal to release them.\n * The `finally` here is that release, it runs on every exit including the normal one, and it\n * is a no-op for an exchange that already ended on its terminal.\n *\n * The `finally` is spelled explicitly rather than with `await using` because this package's\n * declared Node floor cannot PARSE `await using` — `target: ESNext` emits the declaration\n * verbatim, and a floor engine rejects the whole module at load. The obligation discharged is\n * identical either way.\n *\n * @param stream - The controlled serialized held-open result to write out and then end\n * @param transport - The duplex channel to write each message to\n * @returns Resolves once the terminating response has been sent and the exchange has ended\n *\n * @example\n * ```ts\n * const answer = await server.handle(message)\n * if (typeof answer !== 'string' && answer !== undefined) await sendStream(answer, transport)\n * ```\n */\nexport async function sendStream(\n\tstream: MCPTextStreamControllerInterface,\n\ttransport: MCPTransportInterface,\n): Promise<void> {\n\ttry {\n\t\tlet next = await stream.next()\n\t\twhile (!next.done) {\n\t\t\tawait transport.send(next.value)\n\t\t\tnext = await stream.next()\n\t\t}\n\t\tawait transport.send(next.value)\n\t} finally {\n\t\tawait stream[Symbol.asyncDispose]()\n\t}\n}\n\n// The environment-agnostic PORT binders — the keystone that lets an\n// {@link MCPDispatcherInterface} / {@link MCPClientInterface} run over ANY\n// {@link MCPTransportInterface} (a Node stdio pair, a browser MessagePort, a Web\n// Worker `self`) with no per-environment dispatch/correlation wiring duplicated at\n// each face. Both are TOTAL: a `send` throw or rejection is caught and never\n// escapes as an unhandled rejection.\n\n/**\n * Pipe an {@link MCPTransportInterface} into an {@link MCPDispatcherInterface} — every\n * inbound message runs through `server.handle`, and a defined reply is written back\n * via `transport.send`.\n *\n * @remarks\n * `server.handle` already turns a malformed message into a serialized `-32700` /\n * `-32600` reply and a notification into `undefined` (no reply), so this binder parses\n * nothing the server would parse differently: it decodes each inbound message through\n * {@link decodeBoundedMessage} under `server.limit`, the SERVER'S OWN bound, so a message\n * the server would refuse is never parsed here either and still receives its `-32700` from\n * the one place that words it. A HELD-OPEN reply arrives as an\n * {@link import('./types.js').MCPTextStreamControllerInterface} instead of a string: this is\n * the one place that pumps it, writing each notification in order and then the generator's\n * returned terminating response ({@link sendStream}). A `transport.send` throw or rejection —\n * mid-stream included — is caught and routed\n * to `server.emitter`'s `error` event (never rethrown, never an unhandled rejection);\n * a listener on that event that itself throws is swallowed (the end of the line —\n * the caller's own bug, never this binder's). A fault raised AFTER its own request was\n * cancelled reports nothing, because a cancellation is not a fault.\n *\n * **This binder OWNS every exchange it starts, and ends each one on every exit.** It holds one\n * `AbortController` per live request, keyed by the request's id and deleted whenever that\n * request leaves — normally, by a throw, or by cancellation — and it supplies that signal to\n * `handle` as {@link import('./types.js').MCPDispatchOptions}. Three consequences follow.\n * An inbound `notifications/cancelled` ABORTS the request it names, which is how the message-\n * based cancellation path reaches a tool on the carriers that have one (stdio, WebSocket,\n * `MessagePort`); a cancelled request writes NO response, because a peer that asked for a call\n * to stop is not answered by it; and the transport's `closed` signal aborts every request\n * still in flight, so an exchange being pumped when the carrier dies ends with it instead of\n * writing into a socket nobody is holding.\n *\n * `listen`/`closed` are REPLACE semantics (§ port contract): the returned unbind\n * DETACHES by replacing this binder's own handlers with no-ops, so a subsequent\n * `bindServer` call on the SAME transport is never double-dispatched by a stale\n * subscription left behind — an unbind→rebind cycle yields exactly one reply per\n * request. Unbinding is itself an owner exit: it aborts and retires every request still in\n * flight before detaching, so `unbind()` then `close()` and `close()` then `unbind()` end the\n * same exchanges. It does NOT close the transport; that remains the caller's decision.\n *\n * @param server - The transport-agnostic server to dispatch inbound messages over\n * @param transport - The duplex channel to pipe the server over\n * @returns Detach this binder from the transport (does not close it)\n *\n * @example\n * ```ts\n * const unbind = bindServer(server, transport)\n * // ... later, detach without closing:\n * unbind()\n * ```\n */\nexport function bindServer(\n\tserver: MCPDispatcherInterface,\n\ttransport: MCPTransportInterface,\n): () => void {\n\tlet active = true\n\t// The per-live-request registry. It lives HERE rather than on the method registry because\n\t// the controller a cancellation must reach is created per dispatch and published to no\n\t// member — the binder is the one place that both mints the request's lifetime and sees the\n\t// next inbound frame, so it is the only place the two can meet.\n\tconst live = new Map<JSONRPCId, AbortController>()\n\ttransport.listen(async (message) => {\n\t\tif (!active) return\n\t\tconst decoded = decodeBoundedMessage(message, {\n\t\t\tbytes: server.limit.message,\n\t\t\tdepth: server.limit.depth,\n\t\t})\n\t\tconst cancelled = decoded === undefined ? undefined : readCancelledId(decoded)\n\t\tif (cancelled !== undefined) {\n\t\t\tlive.get(cancelled)?.abort()\n\t\t\treturn\n\t\t}\n\t\tconst id = decoded === undefined || !('method' in decoded) ? undefined : decoded.id\n\t\tconst request = new AbortController()\n\t\tif (id !== undefined) live.set(id, request)\n\t\ttry {\n\t\t\tconst answer = await server.handle(message, { signal: request.signal })\n\t\t\tif (answer === undefined) return\n\t\t\t// A cancelled request writes nothing — and a held-open answer is RELEASED rather\n\t\t\t// than dropped, because dropping one is exactly the abandonment this binder owns.\n\t\t\tif (typeof answer === 'string') {\n\t\t\t\tif (!request.signal.aborted) await transport.send(answer)\n\t\t\t} else if (request.signal.aborted) await answer[Symbol.asyncDispose]()\n\t\t\telse await sendStream(answer, transport)\n\t\t} catch (error) {\n\t\t\t// A cancellation is not a fault. Once this request has been aborted, whatever the\n\t\t\t// pump raises IS the abort arriving, and reporting it as a contained fault would\n\t\t\t// put an operator's `error` feed one entry behind every peer that cancels.\n\t\t\tif (!request.signal.aborted) {\n\t\t\t\ttry {\n\t\t\t\t\tserver.emitter.emit('error', error)\n\t\t\t\t} catch {\n\t\t\t\t\t// A throwing `error` listener is the caller's own bug — the end of the line.\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\t// Only ever retire OUR OWN entry: a peer reusing a live id would otherwise have the\n\t\t\t// first request's exit delete the second request's controller and silence its cancel.\n\t\t\tif (id !== undefined && live.get(id) === request) live.delete(id)\n\t\t}\n\t})\n\ttransport.closed(() => {\n\t\tactive = false\n\t\tfor (const pending of live.values()) pending.abort()\n\t\tlive.clear()\n\t})\n\treturn () => {\n\t\tactive = false\n\t\tfor (const pending of live.values()) pending.abort()\n\t\tlive.clear()\n\t\ttransport.listen(() => {})\n\t\ttransport.closed(() => {})\n\t}\n}\n\n/**\n * Pipe an {@link MCPTransportInterface} into an {@link MCPClientInterface} — every\n * inbound message is decoded and delivered onto the client's OWN transport\n * (`client.transport.emitter`'s `message` / `close` events), resolving/rejecting the\n * client's correlated pending requests exactly as a direct reply would.\n *\n * @remarks\n * The client's outbound writes flow through `client.transport.send` — its existing,\n * unmodified request/response correlation — so `client` must have been constructed\n * with a {@link import('./types.js').MCPClientTransportInterface} that itself carries\n * the SAME `transport` (see {@link import('./factories.js').createDuplexClientTransport},\n * the additive factory that adapts an {@link MCPTransportInterface} into that shape);\n * this binder then completes the inbound half by decoding each message and pushing it\n * onto `client.transport.emitter` (an {@link import('@orkestrel/emitter').EmitterInterface}\n * exposes `emit`, so no client modification is needed). A malformed / non-JSON-RPC\n * inbound message is DROPPED (§14, total — never throws); a delivery fault is routed to\n * `client.transport.emitter`'s `error` event (never rethrown). The returned unbind\n * DETACHES this binder (further inbound messages and the transport's `closed` signal are\n * ignored) WITHOUT closing the transport.\n *\n * `listen`/`closed` are REPLACE semantics (§ port contract): the returned unbind\n * DETACHES by replacing this binder's own handlers with no-ops, so a subsequent\n * `bindClient` call on the SAME transport is never double-dispatched by a stale\n * subscription left behind — an unbind→rebind cycle delivers exactly one `message`\n * emit per inbound reply.\n *\n * **This binder needs no live-request registry, and the asymmetry with {@link bindServer} is\n * real rather than an omission.** A server binder holds the lifetime of work it STARTED, so an\n * inbound `notifications/cancelled` has something to reach; a client binder starts no work —\n * `MCPClient` already owns its pending entries and already writes the cancellation frame\n * itself when a caller's `signal` aborts, on a carrier declaring `duplex`. Adding a registry\n * here would be a second correlation table for ids the client is already correlating, and two\n * tables for one fact drift. The one obligation this binder does carry is delivery: a\n * malformed / non-JSON-RPC inbound message is DROPPED (§14, total — never throws).\n *\n * @param client - The transport-agnostic client whose transport to deliver messages onto\n * @param transport - The duplex channel to pipe the client over\n * @returns Detach this binder from the transport (does not close it)\n *\n * @example\n * ```ts\n * const client = createMCPClient({ transport: createDuplexClientTransport(transport) })\n * const unbind = bindClient(client, transport)\n * await client.connect()\n * // ... later, detach without closing:\n * unbind()\n * ```\n */\nexport function bindClient(\n\tclient: MCPClientInterface,\n\ttransport: MCPTransportInterface,\n): () => void {\n\tlet active = true\n\ttransport.listen((message) => {\n\t\tif (!active) return\n\t\tlet parsed: unknown\n\t\ttry {\n\t\t\tparsed = JSON.parse(message)\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\t\tconst decoded = parseJSONRPCMessage(parsed)\n\t\tif (decoded === undefined) return\n\t\ttry {\n\t\t\tclient.transport.emitter.emit('message', decoded)\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tclient.transport.emitter.emit('error', error)\n\t\t\t} catch {\n\t\t\t\t// A throwing `error` listener is the caller's own bug — the end of the line.\n\t\t\t}\n\t\t}\n\t})\n\ttransport.closed(() => {\n\t\tif (!active) return\n\t\tactive = false\n\t\ttry {\n\t\t\tclient.transport.emitter.emit('close')\n\t\t} catch {\n\t\t\t// A throwing `close` listener is the caller's own bug — the end of the line.\n\t\t}\n\t})\n\treturn () => {\n\t\tactive = false\n\t\ttransport.listen(() => {})\n\t\ttransport.closed(() => {})\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type {\n\tJSONRPCError,\n\tJSONRPCErrorResponse,\n\tJSONRPCId,\n\tJSONRPCInvocation,\n\tJSONRPCMessage,\n\tJSONRPCNotification,\n\tJSONRPCRequest,\n\tJSONRPCResponse,\n\tJSONRPCResultResponse,\n\tMCPAnnotations,\n\tMCPBlobResource,\n\tMCPCallResult,\n\tMCPClientCapabilities,\n\tMCPCompletion,\n\tMCPCompletionParams,\n\tMCPCompletionReference,\n\tMCPCompletionResult,\n\tMCPContent,\n\tMCPElicitFieldSchema,\n\tMCPElicitForm,\n\tMCPElicitRequest,\n\tMCPElicitResult,\n\tMCPElicitSchema,\n\tMCPElicitURL,\n\tMCPElicitValue,\n\tMCPIcon,\n\tMCPIdentity,\n\tMCPInputRequest,\n\tMCPInputRequestMap,\n\tMCPInputResult,\n\tMCPJSONLimitOptions,\n\tMCPLegacyResult,\n\tMCPLoggingLevel,\n\tMCPMetaObject,\n\tMCPProgress,\n\tMCPPaginationParams,\n\tMCPPrompt,\n\tMCPPromptArgument,\n\tMCPPromptGetResult,\n\tMCPPromptMessage,\n\tMCPPromptPage,\n\tMCPResource,\n\tMCPResourceContents,\n\tMCPResourcePage,\n\tMCPResourceTemplate,\n\tMCPResourceTemplatePage,\n\tMCPResult,\n\tMCPResultMetaObject,\n\tMCPServerCapabilities,\n\tMCPSubscriptionFilter,\n\tMCPTaskDetail,\n\tMCPTaskResult,\n\tMCPTaskStatus,\n\tMCPTextResource,\n\tMCPVersion,\n} from './types.js'\nimport {\n\tarrayOf,\n\tattempt,\n\tcloneJSONRecord,\n\tisBoolean,\n\tisFiniteNumber,\n\tisInteger,\n\tisRecord,\n\tisString,\n\tisUndefined,\n} from '@orkestrel/contract'\nimport {\n\tMCP_EXTENSION_TASKS,\n\tMCP_META_SERVER,\n\tMCP_META_VERSION,\n\tSUPPORTED_PROTOCOL_VERSIONS,\n} from './constants.js'\nimport { serializeJSON } from './helpers.js'\n\n/** Determine whether a value is an exact finite JSON object. */\nexport function isJSONObject(value: unknown): value is Readonly<Record<string, JSONValue>> {\n\treturn attempt(() => cloneJSONRecord(value)).success\n}\n\n/** Determine whether a string follows the dated MCP `_meta` key grammar. */\nexport function isMCPMetaKey(value: unknown): value is string {\n\tif (!isString(value)) return false\n\tconst slash = value.indexOf('/')\n\tif (slash !== value.lastIndexOf('/')) return false\n\tconst name = slash < 0 ? value : value.slice(slash + 1)\n\tif (slash >= 0) {\n\t\tconst prefix = value.slice(0, slash)\n\t\tif (prefix.length === 0) return false\n\t\tfor (const label of prefix.split('.')) {\n\t\t\tif (!/^[A-Za-z](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(label)) return false\n\t\t}\n\t}\n\treturn name.length === 0 || /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(name)\n}\n\n/** Determine whether a value is exact finite MCP metadata with valid keys. */\nexport function isMCPMetaObject(value: unknown): value is MCPMetaObject {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\treturn owned.success && Object.keys(owned.value).every((key) => isMCPMetaKey(key))\n}\n\n/** Determine whether a value is exact result metadata with a valid reserved server identity. */\nexport function isMCPResultMetaObject(value: unknown): value is MCPResultMetaObject {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success || !Object.keys(owned.value).every((key) => isMCPMetaKey(key))) return false\n\tconst identity = owned.value[MCP_META_SERVER]\n\treturn isUndefined(identity) || isMCPIdentity(identity)\n}\n\n/** Determine whether a value is one dated MCP logging level. */\nexport function isMCPLoggingLevel(value: unknown): value is MCPLoggingLevel {\n\treturn (\n\t\tvalue === 'debug' ||\n\t\tvalue === 'info' ||\n\t\tvalue === 'notice' ||\n\t\tvalue === 'warning' ||\n\t\tvalue === 'error' ||\n\t\tvalue === 'critical' ||\n\t\tvalue === 'alert' ||\n\t\tvalue === 'emergency'\n\t)\n}\n\n/**\n * Determine whether a value is standard padded base64 as required by JSON Schema `byte` format.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is an empty or completely padded standard base64 encoding\n */\nexport function isStandardBase64(value: unknown): value is string {\n\treturn (\n\t\tisString(value) &&\n\t\t/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)\n\t)\n}\n\n/**\n * Determine whether a value is one absolute URI under RFC 3986 syntax.\n *\n * @remarks\n * This host-neutral syntax guard does not resolve, normalize, decode, fetch, or apply a\n * scheme allowlist. Component scanning is bounded by the input length.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is an RFC 3986 URI rather than a relative reference\n */\nexport function isAbsoluteURI(value: unknown): value is string {\n\tif (!isString(value) || value.length === 0) return false\n\tconst separator = value.indexOf(':')\n\tif (separator <= 0 || !/^[A-Za-z][A-Za-z0-9+.-]*$/.test(value.slice(0, separator))) {\n\t\treturn false\n\t}\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst code = value.charCodeAt(index)\n\t\tif (code <= 0x20 || code >= 0x7f) return false\n\t\tif (value[index] === '%') {\n\t\t\tconst escape = value.slice(index + 1, index + 3)\n\t\t\tif (escape.length !== 2 || !/^[0-9A-Fa-f]{2}$/.test(escape)) return false\n\t\t\tindex += 2\n\t\t}\n\t}\n\tif (!/^[A-Za-z0-9\\-._~:/?#[\\]@!$&'()*+,;=%]*$/.test(value)) return false\n\n\tconst fragmentIndex = value.indexOf('#', separator + 1)\n\tif (fragmentIndex >= 0 && fragmentIndex !== value.lastIndexOf('#')) return false\n\tconst beforeFragment = fragmentIndex < 0 ? value : value.slice(0, fragmentIndex)\n\tconst fragment = fragmentIndex < 0 ? undefined : value.slice(fragmentIndex + 1)\n\tconst queryIndex = beforeFragment.indexOf('?', separator + 1)\n\tconst beforeQuery = queryIndex < 0 ? beforeFragment : beforeFragment.slice(0, queryIndex)\n\tconst query = queryIndex < 0 ? undefined : beforeFragment.slice(queryIndex + 1)\n\tconst hierarchy = beforeQuery.slice(separator + 1)\n\tfor (const component of [query, fragment]) {\n\t\tif (component !== undefined && !/^[A-Za-z0-9\\-._~!$&'()*+,;=:@/?%]*$/.test(component)) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (!hierarchy.startsWith('//')) {\n\t\treturn /^[A-Za-z0-9\\-._~!$&'()*+,;=:@/%]*$/.test(hierarchy)\n\t}\n\n\tconst authorityEnd = hierarchy.indexOf('/', 2)\n\tconst authority = authorityEnd < 0 ? hierarchy.slice(2) : hierarchy.slice(2, authorityEnd)\n\tconst path = authorityEnd < 0 ? '' : hierarchy.slice(authorityEnd)\n\tif (!/^[A-Za-z0-9\\-._~!$&'()*+,;=:@/%]*$/.test(path)) return false\n\tconst at = authority.lastIndexOf('@')\n\tif (at !== authority.indexOf('@')) return false\n\tconst userinfo = at < 0 ? undefined : authority.slice(0, at)\n\tconst hostport = at < 0 ? authority : authority.slice(at + 1)\n\tif (userinfo !== undefined && !/^[A-Za-z0-9\\-._~!$&'()*+,;=:%]*$/.test(userinfo)) {\n\t\treturn false\n\t}\n\n\tif (hostport.startsWith('[')) {\n\t\tconst close = hostport.indexOf(']')\n\t\tif (close < 0) return false\n\t\tconst literal = hostport.slice(1, close)\n\t\tconst remainder = hostport.slice(close + 1)\n\t\tif (remainder.length > 0 && !/^:[0-9]*$/.test(remainder)) return false\n\t\tif (/^[vV][0-9A-Fa-f]+\\.[A-Za-z0-9\\-._~!$&'()*+,;=:]+$/.test(literal)) return true\n\t\tif (literal.includes('%') || literal.includes('[') || literal.includes(']')) return false\n\t\tconst elision = literal.indexOf('::')\n\t\tif (elision !== literal.lastIndexOf('::')) return false\n\t\tconst compressed = elision >= 0\n\t\tlet groups: string[]\n\t\tif (compressed) {\n\t\t\tconst left = literal.slice(0, elision)\n\t\t\tconst right = literal.slice(elision + 2)\n\t\t\tif (\n\t\t\t\t(left.length > 0 && (left.startsWith(':') || left.endsWith(':'))) ||\n\t\t\t\t(right.length > 0 && (right.startsWith(':') || right.endsWith(':')))\n\t\t\t)\n\t\t\t\treturn false\n\t\t\tgroups = [\n\t\t\t\t...(left.length === 0 ? [] : left.split(':')),\n\t\t\t\t...(right.length === 0 ? [] : right.split(':')),\n\t\t\t]\n\t\t} else {\n\t\t\tif (literal.startsWith(':') || literal.endsWith(':')) return false\n\t\t\tgroups = literal.split(':')\n\t\t}\n\t\tlet units = 0\n\t\tfor (let index = 0; index < groups.length; index += 1) {\n\t\t\tconst group = groups[index]\n\t\t\tif (group === undefined || group.length === 0) return false\n\t\t\tif (group.includes('.')) {\n\t\t\t\tif (index !== groups.length - 1) return false\n\t\t\t\tconst octets = group.split('.')\n\t\t\t\tif (octets.length !== 4) return false\n\t\t\t\tfor (const octet of octets) {\n\t\t\t\t\tif (!/^(?:0|[1-9][0-9]{0,2})$/.test(octet) || Number(octet) > 255) return false\n\t\t\t\t}\n\t\t\t\tunits += 2\n\t\t\t} else {\n\t\t\t\tif (!/^[0-9A-Fa-f]{1,4}$/.test(group)) return false\n\t\t\t\tunits += 1\n\t\t\t}\n\t\t}\n\t\treturn compressed ? units < 8 : units === 8\n\t}\n\n\tif (hostport.includes('[') || hostport.includes(']')) return false\n\tconst colon = hostport.lastIndexOf(':')\n\tif (colon !== hostport.indexOf(':')) return false\n\tconst host = colon < 0 ? hostport : hostport.slice(0, colon)\n\tconst port = colon < 0 ? undefined : hostport.slice(colon + 1)\n\tif (port !== undefined && !/^[0-9]*$/.test(port)) return false\n\treturn /^[A-Za-z0-9\\-._~!$&'()*+,;=%]*$/.test(host)\n}\n\n/**\n * Determine whether a value is one RFC 3339 `full-date` naming a real calendar day.\n *\n * @remarks\n * RFC 3339 §5.6 defines `date-mday` as `01-28`, `29`, `30`, or `31` BASED ON the month and\n * year, so the grammar is not satisfied by shape alone: `2026-02-30` and `2025-02-29` are\n * well-formed triples that name no day, and a downstream `new Date` rolls each of them\n * silently onto a different date rather than refusing it. February's length follows the\n * Gregorian leap rule — every fourth year except centuries that are not multiples of 400.\n *\n * The check is pure integer arithmetic on the matched fields and never constructs a `Date`,\n * because `Date` is exactly the component that performs the rollover this guard exists to\n * refuse. It is a SYNTAX guard: no time zone, locale, calendar era, or leap second applies.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is an RFC 3339 `full-date` for a day that exists\n *\n * @example\n * ```ts\n * isRFC3339Date('2026-02-28') // true\n * isRFC3339Date('2026-02-30') // false — February never has 30 days\n * isRFC3339Date('2024-02-29') // true — 2024 is a leap year\n * ```\n */\nexport function isRFC3339Date(value: unknown): value is string {\n\tif (!isString(value)) return false\n\tconst matched = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(value)\n\tif (matched === null) return false\n\tconst year = Number(matched[1])\n\tconst month = Number(matched[2])\n\tconst day = Number(matched[3])\n\tif (month < 1 || month > 12 || day < 1) return false\n\tif (month === 2) {\n\t\treturn day <= ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28)\n\t}\n\treturn day <= (month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31)\n}\n\n/**\n * Determine whether a value is one RFC 3339 `date-time` naming a real calendar day.\n *\n * @remarks\n * The `full-date` half is {@link isRFC3339Date}, so an impossible day is refused here for\n * the same reason it is refused there. The `full-time` half requires the literal `T`\n * separator (or its lowercase form), two-digit hour/minute/second, an optional fractional\n * second, and a mandatory offset — `Z` or `±HH:MM`. A space separator, a missing offset, and\n * a bare date all remain refused: RFC 3339 permits the space only by prior agreement, and\n * this package has none. Second `60` is admitted, because the grammar reserves it for a leap\n * second.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is an RFC 3339 `date-time` for a day that exists\n *\n * @example\n * ```ts\n * isRFC3339DateTime('2026-08-07T12:30:00Z') // true\n * isRFC3339DateTime('2026-02-30T00:00:00Z') // false — February never has 30 days\n * isRFC3339DateTime('2026-08-07 12:30:00Z') // false — the separator must be `T`\n * ```\n */\nexport function isRFC3339DateTime(value: unknown): value is string {\n\tif (!isString(value)) return false\n\tconst matched =\n\t\t/^(\\d{4}-\\d{2}-\\d{2})[Tt](?:[01]\\d|2[0-3]):[0-5]\\d:(?:[0-5]\\d|60)(?:\\.\\d+)?(?:[Zz]|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)$/.exec(\n\t\t\tvalue,\n\t\t)\n\treturn matched !== null && isRFC3339Date(matched[1])\n}\n\n/**\n * Determine whether a value is one exact finite MCP progress payload.\n *\n * @param value - The unknown value to inspect\n * @returns Whether required progress and optional total/message fields match the dated schema\n */\nexport function isMCPProgress(value: unknown): value is MCPProgress {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst progress = owned.value\n\t\tif (!isFiniteNumber(progress['progress'])) return false\n\t\tconst total = progress['total']\n\t\tconst message = progress['message']\n\t\treturn (\n\t\t\t(isUndefined(total) || isFiniteNumber(total)) && (isUndefined(message) || isString(message))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value carries valid dated-schema MCP content annotations.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is valid MCP annotations\n */\nexport function isMCPAnnotations(value: unknown): value is MCPAnnotations {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst annotations = owned.value\n\t\tconst audience = annotations['audience']\n\t\tconst priority = annotations['priority']\n\t\tconst lastModified = annotations['lastModified']\n\t\tif (\n\t\t\t!isUndefined(audience) &&\n\t\t\t(!Array.isArray(audience) ||\n\t\t\t\t!audience.every((role) => role === 'user' || role === 'assistant'))\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (!isUndefined(priority) && (!isFiniteNumber(priority) || priority < 0 || priority > 1)) {\n\t\t\treturn false\n\t\t}\n\t\treturn isUndefined(lastModified) || isString(lastModified)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one exact dated-schema MCP icon.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is a valid MCP icon\n */\nexport function isMCPIcon(value: unknown): value is MCPIcon {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst icon = owned.value\n\t\tif (!isAbsoluteURI(icon['src'])) return false\n\t\tconst mimeType = icon['mimeType']\n\t\tconst sizes = icon['sizes']\n\t\tconst theme = icon['theme']\n\t\treturn (\n\t\t\t(isUndefined(mimeType) || isString(mimeType)) &&\n\t\t\t(isUndefined(sizes) || (Array.isArray(sizes) && sizes.every((size) => isString(size)))) &&\n\t\t\t(isUndefined(theme) || theme === 'light' || theme === 'dark')\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/** Determine whether a value is one complete dated MCP implementation identity. */\nexport function isMCPIdentity(value: unknown): value is MCPIdentity {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst identity = owned.value\n\t\tif (!isString(identity['name']) || !isString(identity['version'])) {\n\t\t\treturn false\n\t\t}\n\t\tconst title = identity['title']\n\t\tconst description = identity['description']\n\t\tconst website = identity['websiteUrl']\n\t\tconst icons = identity['icons']\n\t\treturn (\n\t\t\t(isUndefined(title) || isString(title)) &&\n\t\t\t(isUndefined(description) || isString(description)) &&\n\t\t\t(isUndefined(website) || isAbsoluteURI(website)) &&\n\t\t\t(isUndefined(icons) || (Array.isArray(icons) && icons.every((icon) => isMCPIcon(icon))))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/** Determine whether a value is one exact open dated client-capability declaration. */\nexport function isMCPClientCapabilities(value: unknown): value is MCPClientCapabilities {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst capabilities = owned.value\n\t\tfor (const capability of Object.values(capabilities)) {\n\t\t\tif (!isJSONObject(capability)) return false\n\t\t}\n\t\tconst experimental = capabilities['experimental']\n\t\tif (\n\t\t\t!isUndefined(experimental) &&\n\t\t\t(!isJSONObject(experimental) ||\n\t\t\t\t!Object.values(experimental).every((entry) => isJSONObject(entry)))\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tconst sampling = capabilities['sampling']\n\t\tif (\n\t\t\t!isUndefined(sampling) &&\n\t\t\t(!isJSONObject(sampling) ||\n\t\t\t\t(!isUndefined(sampling['context']) && !isJSONObject(sampling['context'])) ||\n\t\t\t\t(!isUndefined(sampling['tools']) && !isJSONObject(sampling['tools'])))\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tconst elicitation = capabilities['elicitation']\n\t\tif (!isUndefined(elicitation)) {\n\t\t\tif (!isJSONObject(elicitation)) return false\n\t\t\tconst form = elicitation['form']\n\t\t\tconst url = elicitation['url']\n\t\t\tif (!isUndefined(form) && !isJSONObject(form)) return false\n\t\t\tif (!isUndefined(url) && !isJSONObject(url)) return false\n\t\t\tif (Object.keys(elicitation).length > 0 && isUndefined(form) && isUndefined(url)) return false\n\t\t}\n\t\tconst extensions = capabilities['extensions']\n\t\tif (!isUndefined(extensions)) {\n\t\t\tif (!isJSONObject(extensions)) return false\n\t\t\tfor (const [key, extension] of Object.entries(extensions)) {\n\t\t\t\tif (!key.includes('/') || !isMCPMetaKey(key) || !isJSONObject(extension)) return false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/** Determine whether a value is one exact open dated server-capability declaration. */\nexport function isMCPServerCapabilities(value: unknown): value is MCPServerCapabilities {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst capabilities = owned.value\n\t\tfor (const capability of Object.values(capabilities)) {\n\t\t\tif (!isJSONObject(capability)) return false\n\t\t}\n\t\tconst experimental = capabilities['experimental']\n\t\tif (\n\t\t\t!isUndefined(experimental) &&\n\t\t\t(!isJSONObject(experimental) ||\n\t\t\t\t!Object.values(experimental).every((entry) => isJSONObject(entry)))\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tfor (const name of ['prompts', 'tools']) {\n\t\t\tconst capability = capabilities[name]\n\t\t\tif (\n\t\t\t\t!isUndefined(capability) &&\n\t\t\t\t(!isJSONObject(capability) ||\n\t\t\t\t\t(!isUndefined(capability['listChanged']) && !isBoolean(capability['listChanged'])))\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tconst resources = capabilities['resources']\n\t\tif (\n\t\t\t!isUndefined(resources) &&\n\t\t\t(!isJSONObject(resources) ||\n\t\t\t\t(!isUndefined(resources['subscribe']) && !isBoolean(resources['subscribe'])) ||\n\t\t\t\t(!isUndefined(resources['listChanged']) && !isBoolean(resources['listChanged'])))\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tconst extensions = capabilities['extensions']\n\t\tif (!isUndefined(extensions)) {\n\t\t\tif (!isJSONObject(extensions)) return false\n\t\t\tfor (const [key, extension] of Object.entries(extensions)) {\n\t\t\t\tif (!key.includes('/') || !isMCPMetaKey(key) || !isJSONObject(extension)) return false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is embedded textual MCP resource contents.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is embedded textual resource contents\n */\nexport function isMCPTextResource(value: unknown): value is MCPTextResource {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst resource = owned.value\n\t\tif (!isAbsoluteURI(resource['uri']) || !isString(resource['text'])) {\n\t\t\treturn false\n\t\t}\n\t\tconst mimeType = resource['mimeType']\n\t\tconst metadata = resource['_meta']\n\t\treturn (\n\t\t\t(isUndefined(mimeType) || isString(mimeType)) &&\n\t\t\t(isUndefined(metadata) || isMCPMetaObject(metadata))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is embedded blob MCP resource contents.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is embedded blob resource contents\n */\nexport function isMCPBlobResource(value: unknown): value is MCPBlobResource {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst resource = owned.value\n\t\tif (!isAbsoluteURI(resource['uri']) || !isStandardBase64(resource['blob'])) {\n\t\t\treturn false\n\t\t}\n\t\tconst mimeType = resource['mimeType']\n\t\tconst metadata = resource['_meta']\n\t\treturn (\n\t\t\t(isUndefined(mimeType) || isString(mimeType)) &&\n\t\t\t(isUndefined(metadata) || isMCPMetaObject(metadata))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one `resources/list` descriptor.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is a valid resource descriptor\n */\nexport function isMCPResource(value: unknown): value is MCPResource {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst resource = owned.value\n\t\tconst icons = resource['icons']\n\t\tconst size = resource['size']\n\t\treturn (\n\t\t\tisAbsoluteURI(resource['uri']) &&\n\t\t\tisString(resource['name']) &&\n\t\t\t(isUndefined(resource['title']) || isString(resource['title'])) &&\n\t\t\t(isUndefined(resource['description']) || isString(resource['description'])) &&\n\t\t\t(isUndefined(resource['mimeType']) || isString(resource['mimeType'])) &&\n\t\t\t(isUndefined(resource['annotations']) || isMCPAnnotations(resource['annotations'])) &&\n\t\t\t(isUndefined(size) || (isInteger(size) && size >= 0)) &&\n\t\t\t(isUndefined(icons) || (Array.isArray(icons) && icons.every((icon) => isMCPIcon(icon)))) &&\n\t\t\t(isUndefined(resource['_meta']) || isMCPMetaObject(resource['_meta']))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one resource-template descriptor.\n *\n * @remarks\n * This guard validates the descriptor shape. Template expansion and the RFC 6570 feature\n * level belong to the consumer-supplied resource manager; this package projects the string.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is a valid resource-template descriptor\n */\nexport function isMCPResourceTemplate(value: unknown): value is MCPResourceTemplate {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst template = owned.value\n\t\tconst icons = template['icons']\n\t\treturn (\n\t\t\tisString(template['uriTemplate']) &&\n\t\t\ttemplate['uriTemplate'].length > 0 &&\n\t\t\tisString(template['name']) &&\n\t\t\t(isUndefined(template['title']) || isString(template['title'])) &&\n\t\t\t(isUndefined(template['description']) || isString(template['description'])) &&\n\t\t\t(isUndefined(template['mimeType']) || isString(template['mimeType'])) &&\n\t\t\t(isUndefined(template['annotations']) || isMCPAnnotations(template['annotations'])) &&\n\t\t\t(isUndefined(icons) || (Array.isArray(icons) && icons.every((icon) => isMCPIcon(icon)))) &&\n\t\t\t(isUndefined(template['_meta']) || isMCPMetaObject(template['_meta']))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is structurally discriminated resource contents.\n *\n * @param value - The unknown value to inspect\n * @returns Whether exactly one of `text` and `blob` is present and valid\n */\nexport function isMCPResourceContents(value: unknown): value is MCPResourceContents {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst resource = owned.value\n\tconst text = Object.hasOwn(resource, 'text')\n\tconst blob = Object.hasOwn(resource, 'blob')\n\tif (text === blob) return false\n\treturn text ? isMCPTextResource(resource) : isMCPBlobResource(resource)\n}\n\n/**\n * Determine whether a value carries the shared optional pagination cursor.\n *\n * @param value - The unknown value to inspect\n * @returns Whether a present `cursor` is a string\n */\nexport function isMCPPaginationParams(value: unknown): value is MCPPaginationParams {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\treturn owned.success && (isUndefined(owned.value['cursor']) || isString(owned.value['cursor']))\n}\n\n/**\n * Determine whether a value is one consumer-owned resource page.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the resources and optional following cursor are valid\n */\nexport function isMCPResourcePage(value: unknown): value is MCPResourcePage {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst resources = owned.value['resources']\n\tconst cursor = owned.value['nextCursor']\n\treturn (\n\t\tArray.isArray(resources) &&\n\t\tresources.every((resource) => isMCPResource(resource)) &&\n\t\t(isUndefined(cursor) || isString(cursor))\n\t)\n}\n\n/**\n * Determine whether a value is one consumer-owned resource-template page.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the templates and optional following cursor are valid\n */\nexport function isMCPResourceTemplatePage(value: unknown): value is MCPResourceTemplatePage {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst templates = owned.value['resourceTemplates']\n\tconst cursor = owned.value['nextCursor']\n\treturn (\n\t\tArray.isArray(templates) &&\n\t\ttemplates.every((template) => isMCPResourceTemplate(template)) &&\n\t\t(isUndefined(cursor) || isString(cursor))\n\t)\n}\n\n/**\n * Determine whether a value is a string-valued MCP argument record.\n *\n * @param value - The unknown value to inspect\n * @returns Whether every own argument value is a string\n */\nexport function isMCPStringArguments(value: unknown): value is Readonly<Record<string, string>> {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\treturn owned.success && Object.values(owned.value).every((argument) => isString(argument))\n}\n\n/**\n * Determine whether a value is one prompt argument descriptor.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the prompt argument descriptor is valid\n */\nexport function isMCPPromptArgument(value: unknown): value is MCPPromptArgument {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst argument = owned.value\n\treturn (\n\t\tisString(argument['name']) &&\n\t\t(isUndefined(argument['title']) || isString(argument['title'])) &&\n\t\t(isUndefined(argument['description']) || isString(argument['description'])) &&\n\t\t(isUndefined(argument['required']) || isBoolean(argument['required']))\n\t)\n}\n\n/**\n * Determine whether a value is one `prompts/list` descriptor.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the prompt descriptor is valid\n */\nexport function isMCPPrompt(value: unknown): value is MCPPrompt {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst prompt = owned.value\n\tconst argumentsValue = prompt['arguments']\n\tconst icons = prompt['icons']\n\treturn (\n\t\tisString(prompt['name']) &&\n\t\t(isUndefined(prompt['title']) || isString(prompt['title'])) &&\n\t\t(isUndefined(prompt['description']) || isString(prompt['description'])) &&\n\t\t(isUndefined(argumentsValue) ||\n\t\t\t(Array.isArray(argumentsValue) &&\n\t\t\t\targumentsValue.every((argument) => isMCPPromptArgument(argument)))) &&\n\t\t(isUndefined(icons) || (Array.isArray(icons) && icons.every((icon) => isMCPIcon(icon)))) &&\n\t\t(isUndefined(prompt['_meta']) || isMCPMetaObject(prompt['_meta']))\n\t)\n}\n\n/**\n * Determine whether a value is one prompt message with existing rich content.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the role and content are valid\n */\nexport function isMCPPromptMessage(value: unknown): value is MCPPromptMessage {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\treturn (\n\t\towned.success &&\n\t\t(owned.value['role'] === 'user' || owned.value['role'] === 'assistant') &&\n\t\tisMCPContent(owned.value['content'])\n\t)\n}\n\n/**\n * Determine whether a value is one consumer-owned prompt page.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the prompts and optional following cursor are valid\n */\nexport function isMCPPromptPage(value: unknown): value is MCPPromptPage {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst prompts = owned.value['prompts']\n\tconst cursor = owned.value['nextCursor']\n\treturn (\n\t\tArray.isArray(prompts) &&\n\t\tprompts.every((prompt) => isMCPPrompt(prompt)) &&\n\t\t(isUndefined(cursor) || isString(cursor))\n\t)\n}\n\n/**\n * Determine whether a value is one complete `prompts/get` result.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the prompt result and all messages are valid\n */\nexport function isMCPPromptGetResult(value: unknown): value is MCPPromptGetResult {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst result = owned.value\n\tconst messages = result['messages']\n\treturn (\n\t\tresult['resultType'] === 'complete' &&\n\t\t(isUndefined(result['description']) || isString(result['description'])) &&\n\t\tArray.isArray(messages) &&\n\t\tmessages.every((message) => isMCPPromptMessage(message)) &&\n\t\t(isUndefined(result['_meta']) || isMCPResultMetaObject(result['_meta']))\n\t)\n}\n\n/**\n * Determine whether a value is a prompt or resource-template completion reference.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the discriminated reference is valid\n */\nexport function isMCPCompletionReference(value: unknown): value is MCPCompletionReference {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst reference = owned.value\n\treturn reference['type'] === 'ref/prompt'\n\t\t? isString(reference['name'])\n\t\t: reference['type'] === 'ref/resource' && isString(reference['uri'])\n}\n\n/**\n * Determine whether a value is one `completion/complete` parameter object.\n *\n * @param value - The unknown value to inspect\n * @returns Whether its reference, fragment, and optional string context are valid\n */\nexport function isMCPCompletionParams(value: unknown): value is MCPCompletionParams {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst params = owned.value\n\tconst argument = attempt(() => cloneJSONRecord(params['argument']))\n\tif (!argument.success) return false\n\tconst context = params['context']\n\tif (!isUndefined(context)) {\n\t\tconst ownedContext = attempt(() => cloneJSONRecord(context))\n\t\tif (\n\t\t\t!ownedContext.success ||\n\t\t\t(!isUndefined(ownedContext.value['arguments']) &&\n\t\t\t\t!isMCPStringArguments(ownedContext.value['arguments']))\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn (\n\t\tisMCPCompletionReference(params['ref']) &&\n\t\tisString(argument.value['name']) &&\n\t\tisString(argument.value['value'])\n\t)\n}\n\n/**\n * Determine whether a value is one host-produced completion candidate set.\n *\n * @param value - The unknown value to inspect\n * @returns Whether its candidates and optional result facts are valid\n */\nexport function isMCPCompletion(value: unknown): value is MCPCompletion {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst completion = owned.value\n\tconst values = completion['values']\n\tconst total = completion['total']\n\treturn (\n\t\tArray.isArray(values) &&\n\t\tvalues.every((candidate) => isString(candidate)) &&\n\t\t(isUndefined(total) || (isInteger(total) && total >= 0)) &&\n\t\t(isUndefined(completion['hasMore']) || isBoolean(completion['hasMore']))\n\t)\n}\n\n/**\n * Determine whether a value is one complete, capped `completion/complete` result.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the result is complete and carries at most 100 candidates\n */\nexport function isMCPCompletionResult(value: unknown): value is MCPCompletionResult {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success || owned.value['resultType'] !== 'complete') return false\n\tconst completion = owned.value['completion']\n\treturn (\n\t\tisMCPCompletion(completion) &&\n\t\tcompletion.values.length <= 100 &&\n\t\t(isUndefined(owned.value['_meta']) || isMCPResultMetaObject(owned.value['_meta']))\n\t)\n}\n\n/**\n * Determine whether a value is one exact dated-schema MCP tool content block.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is valid MCP content\n */\nexport function isMCPContent(value: unknown): value is MCPContent {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst content = owned.value\n\t\tif (!isString(content['type'])) return false\n\t\tconst annotations = content['annotations']\n\t\tconst metadata = content['_meta']\n\t\tif (!isUndefined(annotations) && !isMCPAnnotations(annotations)) return false\n\t\tif (!isUndefined(metadata) && !isMCPMetaObject(metadata)) return false\n\t\tswitch (content['type']) {\n\t\t\tcase 'text':\n\t\t\t\treturn isString(content['text'])\n\t\t\tcase 'image':\n\t\t\tcase 'audio':\n\t\t\t\treturn isStandardBase64(content['data']) && isString(content['mimeType'])\n\t\t\tcase 'resource':\n\t\t\t\treturn isMCPTextResource(content['resource']) || isMCPBlobResource(content['resource'])\n\t\t\tcase 'resource_link': {\n\t\t\t\tconst icons = content['icons']\n\t\t\t\tconst size = content['size']\n\t\t\t\treturn (\n\t\t\t\t\tisString(content['name']) &&\n\t\t\t\t\tisAbsoluteURI(content['uri']) &&\n\t\t\t\t\t(isUndefined(content['title']) || isString(content['title'])) &&\n\t\t\t\t\t(isUndefined(content['description']) || isString(content['description'])) &&\n\t\t\t\t\t(isUndefined(content['mimeType']) || isString(content['mimeType'])) &&\n\t\t\t\t\t(isUndefined(icons) ||\n\t\t\t\t\t\t(Array.isArray(icons) && icons.every((icon) => isMCPIcon(icon)))) &&\n\t\t\t\t\t(isUndefined(size) || (isInteger(size) && size >= 0))\n\t\t\t\t)\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn false\n\t\t}\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one modern MCP result.\n *\n * @remarks\n * The open contract's guard: a record carrying a string `resultType` and, when\n * present, exact result metadata. It deliberately does NOT narrow `resultType` to a\n * known value, because the dated schema keeps adding them — a caller that needs a\n * specific result uses that result's own guard, which narrows to its literal.\n * Mutually exclusive with {@link isMCPLegacyResult} on every input: this one needs\n * `resultType` present and a string, that one needs it absent. Total over hostile\n * input.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is a modern result\n *\n * @example\n * ```ts\n * isMCPResult({ resultType: 'complete' }) // true\n * isMCPResult({ resultType: 'task' }) // true — a later protocol value\n * isMCPResult({ tools: [] }) // false — no discriminator, so it is a legacy result\n * ```\n */\nexport function isMCPResult(value: unknown): value is MCPResult {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst result = owned.value\n\tif (!isString(result['resultType'])) return false\n\tconst metadata = result['_meta']\n\treturn isUndefined(metadata) || isMCPResultMetaObject(metadata)\n}\n\n/**\n * Determine whether a value is one legacy-era MCP result.\n *\n * @remarks\n * The legacy revision has no result discriminator, so the absence of `resultType` is\n * the whole membership rule. Mutually exclusive with {@link isMCPResult}. Total over\n * hostile input.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is a legacy result\n *\n * @example\n * ```ts\n * isMCPLegacyResult({}) // true — the legacy `ping` result\n * isMCPLegacyResult({ resultType: 'complete' }) // false — a modern result\n * ```\n */\nexport function isMCPLegacyResult(value: unknown): value is MCPLegacyResult {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\treturn owned.success && !Object.hasOwn(owned.value, 'resultType')\n}\n\n/**\n * Determine whether a value is a complete modern MCP tool result.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is a complete MCP call result\n */\nexport function isMCPCallResult(value: unknown): value is MCPCallResult {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst result = owned.value\n\t\tif (result['resultType'] !== 'complete') return false\n\t\tconst content = result['content']\n\t\tconst error = result['isError']\n\t\tconst metadata = result['_meta']\n\t\treturn (\n\t\t\tArray.isArray(content) &&\n\t\t\tcontent.every((entry) => isMCPContent(entry)) &&\n\t\t\t(isUndefined(error) || isBoolean(error)) &&\n\t\t\t(isUndefined(metadata) || isMCPResultMetaObject(metadata))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is a modern MCP task-creation result.\n *\n * @remarks\n * The runtime enforcement of {@link MCPTaskManagerInterface.start}'s declared return\n * shape. The manager is consumer-supplied, so its types are a promise rather than a\n * proof: this is what stands between a manager that answers a numeric `taskId` and a\n * client that would receive one. `ttlMs` accepts `null` because the schema uses it to\n * mean \"no expiry\", which is distinct from an absent field.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is a well-formed `resultType: 'task'` result\n *\n * @example\n * ```ts\n * isMCPTaskResult({ resultType: 'task', taskId: 'a', status: 'working',\n * createdAt: '', lastUpdatedAt: '', ttlMs: null }) // true\n * ```\n */\nexport function isMCPTaskResult(value: unknown): value is MCPTaskResult {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst result = owned.value\n\t\tif (result['resultType'] !== 'task') return false\n\t\tconst message = result['statusMessage']\n\t\tconst interval = result['pollIntervalMs']\n\t\tconst lifetime = result['ttlMs']\n\t\tconst metadata = result['_meta']\n\t\treturn (\n\t\t\tisString(result['taskId']) &&\n\t\t\tisMCPTaskStatus(result['status']) &&\n\t\t\tisString(result['createdAt']) &&\n\t\t\tisString(result['lastUpdatedAt']) &&\n\t\t\t(lifetime === null || isFiniteNumber(lifetime)) &&\n\t\t\t(isUndefined(message) || isString(message)) &&\n\t\t\t(isUndefined(interval) || isFiniteNumber(interval)) &&\n\t\t\t(isUndefined(metadata) || isMCPResultMetaObject(metadata))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one of the extension's five task lifecycle states.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is an {@link MCPTaskStatus}\n *\n * @example\n * ```ts\n * isMCPTaskStatus('working') // true\n * isMCPTaskStatus('done') // false — not a state the extension defines\n * ```\n */\nexport function isMCPTaskStatus(value: unknown): value is MCPTaskStatus {\n\treturn (\n\t\tvalue === 'working' ||\n\t\tvalue === 'input_required' ||\n\t\tvalue === 'completed' ||\n\t\tvalue === 'failed' ||\n\t\tvalue === 'cancelled'\n\t)\n}\n\n/**\n * Determine whether a value is one durable task's full snapshot.\n *\n * @remarks\n * The runtime enforcement of {@link MCPTaskManagerInterface.task}'s declared return shape,\n * and the guard `tasks/get` proves its answer with before it reaches the wire. `status`\n * selects what else must be present, exactly as the union declares: `input_required` owns\n * the requests to answer, `completed` owns the deferred call's result, `failed` owns the\n * JSON-RPC error that ended it, and `working` / `cancelled` own nothing further.\n *\n * Unrecognized members stay valid, because the extension is DRAFT and a manager tracking a\n * later revision must not be refused by this one. What is checked is what this package\n * publishes as the contract.\n *\n * @param value - The unknown value to inspect\n * @returns Whether the value is a well-formed {@link MCPTaskDetail}\n *\n * @example\n * ```ts\n * isMCPTaskDetail({ taskId: 'a', status: 'working', createdAt: '', lastUpdatedAt: '',\n * ttlMs: null }) // true\n * isMCPTaskDetail({ taskId: 'a', status: 'completed', createdAt: '', lastUpdatedAt: '',\n * ttlMs: null }) // false — a completed task owes its result\n * ```\n */\nexport function isMCPTaskDetail(value: unknown): value is MCPTaskDetail {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst detail = owned.value\n\t\tconst status = detail['status']\n\t\tconst message = detail['statusMessage']\n\t\tconst interval = detail['pollIntervalMs']\n\t\tconst lifetime = detail['ttlMs']\n\t\tif (\n\t\t\t!isString(detail['taskId']) ||\n\t\t\t!isMCPTaskStatus(status) ||\n\t\t\t!isString(detail['createdAt']) ||\n\t\t\t!isString(detail['lastUpdatedAt']) ||\n\t\t\t(lifetime !== null && !isFiniteNumber(lifetime)) ||\n\t\t\t(!isUndefined(message) && !isString(message)) ||\n\t\t\t(!isUndefined(interval) && !isFiniteNumber(interval))\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (status === 'input_required') return isMCPInputRequestMap(detail['inputRequests'])\n\t\tif (status === 'completed') return isMCPResult(detail['result'])\n\t\tif (status === 'failed') return isJSONRPCError(detail['error'])\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n// AGENTS §14: every guard here is a TOTAL function over the already-`JSON.parse`d\n// value — adversarial input returns `false`, never throws. The raw-string\n// `JSON.parse` (which CAN throw) happens in `MCPServer.handle` inside a try/catch;\n// these guards only ever see a parsed `unknown`. Recursive structure is walked\n// iteratively with explicit ancestor/depth bounds, and callback-capable boundaries use\n// `attempt`, so totality is preserved without relying on the JavaScript call stack.\n\n/**\n * Determine whether a value is a string within a UTF-8 byte bound.\n *\n * @param value - The unknown value to inspect\n * @param bytes - The maximum accepted encoded bytes\n * @returns `true` only for a string whose UTF-8 representation fits the bound\n *\n * @example\n * ```ts\n * isBoundedString('€', 3) // true\n * isBoundedString('€', 2) // false\n * ```\n */\nexport function isBoundedString(value: unknown, bytes: number): value is string {\n\tif (!isString(value) || !Number.isFinite(bytes) || !Number.isInteger(bytes) || bytes < 0) {\n\t\treturn false\n\t}\n\tlet measured = 0\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst code = value.charCodeAt(index)\n\t\tif (code <= 0x7f) measured += 1\n\t\telse if (code <= 0x7ff) measured += 2\n\t\telse if (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = value.charCodeAt(index + 1)\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\tmeasured += 4\n\t\t\t\tindex += 1\n\t\t\t} else measured += 3\n\t\t} else measured += 3\n\t\tif (measured > bytes) return false\n\t}\n\treturn true\n}\n\n/**\n * Determine whether a value is bounded, cycle-free exact JSON.\n *\n * @remarks\n * Traversal is iterative, ancestor-aware, and contained by {@link attempt}; deep input,\n * cycles, accessors, hostile proxies, and `Map`/`Set` return `false` rather than throwing.\n * The byte count matches `JSON.stringify` without first allocating the serialization.\n *\n * @param value - The unknown value to inspect\n * @param limits - Serialized byte, optional key, and nesting-depth bounds\n * @returns `true` only for safe JSON satisfying every bound\n *\n * @example\n * ```ts\n * isBoundedJSON({ ok: true }, { bytes: 16, keys: 1, depth: 1 }) // true\n * ```\n */\nexport function isBoundedJSON<T>(value: T, limits: MCPJSONLimitOptions): value is T & JSONValue {\n\treturn serializeJSON(value, limits) !== undefined\n}\n\n/**\n * Determine whether a value is a valid JSON-RPC correlation id — a string or a\n * finite integer.\n *\n * @remarks\n * An id is present or it is not there at all: `undefined` is not an id (that\n * absence is what makes a call a notification) and `null` is not one either (MCP\n * omits an unreadable id rather than nulling it). A runtime numeric id must be a\n * finite integer; an empty string is a legal id, because the dated schema imposes\n * no minimum length. Total (§14): any other input returns `false`.\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a string or a finite integer\n *\n * @example\n * ```ts\n * isJSONRPCId(1) // true\n * isJSONRPCId('') // true — an empty string is a legal id\n * isJSONRPCId(undefined) // false — absence is not an id\n * isJSONRPCId(null) // false — MCP omits an unreadable id\n * isJSONRPCId(1.5) // false — a numeric id is an integer\n * ```\n */\nexport function isJSONRPCId(value: unknown): value is JSONRPCId {\n\treturn isString(value) || isInteger(value)\n}\n\n/**\n * Determine whether a value is a supported {@link MCPVersion}.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when the value is one of {@link SUPPORTED_PROTOCOL_VERSIONS}\n */\nexport function isMCPVersion(value: unknown): value is MCPVersion {\n\treturn isString(value) && SUPPORTED_PROTOCOL_VERSIONS.some((version) => version === value)\n}\n\n/**\n * Determine whether a value is an MCP {@link MCPSubscriptionFilter}.\n *\n * @remarks\n * Every filter field is optional. Boolean notification families accept only booleans, and\n * `resourceSubscriptions` accepts only an array of string URIs. Unknown fields remain open\n * for protocol extensions and are ignored by the built-in subscription matcher. Total over\n * hostile input.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when every recognized filter field has its protocol shape\n */\nexport function isMCPSubscriptionFilter(value: unknown): value is MCPSubscriptionFilter {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst filter = owned.value\n\tconst tools = filter['toolsListChanged']\n\tif (!isUndefined(tools) && !isBoolean(tools)) return false\n\tconst prompts = filter['promptsListChanged']\n\tif (!isUndefined(prompts) && !isBoolean(prompts)) return false\n\tconst resources = filter['resourcesListChanged']\n\tif (!isUndefined(resources) && !isBoolean(resources)) return false\n\tconst subscriptions = filter['resourceSubscriptions']\n\treturn isUndefined(subscriptions) || arrayOf(isString)(subscriptions)\n}\n\n/**\n * Determine whether a client capability record declares form-mode elicitation.\n *\n * @remarks\n * The protocol's empty `elicitation` object is the implicit form-only declaration.\n * A non-empty declaration must carry a record-valued `form` member; URL-only support\n * does not authorize a form request. Total over hostile input.\n *\n * @param value - The client capability record to inspect\n * @returns `true` when form-mode elicitation is declared\n *\n * @example\n * ```ts\n * isFormElicitationSupported({ elicitation: {} }) // true — implicit form mode\n * isFormElicitationSupported({ elicitation: { url: {} } }) // false\n * ```\n */\nexport function isFormElicitationSupported(value: unknown): boolean {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst elicitation = owned.value['elicitation']\n\t\tif (!isRecord(elicitation)) return false\n\t\tif (isRecord(elicitation['form'])) return true\n\t\treturn Object.keys(elicitation).length === 0\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a client capability record declares the draft Tasks extension.\n *\n * @remarks\n * The declaration lives at `extensions['io.modelcontextprotocol/tasks']` and its value is\n * an empty object, so this is a PRESENCE check: the extension defines no options, and a\n * server that read one would be reading a field no client can meaningfully set. The value\n * must still be a record, because that is the shape the capability record declares — a\n * `true` or a string there is a client speaking a different protocol, not a shorthand.\n *\n * A client declares this PER REQUEST. Nothing here consults a session, because the modern\n * revision is stateless and a capability declared once at connect time says nothing about\n * the request in hand. Total over hostile input.\n *\n * @param value - The client capability record to inspect\n * @returns `true` when the tasks extension is declared\n *\n * @example\n * ```ts\n * isTaskSupported({ extensions: { 'io.modelcontextprotocol/tasks': {} } }) // true\n * isTaskSupported({ extensions: {} }) // false — the key is the declaration\n * ```\n */\nexport function isTaskSupported(value: unknown): boolean {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst extensions = owned.value['extensions']\n\t\treturn isRecord(extensions) && isRecord(extensions[MCP_EXTENSION_TASKS])\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one restricted primitive form-elicitation schema.\n *\n * @param value - The unknown value to inspect\n * @returns `true` for a supported boolean, numeric, string, or string-array schema\n *\n * @example\n * ```ts\n * isMCPElicitFieldSchema({ type: 'boolean', default: true }) // true\n * isMCPElicitFieldSchema({ type: 'object' }) // false\n * ```\n */\nexport function isMCPElicitFieldSchema(value: unknown): value is MCPElicitFieldSchema {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst schema = owned.value\n\ttry {\n\t\tconst title = schema['title']\n\t\tconst description = schema['description']\n\t\tif (!isUndefined(title) && !isString(title)) return false\n\t\tif (!isUndefined(description) && !isString(description)) return false\n\n\t\tconst fallback = schema['default']\n\t\tif (schema['type'] === 'boolean') return isUndefined(fallback) || isBoolean(fallback)\n\t\tif (schema['type'] === 'number' || schema['type'] === 'integer') {\n\t\t\tconst minimum = schema['minimum']\n\t\t\tconst maximum = schema['maximum']\n\t\t\treturn (\n\t\t\t\t(isUndefined(minimum) || isFiniteNumber(minimum)) &&\n\t\t\t\t(isUndefined(maximum) || isFiniteNumber(maximum)) &&\n\t\t\t\t(isUndefined(fallback) || isFiniteNumber(fallback))\n\t\t\t)\n\t\t}\n\t\tif (schema['type'] === 'string') {\n\t\t\tconst minimum = schema['minLength']\n\t\t\tconst maximum = schema['maxLength']\n\t\t\tconst format = schema['format']\n\t\t\tconst choices = schema['enum']\n\t\t\tconst names = schema['enumNames']\n\t\t\tconst titled = schema['oneOf']\n\t\t\tif (\n\t\t\t\t(!isUndefined(minimum) && (!isInteger(minimum) || minimum < 0)) ||\n\t\t\t\t(!isUndefined(maximum) && (!isInteger(maximum) || maximum < 0)) ||\n\t\t\t\t(!isUndefined(fallback) && !isString(fallback)) ||\n\t\t\t\t(!isUndefined(format) &&\n\t\t\t\t\tformat !== 'uri' &&\n\t\t\t\t\tformat !== 'email' &&\n\t\t\t\t\tformat !== 'date' &&\n\t\t\t\t\tformat !== 'date-time')\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif (!isUndefined(choices) && (!Array.isArray(choices) || !choices.every(isString)))\n\t\t\t\treturn false\n\t\t\tif (\n\t\t\t\t!isUndefined(names) &&\n\t\t\t\t(isUndefined(choices) || !Array.isArray(names) || !names.every(isString))\n\t\t\t)\n\t\t\t\treturn false\n\t\t\treturn !(\n\t\t\t\t!isUndefined(titled) &&\n\t\t\t\t(!Array.isArray(titled) ||\n\t\t\t\t\t!titled.every(\n\t\t\t\t\t\t(choice) =>\n\t\t\t\t\t\t\tisJSONObject(choice) && isString(choice['const']) && isString(choice['title']),\n\t\t\t\t\t))\n\t\t\t)\n\t\t}\n\t\tif (schema['type'] !== 'array') return false\n\t\tconst minimum = schema['minItems']\n\t\tconst maximum = schema['maxItems']\n\t\tconst items = schema['items']\n\t\tif (\n\t\t\t(!isUndefined(minimum) && (!isInteger(minimum) || minimum < 0)) ||\n\t\t\t(!isUndefined(maximum) && (!isInteger(maximum) || maximum < 0)) ||\n\t\t\t(!isUndefined(fallback) &&\n\t\t\t\t(!Array.isArray(fallback) || !fallback.every((item) => isString(item)))) ||\n\t\t\t!isJSONObject(items)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tconst itemType = items['type']\n\t\tconst choices = items['enum']\n\t\tconst titled = items['anyOf']\n\t\tif (!isUndefined(itemType) && itemType !== 'string') return false\n\t\tif (!isUndefined(choices) && (!Array.isArray(choices) || !choices.every(isString))) return false\n\t\tif (\n\t\t\t!isUndefined(titled) &&\n\t\t\t(!Array.isArray(titled) ||\n\t\t\t\t!titled.every(\n\t\t\t\t\t(choice) =>\n\t\t\t\t\t\tisJSONObject(choice) && isString(choice['const']) && isString(choice['title']),\n\t\t\t\t))\n\t\t)\n\t\t\treturn false\n\t\treturn (itemType === 'string' && !isUndefined(choices)) || !isUndefined(titled)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is the restricted top-level object schema a form elicitation issues.\n *\n * @remarks\n * The schema half of {@link isMCPElicitForm}, exported on its own because the issued schema\n * outlives the request that issued it: it is bound into protected continuation state and is\n * what {@link isElicitContent} enforces an accepted response against. Every declared property\n * must itself be one restricted {@link MCPElicitFieldSchema}; the schema is otherwise open, so\n * an unrecognized top-level annotation is data rather than a rejection.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when `value` is a restricted object schema of supported field schemas\n *\n * @example\n * ```ts\n * isMCPElicitSchema({ type: 'object', properties: { approved: { type: 'boolean' } } }) // true\n * isMCPElicitSchema({ type: 'object', properties: { nested: { type: 'object' } } }) // false\n * ```\n */\nexport function isMCPElicitSchema(value: unknown): value is MCPElicitSchema {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst schema: Readonly<Record<string, unknown>> = owned.value\n\t\tconst properties = schema['properties']\n\t\tif (schema['type'] !== 'object' || !isJSONObject(properties)) return false\n\t\tconst dialect = schema['$schema']\n\t\tif (!isUndefined(dialect) && !isString(dialect)) return false\n\t\tconst required = schema['required']\n\t\treturn (\n\t\t\t(isUndefined(required) ||\n\t\t\t\t(Array.isArray(required) && required.every((name) => isString(name)))) &&\n\t\t\tObject.values(properties).every((property) => isMCPElicitFieldSchema(property))\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is a form-mode elicitation parameter object.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when `value` has the restricted form elicitation shape\n *\n * @example\n * ```ts\n * isMCPElicitForm({\n * message: 'Continue?',\n * requestedSchema: { type: 'object', properties: {} },\n * }) // true\n * ```\n */\nexport function isMCPElicitForm(value: unknown): value is MCPElicitForm {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst params = owned.value\n\t\tconst mode = params['mode']\n\t\tif (!isUndefined(mode) && mode !== 'form') return false\n\t\treturn isString(params['message']) && isMCPElicitSchema(params['requestedSchema'])\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is a URL-mode elicitation parameter object.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when `value` has the URL elicitation shape\n *\n * @example\n * ```ts\n * isMCPElicitURL({ mode: 'url', message: 'Authenticate', url: 'https://example.test' })\n * ```\n */\nexport function isMCPElicitURL(value: unknown): value is MCPElicitURL {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst params = owned.value\n\t\treturn params['mode'] === 'url' && isString(params['message']) && isAbsoluteURI(params['url'])\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is an embedded `elicitation/create` request.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when `value` is a form- or URL-mode elicitation request\n *\n * @example\n * ```ts\n * isMCPElicitRequest({\n * method: 'elicitation/create',\n * params: { message: 'Continue?', requestedSchema: { type: 'object', properties: {} } },\n * }) // true\n * ```\n */\nexport function isMCPElicitRequest(value: unknown): value is MCPElicitRequest {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst request = owned.value\n\t\tif (request['method'] !== 'elicitation/create') return false\n\t\treturn isMCPElicitForm(request['params']) || isMCPElicitURL(request['params'])\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one legal embedded multi-round-trip request.\n *\n * @param value - The unknown value to inspect\n * @returns `true` for elicitation, deprecated sampling, or deprecated roots requests\n *\n * @example\n * ```ts\n * isMCPInputRequest({ method: 'roots/list' }) // true — legal but not produced by this package\n * ```\n */\nexport function isMCPInputRequest(value: unknown): value is MCPInputRequest {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst request = owned.value\n\t\tif (isMCPElicitRequest(request)) return true\n\t\tconst params = request['params']\n\t\tif (request['method'] === 'sampling/createMessage') return isRecord(params)\n\t\treturn request['method'] === 'roots/list' && (isUndefined(params) || isRecord(params))\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is a server-keyed map of embedded input requests.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when every own value is a legal {@link MCPInputRequest}\n *\n * @example\n * ```ts\n * isMCPInputRequestMap({ confirm: { method: 'roots/list' } }) // true; maps, never arrays\n * ```\n */\nexport function isMCPInputRequestMap(value: unknown): value is MCPInputRequestMap {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\treturn Object.values(owned.value).every((request) => isMCPInputRequest(request))\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is one elicitation response.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when action/content have the protocol shape\n *\n * @example\n * ```ts\n * isMCPElicitResult({ action: 'accept', content: { approved: true } }) // true\n * ```\n */\nexport function isMCPElicitResult(value: unknown): value is MCPElicitResult {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst result = owned.value\n\t\tconst action = result['action']\n\t\tif (action !== 'accept' && action !== 'decline' && action !== 'cancel') return false\n\t\tconst content = result['content']\n\t\tif (action !== 'accept') return isUndefined(content)\n\t\tif (isUndefined(content)) return true\n\t\tif (!isJSONObject(content)) return false\n\t\treturn Object.values(content).every(\n\t\t\t(item) =>\n\t\t\t\tisString(item) ||\n\t\t\t\tisFiniteNumber(item) ||\n\t\t\t\tisBoolean(item) ||\n\t\t\t\t(Array.isArray(item) && item.every((entry) => isString(entry))),\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether accepted elicitation content satisfies the exact schema that was issued.\n *\n * @remarks\n * {@link isMCPElicitResult} says a response has the SHAPE of a response; this says the\n * response answers the QUESTION that was asked. A server that protects the schema it issued\n * and then never enforces it has bought nothing, so this guard closes that gap: it is what\n * turns a bound schema into a checked one.\n *\n * Every own value must be one {@link MCPElicitValue} — a string, a finite number, a boolean,\n * or an array of strings. A value whose name is DECLARED in `schema.properties` must in\n * addition satisfy that field's schema: `integer` rejects a fraction, `minimum` / `maximum`\n * bound a number, `minLength` / `maxLength` bound a string by code points, `enum` and `oneOf`\n * bound it to a declared member, `format` is enforced (`uri` by {@link isAbsoluteURI}, `email`\n * by syntax, and `date` / `date-time` by {@link isRFC3339Date} / {@link isRFC3339DateTime},\n * which refuse a day the calendar does not have), and an array is bounded by `minItems` /\n * `maxItems` with every entry drawn from its `items.enum` or `items.anyOf`. Every name listed\n * in `schema.required` must be present.\n *\n * An UNDECLARED property remains valid: the restricted schema is open by default, so a client\n * that answers more than it was asked is not refused for it. A `schema` that is not itself a\n * valid {@link MCPElicitSchema} admits NOTHING — an unenforceable schema is never a permissive\n * one — which is why `schema` is accepted as `unknown` and checked rather than trusted. Total\n * (§14) over hostile content and hostile schemas alike.\n *\n * @param value - The accepted response content to check\n * @param schema - The exact {@link MCPElicitSchema} that was issued with the elicitation\n * @returns `true` when every declared and undeclared value is legal under `schema`\n *\n * @example\n * ```ts\n * const schema = {\n * \ttype: 'object',\n * \tproperties: { approved: { type: 'boolean' }, count: { type: 'integer', minimum: 1 } },\n * \trequired: ['approved'],\n * }\n * isElicitContent({ approved: true, count: 2 }, schema) // true\n * isElicitContent({ approved: true, count: 2.5 }, schema) // false — not an integer\n * isElicitContent({ count: 2 }, schema) // false — `approved` is required\n * ```\n */\nexport function isElicitContent(\n\tvalue: unknown,\n\tschema: unknown,\n): value is Readonly<Record<string, MCPElicitValue>> {\n\tconst declared = attempt(() => cloneJSONRecord(schema))\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!declared.success || !owned.success || !isMCPElicitSchema(declared.value)) return false\n\ttry {\n\t\tconst content: Readonly<Record<string, unknown>> = owned.value\n\t\tconst properties: unknown = declared.value['properties']\n\t\tconst required: unknown = declared.value['required']\n\t\tif (!isJSONObject(properties)) return false\n\t\tif (Array.isArray(required)) {\n\t\t\tfor (const name of required) {\n\t\t\t\tif (!isString(name) || !Object.hasOwn(content, name)) return false\n\t\t\t}\n\t\t}\n\t\tfor (const [name, item] of Object.entries(content)) {\n\t\t\tif (\n\t\t\t\t!isString(item) &&\n\t\t\t\t!isFiniteNumber(item) &&\n\t\t\t\t!isBoolean(item) &&\n\t\t\t\t!(Array.isArray(item) && item.every((entry) => isString(entry)))\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t// An UNDECLARED property is data, not a violation: the restricted schema is open.\n\t\t\tif (!Object.hasOwn(properties, name)) continue\n\t\t\tconst field: unknown = properties[name]\n\t\t\tif (!isJSONObject(field)) return false\n\t\t\tconst declaredType = field['type']\n\t\t\tif (declaredType === 'boolean') {\n\t\t\t\tif (!isBoolean(item)) return false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (declaredType === 'number' || declaredType === 'integer') {\n\t\t\t\tconst minimum = field['minimum']\n\t\t\t\tconst maximum = field['maximum']\n\t\t\t\tif (!isFiniteNumber(item)) return false\n\t\t\t\tif (declaredType === 'integer' && !Number.isInteger(item)) return false\n\t\t\t\tif (isFiniteNumber(minimum) && item < minimum) return false\n\t\t\t\tif (isFiniteNumber(maximum) && item > maximum) return false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (declaredType === 'string') {\n\t\t\t\tconst choices = field['enum']\n\t\t\t\tconst titled = field['oneOf']\n\t\t\t\tconst minimum = field['minLength']\n\t\t\t\tconst maximum = field['maxLength']\n\t\t\t\tconst format = field['format']\n\t\t\t\tif (!isString(item)) return false\n\t\t\t\tif (Array.isArray(choices) && !choices.includes(item)) return false\n\t\t\t\tif (\n\t\t\t\t\tArray.isArray(titled) &&\n\t\t\t\t\t!titled.some((choice) => isJSONObject(choice) && choice['const'] === item)\n\t\t\t\t) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\t// Code points, not UTF-16 units: JSON Schema counts characters.\n\t\t\t\tconst length = Array.from(item).length\n\t\t\t\tif (isInteger(minimum) && length < minimum) return false\n\t\t\t\tif (isInteger(maximum) && length > maximum) return false\n\t\t\t\tif (format === 'uri' && !isAbsoluteURI(item)) return false\n\t\t\t\tif (format === 'email' && !/^[^\\s@]+@[^\\s@.]+(?:\\.[^\\s@.]+)+$/.test(item)) return false\n\t\t\t\tif (format === 'date' && !isRFC3339Date(item)) return false\n\t\t\t\tif (format === 'date-time' && !isRFC3339DateTime(item)) return false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst items = field['items']\n\t\t\tconst minimum = field['minItems']\n\t\t\tconst maximum = field['maxItems']\n\t\t\tif (!Array.isArray(item) || !item.every((entry) => isString(entry))) return false\n\t\t\tif (isInteger(minimum) && item.length < minimum) return false\n\t\t\tif (isInteger(maximum) && item.length > maximum) return false\n\t\t\tif (!isJSONObject(items)) return false\n\t\t\tconst choices = items['enum']\n\t\t\tconst titled = items['anyOf']\n\t\t\tif (Array.isArray(choices) && !item.every((entry) => choices.includes(entry))) return false\n\t\t\tif (\n\t\t\t\tArray.isArray(titled) &&\n\t\t\t\t!item.every((entry) =>\n\t\t\t\t\ttitled.some((choice) => isJSONObject(choice) && choice['const'] === entry),\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a value is an MCP input-required result.\n *\n * @remarks\n * Enforces the at-least-one-of rule at runtime: `inputRequests`, `requestState`, or\n * both must be present and valid. Total over hostile input.\n *\n * @param value - The unknown value to inspect\n * @returns `true` when `value` is a valid input-required result\n *\n * @example\n * ```ts\n * isMCPInputResult({ resultType: 'input_required', requestState: 'opaque' }) // true\n * isMCPInputResult({ resultType: 'input_required' }) // false\n * ```\n */\nexport function isMCPInputResult(value: unknown): value is MCPInputResult {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\ttry {\n\t\tconst result = owned.value\n\t\tif (result['resultType'] !== 'input_required') return false\n\t\tconst inputRequests = result['inputRequests']\n\t\tconst requestState = result['requestState']\n\t\tconst metadata = result['_meta']\n\t\tif (!isUndefined(inputRequests) && !isMCPInputRequestMap(inputRequests)) return false\n\t\tif (!isUndefined(requestState) && !isString(requestState)) return false\n\t\tif (!isUndefined(metadata) && !isMCPResultMetaObject(metadata)) return false\n\t\treturn !isUndefined(inputRequests) || !isUndefined(requestState)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCRequest}.\n *\n * @remarks\n * A request is a record with `jsonrpc === '2.0'`, a string `method`, and an `id`\n * that {@link isJSONRPCId} accepts. An id-less call is NOT a request — it is a\n * {@link JSONRPCNotification}, which {@link isJSONRPCNotification} answers for. The\n * two guards are mutually exclusive on every input: this one requires a valid `id`\n * value, that one requires no own `id` member at all. `params`, when present, must\n * be a record. Total (§14): any other input returns `false`.\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC request\n *\n * @example\n * ```ts\n * isJSONRPCRequest({ jsonrpc: '2.0', method: 'ping', id: 1 }) // true\n * isJSONRPCRequest({ jsonrpc: '2.0', method: 'notifications/initialized' }) // false — a notification\n * isJSONRPCRequest({ jsonrpc: '1.0', method: 'ping', id: 1 }) // false\n * ```\n */\nexport function isJSONRPCRequest(value: unknown): value is JSONRPCRequest {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst request = owned.value\n\tif (request['jsonrpc'] !== '2.0' || !isString(request['method'])) return false\n\tif (!isJSONRPCId(request['id'])) return false\n\tconst params = request['params']\n\treturn isUndefined(params) || isRecord(params)\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCNotification}.\n *\n * @remarks\n * A notification is a request-shaped call carrying NO `id` member — the protocol\n * forbids one, because nothing answers a notification. `params`, when present, must\n * be a record. Total (§14): any other input returns `false`.\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC notification\n *\n * @example\n * ```ts\n * isJSONRPCNotification({ jsonrpc: '2.0', method: 'notifications/initialized' }) // true\n * isJSONRPCNotification({ jsonrpc: '2.0', method: 'ping', id: 1 }) // false — a request\n * ```\n */\nexport function isJSONRPCNotification(value: unknown): value is JSONRPCNotification {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst notification = owned.value\n\tif (notification['jsonrpc'] !== '2.0' || !isString(notification['method'])) return false\n\tif (Object.hasOwn(notification, 'id')) return false\n\tconst params = notification['params']\n\treturn isUndefined(params) || isRecord(params)\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCInvocation} — a request or a\n * notification.\n *\n * @remarks\n * The union of {@link isJSONRPCRequest} and {@link isJSONRPCNotification}, which are\n * mutually exclusive, so a positive answer names exactly one arm. Total (§14).\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC request or notification\n */\nexport function isJSONRPCInvocation(value: unknown): value is JSONRPCInvocation {\n\treturn isJSONRPCRequest(value) || isJSONRPCNotification(value)\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCResultResponse} — the success\n * arm of a response.\n *\n * @remarks\n * A result answers a request, so `id` is REQUIRED and must be a valid\n * {@link isJSONRPCId}. The envelope must own a `result` and must NOT own an `error`,\n * which is what makes this guard and {@link isJSONRPCErrorResponse} mutually\n * exclusive on every input. `result` itself must be an object: either a modern\n * {@link isMCPResult} or a legacy {@link isMCPLegacyResult}, never a bare primitive.\n * Total (§14).\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC result response\n *\n * @example\n * ```ts\n * isJSONRPCResultResponse({ jsonrpc: '2.0', id: 1, result: { resultType: 'complete' } }) // true\n * isJSONRPCResultResponse({ jsonrpc: '2.0', id: 1, result: 5 }) // false — a result is an object\n * ```\n */\nexport function isJSONRPCResultResponse(value: unknown): value is JSONRPCResultResponse {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst response = owned.value\n\tif (response['jsonrpc'] !== '2.0' || !isJSONRPCId(response['id'])) return false\n\tif (Object.hasOwn(response, 'error') || !Object.hasOwn(response, 'result')) return false\n\tconst result = response['result']\n\treturn isMCPResult(result) || isMCPLegacyResult(result)\n}\n\n/**\n * Determine whether a value is one JSON-RPC `error` member.\n *\n * @remarks\n * The failure OBJECT, not the envelope carrying it — the shape a failed response owns\n * under `error`, and the shape a `failed` {@link MCPTaskDetail} owns under the same name,\n * which is why it is one guard rather than the same three checks written twice.\n *\n * It is deliberately STRUCTURAL rather than exact-JSON: `data` is declared `unknown`, so\n * requiring the whole object to survive a JSON clone would refuse a legal error that\n * carried a non-JSON payload. Both callers here hand it an already-owned value.\n *\n * That choice is why the two key reads are guarded. Every sibling guard clones first, and a\n * clone reads each key once behind a boundary that already owns totality; this one is the\n * family's only DIRECT reader, so it meets `code` and `message` exactly as the value defines\n * them — including as accessors that throw. Reading a named key off an unowned value is\n * itself the hostile step, and it is bounded here rather than allowed to escape. Total (§14).\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` carries an integer `code` and a string `message`\n *\n * @example\n * ```ts\n * isJSONRPCError({ code: -32602, message: 'Invalid params' }) // true\n * isJSONRPCError({ code: -32602.5, message: 'x' }) // false — a code is an integer\n * ```\n */\nexport function isJSONRPCError(value: unknown): value is JSONRPCError {\n\tif (!isRecord(value)) return false\n\tconst read = attempt(() => isInteger(value['code']) && isString(value['message']))\n\treturn read.success && read.value\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCErrorResponse} — the failure\n * arm of a response.\n *\n * @remarks\n * `id` is OPTIONAL here and only here: a peer that could not read the failed\n * request's id OMITS the member rather than sending `null`, so an absent `id` is\n * valid and a `null` one is not. The envelope must own an `error` and must NOT own a\n * `result`. `error` carries an integer `code` and a string `message`. Total (§14).\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC error response\n *\n * @example\n * ```ts\n * isJSONRPCErrorResponse({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' } }) // true\n * isJSONRPCErrorResponse({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'x' } }) // false\n * ```\n */\nexport function isJSONRPCErrorResponse(value: unknown): value is JSONRPCErrorResponse {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst response = owned.value\n\tif (response['jsonrpc'] !== '2.0') return false\n\tif (Object.hasOwn(response, 'id') && !isJSONRPCId(response['id'])) return false\n\tif (Object.hasOwn(response, 'result') || !Object.hasOwn(response, 'error')) return false\n\treturn isJSONRPCError(response['error'])\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCResponse}.\n *\n * @remarks\n * The union of the two mutually exclusive arms. Total (§14).\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC response\n */\nexport function isJSONRPCResponse(value: unknown): value is JSONRPCResponse {\n\treturn isJSONRPCResultResponse(value) || isJSONRPCErrorResponse(value)\n}\n\n/**\n * Determine whether a parsed value is a {@link JSONRPCMessage} — an invocation or a\n * response.\n *\n * @remarks\n * The union of {@link isJSONRPCInvocation} and {@link isJSONRPCResponse}. Total (§14).\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid JSON-RPC message\n */\nexport function isJSONRPCMessage(value: unknown): value is JSONRPCMessage {\n\treturn isJSONRPCInvocation(value) || isJSONRPCResponse(value)\n}\n\n/**\n * Determine whether a parsed value is an MCP `initialize` invocation.\n *\n * @param value - The already-parsed value to test\n * @returns `true` when `value` is a valid `initialize` request or notification\n *\n * @example\n * ```ts\n * isInitializeRequest({ jsonrpc: '2.0', method: 'initialize', id: 1 }) // true\n * isInitializeRequest({ jsonrpc: '2.0', method: 'ping', id: 1 }) // false\n * ```\n */\nexport function isInitializeRequest(value: unknown): value is JSONRPCInvocation {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\treturn owned.success && isJSONRPCInvocation(owned.value) && owned.value['method'] === 'initialize'\n}\n\n/**\n * Determine whether a JSON-RPC invocation uses the modern per-request MCP wire shape.\n *\n * @remarks\n * Presence routes and validity answers: this guard checks only that\n * `params._meta` carries the reserved protocol-version key. The key's value is\n * deliberately not narrowed here, so a present non-string version remains modern\n * and is rejected later by `parseRequestContext` rather than falling through to\n * legacy dispatch. Total over hostile and malformed input.\n *\n * @param value - The already-parsed value to inspect\n * @returns `true` when the value is an invocation carrying the reserved version key\n */\nexport function isModernRequest(value: unknown): value is JSONRPCInvocation {\n\tconst owned = attempt(() => cloneJSONRecord(value))\n\tif (!owned.success) return false\n\tconst request = owned.value\n\tif (!isJSONRPCInvocation(request)) return false\n\tconst params = request['params']\n\tconst metadata = isRecord(params) ? params['_meta'] : undefined\n\treturn isRecord(metadata) && Object.hasOwn(metadata, MCP_META_VERSION)\n}\n","import type { MCPMethodHandler, MCPMethodManagerInterface } from './types.js'\n\n/**\n * The modern method registry an {@link import('./types.js').MCPServerInterface}\n * dispatches through — a name-keyed store of {@link MCPMethodHandler}s that owns its\n * map rather than exposing one.\n *\n * @remarks\n * - **One seam.** The server registers its built-in modern methods here at construction\n * and resolves EVERY modern method from here, so a consumer's method and a built-in\n * are the same kind of thing on the same path.\n * - **Registration is a write, not a merge.** `add` under a name already present\n * REPLACES it, which is how a consumer overrides a built-in; there is no precedence\n * rule to remember.\n * - **A narrower contract than a `Map`.** Callers register and resolve; they cannot\n * iterate, clear, or otherwise reach the server's internal state through it.\n *\n * @example\n * ```ts\n * const methods = new MCPMethodManager()\n * methods.add('tools/list', async ({ id }) => buildJSONRPCResult(id, { tools: [] }))\n * methods.method('tools/list') // the handler\n * methods.method('tools/nope') // undefined → the dispatch branch answers -32601\n * ```\n */\nexport class MCPMethodManager implements MCPMethodManagerInterface {\n\treadonly #handlers = new Map<string, MCPMethodHandler>()\n\n\tadd(name: string, handler: MCPMethodHandler): void {\n\t\tthis.#handlers.set(name, handler)\n\t}\n\n\tmethod(name: string): MCPMethodHandler | undefined {\n\t\treturn this.#handlers.get(name)\n\t}\n}\n","import type {\n\tJSONRPCNotification,\n\tMCPJSONLimitOptions,\n\tMCPProgress,\n\tMCPProgressInterface,\n} from './types.js'\nimport { snapshotJSON } from './cloners.js'\nimport { buildProgressNotification } from './helpers.js'\nimport { isMCPProgress } from './validators.js'\n\n/**\n * A bounded, request-scoped progress handoff between one producer and one serial consumer.\n *\n * The reporter holds at most one owned progress item. {@link report} applies backpressure until\n * {@link take} consumes that slot. It has no replay, queue, concurrent-consumer coordination,\n * task state, or durable-work semantics; stopping or aborting the request discards the slot and\n * rejects pending work.\n *\n * @example\n * ```ts\n * import { MCPProgressReporter } from '@orkestrel/mcp'\n *\n * const reporter = new MCPProgressReporter(\n * \t'call-1',\n * \t{ bytes: 256, keys: 3, depth: 1 },\n * \tnew AbortController().signal,\n * )\n * const reported = reporter.report({ progress: 1, total: 2 })\n * const notification = await reporter.take()\n * await reported\n * reporter.stop()\n * ```\n */\nexport class MCPProgressReporter implements MCPProgressInterface {\n\treadonly #token: string | number\n\treadonly #limits: MCPJSONLimitOptions\n\treadonly #signal: AbortSignal\n\treadonly #listener: () => void\n\t#value: MCPProgress | undefined\n\t#waiter: PromiseWithResolvers<void> | undefined\n\t#consumed: PromiseWithResolvers<void> | undefined\n\t#last: number | undefined\n\t#stopped = false\n\n\t/**\n\t * Create one non-durable progress slot for an active request.\n\t *\n\t * @param token - The opaque progress token copied into each notification\n\t * @param limits - The byte, key, and depth bounds applied to every progress payload\n\t * @param signal - The request signal whose abort permanently stops the reporter\n\t */\n\tconstructor(token: string | number, limits: MCPJSONLimitOptions, signal: AbortSignal) {\n\t\tthis.#token = token\n\t\tthis.#limits = limits\n\t\tthis.#signal = signal\n\t\tthis.#listener = this.stop.bind(this)\n\t\tif (signal.aborted) this.stop()\n\t\telse signal.addEventListener('abort', this.#listener, { once: true })\n\t}\n\n\t/**\n\t * Publish one bounded, strictly increasing progress value and await its consumption.\n\t *\n\t * @param progress - The progress payload to own and hand to the serial consumer\n\t * @returns A promise resolving after {@link take} consumes the item\n\t * @throws When stopped, a previous item remains unconsumed, the payload is invalid or outside\n\t * its bounds, or its `progress` value does not strictly increase\n\t */\n\tasync report(progress: MCPProgress): Promise<void> {\n\t\tthis.#requireIdle()\n\t\tconst snapshot = snapshotJSON(progress, this.#limits)\n\t\tconst owned = snapshot?.[0]\n\t\tconst consumed = Promise.withResolvers<void>()\n\t\tthis.#requireIdle()\n\t\tif (!isMCPProgress(owned))\n\t\t\tthrow new Error('Progress is invalid or exceeds the configured limit')\n\t\tif (this.#last !== undefined && owned.progress <= this.#last) {\n\t\t\tthrow new Error('Progress must strictly increase')\n\t\t}\n\t\tthis.#last = owned.progress\n\t\tthis.#value = owned\n\t\tthis.#consumed = consumed\n\t\tthis.#waiter?.resolve()\n\t\tawait consumed.promise\n\t}\n\n\t/**\n\t * Take the next progress notification, waiting for the single producer slot when empty.\n\t *\n\t * @returns The official progress notification carrying the original token\n\t * @throws When the reporter stops or another consumer already has a pending take\n\t */\n\tasync take(): Promise<JSONRPCNotification> {\n\t\t// The loop's own condition is a door too: a take arriving on a full slot skips the body\n\t\t// entirely, so the entry facts are asked here rather than only inside it. Without this a\n\t\t// rival consumer would walk past a parked consumer's waiter and take the slot it is owed.\n\t\tthis.#requireSoleConsumer()\n\t\twhile (this.#value === undefined) {\n\t\t\tthis.#requireSoleConsumer()\n\t\t\tconst waiter = Promise.withResolvers<void>()\n\t\t\t// The factory is the only caller-reachable code in the loop, and both ways out of the\n\t\t\t// iteration lie past it: the exit below and the park beneath that. So the door runs\n\t\t\t// here, ahead of both, rather than on the parking path alone — a hook that fills the\n\t\t\t// slot AND parks a rival would otherwise send this take out of the loop to consume an\n\t\t\t// item the rival is owed, putting two live consumers on a one-consumer handoff.\n\t\t\tthis.#requireSoleConsumer()\n\t\t\t// A slot that arrived while the factory ran is an answer, not a refusal: re-enter the\n\t\t\t// loop and consume it rather than parking behind a value already sitting in the slot.\n\t\t\tif (this.#value !== undefined) continue\n\t\t\tthis.#waiter = waiter\n\t\t\tawait waiter.promise\n\t\t\tthis.#waiter = undefined\n\t\t}\n\t\tconst progress = this.#value\n\t\tthis.#value = undefined\n\t\tconst consumed = this.#consumed\n\t\tthis.#consumed = undefined\n\t\tconsumed?.resolve()\n\t\treturn buildProgressNotification(this.#token, progress)\n\t}\n\n\t/**\n\t * Permanently stop the reporter, reject pending work, and detach its abort listener.\n\t *\n\t * Repeated calls are idempotent. No queued or replayable progress survives the first call.\n\t *\n\t * @returns Nothing\n\t */\n\tstop(): void {\n\t\tif (this.#stopped) return\n\t\tthis.#stopped = true\n\t\tconst waiter = this.#waiter\n\t\tconst consumed = this.#consumed\n\t\tthis.#waiter = undefined\n\t\tthis.#consumed = undefined\n\t\tthis.#value = undefined\n\t\tthis.#signal.removeEventListener('abort', this.#listener)\n\t\tconst error = new Error('Progress reporter is stopped')\n\t\twaiter?.reject(error)\n\t\tconsumed?.reject(error)\n\t}\n\n\t// Reject a report that enters, or reaches its final check, while stopped or still holding an\n\t// unconsumed slot. Both doors run the same rule, so hostile work between them cannot pass one\n\t// door on a state the other already refused.\n\t#requireIdle(): void {\n\t\tif (this.#stopped) throw new Error('Progress reporter is stopped')\n\t\tif (this.#value !== undefined || this.#consumed !== undefined) {\n\t\t\tthrow new Error('Previous progress has not been consumed')\n\t\t}\n\t}\n\n\t// Reject a take that enters, re-enters the wait, or reaches its final check, while stopped or\n\t// while another consumer already holds the waiter. Every door runs the same rule, so hostile\n\t// work between them cannot pass one door on a state another already refused.\n\t#requireSoleConsumer(): void {\n\t\tif (this.#stopped) throw new Error('Progress reporter is stopped')\n\t\tif (this.#waiter !== undefined) throw new Error('Progress take is already pending')\n\t}\n}\n","import type {\n\tJSONRPCNotification,\n\tJSONRPCResponse,\n\tMCPStream,\n\tMCPStreamControllerInterface,\n} from './types.js'\n\n/**\n * The one cancellation engine every modern held-open result leaves `MCPServer` through.\n *\n * @remarks\n * A native async generator decides cancellation with a QUEUE: `return()` and `throw()` wait\n * behind a `next()` the producer has not answered, so a consumer abandoning a source parked\n * on an event that will never arrive waits forever for its own cancellation. This class\n * arbitrates instead of queueing. It keeps at most ONE read outstanding against the source,\n * settles the consumer's read itself, aborts the request's lifetime BEFORE it delegates\n * cleanup to the producer — so a cooperating producer is woken rather than waited on —\n * contains every promise the producer settles late, and makes every closure path idempotent.\n *\n * The three closures are deliberately different answers: the source's own return is the\n * terminal RESPONSE, `return(value)` is the consumer saying it has the answer already, and\n * {@link stop} is an owner saying there will be no answer at all. Only the first is a\n * message a peer ever sees.\n *\n * A producer's own resource cleanup remains the producer's: JavaScript cannot settle work a\n * generator is suspended inside, so the signal is how an uncooperative producer is asked to\n * finish, and this controller never blocks its consumer on the answer.\n *\n * **What this class does NOT have is an owner of last resort.** No finalizer, no timer, no\n * timeout ends an exchange nobody released. That absence is the design: an exchange holds a\n * producer, a request lifetime and a live server slot, so a silent background release would\n * turn \"a pump forgot its obligation\" from a reproducible defect into a nondeterministic one,\n * and GC timing is not a lifecycle. Whoever is handed one of these ends it on every exit —\n * see {@link import('./types.js').MCPStreamControllerInterface}.\n *\n * @example\n * ```ts\n * import { MCPStreamController } from '@orkestrel/mcp'\n *\n * const closure = new AbortController()\n * const stream = new MCPStreamController(source, closure.signal, closure)\n * const first = await stream.next() // one notification\n * stream.stop() // ends the exchange now, however long the producer takes to notice\n * ```\n */\nexport class MCPStreamController implements MCPStreamControllerInterface {\n\treadonly #source: MCPStream\n\treadonly #signal: AbortSignal\n\treadonly #closure: AbortController\n\treadonly #listener: () => void\n\t#waiter: PromiseWithResolvers<IteratorResult<JSONRPCNotification, JSONRPCResponse>> | undefined\n\t#terminal: JSONRPCResponse | undefined\n\t#error: unknown\n\t#closed = false\n\n\t/**\n\t * Control one produced stream for the lifetime of one request.\n\t *\n\t * @param source - The produced held-open result whose cancellation this controller owns\n\t * @param signal - The request signal every closure settles against; its abort ends the exchange\n\t * @param closure - The request's lifetime controller, aborted the moment the exchange ends\n\t */\n\tconstructor(source: MCPStream, signal: AbortSignal, closure: AbortController) {\n\t\tthis.#source = source\n\t\tthis.#signal = signal\n\t\tthis.#closure = closure\n\t\tthis.#listener = this.#abort.bind(this)\n\t\tif (signal.aborted) this.#fail(signal.reason)\n\t\telse signal.addEventListener('abort', this.#listener, { once: true })\n\t}\n\n\t/**\n\t * Read the next message, or the terminating response that ends the exchange.\n\t *\n\t * @remarks\n\t * At most one read is outstanding against the source at a time, and a rival read is\n\t * refused rather than queued: two live consumers on one held-open answer would split a\n\t * sequence neither of them could reassemble. A read parked on the producer settles as\n\t * soon as the exchange closes, whatever the producer is doing.\n\t *\n\t * @returns The next notification, or the terminal response as the iteration's `return`\n\t * @throws The abort reason when the request ended, or the source's own failure\n\t */\n\tasync next(): Promise<IteratorResult<JSONRPCNotification, JSONRPCResponse>> {\n\t\tif (this.#closed) return this.#exhausted()\n\t\tif (this.#waiter !== undefined) throw new Error('A stream read is already pending')\n\t\tconst waiter = Promise.withResolvers<IteratorResult<JSONRPCNotification, JSONRPCResponse>>()\n\t\tthis.#waiter = waiter\n\t\tconst pending = this.#source.next()\n\t\t// The consumer may leave before the producer answers, and the promise it abandons is\n\t\t// this controller's to contain rather than the runtime's to report.\n\t\tvoid pending.catch(() => undefined)\n\t\tlet result: IteratorResult<JSONRPCNotification, JSONRPCResponse>\n\t\ttry {\n\t\t\tresult = await Promise.race([pending, waiter.promise])\n\t\t} catch (error) {\n\t\t\tif (!this.#closed) this.#fail(error)\n\t\t\tthrow error\n\t\t}\n\t\tif (this.#closed) return this.#exhausted()\n\t\tthis.#waiter = undefined\n\t\tif (result.done !== true) return result\n\t\tthis.#complete(result.value)\n\t\treturn { done: true, value: result.value }\n\t}\n\n\t/**\n\t * End the exchange because the consumer already has its answer.\n\t *\n\t * @param value - The terminal the consumer is ending on\n\t * @returns That terminal as the iteration's `return`\n\t */\n\tasync return(\n\t\tvalue: JSONRPCResponse | PromiseLike<JSONRPCResponse>,\n\t): Promise<IteratorResult<JSONRPCNotification, JSONRPCResponse>> {\n\t\tconst terminal = await value\n\t\tthis.#complete(terminal)\n\t\treturn { done: true, value: terminal }\n\t}\n\n\t/**\n\t * End the exchange with a failure the consumer is raising.\n\t *\n\t * @param error - The failure to end the exchange with\n\t * @returns Never — the returned promise always rejects\n\t * @throws The supplied failure\n\t */\n\tasync throw(error: unknown): Promise<IteratorResult<JSONRPCNotification, JSONRPCResponse>> {\n\t\tthis.#fail(error)\n\t\tthrow error\n\t}\n\n\t/**\n\t * End the exchange permanently, with no terminal response.\n\t *\n\t * @remarks\n\t * Idempotent, and the operation an owner that is not the consumer uses: a transport whose\n\t * connection closed, a pump whose write failed. A parked read settles with the request's\n\t * abort reason and every later read settles the same way.\n\t *\n\t * @returns Nothing\n\t */\n\tstop(): void {\n\t\tif (this.#closed) return\n\t\tthis.#closure.abort()\n\t\tif (!this.#closed) this.#fail(this.#closure.signal.reason)\n\t}\n\n\t/**\n\t * End the exchange when the scope that owns it exits.\n\t *\n\t * @remarks\n\t * {@link stop} under the name a `finally` calls it by, so a pump discharges its ownership\n\t * with one statement covering the normal return and every abandoning exit alike.\n\t * Idempotent, and a no-op for an exchange that already ended on its terminal.\n\t *\n\t * @returns Resolves once the exchange has ended\n\t */\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tthis.stop()\n\t}\n\n\t/**\n\t * Iterate this exchange — the controller is its own iterator.\n\t *\n\t * @returns This controller\n\t */\n\t[Symbol.asyncIterator](): MCPStreamControllerInterface {\n\t\treturn this\n\t}\n\n\t// The request signal ended the exchange: the caller's own abort, or this controller's\n\t// closure of the request lifetime, which are the same event by the time it arrives here.\n\t#abort(): void {\n\t\tthis.#fail(this.#signal.reason)\n\t}\n\n\t// Normal completion — the source produced its terminal, so the exchange keeps it and\n\t// answers every later read with it.\n\t#complete(terminal: JSONRPCResponse): void {\n\t\tif (this.#closed) return\n\t\tthis.#closed = true\n\t\tthis.#terminal = terminal\n\t\tthis.#release()\n\t\tthis.#waiter?.resolve({ done: true, value: terminal })\n\t\tthis.#waiter = undefined\n\t\tvoid this.#source.return(terminal).catch(() => undefined)\n\t}\n\n\t// Closure with NO terminal — an abort, a consumer throw, a stop, or the source's own\n\t// failure. The exchange keeps the reason and answers every later read by raising it.\n\t#fail(error: unknown): void {\n\t\tif (this.#closed) return\n\t\tthis.#closed = true\n\t\tthis.#error = error\n\t\tthis.#release()\n\t\tthis.#waiter?.reject(error)\n\t\tthis.#waiter = undefined\n\t\tvoid this.#source.throw(error).catch(() => undefined)\n\t}\n\n\t// Detach from the request signal and abort the request's lifetime. Both closures run this\n\t// BEFORE they delegate to the source, so a producer parked on the signal is already awake\n\t// when its cleanup arrives.\n\t#release(): void {\n\t\tthis.#signal.removeEventListener('abort', this.#listener)\n\t\tthis.#closure.abort()\n\t}\n\n\t// The answer a read gets once the exchange is over: the terminal it ended on, or the\n\t// reason it ended without one.\n\t#exhausted(): IteratorResult<JSONRPCNotification, JSONRPCResponse> {\n\t\tconst terminal = this.#terminal\n\t\tif (terminal === undefined) throw this.#error\n\t\treturn { done: true, value: terminal }\n\t}\n}\n","import type { MCPStreamControllerInterface, MCPTextStreamControllerInterface } from './types.js'\n\n/**\n * The string-boundary mirror of a controlled held-open result — the same exchange, already\n * serialized.\n *\n * @remarks\n * A TRANSLATION boundary and deliberately nothing else. It serializes each message and the\n * terminating response, and every lifecycle decision — return, throw, dispose, stop — ends\n * the typed exchange beneath it rather than this face. That is the whole design constraint: a\n * serialized face implemented as its own async generator would add a SECOND operation queue,\n * and the queue is exactly the defect the typed controller exists to remove — a `return()`\n * promptly settled at the text face and left queued at the typed one cancels nothing.\n *\n * One member is a narrowing rather than a pass-through, and it is worth knowing before it\n * surprises a producer. `return` receives a STRING; it cannot rebuild the typed\n * `JSONRPCResponse` the typed face would close on, and inventing one by parsing the\n * argument back would make this face decide what the exchange ended with. So it ends the\n * typed exchange with {@link MCPStreamControllerInterface.stop} — no terminal — and answers\n * its own consumer with the string it was handed. A cooperating producer therefore observes\n * its cancellation path here where the typed face would have run its normal return. That is\n * the honest translation of \"the consumer already has its answer\" when the answer is opaque\n * text, not a downgrade to work around.\n *\n * It accepts only a CONTROLLED typed stream. A raw generator would have no lifecycle to\n * delegate to, and this class refuses to grow one of its own.\n *\n * Delegation is total and it is what makes the ownership obligation transitive: `return`,\n * `throw`, `stop`, and dispose each end the TYPED exchange, so a pump holding only this\n * serialized face still releases the producer, the request lifetime, and the live server slot\n * behind it. There is no owner of last resort here either, for the same reason there is none\n * on the typed face.\n *\n * @example\n * ```ts\n * import { MCPTextStreamController } from '@orkestrel/mcp'\n *\n * const text = new MCPTextStreamController(controlled)\n * const first = await text.next() // one serialized notification\n * text.stop() // ends the TYPED exchange, not just this adapter\n * ```\n */\nexport class MCPTextStreamController implements MCPTextStreamControllerInterface {\n\treadonly #stream: MCPStreamControllerInterface\n\n\t/**\n\t * Mirror one controlled typed exchange as its serialized sequence.\n\t *\n\t * @param stream - The controlled typed stream this face serializes and delegates into\n\t */\n\tconstructor(stream: MCPStreamControllerInterface) {\n\t\tthis.#stream = stream\n\t}\n\n\t/**\n\t * Read the next serialized message, or the serialized terminating response.\n\t *\n\t * @returns The next message as a string, or the terminal as the iteration's `return`\n\t * @throws Whatever ended the typed exchange, unserialized — an abort is not a message\n\t */\n\tasync next(): Promise<IteratorResult<string, string>> {\n\t\tconst result = await this.#stream.next()\n\t\tconst text = JSON.stringify(result.value)\n\t\treturn result.done === true ? { done: true, value: text } : { done: false, value: text }\n\t}\n\n\t/**\n\t * End the exchange because the consumer already has its answer.\n\t *\n\t * @remarks\n\t * The typed exchange ends with no terminal, because a string is not a\n\t * `JSONRPCResponse` and this face never parses one back out of its argument. The\n\t * supplied text is the answer to THIS consumer, and a cooperating producer sees its\n\t * cancellation path rather than its normal return.\n\t *\n\t * @param value - The serialized terminal the consumer is ending on\n\t * @returns That terminal as the iteration's `return`\n\t */\n\tasync return(value: string | PromiseLike<string>): Promise<IteratorResult<string, string>> {\n\t\tthis.#stream.stop()\n\t\treturn { done: true, value: await value }\n\t}\n\n\t/**\n\t * End the exchange with a failure the consumer is raising.\n\t *\n\t * @param error - The failure to end the exchange with\n\t * @returns Never — the returned promise always rejects\n\t * @throws The supplied failure\n\t */\n\tasync throw(error: unknown): Promise<IteratorResult<string, string>> {\n\t\tthis.#stream.stop()\n\t\tthrow error\n\t}\n\n\t/**\n\t * End the typed exchange permanently, with no terminal response.\n\t *\n\t * @returns Nothing\n\t */\n\tstop(): void {\n\t\tthis.#stream.stop()\n\t}\n\n\t/**\n\t * End the typed exchange when the scope that owns this face exits.\n\t *\n\t * @remarks\n\t * Delegates downward exactly as {@link stop} does — disposing the serialized arm is\n\t * disposing the exchange, never just this adapter.\n\t *\n\t * @returns Resolves once the typed exchange has ended\n\t */\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tthis.#stream.stop()\n\t}\n\n\t/**\n\t * Iterate this exchange — the controller is its own iterator.\n\t *\n\t * @returns This controller\n\t */\n\t[Symbol.asyncIterator](): MCPTextStreamControllerInterface {\n\t\treturn this\n\t}\n}\n","import type {\n\tJSONRPCErrorResponse,\n\tJSONRPCId,\n\tJSONRPCInvocation,\n\tJSONRPCNotification,\n\tJSONRPCRequest,\n\tJSONRPCResponse,\n\tMCPDispatchOptions,\n\tMCPDispatcherInterface,\n\tMCPLegacyOptions,\n\tMCPLegacyResult,\n\tMCPLimitOptions,\n\tMCPStreamControllerInterface,\n\tMCPTextStreamControllerInterface,\n} from './types.js'\nimport { isRecord, isString } from '@orkestrel/contract'\nimport {\n\tJSONRPC_INVALID_PARAMS,\n\tJSONRPC_METHOD_NOT_FOUND,\n\tJSONRPC_SERVER_ERROR,\n\tMCP_EXTENSION_TASKS,\n\tMCP_META_CAPABILITIES,\n\tMCP_META_SERVER,\n\tMCP_META_VERSION,\n\tMCP_MISSING_CAPABILITY,\n\tMCP_MODERN_VERSION,\n\tMCP_PROTOCOL_VERSION,\n} from './constants.js'\nimport { buildInitializeResult, buildJSONRPCError, buildJSONRPCResult } from './helpers.js'\nimport { isJSONRPCInvocation, isModernRequest } from './validators.js'\n\n/**\n * Translate the fixed legacy method set onto one modern dispatcher.\n *\n * @remarks\n * This decorator owns no execution engine or result normalizer. Modern invocations\n * pass through untouched. Legacy tool methods acquire modern request metadata, run\n * through the configured dispatcher, and lose only fields their dated result shape\n * cannot represent.\n */\nexport class MCPLegacy implements MCPDispatcherInterface {\n\treadonly #options: MCPLegacyOptions\n\n\t/**\n\t * Create a legacy decorator.\n\t *\n\t * @param options - The sole dispatcher and legacy handshake identity\n\t */\n\tconstructor(options: MCPLegacyOptions) {\n\t\tthis.#options = options\n\t}\n\n\tget emitter(): MCPDispatcherInterface['emitter'] {\n\t\treturn this.#options.dispatcher.emitter\n\t}\n\n\tget limit(): Required<MCPLimitOptions> {\n\t\treturn this.#options.dispatcher.limit\n\t}\n\n\tdispatch(\n\t\trequest: JSONRPCRequest,\n\t\toptions?: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | MCPStreamControllerInterface>\n\tdispatch(notification: JSONRPCNotification, options?: MCPDispatchOptions): Promise<undefined>\n\tdispatch(\n\t\tinvocation: JSONRPCInvocation,\n\t\toptions?: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | MCPStreamControllerInterface | undefined>\n\tasync dispatch(\n\t\tinvocation: JSONRPCInvocation,\n\t\toptions?: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | MCPStreamControllerInterface | undefined> {\n\t\tif (isModernRequest(invocation)) {\n\t\t\treturn this.#options.dispatcher.dispatch(invocation, options)\n\t\t}\n\t\tif (!isJSONRPCInvocation(invocation)) {\n\t\t\treturn this.#options.dispatcher.dispatch(invocation, options)\n\t\t}\n\t\treturn this.#legacy(invocation, options)\n\t}\n\n\tasync handle(\n\t\tmessage: string,\n\t\toptions?: MCPDispatchOptions,\n\t): Promise<string | MCPTextStreamControllerInterface | undefined> {\n\t\tlet parsed: unknown\n\t\ttry {\n\t\t\tparsed = JSON.parse(message)\n\t\t} catch {\n\t\t\treturn this.#options.dispatcher.handle(message, options)\n\t\t}\n\t\tif (isModernRequest(parsed) || !isJSONRPCInvocation(parsed)) {\n\t\t\treturn this.#options.dispatcher.handle(message, options)\n\t\t}\n\t\tconst answer = await this.#legacy(parsed, options)\n\t\treturn answer === undefined ? undefined : JSON.stringify(answer)\n\t}\n\n\tasync #legacy(\n\t\tinvocation: JSONRPCInvocation,\n\t\toptions?: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | undefined> {\n\t\tif (invocation.id === undefined) return undefined\n\t\tconst id = invocation.id\n\t\tswitch (invocation.method) {\n\t\t\tcase 'initialize': {\n\t\t\t\tconst requested = invocation.params?.['protocolVersion']\n\t\t\t\treturn buildJSONRPCResult(\n\t\t\t\t\tid,\n\t\t\t\t\tbuildInitializeResult(\n\t\t\t\t\t\tthis.#options.identity.name,\n\t\t\t\t\t\tthis.#options.identity.version,\n\t\t\t\t\t\tisString(requested) ? requested : undefined,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t\tcase 'ping':\n\t\t\tcase 'tools/list':\n\t\t\t\treturn this.#forward(invocation, options)\n\t\t\tcase 'tools/call':\n\t\t\t\t// `-32602` is honest here: these parameters belong to MRTR, which the dated\n\t\t\t\t// protocol could not have produced and therefore cannot continue.\n\t\t\t\tif (\n\t\t\t\t\tinvocation.params !== undefined &&\n\t\t\t\t\t(Object.hasOwn(invocation.params, 'requestState') ||\n\t\t\t\t\t\tObject.hasOwn(invocation.params, 'inputResponses'))\n\t\t\t\t) {\n\t\t\t\t\treturn buildJSONRPCError(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t\t\t'Invalid params: legacy requests cannot continue an input-required result',\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn this.#forward(invocation, options)\n\t\t\tdefault:\n\t\t\t\treturn buildJSONRPCError(\n\t\t\t\t\tid,\n\t\t\t\t\tJSONRPC_METHOD_NOT_FOUND,\n\t\t\t\t\t`Method not found: ${invocation.method}`,\n\t\t\t\t)\n\t\t}\n\t}\n\n\tasync #forward(request: JSONRPCRequest, options?: MCPDispatchOptions): Promise<JSONRPCResponse> {\n\t\tconst params = request.params ?? {}\n\t\tconst metadata = isRecord(params['_meta']) ? params['_meta'] : {}\n\t\tconst translated: JSONRPCRequest = {\n\t\t\t...request,\n\t\t\tparams: {\n\t\t\t\t...params,\n\t\t\t\t_meta: {\n\t\t\t\t\t...metadata,\n\t\t\t\t\t[MCP_META_VERSION]: MCP_MODERN_VERSION,\n\t\t\t\t\t[MCP_META_CAPABILITIES]: {},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tconst answer = await this.#options.dispatcher.dispatch(translated, options)\n\t\tif (Symbol.asyncIterator in answer) {\n\t\t\tanswer.stop()\n\t\t\tawait answer[Symbol.asyncDispose]()\n\t\t\treturn this.#unsupported(request.id, 'stream')\n\t\t}\n\t\treturn this.#project(answer, request.id)\n\t}\n\n\t#project(answer: JSONRPCResponse, id: JSONRPCId): JSONRPCResponse {\n\t\tif (answer.error !== undefined) {\n\t\t\treturn answer.error.code === MCP_MISSING_CAPABILITY\n\t\t\t\t? this.#unsupported(id, this.#capability(answer))\n\t\t\t\t: answer\n\t\t}\n\t\tif (answer.result.resultType !== 'complete') {\n\t\t\treturn this.#unsupported(id, answer.result.resultType ?? 'unstamped')\n\t\t}\n\t\tconst projected: Record<string, unknown> = {}\n\t\tfor (const [key, value] of Object.entries(answer.result)) {\n\t\t\tif (key === 'resultType' || key === 'ttlMs' || key === 'cacheScope') continue\n\t\t\tif (key === 'content' && Array.isArray(value)) {\n\t\t\t\tprojected[key] = value.map((entry) =>\n\t\t\t\t\tisRecord(entry) && entry['type'] === 'text' && isString(entry['text'])\n\t\t\t\t\t\t? { type: 'text', text: entry['text'] }\n\t\t\t\t\t\t: entry,\n\t\t\t\t)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (key !== '_meta' || !isRecord(value)) {\n\t\t\t\tprojected[key] = value\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst metadata: Record<string, unknown> = {}\n\t\t\tfor (const [name, entry] of Object.entries(value)) {\n\t\t\t\tif (name !== MCP_META_SERVER) metadata[name] = entry\n\t\t\t}\n\t\t\tif (Object.keys(metadata).length > 0) projected['_meta'] = metadata\n\t\t}\n\t\tconst result: MCPLegacyResult = projected\n\t\treturn buildJSONRPCResult(id, result)\n\t}\n\n\t#capability(answer: JSONRPCErrorResponse): string {\n\t\tconst data = answer.error.data\n\t\tif (!isRecord(data)) return 'capability-dependent'\n\t\tconst required = data['requiredCapabilities']\n\t\tif (!isRecord(required)) return 'capability-dependent'\n\t\tconst extensions = required['extensions']\n\t\treturn isRecord(extensions) && Object.hasOwn(extensions, MCP_EXTENSION_TASKS)\n\t\t\t? 'task'\n\t\t\t: 'input-required'\n\t}\n\n\t#unsupported(id: JSONRPCId, result: string): JSONRPCErrorResponse {\n\t\tconst article = result === 'input-required' ? 'an' : 'a'\n\t\treturn buildJSONRPCError(\n\t\t\tid,\n\t\t\tJSONRPC_SERVER_ERROR,\n\t\t\t`Legacy protocol ${MCP_PROTOCOL_VERSION} cannot represent ${article} ${result} result`,\n\t\t)\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { ToolCall } from '@orkestrel/tool'\nimport type { JSONValue } from '@orkestrel/contract'\nimport type {\n\tJSONRPCErrorResponse,\n\tJSONRPCId,\n\tJSONRPCInvocation,\n\tJSONRPCNotification,\n\tJSONRPCRequest,\n\tJSONRPCResponse,\n\tMCPCallResult,\n\tMCPCompletion,\n\tMCPCompletionManagerInterface,\n\tMCPCompletionParams,\n\tMCPDispatchOptions,\n\tMCPElicitation,\n\tMCPIdentity,\n\tMCPInputResult,\n\tMCPLimitOptions,\n\tMCPListResult,\n\tMCPMethodManagerInterface,\n\tMCPMethodOptions,\n\tMCPPaginationParams,\n\tMCPPromptGetParams,\n\tMCPPromptGetResult,\n\tMCPPromptManagerInterface,\n\tMCPPromptPage,\n\tMCPResourceManagerInterface,\n\tMCPResourcePage,\n\tMCPResourceReadParams,\n\tMCPResourceReadResult,\n\tMCPResourceTemplatePage,\n\tMCPServerEventMap,\n\tMCPServerInterface,\n\tMCPServerOptions,\n\tMCPStream,\n\tMCPStreamControllerInterface,\n\tMCPSubscriptionFilter,\n\tMCPTaskContext,\n\tMCPTaskManagerInterface,\n\tMCPTaskResult,\n\tMCPTextStreamControllerInterface,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isJSONValue, isRecord, isString, isUndefined, sanitizeBudget } from '@orkestrel/contract'\nimport { snapshotJSON, snapshotToolResult } from './cloners.js'\nimport {\n\tDEFAULT_MCP_CACHE_TTL,\n\tDEFAULT_MCP_LIMITS,\n\tEMPTY_MCP_ARGUMENTS,\n\tJSONRPC_INTERNAL_ERROR,\n\tJSONRPC_INVALID_PARAMS,\n\tJSONRPC_INVALID_REQUEST,\n\tJSONRPC_METHOD_NOT_FOUND,\n\tJSONRPC_PARSE_ERROR,\n\tMCP_EXTENSION_TASKS,\n\tMCP_META_SERVER,\n\tMCP_MISSING_CAPABILITY,\n\tMCP_UNSUPPORTED_VERSION,\n\tSUPPORTED_PROTOCOL_VERSIONS,\n} from './constants.js'\nimport {\n\tbuildDiscoverResult,\n\tbuildJSONRPCError,\n\tbuildJSONRPCResult,\n\tbuildMethodOptions,\n\tbuildModernResult,\n\tbuildSubscriptionAcknowledgement,\n\tbuildSubscriptionFilter,\n\tbuildSubscriptionResult,\n\tbuildToolCall,\n\tbuildToolDescriptors,\n\tdigestJSON,\n\tmatchesSubscriptionNotification,\n\tserializeJSON,\n\tstampSubscriptionNotification,\n} from './helpers.js'\nimport { inferEra } from './inferers.js'\nimport { MCPMethodManager } from './MCPMethodManager.js'\nimport { MCPProgressReporter } from './MCPProgressReporter.js'\nimport { MCPStreamController } from './MCPStreamController.js'\nimport { MCPTextStreamController } from './MCPTextStreamController.js'\nimport { parseJSONRPCMessage, parseMCPInputState, parseRequestContext } from './parsers.js'\nimport {\n\tisAbsoluteURI,\n\tisElicitContent,\n\tisMCPElicitForm,\n\tisMCPElicitResult,\n\tisBoundedJSON,\n\tisBoundedString,\n\tisFormElicitationSupported,\n\tisJSONRPCNotification,\n\tisMCPCallResult,\n\tisMCPCompletion,\n\tisMCPCompletionParams,\n\tisMCPInputResult,\n\tisMCPPaginationParams,\n\tisMCPPromptGetResult,\n\tisMCPPromptPage,\n\tisMCPResourceContents,\n\tisMCPResourcePage,\n\tisMCPResourceTemplatePage,\n\tisMCPStringArguments,\n\tisMCPSubscriptionFilter,\n\tisMCPTaskDetail,\n\tisMCPTaskResult,\n\tisTaskSupported,\n} from './validators.js'\n\n/**\n * A transport-agnostic Model Context Protocol server — dispatches JSON-RPC 2.0\n * requests over a live {@link ToolManagerInterface}, with NO transport coupling.\n *\n * @remarks\n * - **Two entry points.** `dispatch(invocation)` runs an already-parsed invocation and\n * resolves a {@link JSONRPCResponse} for a request — or `undefined` for a\n * {@link JSONRPCNotification}, which carries no `id` and is answered by nothing.\n * `handle(message)` is the string boundary: it\n * `JSON.parse`s the raw message (a failure → a `-32700` response), narrows it to\n * an invocation (a non-invocation → a `-32600` response, with the unreadable `id`\n * OMITTED rather than nulled), dispatches, and serializes the\n * response back to a string (`undefined` for a notification).\n * - **One modern seam.** `server/discover`, `tools/list`, `tools/call`, and\n * `subscriptions/listen` are always registered; `resources/*`, `prompts/*`, and\n * `completion/complete` register independently when their respective host ports are\n * configured — plus `tasks/get`, `tasks/update`, and `tasks/cancel` when the draft Tasks\n * extension is configured — and every method is resolved from the registry on\n * every dispatch: the same path a later method or a consumer's own takes, with an\n * unregistered method still answering `-32601`.\n * - **Provider-agnostic.** Imports only core siblings — JSON-RPC + the tool registry,\n * no HTTP, no model. Wire fields are narrowed via the contracts guards (no `as`).\n * - **Observable (§13).** The owned `emitter` fires `request` at the top of every\n * dispatch; the emitter isolates a listener throw and routes it to its `error` handler\n * (the `error` option), so a listener throw can never escape the dispatch.\n *\n * @example\n * ```ts\n * const tools = createToolManager()\n * tools.add(createTool({ name: 'add', execute: (a) => Number(a.x) + Number(a.y) }))\n * const server = new MCPServer({ identity: { name: 'demo', version: '1.0.0' }, tools })\n * await server.handle('{\"jsonrpc\":\"2.0\",\"method\":\"ping\",\"id\":1,\"params\":{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}}}')\n * // '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"resultType\":\"complete\",\"_meta\":{\"io.modelcontextprotocol/serverInfo\":{\"name\":\"demo\",\"version\":\"1.0.0\"}}}}'\n * ```\n */\nexport class MCPServer implements MCPServerInterface {\n\treadonly #emitter: Emitter<MCPServerEventMap>\n\treadonly #options: MCPServerOptions\n\treadonly #methods: MCPMethodManager\n\treadonly #limits: Required<MCPLimitOptions>\n\t#subscriptions = 0\n\n\tconstructor(options: MCPServerOptions) {\n\t\tthis.#emitter = new Emitter<MCPServerEventMap>({\n\t\t\t...(options.on !== undefined ? { on: options.on } : {}),\n\t\t\t...(options.error !== undefined ? { error: options.error } : {}),\n\t\t})\n\t\tthis.#options = options\n\t\t// Frozen because it is PUBLISHED (`limit`): the boundary checks below and whatever\n\t\t// stands in front of this server read one object, so a consumer cannot move a bound\n\t\t// out from under a check that already ran.\n\t\tthis.#limits = Object.freeze({\n\t\t\tmessage: sanitizeBudget(options.limit?.message, DEFAULT_MCP_LIMITS.message),\n\t\t\tmetadata: sanitizeBudget(options.limit?.metadata, DEFAULT_MCP_LIMITS.metadata),\n\t\t\tkeys: sanitizeBudget(options.limit?.keys, DEFAULT_MCP_LIMITS.keys),\n\t\t\tstate: sanitizeBudget(options.limit?.state, DEFAULT_MCP_LIMITS.state),\n\t\t\tcontent: sanitizeBudget(options.limit?.content, DEFAULT_MCP_LIMITS.content),\n\t\t\tsubscriptions: sanitizeBudget(options.limit?.subscriptions, DEFAULT_MCP_LIMITS.subscriptions),\n\t\t\tdepth: sanitizeBudget(options.limit?.depth, DEFAULT_MCP_LIMITS.depth),\n\t\t})\n\t\tthis.#methods = new MCPMethodManager()\n\t\tthis.#register()\n\t}\n\n\tget emitter(): EmitterInterface<MCPServerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget identity(): MCPIdentity {\n\t\treturn this.#options.identity\n\t}\n\n\tget methods(): MCPMethodManagerInterface {\n\t\treturn this.#methods\n\t}\n\n\tget limit(): Required<MCPLimitOptions> {\n\t\treturn this.#limits\n\t}\n\n\tdispatch(\n\t\trequest: JSONRPCRequest,\n\t\toptions?: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | MCPStreamControllerInterface>\n\tdispatch(notification: JSONRPCNotification, options?: MCPDispatchOptions): Promise<undefined>\n\tdispatch(\n\t\tinvocation: JSONRPCInvocation,\n\t\toptions?: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | MCPStreamControllerInterface | undefined>\n\tasync dispatch(\n\t\tinvocation: JSONRPCInvocation,\n\t\toptions: MCPDispatchOptions = {},\n\t): Promise<JSONRPCResponse | MCPStreamControllerInterface | undefined> {\n\t\tconst decoded = parseJSONRPCMessage(invocation, {\n\t\t\tbytes: this.#limits.message,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (decoded === undefined || !('method' in decoded)) {\n\t\t\treturn buildJSONRPCError(undefined, JSONRPC_INVALID_REQUEST, 'Invalid Request')\n\t\t}\n\t\treturn this.#dispatch(decoded, options)\n\t}\n\n\t// The ONE ingress. It resolves the caller's options into the options every method,\n\t// elicitation, principal, and subscription producer downstream observes, so the\n\t// request's cancellation signal is decided here and nowhere else — and it is the ONE\n\t// wrapping seam too: whatever a built-in or a consumer's own method produces, the stream\n\t// that leaves here is controlled, so cancellation is arbitrated in one place rather than\n\t// per producer.\n\tasync #dispatch(\n\t\tinvocation: JSONRPCInvocation,\n\t\toptions: MCPDispatchOptions,\n\t): Promise<JSONRPCResponse | MCPStreamControllerInterface | undefined> {\n\t\tthis.#emitter.emit('request', invocation.method, invocation.id, 'modern')\n\t\t// A NOTIFICATION is handled (the `request` event already fired) but NEVER produces\n\t\t// a response, whatever its method (`notifications/initialized`, a fire-and-forget\n\t\t// `ping`, an unknown method — all silent). So short-circuit here, and the branches\n\t\t// below only ever run for a request that expects a reply.\n\t\tif (invocation.id === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst id = invocation.id\n\t\tconst metadata = invocation.params?.['_meta']\n\t\tif (\n\t\t\tmetadata !== undefined &&\n\t\t\t!isBoundedJSON(metadata, {\n\t\t\t\tbytes: this.#limits.metadata,\n\t\t\t\tkeys: this.#limits.keys,\n\t\t\t\tdepth: this.#limits.depth,\n\t\t\t})\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `_meta` exceeds the configured limit or contains an unsafe value',\n\t\t\t)\n\t\t}\n\t\tconst closure = new AbortController()\n\t\tconst resolved = buildMethodOptions(options, closure.signal)\n\t\ttry {\n\t\t\tconst answer = await this.#modern(invocation, resolved)\n\t\t\treturn Symbol.asyncIterator in answer\n\t\t\t\t? new MCPStreamController(answer, resolved.signal, closure)\n\t\t\t\t: answer\n\t\t} catch (error) {\n\t\t\treturn this.#contain(error, id)\n\t\t}\n\t}\n\n\tasync handle(\n\t\tmessage: string,\n\t\toptions?: MCPDispatchOptions,\n\t): Promise<string | MCPTextStreamControllerInterface | undefined> {\n\t\tif (!isBoundedString(message, this.#limits.message)) {\n\t\t\treturn JSON.stringify(buildJSONRPCError(undefined, JSONRPC_PARSE_ERROR, 'Parse error'))\n\t\t}\n\t\tlet parsed: unknown\n\t\ttry {\n\t\t\tparsed = JSON.parse(message)\n\t\t} catch {\n\t\t\treturn JSON.stringify(buildJSONRPCError(undefined, JSONRPC_PARSE_ERROR, 'Parse error'))\n\t\t}\n\t\tconst decoded = parseJSONRPCMessage(parsed, {\n\t\t\tbytes: this.#limits.message,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\t// Only an INVOCATION is dispatchable — a response (or any non-message) is invalid input.\n\t\tif (decoded === undefined || !('method' in decoded)) {\n\t\t\treturn JSON.stringify(\n\t\t\t\tbuildJSONRPCError(undefined, JSONRPC_INVALID_REQUEST, 'Invalid Request'),\n\t\t\t)\n\t\t}\n\t\tconst answer = await this.#dispatch(decoded, options ?? {})\n\t\tif (answer === undefined) return undefined\n\t\t// The ONE narrowing point (§4.3): a held-open answer becomes the string mirror of\n\t\t// itself, so the string boundary stays a mirror of the typed core.\n\t\treturn Symbol.asyncIterator in answer\n\t\t\t? new MCPTextStreamController(answer)\n\t\t\t: JSON.stringify(answer)\n\t}\n\n\t// Register the built-in modern methods on the seam `#modern` resolves from — the\n\t// point of the seam is that they are not special: they are the first registrations,\n\t// and a later one (or a consumer's) replaces or joins them in place. The conditional\n\t// block at the end is the same statement about an OPT-IN surface: an extension that\n\t// was not configured adds no registration, so it is absent rather than refused.\n\t//\n\t// The seam carries the REQUEST arm, so no registration narrows anything: dispatch\n\t// short-circuits a notification before this registry is read at all, so every handler here\n\t// — and every handler a consumer adds — is invoked only for a call that expects an answer.\n\t// Each of these seven registrations once opened with an `invocation.id === undefined`\n\t// ternary answering `undefined` for a case that cannot arrive; the seam's own type now says\n\t// that, so the guards are gone rather than restated per member.\n\t//\n\t// Every registration DECLARES the resolved options, and every one that reaches a provider\n\t// hook spends them. The declared parameter is the seam itself and is what a caller can\n\t// observe of it: a registry whose members disagree about their own shape is several places\n\t// that happen to agree rather than one contract, and the member that never declared it is\n\t// the one whoever adds the first await has to re-plumb. `_options` therefore stays here,\n\t// where conformance needs it, and is absent from the two live registry reads below, where\n\t// nothing does.\n\t#register(): void {\n\t\tthis.#methods.add('ping', async (request, _options) =>\n\t\t\tbuildJSONRPCResult(request.id, buildModernResult({}, this.#options.identity)),\n\t\t)\n\t\tthis.#methods.add('server/discover', async (request, _options) => this.#discover(request))\n\t\tthis.#methods.add('tools/list', async (request, _options) => this.#list(request))\n\t\tthis.#methods.add('tools/call', async (request, options) => this.#call(request, options))\n\t\tthis.#methods.add('subscriptions/listen', async (request, options) =>\n\t\t\tthis.#subscribe(request, options),\n\t\t)\n\t\tconst resources = this.#options.resources\n\t\tif (resources !== undefined) {\n\t\t\tthis.#methods.add('resources/list', async (request, options) =>\n\t\t\t\tthis.#resources(request, resources, options),\n\t\t\t)\n\t\t\tthis.#methods.add('resources/read', async (request, options) =>\n\t\t\t\tthis.#read(request, resources, options),\n\t\t\t)\n\t\t\tthis.#methods.add('resources/templates/list', async (request, options) =>\n\t\t\t\tthis.#templates(request, resources, options),\n\t\t\t)\n\t\t}\n\t\tconst prompts = this.#options.prompts\n\t\tif (prompts !== undefined) {\n\t\t\tthis.#methods.add('prompts/list', async (request, options) =>\n\t\t\t\tthis.#prompts(request, prompts, options),\n\t\t\t)\n\t\t\tthis.#methods.add('prompts/get', async (request, options) =>\n\t\t\t\tthis.#prompt(request, prompts, options),\n\t\t\t)\n\t\t}\n\t\tconst completion = this.#options.completion\n\t\tif (completion !== undefined) {\n\t\t\tthis.#methods.add('completion/complete', async (request, options) =>\n\t\t\t\tthis.#suggest(request, completion, options),\n\t\t\t)\n\t\t}\n\t\t// The draft Tasks extension's three methods register ONLY when a consumer configured\n\t\t// the extension. An unconfigured server never registers them, so they resolve to nothing\n\t\t// and the modern branch answers `-32601` through the same unregistered-method path any\n\t\t// other unknown method takes — the honest reply from a server that does not implement an\n\t\t// optional extension, and the reason an unconfigured server is unchanged by all of this.\n\t\t//\n\t\t// The manager is captured HERE rather than read per request, because the registration is\n\t\t// already a snapshot of construction-time configuration: a handler that exists at all is\n\t\t// proof `task` was configured when this server was built, and reading a second, later\n\t\t// value would let the two disagree.\n\t\tconst configured = this.#options.task\n\t\tif (configured === undefined) return\n\t\tconst tasks = configured.tasks\n\t\tthis.#methods.add('tasks/get', async (request, options) => this.#task(request, tasks, options))\n\t\tthis.#methods.add('tasks/update', async (request, options) =>\n\t\t\tthis.#update(request, tasks, options),\n\t\t)\n\t\tthis.#methods.add('tasks/cancel', async (request, options) =>\n\t\t\tthis.#abort(request, tasks, options),\n\t\t)\n\t}\n\n\tasync #modern(\n\t\trequest: JSONRPCRequest,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse | MCPStream> {\n\t\tconst id = request.id\n\t\tconst context = parseRequestContext(request, {\n\t\t\tbytes: this.#limits.message,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (context === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: malformed modern request metadata',\n\t\t\t)\n\t\t}\n\t\tif (inferEra(context.version) === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tMCP_UNSUPPORTED_VERSION,\n\t\t\t\t`Unsupported protocol version: ${context.version}`,\n\t\t\t\t{ supported: SUPPORTED_PROTOCOL_VERSIONS, requested: context.version },\n\t\t\t)\n\t\t}\n\t\t// No blanket rejection of a continuation carrier on a non-tool method. Core owns the\n\t\t// carrier's SHAPE, BOUNDS, and OWNERSHIP for every invocation — a malformed one never\n\t\t// gets this far — and the continuation SEMANTICS belong to whoever registered the\n\t\t// method. A `prompts/get` this server refused to let a consumer implement was a limit\n\t\t// core had no standing to impose.\n\t\tconst handler = this.#methods.method(request.method)\n\t\tif (handler === undefined) {\n\t\t\treturn buildJSONRPCError(id, JSONRPC_METHOD_NOT_FOUND, `Method not found: ${request.method}`)\n\t\t}\n\t\tconst answer = await handler(request, options)\n\t\t// A registered method OWES this request an answer, and the seam's type says so — but the\n\t\t// registry is open, so the one thing this server cannot assume is that a consumer's\n\t\t// handler was typechecked against it. An absent answer is contained here rather than\n\t\t// forwarded, because forwarding it resolves `dispatch(request)` as `undefined` against an\n\t\t// overload that promises a response, and a transport with nothing to write holds the peer\n\t\t// until its own deadline expires. So it is a FAULT, reported once on `error` like every\n\t\t// other contained fault and answered with the same detail-free `-32603` envelope.\n\t\tif (answer === undefined) {\n\t\t\treturn this.#contain(\n\t\t\t\tnew Error(`MCP method '${request.method}' resolved no answer for a request`),\n\t\t\t\tid,\n\t\t\t)\n\t\t}\n\t\treturn answer\n\t}\n\n\t// The built-in `server/discover` handler: a live read of server configuration with no\n\t// await, so it has no cancellation point to spend the request's signal on and takes no\n\t// options. The uniform seam is the registration above, not this private leaf.\n\tasync #discover(request: JSONRPCRequest): Promise<JSONRPCResponse> {\n\t\treturn buildJSONRPCResult(request.id, buildDiscoverResult(this.#options))\n\t}\n\n\t// The built-in modern `tools/list` handler — a cacheable result, so it carries both\n\t// schema-coupled cache stamps. It takes no options for the same reason `#discover` takes\n\t// none: a live registry read with no await to cancel.\n\tasync #list(request: JSONRPCRequest): Promise<JSONRPCResponse> {\n\t\tconst result: MCPListResult = buildModernResult(\n\t\t\t{ tools: buildToolDescriptors(this.#options.tools) },\n\t\t\tthis.#options.identity,\n\t\t\tthis.#options.cache?.ttl ?? DEFAULT_MCP_CACHE_TTL,\n\t\t\tthis.#options.cache?.scope,\n\t\t)\n\t\treturn buildJSONRPCResult(request.id, result)\n\t}\n\n\t// The built-in modern `tools/call` handler — stamped, and NOT cacheable, so it\n\t// carries no cache fields.\n\tasync #resources(\n\t\trequest: JSONRPCRequest,\n\t\tmanager: MCPResourceManagerInterface,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tif (!isMCPPaginationParams(request.params ?? {})) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `cursor` must be a string when present',\n\t\t\t)\n\t\t}\n\t\tconst cursor = request.params?.['cursor']\n\t\tconst pagination: MCPPaginationParams = isString(cursor) ? { cursor } : {}\n\t\tconst page = await manager.resources(pagination, options)\n\t\tconst captured = snapshotJSON(page, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (captured === undefined || !isMCPResourcePage(captured[0])) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server resource manager returned an invalid or oversized page',\n\t\t\t)\n\t\t}\n\t\tconst owned: MCPResourcePage = captured[0]\n\t\tconst result = buildModernResult(\n\t\t\t{\n\t\t\t\tresources: owned.resources,\n\t\t\t\t...(owned.nextCursor === undefined ? {} : { nextCursor: owned.nextCursor }),\n\t\t\t},\n\t\t\tthis.#options.identity,\n\t\t\tthis.#options.cache?.ttl ?? DEFAULT_MCP_CACHE_TTL,\n\t\t\tthis.#options.cache?.scope,\n\t\t)\n\t\treturn buildJSONRPCResult(request.id, result)\n\t}\n\n\tasync #read(\n\t\trequest: JSONRPCRequest,\n\t\tmanager: MCPResourceManagerInterface,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tconst uri = request.params?.['uri']\n\t\tconst inputResponses = request.params?.['inputResponses']\n\t\tconst requestState = request.params?.['requestState']\n\t\tif (\n\t\t\t!isAbsoluteURI(uri) ||\n\t\t\t(!isUndefined(inputResponses) && !isRecord(inputResponses)) ||\n\t\t\t(!isUndefined(requestState) && !isBoundedString(requestState, this.#limits.state))\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `uri` is required and continuation fields must be valid when present',\n\t\t\t)\n\t\t}\n\t\tconst params: MCPResourceReadParams = {\n\t\t\turi,\n\t\t\t...(isRecord(inputResponses) ? { inputResponses } : {}),\n\t\t\t...(isString(requestState) ? { requestState } : {}),\n\t\t}\n\t\tconst read = await manager.resource(params, options)\n\t\tif (read === undefined) {\n\t\t\treturn buildJSONRPCError(request.id, JSONRPC_INVALID_PARAMS, `Resource not found: ${uri}`)\n\t\t}\n\t\tconst captured = snapshotJSON(read, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (captured === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server resource manager returned invalid or oversized contents',\n\t\t\t)\n\t\t}\n\t\tif (isMCPInputResult(captured[0])) {\n\t\t\tconst input: MCPInputResult = captured[0]\n\t\t\treturn buildJSONRPCResult(request.id, {\n\t\t\t\t...input,\n\t\t\t\t_meta: {\n\t\t\t\t\t...(input['_meta'] ?? {}),\n\t\t\t\t\t[MCP_META_SERVER]: this.#options.identity,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tif (\n\t\t\t!Array.isArray(captured[0]) ||\n\t\t\t!captured[0].every((entry) => isMCPResourceContents(entry))\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server resource manager returned invalid or oversized contents',\n\t\t\t)\n\t\t}\n\t\tconst result: MCPResourceReadResult = buildModernResult(\n\t\t\t{ contents: captured[0] },\n\t\t\tthis.#options.identity,\n\t\t\tthis.#options.cache?.ttl ?? DEFAULT_MCP_CACHE_TTL,\n\t\t\tthis.#options.cache?.scope,\n\t\t)\n\t\treturn buildJSONRPCResult(request.id, result)\n\t}\n\n\tasync #templates(\n\t\trequest: JSONRPCRequest,\n\t\tmanager: MCPResourceManagerInterface,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tif (!isMCPPaginationParams(request.params ?? {})) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `cursor` must be a string when present',\n\t\t\t)\n\t\t}\n\t\tconst cursor = request.params?.['cursor']\n\t\tconst pagination: MCPPaginationParams = isString(cursor) ? { cursor } : {}\n\t\tconst page = await manager.templates(pagination, options)\n\t\tconst captured = snapshotJSON(page, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (captured === undefined || !isMCPResourceTemplatePage(captured[0])) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server resource manager returned an invalid or oversized template page',\n\t\t\t)\n\t\t}\n\t\tconst owned: MCPResourceTemplatePage = captured[0]\n\t\tconst result = buildModernResult(\n\t\t\t{\n\t\t\t\tresourceTemplates: owned.resourceTemplates,\n\t\t\t\t...(owned.nextCursor === undefined ? {} : { nextCursor: owned.nextCursor }),\n\t\t\t},\n\t\t\tthis.#options.identity,\n\t\t\tthis.#options.cache?.ttl ?? DEFAULT_MCP_CACHE_TTL,\n\t\t\tthis.#options.cache?.scope,\n\t\t)\n\t\treturn buildJSONRPCResult(request.id, result)\n\t}\n\n\tasync #prompts(\n\t\trequest: JSONRPCRequest,\n\t\tmanager: MCPPromptManagerInterface,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tif (!isMCPPaginationParams(request.params ?? {})) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `cursor` must be a string when present',\n\t\t\t)\n\t\t}\n\t\tconst cursor = request.params?.['cursor']\n\t\tconst pagination: MCPPaginationParams = isString(cursor) ? { cursor } : {}\n\t\tconst page = await manager.prompts(pagination, options)\n\t\tconst captured = snapshotJSON(page, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (captured === undefined || !isMCPPromptPage(captured[0])) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server prompt manager returned an invalid or oversized page',\n\t\t\t)\n\t\t}\n\t\tconst owned: MCPPromptPage = captured[0]\n\t\tconst result = buildModernResult(\n\t\t\t{\n\t\t\t\tprompts: owned.prompts,\n\t\t\t\t...(owned.nextCursor === undefined ? {} : { nextCursor: owned.nextCursor }),\n\t\t\t},\n\t\t\tthis.#options.identity,\n\t\t\tthis.#options.cache?.ttl ?? DEFAULT_MCP_CACHE_TTL,\n\t\t\tthis.#options.cache?.scope,\n\t\t)\n\t\treturn buildJSONRPCResult(request.id, result)\n\t}\n\n\tasync #prompt(\n\t\trequest: JSONRPCRequest,\n\t\tmanager: MCPPromptManagerInterface,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tconst name = request.params?.['name']\n\t\tconst argumentsValue = request.params?.['arguments']\n\t\tconst inputResponses = request.params?.['inputResponses']\n\t\tconst requestState = request.params?.['requestState']\n\t\tif (\n\t\t\t!isString(name) ||\n\t\t\t(!isUndefined(argumentsValue) && !isMCPStringArguments(argumentsValue)) ||\n\t\t\t(!isUndefined(inputResponses) && !isRecord(inputResponses)) ||\n\t\t\t(!isUndefined(requestState) && !isBoundedString(requestState, this.#limits.state))\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `name` is required, argument values must be strings, and continuation fields must be valid when present',\n\t\t\t)\n\t\t}\n\t\tconst params: MCPPromptGetParams = {\n\t\t\tname,\n\t\t\t...(isMCPStringArguments(argumentsValue) ? { arguments: argumentsValue } : {}),\n\t\t\t...(isRecord(inputResponses) ? { inputResponses } : {}),\n\t\t\t...(isString(requestState) ? { requestState } : {}),\n\t\t}\n\t\tconst prompt = await manager.prompt(params, options)\n\t\tif (prompt === undefined) {\n\t\t\treturn buildJSONRPCError(request.id, JSONRPC_INVALID_PARAMS, `Prompt not found: ${name}`)\n\t\t}\n\t\tconst captured = snapshotJSON(prompt, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (captured === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server prompt manager returned an invalid or oversized result',\n\t\t\t)\n\t\t}\n\t\tif (isMCPInputResult(captured[0])) {\n\t\t\tconst input: MCPInputResult = captured[0]\n\t\t\treturn buildJSONRPCResult(request.id, {\n\t\t\t\t...input,\n\t\t\t\t_meta: {\n\t\t\t\t\t...(input['_meta'] ?? {}),\n\t\t\t\t\t[MCP_META_SERVER]: this.#options.identity,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tif (!isMCPPromptGetResult(captured[0])) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server prompt manager returned an invalid or oversized result',\n\t\t\t)\n\t\t}\n\t\tconst result: MCPPromptGetResult = captured[0]\n\t\treturn buildJSONRPCResult(request.id, {\n\t\t\t...result,\n\t\t\t_meta: {\n\t\t\t\t...(result['_meta'] ?? {}),\n\t\t\t\t[MCP_META_SERVER]: this.#options.identity,\n\t\t\t},\n\t\t})\n\t}\n\n\tasync #suggest(\n\t\trequest: JSONRPCRequest,\n\t\tmanager: MCPCompletionManagerInterface,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tconst input = request.params ?? {}\n\t\tif (!isMCPCompletionParams(input)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: a valid completion reference, string argument, and string context are required',\n\t\t\t)\n\t\t}\n\t\tconst params: MCPCompletionParams = {\n\t\t\tref: input.ref,\n\t\t\targument: input.argument,\n\t\t\t...(input.context === undefined ? {} : { context: input.context }),\n\t\t}\n\t\tconst generated = await manager.complete(params, options)\n\t\tif (generated === undefined) {\n\t\t\treturn buildJSONRPCError(request.id, JSONRPC_INVALID_PARAMS, 'Completion reference not found')\n\t\t}\n\t\tconst candidate: unknown = generated\n\t\tif (!isRecord(candidate) || !Array.isArray(candidate['values'])) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server completion manager returned invalid or oversized candidates',\n\t\t\t)\n\t\t}\n\t\tconst values = candidate['values']\n\t\tconst truncated = values.length > 100\n\t\tconst projected = {\n\t\t\tvalues: values.slice(0, 100),\n\t\t\t...(candidate['total'] === undefined ? {} : { total: candidate['total'] }),\n\t\t\t...(truncated\n\t\t\t\t? { hasMore: true }\n\t\t\t\t: candidate['hasMore'] === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { hasMore: candidate['hasMore'] }),\n\t\t}\n\t\tconst captured = snapshotJSON(projected, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (captured === undefined || !isMCPCompletion(captured[0])) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server completion manager returned invalid or oversized candidates',\n\t\t\t)\n\t\t}\n\t\tconst completion: MCPCompletion = captured[0]\n\t\treturn buildJSONRPCResult(request.id, {\n\t\t\tresultType: 'complete',\n\t\t\tcompletion,\n\t\t\t_meta: { [MCP_META_SERVER]: this.#options.identity },\n\t\t})\n\t}\n\n\tasync #call(\n\t\trequest: JSONRPCRequest,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse | MCPStream> {\n\t\tconst id = request.id\n\t\tconst params = request.params\n\t\tconst rawArguments = params?.['arguments']\n\t\tif (params !== undefined && Object.hasOwn(params, 'arguments') && !isRecord(rawArguments)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `arguments` must be an object when present',\n\t\t\t)\n\t\t}\n\t\t// ONE reference from here on: the digest, the input selector, the canonical call, and\n\t\t// the executor all read this exact object. An absent `arguments` resolves to the one\n\t\t// shared frozen record rather than a fresh empty object per call.\n\t\tconst args = isRecord(rawArguments) ? rawArguments : EMPTY_MCP_ARGUMENTS\n\t\tconst input = await this.#input(request, args, options)\n\t\tif (input !== undefined) return input\n\t\tconst call = buildToolCall(request, options.caller, args)\n\t\tif (call === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: a string `name` is required',\n\t\t\t)\n\t\t}\n\t\tconst deferred = await this.#defer(request, call, options)\n\t\tif (deferred !== undefined) return deferred\n\t\tconst token = params?.['_meta']\n\t\tconst progressToken = isRecord(token) ? token['progressToken'] : undefined\n\t\tif (\n\t\t\tthis.#options.execution !== undefined &&\n\t\t\t(isString(progressToken) ||\n\t\t\t\t(typeof progressToken === 'number' && Number.isInteger(progressToken)))\n\t\t) {\n\t\t\treturn this.#progress(request, call, progressToken, options)\n\t\t}\n\t\tconst result = await this.#execute(request, call, options.signal)\n\t\treturn 'jsonrpc' in result ? result : buildJSONRPCResult(id, result)\n\t}\n\n\t// The task decision, and the WHOLE of this server's half of the draft Tasks extension.\n\t//\n\t// Its position between `#input` and `#progress` is the ordering the extension implies.\n\t// MRTR runs FIRST because a call still asking its operator a question has not yet been\n\t// decided — deferring it would durably store a call whose arguments are not settled, and\n\t// the extension says pre-creation input belongs to the original request. Progress runs\n\t// LAST because the two are alternative answers to the same request: a deferred call has\n\t// no request-scoped stream left to report progress on, since the request ends the moment\n\t// the task handle is written.\n\t//\n\t// The server policy decides first whether this call is a task. A client that cannot accept\n\t// that selected outcome is then refused before the manager starts work; skipping the policy\n\t// would silently bypass deployment task policy rather than merely choose an inline result.\n\t//\n\t// Nothing about the task's WORK is here: no store, no timer, no status. All three belong\n\t// to the manager, which is also the only party that outlives this request.\n\tasync #defer(\n\t\trequest: JSONRPCRequest,\n\t\tcall: ToolCall,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse | undefined> {\n\t\tconst configured = this.#options.task\n\t\tif (configured === undefined) return undefined\n\t\tconst deferral: MCPTaskContext = { request, call, tools: this.#options.tools }\n\t\tconst key = await configured.defer(deferral, options)\n\t\t// `undefined` is the policy saying \"run this inline\", and it is the ONLY spelling of that.\n\t\t// An empty key cannot identify an operation, and a manager asked to deduplicate on one\n\t\t// collapses every deferred call onto a single task — so it is a FAULTY policy the\n\t\t// consumer hears about, not a second spelling of absence quietly routed down the inline\n\t\t// path where nobody would ever find it.\n\t\tif (isUndefined(key)) return undefined\n\t\tif (!isString(key) || key.length === 0) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server execution returned an invalid task key',\n\t\t\t)\n\t\t}\n\t\tconst context = parseRequestContext(request, {\n\t\t\tbytes: this.#limits.message,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (context === undefined || !isTaskSupported(context.capabilities)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\trequest.id,\n\t\t\t\tMCP_MISSING_CAPABILITY,\n\t\t\t\t'Client does not support the required Tasks extension',\n\t\t\t\t{ requiredCapabilities: { extensions: { [MCP_EXTENSION_TASKS]: {} } } },\n\t\t\t)\n\t\t}\n\t\t// AWAITED before the answer is built, which is this server's entire half of the\n\t\t// durability rule: whatever the manager must do to make the task retrievable, it has\n\t\t// done by the time a `taskId` exists to hand out.\n\t\tconst created = await configured.tasks.start(key, deferral, options)\n\t\t// Each declared member is read EXACTLY ONCE and nothing else is copied. That is the\n\t\t// ownership seam for this answer, and it is narrower than a JSON snapshot: a manager\n\t\t// that mutates the object it returned, answers differently on a second read, or hangs\n\t\t// extra keys off it changes neither the answer nor its size.\n\t\tconst result: MCPTaskResult = {\n\t\t\tresultType: 'task',\n\t\t\ttaskId: created.taskId,\n\t\t\tstatus: created.status,\n\t\t\t...(created.statusMessage === undefined ? {} : { statusMessage: created.statusMessage }),\n\t\t\tcreatedAt: created.createdAt,\n\t\t\tlastUpdatedAt: created.lastUpdatedAt,\n\t\t\tttlMs: created.ttlMs,\n\t\t\t...(created.pollIntervalMs === undefined ? {} : { pollIntervalMs: created.pollIntervalMs }),\n\t\t\t_meta: { [MCP_META_SERVER]: this.#options.identity },\n\t\t}\n\t\t// The projection bounds the SHAPE; this bounds the SIZE and re-proves the shape at\n\t\t// runtime, because the manager's declared types are a promise rather than a proof.\n\t\tconst captured = snapshotJSON(result, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\treturn captured !== undefined && isMCPTaskResult(captured[0])\n\t\t\t? buildJSONRPCResult(request.id, captured[0])\n\t\t\t: buildJSONRPCError(\n\t\t\t\t\trequest.id,\n\t\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t\t'Server execution returned an invalid or oversized task',\n\t\t\t\t)\n\t}\n\n\t// The resolved signal is already the request's LIFETIME — dispatch aborts it the moment\n\t// this stream closes — so the executor observes it directly and this method composes no\n\t// second cancellation source of its own.\n\tasync *#progress(\n\t\trequest: JSONRPCRequest,\n\t\tcall: ToolCall,\n\t\ttoken: string | number,\n\t\toptions: MCPMethodOptions,\n\t): MCPStream {\n\t\tconst signal = options.signal\n\t\tconst reporter = new MCPProgressReporter(\n\t\t\ttoken,\n\t\t\t{\n\t\t\t\tbytes: this.#limits.content,\n\t\t\t\tkeys: this.#limits.keys,\n\t\t\t\tdepth: this.#limits.depth,\n\t\t\t},\n\t\t\tsignal,\n\t\t)\n\t\tconst execution = this.#execute(request, call, signal, reporter)\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst outcome = await Promise.race([reporter.take(), execution])\n\t\t\t\tif ('method' in outcome) {\n\t\t\t\t\tyield outcome\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn 'jsonrpc' in outcome ? outcome : buildJSONRPCResult(request.id, outcome)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (signal.aborted) throw signal.reason ?? error\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tvoid execution.catch(() => undefined)\n\t\t\treporter.stop()\n\t\t}\n\t}\n\n\tasync #execute(\n\t\trequest: JSONRPCRequest,\n\t\tcall: ToolCall,\n\t\tsignal: AbortSignal,\n\t\tprogress?: MCPProgressReporter,\n\t): Promise<MCPCallResult | JSONRPCResponse> {\n\t\tlet result: unknown\n\t\ttry {\n\t\t\tresult =\n\t\t\t\tthis.#options.execution === undefined\n\t\t\t\t\t? await this.#options.tools.execute(call)\n\t\t\t\t\t: await this.#options.execution({\n\t\t\t\t\t\t\trequest,\n\t\t\t\t\t\t\tcall,\n\t\t\t\t\t\t\ttools: this.#options.tools,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t...(progress === undefined ? {} : { progress }),\n\t\t\t\t\t\t})\n\t\t} catch (error) {\n\t\t\treturn this.#contain(error, request.id)\n\t\t}\n\t\tconst captured = snapshotJSON(result, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (captured !== undefined && isMCPCallResult(captured[0])) return captured[0]\n\t\treturn this.#normalize(captured?.[0] ?? result, request.id)\n\t}\n\n\t// The built-in modern `tools/call` input mechanism, and the FIRST round of it. It is\n\t// deliberately reachable only from `#call`: the other modern handlers cannot produce\n\t// `input_required`.\n\t//\n\t// Order is the whole security property here, and it is: selector, own, capability,\n\t// principal, seal. The selector runs before the capability is known to be needed, because\n\t// only a selector that ASKS for input makes the client's form capability relevant at all;\n\t// everything after it runs only once the answer is yes.\n\tasync #input(\n\t\trequest: JSONRPCRequest,\n\t\targs: Readonly<Record<string, unknown>>,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse | undefined> {\n\t\tconst configured = this.#options.input\n\t\tif (configured === undefined) return undefined\n\t\tconst id = request.id\n\t\tconst params = request.params\n\t\tconst name = params?.['name']\n\t\tif (!isString(name)) return undefined\n\t\tconst digest = await digestJSON(args, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (digest === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: tool arguments are too large or unsafe',\n\t\t\t)\n\t\t}\n\t\tif (params?.['requestState'] !== undefined || params?.['inputResponses'] !== undefined) {\n\t\t\treturn this.#retry(request, name, digest, args, options)\n\t\t}\n\t\tconst elicitation = await configured.elicit({ request, name, arguments: args }, options)\n\t\tif (elicitation === undefined) return undefined\n\t\tconst form = this.#form(elicitation)\n\t\tconst context = parseRequestContext(request, {\n\t\t\tbytes: this.#limits.message,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (form === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: elicitation policy returned an invalid form or continuation context',\n\t\t\t)\n\t\t}\n\t\tif (context === undefined || !isFormElicitationSupported(context.capabilities)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tMCP_MISSING_CAPABILITY,\n\t\t\t\t'Server requires the elicitation capability for this request',\n\t\t\t\t{ requiredCapabilities: { elicitation: {} } },\n\t\t\t)\n\t\t}\n\t\tconst principal = await configured.principal(request, options)\n\t\treturn this.#required(request, name, digest, form, principal, id, undefined)\n\t}\n\n\t// The retry ingress and its verification. Capability stands ahead of BOTH providers, and\n\t// every structural binding is verified before the principal resolver runs: a retry this\n\t// server was always going to refuse must not cost a continuation open, a principal\n\t// lookup, or whatever audit record either of those writes.\n\t//\n\t// The failure taxonomy is deliberate. A carrier the port cannot recover is the CLIENT's\n\t// invalid state; a port that throws, or that opens successfully onto a payload this server\n\t// never authored, is the PROVIDER's contract failure — the client never wrote those bytes\n\t// and cannot act on being told they were wrong.\n\tasync #retry(\n\t\trequest: JSONRPCRequest,\n\t\tname: string,\n\t\tdigest: string,\n\t\targs: Readonly<Record<string, unknown>>,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse | undefined> {\n\t\tconst configured = this.#options.input\n\t\tif (configured === undefined) return undefined\n\t\tconst id = request.id\n\t\tconst requestState = request.params?.['requestState']\n\t\tconst inputResponses = request.params?.['inputResponses']\n\t\tif (!isBoundedString(requestState, this.#limits.state) || !isRecord(inputResponses)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: `inputResponses` and `requestState` are required together',\n\t\t\t)\n\t\t}\n\t\tconst context = parseRequestContext(request, {\n\t\t\tbytes: this.#limits.message,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (context === undefined || !isFormElicitationSupported(context.capabilities)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tMCP_MISSING_CAPABILITY,\n\t\t\t\t'Server requires the elicitation capability for this request',\n\t\t\t\t{ requiredCapabilities: { elicitation: {} } },\n\t\t\t)\n\t\t}\n\t\tconst verified = await configured.continuation.open(requestState)\n\t\tif (verified === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state could not be recovered',\n\t\t\t)\n\t\t}\n\t\tif (!isBoundedString(verified, this.#limits.state) || verified.length === 0) {\n\t\t\treturn this.#contain(\n\t\t\t\tnew Error('Continuation port opened a value outside the configured state bound'),\n\t\t\t\tid,\n\t\t\t)\n\t\t}\n\t\tconst state = parseMCPInputState(verified)\n\t\tif (state === undefined) {\n\t\t\treturn this.#contain(new Error('Continuation port opened a malformed protected payload'), id)\n\t\t}\n\t\t// Extra response keys are IGNORED: the server assigned exactly one key and cares about\n\t\t// exactly that one, so a client batching unrelated answers is not refused for it.\n\t\tconst response = inputResponses[state.key]\n\t\tif (\n\t\t\tstate.expiry <= Date.now() ||\n\t\t\tstate.id === id ||\n\t\t\tstate.version !== context.version ||\n\t\t\tstate.method !== request.method ||\n\t\t\tstate.name !== name ||\n\t\t\tstate.digest !== digest ||\n\t\t\t!Object.hasOwn(inputResponses, state.key)\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state could not be verified for this retry',\n\t\t\t)\n\t\t}\n\t\t// The issued schema is enforced, not merely carried: an accepted response answers the\n\t\t// question that was actually asked, or it is not accepted.\n\t\tif (\n\t\t\t!isMCPElicitResult(response) ||\n\t\t\t(response.action === 'accept' && !isElicitContent(response.content ?? {}, state.schema))\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: the elicitation response is missing or malformed',\n\t\t\t)\n\t\t}\n\t\tconst principal = await configured.principal(request, options)\n\t\tif (!isString(principal) || principal.length === 0 || state.principal !== principal) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state could not be verified for this retry',\n\t\t\t)\n\t\t}\n\t\tconst elicitation = await configured.elicit(\n\t\t\t{\n\t\t\t\trequest,\n\t\t\t\tname,\n\t\t\t\targuments: args,\n\t\t\t\tresponse,\n\t\t\t\t...(state.state !== undefined ? { state: state.state } : {}),\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\t// The recheck after the LAST provider await, and so also the one immediately before\n\t\t// execution: a continuation that lapsed while a provider was parked must not reach the\n\t\t// tool, and the window is a wall-clock deadline rather than a one-time admission.\n\t\tif (state.expiry <= Date.now()) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state could not be verified for this retry',\n\t\t\t)\n\t\t}\n\t\tif (elicitation === undefined) return undefined\n\t\tconst form = this.#form(elicitation)\n\t\tif (form === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: elicitation policy returned an invalid form or continuation context',\n\t\t\t)\n\t\t}\n\t\t// The ORIGINAL id and the prior window travel into the next round: the id because a\n\t\t// multi-round exchange is one correlated call, the window because a further round\n\t\t// EXTENDS a continuation rather than resurrecting one.\n\t\treturn this.#required(request, name, digest, form, principal, state.id, state.expiry)\n\t}\n\n\t// Own the selector's output the moment it is produced. The issued form and its schema are\n\t// snapshotted and frozen HERE, before capability, principal, or seal, so a provider that\n\t// mutates what it returned changes neither the question the client is asked nor the schema\n\t// the sealed state binds — the two would otherwise be free to disagree.\n\t#form(elicitation: unknown): MCPElicitation | undefined {\n\t\tconst owned = snapshotJSON(elicitation, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (owned === undefined || !isRecord(owned[0])) return undefined\n\t\tconst form = owned[0]['request']\n\t\tconst state = owned[0]['state']\n\t\tif (!isMCPElicitForm(form) || (!isUndefined(state) && !isJSONValue(state))) return undefined\n\t\treturn isUndefined(state) ? { request: form } : { request: form, state }\n\t}\n\n\t// Build one form-mode round and seal the call-in-hand state. The random map key is\n\t// minted here, never accepted from the consumer, and is carried inside protected state.\n\t// `origin` is the FIRST round's id, which stays bound however many rounds follow;\n\t// `previous` is the window a further round is extending, rechecked around the seal await.\n\tasync #required(\n\t\trequest: JSONRPCRequest,\n\t\tname: string,\n\t\tdigest: string,\n\t\tform: MCPElicitation,\n\t\tprincipal: unknown,\n\t\torigin: JSONRPCId,\n\t\tprevious: number | undefined,\n\t): Promise<JSONRPCResponse> {\n\t\tconst id = request.id\n\t\tconst configured = this.#options.input\n\t\tconst context = parseRequestContext(request, {\n\t\t\tbytes: this.#limits.message,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (\n\t\t\tconfigured === undefined ||\n\t\t\tcontext === undefined ||\n\t\t\t!isString(principal) ||\n\t\t\tprincipal.length === 0 ||\n\t\t\t!Number.isFinite(configured.ttl) ||\n\t\t\tconfigured.ttl <= 0\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: elicitation policy returned an invalid form or continuation context',\n\t\t\t)\n\t\t}\n\t\tif (previous !== undefined && previous <= Date.now()) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state could not be verified for this retry',\n\t\t\t)\n\t\t}\n\t\tconst key = crypto.randomUUID()\n\t\tconst expiry = Date.now() + configured.ttl\n\t\tconst protectedState = {\n\t\t\tprincipal,\n\t\t\texpiry,\n\t\t\tid: origin,\n\t\t\tversion: context.version,\n\t\t\tmethod: request.method,\n\t\t\tkey,\n\t\t\tname,\n\t\t\tdigest,\n\t\t\tschema: form.request.requestedSchema,\n\t\t\t...(form.state !== undefined ? { state: form.state } : {}),\n\t\t}\n\t\tif (\n\t\t\t!isBoundedJSON(protectedState, {\n\t\t\t\tbytes: this.#limits.state,\n\t\t\t\tdepth: this.#limits.depth,\n\t\t\t})\n\t\t) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state exceeds the configured limit',\n\t\t\t)\n\t\t}\n\t\tconst serialized = serializeJSON(protectedState, {\n\t\t\tbytes: this.#limits.state,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (serialized === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state exceeds the configured limit',\n\t\t\t)\n\t\t}\n\t\tconst requestState = await configured.continuation.seal(serialized)\n\t\tif (!isBoundedString(requestState, this.#limits.state) || requestState.length === 0) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: request state exceeds the configured limit',\n\t\t\t)\n\t\t}\n\t\t// Around the seal await, both windows: the one just minted, and the one this round is\n\t\t// extending. A port that took longer to protect the state than the state was good for\n\t\t// must not hand the client a round already dead on arrival. The two windows are also two\n\t\t// different things to say: a FIRST round has no retry to refuse, and telling that caller\n\t\t// its state failed verification points it at a round it never made.\n\t\tif (expiry <= Date.now() || (previous !== undefined && previous <= Date.now())) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\tprevious === undefined\n\t\t\t\t\t? 'Invalid params: request state expired before it could be issued'\n\t\t\t\t\t: 'Invalid params: request state could not be verified for this retry',\n\t\t\t)\n\t\t}\n\t\treturn buildJSONRPCResult(id, {\n\t\t\tresultType: 'input_required',\n\t\t\tinputRequests: {\n\t\t\t\t[key]: {\n\t\t\t\t\tmethod: 'elicitation/create',\n\t\t\t\t\tparams: { ...form.request, mode: 'form' },\n\t\t\t\t},\n\t\t\t},\n\t\t\trequestState,\n\t\t\t_meta: { [MCP_META_SERVER]: this.#options.identity },\n\t\t})\n\t}\n\n\t// The built-in modern `subscriptions/listen` handler validates the client's filter,\n\t// then returns the event-driven generator that owns acknowledgement and closure order.\n\tasync #subscribe(\n\t\trequest: JSONRPCRequest,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse | MCPStream> {\n\t\tconst id = request.id\n\t\tconst requested = request.params?.['notifications']\n\t\tif (!isMCPSubscriptionFilter(requested)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: a valid `notifications` filter is required',\n\t\t\t)\n\t\t}\n\t\treturn this.#subscription(requested, id, options)\n\t}\n\n\tasync *#subscription(\n\t\trequested: MCPSubscriptionFilter,\n\t\tid: JSONRPCId,\n\t\toptions: MCPMethodOptions,\n\t): MCPStream {\n\t\tif (this.#subscriptions >= this.#limits.subscriptions) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server limit reached: too many live subscriptions',\n\t\t\t)\n\t\t}\n\t\tthis.#subscriptions += 1\n\t\t// Capacity is returned on the ONE event that always happens: the end of the exchange.\n\t\t// It CANNOT be returned by the `finally` alone, because the `finally` requires this\n\t\t// generator to resume, and the steady state of a live subscription is parked inside\n\t\t// `await iterator.next()` on a producer suspended in its own await — where the consumer's\n\t\t// `throw()` and this generator's own `return()` are both queued behind a `next()` nobody\n\t\t// will answer. `MCPStreamController` aborts the request's lifetime from every closure it\n\t\t// has, so this signal fires for a completed exchange, a failed producer, a `stop()`, and\n\t\t// a vanished client alike. The controller is the once-flag: `abort()` is idempotent and\n\t\t// its listener runs at most once, so the `finally` below is the same release, not a\n\t\t// second one.\n\t\tconst slot = new AbortController()\n\t\tslot.signal.addEventListener('abort', () => void (this.#subscriptions -= 1), { once: true })\n\t\tif (options.signal.aborted) slot.abort()\n\t\telse options.signal.addEventListener('abort', () => slot.abort(), { once: true })\n\t\ttry {\n\t\t\tconst configured = this.#options.subscription\n\t\t\tconst notifications = buildSubscriptionFilter(requested, configured?.notifications ?? {})\n\t\t\tyield buildSubscriptionAcknowledgement(notifications, id)\n\t\t\tif (configured !== undefined) {\n\t\t\t\tconst source = await configured.listen(notifications, options)\n\t\t\t\tconst iterator = source[Symbol.asyncIterator]()\n\t\t\t\t// The iterator is held rather than hidden inside `for await` because ending the\n\t\t\t\t// ITERATOR is the only cleanup this loop can still ask of a producer parked on its\n\t\t\t\t// own event source. It is an ASK, not a guarantee: a producer suspended inside its\n\t\t\t\t// own await queues that `return()` behind it and may never run it — which is why\n\t\t\t\t// nothing after the park is load-bearing here, and why the slot is returned from\n\t\t\t\t// the signal above rather than from anything this loop reaches.\n\t\t\t\toptions.signal.addEventListener(\n\t\t\t\t\t'abort',\n\t\t\t\t\t() => void iterator.return?.(undefined)?.catch(() => undefined),\n\t\t\t\t\t{ once: true },\n\t\t\t\t)\n\t\t\t\tfor (let next = await iterator.next(); next.done !== true; next = await iterator.next()) {\n\t\t\t\t\t// Own the produced object BEFORE any decision reads it. The matcher and the\n\t\t\t\t\t// stamper each read `method`, `params.uri`, and `params._meta`; a hostile\n\t\t\t\t\t// producer answering differently per read would otherwise have one value admit\n\t\t\t\t\t// the notification and another value ride out on the wire.\n\t\t\t\t\tconst owned = parseJSONRPCMessage(next.value, {\n\t\t\t\t\t\tbytes: this.#limits.message,\n\t\t\t\t\t\tdepth: this.#limits.depth,\n\t\t\t\t\t})\n\t\t\t\t\tif (owned === undefined || !isJSONRPCNotification(owned)) continue\n\t\t\t\t\tif (matchesSubscriptionNotification(owned, notifications)) {\n\t\t\t\t\t\tyield stampSubscriptionNotification(owned, id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn buildSubscriptionResult(id, this.#options.identity)\n\t\t} catch (error) {\n\t\t\t// An abort is a cancellation, not a fault: it produces no terminal and reports\n\t\t\t// nothing. Anything else is the producer failing while the request was still live,\n\t\t\t// which the client learns as one detail-free terminal.\n\t\t\tif (options.signal.aborted) throw error\n\t\t\treturn this.#contain(error, id)\n\t\t} finally {\n\t\t\tslot.abort()\n\t\t}\n\t}\n\n\t// THE SHARED INGRESS of all three `tasks/*` methods: the capability the extension requires\n\t// on every one of them, then the handle they all name. It answers the validated `taskId` or\n\t// the refusal that ends the request, and a `string` is the WHOLE discriminator — so nothing\n\t// a consumer's manager can produce is ever mistaken for an envelope this server built.\n\t//\n\t// The capability is checked FIRST and unconditionally, because the extension binds it to the\n\t// METHOD rather than to one call's parameters: a client that never declared the extension is\n\t// refused before its parameters are read at all. The code is the GENERIC\n\t// missing-required-client-capability code, the same one the elicitation path answers — the\n\t// two are told apart by `data.requiredCapabilities` alone, because they are two instances of\n\t// one condition rather than two conditions. (The extension's own draft prose still shows\n\t// `-32003` in examples; the dated core schema fixes `-32021`, and a peer implements the\n\t// dated schema.)\n\t#named(request: JSONRPCRequest): string | JSONRPCErrorResponse {\n\t\tconst id = request.id\n\t\tconst context = parseRequestContext(request, {\n\t\t\tbytes: this.#limits.message,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (context === undefined || !isTaskSupported(context.capabilities)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tMCP_MISSING_CAPABILITY,\n\t\t\t\t'Server requires the tasks extension capability for this request',\n\t\t\t\t{ requiredCapabilities: { extensions: { [MCP_EXTENSION_TASKS]: {} } } },\n\t\t\t)\n\t\t}\n\t\t// Bounded by the same budget a protected `requestState` spends: both are opaque handles a\n\t\t// client echoes back, and neither has a length this package gets to choose.\n\t\tconst taskId = request.params?.['taskId']\n\t\tif (!isBoundedString(taskId, this.#limits.state) || taskId.length === 0) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: a bounded string `taskId` is required',\n\t\t\t)\n\t\t}\n\t\treturn taskId\n\t}\n\n\t// The built-in `tasks/get` handler — the ONE read of a durable task, and the only one of the\n\t// three that puts a manager's value on the wire.\n\t//\n\t// The refusal for a `taskId` that resolved to nothing is byte-identical here, on\n\t// `tasks/update`, and on `tasks/cancel`, and it is the same answer for a task that never\n\t// existed, one whose TTL purged it, and one this caller is not entitled to see: the port\n\t// answers `undefined` for all three, so this server cannot tell them apart even in\n\t// principle. That is what makes a `taskId` unprobeable — a second code, or a second message,\n\t// would turn the manager's store into an enumeration oracle.\n\t//\n\t// The snapshot bounds and owns the manager's answer BEFORE the stamp, because the manager is\n\t// the untrusted half: `resultType: 'complete'` and the server identity are this server's own\n\t// and add a fixed, tiny amount that a consumer's content budget should not have to fund.\n\tasync #task(\n\t\trequest: JSONRPCRequest,\n\t\ttasks: MCPTaskManagerInterface,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tconst id = request.id\n\t\tconst named = this.#named(request)\n\t\tif (!isString(named)) return named\n\t\tconst found = await tasks.task(named, options)\n\t\tif (found === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: no task is available for that `taskId`',\n\t\t\t)\n\t\t}\n\t\tconst owned = snapshotJSON(found, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (owned === undefined || !isMCPTaskDetail(owned[0])) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server execution returned an invalid or oversized task',\n\t\t\t)\n\t\t}\n\t\t// `complete`, not `task`. Only the CREATION answer carries `resultType: 'task'`; reading\n\t\t// a task is an ordinary completed method call whose payload happens to be a task.\n\t\treturn buildJSONRPCResult(id, buildModernResult(owned[0], this.#options.identity))\n\t}\n\n\t// The built-in `tasks/update` handler — the client answering the input requests an\n\t// `input_required` task published.\n\t//\n\t// The responses are forwarded VERBATIM. Which keys a task recognizes is the task's own\n\t// knowledge and this server holds none of it, so a key the task never published and a key\n\t// it has already answered are the manager's to IGNORE rather than this server's to refuse.\n\t// A server that guessed would refuse a legal update the moment a manager published a new key.\n\t// The record itself needs no snapshot: `params` arrived bounded, frozen, and owned from the\n\t// single parse at ingress.\n\t//\n\t// Note what this is NOT. It is a second multi-round-trip mechanism, and it carries none of\n\t// the protections the elicitation one does — no `requestState`, no argument digest, no\n\t// expiry, no principal binding — because MCP does not own the task's input channel. The\n\t// manager does, and every one of those bindings would have to be the manager's.\n\t//\n\t// The read below is PROVEN with the same guard `tasks/get` proves its answer with, not\n\t// merely compared against `undefined`. `update` answers `void`, so a read this method\n\t// accepts is a write it authorized, and `undefined` is only ONE of the ways an\n\t// implementation of this port says \"no such task\" — `null` is the ordinary JavaScript\n\t// spelling and the declared return type is a promise rather than a proof. Anything that\n\t// is not a well-formed task is not a task this caller may act on, and the refusal stays\n\t// byte-identical to the one an unknown `taskId` earns.\n\tasync #update(\n\t\trequest: JSONRPCRequest,\n\t\ttasks: MCPTaskManagerInterface,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tconst id = request.id\n\t\tconst named = this.#named(request)\n\t\tif (!isString(named)) return named\n\t\tconst responses = request.params?.['inputResponses']\n\t\tif (!isRecord(responses)) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: an `inputResponses` object is required',\n\t\t\t)\n\t\t}\n\t\tif (!isMCPTaskDetail(await tasks.task(named, options))) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: no task is available for that `taskId`',\n\t\t\t)\n\t\t}\n\t\tawait tasks.update(named, responses, options)\n\t\treturn buildJSONRPCResult(id, buildModernResult({}, this.#options.identity))\n\t}\n\n\t// The built-in `tasks/cancel` handler. Cancellation is ADVISORY: this server ASKS, and the\n\t// acknowledgement reports that the request was accepted, never that the task stopped. A\n\t// manager whose work cannot be interrupted — or whose task already finished — legally reaches\n\t// `completed` afterwards, and this server asserts nothing about which happened.\n\t//\n\t// The `task` read that precedes it is the existence-and-authorization probe, not a state\n\t// machine: `abort` answers `void`, so it has no way to say \"unknown\" and the probe is the\n\t// only place either fact can be established. That is why the read is PROVEN with the same\n\t// guard `tasks/get` proves its answer with rather than compared against `undefined`: a\n\t// probe accepting any value a manager happened to return authorizes a cancellation of a\n\t// task nobody proved exists. Nothing here reads `status`, because there is no transition\n\t// logic in this package to hold one.\n\tasync #abort(\n\t\trequest: JSONRPCRequest,\n\t\ttasks: MCPTaskManagerInterface,\n\t\toptions: MCPMethodOptions,\n\t): Promise<JSONRPCResponse> {\n\t\tconst id = request.id\n\t\tconst named = this.#named(request)\n\t\tif (!isString(named)) return named\n\t\tif (!isMCPTaskDetail(await tasks.task(named, options))) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t'Invalid params: no task is available for that `taskId`',\n\t\t\t)\n\t\t}\n\t\tawait tasks.abort(named, options)\n\t\treturn buildJSONRPCResult(id, buildModernResult({}, this.#options.identity))\n\t}\n\n\t// The ONE containment seam. Every fault the server catches passes through here exactly\n\t// once, and the two halves of containment happen together so they cannot drift apart: the\n\t// caught value goes to the application on `error`, and the peer gets a detail-free envelope.\n\t#contain(error: unknown, id: JSONRPCId): JSONRPCErrorResponse {\n\t\tthis.#emitter.emit('error', error)\n\t\treturn buildJSONRPCError(id, JSONRPC_INTERNAL_ERROR, 'Server error')\n\t}\n\n\t#normalize(result: unknown, id: JSONRPCId): MCPCallResult | JSONRPCResponse {\n\t\tconst snapshot = snapshotToolResult(result, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tif (snapshot === undefined) {\n\t\t\treturn buildJSONRPCError(\n\t\t\t\tid,\n\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t'Server execution returned an invalid tool result',\n\t\t\t)\n\t\t}\n\t\tconst owned = snapshot[0]\n\t\tlet payload: Readonly<Record<string, JSONValue>>\n\t\tif (!owned.success) {\n\t\t\tpayload = { content: [{ type: 'text', text: owned.error }], isError: true }\n\t\t} else if (owned.value === undefined) {\n\t\t\tpayload = { content: [{ type: 'text', text: '' }] }\n\t\t} else {\n\t\t\tconst text = snapshot[1]\n\t\t\t// UNREACHABLE at runtime, and kept anyway: `snapshotToolResult` pairs a defined\n\t\t\t// success with the canonical text and the owned value of ONE `snapshotJSON`, so a\n\t\t\t// defined `owned.value` always arrives with its string and always is exact JSON.\n\t\t\t// `ToolSuccess.value` is nevertheless declared `unknown`, so this is the narrowing\n\t\t\t// that reaches `structuredContent` without an assertion. Deleting it would require\n\t\t\t// one, and silently omitting `structuredContent` instead would answer a shape the\n\t\t\t// tool did not produce. Line-scoped mutation confirms it: flipping this code is the\n\t\t\t// only modern emission the fault sweep cannot kill. Narrowing `ToolResult['value']`\n\t\t\t// upstream is what would remove it.\n\t\t\tif (text === undefined || !isJSONValue(owned.value)) {\n\t\t\t\treturn buildJSONRPCError(\n\t\t\t\t\tid,\n\t\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t\t'Server could not serialize tool content',\n\t\t\t\t)\n\t\t\t}\n\t\t\tpayload = {\n\t\t\t\tcontent: [{ type: 'text', text }],\n\t\t\t\tstructuredContent: owned.value,\n\t\t\t}\n\t\t}\n\t\tconst captured = snapshotJSON(payload, {\n\t\t\tbytes: this.#limits.content,\n\t\t\tkeys: this.#limits.keys,\n\t\t\tdepth: this.#limits.depth,\n\t\t})\n\t\tconst candidate =\n\t\t\tcaptured !== undefined && isRecord(captured[0])\n\t\t\t\t? buildModernResult(captured[0], this.#options.identity)\n\t\t\t\t: undefined\n\t\treturn candidate !== undefined && isMCPCallResult(candidate)\n\t\t\t? candidate\n\t\t\t: buildJSONRPCError(\n\t\t\t\t\tid,\n\t\t\t\t\tJSONRPC_INTERNAL_ERROR,\n\t\t\t\t\t'Server limit exceeded: tool content is too large or unsafe',\n\t\t\t\t)\n\t}\n}\n","import type {\n\tMCPRequestFunction,\n\tMCPTaskClientInterface,\n\tMCPTaskClientOptions,\n\tMCPTaskDetail,\n} from './types.js'\nimport { JSONRPC_INVALID_PARAMS } from './constants.js'\nimport { MCPError } from './errors.js'\nimport { isMCPTaskDetail } from './validators.js'\n\n/**\n * The CLIENT half of the draft Tasks extension — the three `tasks/*` methods over one\n * correlated-request door, exposed as an {@link import('./types.js').MCPClientInterface}'s\n * `tasks`.\n *\n * @remarks\n * - **The mirror of the server-side port, minus `start`.** An\n * {@link import('./types.js').MCPTaskManagerInterface} is the consumer's durable store the\n * SERVER creates tasks in; this is the client's read/answer/stop access to the tasks a peer\n * already created. Creation is missing on purpose: the extension gives a client no flag and\n * no parameter to ask for a task, so `start` has no wire method to be.\n * - **No plural accessor, no loop, no cache.** MCP defines no `tasks/list`, so nothing here\n * enumerates. A task snapshot's `pollIntervalMs` is carried untouched and a one-shot read\n * sits beside it; the SCHEDULE is the consumer's, because this package has no durable place\n * to keep a task, no idea when the application still cares, and no lifetime to hang a timer\n * on that outlives the request it was born from. An instance left alone writes nothing.\n * - **One channel.** Every request goes through the injected\n * {@link import('./types.js').MCPRequestFunction}, so a task read shares the issuing\n * client's id space, pending table, deadline policy, and `disconnect` drain rather than\n * opening a second path to the same peer.\n * - **The peer authorizes.** Nothing is checked locally. A server that never configured the\n * extension answers all three `-32601`, and a task that never existed, one whose TTL purged\n * it, and one belonging to another principal are all the same `-32602` — a refusal this\n * client passes on rather than resolving into a distinction the peer refused to publish.\n *\n * @example\n * ```ts\n * const outcome = await client.call('render', { page: 3 })\n * if (outcome.resultType === 'task') {\n * \t// `outcome.pollIntervalMs` is the peer's HINT — the schedule is yours to run.\n * \tconst detail = await client.tasks.task(outcome.taskId)\n * \tif (detail.status === 'input_required') await client.tasks.update(outcome.taskId, { ok: true })\n * \telse if (detail.status === 'working') await client.tasks.abort(outcome.taskId)\n * }\n * ```\n */\nexport class MCPTaskClient implements MCPTaskClientInterface {\n\treadonly #request: MCPRequestFunction\n\treadonly #timeout: number | undefined\n\n\tconstructor(options: MCPTaskClientOptions) {\n\t\tthis.#request = options.request\n\t\tthis.#timeout = options.timeout\n\t}\n\n\tasync task(id: string): Promise<MCPTaskDetail> {\n\t\tconst result = await this.#request('tasks/get', { taskId: id }, this.#timeout)\n\t\t// PROVEN, not assumed. The peer is the untrusted half here exactly as a consumer's\n\t\t// manager is on the server side, and the same guard the server proves its answer with\n\t\t// before writing it proves this one before a caller narrows on `status`. A snapshot that\n\t\t// does not hold together is refused with the code a malformed payload earns, not passed\n\t\t// on as a task whose `status` a caller would then switch over.\n\t\tif (!isMCPTaskDetail(result)) {\n\t\t\tthrow new MCPError('MCP server returned an invalid task', JSONRPC_INVALID_PARAMS)\n\t\t}\n\t\treturn result\n\t}\n\n\tasync update(id: string, responses: Readonly<Record<string, unknown>>): Promise<void> {\n\t\t// `inputResponses` is the WIRE spelling, carried verbatim from the extension's schema;\n\t\t// the record inside it is the caller's and travels unread, because which keys a task\n\t\t// published is the task's own knowledge and this client holds none of it.\n\t\tawait this.#request('tasks/update', { taskId: id, inputResponses: responses }, this.#timeout)\n\t}\n\n\tasync abort(id: string): Promise<void> {\n\t\t// `tasks/cancel` is the protocol's spelling of this package's `abort`, and the ask is\n\t\t// ADVISORY: the acknowledgement this awaits reports that the request was accepted, never\n\t\t// that the task stopped. Nothing is returned because there is nothing true to return.\n\t\tawait this.#request('tasks/cancel', { taskId: id }, this.#timeout)\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { ToolInterface } from '@orkestrel/tool'\nimport type {\n\tMCPClientTransportInterface,\n\tJSONRPCId,\n\tJSONRPCInvocation,\n\tJSONRPCMessage,\n\tJSONRPCRequest,\n\tMCPCallOptions,\n\tMCPCallOutcome,\n\tMCPClientEventMap,\n\tMCPClientInterface,\n\tMCPClientOptions,\n\tMCPClientCapabilities,\n\tMCPDiscoverResult,\n\tMCPEra,\n\tMCPIdentity,\n\tMCPProgressHandler,\n\tMCPTaskClientInterface,\n\tMCPVersion,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { Tool } from '@orkestrel/tool'\nimport { MCPTaskClient } from './MCPTaskClient.js'\nimport {\n\tattempt,\n\tcloneJSONRecord,\n\tisArray,\n\tisInteger,\n\tisRecord,\n\tisString,\n} from '@orkestrel/contract'\nimport {\n\tDEFAULT_MCP_CLIENT_NAME,\n\tDEFAULT_MCP_CLIENT_VERSION,\n\tDEFAULT_MCP_PROBE_TIMEOUT,\n\tDEFAULT_MCP_REQUEST_TIMEOUT,\n\tJSONRPC_INVALID_PARAMS,\n\tJSONRPC_INVALID_REQUEST,\n\tJSONRPC_METHOD_NOT_FOUND,\n\tMCP_META_CAPABILITIES,\n\tMCP_META_CLIENT,\n\tMCP_META_VERSION,\n\tMCP_MODERN_VERSION,\n\tMCP_PROTOCOL_VERSION,\n\tMCP_UNSUPPORTED_VERSION,\n} from './constants.js'\nimport { MCPError, isMCPError } from './errors.js'\nimport { buildCallOutcome, buildCancelledNotification, matchesResultType } from './helpers.js'\nimport { inferEra, inferVersion } from './inferers.js'\nimport { parseJSONRPCMessage } from './parsers.js'\nimport {\n\tisJSONRPCId,\n\tisJSONRPCResponse,\n\tisMCPProgress,\n\tisMCPResultMetaObject,\n\tisMCPServerCapabilities,\n\tisMCPVersion,\n} from './validators.js'\n\n/**\n * A transport-agnostic Model Context Protocol CLIENT — connects to a REMOTE MCP server\n * over an injected {@link MCPClientTransportInterface}, negotiates the modern or legacy\n * wire era, and exposes the server's tools as local {@link ToolInterface}s an agent can run.\n *\n * @remarks\n * - **The mirror of `MCPServer`.** The server DISPATCHES requests over a tool registry;\n * this client ISSUES them over a transport. `connect` probes `server/discover` unless\n * pinned legacy, falls back to `initialize` only for a legacy peer, and exposes the\n * negotiated `version`; `tools()` lists the remote tools and wraps each as a\n * local {@link ToolInterface} whose `execute` calls back through `call`; `call` runs a\n * remote `tools/call` and reports the arm the peer answered with — a value, a durable\n * task, or a request for more input (a remote `isError: true` throws locally, so an\n * agent's {@link import('@orkestrel/tool').ToolManagerInterface} isolates it into a\n * `success: false` result just like a local throw). A wrapped tool cannot hand an agent\n * a deferred answer, so a non-`'complete'` arm throws there.\n * - **Request↔response correlation.** Each request is tagged with a monotonic numeric\n * `id` ({@link #nextId}); a single transport `message` subscription resolves / rejects\n * the matching {@link #pending} entry by `id`. An error response with no `id` rejects\n * every pending request because the peer could not identify which request failed. A\n * server-initiated message is re-surfaced on the `notification` event, except a progress\n * frame claimed by the request that asked\n * for it; a RESPONSE correlating to nothing pending is discarded, because the request it\n * answers has already settled.\n * - **Per-request cancellation.** `call`'s `options.signal` withdraws ONE caller from ONE\n * request: the pending entry rejects on every carrier, and `notifications/cancelled` goes\n * out only where the transport declares itself duplex — the dated revision defines no\n * client-to-server notification over Streamable HTTP, where closing the response stream\n * is the signal instead. It never cancels the connection and never a durable task.\n * - **Durable tasks, no schedule.** `tasks` is the extension's client half — read, answer, and\n * stop a task the peer deferred a call into. The peer's `pollIntervalMs` hint is carried\n * untouched and the one-shot read sits beside it; there is no timer, no scheduler, and no\n * cache, so a client nobody asks writes nothing after the `resultType: 'task'` answer.\n * - **Per-request registrations.** The caller's abort listener and progress handler live on\n * the {@link #pending} entry, so the single {@link #settle} door releases them on every\n * exit — the deadline, an abort, a rejecting `send`, the answer itself, and the\n * teardown's drain — without any of those paths knowing they exist.\n * - **Per-request deadline.** An ordinary `#request` carries `this.#timeout`. The initial\n * discovery probe uses that same 30-second default, or the shorter probe deadline where\n * `timeout` was configured, so a silent peer cannot hold negotiation indefinitely.\n * `AbortSignal.timeout` (never a raw `setTimeout`) rejects only that pending request, and the\n * same deadline bounds the WAIT on the transport's `close`, the one wait no drain and no signal\n * can reach. It bounds the wait rather than the close, which keeps running, so a retry joins it\n * instead of shutting one connection down twice.\n * - **Transport-agnostic.** Imports only core siblings (JSON-RPC + the tool vocabulary);\n * the concrete transport is injected. Wire fields are narrowed via the contracts\n * guards (no `as`).\n * - **Observable (§13).** The owned `emitter` fires `connect` / `disconnect` /\n * `notification` / `error`; the emitter isolates a listener throw and routes it to its\n * `error` handler (the `error` option), so a listener throw can never escape.\n *\n * @example\n * ```ts\n * const client = new MCPClient({ transport, identity: { name: 'agent', version: '1.0.0' } })\n * await client.connect()\n * const tools = await client.tools()\n * agent.context.tools.add(tools) // the remote tools are now the agent's\n * const outcome = await client.call('search', { query: 'mcp' })\n * if (outcome.resultType === 'complete') use(outcome.value)\n * ```\n */\nexport class MCPClient implements MCPClientInterface {\n\treadonly #emitter: Emitter<MCPClientEventMap>\n\treadonly #transport: MCPClientTransportInterface\n\treadonly #identity: MCPIdentity\n\treadonly #capabilities: MCPClientCapabilities\n\treadonly #pin: MCPVersion | undefined\n\treadonly #timeout: number\n\treadonly #probe: number\n\t// The draft Tasks extension's client half, built once and held. It is given this client's\n\t// own correlated-request door rather than a second path to the peer, so a task read shares\n\t// the id space, the pending table, the deadline, and the `disconnect` drain with every other\n\t// request — and `#request` stays private, because publishing it would be a general\n\t// arbitrary-method capability nothing has asked for. The declared cost of that choice: a\n\t// consumer who registers `prompts/get` on the server's open registry cannot reach it with\n\t// this client, and the guide records the asymmetry rather than leaving it to be discovered.\n\treadonly #tasks: MCPTaskClientInterface\n\t// The in-flight requests, keyed by JSON-RPC id, each holding its promise settlers —\n\t// resolved on the matching response, rejected on an error response, the deadline, an\n\t// abort, or `disconnect`. Genuinely private glue (§5): the settler shape lives inline here.\n\t//\n\t// The entry is also where every per-request REGISTRATION lives, and that placement is the\n\t// whole reason the exits nobody enumerates are already covered. `#settle` is the single\n\t// door out of a pending request — the deadline, an abort, a rejecting `transport.send`, an\n\t// answered response and the teardown's drain all arrive through it — so a listener or\n\t// handler recorded here is released by all of them at once, without any of them knowing it\n\t// exists. Registering one anywhere else (in `call`, in a `finally`, in the abort listener)\n\t// would leak on whichever exit its author did not think of.\n\treadonly #pending = new Map<\n\t\tJSONRPCId,\n\t\t{\n\t\t\treadonly resolve: (value: unknown) => void\n\t\t\treadonly reject: (reason?: unknown) => void\n\t\t\treadonly method: string\n\t\t\treadonly deadline?: AbortSignal\n\t\t\treadonly timeout?: () => void\n\t\t\t// The CALLER's cancellation signal and this request's listener on it. The signal is\n\t\t\t// the caller's and outlives the request, so the listener is removed rather than left\n\t\t\t// to `once`: one controller may be driving several calls.\n\t\t\treadonly signal?: AbortSignal\n\t\t\treadonly abort?: () => void\n\t\t\t// The caller's progress consumer, claimed by an inbound `notifications/progress`\n\t\t\t// naming this request's token. It needs no explicit release — dropping the entry is\n\t\t\t// the release, and a frame arriving afterwards finds nothing and stays a notification.\n\t\t\treadonly progress?: MCPProgressHandler\n\t\t}\n\t>()\n\t#nextId = 0\n\t#connected = false\n\t// WHICH attempt owns the connection this client opened on the transport, if any: the generation\n\t// whose `start()` opened it. One fact, so a claim asks `is this connection MINE` and never `is\n\t// SOMETHING open` — the question a superseded attempt resuming over a connection a LATER attempt\n\t// opened would otherwise answer yes to. Both close sites read and clear it in ONE synchronous\n\t// stretch before awaiting `close()`, and a close still running is joined rather than repeated, so\n\t// `close()` (not contractually idempotent) runs once per connection; and whichever of them meets\n\t// a close that FAILED — or one that merely outran its deadline, which says the shutdown did not\n\t// answer and never that it did not happen — keeps the claim, because a connection that did not\n\t// close, or never confirmed that it had, is still owed one. Which is also why `connect` refuses\n\t// to open while a claim is standing.\n\t#owner: number | undefined = undefined\n\t// The `transport.close()` this client stopped waiting for, while it is still running. A deadline\n\t// ends the WAIT, never the close, so the promise is retained rather than a verdict about it: the\n\t// next caller that owes this connection a close JOINS this one under a fresh deadline instead of\n\t// issuing a second shutdown over it, and the transport's own eventual answer — the only\n\t// authority on whether the connection ended — settles the claim it left standing.\n\t#closing: Promise<void> | undefined = undefined\n\t// The in-flight connect attempt: the negotiation a second caller JOINS, and the generation\n\t// it was published under, so a caller can tell an attempt it may join from one a teardown\n\t// already superseded and must merely outwait. Genuinely private glue (§5), like `#pending`'s\n\t// settler shape.\n\t#connecting: { readonly negotiation: Promise<void>; readonly generation: number } | undefined =\n\t\tundefined\n\t// The in-flight disconnect, published BEFORE its work starts.\n\t#disconnecting: Promise<void> | undefined = undefined\n\t#generation = 0\n\t// Settled by every teardown, and replaced in the same stretch. A raw wire write — a\n\t// notification, which carries no id and therefore no `#pending` entry — is the one await\n\t// the teardown's drain cannot reach and no deadline is watching, so an attempt races its\n\t// own raw write against this and stops waiting on a transport that may never answer.\n\t#supersession = Promise.withResolvers<void>()\n\t#version: MCPVersion | undefined = undefined\n\t#era: MCPEra | undefined = undefined\n\t#offer: MCPVersion\n\n\tconstructor(options: MCPClientOptions) {\n\t\tthis.#emitter = new Emitter<MCPClientEventMap>({\n\t\t\t...(options.on !== undefined ? { on: options.on } : {}),\n\t\t\t...(options.error !== undefined ? { error: options.error } : {}),\n\t\t})\n\t\tthis.#transport = options.transport\n\t\tthis.#identity = options.identity ?? {\n\t\t\tname: DEFAULT_MCP_CLIENT_NAME,\n\t\t\tversion: DEFAULT_MCP_CLIENT_VERSION,\n\t\t}\n\t\tthis.#capabilities = options.capabilities ?? {}\n\t\tthis.#pin = options.version\n\t\tthis.#offer = options.version ?? MCP_MODERN_VERSION\n\t\tthis.#timeout = options.timeout ?? DEFAULT_MCP_REQUEST_TIMEOUT\n\t\tthis.#probe =\n\t\t\toptions.timeout === undefined\n\t\t\t\t? DEFAULT_MCP_REQUEST_TIMEOUT\n\t\t\t\t: Math.min(options.timeout, DEFAULT_MCP_PROBE_TIMEOUT)\n\t\tthis.#tasks = new MCPTaskClient({\n\t\t\trequest: this.#request.bind(this),\n\t\t\ttimeout: this.#timeout,\n\t\t})\n\t\t// One message subscription for the client's whole life: a response settles its\n\t\t// pending request by id; anything else is a server notification.\n\t\tthis.#transport.emitter.on('message', (message) => this.#receive(message))\n\t}\n\n\tget emitter(): EmitterInterface<MCPClientEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget connected(): boolean {\n\t\treturn this.#connected\n\t}\n\n\tget version(): MCPVersion | undefined {\n\t\treturn this.#version\n\t}\n\n\tget transport(): MCPClientTransportInterface {\n\t\treturn this.#transport\n\t}\n\n\tget tasks(): MCPTaskClientInterface {\n\t\treturn this.#tasks\n\t}\n\n\ton<K extends keyof MCPClientEventMap>(\n\t\tevent: K,\n\t\thandler: (...args: MCPClientEventMap[K]) => void,\n\t): void {\n\t\tthis.#emitter.on(event, handler)\n\t}\n\n\tasync connect(): Promise<void> {\n\t\t// Wait out everything that must finish before a NEW attempt may open the next connection: a\n\t\t// teardown in flight, an attempt a teardown already superseded, and a close this client\n\t\t// still OWES. A CURRENT attempt is joined — one handshake, one outcome, shared. A SUPERSEDED\n\t\t// one is outwaited instead: its caller asked for the connection that teardown ended, this\n\t\t// caller is asking for a fresh one, and running beside it would open a second connection\n\t\t// with one owner. Re-read after every wait, because what was in flight when this caller\n\t\t// arrived is not what is in flight when it resumes, and two callers resuming together must\n\t\t// not both open.\n\t\tfor (;;) {\n\t\t\tconst closing = this.#disconnecting\n\t\t\tif (closing !== undefined) {\n\t\t\t\tawait closing.catch(() => undefined)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (this.#connected) return\n\t\t\tconst inflight = this.#connecting\n\t\t\tif (inflight === undefined) {\n\t\t\t\t// The claim a `close()` that faulted — or that outran its deadline — left standing:\n\t\t\t\t// that connection did not close, or never confirmed that it had, so it is still owned,\n\t\t\t\t// and this is the second door onto the rule `disconnect` already enforces — the door\n\t\t\t\t// that never asked. Opening here would `start()` a connection beside it and leave the\n\t\t\t\t// first with no claim and no public path. The debt is settled through the same slot\n\t\t\t\t// `disconnect` publishes, so a caller arriving mid-retry joins one teardown instead\n\t\t\t\t// of racing it; the retry joins a close still running rather than issuing another;\n\t\t\t\t// and a close that fails AGAIN rejects THIS caller with that fault, leaving the debt\n\t\t\t\t// owned for whoever asks next. Read only once no attempt is in flight: a LIVE attempt\n\t\t\t\t// legitimately holds the claim while it negotiates, and closing there would tear down\n\t\t\t\t// the very connection this caller is waiting on.\n\t\t\t\tif (this.#owner === undefined) break\n\t\t\t\tawait this.#teardown()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (inflight.generation === this.#generation) return inflight.negotiation\n\t\t\tawait inflight.negotiation.catch(() => undefined)\n\t\t}\n\t\tthis.#generation += 1\n\t\tconst generation = this.#generation\n\t\t// Published before `#negotiate` — and so before the injected `transport.start()` —\n\t\t// runs: a transport that re-enters `connect()` joins this attempt instead of opening\n\t\t// another. Building the record around `this.#negotiate(...)` directly does NOT close that\n\t\t// door, because an async function runs synchronously to its first await, so `start()`\n\t\t// would already have been called before the assignment.\n\t\tconst negotiation = Promise.resolve().then(() => this.#negotiate(generation))\n\t\tconst published = { negotiation, generation }\n\t\tthis.#connecting = published\n\t\ttry {\n\t\t\tawait negotiation\n\t\t} finally {\n\t\t\t// Only this attempt's own gate: a settling attempt must never unpublish a live one.\n\t\t\tif (this.#connecting === published) this.#connecting = undefined\n\t\t}\n\t}\n\n\tasync discover(): Promise<MCPDiscoverResult> {\n\t\tconst received = await this.#request(\n\t\t\t'server/discover',\n\t\t\tundefined,\n\t\t\tthis.#probe,\n\t\t\tthis.#version ?? this.#offer,\n\t\t)\n\t\tconst owned = attempt(() => cloneJSONRecord(received))\n\t\tif (!owned.success) {\n\t\t\tthrow new MCPError('MCP server returned a malformed discovery result', JSONRPC_INVALID_PARAMS)\n\t\t}\n\t\tconst result = owned.value\n\t\tconst advertised = result['supportedVersions']\n\t\tconst capabilities = result['capabilities']\n\t\tconst ttl = result['ttlMs']\n\t\tconst scope = result['cacheScope']\n\t\tconst instructions = result['instructions']\n\t\tconst metadata = result['_meta']\n\t\tconst resultType = result['resultType']\n\t\tif (\n\t\t\t!isArray(advertised) ||\n\t\t\t!advertised.every(isString) ||\n\t\t\t!isMCPServerCapabilities(capabilities) ||\n\t\t\t!isInteger(ttl) ||\n\t\t\tttl < 0 ||\n\t\t\t(scope !== 'public' && scope !== 'private') ||\n\t\t\t// REQUIRED, not merely constrained. The dated schema puts `resultType` on every\n\t\t\t// modern result and `server/discover` exists only in the modern era, so tolerating\n\t\t\t// its absence buys compatibility with no peer that exists — while synthesizing the\n\t\t\t// missing value would hand the caller a fact the peer never sent. A peer that speaks\n\t\t\t// modern discovery badly therefore fails CLOSED: `#receive` has already settled the\n\t\t\t// era to modern by the time this runs, so the refusal rejects the connection instead\n\t\t\t// of degrading it quietly to legacy.\n\t\t\tresultType !== 'complete' ||\n\t\t\t(instructions !== undefined && !isString(instructions)) ||\n\t\t\t(metadata !== undefined && !isMCPResultMetaObject(metadata))\n\t\t) {\n\t\t\tthrow new MCPError(\n\t\t\t\t'MCP server returned a malformed discovery result',\n\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\tresult,\n\t\t\t)\n\t\t}\n\t\tconst supportedVersions: MCPVersion[] = []\n\t\tfor (const version of advertised) {\n\t\t\tif (isMCPVersion(version)) supportedVersions.push(version)\n\t\t}\n\t\tconst retained = Object.freeze(supportedVersions)\n\t\treturn Object.freeze({\n\t\t\tsupportedVersions: retained,\n\t\t\tcapabilities,\n\t\t\tresultType,\n\t\t\tttlMs: ttl,\n\t\t\tcacheScope: scope,\n\t\t\t...(instructions === undefined ? {} : { instructions }),\n\t\t\t...(metadata === undefined ? {} : { _meta: metadata }),\n\t\t})\n\t}\n\n\tasync disconnect(): Promise<void> {\n\t\tconst closing = this.#disconnecting\n\t\tif (closing !== undefined) return closing\n\t\t// Three things are worth tearing down: an announced connection, an attempt still in\n\t\t// flight, and a connection whose `close()` faulted or never answered — that one is still\n\t\t// owned, and both this path and the next `connect()` can reach it.\n\t\tif (!this.#connected && this.#connecting === undefined && this.#owner === undefined) return\n\t\tawait this.#teardown()\n\t}\n\n\tasync tools(): Promise<readonly ToolInterface[]> {\n\t\tconst result = await this.#request('tools/list', undefined, this.#timeout)\n\t\t// The wire shape is `{ tools: MCPToolDescriptor[] }` — narrow it (§14): a\n\t\t// non-record / non-array `tools` yields no tools rather than throwing.\n\t\tif (!isRecord(result) || !isArray(result['tools'])) return []\n\t\tconst tools: ToolInterface[] = []\n\t\tfor (const descriptor of result['tools']) {\n\t\t\tif (!isRecord(descriptor) || !isString(descriptor['name'])) continue\n\t\t\tconst name = descriptor['name']\n\t\t\ttools.push(this.#tool(name, descriptor))\n\t\t}\n\t\treturn tools\n\t}\n\n\tasync call(\n\t\tname: string,\n\t\targs: Readonly<Record<string, unknown>>,\n\t\toptions?: MCPCallOptions,\n\t): Promise<MCPCallOutcome> {\n\t\tconst result = await this.#request(\n\t\t\t'tools/call',\n\t\t\t{ name, arguments: args },\n\t\t\tthis.#timeout,\n\t\t\tundefined,\n\t\t\toptions,\n\t\t)\n\t\treturn buildCallOutcome(name, result)\n\t}\n\n\t// Issue a request and await its correlated response, bounded by the per-request\n\t// deadline. A monotonic numeric id keys the pending settlers; `AbortSignal.timeout`\n\t// (the taverna idiom — never a raw setTimeout) rejects the pending request if the\n\t// server never answers. The transport `send` is awaited so a write failure rejects\n\t// here rather than leaving a pending request to time out.\n\t//\n\t// `options` carries the CALLER's two per-request registrations, and both are recorded on\n\t// the pending entry rather than around this call, so the single `#settle` door releases\n\t// them on every exit — including the two nobody enumerates, a rejecting `send` and the\n\t// teardown's drain. The request's own id doubles as its progress token: it is already\n\t// unique per request, already travels this exact channel, and needs no second counter to\n\t// drift against.\n\t#request(\n\t\tmethod: string,\n\t\tparams: Readonly<Record<string, unknown>> | undefined,\n\t\tdeadline: number | undefined,\n\t\tversion?: MCPVersion,\n\t\toptions?: MCPCallOptions,\n\t): Promise<unknown> {\n\t\tthis.#nextId += 1\n\t\tconst id = this.#nextId\n\t\tconst timeout = deadline\n\t\tconst caller = options?.signal\n\t\tconst report = options?.progress\n\t\tconst modern = version ?? (this.#era === 'modern' ? this.#version : undefined)\n\t\tconst metadata = {\n\t\t\t...(modern === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\t[MCP_META_VERSION]: modern,\n\t\t\t\t\t\t[MCP_META_CAPABILITIES]: this.#capabilities,\n\t\t\t\t\t\t[MCP_META_CLIENT]: this.#identity,\n\t\t\t\t\t}),\n\t\t\t// Stamped only where a caller is listening: the token is what asks the peer to\n\t\t\t// report at all, so an unwatched request stays exactly the request it was.\n\t\t\t...(report === undefined ? {} : { progressToken: id }),\n\t\t}\n\t\tconst stamped =\n\t\t\tObject.keys(metadata).length === 0 ? params : { ...(params ?? {}), _meta: metadata }\n\t\tconst request: JSONRPCRequest = {\n\t\t\tjsonrpc: '2.0',\n\t\t\tid,\n\t\t\tmethod,\n\t\t\t...(stamped === undefined ? {} : { params: stamped }),\n\t\t}\n\t\treturn new Promise<unknown>((resolve, reject) => {\n\t\t\t// A caller that arrived ALREADY aborted is refused before anything is written. An\n\t\t\t// unsent request has no id the peer could be told about, so there is nothing to\n\t\t\t// cancel, nothing to correlate, and nothing to release.\n\t\t\tif (caller?.aborted === true) {\n\t\t\t\tconst reason: unknown = caller.reason\n\t\t\t\treject(new Error(`MCP request '${method}' was aborted`, { cause: reason }))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlet expiry: AbortSignal | undefined\n\t\t\tlet expire: (() => void) | undefined\n\t\t\tif (timeout !== undefined) {\n\t\t\t\texpiry = AbortSignal.timeout(timeout)\n\t\t\t\texpire = this.#timeoutRequest.bind(this, id, method, timeout)\n\t\t\t\texpiry.addEventListener('abort', expire, { once: true })\n\t\t\t}\n\t\t\tlet abort: (() => void) | undefined\n\t\t\tif (caller !== undefined) {\n\t\t\t\tabort = this.#abortRequest.bind(this, id, method, caller)\n\t\t\t\tcaller.addEventListener('abort', abort, { once: true })\n\t\t\t}\n\t\t\tthis.#pending.set(id, {\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t\tmethod,\n\t\t\t\t...(expiry === undefined ? {} : { deadline: expiry }),\n\t\t\t\t...(expire === undefined ? {} : { timeout: expire }),\n\t\t\t\t...(caller === undefined ? {} : { signal: caller }),\n\t\t\t\t...(abort === undefined ? {} : { abort }),\n\t\t\t\t...(report === undefined ? {} : { progress: report }),\n\t\t\t})\n\t\t\tthis.#transport.send(request).catch((error: unknown) => {\n\t\t\t\tthis.#settle(id, error instanceof Error ? error : new Error(String(error)), true)\n\t\t\t})\n\t\t})\n\t}\n\n\t// Handle one inbound transport message: a correlated response settles its pending request by\n\t// id (an error response rejects, a result resolves), while an id-less error rejects every\n\t// pending request because the peer could not identify which one failed. A `notifications/progress` frame\n\t// naming an in-flight request goes to that request's progress handler; anything else\n\t// server-initiated is re-surfaced on the `notification` event.\n\t//\n\t// A RESPONSE whose id matches nothing pending is discarded instead. Every way to reach\n\t// that state is the same shape — the request settled first, by its deadline, by an abort,\n\t// or by the teardown's drain — and MCP is explicit that a late answer to a cancelled\n\t// request is to be ignored, not treated as a fault. Publishing it as a `notification`\n\t// would announce a response as a server-initiated message, which it is not.\n\t#receive(message: JSONRPCMessage): void {\n\t\tconst owned = parseJSONRPCMessage(message)\n\t\tif (owned === undefined) {\n\t\t\tconst correlated = attempt(() => {\n\t\t\t\tif (!isRecord(message)) return undefined\n\t\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(message, 'id')\n\t\t\t\tif (\n\t\t\t\t\tdescriptor === undefined ||\n\t\t\t\t\tdescriptor.enumerable !== true ||\n\t\t\t\t\t!Object.hasOwn(descriptor, 'value')\n\t\t\t\t)\n\t\t\t\t\treturn undefined\n\t\t\t\tconst id = descriptor.value\n\t\t\t\treturn isJSONRPCId(id) ? id : undefined\n\t\t\t})\n\t\t\tif (correlated.success && correlated.value !== undefined) {\n\t\t\t\tconst pending = this.#pending.get(correlated.value)\n\t\t\t\tif (pending?.method === 'server/discover') {\n\t\t\t\t\tthis.#era = 'modern'\n\t\t\t\t\tthis.#settle(\n\t\t\t\t\t\tcorrelated.value,\n\t\t\t\t\t\tnew MCPError(\n\t\t\t\t\t\t\t'MCP server returned a malformed discovery result',\n\t\t\t\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t\t\t),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.#emitter.emit(\n\t\t\t\t'error',\n\t\t\t\tnew MCPError('MCP transport delivered a malformed message', JSONRPC_INVALID_PARAMS),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tif (isJSONRPCResponse(owned) && owned.id === undefined && owned.error !== undefined) {\n\t\t\tfor (const id of this.#pending.keys()) {\n\t\t\t\tthis.#settle(\n\t\t\t\t\tid,\n\t\t\t\t\tnew MCPError(\n\t\t\t\t\t\t`MCP server returned an error without a request id: ${owned.error.message}`,\n\t\t\t\t\t\towned.error.code,\n\t\t\t\t\t\towned.error.data,\n\t\t\t\t\t),\n\t\t\t\t\ttrue,\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (isJSONRPCResponse(owned) && owned.id !== undefined) {\n\t\t\tconst correlation = owned.id\n\t\t\tconst pending = this.#pending.get(correlation)\n\t\t\tif (pending !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\tpending.method === 'server/discover' &&\n\t\t\t\t\t(owned.error === undefined ||\n\t\t\t\t\t\t(owned.error.code !== JSONRPC_METHOD_NOT_FOUND &&\n\t\t\t\t\t\t\towned.error.code !== JSONRPC_INVALID_REQUEST))\n\t\t\t\t) {\n\t\t\t\t\tthis.#era = 'modern'\n\t\t\t\t}\n\t\t\t\tif (owned.error !== undefined) {\n\t\t\t\t\tthis.#settle(\n\t\t\t\t\t\tcorrelation,\n\t\t\t\t\t\tnew MCPError(owned.error.message, owned.error.code, owned.error.data),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tconst resultType = isRecord(owned.result) ? owned.result['resultType'] : undefined\n\t\t\t\t\tconst metadata = isRecord(owned.result) ? owned.result['_meta'] : undefined\n\t\t\t\t\tif (metadata !== undefined && !isMCPResultMetaObject(metadata)) {\n\t\t\t\t\t\tthis.#settle(\n\t\t\t\t\t\t\tcorrelation,\n\t\t\t\t\t\t\tnew MCPError('MCP server returned invalid result metadata', JSONRPC_INVALID_PARAMS),\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tisRecord(owned.result) &&\n\t\t\t\t\t\tObject.hasOwn(owned.result, 'resultType') &&\n\t\t\t\t\t\t!matchesResultType(pending.method, resultType)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.#settle(\n\t\t\t\t\t\t\tcorrelation,\n\t\t\t\t\t\t\tnew MCPError(\n\t\t\t\t\t\t\t\t`MCP result type '${String(resultType)}' is not supported`,\n\t\t\t\t\t\t\t\tJSONRPC_INVALID_PARAMS,\n\t\t\t\t\t\t\t\t{ resultType },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.#settle(correlation, owned.result, false)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t// A server-initiated message. A progress frame a caller is waiting on is claimed by\n\t\t// that caller; everything else is surfaced for the consumer to react to.\n\t\tif ('method' in owned && this.#reportProgress(owned)) return\n\t\tthis.#emitter.emit('notification', owned)\n\t}\n\n\t// Route one inbound `notifications/progress` frame to the request whose caller asked for\n\t// it, reporting whether the frame was claimed. Unclaimed means exactly one of: the frame\n\t// is not a progress frame, it names no token this client minted, it names a request that\n\t// has already settled (whose registration went with it), or its caller supplied no\n\t// handler — all of which leave it an ordinary server notification.\n\t#reportProgress(message: JSONRPCInvocation): boolean {\n\t\tif (message.method !== 'notifications/progress') return false\n\t\tconst params = message.params\n\t\tconst token = isRecord(params) ? params['progressToken'] : undefined\n\t\tif (!isJSONRPCId(token)) return false\n\t\tconst report = this.#pending.get(token)?.progress\n\t\tif (report === undefined || !isMCPProgress(params)) return false\n\t\t// The handler is the consumer's, so its throw is contained here and surfaced on the\n\t\t// client's own `error` channel rather than escaping into the transport's delivery.\n\t\tconst reported = attempt(() => report(params))\n\t\tif (!reported.success) this.#emitter.emit('error', reported.error)\n\t\treturn true\n\t}\n\n\t// Wrap one remote tool descriptor as a local tool: map `inputSchema` → `parameters`\n\t// (the inverse of the server's rename, no `as`), carry `description` when present,\n\t// and bind `execute` to a remote `tools/call` via `call`.\n\t#tool(name: string, descriptor: Readonly<Record<string, unknown>>): ToolInterface {\n\t\tconst inputSchema = descriptor['inputSchema']\n\t\tconst description = descriptor['description']\n\t\tconst options: {\n\t\t\tname: string\n\t\t\tdescription?: string\n\t\t\tparameters?: Readonly<Record<string, unknown>>\n\t\t\texecute: (args: Readonly<Record<string, unknown>>) => Promise<unknown>\n\t\t} = {\n\t\t\tname,\n\t\t\texecute: this.#execute.bind(this, name),\n\t\t}\n\t\tif (isString(description)) options.description = description\n\t\tif (isRecord(inputSchema)) options.parameters = inputSchema\n\t\treturn new Tool(options)\n\t}\n\n\t// The agent-facing edge of `call`. A wrapped tool owes its caller a VALUE, and the two\n\t// deferred arms have none: the request is over and the answer is somewhere the agent\n\t// cannot wait for. Throwing is the one shape an agent's registry already absorbs — it\n\t// becomes a `success: false` result the model can read — where returning `undefined`\n\t// would read as a tool that succeeded and produced nothing.\n\tasync #execute(name: string, args: Readonly<Record<string, unknown>>): Promise<unknown> {\n\t\tconst outcome = await this.call(name, args)\n\t\tif (outcome.resultType !== 'complete') {\n\t\t\tthrow new Error(`MCP tool '${name}' answered '${outcome.resultType}' and has no inline value`)\n\t\t}\n\t\treturn outcome.value\n\t}\n\n\t// One connect attempt, stamped with the generation `connect` published it under. Every\n\t// re-ask below asks the same question a suspended negotiation must ask before it writes\n\t// anything: is this still the current attempt, or did a `disconnect` supersede it?\n\tasync #negotiate(generation: number): Promise<void> {\n\t\tawait this.#transport.start()\n\t\t// Claimed when the open COMPLETES — an abandoned `start()` that succeeds later still opened\n\t\t// something and must still be closable — and never over a claim already standing. A standing\n\t\t// claim names a connection an earlier attempt opened and no `close()` has confirmed, so\n\t\t// overwriting it would leave that connection with no claim and no public path while this\n\t\t// attempt reported itself connected over the same transport. `connect` refuses to open while\n\t\t// a close is owed, so this is the second lock on that door rather than the door itself.\n\t\tif (this.#owner !== undefined) {\n\t\t\tthrow new Error('MCP client owes a connection it has not closed')\n\t\t}\n\t\tthis.#owner = generation\n\t\ttry {\n\t\t\tif (generation !== this.#generation) throw new Error('MCP client disconnected')\n\t\t\tif (this.#era === 'legacy' || (this.#pin !== undefined && inferEra(this.#pin) === 'legacy')) {\n\t\t\t\tawait this.#initialize(generation, this.#pin ?? MCP_PROTOCOL_VERSION)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlet discovery: MCPDiscoverResult\n\t\t\ttry {\n\t\t\t\ttry {\n\t\t\t\t\tdiscovery = await this.discover()\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Re-ask BEFORE the offer moves: this branch writes a SECOND discovery and\n\t\t\t\t\t// creates a second pending entry, and `#closeConnection` drains `#pending`\n\t\t\t\t\t// exactly once — a retry issued after that drain has nothing left to settle it,\n\t\t\t\t\t// so a superseded attempt would never settle at all.\n\t\t\t\t\tif (generation !== this.#generation) {\n\t\t\t\t\t\tthrow new Error('MCP client disconnected', { cause: error })\n\t\t\t\t\t}\n\t\t\t\t\tif (!isMCPError(error) || error.code !== MCP_UNSUPPORTED_VERSION) throw error\n\t\t\t\t\tif (this.#pin !== undefined) throw error\n\t\t\t\t\tconst supported = isRecord(error.context) ? error.context['supported'] : undefined\n\t\t\t\t\tconst retry = isArray(supported)\n\t\t\t\t\t\t? inferVersion(supported.filter((version): version is string => isString(version)))\n\t\t\t\t\t\t: undefined\n\t\t\t\t\tif (retry === undefined) throw error\n\t\t\t\t\tthis.#offer = retry\n\t\t\t\t\tdiscovery = await this.discover()\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (generation !== this.#generation) throw error\n\t\t\t\tconst fallback =\n\t\t\t\t\tthis.#pin !== MCP_MODERN_VERSION &&\n\t\t\t\t\tthis.#era === undefined &&\n\t\t\t\t\t(!isMCPError(error) || error.code !== MCP_UNSUPPORTED_VERSION)\n\t\t\t\tif (!fallback) throw error\n\t\t\t\tawait this.#initialize(generation, MCP_PROTOCOL_VERSION)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst version = inferVersion(discovery.supportedVersions)\n\t\t\tif (version === undefined) {\n\t\t\t\tthrow new MCPError(\n\t\t\t\t\t'MCP server supports no compatible protocol version',\n\t\t\t\t\tMCP_UNSUPPORTED_VERSION,\n\t\t\t\t\t{\n\t\t\t\t\t\tsupported: discovery.supportedVersions,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (generation !== this.#generation) throw new Error('MCP client disconnected')\n\t\t\tthis.#version = version\n\t\t\tthis.#era = 'modern'\n\t\t\tthis.#connected = true\n\t\t\tthis.#emitter.emit('connect')\n\t\t} catch (error) {\n\t\t\t// A superseded attempt must STILL close a connection IT opened, because `#closeConnection`\n\t\t\t// skipped that close — nothing was open yet when it ran. But it closes only its OWN:\n\t\t\t// the claim is this attempt's generation, so an attempt resuming over a connection a later\n\t\t\t// attempt opened matches nothing and closes nothing. Claiming is synchronous, so the\n\t\t\t// winner is decided before either side suspends.\n\t\t\tif (this.#owner === generation) {\n\t\t\t\tthis.#owner = undefined\n\t\t\t\ttry {\n\t\t\t\t\tawait this.#closeTransport()\n\t\t\t\t} catch (fault) {\n\t\t\t\t\t// The connection did not close — or never confirmed that it had — so its ownership\n\t\t\t\t\t// is not discarded: `disconnect` and the next `connect` are the paths left that can\n\t\t\t\t\t// close it. Two failures owed to two audiences: this observer learns the transport\n\t\t\t\t\t// fault, and the caller below still learns why the connection did not happen.\n\t\t\t\t\tthis.#owner = generation\n\t\t\t\t\tthis.#emitter.emit('error', fault)\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t// Publish the teardown BEFORE its work starts, and unpublish it only once that work has settled.\n\t// While it is published every `disconnect` joins it and every `connect` waits for it, which is\n\t// what keeps one close and one open from running together. Shared by `disconnect` and by the\n\t// `connect` that finds a close still owed, so both travel one slot and one queue.\n\tasync #teardown(): Promise<void> {\n\t\tconst teardown = Promise.resolve().then(() => this.#closeConnection())\n\t\tthis.#disconnecting = teardown\n\t\ttry {\n\t\t\tawait teardown\n\t\t} finally {\n\t\t\tthis.#disconnecting = undefined\n\t\t}\n\t}\n\n\t// Invalidate any in-flight connect FIRST, so it cannot install `connected` over a connection\n\t// this is closing. This does NOT await the attempt: an attempt suspended inside the injected\n\t// `start()` would hold the teardown open for as long as that transport takes to open. What\n\t// unwinds the attempt instead is rejecting every pending request AND settling the supersession\n\t// signal — together they reach every await an attempt can be parked in once the transport has\n\t// opened — and `#owner` decides which side closes. The attempt's gate stays published: it is\n\t// the attempt itself that clears it, once it has settled, so a new `connect()` outwaits it\n\t// rather than running beside it.\n\tasync #closeConnection(): Promise<void> {\n\t\tthis.#generation += 1\n\t\t// Replace, then settle: the settled signal releases every attempt parked in a raw write\n\t\t// right now, and the fresh one belongs to whatever attempt comes next — an attempt racing\n\t\t// an already settled signal would abandon its own writes before making them.\n\t\tconst supersession = this.#supersession\n\t\tthis.#supersession = Promise.withResolvers<void>()\n\t\tsupersession.resolve()\n\t\tconst announced = this.#connected\n\t\tthis.#connected = false\n\t\tthis.#version = undefined\n\t\tfor (const id of this.#pending.keys()) {\n\t\t\tthis.#settle(id, new Error('MCP client disconnected'), true)\n\t\t}\n\t\t// One rule covers both faults this teardown can meet: `disconnect` announces the loss of\n\t\t// a connection this client ANNOUNCED, so an attempt that never emitted `connect` emits no\n\t\t// `disconnect` either — and where it IS owed, a failing `close()` still reaches the\n\t\t// caller without swallowing the announcement.\n\t\tconst owner = this.#owner\n\t\tthis.#owner = undefined\n\t\ttry {\n\t\t\tif (owner !== undefined) await this.#closeTransport()\n\t\t} catch (fault) {\n\t\t\t// The connection did not close — or never confirmed that it had — so it is still owned,\n\t\t\t// and a caller can still reach it: a client that discarded its claim here would leave a\n\t\t\t// real connection open for the process's life with no public path left to close it. Where\n\t\t\t// the fault was the deadline the close is still running, so the next caller joins it and\n\t\t\t// the transport's own answer, not this one, decides whether the debt survives.\n\t\t\tthis.#owner = owner\n\t\t\tthrow fault\n\t\t} finally {\n\t\t\tif (announced) this.#emitter.emit('disconnect')\n\t\t}\n\t}\n\n\t// The transport's own `close()` — the one await nothing else in this client can reach. The drain\n\t// settles a pending request, a request deadline settles one the peer ignores, and the\n\t// supersession signal settles a raw write; a shutdown the transport accepts and never answers is\n\t// deaf to all three, and while a teardown is published it would hold `disconnect` AND every\n\t// later `connect` for the process's life. So the WAIT carries the same deadline every other\n\t// transport wait carries — the wait, never the close, which keeps running and may still end the\n\t// connection. That difference is the whole design here: a fault means the shutdown did NOT\n\t// happen, a deadline means this client stopped waiting to hear whether it did, and treating the\n\t// second as the first is what would send a second `close()` over a connection the first is still\n\t// closing.\n\tasync #closeTransport(): Promise<void> {\n\t\t// Join the close already running; issue one only when none is.\n\t\tlet closing = this.#closing\n\t\tif (closing === undefined) {\n\t\t\tclosing = this.#transport.close()\n\t\t\tthis.#closing = closing\n\t\t\tvoid closing.then(\n\t\t\t\t() => this.#discharge(true),\n\t\t\t\t() => this.#discharge(false),\n\t\t\t)\n\t\t}\n\t\tconst timeout = this.#timeout\n\t\tconst deadline = AbortSignal.timeout(timeout)\n\t\tawait Promise.race([\n\t\t\tclosing,\n\t\t\t// `_` is the unused `resolve`: this side of the race only ever rejects. `race` keeps a\n\t\t\t// handler on both sides, so a deadline that fires after the close returned rejects\n\t\t\t// nothing unhandled.\n\t\t\tnew Promise<never>((_, reject) => {\n\t\t\t\tdeadline.addEventListener(\n\t\t\t\t\t'abort',\n\t\t\t\t\t() => reject(new Error(`MCP transport close timed out after ${timeout}ms`)),\n\t\t\t\t\t{ once: true },\n\t\t\t\t)\n\t\t\t}),\n\t\t])\n\t}\n\n\t// The retained close finally answered, possibly long after its caller stopped waiting for it,\n\t// and only it can say what happened: a close that RESOLVED ended the connection, so the claim it\n\t// left standing is discharged here and the next `connect` may open; one that REJECTED ended\n\t// nothing, so the claim stays owed and the next caller issues a fresh `close()` rather than\n\t// joining a dead one. Nothing can have re-claimed the connection meanwhile — opening requires no\n\t// standing claim, and while this close runs the claim is either held or held open by a published\n\t// teardown — so the discharge can only ever clear the claim this close belonged to.\n\t#discharge(closed: boolean): void {\n\t\tthis.#closing = undefined\n\t\tif (closed) this.#owner = undefined\n\t}\n\n\tasync #initialize(generation: number, version: MCPVersion): Promise<void> {\n\t\tconst result = await this.#request(\n\t\t\t'initialize',\n\t\t\t{\n\t\t\t\tprotocolVersion: version,\n\t\t\t\tcapabilities: {},\n\t\t\t\tclientInfo: this.#identity,\n\t\t\t},\n\t\t\tthis.#timeout,\n\t\t)\n\t\tconst protocol = isRecord(result) ? result['protocolVersion'] : undefined\n\t\tif (protocol === undefined) {\n\t\t\tthrow new Error('MCP server returned no protocol version')\n\t\t}\n\t\tif (!isString(protocol)) {\n\t\t\tthrow new Error('MCP server returned a malformed protocol version')\n\t\t}\n\t\tif (!isMCPVersion(protocol) || inferEra(protocol) !== 'legacy') {\n\t\t\tthrow new Error(`MCP server negotiated unsupported protocol version '${protocol}'`)\n\t\t}\n\t\t// Two re-asks, asking different questions: the first keeps a superseded attempt from\n\t\t// writing to a transport a `disconnect` is already closing, the second keeps it from\n\t\t// installing after that write. Install only after the handshake's last wire write\n\t\t// lands: a failed notification must leave nothing behind for the rejecting\n\t\t// `connect()` to strand.\n\t\tif (generation !== this.#generation) throw new Error('MCP client disconnected')\n\t\t// This notification carries no id, so it creates no `#pending` entry and no deadline\n\t\t// watches it: a peer that accepts the write and never answers would hold this attempt\n\t\t// for the client's whole life, and a teardown's drain has nothing to settle. Racing the\n\t\t// supersession signal ends the WAIT, never the write — the write may still land in the\n\t\t// background, and the re-ask below is what decides this attempt's outcome. `race` keeps a\n\t\t// handler on both sides, so a write that fails after being raced away rejects nothing\n\t\t// unhandled.\n\t\tawait Promise.race([\n\t\t\tthis.#transport.send({ jsonrpc: '2.0', method: 'notifications/initialized' }),\n\t\t\tthis.#supersession.promise,\n\t\t])\n\t\tif (generation !== this.#generation) throw new Error('MCP client disconnected')\n\t\tthis.#version = protocol\n\t\tthis.#era = 'legacy'\n\t\tthis.#connected = true\n\t\tthis.#emitter.emit('connect')\n\t}\n\n\t#timeoutRequest(id: JSONRPCId, method: string, timeout: number): void {\n\t\tthis.#settle(id, new Error(`MCP request '${method}' timed out after ${timeout}ms`), true)\n\t}\n\n\t// The caller withdrew from ONE request. Two things happen and neither is the other's\n\t// precondition: the caller stops waiting, always, on every carrier; and the peer is TOLD,\n\t// only where the carrier can carry a client-initiated notification. Cancellation is\n\t// ADVISORY in MCP — every receiver obligation is `SHOULD` or `MAY` — so the telling is\n\t// courtesy, the local settle is the contract, and a peer that answers anyway is answering\n\t// a request nothing is waiting for.\n\t//\n\t// The frame goes first and is never awaited. It carries no id, so nothing answers it and\n\t// no deadline watches it; a caller that has already stopped waiting must not be made to\n\t// wait again on the courtesy. A write that fails is surfaced for observation only.\n\t//\n\t// Registering nothing here is deliberate: this listener runs INSIDE the request's\n\t// lifetime, and anything it registered would have to be released on the exits this\n\t// listener never sees. `#settle` releases the listener itself.\n\t#abortRequest(id: JSONRPCId, method: string, signal: AbortSignal): void {\n\t\tif (this.#pending.get(id) === undefined) return\n\t\tconst reason: unknown = signal.reason\n\t\tif (this.#transport.duplex) {\n\t\t\tthis.#transport\n\t\t\t\t.send(buildCancelledNotification(id, isString(reason) ? reason : undefined))\n\t\t\t\t.catch((error: unknown) => this.#emitter.emit('error', error))\n\t\t}\n\t\tthis.#settle(id, new Error(`MCP request '${method}' was aborted`, { cause: reason }), true)\n\t}\n\n\t#settle(id: JSONRPCId, value: unknown, failed: boolean): void {\n\t\tconst pending = this.#pending.get(id)\n\t\tif (pending === undefined) return\n\t\tthis.#pending.delete(id)\n\t\tif (pending.deadline !== undefined && pending.timeout !== undefined) {\n\t\t\tpending.deadline.removeEventListener('abort', pending.timeout)\n\t\t}\n\t\t// The caller's signal is the CALLER's and outlives this request — one controller may be\n\t\t// driving several calls — so its listener is removed rather than left to `once`. The\n\t\t// progress handler needs no line here: it lives on the entry that was just dropped.\n\t\tif (pending.signal !== undefined && pending.abort !== undefined) {\n\t\t\tpending.signal.removeEventListener('abort', pending.abort)\n\t\t}\n\t\tif (failed) pending.reject(value)\n\t\telse pending.resolve(value)\n\t}\n}\n","import type {\n\tMCPClientTransportEventMap,\n\tMCPClientTransportInterface,\n\tJSONRPCMessage,\n\tMCPClientInterface,\n\tMCPClientOptions,\n\tMCPDispatcherInterface,\n\tMCPServerInterface,\n\tMCPServerOptions,\n\tMCPTransportInterface,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { MCPClient } from './MCPClient.js'\nimport { MCPLegacy } from './MCPLegacy.js'\nimport { MCPServer } from './MCPServer.js'\n\n/**\n * Create a transport-agnostic Model Context Protocol server — exposes a live\n * {@link import('@orkestrel/tool').ToolManagerInterface} and an optional\n * {@link import('./types.js').MCPResourceManagerInterface},\n * {@link import('./types.js').MCPPromptManagerInterface}, and\n * {@link import('./types.js').MCPCompletionManagerInterface} over JSON-RPC 2.0.\n *\n * @remarks\n * Pump raw message strings through `handle` (parse → dispatch → serialize) from a\n * transport, or call the typed `dispatch` directly with an already-parsed request.\n * The server is provider-agnostic — JSON-RPC plus the tool registry, with no HTTP\n * and no model. The {@link import('@orkestrel/tool').ToolManagerInterface} already\n * isolates a thrown tool into a `success: false` result (surfaced as an MCP\n * `isError: true` tool result), so a misbehaving tool never crashes a dispatch. Subscribe to the\n * `request` event via `server.emitter.on('request', …)` for tracing.\n *\n * @param options - `identity` (the server identity), `tools` (the live tool\n * registry), optional `resources` (the consumer-owned resource registry), optional\n * `prompts` (the consumer-owned prompt registry), optional `completion` (the host-owned\n * prompt and resource-template completion provider),\n * optional `instructions`, and the reserved `on`\n * {@link import('@orkestrel/emitter').EmitterHooks} (see {@link MCPServerOptions})\n * @returns A working {@link MCPServerInterface}\n *\n * @example\n * ```ts\n * import { createMCPServer, createTool, createToolManager } from '@src/core'\n *\n * const tools = createToolManager()\n * tools.add(createTool({ name: 'add', execute: (a) => Number(a.x) + Number(a.y) }))\n *\n * const server = createMCPServer({ identity: { name: 'calculator', version: '1.0.0' }, tools })\n * server.emitter.on('request', (method, id) => log(method, id))\n *\n * // A transport pumps message strings through `handle`:\n * const reply = await server.handle('{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"id\":1,\"params\":{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}}}')\n * // reply → '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"tools\":[{\"name\":\"add\",\"inputSchema\":{\"type\":\"object\"}}],\"resultType\":\"complete\",\"ttlMs\":60000,\"cacheScope\":\"private\",\"_meta\":{\"io.modelcontextprotocol/serverInfo\":{\"name\":\"calculator\",\"version\":\"1.0.0\"}}}}'\n * ```\n */\nexport function createMCPServer(options: MCPServerOptions): MCPServerInterface {\n\treturn new MCPServer(options)\n}\n\n/**\n * Decorate one MCP server with the fixed legacy method translation.\n *\n * @param server - The sole modern dispatcher and handshake identity source\n * @returns A dispatcher accepting both modern and legacy invocations\n */\nexport function createMCPLegacy(server: MCPServerInterface): MCPDispatcherInterface {\n\treturn new MCPLegacy({ dispatcher: server, identity: server.identity })\n}\n\n/**\n * Create a transport-agnostic Model Context Protocol CLIENT — connects to a REMOTE\n * MCP server over an injected {@link import('./types.js').MCPClientTransportInterface},\n * runs the `initialize` handshake, and exposes the server's tools as local\n * {@link import('@orkestrel/tool').ToolInterface}s an agent can run.\n *\n * @remarks\n * The egress mirror of {@link createMCPServer}: where the server exposes a local tool\n * registry over MCP, the client USES a remote server's tools. `connect()` handshakes,\n * validates and exposes the negotiated protocol, `tools()` lists + wraps the remote\n * tools (each `execute` calls back over the wire),\n * and `call(name, args)` runs a remote `tools/call` (a remote tool failure throws\n * locally, so an agent's {@link import('@orkestrel/tool').ToolManagerInterface}\n * isolates it). The transport is injected — a concrete one (the HTTP transport over\n * `fetch`) lives in the published server environment; the client itself is provider-agnostic. Subscribe\n * to `connect` / `disconnect` / `notification` via `client.on(...)` (or\n * `client.emitter.on(...)`).\n *\n * @param options - `transport` (the carrier; REQUIRED), an optional `identity`\n * (the client identity), `timeout` (the per-request deadline), and the reserved `on`\n * {@link import('@orkestrel/emitter').EmitterHooks} (see {@link MCPClientOptions})\n * @returns A working {@link MCPClientInterface}\n *\n * @example\n * ```ts\n * import { createMCPClient } from '@src/core'\n * import { createHTTPClientTransport } from '@orkestrel/mcp/server'\n *\n * const client = createMCPClient({\n * \ttransport: createHTTPClientTransport({ url: 'http://localhost:3000/mcp' }),\n * })\n * await client.connect()\n * agent.context.tools.add(await client.tools()) // give the agent the remote tools\n * const value = await client.call('search', { query: 'mcp' })\n * ```\n */\nexport function createMCPClient(options: MCPClientOptions): MCPClientInterface {\n\treturn new MCPClient(options)\n}\n\n/**\n * Adapt an {@link MCPTransportInterface} (the environment-agnostic duplex message\n * channel) into a {@link MCPClientTransportInterface} — the additive bridge that lets\n * `createMCPClient` run over the new port without any change to `MCPClient`'s\n * existing shape.\n *\n * @remarks\n * Hand the RESULT to `createMCPClient({ transport })`, then pass the SAME\n * `transport` to {@link import('./helpers.js').bindClient} to complete the inbound\n * wiring: `send` serializes each outbound {@link JSONRPCMessage} and writes it via\n * `transport.send`; `close` closes the underlying\n * `transport`; `start` is a no-op (the duplex channel is already open by the time\n * it is handed in — there is no separate connect step at this layer); `session` is\n * always `undefined` (session correlation is a higher-level concern the duplex port\n * does not carry); and `duplex` is always `true`, because carrying frames in both\n * directions at any moment is exactly what the adapted port is — a claim DRIVEN over a real\n * `MessageChannel` and a real scope pair (a client-initiated `notifications/cancelled`\n * observed arriving at the peer) rather than read back off this literal. The literal is\n * true of the PORT, and stays true only while the port has a peer: close the far half and\n * this transport still declares `true` while carrying nothing, which is the one thing a\n * per-carrier declaration cannot express. Inbound delivery (`emitter`'s `message` / `close` events) is\n * `bindClient`'s job, not this factory's — the returned object exposes a `message`-\n * capable emitter for `bindClient` to push onto.\n *\n * @param transport - The duplex channel to adapt\n * @returns A {@link MCPClientTransportInterface} `createMCPClient` can drive\n *\n * @example\n * ```ts\n * const client = createMCPClient({ transport: createDuplexClientTransport(transport) })\n * const unbind = bindClient(client, transport)\n * await client.connect()\n * ```\n */\nexport function createDuplexClientTransport(\n\ttransport: MCPTransportInterface,\n): MCPClientTransportInterface {\n\tconst emitter = new Emitter<MCPClientTransportEventMap>()\n\treturn {\n\t\temitter,\n\t\tsession: undefined,\n\t\t// The adapted port is a duplex channel by construction — that is the whole of what\n\t\t// `MCPTransportInterface` is — so a client frame written at any moment reaches the peer.\n\t\tduplex: true,\n\t\tasync start(): Promise<void> {\n\t\t\t// The duplex channel is already open by the time it is handed in — no separate\n\t\t\t// connect step at this layer.\n\t\t},\n\t\tasync send(message: JSONRPCMessage): Promise<void> {\n\t\t\tawait transport.send(JSON.stringify(message))\n\t\t},\n\t\tasync close(): Promise<void> {\n\t\t\tawait transport.close()\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,IAAa,uBAAmC;;AAGhD,IAAa,qBAAiC;;AAG9C,IAAa,qBAAiC;;;;;;;;;;AAW9C,IAAa,8BAAqD,OAAO,OAAO;CAC/E;CACA;CACA;AACD,CAAC;;AAGD,IAAa,mBAAmB;;AAGhC,IAAa,wBAAwB;;AAGrC,IAAa,kBAAkB;;AAG/B,IAAa,kBAAkB;;AAG/B,IAAa,wBAAwB;;;;;;;;;;AAWrC,IAAa,sBAAsB;;AAGnC,IAAa,sBAAsB;;;;;;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