@studiometa/productive-mcp 0.10.12 → 0.10.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.
@@ -1 +1 @@
1
- {"version":3,"file":"http-QQVUnV2e.js","names":["#body","#init","crypto","Http2ServerRequest2","h2constants","z.custom","z.union","z.string","z.number","z.looseObject","z.object","z\n .object","z.literal","ErrorCode","z.unknown","z.array","z.enum","z.intersection","z.boolean","z.record","z.preprocess","z\n .looseObject","z\n .looseObject","z\n .object","z.optional","z.null","z.iso.datetime","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","ListPromptsRequestSchema","GetPromptRequestSchema","ListToolsRequestSchema","CallToolRequestSchema","z.discriminatedUnion"],"sources":["../../../node_modules/@hono/node-server/dist/index.mjs","../../../node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js","../../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js","../src/http.ts"],"sourcesContent":["// src/server.ts\nimport { createServer as createServerHTTP } from \"http\";\n\n// src/listener.ts\nimport { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from \"http2\";\n\n// src/request.ts\nimport { Http2ServerRequest } from \"http2\";\nimport { Readable } from \"stream\";\nvar RequestError = class extends Error {\n constructor(message, options) {\n super(message, options);\n this.name = \"RequestError\";\n }\n};\nvar toRequestError = (e) => {\n if (e instanceof RequestError) {\n return e;\n }\n return new RequestError(e.message, { cause: e });\n};\nvar GlobalRequest = global.Request;\nvar Request = class extends GlobalRequest {\n constructor(input, options) {\n if (typeof input === \"object\" && getRequestCache in input) {\n input = input[getRequestCache]();\n }\n if (typeof options?.body?.getReader !== \"undefined\") {\n ;\n options.duplex ??= \"half\";\n }\n super(input, options);\n }\n};\nvar newHeadersFromIncoming = (incoming) => {\n const headerRecord = [];\n const rawHeaders = incoming.rawHeaders;\n for (let i = 0; i < rawHeaders.length; i += 2) {\n const { [i]: key, [i + 1]: value } = rawHeaders;\n if (key.charCodeAt(0) !== /*:*/\n 58) {\n headerRecord.push([key, value]);\n }\n }\n return new Headers(headerRecord);\n};\nvar wrapBodyStream = Symbol(\"wrapBodyStream\");\nvar newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n const init = {\n method,\n headers,\n signal: abortController.signal\n };\n if (method === \"TRACE\") {\n init.method = \"GET\";\n const req = new Request(url, init);\n Object.defineProperty(req, \"method\", {\n get() {\n return \"TRACE\";\n }\n });\n return req;\n }\n if (!(method === \"GET\" || method === \"HEAD\")) {\n if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) {\n init.body = new ReadableStream({\n start(controller) {\n controller.enqueue(incoming.rawBody);\n controller.close();\n }\n });\n } else if (incoming[wrapBodyStream]) {\n let reader;\n init.body = new ReadableStream({\n async pull(controller) {\n try {\n reader ||= Readable.toWeb(incoming).getReader();\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n });\n } else {\n init.body = Readable.toWeb(incoming);\n }\n }\n return new Request(url, init);\n};\nvar getRequestCache = Symbol(\"getRequestCache\");\nvar requestCache = Symbol(\"requestCache\");\nvar incomingKey = Symbol(\"incomingKey\");\nvar urlKey = Symbol(\"urlKey\");\nvar headersKey = Symbol(\"headersKey\");\nvar abortControllerKey = Symbol(\"abortControllerKey\");\nvar getAbortController = Symbol(\"getAbortController\");\nvar requestPrototype = {\n get method() {\n return this[incomingKey].method || \"GET\";\n },\n get url() {\n return this[urlKey];\n },\n get headers() {\n return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n },\n [getAbortController]() {\n this[getRequestCache]();\n return this[abortControllerKey];\n },\n [getRequestCache]() {\n this[abortControllerKey] ||= new AbortController();\n return this[requestCache] ||= newRequestFromIncoming(\n this.method,\n this[urlKey],\n this.headers,\n this[incomingKey],\n this[abortControllerKey]\n );\n }\n};\n[\n \"body\",\n \"bodyUsed\",\n \"cache\",\n \"credentials\",\n \"destination\",\n \"integrity\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"keepalive\"\n].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n get() {\n return this[getRequestCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n value: function() {\n return this[getRequestCache]()[k]();\n }\n });\n});\nObject.setPrototypeOf(requestPrototype, Request.prototype);\nvar newRequest = (incoming, defaultHostname) => {\n const req = Object.create(requestPrototype);\n req[incomingKey] = incoming;\n const incomingUrl = incoming.url || \"\";\n if (incomingUrl[0] !== \"/\" && // short-circuit for performance. most requests are relative URL.\n (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n if (incoming instanceof Http2ServerRequest) {\n throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n }\n try {\n const url2 = new URL(incomingUrl);\n req[urlKey] = url2.href;\n } catch (e) {\n throw new RequestError(\"Invalid absolute URL\", { cause: e });\n }\n return req;\n }\n const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n if (!host) {\n throw new RequestError(\"Missing host header\");\n }\n let scheme;\n if (incoming instanceof Http2ServerRequest) {\n scheme = incoming.scheme;\n if (!(scheme === \"http\" || scheme === \"https\")) {\n throw new RequestError(\"Unsupported scheme\");\n }\n } else {\n scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n }\n const url = new URL(`${scheme}://${host}${incomingUrl}`);\n if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\\d+$/, \"\")) {\n throw new RequestError(\"Invalid host header\");\n }\n req[urlKey] = url.href;\n return req;\n};\n\n// src/response.ts\nvar responseCache = Symbol(\"responseCache\");\nvar getResponseCache = Symbol(\"getResponseCache\");\nvar cacheKey = Symbol(\"cache\");\nvar GlobalResponse = global.Response;\nvar Response2 = class _Response {\n #body;\n #init;\n [getResponseCache]() {\n delete this[cacheKey];\n return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);\n }\n constructor(body, init) {\n let headers;\n this.#body = body;\n if (init instanceof _Response) {\n const cachedGlobalResponse = init[responseCache];\n if (cachedGlobalResponse) {\n this.#init = cachedGlobalResponse;\n this[getResponseCache]();\n return;\n } else {\n this.#init = init.#init;\n headers = new Headers(init.#init.headers);\n }\n } else {\n this.#init = init;\n }\n if (typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) {\n ;\n this[cacheKey] = [init?.status || 200, body, headers || init?.headers];\n }\n }\n get headers() {\n const cache = this[cacheKey];\n if (cache) {\n if (!(cache[2] instanceof Headers)) {\n cache[2] = new Headers(\n cache[2] || { \"content-type\": \"text/plain; charset=UTF-8\" }\n );\n }\n return cache[2];\n }\n return this[getResponseCache]().headers;\n }\n get status() {\n return this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n }\n get ok() {\n const status = this.status;\n return status >= 200 && status < 300;\n }\n};\n[\"body\", \"bodyUsed\", \"redirected\", \"statusText\", \"trailers\", \"type\", \"url\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n get() {\n return this[getResponseCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n value: function() {\n return this[getResponseCache]()[k]();\n }\n });\n});\nObject.setPrototypeOf(Response2, GlobalResponse);\nObject.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);\n\n// src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n const cancel = (error) => {\n reader.cancel(error).catch(() => {\n });\n };\n writable.on(\"close\", cancel);\n writable.on(\"error\", cancel);\n (currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n return reader.closed.finally(() => {\n writable.off(\"close\", cancel);\n writable.off(\"error\", cancel);\n });\n function handleStreamError(error) {\n if (error) {\n writable.destroy(error);\n }\n }\n function onDrain() {\n reader.read().then(flow, handleStreamError);\n }\n function flow({ done, value }) {\n try {\n if (done) {\n writable.end();\n } else if (!writable.write(value)) {\n writable.once(\"drain\", onDrain);\n } else {\n return reader.read().then(flow, handleStreamError);\n }\n } catch (e) {\n handleStreamError(e);\n }\n }\n}\nfunction writeFromReadableStream(stream, writable) {\n if (stream.locked) {\n throw new TypeError(\"ReadableStream is locked.\");\n } else if (writable.destroyed) {\n return;\n }\n return writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nvar buildOutgoingHttpHeaders = (headers) => {\n const res = {};\n if (!(headers instanceof Headers)) {\n headers = new Headers(headers ?? void 0);\n }\n const cookies = [];\n for (const [k, v] of headers) {\n if (k === \"set-cookie\") {\n cookies.push(v);\n } else {\n res[k] = v;\n }\n }\n if (cookies.length > 0) {\n res[\"set-cookie\"] = cookies;\n }\n res[\"content-type\"] ??= \"text/plain; charset=UTF-8\";\n return res;\n};\n\n// src/utils/response/constants.ts\nvar X_ALREADY_SENT = \"x-hono-already-sent\";\n\n// src/globals.ts\nimport crypto from \"crypto\";\nif (typeof global.crypto === \"undefined\") {\n global.crypto = crypto;\n}\n\n// src/listener.ts\nvar outgoingEnded = Symbol(\"outgoingEnded\");\nvar incomingDraining = Symbol(\"incomingDraining\");\nvar DRAIN_TIMEOUT_MS = 500;\nvar MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nvar drainIncoming = (incoming) => {\n const incomingWithDrainState = incoming;\n if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {\n return;\n }\n incomingWithDrainState[incomingDraining] = true;\n if (incoming instanceof Http2ServerRequest2) {\n try {\n ;\n incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);\n } catch {\n }\n return;\n }\n let bytesRead = 0;\n const cleanup = () => {\n clearTimeout(timer);\n incoming.off(\"data\", onData);\n incoming.off(\"end\", cleanup);\n incoming.off(\"error\", cleanup);\n };\n const forceClose = () => {\n cleanup();\n const socket = incoming.socket;\n if (socket && !socket.destroyed) {\n socket.destroySoon();\n }\n };\n const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n timer.unref?.();\n const onData = (chunk) => {\n bytesRead += chunk.length;\n if (bytesRead > MAX_DRAIN_BYTES) {\n forceClose();\n }\n };\n incoming.on(\"data\", onData);\n incoming.on(\"end\", cleanup);\n incoming.on(\"error\", cleanup);\n incoming.resume();\n};\nvar handleRequestError = () => new Response(null, {\n status: 400\n});\nvar handleFetchError = (e) => new Response(null, {\n status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500\n});\nvar handleResponseError = (e, outgoing) => {\n const err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n if (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") {\n console.info(\"The user aborted a request.\");\n } else {\n console.error(e);\n if (!outgoing.headersSent) {\n outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n }\n outgoing.end(`Error: ${err.message}`);\n outgoing.destroy(err);\n }\n};\nvar flushHeaders = (outgoing) => {\n if (\"flushHeaders\" in outgoing && outgoing.writable) {\n outgoing.flushHeaders();\n }\n};\nvar responseViaCache = async (res, outgoing) => {\n let [status, body, header] = res[cacheKey];\n let hasContentLength = false;\n if (!header) {\n header = { \"content-type\": \"text/plain; charset=UTF-8\" };\n } else if (header instanceof Headers) {\n hasContentLength = header.has(\"content-length\");\n header = buildOutgoingHttpHeaders(header);\n } else if (Array.isArray(header)) {\n const headerObj = new Headers(header);\n hasContentLength = headerObj.has(\"content-length\");\n header = buildOutgoingHttpHeaders(headerObj);\n } else {\n for (const key in header) {\n if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n hasContentLength = true;\n break;\n }\n }\n }\n if (!hasContentLength) {\n if (typeof body === \"string\") {\n header[\"Content-Length\"] = Buffer.byteLength(body);\n } else if (body instanceof Uint8Array) {\n header[\"Content-Length\"] = body.byteLength;\n } else if (body instanceof Blob) {\n header[\"Content-Length\"] = body.size;\n }\n }\n outgoing.writeHead(status, header);\n if (typeof body === \"string\" || body instanceof Uint8Array) {\n outgoing.end(body);\n } else if (body instanceof Blob) {\n outgoing.end(new Uint8Array(await body.arrayBuffer()));\n } else {\n flushHeaders(outgoing);\n await writeFromReadableStream(body, outgoing)?.catch(\n (e) => handleResponseError(e, outgoing)\n );\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar isPromise = (res) => typeof res.then === \"function\";\nvar responseViaResponseObject = async (res, outgoing, options = {}) => {\n if (isPromise(res)) {\n if (options.errorHandler) {\n try {\n res = await res;\n } catch (err) {\n const errRes = await options.errorHandler(err);\n if (!errRes) {\n return;\n }\n res = errRes;\n }\n } else {\n res = await res.catch(handleFetchError);\n }\n }\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);\n if (res.body) {\n const reader = res.body.getReader();\n const values = [];\n let done = false;\n let currentReadPromise = void 0;\n if (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n let maxReadCount = 2;\n for (let i = 0; i < maxReadCount; i++) {\n currentReadPromise ||= reader.read();\n const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n console.error(e);\n done = true;\n });\n if (!chunk) {\n if (i === 1) {\n await new Promise((resolve) => setTimeout(resolve));\n maxReadCount = 3;\n continue;\n }\n break;\n }\n currentReadPromise = void 0;\n if (chunk.value) {\n values.push(chunk.value);\n }\n if (chunk.done) {\n done = true;\n break;\n }\n }\n if (done && !(\"content-length\" in resHeaderRecord)) {\n resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n }\n }\n outgoing.writeHead(res.status, resHeaderRecord);\n values.forEach((value) => {\n ;\n outgoing.write(value);\n });\n if (done) {\n outgoing.end();\n } else {\n if (values.length === 0) {\n flushHeaders(outgoing);\n }\n await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n }\n } else if (resHeaderRecord[X_ALREADY_SENT]) {\n } else {\n outgoing.writeHead(res.status, resHeaderRecord);\n outgoing.end();\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar getRequestListener = (fetchCallback, options = {}) => {\n const autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n if (options.overrideGlobalObjects !== false && global.Request !== Request) {\n Object.defineProperty(global, \"Request\", {\n value: Request\n });\n Object.defineProperty(global, \"Response\", {\n value: Response2\n });\n }\n return async (incoming, outgoing) => {\n let res, req;\n try {\n req = newRequest(incoming, options.hostname);\n let incomingEnded = !autoCleanupIncoming || incoming.method === \"GET\" || incoming.method === \"HEAD\";\n if (!incomingEnded) {\n ;\n incoming[wrapBodyStream] = true;\n incoming.on(\"end\", () => {\n incomingEnded = true;\n });\n if (incoming instanceof Http2ServerRequest2) {\n ;\n outgoing[outgoingEnded] = () => {\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n };\n }\n outgoing.on(\"finish\", () => {\n if (!incomingEnded) {\n drainIncoming(incoming);\n }\n });\n }\n outgoing.on(\"close\", () => {\n const abortController = req[abortControllerKey];\n if (abortController) {\n if (incoming.errored) {\n req[abortControllerKey].abort(incoming.errored.toString());\n } else if (!outgoing.writableFinished) {\n req[abortControllerKey].abort(\"Client connection prematurely closed.\");\n }\n }\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n });\n res = fetchCallback(req, { incoming, outgoing });\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n } catch (e) {\n if (!res) {\n if (options.errorHandler) {\n res = await options.errorHandler(req ? e : toRequestError(e));\n if (!res) {\n return;\n }\n } else if (!req) {\n res = handleRequestError();\n } else {\n res = handleFetchError(e);\n }\n } else {\n return handleResponseError(e, outgoing);\n }\n }\n try {\n return await responseViaResponseObject(res, outgoing, options);\n } catch (e) {\n return handleResponseError(e, outgoing);\n }\n };\n};\n\n// src/server.ts\nvar createAdaptorServer = (options) => {\n const fetchCallback = options.fetch;\n const requestListener = getRequestListener(fetchCallback, {\n hostname: options.hostname,\n overrideGlobalObjects: options.overrideGlobalObjects,\n autoCleanupIncoming: options.autoCleanupIncoming\n });\n const createServer = options.createServer || createServerHTTP;\n const server = createServer(options.serverOptions || {}, requestListener);\n return server;\n};\nvar serve = (options, listeningListener) => {\n const server = createAdaptorServer(options);\n server.listen(options?.port ?? 3e3, options.hostname, () => {\n const serverInfo = server.address();\n listeningListener && listeningListener(serverInfo);\n });\n return server;\n};\nexport {\n RequestError,\n createAdaptorServer,\n getRequestListener,\n serve\n};\n","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Requested duration in milliseconds to retain task from creation.\n */\n ttl: z.number().optional(),\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a CreateTaskResult immediately, and the actual result can be\n * retrieved later via tasks/result.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n ...RequestSchema.shape\n})\n .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n ...NotificationSchema.shape\n})\n .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n result: ResultSchema\n})\n .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n // SDK error codes\n ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n // Standard JSON-RPC error codes\n ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n // MCP-specific error codes\n ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema.optional(),\n error: z.object({\n /**\n * The error type that occurred.\n */\n code: z.number().int(),\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: z.string(),\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: z.unknown().optional()\n })\n})\n .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for Tool,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n if (Object.keys(value).length === 0) {\n return { form: {} };\n }\n }\n return value;\n}, z.intersection(z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n */\nexport const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via includeContext parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: AssertObjectSchema.optional(),\n /**\n * Present if the client supports tool use via tools and toolChoice parameters.\n */\n tools: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n */\n tasks: ClientTasksCapabilitySchema.optional(),\n /**\n * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: AssertObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: AssertObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n */\n tasks: ServerTasksCapabilitySchema.optional(),\n /**\n * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n /**\n * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n */\n instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n }\n catch {\n return false;\n }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size: z.optional(z.number()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n});\n/**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with ToolResultContent in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's inputSchema.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n/**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint: z.boolean().optional(),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint: z.boolean().optional(),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint: z.boolean().optional(),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - \"required\": Clients MUST invoke the tool as a task\n * - \"optional\": Clients MAY invoke the tool as a task or normal request\n * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to \"forbidden\".\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have type: 'object' at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the structuredContent field of a CallToolResult.\n * Must have type: 'object' at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the Tool does not define an outputSchema, this field MUST be present in the result.\n * For backwards compatibility, this field is always present, but it may be empty.\n */\n content: z.array(ContentBlockSchema).default([]),\n /**\n * An object containing structured tool output.\n *\n * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n});\n/**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n /**\n * If true, the list will be refreshed automatically when a list changed notification is received.\n * The callback will be called with the updated list.\n *\n * If false, the callback will be called with null items, allowing manual refresh.\n *\n * @default true\n */\n autoRefresh: z.boolean().default(true),\n /**\n * Debounce time in milliseconds for list changed notification processing.\n *\n * Multiple notifications received within this timeframe will only trigger one refresh.\n * Set to 0 to disable debouncing.\n *\n * @default 300\n */\n debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.\n */\n level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n});\n/**\n * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"required\": Model MUST use at least one tool before completing\n * - \"none\": Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema).default([]),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: AssertObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n * - \"toolUse\": The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n })),\n default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n }))\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z.object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly decline the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize null to undefined for leniency while maintaining type compatibility.\n */\n content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n constructor(code, message, data) {\n super(`MCP error ${code}: ${message}`);\n this.code = code;\n this.data = data;\n this.name = 'McpError';\n }\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code, message, data) {\n // Check for specific error types\n if (code === ErrorCode.UrlElicitationRequired && data) {\n const errorData = data;\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations, message);\n }\n }\n // Default to generic McpError\n return new McpError(code, message, data);\n }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n get elicitations() {\n return this.data?.elicitations ?? [];\n }\n}\n//# sourceMappingURL=types.js.map","/**\n * Web Standards Streamable HTTP Server Transport\n *\n * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream).\n * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.\n *\n * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport.\n */\nimport { isInitializeRequest, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../types.js';\n/**\n * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification\n * using Web Standard APIs (Request, Response, ReadableStream).\n *\n * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.\n *\n * Usage example:\n *\n * ```typescript\n * // Stateful mode - server sets the session ID\n * const statefulTransport = new WebStandardStreamableHTTPServerTransport({\n * sessionIdGenerator: () => crypto.randomUUID(),\n * });\n *\n * // Stateless mode - explicitly set session ID to undefined\n * const statelessTransport = new WebStandardStreamableHTTPServerTransport({\n * sessionIdGenerator: undefined,\n * });\n *\n * // Hono.js usage\n * app.all('/mcp', async (c) => {\n * return transport.handleRequest(c.req.raw);\n * });\n *\n * // Cloudflare Workers usage\n * export default {\n * async fetch(request: Request): Promise<Response> {\n * return transport.handleRequest(request);\n * }\n * };\n * ```\n *\n * In stateful mode:\n * - Session ID is generated and included in response headers\n * - Session ID is always included in initialization responses\n * - Requests with invalid session IDs are rejected with 404 Not Found\n * - Non-initialization requests without a session ID are rejected with 400 Bad Request\n * - State is maintained in-memory (connections, message history)\n *\n * In stateless mode:\n * - No Session ID is included in any responses\n * - No session validation is performed\n */\nexport class WebStandardStreamableHTTPServerTransport {\n constructor(options = {}) {\n this._started = false;\n this._hasHandledRequest = false;\n this._streamMapping = new Map();\n this._requestToStreamMapping = new Map();\n this._requestResponseMap = new Map();\n this._initialized = false;\n this._enableJsonResponse = false;\n this._standaloneSseStreamId = '_GET_stream';\n this.sessionIdGenerator = options.sessionIdGenerator;\n this._enableJsonResponse = options.enableJsonResponse ?? false;\n this._eventStore = options.eventStore;\n this._onsessioninitialized = options.onsessioninitialized;\n this._onsessionclosed = options.onsessionclosed;\n this._allowedHosts = options.allowedHosts;\n this._allowedOrigins = options.allowedOrigins;\n this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false;\n this._retryInterval = options.retryInterval;\n }\n /**\n * Starts the transport. This is required by the Transport interface but is a no-op\n * for the Streamable HTTP transport as connections are managed per-request.\n */\n async start() {\n if (this._started) {\n throw new Error('Transport already started');\n }\n this._started = true;\n }\n /**\n * Helper to create a JSON error response\n */\n createJsonErrorResponse(status, code, message, options) {\n const error = { code, message };\n if (options?.data !== undefined) {\n error.data = options.data;\n }\n return new Response(JSON.stringify({\n jsonrpc: '2.0',\n error,\n id: null\n }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n ...options?.headers\n }\n });\n }\n /**\n * Validates request headers for DNS rebinding protection.\n * @returns Error response if validation fails, undefined if validation passes.\n */\n validateRequestHeaders(req) {\n // Skip validation if protection is not enabled\n if (!this._enableDnsRebindingProtection) {\n return undefined;\n }\n // Validate Host header if allowedHosts is configured\n if (this._allowedHosts && this._allowedHosts.length > 0) {\n const hostHeader = req.headers.get('host');\n if (!hostHeader || !this._allowedHosts.includes(hostHeader)) {\n const error = `Invalid Host header: ${hostHeader}`;\n this.onerror?.(new Error(error));\n return this.createJsonErrorResponse(403, -32000, error);\n }\n }\n // Validate Origin header if allowedOrigins is configured\n if (this._allowedOrigins && this._allowedOrigins.length > 0) {\n const originHeader = req.headers.get('origin');\n if (originHeader && !this._allowedOrigins.includes(originHeader)) {\n const error = `Invalid Origin header: ${originHeader}`;\n this.onerror?.(new Error(error));\n return this.createJsonErrorResponse(403, -32000, error);\n }\n }\n return undefined;\n }\n /**\n * Handles an incoming HTTP request, whether GET, POST, or DELETE\n * Returns a Response object (Web Standard)\n */\n async handleRequest(req, options) {\n // In stateless mode (no sessionIdGenerator), each request must use a fresh transport.\n // Reusing a stateless transport causes message ID collisions between clients.\n if (!this.sessionIdGenerator && this._hasHandledRequest) {\n throw new Error('Stateless transport cannot be reused across requests. Create a new transport per request.');\n }\n this._hasHandledRequest = true;\n // Validate request headers for DNS rebinding protection\n const validationError = this.validateRequestHeaders(req);\n if (validationError) {\n return validationError;\n }\n switch (req.method) {\n case 'POST':\n return this.handlePostRequest(req, options);\n case 'GET':\n return this.handleGetRequest(req);\n case 'DELETE':\n return this.handleDeleteRequest(req);\n default:\n return this.handleUnsupportedRequest();\n }\n }\n /**\n * Writes a priming event to establish resumption capability.\n * Only sends if eventStore is configured (opt-in for resumability) and\n * the client's protocol version supports empty SSE data (>= 2025-11-25).\n */\n async writePrimingEvent(controller, encoder, streamId, protocolVersion) {\n if (!this._eventStore) {\n return;\n }\n // Priming events have empty data which older clients cannot handle.\n // Only send priming events to clients with protocol version >= 2025-11-25\n // which includes the fix for handling empty SSE data.\n if (protocolVersion < '2025-11-25') {\n return;\n }\n const primingEventId = await this._eventStore.storeEvent(streamId, {});\n let primingEvent = `id: ${primingEventId}\\ndata: \\n\\n`;\n if (this._retryInterval !== undefined) {\n primingEvent = `id: ${primingEventId}\\nretry: ${this._retryInterval}\\ndata: \\n\\n`;\n }\n controller.enqueue(encoder.encode(primingEvent));\n }\n /**\n * Handles GET requests for SSE stream\n */\n async handleGetRequest(req) {\n // The client MUST include an Accept header, listing text/event-stream as a supported content type.\n const acceptHeader = req.headers.get('accept');\n if (!acceptHeader?.includes('text/event-stream')) {\n this.onerror?.(new Error('Not Acceptable: Client must accept text/event-stream'));\n return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept text/event-stream');\n }\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n // Handle resumability: check for Last-Event-ID header\n if (this._eventStore) {\n const lastEventId = req.headers.get('last-event-id');\n if (lastEventId) {\n return this.replayEvents(lastEventId);\n }\n }\n // Check if there's already an active standalone SSE stream for this session\n if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) {\n // Only one GET SSE stream is allowed per session\n this.onerror?.(new Error('Conflict: Only one SSE stream is allowed per session'));\n return this.createJsonErrorResponse(409, -32000, 'Conflict: Only one SSE stream is allowed per session');\n }\n const encoder = new TextEncoder();\n let streamController;\n // Create a ReadableStream with a controller we can use to push SSE events\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n this._streamMapping.delete(this._standaloneSseStreamId);\n }\n });\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive'\n };\n // After initialization, always include the session ID if we have one\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Store the stream mapping with the controller for pushing data\n this._streamMapping.set(this._standaloneSseStreamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(this._standaloneSseStreamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n return new Response(readable, { headers });\n }\n /**\n * Replays events that would have been sent after the specified event ID\n * Only used when resumability is enabled\n */\n async replayEvents(lastEventId) {\n if (!this._eventStore) {\n this.onerror?.(new Error('Event store not configured'));\n return this.createJsonErrorResponse(400, -32000, 'Event store not configured');\n }\n try {\n // If getStreamIdForEventId is available, use it for conflict checking\n let streamId;\n if (this._eventStore.getStreamIdForEventId) {\n streamId = await this._eventStore.getStreamIdForEventId(lastEventId);\n if (!streamId) {\n this.onerror?.(new Error('Invalid event ID format'));\n return this.createJsonErrorResponse(400, -32000, 'Invalid event ID format');\n }\n // Check conflict with the SAME streamId we'll use for mapping\n if (this._streamMapping.get(streamId) !== undefined) {\n this.onerror?.(new Error('Conflict: Stream already has an active connection'));\n return this.createJsonErrorResponse(409, -32000, 'Conflict: Stream already has an active connection');\n }\n }\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive'\n };\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Create a ReadableStream with controller for SSE\n const encoder = new TextEncoder();\n let streamController;\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n // Cleanup will be handled by the mapping\n }\n });\n // Replay events - returns the streamId for backwards compatibility\n const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, {\n send: async (eventId, message) => {\n const success = this.writeSSEEvent(streamController, encoder, message, eventId);\n if (!success) {\n this.onerror?.(new Error('Failed replay events'));\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n }\n });\n this._streamMapping.set(replayedStreamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(replayedStreamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n return new Response(readable, { headers });\n }\n catch (error) {\n this.onerror?.(error);\n return this.createJsonErrorResponse(500, -32000, 'Error replaying events');\n }\n }\n /**\n * Writes an event to an SSE stream via controller with proper formatting\n */\n writeSSEEvent(controller, encoder, message, eventId) {\n try {\n let eventData = `event: message\\n`;\n // Include event ID if provided - this is important for resumability\n if (eventId) {\n eventData += `id: ${eventId}\\n`;\n }\n eventData += `data: ${JSON.stringify(message)}\\n\\n`;\n controller.enqueue(encoder.encode(eventData));\n return true;\n }\n catch (error) {\n this.onerror?.(error);\n return false;\n }\n }\n /**\n * Handles unsupported requests (PUT, PATCH, etc.)\n */\n handleUnsupportedRequest() {\n this.onerror?.(new Error('Method not allowed.'));\n return new Response(JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: 'Method not allowed.'\n },\n id: null\n }), {\n status: 405,\n headers: {\n Allow: 'GET, POST, DELETE',\n 'Content-Type': 'application/json'\n }\n });\n }\n /**\n * Handles POST requests containing JSON-RPC messages\n */\n async handlePostRequest(req, options) {\n try {\n // Validate the Accept header\n const acceptHeader = req.headers.get('accept');\n // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types.\n if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) {\n this.onerror?.(new Error('Not Acceptable: Client must accept both application/json and text/event-stream'));\n return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept both application/json and text/event-stream');\n }\n const ct = req.headers.get('content-type');\n if (!ct || !ct.includes('application/json')) {\n this.onerror?.(new Error('Unsupported Media Type: Content-Type must be application/json'));\n return this.createJsonErrorResponse(415, -32000, 'Unsupported Media Type: Content-Type must be application/json');\n }\n // Build request info from headers and URL\n const requestInfo = {\n headers: Object.fromEntries(req.headers.entries()),\n url: new URL(req.url)\n };\n let rawMessage;\n if (options?.parsedBody !== undefined) {\n rawMessage = options.parsedBody;\n }\n else {\n try {\n rawMessage = await req.json();\n }\n catch {\n this.onerror?.(new Error('Parse error: Invalid JSON'));\n return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON');\n }\n }\n let messages;\n // handle batch and single messages\n try {\n if (Array.isArray(rawMessage)) {\n messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg));\n }\n else {\n messages = [JSONRPCMessageSchema.parse(rawMessage)];\n }\n }\n catch {\n this.onerror?.(new Error('Parse error: Invalid JSON-RPC message'));\n return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON-RPC message');\n }\n // Check if this is an initialization request\n // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/\n const isInitializationRequest = messages.some(isInitializeRequest);\n if (isInitializationRequest) {\n // If it's a server with session management and the session ID is already set we should reject the request\n // to avoid re-initialization.\n if (this._initialized && this.sessionId !== undefined) {\n this.onerror?.(new Error('Invalid Request: Server already initialized'));\n return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Server already initialized');\n }\n if (messages.length > 1) {\n this.onerror?.(new Error('Invalid Request: Only one initialization request is allowed'));\n return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Only one initialization request is allowed');\n }\n this.sessionId = this.sessionIdGenerator?.();\n this._initialized = true;\n // If we have a session ID and an onsessioninitialized handler, call it immediately\n // This is needed in cases where the server needs to keep track of multiple sessions\n if (this.sessionId && this._onsessioninitialized) {\n await Promise.resolve(this._onsessioninitialized(this.sessionId));\n }\n }\n if (!isInitializationRequest) {\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n // Mcp-Protocol-Version header is required for all requests after initialization.\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n }\n // check if it contains requests\n const hasRequests = messages.some(isJSONRPCRequest);\n if (!hasRequests) {\n // if it only contains notifications or responses, return 202\n for (const message of messages) {\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });\n }\n return new Response(null, { status: 202 });\n }\n // The default behavior is to use SSE streaming\n // but in some cases server will return JSON responses\n const streamId = crypto.randomUUID();\n // Extract protocol version for priming event decision.\n // For initialize requests, get from request params.\n // For other requests, get from header (already validated).\n const initRequest = messages.find(m => isInitializeRequest(m));\n const clientProtocolVersion = initRequest\n ? initRequest.params.protocolVersion\n : (req.headers.get('mcp-protocol-version') ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION);\n if (this._enableJsonResponse) {\n // For JSON response mode, return a Promise that resolves when all responses are ready\n return new Promise(resolve => {\n this._streamMapping.set(streamId, {\n resolveJson: resolve,\n cleanup: () => {\n this._streamMapping.delete(streamId);\n }\n });\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n this._requestToStreamMapping.set(message.id, streamId);\n }\n }\n for (const message of messages) {\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });\n }\n });\n }\n // SSE streaming mode - use ReadableStream with controller for more reliable data pushing\n const encoder = new TextEncoder();\n let streamController;\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n this._streamMapping.delete(streamId);\n }\n });\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive'\n };\n // After initialization, always include the session ID if we have one\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Store the response for this request to send messages back through this connection\n // We need to track by request ID to maintain the connection\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n this._streamMapping.set(streamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(streamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n this._requestToStreamMapping.set(message.id, streamId);\n }\n }\n // Write priming event if event store is configured (after mapping is set up)\n await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion);\n // handle each message\n for (const message of messages) {\n // Build closeSSEStream callback for requests when eventStore is configured\n // AND client supports resumability (protocol version >= 2025-11-25).\n // Old clients can't resume if the stream is closed early because they\n // didn't receive a priming event with an event ID.\n let closeSSEStream;\n let closeStandaloneSSEStream;\n if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= '2025-11-25') {\n closeSSEStream = () => {\n this.closeSSEStream(message.id);\n };\n closeStandaloneSSEStream = () => {\n this.closeStandaloneSSEStream();\n };\n }\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream });\n }\n // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses\n // This will be handled by the send() method when responses are ready\n return new Response(readable, { status: 200, headers });\n }\n catch (error) {\n // return JSON-RPC formatted error\n this.onerror?.(error);\n return this.createJsonErrorResponse(400, -32700, 'Parse error', { data: String(error) });\n }\n }\n /**\n * Handles DELETE requests to terminate sessions\n */\n async handleDeleteRequest(req) {\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n await Promise.resolve(this._onsessionclosed?.(this.sessionId));\n await this.close();\n return new Response(null, { status: 200 });\n }\n /**\n * Validates session ID for non-initialization requests.\n * Returns Response error if invalid, undefined otherwise\n */\n validateSession(req) {\n if (this.sessionIdGenerator === undefined) {\n // If the sessionIdGenerator ID is not set, the session management is disabled\n // and we don't need to validate the session ID\n return undefined;\n }\n if (!this._initialized) {\n // If the server has not been initialized yet, reject all requests\n this.onerror?.(new Error('Bad Request: Server not initialized'));\n return this.createJsonErrorResponse(400, -32000, 'Bad Request: Server not initialized');\n }\n const sessionId = req.headers.get('mcp-session-id');\n if (!sessionId) {\n // Non-initialization requests without a session ID should return 400 Bad Request\n this.onerror?.(new Error('Bad Request: Mcp-Session-Id header is required'));\n return this.createJsonErrorResponse(400, -32000, 'Bad Request: Mcp-Session-Id header is required');\n }\n if (sessionId !== this.sessionId) {\n // Reject requests with invalid session ID with 404 Not Found\n this.onerror?.(new Error('Session not found'));\n return this.createJsonErrorResponse(404, -32001, 'Session not found');\n }\n return undefined;\n }\n /**\n * Validates the MCP-Protocol-Version header on incoming requests.\n *\n * For initialization: Version negotiation handles unknown versions gracefully\n * (server responds with its supported version).\n *\n * For subsequent requests with MCP-Protocol-Version header:\n * - Accept if in supported list\n * - 400 if unsupported\n *\n * For HTTP requests without the MCP-Protocol-Version header:\n * - Accept and default to the version negotiated at initialization\n */\n validateProtocolVersion(req) {\n const protocolVersion = req.headers.get('mcp-protocol-version');\n if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {\n this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${protocolVersion}` +\n ` (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`));\n return this.createJsonErrorResponse(400, -32000, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`);\n }\n return undefined;\n }\n async close() {\n // Close all SSE connections\n this._streamMapping.forEach(({ cleanup }) => {\n cleanup();\n });\n this._streamMapping.clear();\n // Clear any pending responses\n this._requestResponseMap.clear();\n this.onclose?.();\n }\n /**\n * Close an SSE stream for a specific request, triggering client reconnection.\n * Use this to implement polling behavior during long-running operations -\n * client will reconnect after the retry interval specified in the priming event.\n */\n closeSSEStream(requestId) {\n const streamId = this._requestToStreamMapping.get(requestId);\n if (!streamId)\n return;\n const stream = this._streamMapping.get(streamId);\n if (stream) {\n stream.cleanup();\n }\n }\n /**\n * Close the standalone GET SSE stream, triggering client reconnection.\n * Use this to implement polling behavior for server-initiated notifications.\n */\n closeStandaloneSSEStream() {\n const stream = this._streamMapping.get(this._standaloneSseStreamId);\n if (stream) {\n stream.cleanup();\n }\n }\n async send(message, options) {\n let requestId = options?.relatedRequestId;\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n // If the message is a response, use the request ID from the message\n requestId = message.id;\n }\n // Check if this message should be sent on the standalone SSE stream (no request ID)\n // Ignore notifications from tools (which have relatedRequestId set)\n // Those will be sent via dedicated response SSE streams\n if (requestId === undefined) {\n // For standalone SSE streams, we can only send requests and notifications\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request');\n }\n // Generate and store event ID if event store is provided\n // Store even if stream is disconnected so events can be replayed on reconnect\n let eventId;\n if (this._eventStore) {\n // Stores the event and gets the generated event ID\n eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message);\n }\n const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId);\n if (standaloneSse === undefined) {\n // Stream is disconnected - event is stored for replay, nothing more to do\n return;\n }\n // Send the message to the standalone SSE stream\n if (standaloneSse.controller && standaloneSse.encoder) {\n this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId);\n }\n return;\n }\n // Get the response for this request\n const streamId = this._requestToStreamMapping.get(requestId);\n if (!streamId) {\n throw new Error(`No connection established for request ID: ${String(requestId)}`);\n }\n const stream = this._streamMapping.get(streamId);\n if (!this._enableJsonResponse && stream?.controller && stream?.encoder) {\n // For SSE responses, generate event ID if event store is provided\n let eventId;\n if (this._eventStore) {\n eventId = await this._eventStore.storeEvent(streamId, message);\n }\n // Write the event to the response stream\n this.writeSSEEvent(stream.controller, stream.encoder, message, eventId);\n }\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._requestResponseMap.set(requestId, message);\n const relatedIds = Array.from(this._requestToStreamMapping.entries())\n .filter(([_, sid]) => sid === streamId)\n .map(([id]) => id);\n // Check if we have responses for all requests using this connection\n const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id));\n if (allResponsesReady) {\n if (!stream) {\n throw new Error(`No connection established for request ID: ${String(requestId)}`);\n }\n if (this._enableJsonResponse && stream.resolveJson) {\n // All responses ready, send as JSON\n const headers = {\n 'Content-Type': 'application/json'\n };\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n const responses = relatedIds.map(id => this._requestResponseMap.get(id));\n if (responses.length === 1) {\n stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers }));\n }\n else {\n stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers }));\n }\n }\n else {\n // End the SSE stream\n stream.cleanup();\n }\n // Clean up\n for (const id of relatedIds) {\n this._requestResponseMap.delete(id);\n this._requestToStreamMapping.delete(id);\n }\n }\n }\n }\n}\n//# sourceMappingURL=webStandardStreamableHttp.js.map","/**\n * Node.js HTTP Streamable HTTP Server Transport\n *\n * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides\n * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse).\n *\n * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly.\n */\nimport { getRequestListener } from '@hono/node-server';\nimport { WebStandardStreamableHTTPServerTransport } from './webStandardStreamableHttp.js';\n/**\n * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.\n * It supports both SSE streaming and direct HTTP responses.\n *\n * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility.\n * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs.\n *\n * Usage example:\n *\n * ```typescript\n * // Stateful mode - server sets the session ID\n * const statefulTransport = new StreamableHTTPServerTransport({\n * sessionIdGenerator: () => randomUUID(),\n * });\n *\n * // Stateless mode - explicitly set session ID to undefined\n * const statelessTransport = new StreamableHTTPServerTransport({\n * sessionIdGenerator: undefined,\n * });\n *\n * // Using with pre-parsed request body\n * app.post('/mcp', (req, res) => {\n * transport.handleRequest(req, res, req.body);\n * });\n * ```\n *\n * In stateful mode:\n * - Session ID is generated and included in response headers\n * - Session ID is always included in initialization responses\n * - Requests with invalid session IDs are rejected with 404 Not Found\n * - Non-initialization requests without a session ID are rejected with 400 Bad Request\n * - State is maintained in-memory (connections, message history)\n *\n * In stateless mode:\n * - No Session ID is included in any responses\n * - No session validation is performed\n */\nexport class StreamableHTTPServerTransport {\n constructor(options = {}) {\n // Store auth and parsedBody per request for passing through to handleRequest\n this._requestContext = new WeakMap();\n this._webStandardTransport = new WebStandardStreamableHTTPServerTransport(options);\n // Create a request listener that wraps the web standard transport\n // getRequestListener converts Node.js HTTP to Web Standard and properly handles SSE streaming\n // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would\n // break frameworks like Next.js whose response classes extend the native Response\n this._requestListener = getRequestListener(async (webRequest) => {\n // Get context if available (set during handleRequest)\n const context = this._requestContext.get(webRequest);\n return this._webStandardTransport.handleRequest(webRequest, {\n authInfo: context?.authInfo,\n parsedBody: context?.parsedBody\n });\n }, { overrideGlobalObjects: false });\n }\n /**\n * Gets the session ID for this transport instance.\n */\n get sessionId() {\n return this._webStandardTransport.sessionId;\n }\n /**\n * Sets callback for when the transport is closed.\n */\n set onclose(handler) {\n this._webStandardTransport.onclose = handler;\n }\n get onclose() {\n return this._webStandardTransport.onclose;\n }\n /**\n * Sets callback for transport errors.\n */\n set onerror(handler) {\n this._webStandardTransport.onerror = handler;\n }\n get onerror() {\n return this._webStandardTransport.onerror;\n }\n /**\n * Sets callback for incoming messages.\n */\n set onmessage(handler) {\n this._webStandardTransport.onmessage = handler;\n }\n get onmessage() {\n return this._webStandardTransport.onmessage;\n }\n /**\n * Starts the transport. This is required by the Transport interface but is a no-op\n * for the Streamable HTTP transport as connections are managed per-request.\n */\n async start() {\n return this._webStandardTransport.start();\n }\n /**\n * Closes the transport and all active connections.\n */\n async close() {\n return this._webStandardTransport.close();\n }\n /**\n * Sends a JSON-RPC message through the transport.\n */\n async send(message, options) {\n return this._webStandardTransport.send(message, options);\n }\n /**\n * Handles an incoming HTTP request, whether GET or POST.\n *\n * This method converts Node.js HTTP objects to Web Standard Request/Response\n * and delegates to the underlying WebStandardStreamableHTTPServerTransport.\n *\n * @param req - Node.js IncomingMessage, optionally with auth property from middleware\n * @param res - Node.js ServerResponse\n * @param parsedBody - Optional pre-parsed body from body-parser middleware\n */\n async handleRequest(req, res, parsedBody) {\n // Store context for this request to pass through auth and parsedBody\n // We need to intercept the request creation to attach this context\n const authInfo = req.auth;\n // Create a custom handler that includes our context\n // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would\n // break frameworks like Next.js whose response classes extend the native Response\n const handler = getRequestListener(async (webRequest) => {\n return this._webStandardTransport.handleRequest(webRequest, {\n authInfo,\n parsedBody\n });\n }, { overrideGlobalObjects: false });\n // Delegate to the request listener which handles all the Node.js <-> Web Standard conversion\n // including proper SSE streaming support\n await handler(req, res);\n }\n /**\n * Close an SSE stream for a specific request, triggering client reconnection.\n * Use this to implement polling behavior during long-running operations -\n * client will reconnect after the retry interval specified in the priming event.\n */\n closeSSEStream(requestId) {\n this._webStandardTransport.closeSSEStream(requestId);\n }\n /**\n * Close the standalone GET SSE stream, triggering client reconnection.\n * Use this to implement polling behavior for server-initiated notifications.\n */\n closeStandaloneSSEStream() {\n this._webStandardTransport.closeStandaloneSSEStream();\n }\n}\n//# sourceMappingURL=streamableHttp.js.map","/**\n * HTTP transport handlers for Productive MCP Server\n *\n * This module contains the app/router creation logic for the HTTP transport.\n * The actual server startup is in server.ts.\n */\n\nimport type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';\nimport type { IncomingMessage } from 'node:http';\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport {\n CallToolRequestSchema,\n ErrorCode,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListResourcesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { H3, defineHandler, type H3Event } from 'h3';\n\nconst OAUTH_PROTECTED_RESOURCE_PATH = '/.well-known/oauth-protected-resource/mcp';\n\nimport { parseAuthHeader, type ProductiveCredentials } from './auth.js';\nimport { executeToolWithCredentials } from './handlers.js';\nimport { INSTRUCTIONS } from './instructions.js';\nimport {\n oauthMetadataHandler,\n registerHandler,\n authorizeGetHandler,\n authorizePostHandler,\n tokenHandler,\n} from './oauth.js';\nimport { listResources, listResourceTemplates, readResource } from './resources.js';\nimport { getAvailablePrompts, handlePrompt } from './stdio.js';\nimport { TOOLS } from './tools.js';\nimport { VERSION } from './version.js';\n\n/**\n * JSON-RPC error response\n */\nexport function jsonRpcError(code: number, message: string, id: string | number | null = null) {\n return {\n jsonrpc: '2.0',\n error: { code, message },\n id,\n };\n}\n\n/**\n * JSON-RPC success response\n */\nexport function jsonRpcSuccess(result: unknown, id: string | number | null = null) {\n return {\n jsonrpc: '2.0',\n result,\n id,\n };\n}\n\n/**\n * Handle the initialize JSON-RPC method\n */\nexport function handleInitialize() {\n return {\n protocolVersion: '2024-11-05',\n serverInfo: {\n name: 'productive-mcp',\n version: VERSION,\n },\n capabilities: {\n tools: {},\n prompts: {},\n resources: {},\n },\n instructions: INSTRUCTIONS,\n };\n}\n\n/**\n * Handle the tools/list JSON-RPC method\n */\nexport function handleToolsList() {\n return { tools: TOOLS };\n}\n\n/**\n * Get base URL from event headers\n */\nfunction getBaseUrl(event: H3Event): string {\n const host = event.req.headers.get('host') || 'localhost:3000';\n const protocol = event.req.headers.get('x-forwarded-proto') || 'http';\n return `${protocol}://${host}`;\n}\n\nfunction buildProtectedResourceMetadata(event: H3Event) {\n const baseUrl = getBaseUrl(event);\n\n return {\n resource: `${baseUrl}/mcp`,\n authorization_servers: [baseUrl],\n scopes_supported: ['productive'],\n bearer_methods_supported: ['header'],\n };\n}\n\nfunction createAuthInfo(token: string, credentials: ProductiveCredentials): AuthInfo {\n return {\n token,\n clientId: credentials.userId || credentials.organizationId,\n scopes: ['productive'],\n extra: {\n credentials,\n },\n };\n}\n\nfunction getCredentialsFromAuthInfo(authInfo: AuthInfo | undefined | null): ProductiveCredentials {\n const credentials = authInfo?.extra?.credentials;\n\n if (\n !credentials ||\n typeof credentials !== 'object' ||\n !('organizationId' in credentials) ||\n !('apiToken' in credentials) ||\n typeof credentials.organizationId !== 'string' ||\n typeof credentials.apiToken !== 'string'\n ) {\n throw new Error(\n 'Authentication required. Provide Bearer token with base64(organizationId:apiToken:userId)',\n );\n }\n\n const userId =\n 'userId' in credentials && typeof credentials.userId === 'string'\n ? credentials.userId\n : undefined;\n\n return {\n organizationId: credentials.organizationId,\n apiToken: credentials.apiToken,\n userId,\n };\n}\n\nexport function createHttpMcpServer(): Server {\n const server = new Server(\n {\n name: 'productive-mcp',\n version: VERSION,\n },\n {\n capabilities: {\n tools: {},\n prompts: {},\n resources: {},\n },\n instructions: INSTRUCTIONS,\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return { tools: TOOLS };\n });\n\n server.setRequestHandler(ListPromptsRequestSchema, async () => {\n return { prompts: getAvailablePrompts() };\n });\n\n server.setRequestHandler(GetPromptRequestSchema, async (request) => {\n return handlePrompt(request.params.name, request.params.arguments as Record<string, string>);\n });\n\n server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return { resources: listResources() };\n });\n\n server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {\n return { resourceTemplates: listResourceTemplates() };\n });\n\n server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {\n const credentials = getCredentialsFromAuthInfo(extra.authInfo);\n\n if (!request.params.uri) {\n throw new McpError(ErrorCode.InvalidParams, 'Invalid params: uri is required');\n }\n\n return readResource(request.params.uri, credentials);\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n const credentials = getCredentialsFromAuthInfo(extra.authInfo);\n return executeToolWithCredentials(\n request.params.name,\n (request.params.arguments as Record<string, unknown>) || {},\n credentials,\n );\n });\n\n return server;\n}\n\nexport async function createHttpMcpTransport(): Promise<StreamableHTTPServerTransport> {\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n\n const server = createHttpMcpServer();\n await server.connect(transport);\n\n return transport;\n}\n\nfunction setUnauthorizedResponseHeaders(event: H3Event) {\n const baseUrl = getBaseUrl(event);\n event.res.headers.delete('Set-Cookie');\n event.res.headers.set(\n 'WWW-Authenticate',\n `Bearer resource_metadata=\"${baseUrl}${OAUTH_PROTECTED_RESOURCE_PATH}\"`,\n );\n}\n\nfunction authenticateRequest(event: H3Event): AuthInfo | null {\n const authHeader = event.req.headers.get('authorization');\n const tokenMatch = authHeader?.match(/^Bearer\\s+(.+)$/i);\n const credentials = parseAuthHeader(authHeader);\n\n if (!credentials || !tokenMatch?.[1]) {\n return null;\n }\n\n return createAuthInfo(tokenMatch[1], credentials);\n}\n\n/**\n * Create the H3 application with all routes\n */\nexport function createHttpApp(): H3 {\n const app = new H3();\n\n // OAuth 2.0 endpoints for Claude Desktop integration (MCP auth spec)\n app.get('/.well-known/oauth-authorization-server', oauthMetadataHandler);\n app.post('/register', registerHandler); // Dynamic Client Registration (RFC 7591)\n app.get('/authorize', authorizeGetHandler);\n app.post('/authorize', authorizePostHandler);\n app.post('/token', tokenHandler);\n\n // OAuth Protected Resource Metadata (RFC 9728 / MCP spec 2025-03-26)\n const protectedResourceMetadataHandler = defineHandler((event) => {\n event.res.headers.set('Content-Type', 'application/json');\n event.res.headers.set('Cache-Control', 'public, max-age=3600');\n\n return buildProtectedResourceMetadata(event);\n });\n\n app.get(OAUTH_PROTECTED_RESOURCE_PATH, protectedResourceMetadataHandler);\n\n // Health check endpoint\n app.get(\n '/',\n defineHandler(() => {\n return { status: 'ok', service: 'productive-mcp', version: VERSION };\n }),\n );\n\n app.get(\n '/health',\n defineHandler(() => {\n return { status: 'ok' };\n }),\n );\n\n const mcpHandler = defineHandler(async (event) => {\n const authInfo = authenticateRequest(event);\n\n if (!authInfo) {\n setUnauthorizedResponseHeaders(event);\n event.res.status = 401;\n event.res.headers.set('Content-Type', 'application/json');\n return event.req.method === 'POST'\n ? jsonRpcError(\n -32001,\n 'Authentication required. Provide Bearer token with base64(organizationId:apiToken:userId)',\n )\n : { error: 'Authentication required' };\n }\n\n const nodeReq = event.runtime?.node?.req as (IncomingMessage & { auth?: AuthInfo }) | undefined;\n const nodeRes = event.runtime?.node?.res as import('node:http').ServerResponse | undefined;\n\n if (!nodeReq || !nodeRes) {\n event.res.status = 501;\n return { error: 'MCP HTTP transport requires Node.js runtime' };\n }\n\n nodeReq.auth = authInfo;\n\n let parsedBody: unknown;\n if (event.req.method === 'POST') {\n try {\n parsedBody = await event.req.json();\n } catch {\n event.res.status = 400;\n event.res.headers.set('Content-Type', 'application/json');\n return jsonRpcError(-32700, 'Parse error: Invalid JSON');\n }\n\n const body = parsedBody as\n | { method?: string; params?: { uri?: string }; id?: string | number | null }\n | undefined;\n if (body?.method === 'resources/read' && !body.params?.uri) {\n event.res.status = 200;\n event.res.headers.set('Content-Type', 'application/json');\n return jsonRpcError(-32602, 'Invalid params: uri is required', body.id ?? null);\n }\n }\n\n const transport = await createHttpMcpTransport();\n await transport.handleRequest(nodeReq, nodeRes, parsedBody);\n\n return undefined;\n });\n\n app.get('/mcp', mcpHandler);\n app.post('/mcp', mcpHandler);\n app.delete('/mcp', mcpHandler);\n\n return app;\n}\n"],"x_google_ignoreList":[0,1,2,3],"mappings":";;;;;;;;;;;;;;AASA,IAAI,eAAe,cAAc,MAAM;CACrC,YAAY,SAAS,SAAS;EAC5B,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;AACA,IAAI,kBAAkB,MAAM;CAC1B,IAAI,aAAa,cACf,OAAO;CAET,OAAO,IAAI,aAAa,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC;AACjD;AACA,IAAI,gBAAgB,OAAO;AAC3B,IAAI,UAAU,cAAc,cAAc;CACxC,YAAY,OAAO,SAAS;EAC1B,IAAI,OAAO,UAAU,YAAY,mBAAmB,OAClD,QAAQ,MAAM,iBAAiB;EAEjC,IAAI,OAAO,SAAS,MAAM,cAAc,aAEtC,QAAQ,WAAW;EAErB,MAAM,OAAO,OAAO;CACtB;AACF;AACA,IAAI,0BAA0B,aAAa;CACzC,MAAM,eAAe,CAAC;CACtB,MAAM,aAAa,SAAS;CAC5B,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK,GAAG;EAC7C,MAAM,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU;EACrC,IAAI,IAAI,WAAW,CAAC,MACpB,IACE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;IACF,aAAa,MAAM,MAAM,IAAI,KAAK;GACpC,QAAQ;IACN,MAAM,IAAI,SAAS;IACnB,MAAM,IAAI,QAAQ,IAAI,gBAAgB,kBAAkB;IACxD,OAAO,aAAa,QAAQ,2BAA2B;GACzD;GAEA,MAAM,OAAO;GAGb,IAAI,MAAM,WAAW,oBAAoB,CAAC,KAAK,QAAQ,KAAK;IAC1D,MAAM,IAAI,SAAS;IACnB,MAAM,IAAI,QAAQ,IAAI,gBAAgB,kBAAkB;IACxD,OAAO,aAAa,QAAQ,mCAAmC,KAAK,MAAM,IAAI;GAChF;EACF;EAGA,OAAM,MADkB,uBAAuB,GAC/B,cAAc,SAAS,SAAS,UAAU;CAG5D,CAAC;CAED,IAAI,IAAI,QAAQ,UAAU;CAC1B,IAAI,KAAK,QAAQ,UAAU;CAC3B,IAAI,OAAO,QAAQ,UAAU;CAE7B,OAAO;AACT"}
1
+ {"version":3,"file":"http-BJd4MLh0.js","names":["#body","#init","crypto","Http2ServerRequest2","h2constants","z.custom","z.union","z.string","z.number","z.looseObject","z.object","z\n .object","z.literal","ErrorCode","z.unknown","z.array","z.enum","z.intersection","z.boolean","z.record","z.preprocess","z\n .looseObject","z\n .looseObject","z\n .object","z.optional","z.null","z.iso.datetime","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","ListPromptsRequestSchema","GetPromptRequestSchema","ListToolsRequestSchema","CallToolRequestSchema","z.discriminatedUnion"],"sources":["../../../node_modules/@hono/node-server/dist/index.mjs","../../../node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js","../../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js","../src/http.ts"],"sourcesContent":["// src/server.ts\nimport { createServer as createServerHTTP } from \"http\";\n\n// src/listener.ts\nimport { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from \"http2\";\n\n// src/request.ts\nimport { Http2ServerRequest } from \"http2\";\nimport { Readable } from \"stream\";\nvar RequestError = class extends Error {\n constructor(message, options) {\n super(message, options);\n this.name = \"RequestError\";\n }\n};\nvar toRequestError = (e) => {\n if (e instanceof RequestError) {\n return e;\n }\n return new RequestError(e.message, { cause: e });\n};\nvar GlobalRequest = global.Request;\nvar Request = class extends GlobalRequest {\n constructor(input, options) {\n if (typeof input === \"object\" && getRequestCache in input) {\n input = input[getRequestCache]();\n }\n if (typeof options?.body?.getReader !== \"undefined\") {\n ;\n options.duplex ??= \"half\";\n }\n super(input, options);\n }\n};\nvar newHeadersFromIncoming = (incoming) => {\n const headerRecord = [];\n const rawHeaders = incoming.rawHeaders;\n for (let i = 0; i < rawHeaders.length; i += 2) {\n const { [i]: key, [i + 1]: value } = rawHeaders;\n if (key.charCodeAt(0) !== /*:*/\n 58) {\n headerRecord.push([key, value]);\n }\n }\n return new Headers(headerRecord);\n};\nvar wrapBodyStream = Symbol(\"wrapBodyStream\");\nvar newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n const init = {\n method,\n headers,\n signal: abortController.signal\n };\n if (method === \"TRACE\") {\n init.method = \"GET\";\n const req = new Request(url, init);\n Object.defineProperty(req, \"method\", {\n get() {\n return \"TRACE\";\n }\n });\n return req;\n }\n if (!(method === \"GET\" || method === \"HEAD\")) {\n if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) {\n init.body = new ReadableStream({\n start(controller) {\n controller.enqueue(incoming.rawBody);\n controller.close();\n }\n });\n } else if (incoming[wrapBodyStream]) {\n let reader;\n init.body = new ReadableStream({\n async pull(controller) {\n try {\n reader ||= Readable.toWeb(incoming).getReader();\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n });\n } else {\n init.body = Readable.toWeb(incoming);\n }\n }\n return new Request(url, init);\n};\nvar getRequestCache = Symbol(\"getRequestCache\");\nvar requestCache = Symbol(\"requestCache\");\nvar incomingKey = Symbol(\"incomingKey\");\nvar urlKey = Symbol(\"urlKey\");\nvar headersKey = Symbol(\"headersKey\");\nvar abortControllerKey = Symbol(\"abortControllerKey\");\nvar getAbortController = Symbol(\"getAbortController\");\nvar requestPrototype = {\n get method() {\n return this[incomingKey].method || \"GET\";\n },\n get url() {\n return this[urlKey];\n },\n get headers() {\n return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n },\n [getAbortController]() {\n this[getRequestCache]();\n return this[abortControllerKey];\n },\n [getRequestCache]() {\n this[abortControllerKey] ||= new AbortController();\n return this[requestCache] ||= newRequestFromIncoming(\n this.method,\n this[urlKey],\n this.headers,\n this[incomingKey],\n this[abortControllerKey]\n );\n }\n};\n[\n \"body\",\n \"bodyUsed\",\n \"cache\",\n \"credentials\",\n \"destination\",\n \"integrity\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"keepalive\"\n].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n get() {\n return this[getRequestCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n value: function() {\n return this[getRequestCache]()[k]();\n }\n });\n});\nObject.setPrototypeOf(requestPrototype, Request.prototype);\nvar newRequest = (incoming, defaultHostname) => {\n const req = Object.create(requestPrototype);\n req[incomingKey] = incoming;\n const incomingUrl = incoming.url || \"\";\n if (incomingUrl[0] !== \"/\" && // short-circuit for performance. most requests are relative URL.\n (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n if (incoming instanceof Http2ServerRequest) {\n throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n }\n try {\n const url2 = new URL(incomingUrl);\n req[urlKey] = url2.href;\n } catch (e) {\n throw new RequestError(\"Invalid absolute URL\", { cause: e });\n }\n return req;\n }\n const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n if (!host) {\n throw new RequestError(\"Missing host header\");\n }\n let scheme;\n if (incoming instanceof Http2ServerRequest) {\n scheme = incoming.scheme;\n if (!(scheme === \"http\" || scheme === \"https\")) {\n throw new RequestError(\"Unsupported scheme\");\n }\n } else {\n scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n }\n const url = new URL(`${scheme}://${host}${incomingUrl}`);\n if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\\d+$/, \"\")) {\n throw new RequestError(\"Invalid host header\");\n }\n req[urlKey] = url.href;\n return req;\n};\n\n// src/response.ts\nvar responseCache = Symbol(\"responseCache\");\nvar getResponseCache = Symbol(\"getResponseCache\");\nvar cacheKey = Symbol(\"cache\");\nvar GlobalResponse = global.Response;\nvar Response2 = class _Response {\n #body;\n #init;\n [getResponseCache]() {\n delete this[cacheKey];\n return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);\n }\n constructor(body, init) {\n let headers;\n this.#body = body;\n if (init instanceof _Response) {\n const cachedGlobalResponse = init[responseCache];\n if (cachedGlobalResponse) {\n this.#init = cachedGlobalResponse;\n this[getResponseCache]();\n return;\n } else {\n this.#init = init.#init;\n headers = new Headers(init.#init.headers);\n }\n } else {\n this.#init = init;\n }\n if (typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) {\n ;\n this[cacheKey] = [init?.status || 200, body, headers || init?.headers];\n }\n }\n get headers() {\n const cache = this[cacheKey];\n if (cache) {\n if (!(cache[2] instanceof Headers)) {\n cache[2] = new Headers(\n cache[2] || { \"content-type\": \"text/plain; charset=UTF-8\" }\n );\n }\n return cache[2];\n }\n return this[getResponseCache]().headers;\n }\n get status() {\n return this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n }\n get ok() {\n const status = this.status;\n return status >= 200 && status < 300;\n }\n};\n[\"body\", \"bodyUsed\", \"redirected\", \"statusText\", \"trailers\", \"type\", \"url\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n get() {\n return this[getResponseCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n value: function() {\n return this[getResponseCache]()[k]();\n }\n });\n});\nObject.setPrototypeOf(Response2, GlobalResponse);\nObject.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);\n\n// src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n const cancel = (error) => {\n reader.cancel(error).catch(() => {\n });\n };\n writable.on(\"close\", cancel);\n writable.on(\"error\", cancel);\n (currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n return reader.closed.finally(() => {\n writable.off(\"close\", cancel);\n writable.off(\"error\", cancel);\n });\n function handleStreamError(error) {\n if (error) {\n writable.destroy(error);\n }\n }\n function onDrain() {\n reader.read().then(flow, handleStreamError);\n }\n function flow({ done, value }) {\n try {\n if (done) {\n writable.end();\n } else if (!writable.write(value)) {\n writable.once(\"drain\", onDrain);\n } else {\n return reader.read().then(flow, handleStreamError);\n }\n } catch (e) {\n handleStreamError(e);\n }\n }\n}\nfunction writeFromReadableStream(stream, writable) {\n if (stream.locked) {\n throw new TypeError(\"ReadableStream is locked.\");\n } else if (writable.destroyed) {\n return;\n }\n return writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nvar buildOutgoingHttpHeaders = (headers) => {\n const res = {};\n if (!(headers instanceof Headers)) {\n headers = new Headers(headers ?? void 0);\n }\n const cookies = [];\n for (const [k, v] of headers) {\n if (k === \"set-cookie\") {\n cookies.push(v);\n } else {\n res[k] = v;\n }\n }\n if (cookies.length > 0) {\n res[\"set-cookie\"] = cookies;\n }\n res[\"content-type\"] ??= \"text/plain; charset=UTF-8\";\n return res;\n};\n\n// src/utils/response/constants.ts\nvar X_ALREADY_SENT = \"x-hono-already-sent\";\n\n// src/globals.ts\nimport crypto from \"crypto\";\nif (typeof global.crypto === \"undefined\") {\n global.crypto = crypto;\n}\n\n// src/listener.ts\nvar outgoingEnded = Symbol(\"outgoingEnded\");\nvar incomingDraining = Symbol(\"incomingDraining\");\nvar DRAIN_TIMEOUT_MS = 500;\nvar MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nvar drainIncoming = (incoming) => {\n const incomingWithDrainState = incoming;\n if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {\n return;\n }\n incomingWithDrainState[incomingDraining] = true;\n if (incoming instanceof Http2ServerRequest2) {\n try {\n ;\n incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);\n } catch {\n }\n return;\n }\n let bytesRead = 0;\n const cleanup = () => {\n clearTimeout(timer);\n incoming.off(\"data\", onData);\n incoming.off(\"end\", cleanup);\n incoming.off(\"error\", cleanup);\n };\n const forceClose = () => {\n cleanup();\n const socket = incoming.socket;\n if (socket && !socket.destroyed) {\n socket.destroySoon();\n }\n };\n const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n timer.unref?.();\n const onData = (chunk) => {\n bytesRead += chunk.length;\n if (bytesRead > MAX_DRAIN_BYTES) {\n forceClose();\n }\n };\n incoming.on(\"data\", onData);\n incoming.on(\"end\", cleanup);\n incoming.on(\"error\", cleanup);\n incoming.resume();\n};\nvar handleRequestError = () => new Response(null, {\n status: 400\n});\nvar handleFetchError = (e) => new Response(null, {\n status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500\n});\nvar handleResponseError = (e, outgoing) => {\n const err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n if (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") {\n console.info(\"The user aborted a request.\");\n } else {\n console.error(e);\n if (!outgoing.headersSent) {\n outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n }\n outgoing.end(`Error: ${err.message}`);\n outgoing.destroy(err);\n }\n};\nvar flushHeaders = (outgoing) => {\n if (\"flushHeaders\" in outgoing && outgoing.writable) {\n outgoing.flushHeaders();\n }\n};\nvar responseViaCache = async (res, outgoing) => {\n let [status, body, header] = res[cacheKey];\n let hasContentLength = false;\n if (!header) {\n header = { \"content-type\": \"text/plain; charset=UTF-8\" };\n } else if (header instanceof Headers) {\n hasContentLength = header.has(\"content-length\");\n header = buildOutgoingHttpHeaders(header);\n } else if (Array.isArray(header)) {\n const headerObj = new Headers(header);\n hasContentLength = headerObj.has(\"content-length\");\n header = buildOutgoingHttpHeaders(headerObj);\n } else {\n for (const key in header) {\n if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n hasContentLength = true;\n break;\n }\n }\n }\n if (!hasContentLength) {\n if (typeof body === \"string\") {\n header[\"Content-Length\"] = Buffer.byteLength(body);\n } else if (body instanceof Uint8Array) {\n header[\"Content-Length\"] = body.byteLength;\n } else if (body instanceof Blob) {\n header[\"Content-Length\"] = body.size;\n }\n }\n outgoing.writeHead(status, header);\n if (typeof body === \"string\" || body instanceof Uint8Array) {\n outgoing.end(body);\n } else if (body instanceof Blob) {\n outgoing.end(new Uint8Array(await body.arrayBuffer()));\n } else {\n flushHeaders(outgoing);\n await writeFromReadableStream(body, outgoing)?.catch(\n (e) => handleResponseError(e, outgoing)\n );\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar isPromise = (res) => typeof res.then === \"function\";\nvar responseViaResponseObject = async (res, outgoing, options = {}) => {\n if (isPromise(res)) {\n if (options.errorHandler) {\n try {\n res = await res;\n } catch (err) {\n const errRes = await options.errorHandler(err);\n if (!errRes) {\n return;\n }\n res = errRes;\n }\n } else {\n res = await res.catch(handleFetchError);\n }\n }\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);\n if (res.body) {\n const reader = res.body.getReader();\n const values = [];\n let done = false;\n let currentReadPromise = void 0;\n if (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n let maxReadCount = 2;\n for (let i = 0; i < maxReadCount; i++) {\n currentReadPromise ||= reader.read();\n const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n console.error(e);\n done = true;\n });\n if (!chunk) {\n if (i === 1) {\n await new Promise((resolve) => setTimeout(resolve));\n maxReadCount = 3;\n continue;\n }\n break;\n }\n currentReadPromise = void 0;\n if (chunk.value) {\n values.push(chunk.value);\n }\n if (chunk.done) {\n done = true;\n break;\n }\n }\n if (done && !(\"content-length\" in resHeaderRecord)) {\n resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n }\n }\n outgoing.writeHead(res.status, resHeaderRecord);\n values.forEach((value) => {\n ;\n outgoing.write(value);\n });\n if (done) {\n outgoing.end();\n } else {\n if (values.length === 0) {\n flushHeaders(outgoing);\n }\n await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n }\n } else if (resHeaderRecord[X_ALREADY_SENT]) {\n } else {\n outgoing.writeHead(res.status, resHeaderRecord);\n outgoing.end();\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar getRequestListener = (fetchCallback, options = {}) => {\n const autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n if (options.overrideGlobalObjects !== false && global.Request !== Request) {\n Object.defineProperty(global, \"Request\", {\n value: Request\n });\n Object.defineProperty(global, \"Response\", {\n value: Response2\n });\n }\n return async (incoming, outgoing) => {\n let res, req;\n try {\n req = newRequest(incoming, options.hostname);\n let incomingEnded = !autoCleanupIncoming || incoming.method === \"GET\" || incoming.method === \"HEAD\";\n if (!incomingEnded) {\n ;\n incoming[wrapBodyStream] = true;\n incoming.on(\"end\", () => {\n incomingEnded = true;\n });\n if (incoming instanceof Http2ServerRequest2) {\n ;\n outgoing[outgoingEnded] = () => {\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n };\n }\n outgoing.on(\"finish\", () => {\n if (!incomingEnded) {\n drainIncoming(incoming);\n }\n });\n }\n outgoing.on(\"close\", () => {\n const abortController = req[abortControllerKey];\n if (abortController) {\n if (incoming.errored) {\n req[abortControllerKey].abort(incoming.errored.toString());\n } else if (!outgoing.writableFinished) {\n req[abortControllerKey].abort(\"Client connection prematurely closed.\");\n }\n }\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n });\n res = fetchCallback(req, { incoming, outgoing });\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n } catch (e) {\n if (!res) {\n if (options.errorHandler) {\n res = await options.errorHandler(req ? e : toRequestError(e));\n if (!res) {\n return;\n }\n } else if (!req) {\n res = handleRequestError();\n } else {\n res = handleFetchError(e);\n }\n } else {\n return handleResponseError(e, outgoing);\n }\n }\n try {\n return await responseViaResponseObject(res, outgoing, options);\n } catch (e) {\n return handleResponseError(e, outgoing);\n }\n };\n};\n\n// src/server.ts\nvar createAdaptorServer = (options) => {\n const fetchCallback = options.fetch;\n const requestListener = getRequestListener(fetchCallback, {\n hostname: options.hostname,\n overrideGlobalObjects: options.overrideGlobalObjects,\n autoCleanupIncoming: options.autoCleanupIncoming\n });\n const createServer = options.createServer || createServerHTTP;\n const server = createServer(options.serverOptions || {}, requestListener);\n return server;\n};\nvar serve = (options, listeningListener) => {\n const server = createAdaptorServer(options);\n server.listen(options?.port ?? 3e3, options.hostname, () => {\n const serverInfo = server.address();\n listeningListener && listeningListener(serverInfo);\n });\n return server;\n};\nexport {\n RequestError,\n createAdaptorServer,\n getRequestListener,\n serve\n};\n","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Requested duration in milliseconds to retain task from creation.\n */\n ttl: z.number().optional(),\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a CreateTaskResult immediately, and the actual result can be\n * retrieved later via tasks/result.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n ...RequestSchema.shape\n})\n .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n ...NotificationSchema.shape\n})\n .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n result: ResultSchema\n})\n .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n // SDK error codes\n ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n // Standard JSON-RPC error codes\n ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n // MCP-specific error codes\n ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema.optional(),\n error: z.object({\n /**\n * The error type that occurred.\n */\n code: z.number().int(),\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: z.string(),\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: z.unknown().optional()\n })\n})\n .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for Tool,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n if (Object.keys(value).length === 0) {\n return { form: {} };\n }\n }\n return value;\n}, z.intersection(z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n */\nexport const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via includeContext parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: AssertObjectSchema.optional(),\n /**\n * Present if the client supports tool use via tools and toolChoice parameters.\n */\n tools: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n */\n tasks: ClientTasksCapabilitySchema.optional(),\n /**\n * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: AssertObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: AssertObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n */\n tasks: ServerTasksCapabilitySchema.optional(),\n /**\n * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n /**\n * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n */\n instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n }\n catch {\n return false;\n }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size: z.optional(z.number()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n});\n/**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with ToolResultContent in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's inputSchema.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n/**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint: z.boolean().optional(),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint: z.boolean().optional(),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint: z.boolean().optional(),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - \"required\": Clients MUST invoke the tool as a task\n * - \"optional\": Clients MAY invoke the tool as a task or normal request\n * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to \"forbidden\".\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have type: 'object' at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the structuredContent field of a CallToolResult.\n * Must have type: 'object' at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the Tool does not define an outputSchema, this field MUST be present in the result.\n * For backwards compatibility, this field is always present, but it may be empty.\n */\n content: z.array(ContentBlockSchema).default([]),\n /**\n * An object containing structured tool output.\n *\n * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n});\n/**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n /**\n * If true, the list will be refreshed automatically when a list changed notification is received.\n * The callback will be called with the updated list.\n *\n * If false, the callback will be called with null items, allowing manual refresh.\n *\n * @default true\n */\n autoRefresh: z.boolean().default(true),\n /**\n * Debounce time in milliseconds for list changed notification processing.\n *\n * Multiple notifications received within this timeframe will only trigger one refresh.\n * Set to 0 to disable debouncing.\n *\n * @default 300\n */\n debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.\n */\n level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n});\n/**\n * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"required\": Model MUST use at least one tool before completing\n * - \"none\": Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema).default([]),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: AssertObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n * - \"toolUse\": The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n })),\n default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n }))\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z.object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly decline the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize null to undefined for leniency while maintaining type compatibility.\n */\n content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n constructor(code, message, data) {\n super(`MCP error ${code}: ${message}`);\n this.code = code;\n this.data = data;\n this.name = 'McpError';\n }\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code, message, data) {\n // Check for specific error types\n if (code === ErrorCode.UrlElicitationRequired && data) {\n const errorData = data;\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations, message);\n }\n }\n // Default to generic McpError\n return new McpError(code, message, data);\n }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n get elicitations() {\n return this.data?.elicitations ?? [];\n }\n}\n//# sourceMappingURL=types.js.map","/**\n * Web Standards Streamable HTTP Server Transport\n *\n * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream).\n * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.\n *\n * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport.\n */\nimport { isInitializeRequest, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../types.js';\n/**\n * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification\n * using Web Standard APIs (Request, Response, ReadableStream).\n *\n * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.\n *\n * Usage example:\n *\n * ```typescript\n * // Stateful mode - server sets the session ID\n * const statefulTransport = new WebStandardStreamableHTTPServerTransport({\n * sessionIdGenerator: () => crypto.randomUUID(),\n * });\n *\n * // Stateless mode - explicitly set session ID to undefined\n * const statelessTransport = new WebStandardStreamableHTTPServerTransport({\n * sessionIdGenerator: undefined,\n * });\n *\n * // Hono.js usage\n * app.all('/mcp', async (c) => {\n * return transport.handleRequest(c.req.raw);\n * });\n *\n * // Cloudflare Workers usage\n * export default {\n * async fetch(request: Request): Promise<Response> {\n * return transport.handleRequest(request);\n * }\n * };\n * ```\n *\n * In stateful mode:\n * - Session ID is generated and included in response headers\n * - Session ID is always included in initialization responses\n * - Requests with invalid session IDs are rejected with 404 Not Found\n * - Non-initialization requests without a session ID are rejected with 400 Bad Request\n * - State is maintained in-memory (connections, message history)\n *\n * In stateless mode:\n * - No Session ID is included in any responses\n * - No session validation is performed\n */\nexport class WebStandardStreamableHTTPServerTransport {\n constructor(options = {}) {\n this._started = false;\n this._hasHandledRequest = false;\n this._streamMapping = new Map();\n this._requestToStreamMapping = new Map();\n this._requestResponseMap = new Map();\n this._initialized = false;\n this._enableJsonResponse = false;\n this._standaloneSseStreamId = '_GET_stream';\n this.sessionIdGenerator = options.sessionIdGenerator;\n this._enableJsonResponse = options.enableJsonResponse ?? false;\n this._eventStore = options.eventStore;\n this._onsessioninitialized = options.onsessioninitialized;\n this._onsessionclosed = options.onsessionclosed;\n this._allowedHosts = options.allowedHosts;\n this._allowedOrigins = options.allowedOrigins;\n this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false;\n this._retryInterval = options.retryInterval;\n }\n /**\n * Starts the transport. This is required by the Transport interface but is a no-op\n * for the Streamable HTTP transport as connections are managed per-request.\n */\n async start() {\n if (this._started) {\n throw new Error('Transport already started');\n }\n this._started = true;\n }\n /**\n * Helper to create a JSON error response\n */\n createJsonErrorResponse(status, code, message, options) {\n const error = { code, message };\n if (options?.data !== undefined) {\n error.data = options.data;\n }\n return new Response(JSON.stringify({\n jsonrpc: '2.0',\n error,\n id: null\n }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n ...options?.headers\n }\n });\n }\n /**\n * Validates request headers for DNS rebinding protection.\n * @returns Error response if validation fails, undefined if validation passes.\n */\n validateRequestHeaders(req) {\n // Skip validation if protection is not enabled\n if (!this._enableDnsRebindingProtection) {\n return undefined;\n }\n // Validate Host header if allowedHosts is configured\n if (this._allowedHosts && this._allowedHosts.length > 0) {\n const hostHeader = req.headers.get('host');\n if (!hostHeader || !this._allowedHosts.includes(hostHeader)) {\n const error = `Invalid Host header: ${hostHeader}`;\n this.onerror?.(new Error(error));\n return this.createJsonErrorResponse(403, -32000, error);\n }\n }\n // Validate Origin header if allowedOrigins is configured\n if (this._allowedOrigins && this._allowedOrigins.length > 0) {\n const originHeader = req.headers.get('origin');\n if (originHeader && !this._allowedOrigins.includes(originHeader)) {\n const error = `Invalid Origin header: ${originHeader}`;\n this.onerror?.(new Error(error));\n return this.createJsonErrorResponse(403, -32000, error);\n }\n }\n return undefined;\n }\n /**\n * Handles an incoming HTTP request, whether GET, POST, or DELETE\n * Returns a Response object (Web Standard)\n */\n async handleRequest(req, options) {\n // In stateless mode (no sessionIdGenerator), each request must use a fresh transport.\n // Reusing a stateless transport causes message ID collisions between clients.\n if (!this.sessionIdGenerator && this._hasHandledRequest) {\n throw new Error('Stateless transport cannot be reused across requests. Create a new transport per request.');\n }\n this._hasHandledRequest = true;\n // Validate request headers for DNS rebinding protection\n const validationError = this.validateRequestHeaders(req);\n if (validationError) {\n return validationError;\n }\n switch (req.method) {\n case 'POST':\n return this.handlePostRequest(req, options);\n case 'GET':\n return this.handleGetRequest(req);\n case 'DELETE':\n return this.handleDeleteRequest(req);\n default:\n return this.handleUnsupportedRequest();\n }\n }\n /**\n * Writes a priming event to establish resumption capability.\n * Only sends if eventStore is configured (opt-in for resumability) and\n * the client's protocol version supports empty SSE data (>= 2025-11-25).\n */\n async writePrimingEvent(controller, encoder, streamId, protocolVersion) {\n if (!this._eventStore) {\n return;\n }\n // Priming events have empty data which older clients cannot handle.\n // Only send priming events to clients with protocol version >= 2025-11-25\n // which includes the fix for handling empty SSE data.\n if (protocolVersion < '2025-11-25') {\n return;\n }\n const primingEventId = await this._eventStore.storeEvent(streamId, {});\n let primingEvent = `id: ${primingEventId}\\ndata: \\n\\n`;\n if (this._retryInterval !== undefined) {\n primingEvent = `id: ${primingEventId}\\nretry: ${this._retryInterval}\\ndata: \\n\\n`;\n }\n controller.enqueue(encoder.encode(primingEvent));\n }\n /**\n * Handles GET requests for SSE stream\n */\n async handleGetRequest(req) {\n // The client MUST include an Accept header, listing text/event-stream as a supported content type.\n const acceptHeader = req.headers.get('accept');\n if (!acceptHeader?.includes('text/event-stream')) {\n this.onerror?.(new Error('Not Acceptable: Client must accept text/event-stream'));\n return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept text/event-stream');\n }\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n // Handle resumability: check for Last-Event-ID header\n if (this._eventStore) {\n const lastEventId = req.headers.get('last-event-id');\n if (lastEventId) {\n return this.replayEvents(lastEventId);\n }\n }\n // Check if there's already an active standalone SSE stream for this session\n if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) {\n // Only one GET SSE stream is allowed per session\n this.onerror?.(new Error('Conflict: Only one SSE stream is allowed per session'));\n return this.createJsonErrorResponse(409, -32000, 'Conflict: Only one SSE stream is allowed per session');\n }\n const encoder = new TextEncoder();\n let streamController;\n // Create a ReadableStream with a controller we can use to push SSE events\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n this._streamMapping.delete(this._standaloneSseStreamId);\n }\n });\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive'\n };\n // After initialization, always include the session ID if we have one\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Store the stream mapping with the controller for pushing data\n this._streamMapping.set(this._standaloneSseStreamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(this._standaloneSseStreamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n return new Response(readable, { headers });\n }\n /**\n * Replays events that would have been sent after the specified event ID\n * Only used when resumability is enabled\n */\n async replayEvents(lastEventId) {\n if (!this._eventStore) {\n this.onerror?.(new Error('Event store not configured'));\n return this.createJsonErrorResponse(400, -32000, 'Event store not configured');\n }\n try {\n // If getStreamIdForEventId is available, use it for conflict checking\n let streamId;\n if (this._eventStore.getStreamIdForEventId) {\n streamId = await this._eventStore.getStreamIdForEventId(lastEventId);\n if (!streamId) {\n this.onerror?.(new Error('Invalid event ID format'));\n return this.createJsonErrorResponse(400, -32000, 'Invalid event ID format');\n }\n // Check conflict with the SAME streamId we'll use for mapping\n if (this._streamMapping.get(streamId) !== undefined) {\n this.onerror?.(new Error('Conflict: Stream already has an active connection'));\n return this.createJsonErrorResponse(409, -32000, 'Conflict: Stream already has an active connection');\n }\n }\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive'\n };\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Create a ReadableStream with controller for SSE\n const encoder = new TextEncoder();\n let streamController;\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n // Cleanup will be handled by the mapping\n }\n });\n // Replay events - returns the streamId for backwards compatibility\n const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, {\n send: async (eventId, message) => {\n const success = this.writeSSEEvent(streamController, encoder, message, eventId);\n if (!success) {\n this.onerror?.(new Error('Failed replay events'));\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n }\n });\n this._streamMapping.set(replayedStreamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(replayedStreamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n return new Response(readable, { headers });\n }\n catch (error) {\n this.onerror?.(error);\n return this.createJsonErrorResponse(500, -32000, 'Error replaying events');\n }\n }\n /**\n * Writes an event to an SSE stream via controller with proper formatting\n */\n writeSSEEvent(controller, encoder, message, eventId) {\n try {\n let eventData = `event: message\\n`;\n // Include event ID if provided - this is important for resumability\n if (eventId) {\n eventData += `id: ${eventId}\\n`;\n }\n eventData += `data: ${JSON.stringify(message)}\\n\\n`;\n controller.enqueue(encoder.encode(eventData));\n return true;\n }\n catch (error) {\n this.onerror?.(error);\n return false;\n }\n }\n /**\n * Handles unsupported requests (PUT, PATCH, etc.)\n */\n handleUnsupportedRequest() {\n this.onerror?.(new Error('Method not allowed.'));\n return new Response(JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: 'Method not allowed.'\n },\n id: null\n }), {\n status: 405,\n headers: {\n Allow: 'GET, POST, DELETE',\n 'Content-Type': 'application/json'\n }\n });\n }\n /**\n * Handles POST requests containing JSON-RPC messages\n */\n async handlePostRequest(req, options) {\n try {\n // Validate the Accept header\n const acceptHeader = req.headers.get('accept');\n // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types.\n if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) {\n this.onerror?.(new Error('Not Acceptable: Client must accept both application/json and text/event-stream'));\n return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept both application/json and text/event-stream');\n }\n const ct = req.headers.get('content-type');\n if (!ct || !ct.includes('application/json')) {\n this.onerror?.(new Error('Unsupported Media Type: Content-Type must be application/json'));\n return this.createJsonErrorResponse(415, -32000, 'Unsupported Media Type: Content-Type must be application/json');\n }\n // Build request info from headers and URL\n const requestInfo = {\n headers: Object.fromEntries(req.headers.entries()),\n url: new URL(req.url)\n };\n let rawMessage;\n if (options?.parsedBody !== undefined) {\n rawMessage = options.parsedBody;\n }\n else {\n try {\n rawMessage = await req.json();\n }\n catch {\n this.onerror?.(new Error('Parse error: Invalid JSON'));\n return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON');\n }\n }\n let messages;\n // handle batch and single messages\n try {\n if (Array.isArray(rawMessage)) {\n messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg));\n }\n else {\n messages = [JSONRPCMessageSchema.parse(rawMessage)];\n }\n }\n catch {\n this.onerror?.(new Error('Parse error: Invalid JSON-RPC message'));\n return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON-RPC message');\n }\n // Check if this is an initialization request\n // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/\n const isInitializationRequest = messages.some(isInitializeRequest);\n if (isInitializationRequest) {\n // If it's a server with session management and the session ID is already set we should reject the request\n // to avoid re-initialization.\n if (this._initialized && this.sessionId !== undefined) {\n this.onerror?.(new Error('Invalid Request: Server already initialized'));\n return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Server already initialized');\n }\n if (messages.length > 1) {\n this.onerror?.(new Error('Invalid Request: Only one initialization request is allowed'));\n return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Only one initialization request is allowed');\n }\n this.sessionId = this.sessionIdGenerator?.();\n this._initialized = true;\n // If we have a session ID and an onsessioninitialized handler, call it immediately\n // This is needed in cases where the server needs to keep track of multiple sessions\n if (this.sessionId && this._onsessioninitialized) {\n await Promise.resolve(this._onsessioninitialized(this.sessionId));\n }\n }\n if (!isInitializationRequest) {\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n // Mcp-Protocol-Version header is required for all requests after initialization.\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n }\n // check if it contains requests\n const hasRequests = messages.some(isJSONRPCRequest);\n if (!hasRequests) {\n // if it only contains notifications or responses, return 202\n for (const message of messages) {\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });\n }\n return new Response(null, { status: 202 });\n }\n // The default behavior is to use SSE streaming\n // but in some cases server will return JSON responses\n const streamId = crypto.randomUUID();\n // Extract protocol version for priming event decision.\n // For initialize requests, get from request params.\n // For other requests, get from header (already validated).\n const initRequest = messages.find(m => isInitializeRequest(m));\n const clientProtocolVersion = initRequest\n ? initRequest.params.protocolVersion\n : (req.headers.get('mcp-protocol-version') ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION);\n if (this._enableJsonResponse) {\n // For JSON response mode, return a Promise that resolves when all responses are ready\n return new Promise(resolve => {\n this._streamMapping.set(streamId, {\n resolveJson: resolve,\n cleanup: () => {\n this._streamMapping.delete(streamId);\n }\n });\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n this._requestToStreamMapping.set(message.id, streamId);\n }\n }\n for (const message of messages) {\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });\n }\n });\n }\n // SSE streaming mode - use ReadableStream with controller for more reliable data pushing\n const encoder = new TextEncoder();\n let streamController;\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n this._streamMapping.delete(streamId);\n }\n });\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive'\n };\n // After initialization, always include the session ID if we have one\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Store the response for this request to send messages back through this connection\n // We need to track by request ID to maintain the connection\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n this._streamMapping.set(streamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(streamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n this._requestToStreamMapping.set(message.id, streamId);\n }\n }\n // Write priming event if event store is configured (after mapping is set up)\n await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion);\n // handle each message\n for (const message of messages) {\n // Build closeSSEStream callback for requests when eventStore is configured\n // AND client supports resumability (protocol version >= 2025-11-25).\n // Old clients can't resume if the stream is closed early because they\n // didn't receive a priming event with an event ID.\n let closeSSEStream;\n let closeStandaloneSSEStream;\n if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= '2025-11-25') {\n closeSSEStream = () => {\n this.closeSSEStream(message.id);\n };\n closeStandaloneSSEStream = () => {\n this.closeStandaloneSSEStream();\n };\n }\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream });\n }\n // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses\n // This will be handled by the send() method when responses are ready\n return new Response(readable, { status: 200, headers });\n }\n catch (error) {\n // return JSON-RPC formatted error\n this.onerror?.(error);\n return this.createJsonErrorResponse(400, -32700, 'Parse error', { data: String(error) });\n }\n }\n /**\n * Handles DELETE requests to terminate sessions\n */\n async handleDeleteRequest(req) {\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n await Promise.resolve(this._onsessionclosed?.(this.sessionId));\n await this.close();\n return new Response(null, { status: 200 });\n }\n /**\n * Validates session ID for non-initialization requests.\n * Returns Response error if invalid, undefined otherwise\n */\n validateSession(req) {\n if (this.sessionIdGenerator === undefined) {\n // If the sessionIdGenerator ID is not set, the session management is disabled\n // and we don't need to validate the session ID\n return undefined;\n }\n if (!this._initialized) {\n // If the server has not been initialized yet, reject all requests\n this.onerror?.(new Error('Bad Request: Server not initialized'));\n return this.createJsonErrorResponse(400, -32000, 'Bad Request: Server not initialized');\n }\n const sessionId = req.headers.get('mcp-session-id');\n if (!sessionId) {\n // Non-initialization requests without a session ID should return 400 Bad Request\n this.onerror?.(new Error('Bad Request: Mcp-Session-Id header is required'));\n return this.createJsonErrorResponse(400, -32000, 'Bad Request: Mcp-Session-Id header is required');\n }\n if (sessionId !== this.sessionId) {\n // Reject requests with invalid session ID with 404 Not Found\n this.onerror?.(new Error('Session not found'));\n return this.createJsonErrorResponse(404, -32001, 'Session not found');\n }\n return undefined;\n }\n /**\n * Validates the MCP-Protocol-Version header on incoming requests.\n *\n * For initialization: Version negotiation handles unknown versions gracefully\n * (server responds with its supported version).\n *\n * For subsequent requests with MCP-Protocol-Version header:\n * - Accept if in supported list\n * - 400 if unsupported\n *\n * For HTTP requests without the MCP-Protocol-Version header:\n * - Accept and default to the version negotiated at initialization\n */\n validateProtocolVersion(req) {\n const protocolVersion = req.headers.get('mcp-protocol-version');\n if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {\n this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${protocolVersion}` +\n ` (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`));\n return this.createJsonErrorResponse(400, -32000, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`);\n }\n return undefined;\n }\n async close() {\n // Close all SSE connections\n this._streamMapping.forEach(({ cleanup }) => {\n cleanup();\n });\n this._streamMapping.clear();\n // Clear any pending responses\n this._requestResponseMap.clear();\n this.onclose?.();\n }\n /**\n * Close an SSE stream for a specific request, triggering client reconnection.\n * Use this to implement polling behavior during long-running operations -\n * client will reconnect after the retry interval specified in the priming event.\n */\n closeSSEStream(requestId) {\n const streamId = this._requestToStreamMapping.get(requestId);\n if (!streamId)\n return;\n const stream = this._streamMapping.get(streamId);\n if (stream) {\n stream.cleanup();\n }\n }\n /**\n * Close the standalone GET SSE stream, triggering client reconnection.\n * Use this to implement polling behavior for server-initiated notifications.\n */\n closeStandaloneSSEStream() {\n const stream = this._streamMapping.get(this._standaloneSseStreamId);\n if (stream) {\n stream.cleanup();\n }\n }\n async send(message, options) {\n let requestId = options?.relatedRequestId;\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n // If the message is a response, use the request ID from the message\n requestId = message.id;\n }\n // Check if this message should be sent on the standalone SSE stream (no request ID)\n // Ignore notifications from tools (which have relatedRequestId set)\n // Those will be sent via dedicated response SSE streams\n if (requestId === undefined) {\n // For standalone SSE streams, we can only send requests and notifications\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request');\n }\n // Generate and store event ID if event store is provided\n // Store even if stream is disconnected so events can be replayed on reconnect\n let eventId;\n if (this._eventStore) {\n // Stores the event and gets the generated event ID\n eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message);\n }\n const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId);\n if (standaloneSse === undefined) {\n // Stream is disconnected - event is stored for replay, nothing more to do\n return;\n }\n // Send the message to the standalone SSE stream\n if (standaloneSse.controller && standaloneSse.encoder) {\n this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId);\n }\n return;\n }\n // Get the response for this request\n const streamId = this._requestToStreamMapping.get(requestId);\n if (!streamId) {\n throw new Error(`No connection established for request ID: ${String(requestId)}`);\n }\n const stream = this._streamMapping.get(streamId);\n if (!this._enableJsonResponse && stream?.controller && stream?.encoder) {\n // For SSE responses, generate event ID if event store is provided\n let eventId;\n if (this._eventStore) {\n eventId = await this._eventStore.storeEvent(streamId, message);\n }\n // Write the event to the response stream\n this.writeSSEEvent(stream.controller, stream.encoder, message, eventId);\n }\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._requestResponseMap.set(requestId, message);\n const relatedIds = Array.from(this._requestToStreamMapping.entries())\n .filter(([_, sid]) => sid === streamId)\n .map(([id]) => id);\n // Check if we have responses for all requests using this connection\n const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id));\n if (allResponsesReady) {\n if (!stream) {\n throw new Error(`No connection established for request ID: ${String(requestId)}`);\n }\n if (this._enableJsonResponse && stream.resolveJson) {\n // All responses ready, send as JSON\n const headers = {\n 'Content-Type': 'application/json'\n };\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n const responses = relatedIds.map(id => this._requestResponseMap.get(id));\n if (responses.length === 1) {\n stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers }));\n }\n else {\n stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers }));\n }\n }\n else {\n // End the SSE stream\n stream.cleanup();\n }\n // Clean up\n for (const id of relatedIds) {\n this._requestResponseMap.delete(id);\n this._requestToStreamMapping.delete(id);\n }\n }\n }\n }\n}\n//# sourceMappingURL=webStandardStreamableHttp.js.map","/**\n * Node.js HTTP Streamable HTTP Server Transport\n *\n * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides\n * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse).\n *\n * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly.\n */\nimport { getRequestListener } from '@hono/node-server';\nimport { WebStandardStreamableHTTPServerTransport } from './webStandardStreamableHttp.js';\n/**\n * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.\n * It supports both SSE streaming and direct HTTP responses.\n *\n * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility.\n * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs.\n *\n * Usage example:\n *\n * ```typescript\n * // Stateful mode - server sets the session ID\n * const statefulTransport = new StreamableHTTPServerTransport({\n * sessionIdGenerator: () => randomUUID(),\n * });\n *\n * // Stateless mode - explicitly set session ID to undefined\n * const statelessTransport = new StreamableHTTPServerTransport({\n * sessionIdGenerator: undefined,\n * });\n *\n * // Using with pre-parsed request body\n * app.post('/mcp', (req, res) => {\n * transport.handleRequest(req, res, req.body);\n * });\n * ```\n *\n * In stateful mode:\n * - Session ID is generated and included in response headers\n * - Session ID is always included in initialization responses\n * - Requests with invalid session IDs are rejected with 404 Not Found\n * - Non-initialization requests without a session ID are rejected with 400 Bad Request\n * - State is maintained in-memory (connections, message history)\n *\n * In stateless mode:\n * - No Session ID is included in any responses\n * - No session validation is performed\n */\nexport class StreamableHTTPServerTransport {\n constructor(options = {}) {\n // Store auth and parsedBody per request for passing through to handleRequest\n this._requestContext = new WeakMap();\n this._webStandardTransport = new WebStandardStreamableHTTPServerTransport(options);\n // Create a request listener that wraps the web standard transport\n // getRequestListener converts Node.js HTTP to Web Standard and properly handles SSE streaming\n // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would\n // break frameworks like Next.js whose response classes extend the native Response\n this._requestListener = getRequestListener(async (webRequest) => {\n // Get context if available (set during handleRequest)\n const context = this._requestContext.get(webRequest);\n return this._webStandardTransport.handleRequest(webRequest, {\n authInfo: context?.authInfo,\n parsedBody: context?.parsedBody\n });\n }, { overrideGlobalObjects: false });\n }\n /**\n * Gets the session ID for this transport instance.\n */\n get sessionId() {\n return this._webStandardTransport.sessionId;\n }\n /**\n * Sets callback for when the transport is closed.\n */\n set onclose(handler) {\n this._webStandardTransport.onclose = handler;\n }\n get onclose() {\n return this._webStandardTransport.onclose;\n }\n /**\n * Sets callback for transport errors.\n */\n set onerror(handler) {\n this._webStandardTransport.onerror = handler;\n }\n get onerror() {\n return this._webStandardTransport.onerror;\n }\n /**\n * Sets callback for incoming messages.\n */\n set onmessage(handler) {\n this._webStandardTransport.onmessage = handler;\n }\n get onmessage() {\n return this._webStandardTransport.onmessage;\n }\n /**\n * Starts the transport. This is required by the Transport interface but is a no-op\n * for the Streamable HTTP transport as connections are managed per-request.\n */\n async start() {\n return this._webStandardTransport.start();\n }\n /**\n * Closes the transport and all active connections.\n */\n async close() {\n return this._webStandardTransport.close();\n }\n /**\n * Sends a JSON-RPC message through the transport.\n */\n async send(message, options) {\n return this._webStandardTransport.send(message, options);\n }\n /**\n * Handles an incoming HTTP request, whether GET or POST.\n *\n * This method converts Node.js HTTP objects to Web Standard Request/Response\n * and delegates to the underlying WebStandardStreamableHTTPServerTransport.\n *\n * @param req - Node.js IncomingMessage, optionally with auth property from middleware\n * @param res - Node.js ServerResponse\n * @param parsedBody - Optional pre-parsed body from body-parser middleware\n */\n async handleRequest(req, res, parsedBody) {\n // Store context for this request to pass through auth and parsedBody\n // We need to intercept the request creation to attach this context\n const authInfo = req.auth;\n // Create a custom handler that includes our context\n // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would\n // break frameworks like Next.js whose response classes extend the native Response\n const handler = getRequestListener(async (webRequest) => {\n return this._webStandardTransport.handleRequest(webRequest, {\n authInfo,\n parsedBody\n });\n }, { overrideGlobalObjects: false });\n // Delegate to the request listener which handles all the Node.js <-> Web Standard conversion\n // including proper SSE streaming support\n await handler(req, res);\n }\n /**\n * Close an SSE stream for a specific request, triggering client reconnection.\n * Use this to implement polling behavior during long-running operations -\n * client will reconnect after the retry interval specified in the priming event.\n */\n closeSSEStream(requestId) {\n this._webStandardTransport.closeSSEStream(requestId);\n }\n /**\n * Close the standalone GET SSE stream, triggering client reconnection.\n * Use this to implement polling behavior for server-initiated notifications.\n */\n closeStandaloneSSEStream() {\n this._webStandardTransport.closeStandaloneSSEStream();\n }\n}\n//# sourceMappingURL=streamableHttp.js.map","/**\n * HTTP transport handlers for Productive MCP Server\n *\n * This module contains the app/router creation logic for the HTTP transport.\n * The actual server startup is in server.ts.\n */\n\nimport type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';\nimport type { IncomingMessage } from 'node:http';\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport {\n CallToolRequestSchema,\n ErrorCode,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListResourcesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { H3, defineHandler, type H3Event } from 'h3';\n\nconst OAUTH_PROTECTED_RESOURCE_PATH = '/.well-known/oauth-protected-resource/mcp';\n\nimport { parseAuthHeader, type ProductiveCredentials } from './auth.js';\nimport { executeToolWithCredentials } from './handlers.js';\nimport { INSTRUCTIONS } from './instructions.js';\nimport {\n oauthMetadataHandler,\n registerHandler,\n authorizeGetHandler,\n authorizePostHandler,\n tokenHandler,\n} from './oauth.js';\nimport { listResources, listResourceTemplates, readResource } from './resources.js';\nimport { getAvailablePrompts, handlePrompt } from './stdio.js';\nimport { TOOLS } from './tools.js';\nimport { VERSION } from './version.js';\n\n/**\n * JSON-RPC error response\n */\nexport function jsonRpcError(code: number, message: string, id: string | number | null = null) {\n return {\n jsonrpc: '2.0',\n error: { code, message },\n id,\n };\n}\n\n/**\n * JSON-RPC success response\n */\nexport function jsonRpcSuccess(result: unknown, id: string | number | null = null) {\n return {\n jsonrpc: '2.0',\n result,\n id,\n };\n}\n\n/**\n * Handle the initialize JSON-RPC method\n */\nexport function handleInitialize() {\n return {\n protocolVersion: '2024-11-05',\n serverInfo: {\n name: 'productive-mcp',\n version: VERSION,\n },\n capabilities: {\n tools: {},\n prompts: {},\n resources: {},\n },\n instructions: INSTRUCTIONS,\n };\n}\n\n/**\n * Handle the tools/list JSON-RPC method\n */\nexport function handleToolsList() {\n return { tools: TOOLS };\n}\n\n/**\n * Get base URL from event headers\n */\nfunction getBaseUrl(event: H3Event): string {\n const host = event.req.headers.get('host') || 'localhost:3000';\n const protocol = event.req.headers.get('x-forwarded-proto') || 'http';\n return `${protocol}://${host}`;\n}\n\nfunction buildProtectedResourceMetadata(event: H3Event) {\n const baseUrl = getBaseUrl(event);\n\n return {\n resource: `${baseUrl}/mcp`,\n authorization_servers: [baseUrl],\n scopes_supported: ['productive'],\n bearer_methods_supported: ['header'],\n };\n}\n\nfunction createAuthInfo(token: string, credentials: ProductiveCredentials): AuthInfo {\n return {\n token,\n clientId: credentials.userId || credentials.organizationId,\n scopes: ['productive'],\n extra: {\n credentials,\n },\n };\n}\n\nfunction getCredentialsFromAuthInfo(authInfo: AuthInfo | undefined | null): ProductiveCredentials {\n const credentials = authInfo?.extra?.credentials;\n\n if (\n !credentials ||\n typeof credentials !== 'object' ||\n !('organizationId' in credentials) ||\n !('apiToken' in credentials) ||\n typeof credentials.organizationId !== 'string' ||\n typeof credentials.apiToken !== 'string'\n ) {\n throw new Error(\n 'Authentication required. Provide Bearer token with base64(organizationId:apiToken:userId)',\n );\n }\n\n const userId =\n 'userId' in credentials && typeof credentials.userId === 'string'\n ? credentials.userId\n : undefined;\n\n return {\n organizationId: credentials.organizationId,\n apiToken: credentials.apiToken,\n userId,\n };\n}\n\nexport function createHttpMcpServer(): Server {\n const server = new Server(\n {\n name: 'productive-mcp',\n version: VERSION,\n },\n {\n capabilities: {\n tools: {},\n prompts: {},\n resources: {},\n },\n instructions: INSTRUCTIONS,\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return { tools: TOOLS };\n });\n\n server.setRequestHandler(ListPromptsRequestSchema, async () => {\n return { prompts: getAvailablePrompts() };\n });\n\n server.setRequestHandler(GetPromptRequestSchema, async (request) => {\n return handlePrompt(request.params.name, request.params.arguments as Record<string, string>);\n });\n\n server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return { resources: listResources() };\n });\n\n server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {\n return { resourceTemplates: listResourceTemplates() };\n });\n\n server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {\n const credentials = getCredentialsFromAuthInfo(extra.authInfo);\n\n if (!request.params.uri) {\n throw new McpError(ErrorCode.InvalidParams, 'Invalid params: uri is required');\n }\n\n return readResource(request.params.uri, credentials);\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n const credentials = getCredentialsFromAuthInfo(extra.authInfo);\n return executeToolWithCredentials(\n request.params.name,\n (request.params.arguments as Record<string, unknown>) || {},\n credentials,\n );\n });\n\n return server;\n}\n\nexport async function createHttpMcpTransport(): Promise<StreamableHTTPServerTransport> {\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n\n const server = createHttpMcpServer();\n await server.connect(transport);\n\n return transport;\n}\n\nfunction setUnauthorizedResponseHeaders(event: H3Event) {\n const baseUrl = getBaseUrl(event);\n event.res.headers.delete('Set-Cookie');\n event.res.headers.set(\n 'WWW-Authenticate',\n `Bearer resource_metadata=\"${baseUrl}${OAUTH_PROTECTED_RESOURCE_PATH}\"`,\n );\n}\n\nfunction authenticateRequest(event: H3Event): AuthInfo | null {\n const authHeader = event.req.headers.get('authorization');\n const tokenMatch = authHeader?.match(/^Bearer\\s+(.+)$/i);\n const credentials = parseAuthHeader(authHeader);\n\n if (!credentials || !tokenMatch?.[1]) {\n return null;\n }\n\n return createAuthInfo(tokenMatch[1], credentials);\n}\n\n/**\n * Create the H3 application with all routes\n */\nexport function createHttpApp(): H3 {\n const app = new H3();\n\n // OAuth 2.0 endpoints for Claude Desktop integration (MCP auth spec)\n app.get('/.well-known/oauth-authorization-server', oauthMetadataHandler);\n app.post('/register', registerHandler); // Dynamic Client Registration (RFC 7591)\n app.get('/authorize', authorizeGetHandler);\n app.post('/authorize', authorizePostHandler);\n app.post('/token', tokenHandler);\n\n // OAuth Protected Resource Metadata (RFC 9728 / MCP spec 2025-03-26)\n const protectedResourceMetadataHandler = defineHandler((event) => {\n event.res.headers.set('Content-Type', 'application/json');\n event.res.headers.set('Cache-Control', 'public, max-age=3600');\n\n return buildProtectedResourceMetadata(event);\n });\n\n app.get(OAUTH_PROTECTED_RESOURCE_PATH, protectedResourceMetadataHandler);\n\n // Health check endpoint\n app.get(\n '/',\n defineHandler(() => {\n return { status: 'ok', service: 'productive-mcp', version: VERSION };\n }),\n );\n\n app.get(\n '/health',\n defineHandler(() => {\n return { status: 'ok' };\n }),\n );\n\n const mcpHandler = defineHandler(async (event) => {\n const authInfo = authenticateRequest(event);\n\n if (!authInfo) {\n setUnauthorizedResponseHeaders(event);\n event.res.status = 401;\n event.res.headers.set('Content-Type', 'application/json');\n return event.req.method === 'POST'\n ? jsonRpcError(\n -32001,\n 'Authentication required. Provide Bearer token with base64(organizationId:apiToken:userId)',\n )\n : { error: 'Authentication required' };\n }\n\n const nodeReq = event.runtime?.node?.req as (IncomingMessage & { auth?: AuthInfo }) | undefined;\n const nodeRes = event.runtime?.node?.res as import('node:http').ServerResponse | undefined;\n\n if (!nodeReq || !nodeRes) {\n event.res.status = 501;\n return { error: 'MCP HTTP transport requires Node.js runtime' };\n }\n\n nodeReq.auth = authInfo;\n\n let parsedBody: unknown;\n if (event.req.method === 'POST') {\n try {\n parsedBody = await event.req.json();\n } catch {\n event.res.status = 400;\n event.res.headers.set('Content-Type', 'application/json');\n return jsonRpcError(-32700, 'Parse error: Invalid JSON');\n }\n\n const body = parsedBody as\n | { method?: string; params?: { uri?: string }; id?: string | number | null }\n | undefined;\n if (body?.method === 'resources/read' && !body.params?.uri) {\n event.res.status = 200;\n event.res.headers.set('Content-Type', 'application/json');\n return jsonRpcError(-32602, 'Invalid params: uri is required', body.id ?? null);\n }\n }\n\n const transport = await createHttpMcpTransport();\n await transport.handleRequest(nodeReq, nodeRes, parsedBody);\n\n return undefined;\n });\n\n app.get('/mcp', mcpHandler);\n app.post('/mcp', mcpHandler);\n app.delete('/mcp', mcpHandler);\n\n return app;\n}\n"],"x_google_ignoreList":[0,1,2,3],"mappings":";;;;;;;;;;;;;;AASA,IAAI,eAAe,cAAc,MAAM;CACrC,YAAY,SAAS,SAAS;EAC5B,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;AACA,IAAI,kBAAkB,MAAM;CAC1B,IAAI,aAAa,cACf,OAAO;CAET,OAAO,IAAI,aAAa,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC;AACjD;AACA,IAAI,gBAAgB,OAAO;AAC3B,IAA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