mcp-proxy 5.5.5 → 5.6.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 CHANGED
@@ -1,118 +1,1849 @@
1
- import {
2
- InMemoryEventStore,
3
- proxyServer,
4
- startHTTPServer
5
- } from "./chunk-57ANGSXD.js";
1
+ import { Client, InMemoryEventStore, JSONRPCMessageSchema, LATEST_PROTOCOL_VERSION, ReadBuffer, Server, anyType, arrayType, booleanType, isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, numberType, objectType, proxyServer, serializeMessage, startHTTPServer, stringType } from "./stdio-Cm2W-uxV.js";
2
+ import process from "node:process";
6
3
 
7
- // src/startStdioServer.ts
8
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
9
- import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
10
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
11
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
12
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
- var ServerType = /* @__PURE__ */ ((ServerType2) => {
14
- ServerType2["HTTPStream"] = "HTTPStream";
15
- ServerType2["SSE"] = "SSE";
16
- return ServerType2;
17
- })(ServerType || {});
18
- var startStdioServer = async ({
19
- initStdioServer,
20
- initStreamClient,
21
- serverType,
22
- transportOptions = {},
23
- url
24
- }) => {
25
- let transport;
26
- switch (serverType) {
27
- case "SSE" /* SSE */:
28
- transport = new SSEClientTransport(new URL(url), transportOptions);
29
- break;
30
- default:
31
- transport = new StreamableHTTPClientTransport(
32
- new URL(url),
33
- transportOptions
34
- );
35
- }
36
- const streamClient = initStreamClient ? await initStreamClient() : new Client(
37
- {
38
- name: "mcp-proxy",
39
- version: "1.0.0"
40
- },
41
- {
42
- capabilities: {}
43
- }
44
- );
45
- await streamClient.connect(transport);
46
- const serverVersion = streamClient.getServerVersion();
47
- const serverCapabilities = streamClient.getServerCapabilities();
48
- const stdioServer = initStdioServer ? await initStdioServer() : new Server(serverVersion, {
49
- capabilities: serverCapabilities
50
- });
51
- const stdioTransport = new StdioServerTransport();
52
- await stdioServer.connect(stdioTransport);
53
- await proxyServer({
54
- client: streamClient,
55
- server: stdioServer,
56
- serverCapabilities
57
- });
58
- return stdioServer;
4
+ //#region node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/index.js
5
+ var ParseError = class extends Error {
6
+ constructor(message, options) {
7
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
8
+ }
59
9
  };
10
+ function noop(_arg) {}
11
+ function createParser(callbacks) {
12
+ if (typeof callbacks == "function") throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
13
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
14
+ let incompleteLine = "", isFirstChunk = !0, id, data = "", eventType = "";
15
+ function feed(newChunk) {
16
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
17
+ for (const line of complete) parseLine(line);
18
+ incompleteLine = incomplete, isFirstChunk = !1;
19
+ }
20
+ function parseLine(line) {
21
+ if (line === "") {
22
+ dispatchEvent();
23
+ return;
24
+ }
25
+ if (line.startsWith(":")) {
26
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
27
+ return;
28
+ }
29
+ const fieldSeparatorIndex = line.indexOf(":");
30
+ if (fieldSeparatorIndex !== -1) {
31
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
32
+ processField(field, value, line);
33
+ return;
34
+ }
35
+ processField(line, "", line);
36
+ }
37
+ function processField(field, value, line) {
38
+ switch (field) {
39
+ case "event":
40
+ eventType = value;
41
+ break;
42
+ case "data":
43
+ data = `${data}${value}
44
+ `;
45
+ break;
46
+ case "id":
47
+ id = value.includes("\0") ? void 0 : value;
48
+ break;
49
+ case "retry":
50
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
51
+ type: "invalid-retry",
52
+ value,
53
+ line
54
+ }));
55
+ break;
56
+ default:
57
+ onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, {
58
+ type: "unknown-field",
59
+ field,
60
+ value,
61
+ line
62
+ }));
63
+ break;
64
+ }
65
+ }
66
+ function dispatchEvent() {
67
+ data.length > 0 && onEvent({
68
+ id,
69
+ event: eventType || void 0,
70
+ data: data.endsWith(`
71
+ `) ? data.slice(0, -1) : data
72
+ }), id = void 0, data = "", eventType = "";
73
+ }
74
+ function reset(options = {}) {
75
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = "", eventType = "", incompleteLine = "";
76
+ }
77
+ return {
78
+ feed,
79
+ reset
80
+ };
81
+ }
82
+ function splitLines(chunk) {
83
+ const lines = [];
84
+ let incompleteLine = "", searchIndex = 0;
85
+ for (; searchIndex < chunk.length;) {
86
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
87
+ `, searchIndex);
88
+ let lineEnd = -1;
89
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
90
+ incompleteLine = chunk.slice(searchIndex);
91
+ break;
92
+ } else {
93
+ const line = chunk.slice(searchIndex, lineEnd);
94
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
95
+ ` && searchIndex++;
96
+ }
97
+ }
98
+ return [lines, incompleteLine];
99
+ }
60
100
 
