mcp-proxy 5.6.0 → 5.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["codeVerifier","tokens","_a","_b","_a","error","transport: SSEClientTransport | StreamableHTTPClientTransport"],"sources":["../node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/index.js","../node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js","../node_modules/.pnpm/pkce-challenge@5.0.0/node_modules/pkce-challenge/dist/index.node.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js","../node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/stream.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js","../src/startStdioServer.ts","../src/tapTransport.ts"],"sourcesContent":["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 ? 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","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 { z } from \"zod\";\n/**\n * RFC 9728 OAuth Protected Resource Metadata\n */\nexport const OAuthProtectedResourceMetadataSchema = z\n .object({\n resource: z.string().url(),\n authorization_servers: z.array(z.string().url()).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 .passthrough();\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z\n .object({\n issuer: z.string(),\n authorization_endpoint: z.string(),\n token_endpoint: z.string(),\n registration_endpoint: z.string().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\n .array(z.string())\n .optional(),\n service_documentation: z.string().optional(),\n revocation_endpoint: z.string().optional(),\n revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n revocation_endpoint_auth_signing_alg_values_supported: z\n .array(z.string())\n .optional(),\n introspection_endpoint: z.string().optional(),\n introspection_endpoint_auth_methods_supported: z\n .array(z.string())\n .optional(),\n introspection_endpoint_auth_signing_alg_values_supported: z\n .array(z.string())\n .optional(),\n code_challenge_methods_supported: z.array(z.string()).optional(),\n})\n .passthrough();\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\n .object({\n issuer: z.string(),\n authorization_endpoint: z.string(),\n token_endpoint: z.string(),\n userinfo_endpoint: z.string().optional(),\n jwks_uri: z.string(),\n registration_endpoint: z.string().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\n .array(z.string())\n .optional(),\n request_object_encryption_enc_values_supported: z\n .array(z.string())\n .optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z\n .array(z.string())\n .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: z.string().optional(),\n op_tos_uri: z.string().optional(),\n})\n .passthrough();\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 = OpenIdProviderMetadataSchema.merge(OAuthMetadataSchema.pick({\n code_challenge_methods_supported: true,\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.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\n .object({\n error: z.string(),\n error_description: z.string().optional(),\n error_uri: z.string().optional(),\n});\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z.object({\n redirect_uris: z.array(z.string()).refine((uris) => uris.every((uri) => URL.canParse(uri)), { message: \"redirect_uris must contain valid URLs\" }),\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: z.string().optional(),\n logo_uri: z.string().optional(),\n scope: z.string().optional(),\n contacts: z.array(z.string()).optional(),\n tos_uri: z.string().optional(),\n policy_uri: z.string().optional(),\n jwks_uri: z.string().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}).strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z.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}).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.object({\n error: z.string(),\n error_description: z.string().optional(),\n}).strip();\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z.object({\n token: z.string(),\n token_type_hint: z.string().optional(),\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 * 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};\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, 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}\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 */\nfunction 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 // 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 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 (_a) {\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 acts as the Authorization server.\n */\n if (!authorizationServerUrl) {\n authorizationServerUrl = 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 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 // Exchange authorization code for tokens\n if (authorizationCode !== undefined) {\n const codeVerifier = await provider.codeVerifier();\n const tokens = await exchangeAuthorization(authorizationServerUrl, {\n metadata,\n clientInformation,\n authorizationCode,\n codeVerifier,\n redirectUri: provider.redirectUrl,\n resource,\n addClientAuthentication: provider.addClientAuthentication,\n fetchFn: 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 || provider.clientMetadata.scope,\n resource,\n });\n await provider.saveCodeVerifier(codeVerifier);\n await provider.redirectToAuthorization(authorizationUrl);\n return \"REDIRECT\";\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 from response header.\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 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 throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);\n }\n if (!response.ok) {\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\n ? `${pathname}/.well-known/${wellKnownPrefix}`\n : `/.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 === 404 && 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 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 return undefined;\n }\n if (!response.ok) {\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. OAuth metadata at root (if URL has path)\n * 3. OIDC metadata endpoints\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 // 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 // 3. 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 = { 'MCP-Protocol-Version': protocolVersion };\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 // 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 const metadata = OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());\n // MCP spec requires OIDC providers to support S256 PKCE\n if (!((_a = metadata.code_challenge_methods_supported) === null || _a === void 0 ? void 0 : _a.includes('S256'))) {\n throw new Error(`Incompatible OIDC provider at ${endpointUrl}: does not support S256 code challenge method required by MCP specification`);\n }\n return metadata;\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 const responseType = \"code\";\n const codeChallengeMethod = \"S256\";\n let authorizationUrl;\n if (metadata) {\n authorizationUrl = new URL(metadata.authorization_endpoint);\n if (!metadata.response_types_supported.includes(responseType)) {\n throw new Error(`Incompatible auth server: does not support response type ${responseType}`);\n }\n if (!metadata.code_challenge_methods_supported ||\n !metadata.code_challenge_methods_supported.includes(codeChallengeMethod)) {\n throw new Error(`Incompatible auth server: does not support code challenge method ${codeChallengeMethod}`);\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\", responseType);\n authorizationUrl.searchParams.set(\"client_id\", clientInformation.client_id);\n authorizationUrl.searchParams.set(\"code_challenge\", codeChallenge);\n authorizationUrl.searchParams.set(\"code_challenge_method\", codeChallengeMethod);\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 * 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 var _a;\n const grantType = \"authorization_code\";\n const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint)\n ? new URL(metadata.token_endpoint)\n : new URL(\"/token\", authorizationServerUrl);\n if ((metadata === null || metadata === void 0 ? void 0 : metadata.grant_types_supported) &&\n !metadata.grant_types_supported.includes(grantType)) {\n throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);\n }\n // Exchange code for tokens\n const headers = new Headers({\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"application/json\",\n });\n const params = new URLSearchParams({\n grant_type: grantType,\n code: authorizationCode,\n code_verifier: codeVerifier,\n redirect_uri: String(redirectUri),\n });\n if (addClientAuthentication) {\n addClientAuthentication(headers, params, authorizationServerUrl, metadata);\n }\n else {\n // Determine and apply client authentication method\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, params);\n }\n if (resource) {\n params.set(\"resource\", resource.href);\n }\n const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {\n method: \"POST\",\n headers,\n body: params,\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return OAuthTokensSchema.parse(await response.json());\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 var _a;\n const grantType = \"refresh_token\";\n let tokenUrl;\n if (metadata) {\n tokenUrl = new URL(metadata.token_endpoint);\n if (metadata.grant_types_supported &&\n !metadata.grant_types_supported.includes(grantType)) {\n throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);\n }\n }\n else {\n tokenUrl = new URL(\"/token\", authorizationServerUrl);\n }\n // Exchange refresh token\n const headers = new Headers({\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n });\n const params = new URLSearchParams({\n grant_type: grantType,\n refresh_token: refreshToken,\n });\n if (addClientAuthentication) {\n addClientAuthentication(headers, params, authorizationServerUrl, metadata);\n }\n else {\n // Determine and apply client authentication method\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, params);\n }\n if (resource) {\n params.set(\"resource\", resource.href);\n }\n const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {\n method: \"POST\",\n headers,\n body: params,\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return OAuthTokensSchema.parse({ refresh_token: refreshToken, ...(await response.json()) });\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 { JSONRPCMessageSchema } from \"../types.js\";\nimport { auth, extractResourceMetadataUrl, 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 */\nexport class SSEClientTransport {\n constructor(url, opts) {\n this._url = url;\n this._resourceMetadataUrl = 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 }\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, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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 return new Headers({ ...headers, ...(_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers });\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 this._resourceMetadataUrl = extractResourceMetadataUrl(response);\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, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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;\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 if (response.status === 401 && this._authProvider) {\n this._resourceMetadataUrl = extractResourceMetadataUrl(response);\n const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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 const text = await response.text().catch(() => null);\n throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);\n }\n }\n catch (error) {\n (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.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 { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessageSchema } from \"../types.js\";\nimport { auth, extractResourceMetadataUrl, 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._url = url;\n this._resourceMetadataUrl = 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._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, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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 = this._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;\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 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 (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.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 // Access default values directly, ensuring they're never undefined\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 _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 * Schedule a reconnection attempt with exponential 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 (maxRetries > 0 && 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 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 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 .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 onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id);\n }\n if (!event.event || event.event === \"message\") {\n try {\n const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));\n if (replayMessageId !== undefined && isJSONRPCResponse(message)) {\n message.id = replayMessageId;\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 }\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 if (isReconnectable &&\n this._abortController &&\n !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, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\n if (result !== \"AUTHORIZED\") {\n throw new UnauthorizedError(\"Failed to authorize\");\n }\n }\n async close() {\n var _a, _b;\n // Abort any pending requests\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;\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 if (response.status === 401 && this._authProvider) {\n this._resourceMetadataUrl = extractResourceMetadataUrl(response);\n const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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 const text = await response.text().catch(() => null);\n throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);\n }\n // If the response is 202 Accepted, there's no body to process\n if (response.status === 202) {\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 (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, msg);\n }\n }\n else {\n throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);\n }\n }\n }\n catch (error) {\n (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.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;\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 // 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 (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.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//# 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 a 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],"mappings":";;;;AAAA,IAAM,aAAN,cAAyB,MAAM;CAC7B,YAAY,SAAS,SAAS;AAC5B,QAAM,UAAU,KAAK,OAAO,cAAc,KAAK,OAAO,QAAQ,MAAM,KAAK,QAAQ,QAAQ,OAAO,KAAK,QAAQ,QAAQ,OAAO,KAAK,OAAO,QAAQ;;;AAGpJ,SAAS,KAAK,MAAM;AAEpB,SAAS,aAAa,WAAW;AAC/B,KAAI,OAAO,aAAa,WACtB,OAAM,IAAI,UACR;CAEJ,MAAM,EAAE,UAAU,MAAM,UAAU,MAAM,UAAU,MAAM,cAAc;CACtE,IAAI,iBAAiB,IAAI,eAAe,CAAC,GAAG,IAAI,OAAO,IAAI,YAAY;CACvE,SAAS,KAAK,UAAU;EACtB,MAAM,QAAQ,eAAe,SAAS,QAAQ,iBAAiB,MAAM,UAAU,CAAC,UAAU,cAAc,WAAW,GAAG,iBAAiB;AACvI,OAAK,MAAM,QAAQ,SACjB,WAAU;AACZ,mBAAiB,YAAY,eAAe,CAAC;;CAE/C,SAAS,UAAU,MAA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UAAiB;AAC1C,eAAa;GACX;GACA,MAAM;;AAGR,SAAO,kBAAkB;;AAG3B,WAAU,YAAY,OAAO,YAA4B;AACvD,eAAa;GACX;GACA,MAAM;;AAGR,SAAO,oBAAoB;;AAG7B,WAAU,OAAO,OAAO,YAA4B;AAClD,eAAa;GACX;GACA,MAAM;;AAGR,SAAO,eAAe;;AAGxB,WAAU,QAAQ,YAAY;AAC5B,eAAa,EACX,MAAM;AAGR,SAAO;;AAGT,QAAO"}
1
+ {"version":3,"file":"index.js","names":["z.string","z.NEVER","z\n .object","z.array","z.boolean","z\n .array","z.number","z.object","z.any","codeVerifier","tokens","_a","_b","_a","error","transport: SSEClientTransport | StreamableHTTPClientTransport"],"sources":["../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/pkce-challenge@5.0.0/node_modules/pkce-challenge/dist/index.node.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.18.1/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.18.1/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.18.1/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.18.1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.18.1/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.18.1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.18.1/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js","../src/startStdioServer.ts","../src/tapTransport.ts"],"sourcesContent":["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","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 { z } from \"zod\";\n/**\n * Reusable URL validation that disallows javascript: scheme\n */\nexport const SafeUrlSchema = z.string().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}).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\n .object({\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 .passthrough();\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z\n .object({\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\n .array(z.string())\n .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\n .array(z.string())\n .optional(),\n introspection_endpoint: z.string().optional(),\n introspection_endpoint_auth_methods_supported: z\n .array(z.string())\n .optional(),\n introspection_endpoint_auth_signing_alg_values_supported: z\n .array(z.string())\n .optional(),\n code_challenge_methods_supported: z.array(z.string()).optional(),\n})\n .passthrough();\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\n .object({\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\n .array(z.string())\n .optional(),\n request_object_encryption_enc_values_supported: z\n .array(z.string())\n .optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z\n .array(z.string())\n .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})\n .passthrough();\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 = OpenIdProviderMetadataSchema.merge(OAuthMetadataSchema.pick({\n code_challenge_methods_supported: true,\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.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\n .object({\n error: z.string(),\n error_description: z.string().optional(),\n error_uri: z.string().optional(),\n});\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z.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: SafeUrlSchema.optional(),\n scope: z.string().optional(),\n contacts: z.array(z.string()).optional(),\n tos_uri: SafeUrlSchema.optional(),\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}).strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z.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}).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.object({\n error: z.string(),\n error_description: z.string().optional(),\n}).strip();\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z.object({\n token: z.string(),\n token_type_hint: z.string().optional(),\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 * 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};\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, 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}\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 */\nfunction 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 // 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 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 (_a) {\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 acts as the Authorization server.\n */\n if (!authorizationServerUrl) {\n authorizationServerUrl = 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 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 // Exchange authorization code for tokens\n if (authorizationCode !== undefined) {\n const codeVerifier = await provider.codeVerifier();\n const tokens = await exchangeAuthorization(authorizationServerUrl, {\n metadata,\n clientInformation,\n authorizationCode,\n codeVerifier,\n redirectUri: provider.redirectUrl,\n resource,\n addClientAuthentication: provider.addClientAuthentication,\n fetchFn: 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 || provider.clientMetadata.scope,\n resource,\n });\n await provider.saveCodeVerifier(codeVerifier);\n await provider.redirectToAuthorization(authorizationUrl);\n return \"REDIRECT\";\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 from response header.\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 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 throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);\n }\n if (!response.ok) {\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\n ? `${pathname}/.well-known/${wellKnownPrefix}`\n : `/.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 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 return undefined;\n }\n if (!response.ok) {\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. OAuth metadata at root (if URL has path)\n * 3. OIDC metadata endpoints\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 // 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 // 3. 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 = { 'MCP-Protocol-Version': protocolVersion };\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 // 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 const metadata = OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());\n // MCP spec requires OIDC providers to support S256 PKCE\n if (!((_a = metadata.code_challenge_methods_supported) === null || _a === void 0 ? void 0 : _a.includes('S256'))) {\n throw new Error(`Incompatible OIDC provider at ${endpointUrl}: does not support S256 code challenge method required by MCP specification`);\n }\n return metadata;\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 const responseType = \"code\";\n const codeChallengeMethod = \"S256\";\n let authorizationUrl;\n if (metadata) {\n authorizationUrl = new URL(metadata.authorization_endpoint);\n if (!metadata.response_types_supported.includes(responseType)) {\n throw new Error(`Incompatible auth server: does not support response type ${responseType}`);\n }\n if (!metadata.code_challenge_methods_supported ||\n !metadata.code_challenge_methods_supported.includes(codeChallengeMethod)) {\n throw new Error(`Incompatible auth server: does not support code challenge method ${codeChallengeMethod}`);\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\", responseType);\n authorizationUrl.searchParams.set(\"client_id\", clientInformation.client_id);\n authorizationUrl.searchParams.set(\"code_challenge\", codeChallenge);\n authorizationUrl.searchParams.set(\"code_challenge_method\", codeChallengeMethod);\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 * 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 var _a;\n const grantType = \"authorization_code\";\n const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint)\n ? new URL(metadata.token_endpoint)\n : new URL(\"/token\", authorizationServerUrl);\n if ((metadata === null || metadata === void 0 ? void 0 : metadata.grant_types_supported) &&\n !metadata.grant_types_supported.includes(grantType)) {\n throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);\n }\n // Exchange code for tokens\n const headers = new Headers({\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"application/json\",\n });\n const params = new URLSearchParams({\n grant_type: grantType,\n code: authorizationCode,\n code_verifier: codeVerifier,\n redirect_uri: String(redirectUri),\n });\n if (addClientAuthentication) {\n addClientAuthentication(headers, params, authorizationServerUrl, metadata);\n }\n else {\n // Determine and apply client authentication method\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, params);\n }\n if (resource) {\n params.set(\"resource\", resource.href);\n }\n const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {\n method: \"POST\",\n headers,\n body: params,\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return OAuthTokensSchema.parse(await response.json());\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 var _a;\n const grantType = \"refresh_token\";\n let tokenUrl;\n if (metadata) {\n tokenUrl = new URL(metadata.token_endpoint);\n if (metadata.grant_types_supported &&\n !metadata.grant_types_supported.includes(grantType)) {\n throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);\n }\n }\n else {\n tokenUrl = new URL(\"/token\", authorizationServerUrl);\n }\n // Exchange refresh token\n const headers = new Headers({\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n });\n const params = new URLSearchParams({\n grant_type: grantType,\n refresh_token: refreshToken,\n });\n if (addClientAuthentication) {\n addClientAuthentication(headers, params, authorizationServerUrl, metadata);\n }\n else {\n // Determine and apply client authentication method\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, params);\n }\n if (resource) {\n params.set(\"resource\", resource.href);\n }\n const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {\n method: \"POST\",\n headers,\n body: params,\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return OAuthTokensSchema.parse({ refresh_token: refreshToken, ...(await response.json()) });\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 { JSONRPCMessageSchema } from \"../types.js\";\nimport { auth, extractResourceMetadataUrl, 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 */\nexport class SSEClientTransport {\n constructor(url, opts) {\n this._url = url;\n this._resourceMetadataUrl = 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 }\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, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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 return new Headers({ ...headers, ...(_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers });\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 this._resourceMetadataUrl = extractResourceMetadataUrl(response);\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, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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;\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 if (response.status === 401 && this._authProvider) {\n this._resourceMetadataUrl = extractResourceMetadataUrl(response);\n const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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 const text = await response.text().catch(() => null);\n throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);\n }\n }\n catch (error) {\n (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.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 { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessageSchema } from \"../types.js\";\nimport { auth, extractResourceMetadataUrl, 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._url = url;\n this._resourceMetadataUrl = 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._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, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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 = this._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;\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 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 (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.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 // Access default values directly, ensuring they're never undefined\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 _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 * Schedule a reconnection attempt with exponential 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 (maxRetries > 0 && 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 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 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 .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 onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id);\n }\n if (!event.event || event.event === \"message\") {\n try {\n const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));\n if (replayMessageId !== undefined && isJSONRPCResponse(message)) {\n message.id = replayMessageId;\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 }\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 if (isReconnectable &&\n this._abortController &&\n !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, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\n if (result !== \"AUTHORIZED\") {\n throw new UnauthorizedError(\"Failed to authorize\");\n }\n }\n async close() {\n var _a, _b;\n // Abort any pending requests\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;\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 if (response.status === 401 && this._authProvider) {\n this._resourceMetadataUrl = extractResourceMetadataUrl(response);\n const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, fetchFn: this._fetch });\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 const text = await response.text().catch(() => null);\n throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);\n }\n // If the response is 202 Accepted, there's no body to process\n if (response.status === 202) {\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 (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, msg);\n }\n }\n else {\n throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);\n }\n }\n }\n catch (error) {\n (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.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;\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 // 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 (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.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//# 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 a 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],"mappings":";;;;AAAA,IAAM,aAAN,c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