Skip to main content
Glama
index.mjs.map168 kB
{"version":3,"file":"index.mjs","names":["core._coercedNumber","schemas.ZodNumber","url","url","z\n .url","z.NEVER","url","z.looseObject","z.string","z.array","z.boolean","z.object","z\n .object","z.coerce.number","z.literal","z.any","z.number","url","tokens","url","url","_a","_b","url","_a","error","transport: SSEClientTransport | StreamableHTTPClientTransport","url"],"sources":["../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/compat.js","../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/coerce.js","../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js","../node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js","../node_modules/.pnpm/pkce-challenge@5.0.0/node_modules/pkce-challenge/dist/index.node.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js","../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.24.3_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js","../src/startStdioServer.ts","../src/tapTransport.ts"],"sourcesContent":["// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nfunction noop(_arg) {\n}\nfunction createParser(callbacks) {\n if (typeof callbacks == \"function\")\n throw new TypeError(\n \"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?\"\n );\n const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;\n let incompleteLine = \"\", isFirstChunk = !0, id, data = \"\", eventType = \"\";\n function feed(newChunk) {\n const chunk = isFirstChunk ? newChunk.replace(/^\\xEF\\xBB\\xBF/, \"\") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);\n for (const line of complete)\n parseLine(line);\n incompleteLine = incomplete, isFirstChunk = !1;\n }\n function parseLine(line) {\n if (line === \"\") {\n dispatchEvent();\n return;\n }\n if (line.startsWith(\":\")) {\n onComment && onComment(line.slice(line.startsWith(\": \") ? 2 : 1));\n return;\n }\n const fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex !== -1) {\n const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === \" \" ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n return;\n }\n processField(line, \"\", line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value;\n break;\n case \"data\":\n data = `${data}${value}\n`;\n break;\n case \"id\":\n id = value.includes(\"\\0\") ? void 0 : value;\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n data.length > 0 && onEvent({\n id,\n event: eventType || void 0,\n // If the data buffer's last character is a U+000A LINE FEED (LF) character,\n // then remove the last character from the data buffer.\n data: data.endsWith(`\n`) ? data.slice(0, -1) : data\n }), id = void 0, data = \"\", eventType = \"\";\n }\n function reset(options = {}) {\n incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = \"\", eventType = \"\", incompleteLine = \"\";\n }\n return { feed, reset };\n}\nfunction splitLines(chunk) {\n const lines = [];\n let incompleteLine = \"\", searchIndex = 0;\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {\n incompleteLine = chunk.slice(searchIndex);\n break;\n } else {\n const line = chunk.slice(searchIndex, lineEnd);\n lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === \"\\r\" && chunk[searchIndex] === `\n` && searchIndex++;\n }\n }\n return [lines, incompleteLine];\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"eventsource-parser\";\nclass ErrorEvent extends Event {\n /**\n * Constructs a new `ErrorEvent` instance. This is typically not called directly,\n * but rather emitted by the `EventSource` object when an error occurs.\n *\n * @param type - The type of the event (should be \"error\")\n * @param errorEventInitDict - Optional properties to include in the error event\n */\n constructor(type, errorEventInitDict) {\n var _a, _b;\n super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0;\n }\n /**\n * Node.js \"hides\" the `message` and `code` properties of the `ErrorEvent` instance,\n * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,\n * we explicitly include the properties in the `inspect` method.\n *\n * This is automatically called by Node.js when you `console.log` an instance of this class.\n *\n * @param _depth - The current depth\n * @param options - The options passed to `util.inspect`\n * @param inspect - The inspect function to use (prevents having to import it from `util`)\n * @returns A string representation of the error\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")](_depth, options, inspect) {\n return inspect(inspectableError(this), options);\n }\n /**\n * Deno \"hides\" the `message` and `code` properties of the `ErrorEvent` instance,\n * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,\n * we explicitly include the properties in the `inspect` method.\n *\n * This is automatically called by Deno when you `console.log` an instance of this class.\n *\n * @param inspect - The inspect function to use (prevents having to import it from `util`)\n * @param options - The options passed to `Deno.inspect`\n * @returns A string representation of the error\n */\n [Symbol.for(\"Deno.customInspect\")](inspect, options) {\n return inspect(inspectableError(this), options);\n }\n}\nfunction syntaxError(message) {\n const DomException = globalThis.DOMException;\n return typeof DomException == \"function\" ? new DomException(message, \"SyntaxError\") : new SyntaxError(message);\n}\nfunction flattenError(err) {\n return err instanceof Error ? \"errors\" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(\", \") : \"cause\" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;\n}\nfunction inspectableError(err) {\n return {\n type: err.type,\n message: err.message,\n code: err.code,\n defaultPrevented: err.defaultPrevented,\n cancelable: err.cancelable,\n timeStamp: err.timeStamp\n };\n}\nvar __typeError = (msg) => {\n throw TypeError(msg);\n}, __accessCheck = (obj, member, msg) => member.has(obj) || __typeError(\"Cannot \" + msg), __privateGet = (obj, member, getter) => (__accessCheck(obj, member, \"read from private field\"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => member.has(obj) ? __typeError(\"Cannot add the same private member more than once\") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, \"write to private field\"), member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck(obj, member, \"access private method\"), method), _readyState, _url, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect;\nclass EventSource extends EventTarget {\n constructor(url, eventSourceInitDict) {\n var _a, _b;\n super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {\n var _a2;\n __privateGet(this, _parser).reset();\n const { body, redirected, status, headers } = response;\n if (status === 204) {\n __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, \"Server sent HTTP 204, not reconnecting\", 204), this.close();\n return;\n }\n if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {\n __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);\n return;\n }\n if (!(headers.get(\"content-type\") || \"\").startsWith(\"text/event-stream\")) {\n __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected \"text/event-stream\"', status);\n return;\n }\n if (__privateGet(this, _readyState) === this.CLOSED)\n return;\n __privateSet(this, _readyState, this.OPEN);\n const openEvent = new Event(\"open\");\n if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != \"object\" || !body || !(\"getReader\" in body)) {\n __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, \"Invalid response body, expected a web ReadableStream\", status), this.close();\n return;\n }\n const decoder = new TextDecoder(), reader = body.getReader();\n let open = !0;\n do {\n const { done, value } = await reader.read();\n value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = !1, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));\n } while (open);\n }), __privateAdd(this, _onFetchError, (err) => {\n __privateSet(this, _controller, void 0), !(err.name === \"AbortError\" || err.type === \"aborted\") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));\n }), __privateAdd(this, _onEvent, (event) => {\n typeof event.id == \"string\" && __privateSet(this, _lastEventId, event.id);\n const messageEvent = new MessageEvent(event.event || \"message\", {\n data: event.data,\n origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,\n lastEventId: event.id || \"\"\n });\n __privateGet(this, _onMessage) && (!event.event || event.event === \"message\") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);\n }), __privateAdd(this, _onRetryChange, (value) => {\n __privateSet(this, _reconnectInterval, value);\n }), __privateAdd(this, _reconnect, () => {\n __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);\n });\n try {\n if (url instanceof URL)\n __privateSet(this, _url, url);\n else if (typeof url == \"string\")\n __privateSet(this, _url, new URL(url, getBaseURL()));\n else\n throw new Error(\"Invalid URL\");\n } catch {\n throw syntaxError(\"An invalid or illegal string was specified\");\n }\n __privateSet(this, _parser, createParser({\n onEvent: __privateGet(this, _onEvent),\n onRetry: __privateGet(this, _onRetryChange)\n })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : !1), __privateMethod(this, _EventSource_instances, connect_fn).call(this);\n }\n /**\n * Returns the state of this EventSource object's connection. It can have the values described below.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)\n *\n * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,\n * defined in the TypeScript `dom` library.\n *\n * @public\n */\n get readyState() {\n return __privateGet(this, _readyState);\n }\n /**\n * Returns the URL providing the event stream.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)\n *\n * @public\n */\n get url() {\n return __privateGet(this, _url).href;\n }\n /**\n * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to \"include\", and false otherwise.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)\n */\n get withCredentials() {\n return __privateGet(this, _withCredentials);\n }\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */\n get onerror() {\n return __privateGet(this, _onError);\n }\n set onerror(value) {\n __privateSet(this, _onError, value);\n }\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */\n get onmessage() {\n return __privateGet(this, _onMessage);\n }\n set onmessage(value) {\n __privateSet(this, _onMessage, value);\n }\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */\n get onopen() {\n return __privateGet(this, _onOpen);\n }\n set onopen(value) {\n __privateSet(this, _onOpen, value);\n }\n addEventListener(type, listener, options) {\n const listen = listener;\n super.addEventListener(type, listen, options);\n }\n removeEventListener(type, listener, options) {\n const listen = listener;\n super.removeEventListener(type, listen, options);\n }\n /**\n * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.\n *\n * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)\n *\n * @public\n */\n close() {\n __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));\n }\n}\n_readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**\n* Connect to the given URL and start receiving events\n*\n* @internal\n*/\nconnect_fn = function() {\n __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));\n}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**\n* Get request options for the `fetch()` request\n*\n* @returns The request options\n* @internal\n*/\ngetRequestOptions_fn = function() {\n var _a;\n const init = {\n // [spec] Let `corsAttributeState` be `Anonymous`…\n // [spec] …will have their mode set to \"cors\"…\n mode: \"cors\",\n redirect: \"follow\",\n headers: { Accept: \"text/event-stream\", ...__privateGet(this, _lastEventId) ? { \"Last-Event-ID\": __privateGet(this, _lastEventId) } : void 0 },\n cache: \"no-store\",\n signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal\n };\n return \"window\" in globalThis && (init.credentials = this.withCredentials ? \"include\" : \"same-origin\"), init;\n}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**\n* Handles the process referred to in the EventSource specification as \"failing a connection\".\n*\n* @param error - The error causing the connection to fail\n* @param code - The HTTP status code, if available\n* @internal\n*/\nfailConnection_fn = function(message, code) {\n var _a;\n __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);\n const errorEvent = new ErrorEvent(\"error\", { code, message });\n (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);\n}, /**\n* Schedules a reconnection attempt against the EventSource endpoint.\n*\n* @param message - The error causing the connection to fail\n* @param code - The HTTP status code, if available\n* @internal\n*/\nscheduleReconnect_fn = function(message, code) {\n var _a;\n if (__privateGet(this, _readyState) === this.CLOSED)\n return;\n __privateSet(this, _readyState, this.CONNECTING);\n const errorEvent = new ErrorEvent(\"error\", { code, message });\n (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));\n}, _reconnect = /* @__PURE__ */ new WeakMap(), /**\n* ReadyState representing an EventSource currently trying to connect\n*\n* @public\n*/\nEventSource.CONNECTING = 0, /**\n* ReadyState representing an EventSource connection that is open (eg connected)\n*\n* @public\n*/\nEventSource.OPEN = 1, /**\n* ReadyState representing an EventSource connection that is closed (eg disconnected)\n*\n* @public\n*/\nEventSource.CLOSED = 2;\nfunction getBaseURL() {\n const doc = \"document\" in globalThis ? globalThis.document : void 0;\n return doc && typeof doc == \"object\" && \"baseURI\" in doc && typeof doc.baseURI == \"string\" ? doc.baseURI : void 0;\n}\nexport {\n ErrorEvent,\n EventSource\n};\n//# sourceMappingURL=index.js.map\n","/**\n * Normalizes HeadersInit to a plain Record<string, string> for manipulation.\n * Handles Headers objects, arrays of tuples, and plain objects.\n */\nexport function normalizeHeaders(headers) {\n if (!headers)\n return {};\n if (headers instanceof Headers) {\n return Object.fromEntries(headers.entries());\n }\n if (Array.isArray(headers)) {\n return Object.fromEntries(headers);\n }\n return { ...headers };\n}\n/**\n * Creates a fetch function that includes base RequestInit options.\n * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.\n *\n * @param baseFetch - The base fetch function to wrap (defaults to global fetch)\n * @param baseInit - The base RequestInit to merge with each request\n * @returns A wrapped fetch function that merges base options with call-specific options\n */\nexport function createFetchWithInit(baseFetch = fetch, baseInit) {\n if (!baseInit) {\n return baseFetch;\n }\n // Return a wrapped fetch that merges base RequestInit with call-specific init\n return async (url, init) => {\n const mergedInit = {\n ...baseInit,\n ...init,\n // Headers need special handling - merge instead of replace\n headers: (init === null || init === void 0 ? void 0 : init.headers) ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers\n };\n return baseFetch(url, mergedInit);\n };\n}\n//# sourceMappingURL=transport.js.map","let crypto;\ncrypto =\n globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL\n globalThis.crypto ?? // Node.js >18\n import(\"node:crypto\").then(m => m.webcrypto); // Node.js <18 Non-REPL\n/**\n * Creates an array of length `size` of random bytes\n * @param size\n * @returns Array of random ints (0 to 255)\n */\nasync function getRandomValues(size) {\n return (await crypto).getRandomValues(new Uint8Array(size));\n}\n/** Generate cryptographically strong random string\n * @param size The desired length of the string\n * @returns The random string\n */\nasync function random(size) {\n const mask = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\";\n let result = \"\";\n const randomUints = await getRandomValues(size);\n for (let i = 0; i < size; i++) {\n // cap the value of the randomIndex to mask.length - 1\n const randomIndex = randomUints[i] % mask.length;\n result += mask[randomIndex];\n }\n return result;\n}\n/** Generate a PKCE challenge verifier\n * @param length Length of the verifier\n * @returns A random verifier `length` characters long\n */\nasync function generateVerifier(length) {\n return await random(length);\n}\n/** Generate a PKCE code challenge from a code verifier\n * @param code_verifier\n * @returns The base64 url encoded code challenge\n */\nexport async function generateChallenge(code_verifier) {\n const buffer = await (await crypto).subtle.digest(\"SHA-256\", new TextEncoder().encode(code_verifier));\n // Generate base64url string\n // btoa is deprecated in Node.js but is used here for web browser compatibility\n // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811)\n return btoa(String.fromCharCode(...new Uint8Array(buffer)))\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n .replace(/=/g, '');\n}\n/** Generate a PKCE challenge pair\n * @param length Length of the verifer (between 43-128). Defaults to 43.\n * @returns PKCE challenge pair\n */\nexport default async function pkceChallenge(length) {\n if (!length)\n length = 43;\n if (length < 43 || length > 128) {\n throw `Expected a length between 43 and 128. Received ${length}.`;\n }\n const verifier = await generateVerifier(length);\n const challenge = await generateChallenge(verifier);\n return {\n code_verifier: verifier,\n code_challenge: challenge,\n };\n}\n/** Verify that a code_verifier produces the expected code challenge\n * @param code_verifier\n * @param expectedChallenge The code challenge to verify\n * @returns True if challenges are equal. False otherwise.\n */\nexport async function verifyChallenge(code_verifier, expectedChallenge) {\n const actualChallenge = await generateChallenge(code_verifier);\n return actualChallenge === expectedChallenge;\n}\n","import * as z from 'zod/v4';\n/**\n * Reusable URL validation that disallows javascript: scheme\n */\nexport const SafeUrlSchema = z\n .url()\n .superRefine((val, ctx) => {\n if (!URL.canParse(val)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'URL must be parseable',\n fatal: true\n });\n return z.NEVER;\n }\n})\n .refine(url => {\n const u = new URL(url);\n return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:';\n}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' });\n/**\n * RFC 9728 OAuth Protected Resource Metadata\n */\nexport const OAuthProtectedResourceMetadataSchema = z.looseObject({\n resource: z.string().url(),\n authorization_servers: z.array(SafeUrlSchema).optional(),\n jwks_uri: z.string().url().optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n resource_signing_alg_values_supported: z.array(z.string()).optional(),\n resource_name: z.string().optional(),\n resource_documentation: z.string().optional(),\n resource_policy_uri: z.string().url().optional(),\n resource_tos_uri: z.string().url().optional(),\n tls_client_certificate_bound_access_tokens: z.boolean().optional(),\n authorization_details_types_supported: z.array(z.string()).optional(),\n dpop_signing_alg_values_supported: z.array(z.string()).optional(),\n dpop_bound_access_tokens_required: z.boolean().optional()\n});\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n service_documentation: SafeUrlSchema.optional(),\n revocation_endpoint: SafeUrlSchema.optional(),\n revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n introspection_endpoint: z.string().optional(),\n introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n code_challenge_methods_supported: z.array(z.string()).optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery 1.0 Provider Metadata\n * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n */\nexport const OpenIdProviderMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n userinfo_endpoint: SafeUrlSchema.optional(),\n jwks_uri: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n acr_values_supported: z.array(z.string()).optional(),\n subject_types_supported: z.array(z.string()),\n id_token_signing_alg_values_supported: z.array(z.string()),\n id_token_encryption_alg_values_supported: z.array(z.string()).optional(),\n id_token_encryption_enc_values_supported: z.array(z.string()).optional(),\n userinfo_signing_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),\n request_object_signing_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_enc_values_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n display_values_supported: z.array(z.string()).optional(),\n claim_types_supported: z.array(z.string()).optional(),\n claims_supported: z.array(z.string()).optional(),\n service_documentation: z.string().optional(),\n claims_locales_supported: z.array(z.string()).optional(),\n ui_locales_supported: z.array(z.string()).optional(),\n claims_parameter_supported: z.boolean().optional(),\n request_parameter_supported: z.boolean().optional(),\n request_uri_parameter_supported: z.boolean().optional(),\n require_request_uri_registration: z.boolean().optional(),\n op_policy_uri: SafeUrlSchema.optional(),\n op_tos_uri: SafeUrlSchema.optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery metadata that may include OAuth 2.0 fields\n * This schema represents the real-world scenario where OIDC providers\n * return a mix of OpenID Connect and OAuth 2.0 metadata fields\n */\nexport const OpenIdProviderDiscoveryMetadataSchema = z.object({\n ...OpenIdProviderMetadataSchema.shape,\n ...OAuthMetadataSchema.pick({\n code_challenge_methods_supported: true\n }).shape\n});\n/**\n * OAuth 2.1 token response\n */\nexport const OAuthTokensSchema = z\n .object({\n access_token: z.string(),\n id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect\n token_type: z.string(),\n expires_in: z.coerce.number().optional(),\n scope: z.string().optional(),\n refresh_token: z.string().optional()\n})\n .strip();\n/**\n * OAuth 2.1 error response\n */\nexport const OAuthErrorResponseSchema = z.object({\n error: z.string(),\n error_description: z.string().optional(),\n error_uri: z.string().optional()\n});\n/**\n * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri\n */\nexport const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined));\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z\n .object({\n redirect_uris: z.array(SafeUrlSchema),\n token_endpoint_auth_method: z.string().optional(),\n grant_types: z.array(z.string()).optional(),\n response_types: z.array(z.string()).optional(),\n client_name: z.string().optional(),\n client_uri: SafeUrlSchema.optional(),\n logo_uri: OptionalSafeUrlSchema,\n scope: z.string().optional(),\n contacts: z.array(z.string()).optional(),\n tos_uri: OptionalSafeUrlSchema,\n policy_uri: z.string().optional(),\n jwks_uri: SafeUrlSchema.optional(),\n jwks: z.any().optional(),\n software_id: z.string().optional(),\n software_version: z.string().optional(),\n software_statement: z.string().optional()\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z\n .object({\n client_id: z.string(),\n client_secret: z.string().optional(),\n client_id_issued_at: z.number().optional(),\n client_secret_expires_at: z.number().optional()\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)\n */\nexport const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration error response\n */\nexport const OAuthClientRegistrationErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional()\n})\n .strip();\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z\n .object({\n token: z.string(),\n token_type_hint: z.string().optional()\n})\n .strip();\n//# sourceMappingURL=auth.js.map","/**\n * Utilities for handling OAuth resource URIs.\n */\n/**\n * Converts a server URL to a resource URL by removing the fragment.\n * RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n * Keeps everything else unchanged (scheme, domain, port, path, query).\n */\nexport function resourceUrlFromServerUrl(url) {\n const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href);\n resourceURL.hash = ''; // Remove fragment\n return resourceURL;\n}\n/**\n * Checks if a requested resource URL matches a configured resource URL.\n * A requested resource matches if it has the same scheme, domain, port,\n * and its path starts with the configured resource's path.\n *\n * @param requestedResource The resource URL being requested\n * @param configuredResource The resource URL that has been configured\n * @returns true if the requested resource matches the configured resource, false otherwise\n */\nexport function checkResourceAllowed({ requestedResource, configuredResource }) {\n const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href);\n const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href);\n // Compare the origin (scheme, domain, and port)\n if (requested.origin !== configured.origin) {\n return false;\n }\n // Handle cases like requested=/foo and configured=/foo/\n if (requested.pathname.length < configured.pathname.length) {\n return false;\n }\n // Check if the requested path starts with the configured path\n // Ensure both paths end with / for proper comparison\n // This ensures that if we have paths like \"/api\" and \"/api/users\",\n // we properly detect that \"/api/users\" is a subpath of \"/api\"\n // By adding a trailing slash if missing, we avoid false positives\n // where paths like \"/api123\" would incorrectly match \"/api\"\n const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/';\n const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/';\n return requestedPath.startsWith(configuredPath);\n}\n//# sourceMappingURL=auth-utils.js.map","/**\n * Base class for all OAuth errors\n */\nexport class OAuthError extends Error {\n constructor(message, errorUri) {\n super(message);\n this.errorUri = errorUri;\n this.name = this.constructor.name;\n }\n /**\n * Converts the error to a standard OAuth error response object\n */\n toResponseObject() {\n const response = {\n error: this.errorCode,\n error_description: this.message\n };\n if (this.errorUri) {\n response.error_uri = this.errorUri;\n }\n return response;\n }\n get errorCode() {\n return this.constructor.errorCode;\n }\n}\n/**\n * Invalid request error - The request is missing a required parameter,\n * includes an invalid parameter value, includes a parameter more than once,\n * or is otherwise malformed.\n */\nexport class InvalidRequestError extends OAuthError {\n}\nInvalidRequestError.errorCode = 'invalid_request';\n/**\n * Invalid client error - Client authentication failed (e.g., unknown client, no client\n * authentication included, or unsupported authentication method).\n */\nexport class InvalidClientError extends OAuthError {\n}\nInvalidClientError.errorCode = 'invalid_client';\n/**\n * Invalid grant error - The provided authorization grant or refresh token is\n * invalid, expired, revoked, does not match the redirection URI used in the\n * authorization request, or was issued to another client.\n */\nexport class InvalidGrantError extends OAuthError {\n}\nInvalidGrantError.errorCode = 'invalid_grant';\n/**\n * Unauthorized client error - The authenticated client is not authorized to use\n * this authorization grant type.\n */\nexport class UnauthorizedClientError extends OAuthError {\n}\nUnauthorizedClientError.errorCode = 'unauthorized_client';\n/**\n * Unsupported grant type error - The authorization grant type is not supported\n * by the authorization server.\n */\nexport class UnsupportedGrantTypeError extends OAuthError {\n}\nUnsupportedGrantTypeError.errorCode = 'unsupported_grant_type';\n/**\n * Invalid scope error - The requested scope is invalid, unknown, malformed, or\n * exceeds the scope granted by the resource owner.\n */\nexport class InvalidScopeError extends OAuthError {\n}\nInvalidScopeError.errorCode = 'invalid_scope';\n/**\n * Access denied error - The resource owner or authorization server denied the request.\n */\nexport class AccessDeniedError extends OAuthError {\n}\nAccessDeniedError.errorCode = 'access_denied';\n/**\n * Server error - The authorization server encountered an unexpected condition\n * that prevented it from fulfilling the request.\n */\nexport class ServerError extends OAuthError {\n}\nServerError.errorCode = 'server_error';\n/**\n * Temporarily unavailable error - The authorization server is currently unable to\n * handle the request due to a temporary overloading or maintenance of the server.\n */\nexport class TemporarilyUnavailableError extends OAuthError {\n}\nTemporarilyUnavailableError.errorCode = 'temporarily_unavailable';\n/**\n * Unsupported response type error - The authorization server does not support\n * obtaining an authorization code using this method.\n */\nexport class UnsupportedResponseTypeError extends OAuthError {\n}\nUnsupportedResponseTypeError.errorCode = 'unsupported_response_type';\n/**\n * Unsupported token type error - The authorization server does not support\n * the requested token type.\n */\nexport class UnsupportedTokenTypeError extends OAuthError {\n}\nUnsupportedTokenTypeError.errorCode = 'unsupported_token_type';\n/**\n * Invalid token error - The access token provided is expired, revoked, malformed,\n * or invalid for other reasons.\n */\nexport class InvalidTokenError extends OAuthError {\n}\nInvalidTokenError.errorCode = 'invalid_token';\n/**\n * Method not allowed error - The HTTP method used is not allowed for this endpoint.\n * (Custom, non-standard error)\n */\nexport class MethodNotAllowedError extends OAuthError {\n}\nMethodNotAllowedError.errorCode = 'method_not_allowed';\n/**\n * Too many requests error - Rate limit exceeded.\n * (Custom, non-standard error based on RFC 6585)\n */\nexport class TooManyRequestsError extends OAuthError {\n}\nTooManyRequestsError.errorCode = 'too_many_requests';\n/**\n * Invalid client metadata error - The client metadata is invalid.\n * (Custom error for dynamic client registration - RFC 7591)\n */\nexport class InvalidClientMetadataError extends OAuthError {\n}\nInvalidClientMetadataError.errorCode = 'invalid_client_metadata';\n/**\n * Insufficient scope error - The request requires higher privileges than provided by the access token.\n */\nexport class InsufficientScopeError extends OAuthError {\n}\nInsufficientScopeError.errorCode = 'insufficient_scope';\n/**\n * Invalid target error - The requested resource is invalid, missing, unknown, or malformed.\n * (Custom error for resource indicators - RFC 8707)\n */\nexport class InvalidTargetError extends OAuthError {\n}\nInvalidTargetError.errorCode = 'invalid_target';\n/**\n * A utility class for defining one-off error codes\n */\nexport class CustomOAuthError extends OAuthError {\n constructor(customErrorCode, message, errorUri) {\n super(message, errorUri);\n this.customErrorCode = customErrorCode;\n }\n get errorCode() {\n return this.customErrorCode;\n }\n}\n/**\n * A full list of all OAuthErrors, enabling parsing from error responses\n */\nexport const OAUTH_ERRORS = {\n [InvalidRequestError.errorCode]: InvalidRequestError,\n [InvalidClientError.errorCode]: InvalidClientError,\n [InvalidGrantError.errorCode]: InvalidGrantError,\n [UnauthorizedClientError.errorCode]: UnauthorizedClientError,\n [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,\n [InvalidScopeError.errorCode]: InvalidScopeError,\n [AccessDeniedError.errorCode]: AccessDeniedError,\n [ServerError.errorCode]: ServerError,\n [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,\n [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,\n [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,\n [InvalidTokenError.errorCode]: InvalidTokenError,\n [MethodNotAllowedError.errorCode]: MethodNotAllowedError,\n [TooManyRequestsError.errorCode]: TooManyRequestsError,\n [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,\n [InsufficientScopeError.errorCode]: InsufficientScopeError,\n [InvalidTargetError.errorCode]: InvalidTargetError\n};\n//# sourceMappingURL=errors.js.map","import pkceChallenge from 'pkce-challenge';\nimport { LATEST_PROTOCOL_VERSION } from '../types.js';\nimport { OAuthErrorResponseSchema, OpenIdProviderDiscoveryMetadataSchema } from '../shared/auth.js';\nimport { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from '../shared/auth.js';\nimport { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js';\nimport { InvalidClientError, InvalidClientMetadataError, InvalidGrantError, OAUTH_ERRORS, OAuthError, ServerError, UnauthorizedClientError } from '../server/auth/errors.js';\nexport class UnauthorizedError extends Error {\n constructor(message) {\n super(message !== null && message !== void 0 ? message : 'Unauthorized');\n }\n}\nfunction isClientAuthMethod(method) {\n return ['client_secret_basic', 'client_secret_post', 'none'].includes(method);\n}\nconst AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';\nconst AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';\n/**\n * Determines the best client authentication method to use based on server support and client configuration.\n *\n * Priority order (highest to lowest):\n * 1. client_secret_basic (if client secret is available)\n * 2. client_secret_post (if client secret is available)\n * 3. none (for public clients)\n *\n * @param clientInformation - OAuth client information containing credentials\n * @param supportedMethods - Authentication methods supported by the authorization server\n * @returns The selected authentication method\n */\nexport function selectClientAuthMethod(clientInformation, supportedMethods) {\n const hasClientSecret = clientInformation.client_secret !== undefined;\n // If server doesn't specify supported methods, use RFC 6749 defaults\n if (supportedMethods.length === 0) {\n return hasClientSecret ? 'client_secret_post' : 'none';\n }\n // Prefer the method returned by the server during client registration if valid and supported\n if ('token_endpoint_auth_method' in clientInformation &&\n clientInformation.token_endpoint_auth_method &&\n isClientAuthMethod(clientInformation.token_endpoint_auth_method) &&\n supportedMethods.includes(clientInformation.token_endpoint_auth_method)) {\n return clientInformation.token_endpoint_auth_method;\n }\n // Try methods in priority order (most secure first)\n if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {\n return 'client_secret_basic';\n }\n if (hasClientSecret && supportedMethods.includes('client_secret_post')) {\n return 'client_secret_post';\n }\n if (supportedMethods.includes('none')) {\n return 'none';\n }\n // Fallback: use what we have\n return hasClientSecret ? 'client_secret_post' : 'none';\n}\n/**\n * Applies client authentication to the request based on the specified method.\n *\n * Implements OAuth 2.1 client authentication methods:\n * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)\n * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)\n * - none: Public client authentication (RFC 6749 Section 2.1)\n *\n * @param method - The authentication method to use\n * @param clientInformation - OAuth client information containing credentials\n * @param headers - HTTP headers object to modify\n * @param params - URL search parameters to modify\n * @throws {Error} When required credentials are missing\n */\nfunction applyClientAuthentication(method, clientInformation, headers, params) {\n const { client_id, client_secret } = clientInformation;\n switch (method) {\n case 'client_secret_basic':\n applyBasicAuth(client_id, client_secret, headers);\n return;\n case 'client_secret_post':\n applyPostAuth(client_id, client_secret, params);\n return;\n case 'none':\n applyPublicAuth(client_id, params);\n return;\n default:\n throw new Error(`Unsupported client authentication method: ${method}`);\n }\n}\n/**\n * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)\n */\nfunction applyBasicAuth(clientId, clientSecret, headers) {\n if (!clientSecret) {\n throw new Error('client_secret_basic authentication requires a client_secret');\n }\n const credentials = btoa(`${clientId}:${clientSecret}`);\n headers.set('Authorization', `Basic ${credentials}`);\n}\n/**\n * Applies POST body authentication (RFC 6749 Section 2.3.1)\n */\nfunction applyPostAuth(clientId, clientSecret, params) {\n params.set('client_id', clientId);\n if (clientSecret) {\n params.set('client_secret', clientSecret);\n }\n}\n/**\n * Applies public client authentication (RFC 6749 Section 2.1)\n */\nfunction applyPublicAuth(clientId, params) {\n params.set('client_id', clientId);\n}\n/**\n * Parses an OAuth error response from a string or Response object.\n *\n * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec\n * and an instance of the appropriate OAuthError subclass will be returned.\n * If parsing fails, it falls back to a generic ServerError that includes\n * the response status (if available) and original content.\n *\n * @param input - A Response object or string containing the error response\n * @returns A Promise that resolves to an OAuthError instance\n */\nexport async function parseErrorResponse(input) {\n const statusCode = input instanceof Response ? input.status : undefined;\n const body = input instanceof Response ? await input.text() : input;\n try {\n const result = OAuthErrorResponseSchema.parse(JSON.parse(body));\n const { error, error_description, error_uri } = result;\n const errorClass = OAUTH_ERRORS[error] || ServerError;\n return new errorClass(error_description || '', error_uri);\n }\n catch (error) {\n // Not a valid OAuth error response, but try to inform the user of the raw data anyway\n const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`;\n return new ServerError(errorMessage);\n }\n}\n/**\n * Orchestrates the full auth flow with a server.\n *\n * This can be used as a single entry point for all authorization functionality,\n * instead of linking together the other lower-level functions in this module.\n */\nexport async function auth(provider, options) {\n var _a, _b;\n try {\n return await authInternal(provider, options);\n }\n catch (error) {\n // Handle recoverable error types by invalidating credentials and retrying\n if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {\n await ((_a = provider.invalidateCredentials) === null || _a === void 0 ? void 0 : _a.call(provider, 'all'));\n return await authInternal(provider, options);\n }\n else if (error instanceof InvalidGrantError) {\n await ((_b = provider.invalidateCredentials) === null || _b === void 0 ? void 0 : _b.call(provider, 'tokens'));\n return await authInternal(provider, options);\n }\n // Throw otherwise\n throw error;\n }\n}\nasync function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {\n var _a, _b;\n let resourceMetadata;\n let authorizationServerUrl;\n try {\n resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn);\n if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {\n authorizationServerUrl = resourceMetadata.authorization_servers[0];\n }\n }\n catch (_c) {\n // Ignore errors and fall back to /.well-known/oauth-authorization-server\n }\n /**\n * If we don't get a valid authorization server metadata from protected resource metadata,\n * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server base URL acts as the Authorization server.\n */\n if (!authorizationServerUrl) {\n authorizationServerUrl = new URL('/', serverUrl);\n }\n const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);\n const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, {\n fetchFn\n });\n // Handle client registration if needed\n let clientInformation = await Promise.resolve(provider.clientInformation());\n if (!clientInformation) {\n if (authorizationCode !== undefined) {\n throw new Error('Existing OAuth client information is required when exchanging an authorization code');\n }\n const supportsUrlBasedClientId = (metadata === null || metadata === void 0 ? void 0 : metadata.client_id_metadata_document_supported) === true;\n const clientMetadataUrl = provider.clientMetadataUrl;\n if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {\n throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);\n }\n const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;\n if (shouldUseUrlBasedClientId) {\n // SEP-991: URL-based Client IDs\n clientInformation = {\n client_id: clientMetadataUrl\n };\n await ((_a = provider.saveClientInformation) === null || _a === void 0 ? void 0 : _a.call(provider, clientInformation));\n }\n else {\n // Fallback to dynamic registration\n if (!provider.saveClientInformation) {\n throw new Error('OAuth client information must be saveable for dynamic registration');\n }\n const fullInformation = await registerClient(authorizationServerUrl, {\n metadata,\n clientMetadata: provider.clientMetadata,\n fetchFn\n });\n await provider.saveClientInformation(fullInformation);\n clientInformation = fullInformation;\n }\n }\n // Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL\n const nonInteractiveFlow = !provider.redirectUrl;\n // Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows\n if (authorizationCode !== undefined || nonInteractiveFlow) {\n const tokens = await fetchToken(provider, authorizationServerUrl, {\n metadata,\n resource,\n authorizationCode,\n fetchFn\n });\n await provider.saveTokens(tokens);\n return 'AUTHORIZED';\n }\n const tokens = await provider.tokens();\n // Handle token refresh or new authorization\n if (tokens === null || tokens === void 0 ? void 0 : tokens.refresh_token) {\n try {\n // Attempt to refresh the token\n const newTokens = await refreshAuthorization(authorizationServerUrl, {\n metadata,\n clientInformation,\n refreshToken: tokens.refresh_token,\n resource,\n addClientAuthentication: provider.addClientAuthentication,\n fetchFn\n });\n await provider.saveTokens(newTokens);\n return 'AUTHORIZED';\n }\n catch (error) {\n // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.\n if (!(error instanceof OAuthError) || error instanceof ServerError) {\n // Could not refresh OAuth tokens\n }\n else {\n // Refresh failed for another reason, re-throw\n throw error;\n }\n }\n }\n const state = provider.state ? await provider.state() : undefined;\n // Start new authorization flow\n const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {\n metadata,\n clientInformation,\n state,\n redirectUrl: provider.redirectUrl,\n scope: scope || ((_b = resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.scopes_supported) === null || _b === void 0 ? void 0 : _b.join(' ')) || provider.clientMetadata.scope,\n resource\n });\n await provider.saveCodeVerifier(codeVerifier);\n await provider.redirectToAuthorization(authorizationUrl);\n return 'REDIRECT';\n}\n/**\n * SEP-991: URL-based Client IDs\n * Validate that the client_id is a valid URL with https scheme\n */\nexport function isHttpsUrl(value) {\n if (!value)\n return false;\n try {\n const url = new URL(value);\n return url.protocol === 'https:' && url.pathname !== '/';\n }\n catch (_a) {\n return false;\n }\n}\nexport async function selectResourceURL(serverUrl, provider, resourceMetadata) {\n const defaultResource = resourceUrlFromServerUrl(serverUrl);\n // If provider has custom validation, delegate to it\n if (provider.validateResourceURL) {\n return await provider.validateResourceURL(defaultResource, resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.resource);\n }\n // Only include resource parameter when Protected Resource Metadata is present\n if (!resourceMetadata) {\n return undefined;\n }\n // Validate that the metadata's resource is compatible with our request\n if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {\n throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);\n }\n // Prefer the resource from metadata since it's what the server is telling us to request\n return new URL(resourceMetadata.resource);\n}\n/**\n * Extract resource_metadata, scope, and error from WWW-Authenticate header.\n */\nexport function extractWWWAuthenticateParams(res) {\n const authenticateHeader = res.headers.get('WWW-Authenticate');\n if (!authenticateHeader) {\n return {};\n }\n const [type, scheme] = authenticateHeader.split(' ');\n if (type.toLowerCase() !== 'bearer' || !scheme) {\n return {};\n }\n const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined;\n let resourceMetadataUrl;\n if (resourceMetadataMatch) {\n try {\n resourceMetadataUrl = new URL(resourceMetadataMatch);\n }\n catch (_a) {\n // Ignore invalid URL\n }\n }\n const scope = extractFieldFromWwwAuth(res, 'scope') || undefined;\n const error = extractFieldFromWwwAuth(res, 'error') || undefined;\n return {\n resourceMetadataUrl,\n scope,\n error\n };\n}\n/**\n * Extracts a specific field's value from the WWW-Authenticate header string.\n *\n * @param response The HTTP response object containing the headers.\n * @param fieldName The name of the field to extract (e.g., \"realm\", \"nonce\").\n * @returns The field value\n */\nfunction extractFieldFromWwwAuth(response, fieldName) {\n const wwwAuthHeader = response.headers.get('WWW-Authenticate');\n if (!wwwAuthHeader) {\n return null;\n }\n const pattern = new RegExp(`${fieldName}=(?:\"([^\"]+)\"|([^\\\\s,]+))`);\n const match = wwwAuthHeader.match(pattern);\n if (match) {\n // Pattern matches: field_name=\"value\" or field_name=value (unquoted)\n return match[1] || match[2];\n }\n return null;\n}\n/**\n * Extract resource_metadata from response header.\n * @deprecated Use `extractWWWAuthenticateParams` instead.\n */\nexport function extractResourceMetadataUrl(res) {\n const authenticateHeader = res.headers.get('WWW-Authenticate');\n if (!authenticateHeader) {\n return undefined;\n }\n const [type, scheme] = authenticateHeader.split(' ');\n if (type.toLowerCase() !== 'bearer' || !scheme) {\n return undefined;\n }\n const regex = /resource_metadata=\"([^\"]*)\"/;\n const match = regex.exec(authenticateHeader);\n if (!match) {\n return undefined;\n }\n try {\n return new URL(match[1]);\n }\n catch (_a) {\n return undefined;\n }\n}\n/**\n * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n */\nexport async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {\n var _a, _b;\n const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, {\n protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion,\n metadataUrl: opts === null || opts === void 0 ? void 0 : opts.resourceMetadataUrl\n });\n if (!response || response.status === 404) {\n await ((_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.cancel());\n throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);\n }\n if (!response.ok) {\n await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel());\n throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);\n }\n return OAuthProtectedResourceMetadataSchema.parse(await response.json());\n}\n/**\n * Helper function to handle fetch with CORS retry logic\n */\nasync function fetchWithCorsRetry(url, headers, fetchFn = fetch) {\n try {\n return await fetchFn(url, { headers });\n }\n catch (error) {\n if (error instanceof TypeError) {\n if (headers) {\n // CORS errors come back as TypeError, retry without headers\n return fetchWithCorsRetry(url, undefined, fetchFn);\n }\n else {\n // We're getting CORS errors on retry too, return undefined\n return undefined;\n }\n }\n throw error;\n }\n}\n/**\n * Constructs the well-known path for auth-related metadata discovery\n */\nfunction buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) {\n // Strip trailing slash from pathname to avoid double slashes\n if (pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1);\n }\n return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;\n}\n/**\n * Tries to discover OAuth metadata at a specific URL\n */\nasync function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {\n const headers = {\n 'MCP-Protocol-Version': protocolVersion\n };\n return await fetchWithCorsRetry(url, headers, fetchFn);\n}\n/**\n * Determines if fallback to root discovery should be attempted\n */\nfunction shouldAttemptFallback(response, pathname) {\n return !response || (response.status >= 400 && response.status < 500 && pathname !== '/');\n}\n/**\n * Generic function for discovering OAuth metadata with fallback support\n */\nasync function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {\n var _a, _b;\n const issuer = new URL(serverUrl);\n const protocolVersion = (_a = opts === null || opts === void 0 ? void 0 : opts.protocolVersion) !== null && _a !== void 0 ? _a : LATEST_PROTOCOL_VERSION;\n let url;\n if (opts === null || opts === void 0 ? void 0 : opts.metadataUrl) {\n url = new URL(opts.metadataUrl);\n }\n else {\n // Try path-aware discovery first\n const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);\n url = new URL(wellKnownPath, (_b = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b !== void 0 ? _b : issuer);\n url.search = issuer.search;\n }\n let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);\n // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery\n if (!(opts === null || opts === void 0 ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {\n const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);\n response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);\n }\n return response;\n}\n/**\n * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n *\n * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`.\n */\nexport async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) {\n var _a, _b;\n if (typeof issuer === 'string') {\n issuer = new URL(issuer);\n }\n if (!authorizationServerUrl) {\n authorizationServerUrl = issuer;\n }\n if (typeof authorizationServerUrl === 'string') {\n authorizationServerUrl = new URL(authorizationServerUrl);\n }\n protocolVersion !== null && protocolVersion !== void 0 ? protocolVersion : (protocolVersion = LATEST_PROTOCOL_VERSION);\n const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, {\n protocolVersion,\n metadataServerUrl: authorizationServerUrl\n });\n if (!response || response.status === 404) {\n await ((_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.cancel());\n return undefined;\n }\n if (!response.ok) {\n await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel());\n throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);\n }\n return OAuthMetadataSchema.parse(await response.json());\n}\n/**\n * Builds a list of discovery URLs to try for authorization server metadata.\n * URLs are returned in priority order:\n * 1. OAuth metadata at the given URL\n * 2. OIDC metadata endpoints at the given URL\n */\nexport function buildDiscoveryUrls(authorizationServerUrl) {\n const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl;\n const hasPath = url.pathname !== '/';\n const urlsToTry = [];\n if (!hasPath) {\n // Root path: https://example.com/.well-known/oauth-authorization-server\n urlsToTry.push({\n url: new URL('/.well-known/oauth-authorization-server', url.origin),\n type: 'oauth'\n });\n // OIDC: https://example.com/.well-known/openid-configuration\n urlsToTry.push({\n url: new URL(`/.well-known/openid-configuration`, url.origin),\n type: 'oidc'\n });\n return urlsToTry;\n }\n // Strip trailing slash from pathname to avoid double slashes\n let pathname = url.pathname;\n if (pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1);\n }\n // 1. OAuth metadata at the given URL\n // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1\n urlsToTry.push({\n url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),\n type: 'oauth'\n });\n // 2. OIDC metadata endpoints\n // RFC 8414 style: Insert /.well-known/openid-configuration before the path\n urlsToTry.push({\n url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),\n type: 'oidc'\n });\n // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path\n urlsToTry.push({\n url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),\n type: 'oidc'\n });\n return urlsToTry;\n}\n/**\n * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata\n * and OpenID Connect Discovery 1.0 specifications.\n *\n * This function implements a fallback strategy for authorization server discovery:\n * 1. Attempts RFC 8414 OAuth metadata discovery first\n * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery\n *\n * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's\n * protected resource metadata, or the MCP server's URL if the\n * metadata was not found.\n * @param options - Configuration options\n * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch\n * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION\n * @returns Promise resolving to authorization server metadata, or undefined if discovery fails\n */\nexport async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {\n var _a;\n const headers = {\n 'MCP-Protocol-Version': protocolVersion,\n Accept: 'application/json'\n };\n // Get the list of URLs to try\n const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);\n // Try each URL in order\n for (const { url: endpointUrl, type } of urlsToTry) {\n const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);\n if (!response) {\n /**\n * CORS error occurred - don't throw as the endpoint may not allow CORS,\n * continue trying other possible endpoints\n */\n continue;\n }\n if (!response.ok) {\n await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel());\n // Continue looking for any 4xx response code.\n if (response.status >= 400 && response.status < 500) {\n continue; // Try next URL\n }\n throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`);\n }\n // Parse and validate based on type\n if (type === 'oauth') {\n return OAuthMetadataSchema.parse(await response.json());\n }\n else {\n return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());\n }\n }\n return undefined;\n}\n/**\n * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.\n */\nexport async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {\n let authorizationUrl;\n if (metadata) {\n authorizationUrl = new URL(metadata.authorization_endpoint);\n if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {\n throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);\n }\n if (metadata.code_challenge_methods_supported &&\n !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {\n throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);\n }\n }\n else {\n authorizationUrl = new URL('/authorize', authorizationServerUrl);\n }\n // Generate PKCE challenge\n const challenge = await pkceChallenge();\n const codeVerifier = challenge.code_verifier;\n const codeChallenge = challenge.code_challenge;\n authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE);\n authorizationUrl.searchParams.set('client_id', clientInformation.client_id);\n authorizationUrl.searchParams.set('code_challenge', codeChallenge);\n authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD);\n authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl));\n if (state) {\n authorizationUrl.searchParams.set('state', state);\n }\n if (scope) {\n authorizationUrl.searchParams.set('scope', scope);\n }\n if (scope === null || scope === void 0 ? void 0 : scope.includes('offline_access')) {\n // if the request includes the OIDC-only \"offline_access\" scope,\n // we need to set the prompt to \"consent\" to ensure the user is prompted to grant offline access\n // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess\n authorizationUrl.searchParams.append('prompt', 'consent');\n }\n if (resource) {\n authorizationUrl.searchParams.set('resource', resource.href);\n }\n return { authorizationUrl, codeVerifier };\n}\n/**\n * Prepares token request parameters for an authorization code exchange.\n *\n * This is the default implementation used by fetchToken when the provider\n * doesn't implement prepareTokenRequest.\n *\n * @param authorizationCode - The authorization code received from the authorization endpoint\n * @param codeVerifier - The PKCE code verifier\n * @param redirectUri - The redirect URI used in the authorization request\n * @returns URLSearchParams for the authorization_code grant\n */\nexport function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {\n return new URLSearchParams({\n grant_type: 'authorization_code',\n code: authorizationCode,\n code_verifier: codeVerifier,\n redirect_uri: String(redirectUri)\n });\n}\n/**\n * Internal helper to execute a token request with the given parameters.\n * Used by exchangeAuthorization, refreshAuthorization, and fetchToken.\n */\nasync function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {\n var _a;\n const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl);\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json'\n });\n if (resource) {\n tokenRequestParams.set('resource', resource.href);\n }\n if (addClientAuthentication) {\n await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);\n }\n else if (clientInformation) {\n const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : [];\n const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);\n applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);\n }\n const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {\n method: 'POST',\n headers,\n body: tokenRequestParams\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return OAuthTokensSchema.parse(await response.json());\n}\n/**\n * Exchanges an authorization code for an access token with the given server.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Falls back to appropriate defaults when server metadata is unavailable\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, auth code, etc.\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When token exchange fails or authentication is invalid\n */\nexport async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {\n const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri);\n return executeTokenRequest(authorizationServerUrl, {\n metadata,\n tokenRequestParams,\n clientInformation,\n addClientAuthentication,\n resource,\n fetchFn\n });\n}\n/**\n * Exchange a refresh token for an updated access token.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Preserves the original refresh token if a new one is not returned\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, refresh token, etc.\n * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)\n * @throws {Error} When token refresh fails or authentication is invalid\n */\nexport async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {\n const tokenRequestParams = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken\n });\n const tokens = await executeTokenRequest(authorizationServerUrl, {\n metadata,\n tokenRequestParams,\n clientInformation,\n addClientAuthentication,\n resource,\n fetchFn\n });\n // Preserve original refresh token if server didn't return a new one\n return { refresh_token: refreshToken, ...tokens };\n}\n/**\n * Unified token fetching that works with any grant type via provider.prepareTokenRequest().\n *\n * This function provides a single entry point for obtaining tokens regardless of the\n * OAuth grant type. The provider's prepareTokenRequest() method determines which grant\n * to use and supplies the grant-specific parameters.\n *\n * @param provider - OAuth client provider that implements prepareTokenRequest()\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration for the token request\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails\n *\n * @example\n * // Provider for client_credentials:\n * class MyProvider implements OAuthClientProvider {\n * prepareTokenRequest(scope) {\n * const params = new URLSearchParams({ grant_type: 'client_credentials' });\n * if (scope) params.set('scope', scope);\n * return params;\n * }\n * // ... other methods\n * }\n *\n * const tokens = await fetchToken(provider, authServerUrl, { metadata });\n */\nexport async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {\n const scope = provider.clientMetadata.scope;\n // Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code\n let tokenRequestParams;\n if (provider.prepareTokenRequest) {\n tokenRequestParams = await provider.prepareTokenRequest(scope);\n }\n // Default to authorization_code grant if no custom prepareTokenRequest\n if (!tokenRequestParams) {\n if (!authorizationCode) {\n throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required');\n }\n if (!provider.redirectUrl) {\n throw new Error('redirectUrl is required for authorization_code flow');\n }\n const codeVerifier = await provider.codeVerifier();\n tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);\n }\n const clientInformation = await provider.clientInformation();\n return executeTokenRequest(authorizationServerUrl, {\n metadata,\n tokenRequestParams,\n clientInformation: clientInformation !== null && clientInformation !== void 0 ? clientInformation : undefined,\n addClientAuthentication: provider.addClientAuthentication,\n resource,\n fetchFn\n });\n}\n/**\n * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.\n */\nexport async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) {\n let registrationUrl;\n if (metadata) {\n if (!metadata.registration_endpoint) {\n throw new Error('Incompatible auth server: does not support dynamic client registration');\n }\n registrationUrl = new URL(metadata.registration_endpoint);\n }\n else {\n registrationUrl = new URL('/register', authorizationServerUrl);\n }\n const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(registrationUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(clientMetadata)\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return OAuthClientInformationFullSchema.parse(await response.json());\n}\n//# sourceMappingURL=auth.js.map","import { EventSource } from 'eventsource';\nimport { createFetchWithInit, normalizeHeaders } from '../shared/transport.js';\nimport { JSONRPCMessageSchema } from '../types.js';\nimport { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';\nexport class SseError extends Error {\n constructor(code, message, event) {\n super(`SSE error: ${message}`);\n this.code = code;\n this.event = event;\n }\n}\n/**\n * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving\n * messages and make separate POST requests for sending messages.\n * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.\n */\nexport class SSEClientTransport {\n constructor(url, opts) {\n this._url = url;\n this._resourceMetadataUrl = undefined;\n this._scope = undefined;\n this._eventSourceInit = opts === null || opts === void 0 ? void 0 : opts.eventSourceInit;\n this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;\n this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;\n this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;\n this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit);\n }\n async _authThenStart() {\n var _a;\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n let result;\n try {\n result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n }\n catch (error) {\n (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);\n throw error;\n }\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n return await this._startOrAuth();\n }\n async _commonHeaders() {\n var _a;\n const headers = {};\n if (this._authProvider) {\n const tokens = await this._authProvider.tokens();\n if (tokens) {\n headers['Authorization'] = `Bearer ${tokens.access_token}`;\n }\n }\n if (this._protocolVersion) {\n headers['mcp-protocol-version'] = this._protocolVersion;\n }\n const extraHeaders = normalizeHeaders((_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers);\n return new Headers({\n ...headers,\n ...extraHeaders\n });\n }\n _startOrAuth() {\n var _a, _b, _c;\n const fetchImpl = ((_c = (_b = (_a = this === null || this === void 0 ? void 0 : this._eventSourceInit) === null || _a === void 0 ? void 0 : _a.fetch) !== null && _b !== void 0 ? _b : this._fetch) !== null && _c !== void 0 ? _c : fetch);\n return new Promise((resolve, reject) => {\n this._eventSource = new EventSource(this._url.href, {\n ...this._eventSourceInit,\n fetch: async (url, init) => {\n const headers = await this._commonHeaders();\n headers.set('Accept', 'text/event-stream');\n const response = await fetchImpl(url, {\n ...init,\n headers\n });\n if (response.status === 401 && response.headers.has('www-authenticate')) {\n const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n this._resourceMetadataUrl = resourceMetadataUrl;\n this._scope = scope;\n }\n return response;\n }\n });\n this._abortController = new AbortController();\n this._eventSource.onerror = event => {\n var _a;\n if (event.code === 401 && this._authProvider) {\n this._authThenStart().then(resolve, reject);\n return;\n }\n const error = new SseError(event.code, event.message, event);\n reject(error);\n (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);\n };\n this._eventSource.onopen = () => {\n // The connection is open, but we need to wait for the endpoint to be received.\n };\n this._eventSource.addEventListener('endpoint', (event) => {\n var _a;\n const messageEvent = event;\n try {\n this._endpoint = new URL(messageEvent.data, this._url);\n if (this._endpoint.origin !== this._url.origin) {\n throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);\n }\n }\n catch (error) {\n reject(error);\n (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);\n void this.close();\n return;\n }\n resolve();\n });\n this._eventSource.onmessage = (event) => {\n var _a, _b;\n const messageEvent = event;\n let message;\n try {\n message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));\n }\n catch (error) {\n (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);\n return;\n }\n (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, message);\n };\n });\n }\n async start() {\n if (this._eventSource) {\n throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n }\n return await this._startOrAuth();\n }\n /**\n * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.\n */\n async finishAuth(authorizationCode) {\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n authorizationCode,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError('Failed to authorize');\n }\n }\n async close() {\n var _a, _b, _c;\n (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort();\n (_b = this._eventSource) === null || _b === void 0 ? void 0 : _b.close();\n (_c = this.onclose) === null || _c === void 0 ? void 0 : _c.call(this);\n }\n async send(message) {\n var _a, _b, _c, _d;\n if (!this._endpoint) {\n throw new Error('Not connected');\n }\n try {\n const headers = await this._commonHeaders();\n headers.set('content-type', 'application/json');\n const init = {\n ...this._requestInit,\n method: 'POST',\n headers,\n body: JSON.stringify(message),\n signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal\n };\n const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._endpoint, init);\n if (!response.ok) {\n const text = await response.text().catch(() => null);\n if (response.status === 401 && this._authProvider) {\n const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n this._resourceMetadataUrl = resourceMetadataUrl;\n this._scope = scope;\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n // Purposely _not_ awaited, so we don't call onerror twice\n return this.send(message);\n }\n throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);\n }\n // Release connection - POST responses don't have content we need\n await ((_c = response.body) === null || _c === void 0 ? void 0 : _c.cancel());\n }\n catch (error) {\n (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error);\n throw error;\n }\n }\n setProtocolVersion(version) {\n this._protocolVersion = version;\n }\n}\n//# sourceMappingURL=sse.js.map","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n onError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n },\n onRetry,\n onComment\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n","import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js';\nimport { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessageSchema } from '../types.js';\nimport { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';\nimport { EventSourceParserStream } from 'eventsource-parser/stream';\n// Default reconnection options for StreamableHTTP connections\nconst DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {\n initialReconnectionDelay: 1000,\n maxReconnectionDelay: 30000,\n reconnectionDelayGrowFactor: 1.5,\n maxRetries: 2\n};\nexport class StreamableHTTPError extends Error {\n constructor(code, message) {\n super(`Streamable HTTP error: ${message}`);\n this.code = code;\n }\n}\n/**\n * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.\n * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events\n * for receiving messages.\n */\nexport class StreamableHTTPClientTransport {\n constructor(url, opts) {\n var _a;\n this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401\n this._url = url;\n this._resourceMetadataUrl = undefined;\n this._scope = undefined;\n this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;\n this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;\n this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;\n this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit);\n this._sessionId = opts === null || opts === void 0 ? void 0 : opts.sessionId;\n this._reconnectionOptions = (_a = opts === null || opts === void 0 ? void 0 : opts.reconnectionOptions) !== null && _a !== void 0 ? _a : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;\n }\n async _authThenStart() {\n var _a;\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n let result;\n try {\n result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n }\n catch (error) {\n (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);\n throw error;\n }\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n return await this._startOrAuthSse({ resumptionToken: undefined });\n }\n async _commonHeaders() {\n var _a;\n const headers = {};\n if (this._authProvider) {\n const tokens = await this._authProvider.tokens();\n if (tokens) {\n headers['Authorization'] = `Bearer ${tokens.access_token}`;\n }\n }\n if (this._sessionId) {\n headers['mcp-session-id'] = this._sessionId;\n }\n if (this._protocolVersion) {\n headers['mcp-protocol-version'] = this._protocolVersion;\n }\n const extraHeaders = normalizeHeaders((_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers);\n return new Headers({\n ...headers,\n ...extraHeaders\n });\n }\n async _startOrAuthSse(options) {\n var _a, _b, _c, _d;\n const { resumptionToken } = options;\n try {\n // Try to open an initial SSE stream with GET to listen for server messages\n // This is optional according to the spec - server may not support it\n const headers = await this._commonHeaders();\n headers.set('Accept', 'text/event-stream');\n // Include Last-Event-ID header for resumable streams if provided\n if (resumptionToken) {\n headers.set('last-event-id', resumptionToken);\n }\n const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._url, {\n method: 'GET',\n headers,\n signal: (_b = this._abortController) === null || _b === void 0 ? void 0 : _b.signal\n });\n if (!response.ok) {\n await ((_c = response.body) === null || _c === void 0 ? void 0 : _c.cancel());\n if (response.status === 401 && this._authProvider) {\n // Need to authenticate\n return await this._authThenStart();\n }\n // 405 indicates that the server does not offer an SSE stream at GET endpoint\n // This is an expected case that should not trigger an error\n if (response.status === 405) {\n return;\n }\n throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);\n }\n this._handleSseStream(response.body, options, true);\n }\n catch (error) {\n (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error);\n throw error;\n }\n }\n /**\n * Calculates the next reconnection delay using backoff algorithm\n *\n * @param attempt Current reconnection attempt count for the specific stream\n * @returns Time to wait in milliseconds before next reconnection attempt\n */\n _getNextReconnectionDelay(attempt) {\n // Use server-provided retry value if available\n if (this._serverRetryMs !== undefined) {\n return this._serverRetryMs;\n }\n // Fall back to exponential backoff\n const initialDelay = this._reconnectionOptions.initialReconnectionDelay;\n const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;\n const maxDelay = this._reconnectionOptions.maxReconnectionDelay;\n // Cap at maximum delay\n return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);\n }\n /**\n * Schedule a reconnection attempt using server-provided retry interval or backoff\n *\n * @param lastEventId The ID of the last received event for resumability\n * @param attemptCount Current reconnection attempt count for this specific stream\n */\n _scheduleReconnection(options, attemptCount = 0) {\n var _a;\n // Use provided options or default options\n const maxRetries = this._reconnectionOptions.maxRetries;\n // Check if we've exceeded maximum retry attempts\n if (attemptCount >= maxRetries) {\n (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));\n return;\n }\n // Calculate next delay based on current attempt count\n const delay = this._getNextReconnectionDelay(attemptCount);\n // Schedule the reconnection\n this._reconnectionTimeout = setTimeout(() => {\n // Use the last event ID to resume where we left off\n this._startOrAuthSse(options).catch(error => {\n var _a;\n (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));\n // Schedule another attempt if this one failed, incrementing the attempt counter\n this._scheduleReconnection(options, attemptCount + 1);\n });\n }, delay);\n }\n _handleSseStream(stream, options, isReconnectable) {\n if (!stream) {\n return;\n }\n const { onresumptiontoken, replayMessageId } = options;\n let lastEventId;\n // Track whether we've received a priming event (event with ID)\n // Per spec, server SHOULD send a priming event with ID before closing\n let hasPrimingEvent = false;\n // Track whether we've received a response - if so, no need to reconnect\n // Reconnection is for when server disconnects BEFORE sending response\n let receivedResponse = false;\n const processStream = async () => {\n var _a, _b, _c, _d;\n // this is the closest we can get to trying to catch network errors\n // if something happens reader will throw\n try {\n // Create a pipeline: binary stream -> text decoder -> SSE parser\n const reader = stream\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new EventSourceParserStream({\n onRetry: (retryMs) => {\n // Capture server-provided retry value for reconnection timing\n this._serverRetryMs = retryMs;\n }\n }))\n .getReader();\n while (true) {\n const { value: event, done } = await reader.read();\n if (done) {\n break;\n }\n // Update last event ID if provided\n if (event.id) {\n lastEventId = event.id;\n // Mark that we've received a priming event - stream is now resumable\n hasPrimingEvent = true;\n onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id);\n }\n // Skip events with no data (priming events, keep-alives)\n if (!event.data) {\n continue;\n }\n if (!event.event || event.event === 'message') {\n try {\n const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));\n if (isJSONRPCResponse(message)) {\n // Mark that we received a response - no need to reconnect for this request\n receivedResponse = true;\n if (replayMessageId !== undefined) {\n message.id = replayMessageId;\n }\n }\n (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message);\n }\n catch (error) {\n (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error);\n }\n }\n }\n // Handle graceful server-side disconnect\n // Server may close connection after sending event ID and retry field\n // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n // BUT don't reconnect if we already received a response - the request is complete\n const canResume = isReconnectable || hasPrimingEvent;\n const needsReconnect = canResume && !receivedResponse;\n if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {\n this._scheduleReconnection({\n resumptionToken: lastEventId,\n onresumptiontoken,\n replayMessageId\n }, 0);\n }\n }\n catch (error) {\n // Handle stream errors - likely a network disconnect\n (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, new Error(`SSE stream disconnected: ${error}`));\n // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing\n // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n // BUT don't reconnect if we already received a response - the request is complete\n const canResume = isReconnectable || hasPrimingEvent;\n const needsReconnect = canResume && !receivedResponse;\n if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {\n // Use the exponential backoff reconnection strategy\n try {\n this._scheduleReconnection({\n resumptionToken: lastEventId,\n onresumptiontoken,\n replayMessageId\n }, 0);\n }\n catch (error) {\n (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`));\n }\n }\n }\n };\n processStream();\n }\n async start() {\n if (this._abortController) {\n throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n }\n this._abortController = new AbortController();\n }\n /**\n * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.\n */\n async finishAuth(authorizationCode) {\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n authorizationCode,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError('Failed to authorize');\n }\n }\n async close() {\n var _a, _b;\n if (this._reconnectionTimeout) {\n clearTimeout(this._reconnectionTimeout);\n this._reconnectionTimeout = undefined;\n }\n (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort();\n (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this);\n }\n async send(message, options) {\n var _a, _b, _c, _d, _e, _f, _g;\n try {\n const { resumptionToken, onresumptiontoken } = options || {};\n if (resumptionToken) {\n // If we have at last event ID, we need to reconnect the SSE stream\n this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); });\n return;\n }\n const headers = await this._commonHeaders();\n headers.set('content-type', 'application/json');\n headers.set('accept', 'application/json, text/event-stream');\n const init = {\n ...this._requestInit,\n method: 'POST',\n headers,\n body: JSON.stringify(message),\n signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal\n };\n const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init);\n // Handle session ID received during initialization\n const sessionId = response.headers.get('mcp-session-id');\n if (sessionId) {\n this._sessionId = sessionId;\n }\n if (!response.ok) {\n const text = await response.text().catch(() => null);\n if (response.status === 401 && this._authProvider) {\n // Prevent infinite recursion when server returns 401 after successful auth\n if (this._hasCompletedAuthFlow) {\n throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication');\n }\n const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n this._resourceMetadataUrl = resourceMetadataUrl;\n this._scope = scope;\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n // Mark that we completed auth flow\n this._hasCompletedAuthFlow = true;\n // Purposely _not_ awaited, so we don't call onerror twice\n return this.send(message);\n }\n if (response.status === 403 && this._authProvider) {\n const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);\n if (error === 'insufficient_scope') {\n const wwwAuthHeader = response.headers.get('WWW-Authenticate');\n // Check if we've already tried upscoping with this header to prevent infinite loops.\n if (this._lastUpscopingHeader === wwwAuthHeader) {\n throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping');\n }\n if (scope) {\n this._scope = scope;\n }\n if (resourceMetadataUrl) {\n this._resourceMetadataUrl = resourceMetadataUrl;\n }\n // Mark that upscoping was tried.\n this._lastUpscopingHeader = wwwAuthHeader !== null && wwwAuthHeader !== void 0 ? wwwAuthHeader : undefined;\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetch\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n return this.send(message);\n }\n }\n throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);\n }\n // Reset auth loop flag on successful response\n this._hasCompletedAuthFlow = false;\n this._lastUpscopingHeader = undefined;\n // If the response is 202 Accepted, there's no body to process\n if (response.status === 202) {\n await ((_c = response.body) === null || _c === void 0 ? void 0 : _c.cancel());\n // if the accepted notification is initialized, we start the SSE stream\n // if it's supported by the server\n if (isInitializedNotification(message)) {\n // Start without a lastEventId since this is a fresh connection\n this._startOrAuthSse({ resumptionToken: undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); });\n }\n return;\n }\n // Get original message(s) for detecting request IDs\n const messages = Array.isArray(message) ? message : [message];\n const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0;\n // Check the response type\n const contentType = response.headers.get('content-type');\n if (hasRequests) {\n if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('text/event-stream')) {\n // Handle SSE stream responses for requests\n // We use the same handler as standalone streams, which now supports\n // reconnection with the last event ID\n this._handleSseStream(response.body, { onresumptiontoken }, false);\n }\n else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {\n // For non-streaming servers, we might get direct JSON responses\n const data = await response.json();\n const responseMessages = Array.isArray(data)\n ? data.map(msg => JSONRPCMessageSchema.parse(msg))\n : [JSONRPCMessageSchema.parse(data)];\n for (const msg of responseMessages) {\n (_d = this.onmessage) === null || _d === void 0 ? void 0 : _d.call(this, msg);\n }\n }\n else {\n await ((_e = response.body) === null || _e === void 0 ? void 0 : _e.cancel());\n throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);\n }\n }\n else {\n // No requests in message but got 200 OK - still need to release connection\n await ((_f = response.body) === null || _f === void 0 ? void 0 : _f.cancel());\n }\n }\n catch (error) {\n (_g = this.onerror) === null || _g === void 0 ? void 0 : _g.call(this, error);\n throw error;\n }\n }\n get sessionId() {\n return this._sessionId;\n }\n /**\n * Terminates the current session by sending a DELETE request to the server.\n *\n * Clients that no longer need a particular session\n * (e.g., because the user is leaving the client application) SHOULD send an\n * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly\n * terminate the session.\n *\n * The server MAY respond with HTTP 405 Method Not Allowed, indicating that\n * the server does not allow clients to terminate sessions.\n */\n async terminateSession() {\n var _a, _b, _c, _d;\n if (!this._sessionId) {\n return; // No session to terminate\n }\n try {\n const headers = await this._commonHeaders();\n const init = {\n ...this._requestInit,\n method: 'DELETE',\n headers,\n signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal\n };\n const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init);\n await ((_c = response.body) === null || _c === void 0 ? void 0 : _c.cancel());\n // We specifically handle 405 as a valid response according to the spec,\n // meaning the server does not support explicit session termination\n if (!response.ok && response.status !== 405) {\n throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);\n }\n this._sessionId = undefined;\n }\n catch (error) {\n (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error);\n throw error;\n }\n }\n setProtocolVersion(version) {\n this._protocolVersion = version;\n }\n get protocolVersion() {\n return this._protocolVersion;\n }\n /**\n * Resume an SSE stream from a previous event ID.\n * Opens a GET SSE connection with Last-Event-ID header to replay missed events.\n *\n * @param lastEventId The event ID to resume from\n * @param options Optional callback to receive new resumption tokens\n */\n async resumeStream(lastEventId, options) {\n await this._startOrAuthSse({\n resumptionToken: lastEventId,\n onresumptiontoken: options === null || options === void 0 ? void 0 : options.onresumptiontoken\n });\n }\n}\n//# sourceMappingURL=streamableHttp.js.map","import process from 'node:process';\nimport { ReadBuffer, serializeMessage } from '../shared/stdio.js';\n/**\n * Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout.\n *\n * This transport is only available in Node.js environments.\n */\nexport class StdioServerTransport {\n constructor(_stdin = process.stdin, _stdout = process.stdout) {\n this._stdin = _stdin;\n this._stdout = _stdout;\n this._readBuffer = new ReadBuffer();\n this._started = false;\n // Arrow functions to bind `this` properly, while maintaining function identity.\n this._ondata = (chunk) => {\n this._readBuffer.append(chunk);\n this.processReadBuffer();\n };\n this._onerror = (error) => {\n var _a;\n (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error);\n };\n }\n /**\n * Starts listening for messages on stdin.\n */\n async start() {\n if (this._started) {\n throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.');\n }\n this._started = true;\n this._stdin.on('data', this._ondata);\n this._stdin.on('error', this._onerror);\n }\n processReadBuffer() {\n var _a, _b;\n while (true) {\n try {\n const message = this._readBuffer.readMessage();\n if (message === null) {\n break;\n }\n (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message);\n }\n catch (error) {\n (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error);\n }\n }\n }\n async close() {\n var _a;\n // Remove our event listeners first\n this._stdin.off('data', this._ondata);\n this._stdin.off('error', this._onerror);\n // Check if we were the only data listener\n const remainingDataListeners = this._stdin.listenerCount('data');\n if (remainingDataListeners === 0) {\n // Only pause stdin if we were the only listener\n // This prevents interfering with other parts of the application that might be using stdin\n this._stdin.pause();\n }\n // Clear the buffer and notify closure\n this._readBuffer.clear();\n (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n send(message) {\n return new Promise(resolve => {\n const json = serializeMessage(message);\n if (this._stdout.write(json)) {\n resolve();\n }\n else {\n this._stdout.once('drain', resolve);\n }\n });\n }\n}\n//# sourceMappingURL=stdio.js.map","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n\nimport { proxyServer } from \"./proxyServer.js\";\n\nexport enum ServerType {\n HTTPStream = \"HTTPStream\",\n SSE = \"SSE\",\n}\n\nexport const startStdioServer = async ({\n initStdioServer,\n initStreamClient,\n serverType,\n transportOptions = {},\n url,\n}: {\n initStdioServer?: () => Promise<Server>;\n initStreamClient?: () => Promise<Client>;\n serverType: ServerType;\n transportOptions?:\n | SSEClientTransportOptions\n | StreamableHTTPClientTransportOptions;\n url: string;\n}): Promise<Server> => {\n let transport: SSEClientTransport | StreamableHTTPClientTransport;\n switch (serverType) {\n case ServerType.SSE:\n transport = new SSEClientTransport(new URL(url), transportOptions);\n break;\n default:\n transport = new StreamableHTTPClientTransport(\n new URL(url),\n transportOptions,\n );\n }\n const streamClient = initStreamClient\n ? await initStreamClient()\n : new Client(\n {\n name: \"mcp-proxy\",\n version: \"1.0.0\",\n },\n {\n capabilities: {},\n },\n );\n\n await streamClient.connect(transport);\n\n const serverVersion = streamClient.getServerVersion() as {\n name: string;\n version: string;\n };\n\n const serverCapabilities = streamClient.getServerCapabilities() as {\n capabilities: Record<string, unknown>;\n };\n\n const stdioServer = initStdioServer\n ? await initStdioServer()\n : new Server(serverVersion, {\n capabilities: serverCapabilities,\n });\n\n const stdioTransport = new StdioServerTransport();\n\n await stdioServer.connect(stdioTransport);\n\n await proxyServer({\n client: streamClient,\n server: stdioServer,\n serverCapabilities,\n });\n\n return stdioServer;\n};\n","import { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\n\ntype TransportEvent =\n | {\n error: Error;\n type: \"onerror\";\n }\n | {\n message: JSONRPCMessage;\n type: \"onmessage\";\n }\n | {\n message: JSONRPCMessage;\n type: \"send\";\n }\n | {\n type: \"close\";\n }\n | {\n type: \"onclose\";\n }\n | {\n type: \"start\";\n };\n\nexport const tapTransport = (\n transport: Transport,\n eventHandler: (event: TransportEvent) => void,\n): Transport => {\n const originalClose = transport.close.bind(transport);\n const originalOnClose = transport.onclose?.bind(transport);\n const originalOnError = transport.onerror?.bind(transport);\n const originalOnMessage = transport.onmessage?.bind(transport);\n const originalSend = transport.send.bind(transport);\n const originalStart = transport.start.bind(transport);\n\n transport.close = async () => {\n eventHandler({\n type: \"close\",\n });\n\n return originalClose?.();\n };\n\n transport.onclose = async () => {\n eventHandler({\n type: \"onclose\",\n });\n\n return originalOnClose?.();\n };\n\n transport.onerror = async (error: Error) => {\n eventHandler({\n error,\n type: \"onerror\",\n });\n\n return originalOnError?.(error);\n };\n\n transport.onmessage = async (message: JSONRPCMessage) => {\n eventHandler({\n message,\n type: \"onmessage\",\n });\n\n return originalOnMessage?.(message);\n };\n\n transport.send = async (message: JSONRPCMessage) => {\n eventHandler({\n message,\n type: \"send\",\n });\n\n return originalSend?.(message);\n };\n\n transport.start = async () => {\n eventHandler({\n type: \"start\",\n });\n\n return originalStart?.();\n };\n\n return transport;\n};\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],"mappings":";;;;;AAGA,MAAa,eAAe;CACxB,cAAc;CACd,SAAS;CACT,WA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QAAQ,eAAe;AAEzC,OAAM,YAAY;EAChB,QAAQ;EACR,QAAQ;EACR;EACD,CAAC;AAEF,QAAO;;;;;ACtDT,MAAa,gBACX,WACA,iBACc;CACd,MAAM,gBAAgB,UAAU,MAAM,KAAK,UAAU;CACrD,MAAM,kBAAkB,UAAU,SAAS,KAAK,UAAU;CAC1D,MAAM,kBAAkB,UAAU,SAAS,KAAK,UAAU;CAC1D,MAAM,oBAAoB,UAAU,WAAW,KAAK,UAAU;CAC9D,MAAM,eAAe,UAAU,KAAK,KAAK,UAAU;CACnD,MAAM,gBAAgB,UAAU,MAAM,KAAK,UAAU;AAErD,WAAU,QAAQ,YAAY;AAC5B,eAAa,EACX,MAAM,SACP,CAAC;AAEF,SAAO,iBAAiB;;AAG1B,WAAU,UAAU,YAAY;AAC9B,eAAa,EACX,MAAM,WACP,CAAC;AAEF,SAAO,mBAAmB;;AAG5B,WAAU,UAAU,OAAO,UAAiB;AAC1C,eAAa;GACX;GACA,MAAM;GACP,CAAC;AAEF,SAAO,kBAAkB,MAAM;;AAGjC,WAAU,YAAY,OAAO,YAA4B;AACvD,eAAa;GACX;GACA,MAAM;GACP,CAAC;AAEF,SAAO,oBAAoB,QAAQ;;AAGrC,WAAU,OAAO,OAAO,YAA4B;AAClD,eAAa;GACX;GACA,MAAM;GACP,CAAC;AAEF,SAAO,eAAe,QAAQ;;AAGhC,WAAU,QAAQ,YAAY;AAC5B,eAAa,EACX,MAAM,SACP,CAAC;AAEF,SAAO,iBAAiB;;AAG1B,QAAO"}

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Valerio357/bet-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server