61
- // src/tapTransport.ts
62
- var tapTransport = (transport, eventHandler) => {
63
- const originalClose = transport.close.bind(transport);
64
- const originalOnClose = transport.onclose?.bind(transport);
65
- const originalOnError = transport.onerror?.bind(transport);
66
- const originalOnMessage = transport.onmessage?.bind(transport);
67
- const originalSend = transport.send.bind(transport);
68
- const originalStart = transport.start.bind(transport);
69
- transport.close = async () => {
70
- eventHandler({
71
- type: "close"
72
- });
73
- return originalClose?.();
74
- };
75
- transport.onclose = async () => {
76
- eventHandler({
77
- type: "onclose"
78
- });
79
- return originalOnClose?.();
80
- };
81
- transport.onerror = async (error) => {
82
- eventHandler({
83
- error,
84
- type: "onerror"
85
- });
86
- return originalOnError?.(error);
87
- };
88
- transport.onmessage = async (message) => {
89
- eventHandler({
90
- message,
91
- type: "onmessage"
92
- });
93
- return originalOnMessage?.(message);
94
- };
95
- transport.send = async (message) => {
96
- eventHandler({
97
- message,
98
- type: "send"
99
- });
100
- return originalSend?.(message);
101
- };
102
- transport.start = async () => {
103
- eventHandler({
104
- type: "start"
105
- });
106
- return originalStart?.();
107
- };
108
- return transport;
101
+ //#endregion
102
+ //#region node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js
103
+ var ErrorEvent = class extends Event {
104
+ /**
105
+ * Constructs a new `ErrorEvent` instance. This is typically not called directly,
106
+ * but rather emitted by the `EventSource` object when an error occurs.
107
+ *
108
+ * @param type - The type of the event (should be "error")
109
+ * @param errorEventInitDict - Optional properties to include in the error event
110
+ */
111
+ constructor(type, errorEventInitDict) {
112
+ var _a, _b;
113
+ 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;
114
+ }
115
+ /**
116
+ * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
117
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
118
+ * we explicitly include the properties in the `inspect` method.
119
+ *
120
+ * This is automatically called by Node.js when you `console.log` an instance of this class.
121
+ *
122
+ * @param _depth - The current depth
123
+ * @param options - The options passed to `util.inspect`
124
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
125
+ * @returns A string representation of the error
126
+ */
127
+ [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
128
+ return inspect(inspectableError(this), options);
129
+ }
130
+ /**
131
+ * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
132
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
133
+ * we explicitly include the properties in the `inspect` method.
134
+ *
135
+ * This is automatically called by Deno when you `console.log` an instance of this class.
136
+ *
137
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
138
+ * @param options - The options passed to `Deno.inspect`
139
+ * @returns A string representation of the error
140
+ */
141
+ [Symbol.for("Deno.customInspect")](inspect, options) {
142
+ return inspect(inspectableError(this), options);
143
+ }
109
144
  };
110
- export {
111
- InMemoryEventStore,
112
- ServerType,
113
- proxyServer,
114
- startHTTPServer,
115
- startStdioServer,
116
- tapTransport
145
+ function syntaxError(message) {
146
+ const DomException = globalThis.DOMException;
147
+ return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
148
+ }
149
+ function flattenError(err) {
150
+ 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}`;
151
+ }
152
+ function inspectableError(err) {
153
+ return {
154
+ type: err.type,
155
+ message: err.message,
156
+ code: err.code,
157
+ defaultPrevented: err.defaultPrevented,
158
+ cancelable: err.cancelable,
159
+ timeStamp: err.timeStamp
160
+ };
161
+ }
162
+ var __typeError = (msg) => {
163
+ throw TypeError(msg);
164
+ }, __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;
165
+ var EventSource = class extends EventTarget {
166
+ constructor(url, eventSourceInitDict) {
167
+ var _a, _b;
168
+ 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) => {
169
+ var _a2;
170
+ __privateGet(this, _parser).reset();
171
+ const { body, redirected, status, headers } = response;
172
+ if (status === 204) {
173
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
174
+ return;
175
+ }
176
+ if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
177
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
178
+ return;
179
+ }
180
+ if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
181
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid content type, expected \"text/event-stream\"", status);
182
+ return;
183
+ }
184
+ if (__privateGet(this, _readyState) === this.CLOSED) return;
185
+ __privateSet(this, _readyState, this.OPEN);
186
+ const openEvent = new Event("open");
187
+ if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
188
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
189
+ return;
190
+ }
191
+ const decoder = new TextDecoder(), reader = body.getReader();
192
+ let open = !0;
193
+ do {
194
+ const { done, value } = await reader.read();
195
+ 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));
196
+ } while (open);
197
+ }), __privateAdd(this, _onFetchError, (err) => {
198
+ __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
199
+ }), __privateAdd(this, _onEvent, (event) => {
200
+ typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
201
+ const messageEvent = new MessageEvent(event.event || "message", {
202
+ data: event.data,
203
+ origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
204
+ lastEventId: event.id || ""
205
+ });
206
+ __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
207
+ }), __privateAdd(this, _onRetryChange, (value) => {
208
+ __privateSet(this, _reconnectInterval, value);
209
+ }), __privateAdd(this, _reconnect, () => {
210
+ __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
211
+ });
212
+ try {
213
+ if (url instanceof URL) __privateSet(this, _url, url);
214
+ else if (typeof url == "string") __privateSet(this, _url, new URL(url, getBaseURL()));
215
+ else throw new Error("Invalid URL");
216
+ } catch {
217
+ throw syntaxError("An invalid or illegal string was specified");
218
+ }
219
+ __privateSet(this, _parser, createParser({
220
+ onEvent: __privateGet(this, _onEvent),
221
+ onRetry: __privateGet(this, _onRetryChange)
222
+ })), __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);
223
+ }
224
+ /**
225
+ * Returns the state of this EventSource object's connection. It can have the values described below.
226
+ *
227
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
228
+ *
229
+ * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
230
+ * defined in the TypeScript `dom` library.
231
+ *
232
+ * @public
233
+ */
234
+ get readyState() {
235
+ return __privateGet(this, _readyState);
236
+ }
237
+ /**
238
+ * Returns the URL providing the event stream.
239
+ *
240
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
241
+ *
242
+ * @public
243
+ */
244
+ get url() {
245
+ return __privateGet(this, _url).href;
246
+ }
247
+ /**
248
+ * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
249
+ *
250
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
251
+ */
252
+ get withCredentials() {
253
+ return __privateGet(this, _withCredentials);
254
+ }
255
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
256
+ get onerror() {
257
+ return __privateGet(this, _onError);
258
+ }
259
+ set onerror(value) {
260
+ __privateSet(this, _onError, value);
261
+ }
262
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
263
+ get onmessage() {
264
+ return __privateGet(this, _onMessage);
265
+ }
266
+ set onmessage(value) {
267
+ __privateSet(this, _onMessage, value);
268
+ }
269
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
270
+ get onopen() {
271
+ return __privateGet(this, _onOpen);
272
+ }
273
+ set onopen(value) {
274
+ __privateSet(this, _onOpen, value);
275
+ }
276
+ addEventListener(type, listener, options) {
277
+ const listen = listener;
278
+ super.addEventListener(type, listen, options);
279
+ }
280
+ removeEventListener(type, listener, options) {
281
+ const listen = listener;
282
+ super.removeEventListener(type, listen, options);
283
+ }
284
+ /**
285
+ * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
286
+ *
287
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
288
+ *
289
+ * @public
290
+ */
291
+ close() {
292
+ __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));
293
+ }
117
294
  };
295
+ _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(), connect_fn = function() {
296
+ __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));
297
+ }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), getRequestOptions_fn = function() {
298
+ var _a;
299
+ const init = {
300
+ mode: "cors",
301
+ redirect: "follow",
302
+ headers: {
303
+ Accept: "text/event-stream",
304
+ ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0
305
+ },
306
+ cache: "no-store",
307
+ signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal
308
+ };
309
+ return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
310
+ }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), failConnection_fn = function(message, code) {
311
+ var _a;
312
+ __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
313
+ const errorEvent = new ErrorEvent("error", {
314
+ code,
315
+ message
316
+ });
317
+ (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);
318
+ }, scheduleReconnect_fn = function(message, code) {
319
+ var _a;
320
+ if (__privateGet(this, _readyState) === this.CLOSED) return;
321
+ __privateSet(this, _readyState, this.CONNECTING);
322
+ const errorEvent = new ErrorEvent("error", {
323
+ code,
324
+ message
325
+ });
326
+ (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
327
+ }, _reconnect = /* @__PURE__ */ new WeakMap(), EventSource.CONNECTING = 0, EventSource.OPEN = 1, EventSource.CLOSED = 2;
328
+ function getBaseURL() {
329
+ const doc = "document" in globalThis ? globalThis.document : void 0;
330
+ return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
331
+ }
332
+
333
+ //#endregion
334
+ //#region node_modules/.pnpm/pkce-challenge@5.0.0/node_modules/pkce-challenge/dist/index.node.js
335
+ let crypto;
336
+ crypto = globalThis.crypto?.webcrypto ?? globalThis.crypto ?? import("node:crypto").then((m) => m.webcrypto);
337
+ /**
338
+ * Creates an array of length `size` of random bytes
339
+ * @param size
340
+ * @returns Array of random ints (0 to 255)
341
+ */
342
+ async function getRandomValues(size) {
343
+ return (await crypto).getRandomValues(new Uint8Array(size));
344
+ }
345
+ /** Generate cryptographically strong random string
346
+ * @param size The desired length of the string
347
+ * @returns The random string
348
+ */
349
+ async function random(size) {
350
+ const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
351
+ let result = "";
352
+ const randomUints = await getRandomValues(size);
353
+ for (let i = 0; i < size; i++) {
354
+ const randomIndex = randomUints[i] % 66;
355
+ result += mask[randomIndex];
356
+ }
357
+ return result;
358
+ }
359
+ /** Generate a PKCE challenge verifier
360
+ * @param length Length of the verifier
361
+ * @returns A random verifier `length` characters long
362
+ */
363
+ async function generateVerifier(length) {
364
+ return await random(length);
365
+ }
366
+ /** Generate a PKCE code challenge from a code verifier
367
+ * @param code_verifier
368
+ * @returns The base64 url encoded code challenge
369
+ */
370
+ async function generateChallenge(code_verifier) {
371
+ const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
372
+ return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
373
+ }
374
+ /** Generate a PKCE challenge pair
375
+ * @param length Length of the verifer (between 43-128). Defaults to 43.
376
+ * @returns PKCE challenge pair
377
+ */
378
+ async function pkceChallenge(length) {
379
+ if (!length) length = 43;
380
+ if (length < 43 || length > 128) throw `Expected a length between 43 and 128. Received ${length}.`;
381
+ const verifier = await generateVerifier(length);
382
+ const challenge = await generateChallenge(verifier);
383
+ return {
384
+ code_verifier: verifier,
385
+ code_challenge: challenge
386
+ };
387
+ }
388
+
389
+ //#endregion
390
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
391
+ /**
392
+ * RFC 9728 OAuth Protected Resource Metadata
393
+ */
394
+ const OAuthProtectedResourceMetadataSchema = objectType({
395
+ resource: stringType().url(),
396
+ authorization_servers: arrayType(stringType().url()).optional(),
397
+ jwks_uri: stringType().url().optional(),
398
+ scopes_supported: arrayType(stringType()).optional(),
399
+ bearer_methods_supported: arrayType(stringType()).optional(),
400
+ resource_signing_alg_values_supported: arrayType(stringType()).optional(),
401
+ resource_name: stringType().optional(),
402
+ resource_documentation: stringType().optional(),
403
+ resource_policy_uri: stringType().url().optional(),
404
+ resource_tos_uri: stringType().url().optional(),
405
+ tls_client_certificate_bound_access_tokens: booleanType().optional(),
406
+ authorization_details_types_supported: arrayType(stringType()).optional(),
407
+ dpop_signing_alg_values_supported: arrayType(stringType()).optional(),
408
+ dpop_bound_access_tokens_required: booleanType().optional()
409
+ }).passthrough();
410
+ /**
411
+ * RFC 8414 OAuth 2.0 Authorization Server Metadata
412
+ */
413
+ const OAuthMetadataSchema = objectType({
414
+ issuer: stringType(),
415
+ authorization_endpoint: stringType(),
416
+ token_endpoint: stringType(),
417
+ registration_endpoint: stringType().optional(),
418
+ scopes_supported: arrayType(stringType()).optional(),
419
+ response_types_supported: arrayType(stringType()),
420
+ response_modes_supported: arrayType(stringType()).optional(),
421
+ grant_types_supported: arrayType(stringType()).optional(),
422
+ token_endpoint_auth_methods_supported: arrayType(stringType()).optional(),
423
+ token_endpoint_auth_signing_alg_values_supported: arrayType(stringType()).optional(),
424
+ service_documentation: stringType().optional(),
425
+ revocation_endpoint: stringType().optional(),
426
+ revocation_endpoint_auth_methods_supported: arrayType(stringType()).optional(),
427
+ revocation_endpoint_auth_signing_alg_values_supported: arrayType(stringType()).optional(),
428
+ introspection_endpoint: stringType().optional(),
429
+ introspection_endpoint_auth_methods_supported: arrayType(stringType()).optional(),
430
+ introspection_endpoint_auth_signing_alg_values_supported: arrayType(stringType()).optional(),
431
+ code_challenge_methods_supported: arrayType(stringType()).optional()
432
+ }).passthrough();
433
+ /**
434
+ * OpenID Connect Discovery 1.0 Provider Metadata
435
+ * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
436
+ */
437
+ const OpenIdProviderMetadataSchema = objectType({
438
+ issuer: stringType(),
439
+ authorization_endpoint: stringType(),
440
+ token_endpoint: stringType(),
441
+ userinfo_endpoint: stringType().optional(),
442
+ jwks_uri: stringType(),
443
+ registration_endpoint: stringType().optional(),
444
+ scopes_supported: arrayType(stringType()).optional(),
445
+ response_types_supported: arrayType(stringType()),
446
+ response_modes_supported: arrayType(stringType()).optional(),
447
+ grant_types_supported: arrayType(stringType()).optional(),
448
+ acr_values_supported: arrayType(stringType()).optional(),
449
+ subject_types_supported: arrayType(stringType()),
450
+ id_token_signing_alg_values_supported: arrayType(stringType()),
451
+ id_token_encryption_alg_values_supported: arrayType(stringType()).optional(),
452
+ id_token_encryption_enc_values_supported: arrayType(stringType()).optional(),
453
+ userinfo_signing_alg_values_supported: arrayType(stringType()).optional(),
454
+ userinfo_encryption_alg_values_supported: arrayType(stringType()).optional(),
455
+ userinfo_encryption_enc_values_supported: arrayType(stringType()).optional(),
456
+ request_object_signing_alg_values_supported: arrayType(stringType()).optional(),
457
+ request_object_encryption_alg_values_supported: arrayType(stringType()).optional(),
458
+ request_object_encryption_enc_values_supported: arrayType(stringType()).optional(),
459
+ token_endpoint_auth_methods_supported: arrayType(stringType()).optional(),
460
+ token_endpoint_auth_signing_alg_values_supported: arrayType(stringType()).optional(),
461
+ display_values_supported: arrayType(stringType()).optional(),
462
+ claim_types_supported: arrayType(stringType()).optional(),
463
+ claims_supported: arrayType(stringType()).optional(),
464
+ service_documentation: stringType().optional(),
465
+ claims_locales_supported: arrayType(stringType()).optional(),
466
+ ui_locales_supported: arrayType(stringType()).optional(),
467
+ claims_parameter_supported: booleanType().optional(),
468
+ request_parameter_supported: booleanType().optional(),
469
+ request_uri_parameter_supported: booleanType().optional(),
470
+ require_request_uri_registration: booleanType().optional(),
471
+ op_policy_uri: stringType().optional(),
472
+ op_tos_uri: stringType().optional()
473
+ }).passthrough();
474
+ /**
475
+ * OpenID Connect Discovery metadata that may include OAuth 2.0 fields
476
+ * This schema represents the real-world scenario where OIDC providers
477
+ * return a mix of OpenID Connect and OAuth 2.0 metadata fields
478
+ */
479
+ const OpenIdProviderDiscoveryMetadataSchema = OpenIdProviderMetadataSchema.merge(OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }));
480
+ /**
481
+ * OAuth 2.1 token response
482
+ */
483
+ const OAuthTokensSchema = objectType({
484
+ access_token: stringType(),
485
+ id_token: stringType().optional(),
486
+ token_type: stringType(),
487
+ expires_in: numberType().optional(),
488
+ scope: stringType().optional(),
489
+ refresh_token: stringType().optional()
490
+ }).strip();
491
+ /**
492
+ * OAuth 2.1 error response
493
+ */
494
+ const OAuthErrorResponseSchema = objectType({
495
+ error: stringType(),
496
+ error_description: stringType().optional(),
497
+ error_uri: stringType().optional()
498
+ });
499
+ /**
500
+ * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata
501
+ */
502
+ const OAuthClientMetadataSchema = objectType({
503
+ redirect_uris: arrayType(stringType()).refine((uris) => uris.every((uri) => URL.canParse(uri)), { message: "redirect_uris must contain valid URLs" }),
504
+ token_endpoint_auth_method: stringType().optional(),
505
+ grant_types: arrayType(stringType()).optional(),
506
+ response_types: arrayType(stringType()).optional(),
507
+ client_name: stringType().optional(),
508
+ client_uri: stringType().optional(),
509
+ logo_uri: stringType().optional(),
510
+ scope: stringType().optional(),
511
+ contacts: arrayType(stringType()).optional(),
512
+ tos_uri: stringType().optional(),
513
+ policy_uri: stringType().optional(),
514
+ jwks_uri: stringType().optional(),
515
+ jwks: anyType().optional(),
516
+ software_id: stringType().optional(),
517
+ software_version: stringType().optional(),
518
+ software_statement: stringType().optional()
519
+ }).strip();
520
+ /**
521
+ * RFC 7591 OAuth 2.0 Dynamic Client Registration client information
522
+ */
523
+ const OAuthClientInformationSchema = objectType({
524
+ client_id: stringType(),
525
+ client_secret: stringType().optional(),
526
+ client_id_issued_at: numberType().optional(),
527
+ client_secret_expires_at: numberType().optional()
528
+ }).strip();
529
+ /**
530
+ * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)
531
+ */
532
+ const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
533
+ /**
534
+ * RFC 7591 OAuth 2.0 Dynamic Client Registration error response
535
+ */
536
+ const OAuthClientRegistrationErrorSchema = objectType({
537
+ error: stringType(),
538
+ error_description: stringType().optional()
539
+ }).strip();
540
+ /**
541
+ * RFC 7009 OAuth 2.0 Token Revocation request
542
+ */
543
+ const OAuthTokenRevocationRequestSchema = objectType({
544
+ token: stringType(),
545
+ token_type_hint: stringType().optional()
546
+ }).strip();
547
+
548
+ //#endregion
549
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
550
+ /**
551
+ * Utilities for handling OAuth resource URIs.
552
+ */
553
+ /**
554
+ * Converts a server URL to a resource URL by removing the fragment.
555
+ * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component".
556
+ * Keeps everything else unchanged (scheme, domain, port, path, query).
557
+ */
558
+ function resourceUrlFromServerUrl(url) {
559
+ const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href);
560
+ resourceURL.hash = "";
561
+ return resourceURL;
562
+ }
563
+ /**
564
+ * Checks if a requested resource URL matches a configured resource URL.
565
+ * A requested resource matches if it has the same scheme, domain, port,
566
+ * and its path starts with the configured resource's path.
567
+ *
568
+ * @param requestedResource The resource URL being requested
569
+ * @param configuredResource The resource URL that has been configured
570
+ * @returns true if the requested resource matches the configured resource, false otherwise
571
+ */
572
+ function checkResourceAllowed({ requestedResource, configuredResource }) {
573
+ const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
574
+ const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
575
+ if (requested.origin !== configured.origin) return false;
576
+ if (requested.pathname.length < configured.pathname.length) return false;
577
+ const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
578
+ const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
579
+ return requestedPath.startsWith(configuredPath);
580
+ }
581
+
582
+ //#endregion
583
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
584
+ /**
585
+ * Base class for all OAuth errors
586
+ */
587
+ var OAuthError = class extends Error {
588
+ constructor(message, errorUri) {
589
+ super(message);
590
+ this.errorUri = errorUri;
591
+ this.name = this.constructor.name;
592
+ }
593
+ /**
594
+ * Converts the error to a standard OAuth error response object
595
+ */
596
+ toResponseObject() {
597
+ const response = {
598
+ error: this.errorCode,
599
+ error_description: this.message
600
+ };
601
+ if (this.errorUri) response.error_uri = this.errorUri;
602
+ return response;
603
+ }
604
+ get errorCode() {
605
+ return this.constructor.errorCode;
606
+ }
607
+ };
608
+ /**
609
+ * Invalid request error - The request is missing a required parameter,
610
+ * includes an invalid parameter value, includes a parameter more than once,
611
+ * or is otherwise malformed.
612
+ */
613
+ var InvalidRequestError = class extends OAuthError {};
614
+ InvalidRequestError.errorCode = "invalid_request";
615
+ /**
616
+ * Invalid client error - Client authentication failed (e.g., unknown client, no client
617
+ * authentication included, or unsupported authentication method).
618
+ */
619
+ var InvalidClientError = class extends OAuthError {};
620
+ InvalidClientError.errorCode = "invalid_client";
621
+ /**
622
+ * Invalid grant error - The provided authorization grant or refresh token is
623
+ * invalid, expired, revoked, does not match the redirection URI used in the
624
+ * authorization request, or was issued to another client.
625
+ */
626
+ var InvalidGrantError = class extends OAuthError {};
627
+ InvalidGrantError.errorCode = "invalid_grant";
628
+ /**
629
+ * Unauthorized client error - The authenticated client is not authorized to use
630
+ * this authorization grant type.
631
+ */
632
+ var UnauthorizedClientError = class extends OAuthError {};
633
+ UnauthorizedClientError.errorCode = "unauthorized_client";
634
+ /**
635
+ * Unsupported grant type error - The authorization grant type is not supported
636
+ * by the authorization server.
637
+ */
638
+ var UnsupportedGrantTypeError = class extends OAuthError {};
639
+ UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
640
+ /**
641
+ * Invalid scope error - The requested scope is invalid, unknown, malformed, or
642
+ * exceeds the scope granted by the resource owner.
643
+ */
644
+ var InvalidScopeError = class extends OAuthError {};
645
+ InvalidScopeError.errorCode = "invalid_scope";
646
+ /**
647
+ * Access denied error - The resource owner or authorization server denied the request.
648
+ */
649
+ var AccessDeniedError = class extends OAuthError {};
650
+ AccessDeniedError.errorCode = "access_denied";
651
+ /**
652
+ * Server error - The authorization server encountered an unexpected condition
653
+ * that prevented it from fulfilling the request.
654
+ */
655
+ var ServerError = class extends OAuthError {};
656
+ ServerError.errorCode = "server_error";
657
+ /**
658
+ * Temporarily unavailable error - The authorization server is currently unable to
659
+ * handle the request due to a temporary overloading or maintenance of the server.
660
+ */
661
+ var TemporarilyUnavailableError = class extends OAuthError {};
662
+ TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
663
+ /**
664
+ * Unsupported response type error - The authorization server does not support
665
+ * obtaining an authorization code using this method.
666
+ */
667
+ var UnsupportedResponseTypeError = class extends OAuthError {};
668
+ UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
669
+ /**
670
+ * Unsupported token type error - The authorization server does not support
671
+ * the requested token type.
672
+ */
673
+ var UnsupportedTokenTypeError = class extends OAuthError {};
674
+ UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
675
+ /**
676
+ * Invalid token error - The access token provided is expired, revoked, malformed,
677
+ * or invalid for other reasons.
678
+ */
679
+ var InvalidTokenError = class extends OAuthError {};
680
+ InvalidTokenError.errorCode = "invalid_token";
681
+ /**
682
+ * Method not allowed error - The HTTP method used is not allowed for this endpoint.
683
+ * (Custom, non-standard error)
684
+ */
685
+ var MethodNotAllowedError = class extends OAuthError {};
686
+ MethodNotAllowedError.errorCode = "method_not_allowed";
687
+ /**
688
+ * Too many requests error - Rate limit exceeded.
689
+ * (Custom, non-standard error based on RFC 6585)
690
+ */
691
+ var TooManyRequestsError = class extends OAuthError {};
692
+ TooManyRequestsError.errorCode = "too_many_requests";
693
+ /**
694
+ * Invalid client metadata error - The client metadata is invalid.
695
+ * (Custom error for dynamic client registration - RFC 7591)
696
+ */
697
+ var InvalidClientMetadataError = class extends OAuthError {};
698
+ InvalidClientMetadataError.errorCode = "invalid_client_metadata";
699
+ /**
700
+ * Insufficient scope error - The request requires higher privileges than provided by the access token.
701
+ */
702
+ var InsufficientScopeError = class extends OAuthError {};
703
+ InsufficientScopeError.errorCode = "insufficient_scope";
704
+ /**
705
+ * A full list of all OAuthErrors, enabling parsing from error responses
706
+ */
707
+ const OAUTH_ERRORS = {
708
+ [InvalidRequestError.errorCode]: InvalidRequestError,
709
+ [InvalidClientError.errorCode]: InvalidClientError,
710
+ [InvalidGrantError.errorCode]: InvalidGrantError,
711
+ [UnauthorizedClientError.errorCode]: UnauthorizedClientError,
712
+ [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
713
+ [InvalidScopeError.errorCode]: InvalidScopeError,
714
+ [AccessDeniedError.errorCode]: AccessDeniedError,
715
+ [ServerError.errorCode]: ServerError,
716
+ [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
717
+ [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
718
+ [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
719
+ [InvalidTokenError.errorCode]: InvalidTokenError,
720
+ [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
721
+ [TooManyRequestsError.errorCode]: TooManyRequestsError,
722
+ [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
723
+ [InsufficientScopeError.errorCode]: InsufficientScopeError
724
+ };
725
+
726
+ //#endregion
727
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
728
+ var UnauthorizedError = class extends Error {
729
+ constructor(message) {
730
+ super(message !== null && message !== void 0 ? message : "Unauthorized");
731
+ }
732
+ };
733
+ /**
734
+ * Determines the best client authentication method to use based on server support and client configuration.
735
+ *
736
+ * Priority order (highest to lowest):
737
+ * 1. client_secret_basic (if client secret is available)
738
+ * 2. client_secret_post (if client secret is available)
739
+ * 3. none (for public clients)
740
+ *
741
+ * @param clientInformation - OAuth client information containing credentials
742
+ * @param supportedMethods - Authentication methods supported by the authorization server
743
+ * @returns The selected authentication method
744
+ */
745
+ function selectClientAuthMethod(clientInformation, supportedMethods) {
746
+ const hasClientSecret = clientInformation.client_secret !== void 0;
747
+ if (supportedMethods.length === 0) return hasClientSecret ? "client_secret_post" : "none";
748
+ if (hasClientSecret && supportedMethods.includes("client_secret_basic")) return "client_secret_basic";
749
+ if (hasClientSecret && supportedMethods.includes("client_secret_post")) return "client_secret_post";
750
+ if (supportedMethods.includes("none")) return "none";
751
+ return hasClientSecret ? "client_secret_post" : "none";
752
+ }
753
+ /**
754
+ * Applies client authentication to the request based on the specified method.
755
+ *
756
+ * Implements OAuth 2.1 client authentication methods:
757
+ * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)
758
+ * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)
759
+ * - none: Public client authentication (RFC 6749 Section 2.1)
760
+ *
761
+ * @param method - The authentication method to use
762
+ * @param clientInformation - OAuth client information containing credentials
763
+ * @param headers - HTTP headers object to modify
764
+ * @param params - URL search parameters to modify
765
+ * @throws {Error} When required credentials are missing
766
+ */
767
+ function applyClientAuthentication(method, clientInformation, headers, params) {
768
+ const { client_id, client_secret } = clientInformation;
769
+ switch (method) {
770
+ case "client_secret_basic":
771
+ applyBasicAuth(client_id, client_secret, headers);
772
+ return;
773
+ case "client_secret_post":
774
+ applyPostAuth(client_id, client_secret, params);
775
+ return;
776
+ case "none":
777
+ applyPublicAuth(client_id, params);
778
+ return;
779
+ default: throw new Error(`Unsupported client authentication method: ${method}`);
780
+ }
781
+ }
782
+ /**
783
+ * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)
784
+ */
785
+ function applyBasicAuth(clientId, clientSecret, headers) {
786
+ if (!clientSecret) throw new Error("client_secret_basic authentication requires a client_secret");
787
+ const credentials = btoa(`${clientId}:${clientSecret}`);
788
+ headers.set("Authorization", `Basic ${credentials}`);
789
+ }
790
+ /**
791
+ * Applies POST body authentication (RFC 6749 Section 2.3.1)
792
+ */
793
+ function applyPostAuth(clientId, clientSecret, params) {
794
+ params.set("client_id", clientId);
795
+ if (clientSecret) params.set("client_secret", clientSecret);
796
+ }
797
+ /**
798
+ * Applies public client authentication (RFC 6749 Section 2.1)
799
+ */
800
+ function applyPublicAuth(clientId, params) {
801
+ params.set("client_id", clientId);
802
+ }
803
+ /**
804
+ * Parses an OAuth error response from a string or Response object.
805
+ *
806
+ * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec
807
+ * and an instance of the appropriate OAuthError subclass will be returned.
808
+ * If parsing fails, it falls back to a generic ServerError that includes
809
+ * the response status (if available) and original content.
810
+ *
811
+ * @param input - A Response object or string containing the error response
812
+ * @returns A Promise that resolves to an OAuthError instance
813
+ */
814
+ async function parseErrorResponse(input) {
815
+ const statusCode = input instanceof Response ? input.status : void 0;
816
+ const body = input instanceof Response ? await input.text() : input;
817
+ try {
818
+ const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
819
+ const { error, error_description, error_uri } = result;
820
+ const errorClass = OAUTH_ERRORS[error] || ServerError;
821
+ return new errorClass(error_description || "", error_uri);
822
+ } catch (error) {
823
+ const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
824
+ return new ServerError(errorMessage);
825
+ }
826
+ }
827
+ /**
828
+ * Orchestrates the full auth flow with a server.
829
+ *
830
+ * This can be used as a single entry point for all authorization functionality,
831
+ * instead of linking together the other lower-level functions in this module.
832
+ */
833
+ async function auth(provider, options) {
834
+ var _a, _b;
835
+ try {
836
+ return await authInternal(provider, options);
837
+ } catch (error) {
838
+ if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
839
+ await ((_a = provider.invalidateCredentials) === null || _a === void 0 ? void 0 : _a.call(provider, "all"));
840
+ return await authInternal(provider, options);
841
+ } else if (error instanceof InvalidGrantError) {
842
+ await ((_b = provider.invalidateCredentials) === null || _b === void 0 ? void 0 : _b.call(provider, "tokens"));
843
+ return await authInternal(provider, options);
844
+ }
845
+ throw error;
846
+ }
847
+ }
848
+ async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
849
+ let resourceMetadata;
850
+ let authorizationServerUrl;
851
+ try {
852
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn);
853
+ if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) authorizationServerUrl = resourceMetadata.authorization_servers[0];
854
+ } catch (_a) {}
855
+ /**
856
+ * If we don't get a valid authorization server metadata from protected resource metadata,
857
+ * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server acts as the Authorization server.
858
+ */
859
+ if (!authorizationServerUrl) authorizationServerUrl = serverUrl;
860
+ const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
861
+ const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
862
+ let clientInformation = await Promise.resolve(provider.clientInformation());
863
+ if (!clientInformation) {
864
+ if (authorizationCode !== void 0) throw new Error("Existing OAuth client information is required when exchanging an authorization code");
865
+ if (!provider.saveClientInformation) throw new Error("OAuth client information must be saveable for dynamic registration");
866
+ const fullInformation = await registerClient(authorizationServerUrl, {
867
+ metadata,
868
+ clientMetadata: provider.clientMetadata,
869
+ fetchFn
870
+ });
871
+ await provider.saveClientInformation(fullInformation);
872
+ clientInformation = fullInformation;
873
+ }
874
+ if (authorizationCode !== void 0) {
875
+ const codeVerifier$1 = await provider.codeVerifier();
876
+ const tokens$1 = await exchangeAuthorization(authorizationServerUrl, {
877
+ metadata,
878
+ clientInformation,
879
+ authorizationCode,
880
+ codeVerifier: codeVerifier$1,
881
+ redirectUri: provider.redirectUrl,
882
+ resource,
883
+ addClientAuthentication: provider.addClientAuthentication,
884
+ fetchFn
885
+ });
886
+ await provider.saveTokens(tokens$1);
887
+ return "AUTHORIZED";
888
+ }
889
+ const tokens = await provider.tokens();
890
+ if (tokens === null || tokens === void 0 ? void 0 : tokens.refresh_token) try {
891
+ const newTokens = await refreshAuthorization(authorizationServerUrl, {
892
+ metadata,
893
+ clientInformation,
894
+ refreshToken: tokens.refresh_token,
895
+ resource,
896
+ addClientAuthentication: provider.addClientAuthentication,
897
+ fetchFn
898
+ });
899
+ await provider.saveTokens(newTokens);
900
+ return "AUTHORIZED";
901
+ } catch (error) {
902
+ if (!(error instanceof OAuthError) || error instanceof ServerError) {} else throw error;
903
+ }
904
+ const state = provider.state ? await provider.state() : void 0;
905
+ const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
906
+ metadata,
907
+ clientInformation,
908
+ state,
909
+ redirectUrl: provider.redirectUrl,
910
+ scope: scope || provider.clientMetadata.scope,
911
+ resource
912
+ });
913
+ await provider.saveCodeVerifier(codeVerifier);
914
+ await provider.redirectToAuthorization(authorizationUrl);
915
+ return "REDIRECT";
916
+ }
917
+ async function selectResourceURL(serverUrl, provider, resourceMetadata) {
918
+ const defaultResource = resourceUrlFromServerUrl(serverUrl);
919
+ if (provider.validateResourceURL) return await provider.validateResourceURL(defaultResource, resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.resource);
920
+ if (!resourceMetadata) return void 0;
921
+ if (!checkResourceAllowed({
922
+ requestedResource: defaultResource,
923
+ configuredResource: resourceMetadata.resource
924
+ })) throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
925
+ return new URL(resourceMetadata.resource);
926
+ }
927
+ /**
928
+ * Extract resource_metadata from response header.
929
+ */
930
+ function extractResourceMetadataUrl(res) {
931
+ const authenticateHeader = res.headers.get("WWW-Authenticate");
932
+ if (!authenticateHeader) return void 0;
933
+ const [type, scheme] = authenticateHeader.split(" ");
934
+ if (type.toLowerCase() !== "bearer" || !scheme) return void 0;
935
+ const regex = /resource_metadata="([^"]*)"/;
936
+ const match = regex.exec(authenticateHeader);
937
+ if (!match) return void 0;
938
+ try {
939
+ return new URL(match[1]);
940
+ } catch (_a) {
941
+ return void 0;
942
+ }
943
+ }
944
+ /**
945
+ * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.
946
+ *
947
+ * If the server returns a 404 for the well-known endpoint, this function will
948
+ * return `undefined`. Any other errors will be thrown as exceptions.
949
+ */
950
+ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
951
+ const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
952
+ protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion,
953
+ metadataUrl: opts === null || opts === void 0 ? void 0 : opts.resourceMetadataUrl
954
+ });
955
+ if (!response || response.status === 404) throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
956
+ if (!response.ok) throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
957
+ return OAuthProtectedResourceMetadataSchema.parse(await response.json());
958
+ }
959
+ /**
960
+ * Helper function to handle fetch with CORS retry logic
961
+ */
962
+ async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
963
+ try {
964
+ return await fetchFn(url, { headers });
965
+ } catch (error) {
966
+ if (error instanceof TypeError) if (headers) return fetchWithCorsRetry(url, void 0, fetchFn);
967
+ else return void 0;
968
+ throw error;
969
+ }
970
+ }
971
+ /**
972
+ * Constructs the well-known path for auth-related metadata discovery
973
+ */
974
+ function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
975
+ if (pathname.endsWith("/")) pathname = pathname.slice(0, -1);
976
+ return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
977
+ }
978
+ /**
979
+ * Tries to discover OAuth metadata at a specific URL
980
+ */
981
+ async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
982
+ const headers = { "MCP-Protocol-Version": protocolVersion };
983
+ return await fetchWithCorsRetry(url, headers, fetchFn);
984
+ }
985
+ /**
986
+ * Determines if fallback to root discovery should be attempted
987
+ */
988
+ function shouldAttemptFallback(response, pathname) {
989
+ return !response || response.status === 404 && pathname !== "/";
990
+ }
991
+ /**
992
+ * Generic function for discovering OAuth metadata with fallback support
993
+ */
994
+ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
995
+ var _a, _b;
996
+ const issuer = new URL(serverUrl);
997
+ const protocolVersion = (_a = opts === null || opts === void 0 ? void 0 : opts.protocolVersion) !== null && _a !== void 0 ? _a : LATEST_PROTOCOL_VERSION;
998
+ let url;
999
+ if (opts === null || opts === void 0 ? void 0 : opts.metadataUrl) url = new URL(opts.metadataUrl);
1000
+ else {
1001
+ const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
1002
+ url = new URL(wellKnownPath, (_b = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b !== void 0 ? _b : issuer);
1003
+ url.search = issuer.search;
1004
+ }
1005
+ let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);
1006
+ if (!(opts === null || opts === void 0 ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {
1007
+ const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
1008
+ response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
1009
+ }
1010
+ return response;
1011
+ }
1012
+ /**
1013
+ * Builds a list of discovery URLs to try for authorization server metadata.
1014
+ * URLs are returned in priority order:
1015
+ * 1. OAuth metadata at the given URL
1016
+ * 2. OAuth metadata at root (if URL has path)
1017
+ * 3. OIDC metadata endpoints
1018
+ */
1019
+ function buildDiscoveryUrls(authorizationServerUrl) {
1020
+ const url = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
1021
+ const hasPath = url.pathname !== "/";
1022
+ const urlsToTry = [];
1023
+ if (!hasPath) {
1024
+ urlsToTry.push({
1025
+ url: new URL("/.well-known/oauth-authorization-server", url.origin),
1026
+ type: "oauth"
1027
+ });
1028
+ urlsToTry.push({
1029
+ url: new URL(`/.well-known/openid-configuration`, url.origin),
1030
+ type: "oidc"
1031
+ });
1032
+ return urlsToTry;
1033
+ }
1034
+ let pathname = url.pathname;
1035
+ if (pathname.endsWith("/")) pathname = pathname.slice(0, -1);
1036
+ urlsToTry.push({
1037
+ url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),
1038
+ type: "oauth"
1039
+ });
1040
+ urlsToTry.push({
1041
+ url: new URL("/.well-known/oauth-authorization-server", url.origin),
1042
+ type: "oauth"
1043
+ });
1044
+ urlsToTry.push({
1045
+ url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),
1046
+ type: "oidc"
1047
+ });
1048
+ urlsToTry.push({
1049
+ url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),
1050
+ type: "oidc"
1051
+ });
1052
+ return urlsToTry;
1053
+ }
1054
+ /**
1055
+ * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata
1056
+ * and OpenID Connect Discovery 1.0 specifications.
1057
+ *
1058
+ * This function implements a fallback strategy for authorization server discovery:
1059
+ * 1. Attempts RFC 8414 OAuth metadata discovery first
1060
+ * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery
1061
+ *
1062
+ * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's
1063
+ * protected resource metadata, or the MCP server's URL if the
1064
+ * metadata was not found.
1065
+ * @param options - Configuration options
1066
+ * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch
1067
+ * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION
1068
+ * @returns Promise resolving to authorization server metadata, or undefined if discovery fails
1069
+ */
1070
+ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
1071
+ var _a;
1072
+ const headers = { "MCP-Protocol-Version": protocolVersion };
1073
+ const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
1074
+ for (const { url: endpointUrl, type } of urlsToTry) {
1075
+ const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
1076
+ if (!response)
1077
+ /**
1078
+ * CORS error occurred - don't throw as the endpoint may not allow CORS,
1079
+ * continue trying other possible endpoints
1080
+ */
1081
+ continue;
1082
+ if (!response.ok) {
1083
+ if (response.status >= 400 && response.status < 500) continue;
1084
+ throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
1085
+ }
1086
+ if (type === "oauth") return OAuthMetadataSchema.parse(await response.json());
1087
+ else {
1088
+ const metadata = OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
1089
+ if (!((_a = metadata.code_challenge_methods_supported) === null || _a === void 0 ? void 0 : _a.includes("S256"))) throw new Error(`Incompatible OIDC provider at ${endpointUrl}: does not support S256 code challenge method required by MCP specification`);
1090
+ return metadata;
1091
+ }
1092
+ }
1093
+ return void 0;
1094
+ }
1095
+ /**
1096
+ * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.
1097
+ */
1098
+ async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
1099
+ const responseType = "code";
1100
+ const codeChallengeMethod = "S256";
1101
+ let authorizationUrl;
1102
+ if (metadata) {
1103
+ authorizationUrl = new URL(metadata.authorization_endpoint);
1104
+ if (!metadata.response_types_supported.includes(responseType)) throw new Error(`Incompatible auth server: does not support response type ${responseType}`);
1105
+ if (!metadata.code_challenge_methods_supported || !metadata.code_challenge_methods_supported.includes(codeChallengeMethod)) throw new Error(`Incompatible auth server: does not support code challenge method ${codeChallengeMethod}`);
1106
+ } else authorizationUrl = new URL("/authorize", authorizationServerUrl);
1107
+ const challenge = await pkceChallenge();
1108
+ const codeVerifier = challenge.code_verifier;
1109
+ const codeChallenge = challenge.code_challenge;
1110
+ authorizationUrl.searchParams.set("response_type", responseType);
1111
+ authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
1112
+ authorizationUrl.searchParams.set("code_challenge", codeChallenge);
1113
+ authorizationUrl.searchParams.set("code_challenge_method", codeChallengeMethod);
1114
+ authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
1115
+ if (state) authorizationUrl.searchParams.set("state", state);
1116
+ if (scope) authorizationUrl.searchParams.set("scope", scope);
1117
+ if (scope === null || scope === void 0 ? void 0 : scope.includes("offline_access")) authorizationUrl.searchParams.append("prompt", "consent");
1118
+ if (resource) authorizationUrl.searchParams.set("resource", resource.href);
1119
+ return {
1120
+ authorizationUrl,
1121
+ codeVerifier
1122
+ };
1123
+ }
1124
+ /**
1125
+ * Exchanges an authorization code for an access token with the given server.
1126
+ *
1127
+ * Supports multiple client authentication methods as specified in OAuth 2.1:
1128
+ * - Automatically selects the best authentication method based on server support
1129
+ * - Falls back to appropriate defaults when server metadata is unavailable
1130
+ *
1131
+ * @param authorizationServerUrl - The authorization server's base URL
1132
+ * @param options - Configuration object containing client info, auth code, etc.
1133
+ * @returns Promise resolving to OAuth tokens
1134
+ * @throws {Error} When token exchange fails or authentication is invalid
1135
+ */
1136
+ async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {
1137
+ var _a;
1138
+ const grantType = "authorization_code";
1139
+ const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
1140
+ if ((metadata === null || metadata === void 0 ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);
1141
+ const headers = new Headers({
1142
+ "Content-Type": "application/x-www-form-urlencoded",
1143
+ "Accept": "application/json"
1144
+ });
1145
+ const params = new URLSearchParams({
1146
+ grant_type: grantType,
1147
+ code: authorizationCode,
1148
+ code_verifier: codeVerifier,
1149
+ redirect_uri: String(redirectUri)
1150
+ });
1151
+ if (addClientAuthentication) addClientAuthentication(headers, params, authorizationServerUrl, metadata);
1152
+ else {
1153
+ const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : [];
1154
+ const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
1155
+ applyClientAuthentication(authMethod, clientInformation, headers, params);
1156
+ }
1157
+ if (resource) params.set("resource", resource.href);
1158
+ const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {
1159
+ method: "POST",
1160
+ headers,
1161
+ body: params
1162
+ });
1163
+ if (!response.ok) throw await parseErrorResponse(response);
1164
+ return OAuthTokensSchema.parse(await response.json());
1165
+ }
1166
+ /**
1167
+ * Exchange a refresh token for an updated access token.
1168
+ *
1169
+ * Supports multiple client authentication methods as specified in OAuth 2.1:
1170
+ * - Automatically selects the best authentication method based on server support
1171
+ * - Preserves the original refresh token if a new one is not returned
1172
+ *
1173
+ * @param authorizationServerUrl - The authorization server's base URL
1174
+ * @param options - Configuration object containing client info, refresh token, etc.
1175
+ * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)
1176
+ * @throws {Error} When token refresh fails or authentication is invalid
1177
+ */
1178
+ async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
1179
+ var _a;
1180
+ const grantType = "refresh_token";
1181
+ let tokenUrl;
1182
+ if (metadata) {
1183
+ tokenUrl = new URL(metadata.token_endpoint);
1184
+ if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);
1185
+ } else tokenUrl = new URL("/token", authorizationServerUrl);
1186
+ const headers = new Headers({ "Content-Type": "application/x-www-form-urlencoded" });
1187
+ const params = new URLSearchParams({
1188
+ grant_type: grantType,
1189
+ refresh_token: refreshToken
1190
+ });
1191
+ if (addClientAuthentication) addClientAuthentication(headers, params, authorizationServerUrl, metadata);
1192
+ else {
1193
+ const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : [];
1194
+ const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
1195
+ applyClientAuthentication(authMethod, clientInformation, headers, params);
1196
+ }
1197
+ if (resource) params.set("resource", resource.href);
1198
+ const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {
1199
+ method: "POST",
1200
+ headers,
1201
+ body: params
1202
+ });
1203
+ if (!response.ok) throw await parseErrorResponse(response);
1204
+ return OAuthTokensSchema.parse({
1205
+ refresh_token: refreshToken,
1206
+ ...await response.json()
1207
+ });
1208
+ }
1209
+ /**
1210
+ * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.
1211
+ */
1212
+ async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) {
1213
+ let registrationUrl;
1214
+ if (metadata) {
1215
+ if (!metadata.registration_endpoint) throw new Error("Incompatible auth server: does not support dynamic client registration");
1216
+ registrationUrl = new URL(metadata.registration_endpoint);
1217
+ } else registrationUrl = new URL("/register", authorizationServerUrl);
1218
+ const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(registrationUrl, {
1219
+ method: "POST",
1220
+ headers: { "Content-Type": "application/json" },
1221
+ body: JSON.stringify(clientMetadata)
1222
+ });
1223
+ if (!response.ok) throw await parseErrorResponse(response);
1224
+ return OAuthClientInformationFullSchema.parse(await response.json());
1225
+ }
1226
+
1227
+ //#endregion
1228
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
1229
+ var SseError = class extends Error {
1230
+ constructor(code, message, event) {
1231
+ super(`SSE error: ${message}`);
1232
+ this.code = code;
1233
+ this.event = event;
1234
+ }
1235
+ };
1236
+ /**
1237
+ * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving
1238
+ * messages and make separate POST requests for sending messages.
1239
+ */
1240
+ var SSEClientTransport = class {
1241
+ constructor(url, opts) {
1242
+ this._url = url;
1243
+ this._resourceMetadataUrl = void 0;
1244
+ this._eventSourceInit = opts === null || opts === void 0 ? void 0 : opts.eventSourceInit;
1245
+ this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;
1246
+ this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;
1247
+ this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;
1248
+ }
1249
+ async _authThenStart() {
1250
+ var _a;
1251
+ if (!this._authProvider) throw new UnauthorizedError("No auth provider");
1252
+ let result;
1253
+ try {
1254
+ result = await auth(this._authProvider, {
1255
+ serverUrl: this._url,
1256
+ resourceMetadataUrl: this._resourceMetadataUrl,
1257
+ fetchFn: this._fetch
1258
+ });
1259
+ } catch (error) {
1260
+ (_a = this.onerror) === null || _a === void 0 || _a.call(this, error);
1261
+ throw error;
1262
+ }
1263
+ if (result !== "AUTHORIZED") throw new UnauthorizedError();
1264
+ return await this._startOrAuth();
1265
+ }
1266
+ async _commonHeaders() {
1267
+ var _a;
1268
+ const headers = {};
1269
+ if (this._authProvider) {
1270
+ const tokens = await this._authProvider.tokens();
1271
+ if (tokens) headers["Authorization"] = `Bearer ${tokens.access_token}`;
1272
+ }
1273
+ if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion;
1274
+ return new Headers({
1275
+ ...headers,
1276
+ ...(_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers
1277
+ });
1278
+ }
1279
+ _startOrAuth() {
1280
+ var _a, _b, _c;
1281
+ 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;
1282
+ return new Promise((resolve, reject) => {
1283
+ this._eventSource = new EventSource(this._url.href, {
1284
+ ...this._eventSourceInit,
1285
+ fetch: async (url, init) => {
1286
+ const headers = await this._commonHeaders();
1287
+ headers.set("Accept", "text/event-stream");
1288
+ const response = await fetchImpl(url, {
1289
+ ...init,
1290
+ headers
1291
+ });
1292
+ if (response.status === 401 && response.headers.has("www-authenticate")) this._resourceMetadataUrl = extractResourceMetadataUrl(response);
1293
+ return response;
1294
+ }
1295
+ });
1296
+ this._abortController = new AbortController();
1297
+ this._eventSource.onerror = (event) => {
1298
+ var _a$1;
1299
+ if (event.code === 401 && this._authProvider) {
1300
+ this._authThenStart().then(resolve, reject);
1301
+ return;
1302
+ }
1303
+ const error = new SseError(event.code, event.message, event);
1304
+ reject(error);
1305
+ (_a$1 = this.onerror) === null || _a$1 === void 0 || _a$1.call(this, error);
1306
+ };
1307
+ this._eventSource.onopen = () => {};
1308
+ this._eventSource.addEventListener("endpoint", (event) => {
1309
+ var _a$1;
1310
+ const messageEvent = event;
1311
+ try {
1312
+ this._endpoint = new URL(messageEvent.data, this._url);
1313
+ if (this._endpoint.origin !== this._url.origin) throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
1314
+ } catch (error) {
1315
+ reject(error);
1316
+ (_a$1 = this.onerror) === null || _a$1 === void 0 || _a$1.call(this, error);
1317
+ this.close();
1318
+ return;
1319
+ }
1320
+ resolve();
1321
+ });
1322
+ this._eventSource.onmessage = (event) => {
1323
+ var _a$1, _b$1;
1324
+ const messageEvent = event;
1325
+ let message;
1326
+ try {
1327
+ message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
1328
+ } catch (error) {
1329
+ (_a$1 = this.onerror) === null || _a$1 === void 0 || _a$1.call(this, error);
1330
+ return;
1331
+ }
1332
+ (_b$1 = this.onmessage) === null || _b$1 === void 0 || _b$1.call(this, message);
1333
+ };
1334
+ });
1335
+ }
1336
+ async start() {
1337
+ if (this._eventSource) throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
1338
+ return await this._startOrAuth();
1339
+ }
1340
+ /**
1341
+ * 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.
1342
+ */
1343
+ async finishAuth(authorizationCode) {
1344
+ if (!this._authProvider) throw new UnauthorizedError("No auth provider");
1345
+ const result = await auth(this._authProvider, {
1346
+ serverUrl: this._url,
1347
+ authorizationCode,
1348
+ resourceMetadataUrl: this._resourceMetadataUrl,
1349
+ fetchFn: this._fetch
1350
+ });
1351
+ if (result !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize");
1352
+ }
1353
+ async close() {
1354
+ var _a, _b, _c;
1355
+ (_a = this._abortController) === null || _a === void 0 || _a.abort();
1356
+ (_b = this._eventSource) === null || _b === void 0 || _b.close();
1357
+ (_c = this.onclose) === null || _c === void 0 || _c.call(this);
1358
+ }
1359
+ async send(message) {
1360
+ var _a, _b, _c;
1361
+ if (!this._endpoint) throw new Error("Not connected");
1362
+ try {
1363
+ const headers = await this._commonHeaders();
1364
+ headers.set("content-type", "application/json");
1365
+ const init = {
1366
+ ...this._requestInit,
1367
+ method: "POST",
1368
+ headers,
1369
+ body: JSON.stringify(message),
1370
+ signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal
1371
+ };
1372
+ const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._endpoint, init);
1373
+ if (!response.ok) {
1374
+ if (response.status === 401 && this._authProvider) {
1375
+ this._resourceMetadataUrl = extractResourceMetadataUrl(response);
1376
+ const result = await auth(this._authProvider, {
1377
+ serverUrl: this._url,
1378
+ resourceMetadataUrl: this._resourceMetadataUrl,
1379
+ fetchFn: this._fetch
1380
+ });
1381
+ if (result !== "AUTHORIZED") throw new UnauthorizedError();
1382
+ return this.send(message);
1383
+ }
1384
+ const text = await response.text().catch(() => null);
1385
+ throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
1386
+ }
1387
+ } catch (error) {
1388
+ (_c = this.onerror) === null || _c === void 0 || _c.call(this, error);
1389
+ throw error;
1390
+ }
1391
+ }
1392
+ setProtocolVersion(version) {
1393
+ this._protocolVersion = version;
1394
+ }
1395
+ };
1396
+
1397
+ //#endregion
1398
+ //#region node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/stream.js
1399
+ var EventSourceParserStream = class extends TransformStream {
1400
+ constructor({ onError, onRetry, onComment } = {}) {
1401
+ let parser;
1402
+ super({
1403
+ start(controller) {
1404
+ parser = createParser({
1405
+ onEvent: (event) => {
1406
+ controller.enqueue(event);
1407
+ },
1408
+ onError(error) {
1409
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
1410
+ },
1411
+ onRetry,
1412
+ onComment
1413
+ });
1414
+ },
1415
+ transform(chunk) {
1416
+ parser.feed(chunk);
1417
+ }
1418
+ });
1419
+ }
1420
+ };
1421
+
1422
+ //#endregion
1423
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
1424
+ const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
1425
+ initialReconnectionDelay: 1e3,
1426
+ maxReconnectionDelay: 3e4,
1427
+ reconnectionDelayGrowFactor: 1.5,
1428
+ maxRetries: 2
1429
+ };
1430
+ var StreamableHTTPError = class extends Error {
1431
+ constructor(code, message) {
1432
+ super(`Streamable HTTP error: ${message}`);
1433
+ this.code = code;
1434
+ }
1435
+ };
1436
+ /**
1437
+ * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
1438
+ * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events
1439
+ * for receiving messages.
1440
+ */
1441
+ var StreamableHTTPClientTransport = class {
1442
+ constructor(url, opts) {
1443
+ var _a;
1444
+ this._url = url;
1445
+ this._resourceMetadataUrl = void 0;
1446
+ this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;
1447
+ this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;
1448
+ this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;
1449
+ this._sessionId = opts === null || opts === void 0 ? void 0 : opts.sessionId;
1450
+ this._reconnectionOptions = (_a = opts === null || opts === void 0 ? void 0 : opts.reconnectionOptions) !== null && _a !== void 0 ? _a : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
1451
+ }
1452
+ async _authThenStart() {
1453
+ var _a;
1454
+ if (!this._authProvider) throw new UnauthorizedError("No auth provider");
1455
+ let result;
1456
+ try {
1457
+ result = await auth(this._authProvider, {
1458
+ serverUrl: this._url,
1459
+ resourceMetadataUrl: this._resourceMetadataUrl,
1460
+ fetchFn: this._fetch
1461
+ });
1462
+ } catch (error) {
1463
+ (_a = this.onerror) === null || _a === void 0 || _a.call(this, error);
1464
+ throw error;
1465
+ }
1466
+ if (result !== "AUTHORIZED") throw new UnauthorizedError();
1467
+ return await this._startOrAuthSse({ resumptionToken: void 0 });
1468
+ }
1469
+ async _commonHeaders() {
1470
+ var _a;
1471
+ const headers = {};
1472
+ if (this._authProvider) {
1473
+ const tokens = await this._authProvider.tokens();
1474
+ if (tokens) headers["Authorization"] = `Bearer ${tokens.access_token}`;
1475
+ }
1476
+ if (this._sessionId) headers["mcp-session-id"] = this._sessionId;
1477
+ if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion;
1478
+ const extraHeaders = this._normalizeHeaders((_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers);
1479
+ return new Headers({
1480
+ ...headers,
1481
+ ...extraHeaders
1482
+ });
1483
+ }
1484
+ async _startOrAuthSse(options) {
1485
+ var _a, _b, _c;
1486
+ const { resumptionToken } = options;
1487
+ try {
1488
+ const headers = await this._commonHeaders();
1489
+ headers.set("Accept", "text/event-stream");
1490
+ if (resumptionToken) headers.set("last-event-id", resumptionToken);
1491
+ const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._url, {
1492
+ method: "GET",
1493
+ headers,
1494
+ signal: (_b = this._abortController) === null || _b === void 0 ? void 0 : _b.signal
1495
+ });
1496
+ if (!response.ok) {
1497
+ if (response.status === 401 && this._authProvider) return await this._authThenStart();
1498
+ if (response.status === 405) return;
1499
+ throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
1500
+ }
1501
+ this._handleSseStream(response.body, options, true);
1502
+ } catch (error) {
1503
+ (_c = this.onerror) === null || _c === void 0 || _c.call(this, error);
1504
+ throw error;
1505
+ }
1506
+ }
1507
+ /**
1508
+ * Calculates the next reconnection delay using backoff algorithm
1509
+ *
1510
+ * @param attempt Current reconnection attempt count for the specific stream
1511
+ * @returns Time to wait in milliseconds before next reconnection attempt
1512
+ */
1513
+ _getNextReconnectionDelay(attempt) {
1514
+ const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
1515
+ const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
1516
+ const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
1517
+ return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
1518
+ }
1519
+ _normalizeHeaders(headers) {
1520
+ if (!headers) return {};
1521
+ if (headers instanceof Headers) return Object.fromEntries(headers.entries());
1522
+ if (Array.isArray(headers)) return Object.fromEntries(headers);
1523
+ return { ...headers };
1524
+ }
1525
+ /**
1526
+ * Schedule a reconnection attempt with exponential backoff
1527
+ *
1528
+ * @param lastEventId The ID of the last received event for resumability
1529
+ * @param attemptCount Current reconnection attempt count for this specific stream
1530
+ */
1531
+ _scheduleReconnection(options, attemptCount = 0) {
1532
+ var _a;
1533
+ const maxRetries = this._reconnectionOptions.maxRetries;
1534
+ if (maxRetries > 0 && attemptCount >= maxRetries) {
1535
+ (_a = this.onerror) === null || _a === void 0 || _a.call(this, /* @__PURE__ */ new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
1536
+ return;
1537
+ }
1538
+ const delay = this._getNextReconnectionDelay(attemptCount);
1539
+ setTimeout(() => {
1540
+ this._startOrAuthSse(options).catch((error) => {
1541
+ var _a$1;
1542
+ (_a$1 = this.onerror) === null || _a$1 === void 0 || _a$1.call(this, /* @__PURE__ */ new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
1543
+ this._scheduleReconnection(options, attemptCount + 1);
1544
+ });
1545
+ }, delay);
1546
+ }
1547
+ _handleSseStream(stream, options, isReconnectable) {
1548
+ if (!stream) return;
1549
+ const { onresumptiontoken, replayMessageId } = options;
1550
+ let lastEventId;
1551
+ const processStream = async () => {
1552
+ var _a, _b, _c, _d;
1553
+ try {
1554
+ const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).getReader();
1555
+ while (true) {
1556
+ const { value: event, done } = await reader.read();
1557
+ if (done) break;
1558
+ if (event.id) {
1559
+ lastEventId = event.id;
1560
+ onresumptiontoken === null || onresumptiontoken === void 0 || onresumptiontoken(event.id);
1561
+ }
1562
+ if (!event.event || event.event === "message") try {
1563
+ const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
1564
+ if (replayMessageId !== void 0 && isJSONRPCResponse(message)) message.id = replayMessageId;
1565
+ (_a = this.onmessage) === null || _a === void 0 || _a.call(this, message);
1566
+ } catch (error) {
1567
+ (_b = this.onerror) === null || _b === void 0 || _b.call(this, error);
1568
+ }
1569
+ }
1570
+ } catch (error) {
1571
+ (_c = this.onerror) === null || _c === void 0 || _c.call(this, /* @__PURE__ */ new Error(`SSE stream disconnected: ${error}`));
1572
+ if (isReconnectable && this._abortController && !this._abortController.signal.aborted) try {
1573
+ this._scheduleReconnection({
1574
+ resumptionToken: lastEventId,
1575
+ onresumptiontoken,
1576
+ replayMessageId
1577
+ }, 0);
1578
+ } catch (error$1) {
1579
+ (_d = this.onerror) === null || _d === void 0 || _d.call(this, /* @__PURE__ */ new Error(`Failed to reconnect: ${error$1 instanceof Error ? error$1.message : String(error$1)}`));
1580
+ }
1581
+ }
1582
+ };
1583
+ processStream();
1584
+ }
1585
+ async start() {
1586
+ if (this._abortController) throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
1587
+ this._abortController = new AbortController();
1588
+ }
1589
+ /**
1590
+ * 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.
1591
+ */
1592
+ async finishAuth(authorizationCode) {
1593
+ if (!this._authProvider) throw new UnauthorizedError("No auth provider");
1594
+ const result = await auth(this._authProvider, {
1595
+ serverUrl: this._url,
1596
+ authorizationCode,
1597
+ resourceMetadataUrl: this._resourceMetadataUrl,
1598
+ fetchFn: this._fetch
1599
+ });
1600
+ if (result !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize");
1601
+ }
1602
+ async close() {
1603
+ var _a, _b;
1604
+ (_a = this._abortController) === null || _a === void 0 || _a.abort();
1605
+ (_b = this.onclose) === null || _b === void 0 || _b.call(this);
1606
+ }
1607
+ async send(message, options) {
1608
+ var _a, _b, _c, _d;
1609
+ try {
1610
+ const { resumptionToken, onresumptiontoken } = options || {};
1611
+ if (resumptionToken) {
1612
+ this._startOrAuthSse({
1613
+ resumptionToken,
1614
+ replayMessageId: isJSONRPCRequest(message) ? message.id : void 0
1615
+ }).catch((err) => {
1616
+ var _a$1;
1617
+ return (_a$1 = this.onerror) === null || _a$1 === void 0 ? void 0 : _a$1.call(this, err);
1618
+ });
1619
+ return;
1620
+ }
1621
+ const headers = await this._commonHeaders();
1622
+ headers.set("content-type", "application/json");
1623
+ headers.set("accept", "application/json, text/event-stream");
1624
+ const init = {
1625
+ ...this._requestInit,
1626
+ method: "POST",
1627
+ headers,
1628
+ body: JSON.stringify(message),
1629
+ signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal
1630
+ };
1631
+ const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init);
1632
+ const sessionId = response.headers.get("mcp-session-id");
1633
+ if (sessionId) this._sessionId = sessionId;
1634
+ if (!response.ok) {
1635
+ if (response.status === 401 && this._authProvider) {
1636
+ this._resourceMetadataUrl = extractResourceMetadataUrl(response);
1637
+ const result = await auth(this._authProvider, {
1638
+ serverUrl: this._url,
1639
+ resourceMetadataUrl: this._resourceMetadataUrl,
1640
+ fetchFn: this._fetch
1641
+ });
1642
+ if (result !== "AUTHORIZED") throw new UnauthorizedError();
1643
+ return this.send(message);
1644
+ }
1645
+ const text = await response.text().catch(() => null);
1646
+ throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
1647
+ }
1648
+ if (response.status === 202) {
1649
+ if (isInitializedNotification(message)) this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => {
1650
+ var _a$1;
1651
+ return (_a$1 = this.onerror) === null || _a$1 === void 0 ? void 0 : _a$1.call(this, err);
1652
+ });
1653
+ return;
1654
+ }
1655
+ const messages = Array.isArray(message) ? message : [message];
1656
+ const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
1657
+ const contentType = response.headers.get("content-type");
1658
+ if (hasRequests) if (contentType === null || contentType === void 0 ? void 0 : contentType.includes("text/event-stream")) this._handleSseStream(response.body, { onresumptiontoken }, false);
1659
+ else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes("application/json")) {
1660
+ const data = await response.json();
1661
+ const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
1662
+ for (const msg of responseMessages) (_c = this.onmessage) === null || _c === void 0 || _c.call(this, msg);
1663
+ } else throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
1664
+ } catch (error) {
1665
+ (_d = this.onerror) === null || _d === void 0 || _d.call(this, error);
1666
+ throw error;
1667
+ }
1668
+ }
1669
+ get sessionId() {
1670
+ return this._sessionId;
1671
+ }
1672
+ /**
1673
+ * Terminates the current session by sending a DELETE request to the server.
1674
+ *
1675
+ * Clients that no longer need a particular session
1676
+ * (e.g., because the user is leaving the client application) SHOULD send an
1677
+ * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
1678
+ * terminate the session.
1679
+ *
1680
+ * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
1681
+ * the server does not allow clients to terminate sessions.
1682
+ */
1683
+ async terminateSession() {
1684
+ var _a, _b, _c;
1685
+ if (!this._sessionId) return;
1686
+ try {
1687
+ const headers = await this._commonHeaders();
1688
+ const init = {
1689
+ ...this._requestInit,
1690
+ method: "DELETE",
1691
+ headers,
1692
+ signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal
1693
+ };
1694
+ const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init);
1695
+ if (!response.ok && response.status !== 405) throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
1696
+ this._sessionId = void 0;
1697
+ } catch (error) {
1698
+ (_c = this.onerror) === null || _c === void 0 || _c.call(this, error);
1699
+ throw error;
1700
+ }
1701
+ }
1702
+ setProtocolVersion(version) {
1703
+ this._protocolVersion = version;
1704
+ }
1705
+ get protocolVersion() {
1706
+ return this._protocolVersion;
1707
+ }
1708
+ };
1709
+
1710
+ //#endregion
1711
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.17.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
1712
+ /**
1713
+ * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout.
1714
+ *
1715
+ * This transport is only available in Node.js environments.
1716
+ */
1717
+ var StdioServerTransport = class {
1718
+ constructor(_stdin = process.stdin, _stdout = process.stdout) {
1719
+ this._stdin = _stdin;
1720
+ this._stdout = _stdout;
1721
+ this._readBuffer = new ReadBuffer();
1722
+ this._started = false;
1723
+ this._ondata = (chunk) => {
1724
+ this._readBuffer.append(chunk);
1725
+ this.processReadBuffer();
1726
+ };
1727
+ this._onerror = (error) => {
1728
+ var _a;
1729
+ (_a = this.onerror) === null || _a === void 0 || _a.call(this, error);
1730
+ };
1731
+ }
1732
+ /**
1733
+ * Starts listening for messages on stdin.
1734
+ */
1735
+ async start() {
1736
+ if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
1737
+ this._started = true;
1738
+ this._stdin.on("data", this._ondata);
1739
+ this._stdin.on("error", this._onerror);
1740
+ }
1741
+ processReadBuffer() {
1742
+ var _a, _b;
1743
+ while (true) try {
1744
+ const message = this._readBuffer.readMessage();
1745
+ if (message === null) break;
1746
+ (_a = this.onmessage) === null || _a === void 0 || _a.call(this, message);
1747
+ } catch (error) {
1748
+ (_b = this.onerror) === null || _b === void 0 || _b.call(this, error);
1749
+ }
1750
+ }
1751
+ async close() {
1752
+ var _a;
1753
+ this._stdin.off("data", this._ondata);
1754
+ this._stdin.off("error", this._onerror);
1755
+ const remainingDataListeners = this._stdin.listenerCount("data");
1756
+ if (remainingDataListeners === 0) this._stdin.pause();
1757
+ this._readBuffer.clear();
1758
+ (_a = this.onclose) === null || _a === void 0 || _a.call(this);
1759
+ }
1760
+ send(message) {
1761
+ return new Promise((resolve) => {
1762
+ const json = serializeMessage(message);
1763
+ if (this._stdout.write(json)) resolve();
1764
+ else this._stdout.once("drain", resolve);
1765
+ });
1766
+ }
1767
+ };
1768
+
1769
+ //#endregion
1770
+ //#region src/startStdioServer.ts
1771
+ let ServerType = /* @__PURE__ */ function(ServerType$1) {
1772
+ ServerType$1["HTTPStream"] = "HTTPStream";
1773
+ ServerType$1["SSE"] = "SSE";
1774
+ return ServerType$1;
1775
+ }({});
1776
+ const startStdioServer = async ({ initStdioServer, initStreamClient, serverType, transportOptions = {}, url }) => {
1777
+ let transport;
1778
+ switch (serverType) {
1779
+ case ServerType.SSE:
1780
+ transport = new SSEClientTransport(new URL(url), transportOptions);
1781
+ break;
1782
+ default: transport = new StreamableHTTPClientTransport(new URL(url), transportOptions);
1783
+ }
1784
+ const streamClient = initStreamClient ? await initStreamClient() : new Client({
1785
+ name: "mcp-proxy",
1786
+ version: "1.0.0"
1787
+ }, { capabilities: {} });
1788
+ await streamClient.connect(transport);
1789
+ const serverVersion = streamClient.getServerVersion();
1790
+ const serverCapabilities = streamClient.getServerCapabilities();
1791
+ const stdioServer = initStdioServer ? await initStdioServer() : new Server(serverVersion, { capabilities: serverCapabilities });
1792
+ const stdioTransport = new StdioServerTransport();
1793
+ await stdioServer.connect(stdioTransport);
1794
+ await proxyServer({
1795
+ client: streamClient,
1796
+ server: stdioServer,
1797
+ serverCapabilities
1798
+ });
1799
+ return stdioServer;
1800
+ };
1801
+
1802
+ //#endregion
1803
+ //#region src/tapTransport.ts
1804
+ const tapTransport = (transport, eventHandler) => {
1805
+ const originalClose = transport.close.bind(transport);
1806
+ const originalOnClose = transport.onclose?.bind(transport);
1807
+ const originalOnError = transport.onerror?.bind(transport);
1808
+ const originalOnMessage = transport.onmessage?.bind(transport);
1809
+ const originalSend = transport.send.bind(transport);
1810
+ const originalStart = transport.start.bind(transport);
1811
+ transport.close = async () => {
1812
+ eventHandler({ type: "close" });
1813
+ return originalClose?.();
1814
+ };
1815
+ transport.onclose = async () => {
1816
+ eventHandler({ type: "onclose" });
1817
+ return originalOnClose?.();
1818
+ };
1819
+ transport.onerror = async (error) => {
1820
+ eventHandler({
1821
+ error,
1822
+ type: "onerror"
1823
+ });
1824
+ return originalOnError?.(error);
1825
+ };
1826
+ transport.onmessage = async (message) => {
1827
+ eventHandler({
1828
+ message,
1829
+ type: "onmessage"
1830
+ });
1831
+ return originalOnMessage?.(message);
1832
+ };
1833
+ transport.send = async (message) => {
1834
+ eventHandler({
1835
+ message,
1836
+ type: "send"
1837
+ });
1838
+ return originalSend?.(message);
1839
+ };
1840
+ transport.start = async () => {
1841
+ eventHandler({ type: "start" });
1842
+ return originalStart?.();
1843
+ };
1844
+ return transport;
1845
+ };
1846
+
1847
+ //#endregion
1848
+ export { InMemoryEventStore, ServerType, proxyServer, startHTTPServer, startStdioServer, tapTransport };
118
1849
  //# sourceMappingURL=index.js.map