@mcp-use/client 0.0.0-bootstrap.0 → 2.0.0-beta.1

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.
Files changed (121) hide show
  1. package/README.md +127 -4
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/auth/browser.d.ts +149 -0
  4. package/dist/auth/browser.d.ts.map +1 -0
  5. package/dist/auth/callback.d.ts +9 -0
  6. package/dist/auth/callback.d.ts.map +1 -0
  7. package/dist/auth/flow.d.ts +23 -0
  8. package/dist/auth/flow.d.ts.map +1 -0
  9. package/dist/auth/node.d.ts +100 -0
  10. package/dist/auth/node.d.ts.map +1 -0
  11. package/dist/auth/popup.d.ts +67 -0
  12. package/dist/auth/popup.d.ts.map +1 -0
  13. package/dist/auth/session-store.d.ts +114 -0
  14. package/dist/auth/session-store.d.ts.map +1 -0
  15. package/dist/auth/storage-file.d.ts +18 -0
  16. package/dist/auth/storage-file.d.ts.map +1 -0
  17. package/dist/auth/storage.d.ts +25 -0
  18. package/dist/auth/storage.d.ts.map +1 -0
  19. package/dist/auth/url.d.ts +17 -0
  20. package/dist/auth/url.d.ts.map +1 -0
  21. package/dist/code-mode/connector.d.ts +27 -0
  22. package/dist/code-mode/connector.d.ts.map +1 -0
  23. package/dist/code-mode/executor-e2b.d.ts +46 -0
  24. package/dist/code-mode/executor-e2b.d.ts.map +1 -0
  25. package/dist/code-mode/executor-vm.d.ts +39 -0
  26. package/dist/code-mode/executor-vm.d.ts.map +1 -0
  27. package/dist/code-mode/executor.d.ts +66 -0
  28. package/dist/code-mode/executor.d.ts.map +1 -0
  29. package/dist/core/base.d.ts +418 -0
  30. package/dist/core/base.d.ts.map +1 -0
  31. package/dist/core/browser.d.ts +20 -0
  32. package/dist/core/browser.d.ts.map +1 -0
  33. package/dist/core/config.d.ts +149 -0
  34. package/dist/core/config.d.ts.map +1 -0
  35. package/dist/core/node.d.ts +441 -0
  36. package/dist/core/node.d.ts.map +1 -0
  37. package/dist/core/session.d.ts +683 -0
  38. package/dist/core/session.d.ts.map +1 -0
  39. package/dist/index-browser.d.ts +25 -0
  40. package/dist/index-browser.d.ts.map +1 -0
  41. package/dist/index-browser.js +4150 -0
  42. package/dist/index-browser.js.map +1 -0
  43. package/dist/index.d.ts +23 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +5598 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/react/McpClientProvider.d.ts +242 -0
  48. package/dist/react/McpClientProvider.d.ts.map +1 -0
  49. package/dist/react/index.d.ts +33 -0
  50. package/dist/react/index.d.ts.map +1 -0
  51. package/dist/react/index.js +7936 -0
  52. package/dist/react/index.js.map +1 -0
  53. package/dist/react/rpc-logger.d.ts +42 -0
  54. package/dist/react/rpc-logger.d.ts.map +1 -0
  55. package/dist/react/storage.d.ts +51 -0
  56. package/dist/react/storage.d.ts.map +1 -0
  57. package/dist/react/types.d.ts +596 -0
  58. package/dist/react/types.d.ts.map +1 -0
  59. package/dist/react/useMcp-helpers.d.ts +99 -0
  60. package/dist/react/useMcp-helpers.d.ts.map +1 -0
  61. package/dist/react/useMcp-operations.d.ts +156 -0
  62. package/dist/react/useMcp-operations.d.ts.map +1 -0
  63. package/dist/react/useMcp.d.ts +48 -0
  64. package/dist/react/useMcp.d.ts.map +1 -0
  65. package/dist/react/useMcpServerQueues.d.ts +376 -0
  66. package/dist/react/useMcpServerQueues.d.ts.map +1 -0
  67. package/dist/react/view/ViewRenderer.d.ts +12 -0
  68. package/dist/react/view/ViewRenderer.d.ts.map +1 -0
  69. package/dist/react/view/ext-apps-bridge.d.ts +3 -0
  70. package/dist/react/view/ext-apps-bridge.d.ts.map +1 -0
  71. package/dist/react/view/parse-custom-props.d.ts +2 -0
  72. package/dist/react/view/parse-custom-props.d.ts.map +1 -0
  73. package/dist/react/view/resolve-view-resource.d.ts +12 -0
  74. package/dist/react/view/resolve-view-resource.d.ts.map +1 -0
  75. package/dist/react/view/sandbox-blob-url.d.ts +25 -0
  76. package/dist/react/view/sandbox-blob-url.d.ts.map +1 -0
  77. package/dist/react/view/types.d.ts +97 -0
  78. package/dist/react/view/types.d.ts.map +1 -0
  79. package/dist/react/view/use-display-mode.d.ts +18 -0
  80. package/dist/react/view/use-display-mode.d.ts.map +1 -0
  81. package/dist/react/view/view-detection.d.ts +4 -0
  82. package/dist/react/view/view-detection.d.ts.map +1 -0
  83. package/dist/telemetry/client-telemetry.d.ts +13 -0
  84. package/dist/telemetry/client-telemetry.d.ts.map +1 -0
  85. package/dist/telemetry/configure-browser.d.ts +2 -0
  86. package/dist/telemetry/configure-browser.d.ts.map +1 -0
  87. package/dist/telemetry/configure-node.d.ts +2 -0
  88. package/dist/telemetry/configure-node.d.ts.map +1 -0
  89. package/dist/telemetry/connector-telemetry.d.ts +8 -0
  90. package/dist/telemetry/connector-telemetry.d.ts.map +1 -0
  91. package/dist/telemetry/events.d.ts +91 -0
  92. package/dist/telemetry/events.d.ts.map +1 -0
  93. package/dist/telemetry/index.d.ts +3 -0
  94. package/dist/telemetry/index.d.ts.map +1 -0
  95. package/dist/telemetry/tel-fetch.d.ts +25 -0
  96. package/dist/telemetry/tel-fetch.d.ts.map +1 -0
  97. package/dist/telemetry/telemetry-browser.d.ts +6 -0
  98. package/dist/telemetry/telemetry-browser.d.ts.map +1 -0
  99. package/dist/telemetry/telemetry-node.d.ts +8 -0
  100. package/dist/telemetry/telemetry-node.d.ts.map +1 -0
  101. package/dist/telemetry/telemetry.d.ts +79 -0
  102. package/dist/telemetry/telemetry.d.ts.map +1 -0
  103. package/dist/transport/base.d.ts +505 -0
  104. package/dist/transport/base.d.ts.map +1 -0
  105. package/dist/transport/connection-manager.d.ts +55 -0
  106. package/dist/transport/connection-manager.d.ts.map +1 -0
  107. package/dist/transport/http.d.ts +74 -0
  108. package/dist/transport/http.d.ts.map +1 -0
  109. package/dist/transport/stdio.d.ts +48 -0
  110. package/dist/transport/stdio.d.ts.map +1 -0
  111. package/dist/utils/elicitation.d.ts +52 -0
  112. package/dist/utils/elicitation.d.ts.map +1 -0
  113. package/dist/utils/favicon.d.ts +6 -0
  114. package/dist/utils/favicon.d.ts.map +1 -0
  115. package/dist/utils/json-schema-validator.d.ts +13 -0
  116. package/dist/utils/json-schema-validator.d.ts.map +1 -0
  117. package/dist/utils/logging.d.ts +32 -0
  118. package/dist/utils/logging.d.ts.map +1 -0
  119. package/dist/utils/version.d.ts +3 -0
  120. package/dist/utils/version.d.ts.map +1 -0
  121. package/package.json +77 -8
@@ -0,0 +1,4150 @@
1
+ // src/telemetry/client-telemetry.ts
2
+ var tracker;
3
+ function setClientTelemetryTracker(nextTracker) {
4
+ tracker = nextTracker;
5
+ }
6
+ function trackClientAddServer(name, config) {
7
+ void tracker?.addServer(name, config);
8
+ }
9
+ function trackClientRemoveServer(name) {
10
+ void tracker?.removeServer(name);
11
+ }
12
+
13
+ // src/telemetry/connector-telemetry.ts
14
+ var tracker2;
15
+ function setConnectorTelemetryTracker(nextTracker) {
16
+ tracker2 = nextTracker;
17
+ }
18
+ function trackConnectorTelemetry(data) {
19
+ void tracker2?.(data);
20
+ }
21
+
22
+ // src/utils/logging.ts
23
+ var LEVELS = [
24
+ "silent",
25
+ "error",
26
+ "warn",
27
+ "info",
28
+ "http",
29
+ "verbose",
30
+ "debug",
31
+ "silly"
32
+ ];
33
+ var EMOJI = {
34
+ silent: "",
35
+ error: "\u274C",
36
+ warn: "\u26A0\uFE0F",
37
+ info: "\u2139\uFE0F",
38
+ http: "\u{1F310}",
39
+ verbose: "\u{1F4DD}",
40
+ debug: "\u{1F50D}",
41
+ silly: "\u{1F92A}"
42
+ };
43
+ function envLevel() {
44
+ let raw;
45
+ try {
46
+ raw = typeof process !== "undefined" ? process.env?.MCP_USE_LOG_LEVEL ?? process.env?.DEBUG : void 0;
47
+ } catch {
48
+ }
49
+ const v = raw?.trim().toLowerCase();
50
+ if (v === "2") return "debug";
51
+ if (v && LEVELS.includes(v)) return v;
52
+ return "info";
53
+ }
54
+ var SimpleConsoleLogger = class {
55
+ constructor(name = "mcp-use", level = "info", format = "minimal") {
56
+ this.name = name;
57
+ this.level = level;
58
+ this.format = format;
59
+ }
60
+ write(level, message, args) {
61
+ if (this.level === "silent" || LEVELS.indexOf(level) > LEVELS.indexOf(this.level)) {
62
+ return;
63
+ }
64
+ const extra = args.map((a) => {
65
+ if (typeof a === "string") return a;
66
+ try {
67
+ return JSON.stringify(a);
68
+ } catch {
69
+ return String(a);
70
+ }
71
+ }).join(" ");
72
+ const full = extra ? `${message} ${extra}` : message;
73
+ const ts = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
74
+ const label = this.format === "minimal" ? level : level.toUpperCase();
75
+ const emoji = this.format === "emoji" ? ` ${EMOJI[level]}` : "";
76
+ const line = `${ts} [${this.name}]${emoji} ${label}: ${full}`;
77
+ const fn = level === "error" ? console.error : level === "warn" ? console.warn : level === "info" ? console.info : level === "debug" ? console.debug : console.log;
78
+ fn(line);
79
+ }
80
+ error = (m, ...a) => this.write("error", m, a);
81
+ warn = (m, ...a) => this.write("warn", m, a);
82
+ info = (m, ...a) => this.write("info", m, a);
83
+ debug = (m, ...a) => this.write("debug", m, a);
84
+ http = (m, ...a) => this.write("http", m, a);
85
+ verbose = (m, ...a) => this.write("verbose", m, a);
86
+ silly = (m, ...a) => this.write("silly", m, a);
87
+ setFormat(format) {
88
+ this.format = format;
89
+ }
90
+ };
91
+ var Logger = class {
92
+ static instances = {};
93
+ static currentFormat = "minimal";
94
+ static currentLevel;
95
+ static get(name = "mcp-use") {
96
+ return this.instances[name] ??= new SimpleConsoleLogger(
97
+ name,
98
+ this.currentLevel ?? envLevel(),
99
+ this.currentFormat
100
+ );
101
+ }
102
+ static configure({
103
+ level = envLevel(),
104
+ format = "minimal"
105
+ } = {}) {
106
+ this.currentLevel = level;
107
+ this.currentFormat = format;
108
+ for (const log of Object.values(this.instances)) {
109
+ log.level = level;
110
+ log.format = format;
111
+ }
112
+ }
113
+ static setDebug(enabled) {
114
+ const level = enabled === 2 || enabled === true ? "debug" : "info";
115
+ this.currentLevel = level;
116
+ for (const log of Object.values(this.instances)) log.level = level;
117
+ try {
118
+ if (typeof process !== "undefined" && process.env) {
119
+ process.env.MCP_USE_LOG_LEVEL = level;
120
+ }
121
+ } catch {
122
+ }
123
+ }
124
+ static setFormat(format) {
125
+ this.configure({ format });
126
+ }
127
+ };
128
+ var logger = Logger.get();
129
+
130
+ // src/utils/version.ts
131
+ var VERSION = "2.0.0-beta.0";
132
+ function getPackageVersion() {
133
+ return VERSION;
134
+ }
135
+
136
+ // src/telemetry/events.ts
137
+ var BaseTelemetryEvent = class {
138
+ };
139
+ var MCPAgentExecutionEvent = class extends BaseTelemetryEvent {
140
+ constructor(data) {
141
+ super();
142
+ this.data = data;
143
+ }
144
+ get name() {
145
+ return "mcp_agent_execution";
146
+ }
147
+ get properties() {
148
+ return {
149
+ // Core execution info
150
+ execution_method: this.data.executionMethod,
151
+ query: this.data.query,
152
+ query_length: this.data.query.length,
153
+ success: this.data.success,
154
+ // Agent configuration
155
+ model_provider: this.data.modelProvider,
156
+ model_name: this.data.modelName,
157
+ server_count: this.data.serverCount,
158
+ server_identifiers: this.data.serverIdentifiers,
159
+ total_tools_available: this.data.totalToolsAvailable,
160
+ tools_available_names: this.data.toolsAvailableNames,
161
+ max_steps_configured: this.data.maxStepsConfigured,
162
+ memory_enabled: this.data.memoryEnabled,
163
+ use_server_manager: this.data.useServerManager,
164
+ // Execution parameters (always include, even if null)
165
+ max_steps_used: this.data.maxStepsUsed,
166
+ manage_connector: this.data.manageConnector,
167
+ external_history_used: this.data.externalHistoryUsed,
168
+ // Execution results (always include, even if null)
169
+ steps_taken: this.data.stepsTaken ?? null,
170
+ tools_used_count: this.data.toolsUsedCount ?? null,
171
+ tools_used_names: this.data.toolsUsedNames ?? null,
172
+ response: this.data.response ?? null,
173
+ response_length: this.data.response ? this.data.response.length : null,
174
+ execution_time_ms: this.data.executionTimeMs ?? null,
175
+ error_type: this.data.errorType ?? null,
176
+ conversation_history_length: this.data.conversationHistoryLength ?? null
177
+ };
178
+ }
179
+ };
180
+ var MCPClientInitEvent = class extends BaseTelemetryEvent {
181
+ constructor(data) {
182
+ super();
183
+ this.data = data;
184
+ }
185
+ get name() {
186
+ return "mcpclient_init";
187
+ }
188
+ get properties() {
189
+ return {
190
+ code_mode: this.data.codeMode,
191
+ sandbox: this.data.sandbox,
192
+ all_callbacks: this.data.allCallbacks,
193
+ verify: this.data.verify,
194
+ servers: this.data.servers,
195
+ num_servers: this.data.numServers,
196
+ is_browser: this.data.isBrowser
197
+ };
198
+ }
199
+ };
200
+ var ConnectorInitEvent = class extends BaseTelemetryEvent {
201
+ constructor(data) {
202
+ super();
203
+ this.data = data;
204
+ }
205
+ get name() {
206
+ return "connector_init";
207
+ }
208
+ get properties() {
209
+ return {
210
+ connector_type: this.data.connectorType,
211
+ server_command: this.data.serverCommand ?? null,
212
+ server_args: this.data.serverArgs ?? null,
213
+ server_url: this.data.serverUrl ?? null,
214
+ public_identifier: this.data.publicIdentifier ?? null
215
+ };
216
+ }
217
+ };
218
+ var ClientAddServerEvent = class extends BaseTelemetryEvent {
219
+ constructor(data) {
220
+ super();
221
+ this.data = data;
222
+ }
223
+ get name() {
224
+ return "client_add_server";
225
+ }
226
+ get properties() {
227
+ const { serverName, serverConfig } = this.data;
228
+ const url = serverConfig.url;
229
+ return {
230
+ server_name: serverName,
231
+ server_url_domain: url ? this._extractHostname(url) : null,
232
+ transport: serverConfig.transport ?? null,
233
+ has_auth: !!(serverConfig.authToken || serverConfig.authProvider)
234
+ };
235
+ }
236
+ _extractHostname(url) {
237
+ try {
238
+ return new URL(url).hostname;
239
+ } catch {
240
+ return null;
241
+ }
242
+ }
243
+ };
244
+ var ClientRemoveServerEvent = class extends BaseTelemetryEvent {
245
+ constructor(data) {
246
+ super();
247
+ this.data = data;
248
+ }
249
+ get name() {
250
+ return "client_remove_server";
251
+ }
252
+ get properties() {
253
+ return {
254
+ server_name: this.data.serverName
255
+ };
256
+ }
257
+ };
258
+
259
+ // src/telemetry/tel-fetch.ts
260
+ async function telFetch(url, init) {
261
+ try {
262
+ await fetch(url, init);
263
+ } catch {
264
+ }
265
+ }
266
+ var POSTHOG_HOST = "https://eu.i.posthog.com";
267
+ var POSTHOG_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
268
+ var SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
269
+ var SCARF_GATEWAY_BEACON_URL = "https://mcpuse.gateway.scarf.sh/simple/";
270
+ var SCARF_BEACON_MAX_URL = 1800;
271
+ var SCARF_BEACON_TRUNCATED_KEYS = /* @__PURE__ */ new Set(["query", "response", "messages"]);
272
+ function stringifyScarfValue(value) {
273
+ if (value === null || value === void 0) return "";
274
+ if (typeof value === "string") return value;
275
+ if (typeof value === "number" || typeof value === "boolean") {
276
+ return String(value);
277
+ }
278
+ try {
279
+ return JSON.stringify(value);
280
+ } catch {
281
+ return String(value);
282
+ }
283
+ }
284
+ function buildScarfBeaconUrl(properties, baseUrl = SCARF_GATEWAY_BEACON_URL) {
285
+ const params = new URLSearchParams();
286
+ for (const [key, value] of Object.entries(properties)) {
287
+ let serialized = stringifyScarfValue(value);
288
+ if (SCARF_BEACON_TRUNCATED_KEYS.has(key) && serialized.length > 120) {
289
+ serialized = `${serialized.slice(0, 117)}...`;
290
+ }
291
+ if (serialized !== "") params.set(key, serialized);
292
+ }
293
+ let url = `${baseUrl}${baseUrl.includes("?") ? "&" : "?"}${params.toString()}`;
294
+ if (url.length <= SCARF_BEACON_MAX_URL) return url;
295
+ const keys = [...params.keys()].sort(
296
+ (a, b) => (params.get(b)?.length ?? 0) - (params.get(a)?.length ?? 0)
297
+ );
298
+ for (const key of keys) {
299
+ if (url.length <= SCARF_BEACON_MAX_URL) break;
300
+ if (key === "event" || key === "user_id") continue;
301
+ params.delete(key);
302
+ url = `${baseUrl}${baseUrl.includes("?") ? "&" : "?"}${params.toString()}`;
303
+ }
304
+ return url.slice(0, SCARF_BEACON_MAX_URL);
305
+ }
306
+ function captureScarfPost(properties, endpoint) {
307
+ return telFetch(endpoint, {
308
+ method: "POST",
309
+ headers: { "Content-Type": "application/json" },
310
+ keepalive: true,
311
+ body: JSON.stringify(properties)
312
+ });
313
+ }
314
+ function captureScarfBeacon(properties, endpoint) {
315
+ try {
316
+ const url = buildScarfBeaconUrl(properties, endpoint);
317
+ const img = new Image();
318
+ img.referrerPolicy = "no-referrer-when-downgrade";
319
+ img.src = url;
320
+ } catch {
321
+ }
322
+ return Promise.resolve();
323
+ }
324
+ function capturePostHog(params) {
325
+ const host = params.host ?? POSTHOG_HOST;
326
+ const apiKey = params.apiKey ?? POSTHOG_API_KEY;
327
+ return telFetch(`${host}/i/v0/e/`, {
328
+ method: "POST",
329
+ headers: { "Content-Type": "application/json" },
330
+ keepalive: true,
331
+ body: JSON.stringify({
332
+ api_key: apiKey,
333
+ event: params.event,
334
+ distinct_id: params.distinctId,
335
+ properties: params.properties,
336
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
337
+ })
338
+ });
339
+ }
340
+ function captureScarf(properties, endpoint = SCARF_GATEWAY_URL) {
341
+ if (typeof window !== "undefined") {
342
+ const beaconEndpoint = endpoint === SCARF_GATEWAY_URL ? SCARF_GATEWAY_BEACON_URL : endpoint;
343
+ return captureScarfBeacon(properties, beaconEndpoint);
344
+ }
345
+ return captureScarfPost(properties, endpoint);
346
+ }
347
+
348
+ // src/telemetry/telemetry.ts
349
+ function generateUUID() {
350
+ return globalThis.crypto.randomUUID();
351
+ }
352
+ function secureRandomString() {
353
+ const array = new Uint8Array(8);
354
+ globalThis.crypto.getRandomValues(array);
355
+ return Array.from(array, (v) => v.toString(16).padStart(2, "0")).join("");
356
+ }
357
+ function isVersionGreater(a, b) {
358
+ const parse = (v) => v.split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
359
+ const pa = parse(a);
360
+ const pb = parse(b);
361
+ const len = Math.max(pa.length, pb.length);
362
+ for (let i = 0; i < len; i++) {
363
+ const da = pa[i] ?? 0;
364
+ const db = pb[i] ?? 0;
365
+ if (da !== db) return da > db;
366
+ }
367
+ return false;
368
+ }
369
+ var USER_ID_STORAGE_KEY = "mcp_use_user_id";
370
+ var PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
371
+ var HOST = "https://eu.i.posthog.com";
372
+ var configuredStorage = null;
373
+ function isLocalStorageFunctional() {
374
+ return typeof localStorage !== "undefined" && typeof localStorage.getItem === "function" && typeof localStorage.setItem === "function" && typeof localStorage.removeItem === "function";
375
+ }
376
+ function createLocalStorageBackend() {
377
+ if (!isLocalStorageFunctional()) return null;
378
+ try {
379
+ localStorage.setItem("__mcp_use_test__", "1");
380
+ localStorage.removeItem("__mcp_use_test__");
381
+ } catch {
382
+ return null;
383
+ }
384
+ return {
385
+ getUserId() {
386
+ try {
387
+ return localStorage.getItem(USER_ID_STORAGE_KEY);
388
+ } catch {
389
+ return null;
390
+ }
391
+ },
392
+ setUserId(id) {
393
+ try {
394
+ localStorage.setItem(USER_ID_STORAGE_KEY, id);
395
+ } catch {
396
+ }
397
+ },
398
+ // Package-download dedup is node/Scarf-oriented; localStorage unused.
399
+ getDownloadedVersion: () => null,
400
+ setDownloadedVersion: () => void 0
401
+ };
402
+ }
403
+ function detectRuntimeEnvironment() {
404
+ try {
405
+ if (typeof globalThis.Bun !== "undefined") {
406
+ return "bun";
407
+ }
408
+ if (typeof globalThis.Deno !== "undefined") {
409
+ return "deno";
410
+ }
411
+ if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
412
+ return "cloudflare-workers";
413
+ }
414
+ if (typeof globalThis.EdgeRuntime !== "undefined") {
415
+ return "edge";
416
+ }
417
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
418
+ return "browser";
419
+ }
420
+ if (typeof process !== "undefined" && typeof process.versions?.node !== "undefined") {
421
+ return "node";
422
+ }
423
+ return "unknown";
424
+ } catch {
425
+ return "unknown";
426
+ }
427
+ }
428
+ function readSourceHint() {
429
+ if (typeof process !== "undefined" && process.env?.MCP_USE_TELEMETRY_SOURCE) {
430
+ return process.env.MCP_USE_TELEMETRY_SOURCE;
431
+ }
432
+ try {
433
+ if (isLocalStorageFunctional()) {
434
+ return localStorage.getItem("MCP_USE_TELEMETRY_SOURCE") ?? void 0;
435
+ }
436
+ } catch {
437
+ }
438
+ return void 0;
439
+ }
440
+ function isTelemetryDisabled() {
441
+ if (typeof window !== "undefined" && window.__MCP_USE_ANONYMIZED_TELEMETRY__ === false) {
442
+ return true;
443
+ }
444
+ if (typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false") {
445
+ return true;
446
+ }
447
+ try {
448
+ if (isLocalStorageFunctional() && localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY") === "false") {
449
+ return true;
450
+ }
451
+ } catch {
452
+ }
453
+ return false;
454
+ }
455
+ function sessionId() {
456
+ try {
457
+ return `session-${generateUUID()}`;
458
+ } catch {
459
+ return `session-${Date.now()}-${secureRandomString()}`;
460
+ }
461
+ }
462
+ var Telemetry = class _Telemetry {
463
+ static instance = null;
464
+ UNKNOWN_USER_ID = "UNKNOWN_USER_ID";
465
+ _currUserId = null;
466
+ _telemetryEnabled = false;
467
+ _pending = /* @__PURE__ */ new Set();
468
+ _scarfEnabled = false;
469
+ _runtimeEnvironment;
470
+ _storageCapability;
471
+ _storage;
472
+ /** True when node entry installed fs storage (package-download dedup). */
473
+ _fsBacked;
474
+ _source;
475
+ _productVersion;
476
+ constructor() {
477
+ this._runtimeEnvironment = detectRuntimeEnvironment();
478
+ this._fsBacked = configuredStorage !== null;
479
+ this._storage = configuredStorage ?? createLocalStorageBackend() ?? null;
480
+ this._storageCapability = this._storage ? "persistent" : "session-only";
481
+ this._source = readSourceHint() || this._runtimeEnvironment;
482
+ const disabled = isTelemetryDisabled();
483
+ const canSupport = this._runtimeEnvironment !== "unknown";
484
+ if (disabled) {
485
+ this._telemetryEnabled = false;
486
+ logger.debug("Telemetry disabled via opt-out");
487
+ } else if (!canSupport) {
488
+ this._telemetryEnabled = false;
489
+ logger.debug(
490
+ `Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`
491
+ );
492
+ } else {
493
+ logger.debug(
494
+ "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
495
+ );
496
+ this._telemetryEnabled = true;
497
+ this._scarfEnabled = true;
498
+ if (this._fsBacked) {
499
+ setTimeout(() => {
500
+ this.trackPackageDownload({ triggered_by: "initialization" }).catch(
501
+ (e) => logger.debug(`Failed to track package download: ${e}`)
502
+ );
503
+ }, 0);
504
+ }
505
+ }
506
+ }
507
+ get runtimeEnvironment() {
508
+ return this._runtimeEnvironment;
509
+ }
510
+ get storageCapability() {
511
+ return this._storageCapability;
512
+ }
513
+ static getInstance() {
514
+ if (!_Telemetry.instance) {
515
+ _Telemetry.instance = new _Telemetry();
516
+ }
517
+ return _Telemetry.instance;
518
+ }
519
+ setSource(source) {
520
+ this._source = source;
521
+ try {
522
+ if (isLocalStorageFunctional()) {
523
+ localStorage.setItem("MCP_USE_TELEMETRY_SOURCE", source);
524
+ }
525
+ } catch {
526
+ }
527
+ logger.debug(`Telemetry source set to: ${source}`);
528
+ }
529
+ getSource() {
530
+ return this._source;
531
+ }
532
+ setProductVersion(version) {
533
+ this._productVersion = version;
534
+ }
535
+ get isEnabled() {
536
+ return this._telemetryEnabled || this._scarfEnabled;
537
+ }
538
+ get userId() {
539
+ if (this._currUserId) return this._currUserId;
540
+ try {
541
+ if (this._storage) {
542
+ const existing = this._storage.getUserId();
543
+ if (existing) {
544
+ this._currUserId = existing;
545
+ return existing;
546
+ }
547
+ const id = generateUUID();
548
+ this._storage.setUserId(id);
549
+ this._currUserId = id;
550
+ return id;
551
+ }
552
+ this._currUserId = sessionId();
553
+ } catch {
554
+ this._currUserId = this.UNKNOWN_USER_ID;
555
+ }
556
+ return this._currUserId;
557
+ }
558
+ async capture(event) {
559
+ if (!this._telemetryEnabled && !this._scarfEnabled) return;
560
+ const currentUserId = this.userId;
561
+ const properties = {
562
+ ...event.properties,
563
+ mcp_use_version: this._productVersion ?? getPackageVersion(),
564
+ language: "typescript",
565
+ source: this._source,
566
+ runtime: this._runtimeEnvironment
567
+ };
568
+ if (this._telemetryEnabled) {
569
+ const p = capturePostHog({
570
+ host: HOST,
571
+ apiKey: PROJECT_API_KEY,
572
+ event: event.name,
573
+ distinctId: currentUserId,
574
+ properties
575
+ });
576
+ this._pending.add(p);
577
+ void p.finally(() => this._pending.delete(p));
578
+ }
579
+ if (this._scarfEnabled) {
580
+ const p = captureScarf({
581
+ ...properties,
582
+ user_id: currentUserId,
583
+ event: event.name
584
+ });
585
+ this._pending.add(p);
586
+ void p.finally(() => this._pending.delete(p));
587
+ }
588
+ }
589
+ async trackPackageDownload(properties) {
590
+ if (!this._scarfEnabled || !this._fsBacked || !this._storage) return;
591
+ const currentVersion = getPackageVersion();
592
+ const saved = this._storage.getDownloadedVersion();
593
+ let firstDownload = false;
594
+ let shouldTrack = false;
595
+ if (!saved) {
596
+ shouldTrack = true;
597
+ firstDownload = true;
598
+ this._storage.setDownloadedVersion(currentVersion);
599
+ } else if (isVersionGreater(currentVersion, saved)) {
600
+ shouldTrack = true;
601
+ this._storage.setDownloadedVersion(currentVersion);
602
+ }
603
+ if (!shouldTrack) return;
604
+ await captureScarf({
605
+ ...properties || {},
606
+ mcp_use_version: currentVersion,
607
+ user_id: this.userId,
608
+ event: "package_download",
609
+ first_download: firstDownload,
610
+ language: "typescript",
611
+ source: this._source,
612
+ runtime: this._runtimeEnvironment
613
+ });
614
+ }
615
+ async trackAgentExecution(data) {
616
+ if (!this.isEnabled) return;
617
+ await this.capture(new MCPAgentExecutionEvent(data));
618
+ }
619
+ async trackMCPClientInit(data) {
620
+ if (!this.isEnabled) return;
621
+ await this.capture(new MCPClientInitEvent(data));
622
+ }
623
+ async trackConnectorInit(data) {
624
+ if (!this.isEnabled) return;
625
+ await this.capture(new ConnectorInitEvent(data));
626
+ }
627
+ async trackClientAddServer(serverName, serverConfig) {
628
+ if (!this.isEnabled) return;
629
+ await this.capture(new ClientAddServerEvent({ serverName, serverConfig }));
630
+ }
631
+ async trackClientRemoveServer(serverName) {
632
+ if (!this.isEnabled) return;
633
+ await this.capture(new ClientRemoveServerEvent({ serverName }));
634
+ }
635
+ async trackUseMcpConnection(data) {
636
+ if (!this.isEnabled) return;
637
+ await this.capture({
638
+ name: "usemcp_connection",
639
+ properties: {
640
+ url_domain: new URL(data.url).hostname,
641
+ transport_type: data.transportType,
642
+ success: data.success,
643
+ error_type: data.errorType ?? null,
644
+ connection_time_ms: data.connectionTimeMs ?? null,
645
+ has_oauth: data.hasOAuth,
646
+ has_sampling: data.hasSampling,
647
+ has_elicitation: data.hasElicitation
648
+ }
649
+ });
650
+ }
651
+ async trackUseMcpToolCall(data) {
652
+ if (!this.isEnabled) return;
653
+ await this.capture({
654
+ name: "usemcp_tool_call",
655
+ properties: {
656
+ tool_name: data.toolName,
657
+ success: data.success,
658
+ error_type: data.errorType ?? null,
659
+ execution_time_ms: data.executionTimeMs ?? null
660
+ }
661
+ });
662
+ }
663
+ async trackUseMcpResourceRead(data) {
664
+ if (!this.isEnabled) return;
665
+ await this.capture({
666
+ name: "usemcp_resource_read",
667
+ properties: {
668
+ resource_uri_scheme: data.resourceUri.split(":")[0],
669
+ success: data.success,
670
+ error_type: data.errorType ?? null
671
+ }
672
+ });
673
+ }
674
+ identify(userId, properties) {
675
+ this._currUserId = userId;
676
+ this._storage?.setUserId(userId);
677
+ if (this._telemetryEnabled) {
678
+ void capturePostHog({
679
+ host: HOST,
680
+ apiKey: PROJECT_API_KEY,
681
+ event: "$identify",
682
+ distinctId: userId,
683
+ properties: { $set: properties ?? {} }
684
+ });
685
+ }
686
+ }
687
+ reset() {
688
+ this._currUserId = null;
689
+ }
690
+ flush() {
691
+ void Promise.allSettled([...this._pending]);
692
+ }
693
+ async shutdown() {
694
+ try {
695
+ await Promise.allSettled([...this._pending]);
696
+ logger.debug("Telemetry fetch captures flushed");
697
+ } catch (e) {
698
+ logger.debug(`Error flushing telemetry captures: ${e}`);
699
+ }
700
+ }
701
+ };
702
+ var Tel = Telemetry;
703
+ function setTelemetrySource(source) {
704
+ Tel.getInstance().setSource(source);
705
+ }
706
+ function setProductVersion(version) {
707
+ Tel.getInstance().setProductVersion(version);
708
+ }
709
+
710
+ // src/telemetry/configure-browser.ts
711
+ setClientTelemetryTracker({
712
+ addServer: (name, config) => Telemetry.getInstance().trackClientAddServer(name, config).catch(() => void 0),
713
+ removeServer: (name) => Telemetry.getInstance().trackClientRemoveServer(name).catch(() => void 0)
714
+ });
715
+ setConnectorTelemetryTracker(
716
+ (data) => Telemetry.getInstance().trackConnectorInit(data).catch(() => void 0)
717
+ );
718
+
719
+ // src/auth/url.ts
720
+ function sanitizeUrl(raw) {
721
+ const abort = () => {
722
+ throw new Error(`Invalid url to pass to open(): ${raw}`);
723
+ };
724
+ let url;
725
+ try {
726
+ url = new URL(raw);
727
+ } catch (_) {
728
+ abort();
729
+ }
730
+ if (url.protocol !== "https:" && url.protocol !== "http:") abort();
731
+ if (url.hostname !== encodeURIComponent(url.hostname)) abort();
732
+ if (url.username) url.username = encodeURIComponent(url.username);
733
+ if (url.password) url.password = encodeURIComponent(url.password);
734
+ url.pathname = url.pathname.slice(0, 1) + encodeURIComponent(url.pathname.slice(1)).replace(/%2f/gi, "/");
735
+ url.search = url.search.slice(0, 1) + Array.from(url.searchParams.entries()).map(sanitizeParam).join("&");
736
+ url.hash = url.hash.slice(0, 1) + encodeURIComponent(url.hash.slice(1));
737
+ return url.href;
738
+ }
739
+ function sanitizeParam([k, v]) {
740
+ return `${encodeURIComponent(k)}${v.length > 0 ? `=${encodeURIComponent(v)}` : ""}`;
741
+ }
742
+
743
+ // src/auth/storage.ts
744
+ var LocalStorageKVStore = class {
745
+ get(key) {
746
+ return localStorage.getItem(key);
747
+ }
748
+ set(key, value) {
749
+ localStorage.setItem(key, value);
750
+ }
751
+ remove(key) {
752
+ localStorage.removeItem(key);
753
+ }
754
+ keys() {
755
+ const out = [];
756
+ for (let i = 0; i < localStorage.length; i++) {
757
+ const k = localStorage.key(i);
758
+ if (k) out.push(k);
759
+ }
760
+ return out;
761
+ }
762
+ };
763
+
764
+ // src/auth/session-store.ts
765
+ import { validateClientMetadataUrl } from "@modelcontextprotocol/client";
766
+ var OAuthSessionStore = class _OAuthSessionStore {
767
+ serverUrl;
768
+ storageKeyPrefix;
769
+ serverUrlHash;
770
+ clientName;
771
+ clientUri;
772
+ logoUri;
773
+ callbackUrl;
774
+ clientMetadataUrl;
775
+ scope;
776
+ store;
777
+ allowClientSecret;
778
+ constructor(serverUrl, options, store) {
779
+ validateClientMetadataUrl(options.clientMetadataUrl);
780
+ this.serverUrl = serverUrl;
781
+ this.storageKeyPrefix = options.storageKeyPrefix || "mcp:auth";
782
+ this.serverUrlHash = _OAuthSessionStore.hashString(serverUrl);
783
+ this.clientName = options.clientName || "mcp-use";
784
+ this.clientUri = options.clientUri || (typeof window !== "undefined" ? window.location.origin : "https://mcp-use.com");
785
+ this.logoUri = options.logoUri || "https://mcp-use.com/logo.png";
786
+ this.callbackUrl = sanitizeUrl(
787
+ options.callbackUrl || (typeof window !== "undefined" ? new URL("/oauth/callback", window.location.origin).toString() : "/oauth/callback")
788
+ );
789
+ this.clientMetadataUrl = options.clientMetadataUrl;
790
+ this.scope = options.scope;
791
+ this.store = store;
792
+ this.allowClientSecret = options.allowClientSecret ?? true;
793
+ }
794
+ getKey(keySuffix) {
795
+ return `${this.storageKeyPrefix}_${this.serverUrlHash}_${keySuffix}`;
796
+ }
797
+ static hashString(str) {
798
+ let hash = 0;
799
+ for (let i = 0; i < str.length; i++) {
800
+ const char = str.charCodeAt(i);
801
+ hash = (hash << 5) - hash + char;
802
+ hash = hash & hash;
803
+ }
804
+ return Math.abs(hash).toString(16);
805
+ }
806
+ // --- SDK Interface Methods (delegated) ---
807
+ get redirectUrl() {
808
+ return this.callbackUrl;
809
+ }
810
+ get clientMetadata() {
811
+ return {
812
+ redirect_uris: [this.redirectUrl],
813
+ token_endpoint_auth_method: "none",
814
+ grant_types: ["authorization_code", "refresh_token"],
815
+ response_types: ["code"],
816
+ client_name: this.clientName,
817
+ client_uri: this.clientUri,
818
+ logo_uri: this.logoUri,
819
+ ...this.scope ? { scope: this.scope } : {}
820
+ };
821
+ }
822
+ credentialKey(kind, ctx) {
823
+ return ctx ? this.getKey(`${kind}_${encodeURIComponent(ctx.issuer)}`) : this.getKey(kind);
824
+ }
825
+ async readCredential(kind, ctx) {
826
+ const key = this.credentialKey(kind, ctx);
827
+ const data = await this.store.get(key);
828
+ if (!data && ctx) {
829
+ const legacyKey = this.credentialKey(kind);
830
+ const legacyData = await this.store.get(legacyKey);
831
+ if (legacyData) {
832
+ try {
833
+ const legacyValue = JSON.parse(legacyData);
834
+ if (!legacyValue.issuer || legacyValue.issuer === ctx.issuer) {
835
+ const migratedValue = {
836
+ ...legacyValue,
837
+ issuer: ctx.issuer
838
+ };
839
+ const migratedData = JSON.stringify(migratedValue);
840
+ await this.store.set(key, migratedData);
841
+ await this.store.set(legacyKey, migratedData);
842
+ return { key, value: migratedValue };
843
+ }
844
+ } catch {
845
+ await this.store.remove(legacyKey);
846
+ }
847
+ }
848
+ return void 0;
849
+ }
850
+ if (!data) return void 0;
851
+ try {
852
+ return { key, value: JSON.parse(data) };
853
+ } catch (e) {
854
+ console.warn(
855
+ `[${this.storageKeyPrefix}] Failed to parse ${kind.replace("_", " ")}:`,
856
+ e
857
+ );
858
+ await this.store.remove(key);
859
+ return void 0;
860
+ }
861
+ }
862
+ async tokens(ctx) {
863
+ return (await this.readCredential("tokens", ctx))?.value;
864
+ }
865
+ async saveTokens(tokens, ctx) {
866
+ const serialized = JSON.stringify(tokens);
867
+ await this.store.set(this.credentialKey("tokens", ctx), serialized);
868
+ if (ctx) await this.store.set(this.credentialKey("tokens"), serialized);
869
+ await this.store.remove(this.getKey("code_verifier"));
870
+ await this.store.remove(this.getKey("last_auth_url"));
871
+ }
872
+ async clientInformation(ctx) {
873
+ const stored = await this.readCredential("client_info", ctx);
874
+ if (!stored) return void 0;
875
+ const { key, value: clientInfo } = stored;
876
+ try {
877
+ if (!this.allowClientSecret && clientInfo.client_secret) {
878
+ await this.store.remove(key);
879
+ if (ctx) await this.store.remove(this.credentialKey("client_info"));
880
+ console.warn(
881
+ `[${this.storageKeyPrefix}] Removed OAuth client information containing a browser client_secret.`
882
+ );
883
+ return void 0;
884
+ }
885
+ const storedRedirectUris = Array.isArray(clientInfo.redirect_uris) ? clientInfo.redirect_uris : [];
886
+ const hasMatchingRedirect = storedRedirectUris.length === 0 || storedRedirectUris.includes(this.redirectUrl);
887
+ if (!hasMatchingRedirect) {
888
+ console.info(
889
+ `[${this.storageKeyPrefix}] Invalidating cached OAuth client info due to redirect URI mismatch.`
890
+ );
891
+ await this.store.remove(key);
892
+ await this.store.remove(this.credentialKey("tokens", ctx));
893
+ await this.store.remove(this.getKey("last_auth_url"));
894
+ return void 0;
895
+ }
896
+ return clientInfo;
897
+ } catch {
898
+ await this.store.remove(key);
899
+ return void 0;
900
+ }
901
+ }
902
+ async saveClientInformation(clientInformation, ctx) {
903
+ const info = clientInformation;
904
+ if (!this.allowClientSecret && info.client_secret) {
905
+ await this.store.remove(this.credentialKey("client_info", ctx));
906
+ if (ctx) await this.store.remove(this.credentialKey("client_info"));
907
+ throw new Error(
908
+ "Browser OAuth clients must be public clients; client_secret persistence is not allowed."
909
+ );
910
+ }
911
+ const serialized = JSON.stringify(clientInformation);
912
+ await this.store.set(this.credentialKey("client_info", ctx), serialized);
913
+ if (ctx) {
914
+ await this.store.set(this.credentialKey("client_info"), serialized);
915
+ }
916
+ }
917
+ async saveCodeVerifier(codeVerifier) {
918
+ await this.store.set(this.getKey("code_verifier"), codeVerifier);
919
+ }
920
+ async codeVerifier() {
921
+ const key = this.getKey("code_verifier");
922
+ const verifier = await this.store.get(key);
923
+ if (!verifier) {
924
+ throw new Error(
925
+ `[${this.storageKeyPrefix}] Code verifier not found in storage for key ${key}. Auth flow likely corrupted or timed out.`
926
+ );
927
+ }
928
+ return verifier;
929
+ }
930
+ async invalidateCredentials(scope) {
931
+ const removeCredentialKeys = async (kind) => {
932
+ const prefix = `${this.getKey(kind)}_`;
933
+ for (const key of await this.store.keys()) {
934
+ if (key === this.getKey(kind) || key.startsWith(prefix)) {
935
+ await this.store.remove(key);
936
+ }
937
+ }
938
+ };
939
+ switch (scope) {
940
+ case "all":
941
+ await removeCredentialKeys("tokens");
942
+ await removeCredentialKeys("client_info");
943
+ await this.store.remove(this.getKey("code_verifier"));
944
+ await this.store.remove(this.getKey("last_auth_url"));
945
+ await this.store.remove(this.getKey("discovery_state"));
946
+ await this.store.remove(this.getKey("token_endpoint"));
947
+ break;
948
+ case "client":
949
+ await removeCredentialKeys("client_info");
950
+ break;
951
+ case "tokens":
952
+ await removeCredentialKeys("tokens");
953
+ break;
954
+ case "verifier":
955
+ await this.store.remove(this.getKey("code_verifier"));
956
+ break;
957
+ case "discovery":
958
+ await this.store.remove(this.getKey("discovery_state"));
959
+ break;
960
+ default:
961
+ break;
962
+ }
963
+ }
964
+ /**
965
+ * Persist the OAuth discovery state (authorization-server metadata resolved
966
+ * during the auth flow). Stored with the same durability as the code
967
+ * verifier so the callback leg can verify it is exchanging the code at the
968
+ * same authorization server the redirect targeted (SEP-2352 mix-up defense).
969
+ */
970
+ async saveDiscoveryState(state) {
971
+ await this.store.set(this.getKey("discovery_state"), JSON.stringify(state));
972
+ }
973
+ /** Return the previously saved discovery state, or `undefined`. */
974
+ async discoveryState() {
975
+ const data = await this.store.get(this.getKey("discovery_state"));
976
+ if (!data) return void 0;
977
+ try {
978
+ return JSON.parse(data);
979
+ } catch {
980
+ await this.store.remove(this.getKey("discovery_state"));
981
+ return void 0;
982
+ }
983
+ }
984
+ // --- Helper / non-SDK methods ---
985
+ /**
986
+ * Generates and persists `StoredState` for an authorization request,
987
+ * appends the `state` query param to the URL, and persists the sanitized
988
+ * URL to `last_auth_url` so it can be replayed on popup-blocker fallback.
989
+ *
990
+ * @returns The sanitized authorization URL string with the `state` param appended.
991
+ */
992
+ async storeAuthorizationState(authorizationUrl, opts = {}) {
993
+ const state = globalThis.crypto.randomUUID();
994
+ const stateKey = `${this.storageKeyPrefix}:state_${state}`;
995
+ const stateData = {
996
+ serverUrlHash: this.serverUrlHash,
997
+ expiry: Date.now() + 1e3 * 60 * 10,
998
+ // State expires in 10 minutes
999
+ providerOptions: {
1000
+ serverUrl: this.serverUrl,
1001
+ storageKeyPrefix: this.storageKeyPrefix,
1002
+ clientName: this.clientName,
1003
+ clientUri: this.clientUri,
1004
+ callbackUrl: this.callbackUrl,
1005
+ ...this.clientMetadataUrl ? { clientMetadataUrl: this.clientMetadataUrl } : {},
1006
+ ...opts.extraProviderOptions ?? {}
1007
+ },
1008
+ flowType: opts.flowType,
1009
+ returnUrl: opts.returnUrl
1010
+ };
1011
+ authorizationUrl.searchParams.set("state", state);
1012
+ const sanitizedAuthUrl = sanitizeUrl(authorizationUrl.toString());
1013
+ await this.store.set(stateKey, JSON.stringify(stateData));
1014
+ await this.store.set(this.getKey("last_auth_url"), sanitizedAuthUrl);
1015
+ return sanitizedAuthUrl;
1016
+ }
1017
+ /**
1018
+ * Return the token endpoint from SDK-managed discovery state. The SDK
1019
+ * persists this state during `auth()`, avoiding a second discovery flow.
1020
+ */
1021
+ async getTokenEndpoint() {
1022
+ return (await this.discoveryState())?.authorizationServerMetadata?.token_endpoint ?? null;
1023
+ }
1024
+ };
1025
+
1026
+ // src/auth/browser.ts
1027
+ async function serializeBody(body) {
1028
+ if (typeof body === "string") return body;
1029
+ if (body instanceof URLSearchParams || body instanceof FormData) {
1030
+ return Object.fromEntries(body.entries());
1031
+ }
1032
+ if (body instanceof Blob) return await body.text();
1033
+ return body;
1034
+ }
1035
+ var BrowserOAuthClientProvider = class {
1036
+ serverUrl;
1037
+ staticClientInfo;
1038
+ session;
1039
+ // Browser-only state
1040
+ preventAutoAuth;
1041
+ useRedirectFlow;
1042
+ oauthProxyUrl;
1043
+ connectionUrl;
1044
+ proxyOAuthRequests;
1045
+ onPopupWindow;
1046
+ constructor(serverUrl, options = {}) {
1047
+ if (options.staticClientInfo?.client_secret) {
1048
+ throw new Error(
1049
+ "Browser OAuth clients must be public clients; staticClientInfo.client_secret is not allowed."
1050
+ );
1051
+ }
1052
+ this.serverUrl = serverUrl;
1053
+ this.session = new OAuthSessionStore(
1054
+ serverUrl,
1055
+ { ...options, allowClientSecret: false },
1056
+ new LocalStorageKVStore()
1057
+ );
1058
+ this.preventAutoAuth = options.preventAutoAuth;
1059
+ this.useRedirectFlow = options.useRedirectFlow;
1060
+ this.oauthProxyUrl = options.oauthProxyUrl;
1061
+ this.connectionUrl = options.connectionUrl;
1062
+ this.proxyOAuthRequests = options.proxyOAuthRequests ?? true;
1063
+ this.staticClientInfo = options.staticClientInfo;
1064
+ this.onPopupWindow = options.onPopupWindow;
1065
+ }
1066
+ // --- Identity / key fields exposed for callback handling ---
1067
+ get storageKeyPrefix() {
1068
+ return this.session.storageKeyPrefix;
1069
+ }
1070
+ get serverUrlHash() {
1071
+ return this.session.serverUrlHash;
1072
+ }
1073
+ get clientName() {
1074
+ return this.session.clientName;
1075
+ }
1076
+ get clientUri() {
1077
+ return this.session.clientUri;
1078
+ }
1079
+ get logoUri() {
1080
+ return this.session.logoUri;
1081
+ }
1082
+ get callbackUrl() {
1083
+ return this.session.callbackUrl;
1084
+ }
1085
+ get scope() {
1086
+ return this.session.scope;
1087
+ }
1088
+ get clientMetadataUrl() {
1089
+ return this.session.clientMetadataUrl;
1090
+ }
1091
+ getKey(keySuffix) {
1092
+ return this.session.getKey(keySuffix);
1093
+ }
1094
+ /**
1095
+ * Re-anchor an SDK-derived OAuth discovery URL from the MCP connection
1096
+ * (proxy) origin onto the actual MCP server.
1097
+ *
1098
+ * When MCP traffic is tunneled through a gateway/inspector proxy, the SDK
1099
+ * transport derives `/.well-known/*` URLs from the URL it connected to (the
1100
+ * proxy) whenever no `resource_metadata` hint is available — the SSE
1101
+ * transport's EventSource cannot read `WWW-Authenticate`, and token refresh
1102
+ * runs without a 401 response at hand. The proxy origin serves no OAuth
1103
+ * metadata, so discovery would fail and the server would be misclassified
1104
+ * as "does not support OAuth". Rewriting reproduces what a direct
1105
+ * connection would have requested: the same well-known document, anchored
1106
+ * on the server origin, with the RFC 8414 §3.1 / RFC 9728 §3.1 path
1107
+ * insertion using the server's path instead of the proxy's.
1108
+ */
1109
+ reanchorWellKnownUrl(url) {
1110
+ if (!this.connectionUrl) return url;
1111
+ try {
1112
+ const requested = new URL(url);
1113
+ const connection = new URL(this.connectionUrl);
1114
+ if (requested.origin !== connection.origin) return url;
1115
+ if (!requested.pathname.startsWith("/.well-known/")) return url;
1116
+ const target = new URL(this.serverUrl);
1117
+ const rest = requested.pathname.slice("/.well-known/".length);
1118
+ const [doc, ...suffixParts] = rest.split("/");
1119
+ if (!doc) return url;
1120
+ const suffix = suffixParts.length ? `/${suffixParts.join("/")}` : "";
1121
+ const connectionPath = connection.pathname.replace(/\/+$/, "");
1122
+ const targetPath = target.pathname.replace(/\/+$/, "");
1123
+ const newSuffix = suffix && suffix === connectionPath ? targetPath : suffix;
1124
+ return `${target.origin}/.well-known/${doc}${newSuffix}${requested.search}`;
1125
+ } catch {
1126
+ return url;
1127
+ }
1128
+ }
1129
+ /**
1130
+ * Returns a `fetch` function, scoped to this provider, that routes OAuth
1131
+ * metadata and non-browser OAuth endpoint requests through the configured
1132
+ * `oauthProxyUrl` to bypass CORS. Authorization endpoints are navigated by
1133
+ * the browser and all unrelated requests pass through unchanged.
1134
+ *
1135
+ * Unlike patching the global `fetch`, the returned function only affects the
1136
+ * transport/auth calls it is explicitly handed to (via the SDK transport's
1137
+ * `fetch` option or `auth({ fetchFn })`). Connecting one server "Via Proxy"
1138
+ * therefore never alters fetch behavior for other servers, other
1139
+ * connections, or the rest of the page.
1140
+ *
1141
+ * When this provider is not configured to proxy OAuth requests (no
1142
+ * `oauthProxyUrl`, or `proxyOAuthRequests` disabled), the provided
1143
+ * `baseFetch` is returned as-is (or `undefined` when none is given, letting
1144
+ * the SDK fall back to its default `fetch`).
1145
+ *
1146
+ * @param baseFetch - The fetch used for non-OAuth requests and for the
1147
+ * underlying proxy calls. Defaults to the global `fetch`.
1148
+ */
1149
+ getProxyFetch(baseFetch) {
1150
+ if (!this.proxyOAuthRequests || !this.oauthProxyUrl) {
1151
+ return baseFetch;
1152
+ }
1153
+ const base = baseFetch ?? globalThis.fetch.bind(globalThis);
1154
+ const oauthProxyUrl = this.oauthProxyUrl;
1155
+ const discoveredEndpoints = /* @__PURE__ */ new Set();
1156
+ let restoredDiscovery = false;
1157
+ return async (input, init) => {
1158
+ const requestedUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
1159
+ const url = this.reanchorWellKnownUrl(requestedUrl);
1160
+ let pathname;
1161
+ try {
1162
+ pathname = new URL(url).pathname;
1163
+ } catch {
1164
+ return await base(input, init);
1165
+ }
1166
+ const isMetadata = pathname.includes("/.well-known/");
1167
+ if (!restoredDiscovery) {
1168
+ restoredDiscovery = true;
1169
+ const metadata = (await this.discoveryState())?.authorizationServerMetadata;
1170
+ for (const key of [
1171
+ "registration_endpoint",
1172
+ "token_endpoint",
1173
+ "revocation_endpoint",
1174
+ "introspection_endpoint"
1175
+ ]) {
1176
+ if (typeof metadata?.[key] === "string") {
1177
+ discoveredEndpoints.add(metadata[key]);
1178
+ }
1179
+ }
1180
+ }
1181
+ const isProxiedEndpoint = discoveredEndpoints.has(url) || /\/(?:register|registration|token|revoke|revocation|introspect|introspection)\/?$/.test(
1182
+ pathname
1183
+ );
1184
+ if (!isMetadata && !isProxiedEndpoint) {
1185
+ return await base(input, init);
1186
+ }
1187
+ try {
1188
+ const urlObj = new URL(url);
1189
+ const proxyUrlObj = new URL(oauthProxyUrl);
1190
+ if (urlObj.origin === proxyUrlObj.origin && (urlObj.pathname.startsWith(proxyUrlObj.pathname) || url.includes("/inspector/api/oauth"))) {
1191
+ return await base(input, init);
1192
+ }
1193
+ } catch {
1194
+ }
1195
+ const proxyEndpoint = isMetadata ? `${oauthProxyUrl}/metadata?serverUrl=${encodeURIComponent(
1196
+ this.serverUrl
1197
+ )}&url=${encodeURIComponent(url)}` : `${oauthProxyUrl}/proxy`;
1198
+ if (isMetadata) {
1199
+ const response2 = await base(proxyEndpoint, {
1200
+ ...init,
1201
+ method: "GET"
1202
+ });
1203
+ try {
1204
+ const metadata = await response2.clone().json();
1205
+ for (const key of [
1206
+ "registration_endpoint",
1207
+ "token_endpoint",
1208
+ "revocation_endpoint",
1209
+ "introspection_endpoint"
1210
+ ]) {
1211
+ if (typeof metadata[key] === "string") {
1212
+ discoveredEndpoints.add(metadata[key]);
1213
+ }
1214
+ }
1215
+ } catch {
1216
+ }
1217
+ return response2;
1218
+ }
1219
+ const body = init?.body ? await serializeBody(init.body) : void 0;
1220
+ const response = await base(proxyEndpoint, {
1221
+ method: "POST",
1222
+ headers: { "Content-Type": "application/json" },
1223
+ body: JSON.stringify({
1224
+ serverUrl: this.serverUrl,
1225
+ url,
1226
+ method: init?.method || "POST",
1227
+ headers: init?.headers ? Object.fromEntries(new Headers(init.headers)) : {},
1228
+ body
1229
+ })
1230
+ });
1231
+ const data = await response.json();
1232
+ return new Response(JSON.stringify(data.body), {
1233
+ status: data.status,
1234
+ statusText: data.statusText,
1235
+ headers: new Headers(data.headers)
1236
+ });
1237
+ };
1238
+ }
1239
+ // --- SDK Interface Methods (delegated) ---
1240
+ get redirectUrl() {
1241
+ return this.session.redirectUrl;
1242
+ }
1243
+ get clientMetadata() {
1244
+ return this.session.clientMetadata;
1245
+ }
1246
+ tokens(ctx) {
1247
+ return this.session.tokens(ctx);
1248
+ }
1249
+ saveTokens(tokens, ctx) {
1250
+ return this.session.saveTokens(tokens, ctx);
1251
+ }
1252
+ async clientInformation(ctx) {
1253
+ if (this.staticClientInfo) return this.staticClientInfo;
1254
+ return this.session.clientInformation(ctx);
1255
+ }
1256
+ async saveClientInformation(clientInformation, ctx) {
1257
+ if (this.staticClientInfo) return;
1258
+ return this.session.saveClientInformation(clientInformation, ctx);
1259
+ }
1260
+ codeVerifier() {
1261
+ return this.session.codeVerifier();
1262
+ }
1263
+ saveCodeVerifier(codeVerifier) {
1264
+ return this.session.saveCodeVerifier(codeVerifier);
1265
+ }
1266
+ invalidateCredentials(scope) {
1267
+ return this.session.invalidateCredentials(scope);
1268
+ }
1269
+ /**
1270
+ * Persist OAuth discovery state (SEP-2352). Delegated to the session store;
1271
+ * implementing this silences the SDK's per-callback warning and enables the
1272
+ * authorization-server mix-up defense on the callback leg.
1273
+ */
1274
+ saveDiscoveryState(state) {
1275
+ return this.session.saveDiscoveryState(state);
1276
+ }
1277
+ /** Return previously saved OAuth discovery state, or `undefined`. */
1278
+ discoveryState() {
1279
+ return this.session.discoveryState();
1280
+ }
1281
+ /**
1282
+ * Return the token endpoint from the SDK's persisted discovery state.
1283
+ * Returns `null` before a successful authorization discovery.
1284
+ */
1285
+ getTokenEndpoint() {
1286
+ return this.session.getTokenEndpoint();
1287
+ }
1288
+ /**
1289
+ * Return the stored public OAuth client ID. Browser providers do not retain
1290
+ * client secrets.
1291
+ */
1292
+ async getClientCredentials() {
1293
+ const info = await this.clientInformation();
1294
+ return info?.client_id ? { client_id: info.client_id } : null;
1295
+ }
1296
+ /**
1297
+ * Generates and persists `StoredState` for an authorization request,
1298
+ * and returns the sanitized URL with the `state` param appended. Does NOT
1299
+ * open a popup or redirect —
1300
+ * use `redirectToAuthorization` for that.
1301
+ */
1302
+ async prepareAuthorizationUrl(authorizationUrl) {
1303
+ return this.session.storeAuthorizationState(authorizationUrl, {
1304
+ extraProviderOptions: {
1305
+ oauthProxyUrl: this.oauthProxyUrl,
1306
+ ...this.clientMetadataUrl ? { clientMetadataUrl: this.clientMetadataUrl } : {},
1307
+ ...this.staticClientInfo ? { staticClientInfo: this.staticClientInfo } : {},
1308
+ ...this.scope ? { scope: this.scope } : {}
1309
+ },
1310
+ flowType: this.useRedirectFlow ? "redirect" : "popup",
1311
+ returnUrl: typeof window !== "undefined" ? window.location.href : void 0
1312
+ });
1313
+ }
1314
+ /**
1315
+ * Redirects the user agent to the authorization URL, storing necessary state.
1316
+ * @param authorizationUrl The fully constructed authorization URL from the SDK.
1317
+ */
1318
+ async redirectToAuthorization(authorizationUrl) {
1319
+ const sanitizedAuthUrl = await this.prepareAuthorizationUrl(authorizationUrl);
1320
+ if (this.preventAutoAuth) {
1321
+ console.info(
1322
+ `[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`
1323
+ );
1324
+ return;
1325
+ }
1326
+ if (this.useRedirectFlow) {
1327
+ console.info(
1328
+ `[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`
1329
+ );
1330
+ window.location.href = sanitizedAuthUrl;
1331
+ return;
1332
+ }
1333
+ const popupFeatures = "width=600,height=700,resizable=yes,scrollbars=yes,status=yes";
1334
+ try {
1335
+ const popup = window.open(
1336
+ sanitizedAuthUrl,
1337
+ `mcp_auth_${this.serverUrlHash}`,
1338
+ popupFeatures
1339
+ );
1340
+ if (this.onPopupWindow) {
1341
+ this.onPopupWindow(sanitizedAuthUrl, popupFeatures, popup);
1342
+ }
1343
+ if (!popup || popup.closed || typeof popup.closed === "undefined") {
1344
+ console.warn(
1345
+ `[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`
1346
+ );
1347
+ } else {
1348
+ popup.focus();
1349
+ console.info(
1350
+ `[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`
1351
+ );
1352
+ }
1353
+ } catch (e) {
1354
+ console.error(
1355
+ `[${this.storageKeyPrefix}] Error opening popup window:`,
1356
+ e
1357
+ );
1358
+ }
1359
+ }
1360
+ /**
1361
+ * Retrieves the last URL passed to `redirectToAuthorization`. Useful for manual fallback.
1362
+ */
1363
+ getLastAttemptedAuthUrl() {
1364
+ const storedUrl = localStorage.getItem(this.getKey("last_auth_url"));
1365
+ if (!storedUrl) return null;
1366
+ return sanitizeUrl(storedUrl);
1367
+ }
1368
+ clearStorage() {
1369
+ const prefixPattern = `${this.storageKeyPrefix}_${this.serverUrlHash}_`;
1370
+ const statePattern = `${this.storageKeyPrefix}:state_`;
1371
+ const keysToRemove = [];
1372
+ let count = 0;
1373
+ for (let i = 0; i < localStorage.length; i++) {
1374
+ const key = localStorage.key(i);
1375
+ if (!key) continue;
1376
+ if (key.startsWith(prefixPattern)) {
1377
+ keysToRemove.push(key);
1378
+ } else if (key.startsWith(statePattern)) {
1379
+ try {
1380
+ const item = localStorage.getItem(key);
1381
+ if (item) {
1382
+ const state = JSON.parse(item);
1383
+ if (state.serverUrlHash === this.serverUrlHash) {
1384
+ keysToRemove.push(key);
1385
+ }
1386
+ }
1387
+ } catch (e) {
1388
+ console.warn(
1389
+ `[${this.storageKeyPrefix}] Error parsing state key ${key} during clearStorage:`,
1390
+ e
1391
+ );
1392
+ }
1393
+ }
1394
+ }
1395
+ const uniqueKeysToRemove = [...new Set(keysToRemove)];
1396
+ uniqueKeysToRemove.forEach((key) => {
1397
+ localStorage.removeItem(key);
1398
+ count++;
1399
+ });
1400
+ return count;
1401
+ }
1402
+ };
1403
+ async function createOAuthProvider(serverUrl, options = {}) {
1404
+ return new BrowserOAuthClientProvider(serverUrl, options);
1405
+ }
1406
+
1407
+ // src/auth/callback.ts
1408
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
1409
+
1410
+ // src/auth/popup.ts
1411
+ var MCP_AUTH_BROADCAST_CHANNEL = "mcp_auth_callback";
1412
+ var MCP_AUTH_CALLBACK_MESSAGE_TYPE = "mcp_auth_callback";
1413
+ function hasStoredTokens(tokensKey) {
1414
+ try {
1415
+ return typeof localStorage !== "undefined" && !!localStorage.getItem(tokensKey);
1416
+ } catch {
1417
+ return false;
1418
+ }
1419
+ }
1420
+ function runAuthPopup({
1421
+ popup,
1422
+ state,
1423
+ tokensKey,
1424
+ timeoutMs = 5 * 6e4,
1425
+ closePollMs = 1e3,
1426
+ closeGraceMs = 2e4,
1427
+ expectedOrigin = typeof window !== "undefined" ? window.location.origin : ""
1428
+ }) {
1429
+ return new Promise((resolve) => {
1430
+ let settled = false;
1431
+ let closeTimer = null;
1432
+ let timeoutTimer = null;
1433
+ let graceTimer = null;
1434
+ let broadcastChannel = null;
1435
+ const cleanup = () => {
1436
+ if (closeTimer) {
1437
+ clearInterval(closeTimer);
1438
+ closeTimer = null;
1439
+ }
1440
+ if (timeoutTimer) {
1441
+ clearTimeout(timeoutTimer);
1442
+ timeoutTimer = null;
1443
+ }
1444
+ if (graceTimer) {
1445
+ clearTimeout(graceTimer);
1446
+ graceTimer = null;
1447
+ }
1448
+ if (typeof window !== "undefined") {
1449
+ window.removeEventListener("message", messageHandler);
1450
+ window.removeEventListener("storage", storageHandler);
1451
+ }
1452
+ if (broadcastChannel) {
1453
+ try {
1454
+ broadcastChannel.removeEventListener("message", broadcastHandler);
1455
+ broadcastChannel.close();
1456
+ } catch {
1457
+ }
1458
+ broadcastChannel = null;
1459
+ }
1460
+ };
1461
+ const settle = (result) => {
1462
+ if (settled) return;
1463
+ settled = true;
1464
+ cleanup();
1465
+ resolve(result);
1466
+ };
1467
+ const handlePayload = (payload) => {
1468
+ if (!payload || payload.type !== MCP_AUTH_CALLBACK_MESSAGE_TYPE) return;
1469
+ if (payload.state && state && payload.state !== state) return;
1470
+ if (payload.success) {
1471
+ settle({ kind: "success" });
1472
+ } else {
1473
+ settle({
1474
+ kind: "error",
1475
+ error: payload.error ?? "Authentication failed in callback."
1476
+ });
1477
+ }
1478
+ };
1479
+ const messageHandler = (event) => {
1480
+ if (expectedOrigin && event.origin !== expectedOrigin) return;
1481
+ handlePayload(event.data);
1482
+ };
1483
+ const broadcastHandler = (event) => {
1484
+ handlePayload(event.data);
1485
+ };
1486
+ const storageHandler = (event) => {
1487
+ if (event.key !== tokensKey) return;
1488
+ if (event.newValue) settle({ kind: "success" });
1489
+ };
1490
+ if (typeof window !== "undefined") {
1491
+ window.addEventListener("message", messageHandler);
1492
+ window.addEventListener("storage", storageHandler);
1493
+ }
1494
+ if (typeof BroadcastChannel !== "undefined") {
1495
+ try {
1496
+ broadcastChannel = new BroadcastChannel(MCP_AUTH_BROADCAST_CHANNEL);
1497
+ broadcastChannel.addEventListener("message", broadcastHandler);
1498
+ } catch {
1499
+ broadcastChannel = null;
1500
+ }
1501
+ }
1502
+ if (popup) {
1503
+ closeTimer = setInterval(() => {
1504
+ if (settled) return;
1505
+ let closed = false;
1506
+ try {
1507
+ closed = popup.closed;
1508
+ } catch {
1509
+ closed = false;
1510
+ }
1511
+ if (!closed) return;
1512
+ if (closeTimer) {
1513
+ clearInterval(closeTimer);
1514
+ closeTimer = null;
1515
+ }
1516
+ if (hasStoredTokens(tokensKey)) {
1517
+ settle({ kind: "success" });
1518
+ return;
1519
+ }
1520
+ graceTimer = setTimeout(() => {
1521
+ settle(
1522
+ hasStoredTokens(tokensKey) ? { kind: "success" } : { kind: "cancelled" }
1523
+ );
1524
+ }, closeGraceMs);
1525
+ }, closePollMs);
1526
+ }
1527
+ timeoutTimer = setTimeout(() => {
1528
+ settle(
1529
+ hasStoredTokens(tokensKey) ? { kind: "success" } : { kind: "timeout" }
1530
+ );
1531
+ }, timeoutMs);
1532
+ });
1533
+ }
1534
+
1535
+ // src/auth/callback.ts
1536
+ var inFlightCallback = null;
1537
+ function isMcpAuthPopupWindow() {
1538
+ return typeof window !== "undefined" && window.name.startsWith("mcp_auth_");
1539
+ }
1540
+ function buildCallbackPayload(success, error, meta) {
1541
+ return {
1542
+ type: MCP_AUTH_CALLBACK_MESSAGE_TYPE,
1543
+ success,
1544
+ ...success ? {} : { error: error ?? "Unknown error" },
1545
+ ...meta.state ? { state: meta.state } : {},
1546
+ ...meta.serverUrlHash ? { serverUrlHash: meta.serverUrlHash } : {}
1547
+ };
1548
+ }
1549
+ function broadcastCallback(payload) {
1550
+ if (typeof BroadcastChannel === "undefined") return;
1551
+ let channel;
1552
+ try {
1553
+ channel = new BroadcastChannel(MCP_AUTH_BROADCAST_CHANNEL);
1554
+ channel.postMessage(payload);
1555
+ } catch (error) {
1556
+ console.warn("[mcp-callback] Failed to broadcast callback result:", error);
1557
+ } finally {
1558
+ if (channel) {
1559
+ setTimeout(() => {
1560
+ try {
1561
+ channel?.close();
1562
+ } catch {
1563
+ }
1564
+ }, 0);
1565
+ }
1566
+ }
1567
+ }
1568
+ function renderResult(title, message, error, returnUrl) {
1569
+ if (typeof document === "undefined") return;
1570
+ document.body.innerHTML = "";
1571
+ const container = document.createElement("div");
1572
+ container.style.fontFamily = "sans-serif";
1573
+ container.style.padding = "20px";
1574
+ const heading = document.createElement("h1");
1575
+ heading.textContent = title;
1576
+ container.appendChild(heading);
1577
+ const text = document.createElement("p");
1578
+ text.textContent = message;
1579
+ if (error) {
1580
+ text.style.color = "red";
1581
+ text.style.backgroundColor = "#ffebeb";
1582
+ text.style.border = "1px solid red";
1583
+ text.style.padding = "10px";
1584
+ text.style.borderRadius = "4px";
1585
+ }
1586
+ container.appendChild(text);
1587
+ const close = document.createElement("a");
1588
+ close.href = "#";
1589
+ close.textContent = "Close this window";
1590
+ close.onclick = (event) => {
1591
+ event.preventDefault();
1592
+ window.close();
1593
+ return false;
1594
+ };
1595
+ container.appendChild(close);
1596
+ if (returnUrl) {
1597
+ const separator = document.createTextNode(" or ");
1598
+ const back = document.createElement("a");
1599
+ back.href = returnUrl;
1600
+ back.textContent = "return to the app";
1601
+ container.append(separator, back);
1602
+ }
1603
+ document.body.appendChild(container);
1604
+ }
1605
+ function findStoredState(state) {
1606
+ const defaultKey = `mcp:auth:state_${state}`;
1607
+ let key = localStorage.getItem(defaultKey) ? defaultKey : null;
1608
+ if (!key) {
1609
+ const suffix = `:state_${state}`;
1610
+ for (let index = 0; index < localStorage.length; index++) {
1611
+ const candidate = localStorage.key(index);
1612
+ if (candidate?.endsWith(suffix)) {
1613
+ key = candidate;
1614
+ break;
1615
+ }
1616
+ }
1617
+ }
1618
+ const serialized = key ? localStorage.getItem(key) : null;
1619
+ if (!key || !serialized) {
1620
+ throw new Error(`Invalid or expired OAuth state "${state}".`);
1621
+ }
1622
+ let value;
1623
+ try {
1624
+ value = JSON.parse(serialized);
1625
+ } catch {
1626
+ localStorage.removeItem(key);
1627
+ throw new Error("Failed to parse stored OAuth state.");
1628
+ }
1629
+ return { key, value };
1630
+ }
1631
+ function redirectWithError(returnUrl, message) {
1632
+ const url = new URL(returnUrl);
1633
+ url.searchParams.set("auth_error", "oauth_callback_failed");
1634
+ url.searchParams.set("auth_error_description", message);
1635
+ window.location.href = url.toString();
1636
+ }
1637
+ function signalResult(success, error, storedState, meta) {
1638
+ const payload = buildCallbackPayload(success, error, meta);
1639
+ const returnUrl = storedState?.returnUrl;
1640
+ const popup = storedState?.flowType === "popup" || isMcpAuthPopupWindow();
1641
+ if (storedState?.flowType === "redirect" && returnUrl) {
1642
+ if (success) window.location.href = returnUrl;
1643
+ else redirectWithError(returnUrl, error ?? "Authentication failed.");
1644
+ return;
1645
+ }
1646
+ if (window.opener && !window.opener.closed) {
1647
+ window.opener.postMessage(payload, window.location.origin);
1648
+ window.close();
1649
+ return;
1650
+ }
1651
+ if (popup) {
1652
+ broadcastCallback(payload);
1653
+ renderResult(
1654
+ success ? "Authentication Successful!" : "Authentication Error",
1655
+ success ? "You're authenticated. You can close this window and return to the app." : error ?? "Authentication failed.",
1656
+ !success,
1657
+ returnUrl
1658
+ );
1659
+ try {
1660
+ window.close();
1661
+ } catch {
1662
+ }
1663
+ return;
1664
+ }
1665
+ if (returnUrl) {
1666
+ if (success) window.location.href = returnUrl;
1667
+ else redirectWithError(returnUrl, error ?? "Authentication failed.");
1668
+ return;
1669
+ }
1670
+ if (!success) {
1671
+ renderResult(
1672
+ "Authentication Error",
1673
+ error ?? "Authentication failed.",
1674
+ true
1675
+ );
1676
+ return;
1677
+ }
1678
+ window.location.href = "/";
1679
+ }
1680
+ function onMcpAuthorization() {
1681
+ if (!inFlightCallback) inFlightCallback = completeAuthorization();
1682
+ return inFlightCallback;
1683
+ }
1684
+ async function completeAuthorization() {
1685
+ const callbackParams = new URLSearchParams(window.location.search);
1686
+ const state = callbackParams.get("state");
1687
+ let stateKey = null;
1688
+ let storedState = null;
1689
+ let provider = null;
1690
+ try {
1691
+ if (!state) {
1692
+ throw new Error("OAuth callback is missing the state parameter.");
1693
+ }
1694
+ const stored = findStoredState(state);
1695
+ stateKey = stored.key;
1696
+ storedState = stored.value;
1697
+ if (!storedState.expiry || storedState.expiry < Date.now()) {
1698
+ localStorage.removeItem(stateKey);
1699
+ throw new Error(
1700
+ "OAuth state has expired. Please start authentication again."
1701
+ );
1702
+ }
1703
+ if (!storedState.providerOptions) {
1704
+ throw new Error("Stored OAuth state is missing provider options.");
1705
+ }
1706
+ const { serverUrl, ...providerOptions } = storedState.providerOptions;
1707
+ provider = new BrowserOAuthClientProvider(serverUrl, providerOptions);
1708
+ const transport = new StreamableHTTPClientTransport(new URL(serverUrl), {
1709
+ authProvider: provider,
1710
+ fetch: provider.getProxyFetch()
1711
+ });
1712
+ await transport.finishAuth(callbackParams);
1713
+ localStorage.removeItem(stateKey);
1714
+ signalResult(true, void 0, storedState, {
1715
+ state,
1716
+ serverUrlHash: storedState.serverUrlHash
1717
+ });
1718
+ } catch (error) {
1719
+ const message = error instanceof Error ? error.message : String(error);
1720
+ console.error("[mcp-callback] OAuth callback failed:", error);
1721
+ if (stateKey) localStorage.removeItem(stateKey);
1722
+ if (provider) localStorage.removeItem(provider.getKey("last_auth_url"));
1723
+ signalResult(false, message, storedState, {
1724
+ state,
1725
+ serverUrlHash: storedState?.serverUrlHash
1726
+ });
1727
+ }
1728
+ }
1729
+
1730
+ // src/auth/flow.ts
1731
+ import {
1732
+ auth,
1733
+ UnauthorizedError
1734
+ } from "@modelcontextprotocol/client";
1735
+ var DEFAULT_AUTH_TIMEOUT_MS = 5 * 6e4;
1736
+ function isUnauthorized(err, depth = 0) {
1737
+ if (!err || depth > 5) return false;
1738
+ if (err instanceof UnauthorizedError) return true;
1739
+ if (err instanceof Error) {
1740
+ const code = err.code;
1741
+ if (code === 401) return true;
1742
+ if (err.name === "UnauthorizedError") return true;
1743
+ const message = err.message ?? "";
1744
+ if (message.includes("401") || message.includes("Unauthorized")) {
1745
+ return true;
1746
+ }
1747
+ if (err.cause && isUnauthorized(err.cause, depth + 1)) return true;
1748
+ const data = err.data;
1749
+ if (data?.cause && isUnauthorized(data.cause, depth + 1)) return true;
1750
+ }
1751
+ return false;
1752
+ }
1753
+ async function completeOAuthFlow(provider, serverUrl, options = {}) {
1754
+ const flowProvider = provider;
1755
+ const timeoutMs = options.timeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS;
1756
+ const fetchFn = options.fetchFn ?? flowProvider.getProxyFetch?.() ?? void 0;
1757
+ if (!flowProvider.hasPendingFlow) {
1758
+ const result = await auth(provider, { serverUrl, fetchFn });
1759
+ if (result === "AUTHORIZED") return;
1760
+ if (result !== "REDIRECT") {
1761
+ throw new Error(`Unexpected OAuth auth() result: ${result}`);
1762
+ }
1763
+ }
1764
+ if (typeof flowProvider.getAuthorizationCode === "function") {
1765
+ const code = await flowProvider.getAuthorizationCode();
1766
+ await auth(provider, {
1767
+ serverUrl,
1768
+ authorizationCode: code,
1769
+ fetchFn
1770
+ });
1771
+ return;
1772
+ }
1773
+ await waitForBrowserAuthComplete(flowProvider, timeoutMs);
1774
+ }
1775
+ async function waitForBrowserAuthComplete(provider, timeoutMs) {
1776
+ if (typeof window === "undefined") {
1777
+ throw new Error(
1778
+ "OAuth redirect requires a browser environment or a provider with getAuthorizationCode()"
1779
+ );
1780
+ }
1781
+ if (provider.useRedirectFlow) {
1782
+ return;
1783
+ }
1784
+ const tokensKey = provider.getKey?.("tokens");
1785
+ if (!tokensKey) {
1786
+ throw new Error(
1787
+ "Browser OAuth provider must expose getKey() for token storage"
1788
+ );
1789
+ }
1790
+ let state = null;
1791
+ const authUrl = provider.getLastAttemptedAuthUrl?.();
1792
+ if (authUrl) {
1793
+ try {
1794
+ state = new URL(authUrl).searchParams.get("state");
1795
+ } catch {
1796
+ }
1797
+ }
1798
+ const result = await runAuthPopup({
1799
+ popup: null,
1800
+ state,
1801
+ tokensKey,
1802
+ timeoutMs
1803
+ });
1804
+ switch (result.kind) {
1805
+ case "success":
1806
+ return;
1807
+ case "cancelled":
1808
+ throw new Error("OAuth authentication was cancelled.");
1809
+ case "timeout":
1810
+ throw new Error(
1811
+ `OAuth callback not received within ${timeoutMs}ms. Ensure /oauth/callback calls onMcpAuthorization().`
1812
+ );
1813
+ case "error":
1814
+ throw new Error(result.error);
1815
+ default:
1816
+ throw new Error("Unexpected OAuth popup result");
1817
+ }
1818
+ }
1819
+
1820
+ // src/index-browser.ts
1821
+ import { auth as auth2, UnauthorizedError as UnauthorizedError3 } from "@modelcontextprotocol/client";
1822
+
1823
+ // src/transport/http.ts
1824
+ import {
1825
+ Client,
1826
+ SdkError,
1827
+ SdkHttpError,
1828
+ StreamableHTTPClientTransport as StreamableHTTPClientTransport2,
1829
+ UnauthorizedError as UnauthorizedError2
1830
+ } from "@modelcontextprotocol/client";
1831
+
1832
+ // src/utils/json-schema-validator.ts
1833
+ import {
1834
+ CfWorkerJsonSchemaValidator
1835
+ } from "@modelcontextprotocol/client/validators/cf-worker";
1836
+ var DRAFT_04_URI = "http://json-schema.org/draft-04/schema";
1837
+ var DRAFT_07_URIS = /* @__PURE__ */ new Set([
1838
+ "http://json-schema.org/draft-07/schema",
1839
+ "https://json-schema.org/draft-07/schema"
1840
+ ]);
1841
+ var DRAFT_2019_09_URIS = /* @__PURE__ */ new Set([
1842
+ "https://json-schema.org/draft/2019-09/schema",
1843
+ "http://json-schema.org/draft/2019-09/schema"
1844
+ ]);
1845
+ var DRAFT_2020_12_URIS = /* @__PURE__ */ new Set([
1846
+ "https://json-schema.org/draft/2020-12/schema",
1847
+ "http://json-schema.org/draft/2020-12/schema"
1848
+ ]);
1849
+ function resolveDraft(schema) {
1850
+ if (!("$schema" in schema) || typeof schema.$schema !== "string") {
1851
+ return "2020-12";
1852
+ }
1853
+ const normalized = schema.$schema.replace(/#$/, "");
1854
+ if (normalized === DRAFT_04_URI) return "4";
1855
+ if (DRAFT_07_URIS.has(normalized)) return "7";
1856
+ if (DRAFT_2019_09_URIS.has(normalized)) return "2019-09";
1857
+ if (DRAFT_2020_12_URIS.has(normalized)) return "2020-12";
1858
+ return void 0;
1859
+ }
1860
+ var DialectJsonSchemaValidator = class {
1861
+ getValidator(schema) {
1862
+ const draft = resolveDraft(schema);
1863
+ const delegate = draft !== void 0 ? new CfWorkerJsonSchemaValidator({ draft }) : new CfWorkerJsonSchemaValidator();
1864
+ return delegate.getValidator(schema);
1865
+ }
1866
+ };
1867
+
1868
+ // src/transport/base.ts
1869
+ var passthroughResultSchema = {
1870
+ "~standard": {
1871
+ version: 1,
1872
+ vendor: "mcp-use",
1873
+ validate: (value) => ({ value })
1874
+ }
1875
+ };
1876
+ var BaseConnector = class {
1877
+ client = null;
1878
+ connectionManager = null;
1879
+ toolsCache = null;
1880
+ capabilitiesCache = null;
1881
+ serverInfoCache = null;
1882
+ connected = false;
1883
+ opts;
1884
+ notificationHandlers = [];
1885
+ rootsCache = [];
1886
+ activeProgressHandlers = /* @__PURE__ */ new Set();
1887
+ constructor(opts = {}) {
1888
+ this.opts = opts;
1889
+ if (opts.roots) {
1890
+ this.rootsCache = [...opts.roots];
1891
+ }
1892
+ if (opts.onNotification) {
1893
+ this.notificationHandlers.push(opts.onNotification);
1894
+ }
1895
+ }
1896
+ /**
1897
+ * Track connector initialization event
1898
+ * Should be called by subclasses after successful connection
1899
+ */
1900
+ trackConnectorInit(data) {
1901
+ const connectorType = this.constructor.name;
1902
+ trackConnectorTelemetry({ connectorType, ...data });
1903
+ }
1904
+ /**
1905
+ * Register a handler for server notifications
1906
+ *
1907
+ * @param handler - Function to call when a notification is received
1908
+ *
1909
+ * @example
1910
+ * ```typescript
1911
+ * connector.onNotification((notification) => {
1912
+ * console.log(`Received: ${notification.method}`, notification.params);
1913
+ * });
1914
+ * ```
1915
+ */
1916
+ onNotification(handler) {
1917
+ this.notificationHandlers.push(handler);
1918
+ if (this.client) {
1919
+ this.setupNotificationHandler();
1920
+ }
1921
+ }
1922
+ /** Forward a normalized notification to every registered consumer. */
1923
+ async forwardNotification(notification) {
1924
+ for (const handler of this.notificationHandlers) {
1925
+ try {
1926
+ await handler(notification);
1927
+ } catch (err) {
1928
+ logger.error("Error in notification handler:", err);
1929
+ }
1930
+ }
1931
+ }
1932
+ /** Handle SDK list-change callbacks identically on v1 and v2 connections. */
1933
+ async handleListChanged(method, error, tools) {
1934
+ if (error) {
1935
+ logger.warn(`[Auto] ${method} refresh failed:`, error);
1936
+ return;
1937
+ }
1938
+ if (method === "notifications/tools/list_changed" && tools) {
1939
+ this.toolsCache = [...tools];
1940
+ }
1941
+ await this.forwardNotification({ method });
1942
+ }
1943
+ /**
1944
+ * Internal: wire notification handlers to the SDK client
1945
+ * Includes automatic handling for list_changed notifications per MCP spec
1946
+ */
1947
+ setupNotificationHandler() {
1948
+ if (!this.client) return;
1949
+ this.client.fallbackNotificationHandler = async (notification) => {
1950
+ switch (notification.method) {
1951
+ case "notifications/tools/list_changed":
1952
+ await this.refreshToolsCache();
1953
+ break;
1954
+ case "notifications/resources/list_changed":
1955
+ await this.onResourcesListChanged();
1956
+ break;
1957
+ case "notifications/prompts/list_changed":
1958
+ await this.onPromptsListChanged();
1959
+ break;
1960
+ default:
1961
+ break;
1962
+ }
1963
+ await this.forwardNotification(notification);
1964
+ };
1965
+ const client = this.client;
1966
+ const handlersMap = client._notificationHandlers;
1967
+ for (const method of [
1968
+ "notifications/progress",
1969
+ "notifications/cancelled"
1970
+ ]) {
1971
+ const originalHandler = handlersMap.get(method);
1972
+ if (originalHandler) {
1973
+ handlersMap.set(method, async (notification) => {
1974
+ await originalHandler(notification);
1975
+ await this.forwardNotification(notification);
1976
+ });
1977
+ }
1978
+ }
1979
+ }
1980
+ /**
1981
+ * Forward v2 MRTR progress whose retry request IDs are not associated with
1982
+ * the original call callback by the current SDK beta.
1983
+ *
1984
+ * ponytail: fallback is enabled only when exactly one progress-aware call is
1985
+ * active; remove it when the upstream SDK propagates handlers to MRTR rounds.
1986
+ */
1987
+ setupRoundProgressForwarding() {
1988
+ if (!this.client) return;
1989
+ const sdkClient = this.client;
1990
+ const original = sdkClient._onnotification.bind(this.client);
1991
+ sdkClient._onnotification = async (message) => {
1992
+ if (message && typeof message === "object" && message.method === "notifications/progress") {
1993
+ this.forwardRoundProgress(message.params);
1994
+ }
1995
+ await original?.(message);
1996
+ };
1997
+ }
1998
+ /** Forward progress parsed from a transport stream to the active call. */
1999
+ forwardRoundProgress(params) {
2000
+ if (this.activeProgressHandlers.size === 1) {
2001
+ const [handler] = this.activeProgressHandlers;
2002
+ handler?.(
2003
+ params
2004
+ );
2005
+ }
2006
+ }
2007
+ /**
2008
+ * Auto-refresh tools cache when server sends tools/list_changed notification
2009
+ */
2010
+ async refreshToolsCache() {
2011
+ if (!this.client) return;
2012
+ try {
2013
+ logger.debug(
2014
+ "[Auto] Refreshing tools cache due to list_changed notification"
2015
+ );
2016
+ const result = await this.client.listTools();
2017
+ this.toolsCache = result.tools ?? [];
2018
+ logger.debug(
2019
+ `[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`
2020
+ );
2021
+ } catch (err) {
2022
+ logger.warn("[Auto] Failed to refresh tools cache:", err);
2023
+ }
2024
+ }
2025
+ /**
2026
+ * Called when server sends resources/list_changed notification
2027
+ * Resources aren't cached by default, but we log for user awareness
2028
+ */
2029
+ async onResourcesListChanged() {
2030
+ logger.debug(
2031
+ "[Auto] Resources list changed - clients should re-fetch if needed"
2032
+ );
2033
+ }
2034
+ /**
2035
+ * Called when server sends prompts/list_changed notification
2036
+ * Prompts aren't cached by default, but we log for user awareness
2037
+ */
2038
+ async onPromptsListChanged() {
2039
+ logger.debug(
2040
+ "[Auto] Prompts list changed - clients should re-fetch if needed"
2041
+ );
2042
+ }
2043
+ /**
2044
+ * Set roots and notify the server.
2045
+ * Roots represent directories or files that the client has access to.
2046
+ *
2047
+ * @param roots - Array of Root objects with `uri` (must start with "file://") and optional `name`
2048
+ *
2049
+ * @deprecated Roots are retained only for v1 compatibility.
2050
+ *
2051
+ * @example
2052
+ * ```typescript
2053
+ * await connector.setRoots([
2054
+ * { uri: "file:///home/user/project", name: "My Project" },
2055
+ * { uri: "file:///home/user/data" }
2056
+ * ]);
2057
+ * ```
2058
+ */
2059
+ async setRoots(roots) {
2060
+ this.rootsCache = [...roots];
2061
+ if (this.client) {
2062
+ logger.debug(
2063
+ `Sending roots/list_changed notification with ${roots.length} root(s)`
2064
+ );
2065
+ await this.client.sendRootsListChanged();
2066
+ }
2067
+ }
2068
+ /**
2069
+ * Get the current roots.
2070
+ */
2071
+ getRoots() {
2072
+ return [...this.rootsCache];
2073
+ }
2074
+ /**
2075
+ * Internal: set up roots/list request handler.
2076
+ * Must be registered after Client construction and before connect() so the
2077
+ * handler is available during initialize / reverse RPC for the full session.
2078
+ */
2079
+ setupRootsHandler() {
2080
+ if (!this.client) return;
2081
+ this.client.setRequestHandler("roots/list", async () => {
2082
+ logger.debug(
2083
+ `Server requested roots list, returning ${this.rootsCache.length} root(s)`
2084
+ );
2085
+ return { roots: this.rootsCache };
2086
+ });
2087
+ }
2088
+ /**
2089
+ * Internal: set up sampling/createMessage request handler.
2090
+ * Must be registered after Client construction and before connect().
2091
+ */
2092
+ setupSamplingHandler() {
2093
+ if (!this.client) {
2094
+ logger.debug("setupSamplingHandler: No client available");
2095
+ return;
2096
+ }
2097
+ const samplingCallback = this.opts.onSampling;
2098
+ if (!samplingCallback) {
2099
+ logger.debug("setupSamplingHandler: No sampling callback provided");
2100
+ return;
2101
+ }
2102
+ logger.debug("setupSamplingHandler: Setting up sampling request handler");
2103
+ this.client.setRequestHandler("sampling/createMessage", async (request) => {
2104
+ logger.debug("Server requested sampling, forwarding to callback");
2105
+ return await samplingCallback(request.params);
2106
+ });
2107
+ logger.debug(
2108
+ "setupSamplingHandler: Sampling handler registered successfully"
2109
+ );
2110
+ }
2111
+ /**
2112
+ * Internal: set up elicitation/create request handler.
2113
+ * Must be registered after Client construction and before connect().
2114
+ */
2115
+ setupElicitationHandler() {
2116
+ if (!this.client) {
2117
+ logger.debug("setupElicitationHandler: No client available");
2118
+ return;
2119
+ }
2120
+ const elicitationCallback = this.opts.onElicitation;
2121
+ if (!elicitationCallback) {
2122
+ logger.debug("setupElicitationHandler: No elicitation callback provided");
2123
+ return;
2124
+ }
2125
+ logger.debug(
2126
+ "setupElicitationHandler: Setting up elicitation request handler"
2127
+ );
2128
+ this.client.setRequestHandler("elicitation/create", async (request) => {
2129
+ logger.debug("Server requested elicitation, forwarding to callback");
2130
+ return await elicitationCallback(
2131
+ request.params
2132
+ );
2133
+ });
2134
+ logger.debug(
2135
+ "setupElicitationHandler: Elicitation handler registered successfully"
2136
+ );
2137
+ }
2138
+ /** Disconnect and release resources. */
2139
+ async disconnect() {
2140
+ if (!this.connected) {
2141
+ logger.debug("Not connected to MCP implementation");
2142
+ return;
2143
+ }
2144
+ logger.debug("Disconnecting from MCP implementation");
2145
+ await this.cleanupResources();
2146
+ this.connected = false;
2147
+ logger.debug("Disconnected from MCP implementation");
2148
+ }
2149
+ /** Check if the client is connected */
2150
+ get isClientConnected() {
2151
+ return this.client != null;
2152
+ }
2153
+ /**
2154
+ * Initialise the MCP session **after** `connect()` has succeeded.
2155
+ *
2156
+ * In the SDK, `Client.connect(transport)` automatically performs the
2157
+ * protocol‑level `initialize` handshake, so we only need to cache the list of
2158
+ * tools and expose some server info.
2159
+ */
2160
+ async initialize(defaultRequestOptions = this.opts.defaultRequestOptions ?? {}) {
2161
+ if (!this.client) {
2162
+ throw new Error("MCP client is not connected");
2163
+ }
2164
+ logger.debug("Caching server capabilities & tools");
2165
+ const capabilities = this.client.getServerCapabilities();
2166
+ this.capabilitiesCache = capabilities || null;
2167
+ const serverInfo = this.client.getServerVersion();
2168
+ this.serverInfoCache = serverInfo ? {
2169
+ name: serverInfo.name,
2170
+ version: serverInfo.version,
2171
+ title: serverInfo.title,
2172
+ description: serverInfo.description,
2173
+ websiteUrl: serverInfo.websiteUrl,
2174
+ icons: serverInfo.icons
2175
+ } : null;
2176
+ try {
2177
+ const listToolsRes = await this.client.listTools(
2178
+ void 0,
2179
+ defaultRequestOptions
2180
+ );
2181
+ this.toolsCache = listToolsRes.tools ?? [];
2182
+ logger.debug(`Fetched ${this.toolsCache.length} tools from server`);
2183
+ } catch (err) {
2184
+ const error = err;
2185
+ if (error.code === -32601) {
2186
+ logger.debug("Server does not implement tools/list, assuming no tools");
2187
+ } else {
2188
+ logger.debug("Failed to list tools, assuming empty:", error.message);
2189
+ }
2190
+ this.toolsCache = [];
2191
+ }
2192
+ logger.debug("Server capabilities:", capabilities);
2193
+ logger.debug("Server info:", serverInfo);
2194
+ return capabilities;
2195
+ }
2196
+ /** Lazily expose the cached tools list. */
2197
+ get tools() {
2198
+ if (!this.toolsCache) {
2199
+ throw new Error("MCP client is not initialized; call initialize() first");
2200
+ }
2201
+ return this.toolsCache;
2202
+ }
2203
+ /** Expose cached server capabilities. */
2204
+ get serverCapabilities() {
2205
+ return this.capabilitiesCache || {};
2206
+ }
2207
+ /** Expose cached server info. */
2208
+ get serverInfo() {
2209
+ return this.serverInfoCache;
2210
+ }
2211
+ /** Instructions supplied by the connected server, if any. */
2212
+ get instructions() {
2213
+ return this.client?.getInstructions?.();
2214
+ }
2215
+ /**
2216
+ * The negotiated protocol era for the active connection.
2217
+ * - `"legacy"` — 2025-era server, sessionful `initialize` handshake.
2218
+ * - `"modern"` — 2026-era server, stateless per-request.
2219
+ * `undefined` before the connection has negotiated.
2220
+ */
2221
+ get protocolEra() {
2222
+ return this.client?.getProtocolEra?.();
2223
+ }
2224
+ /** The protocol version string negotiated for the active connection. */
2225
+ get negotiatedProtocolVersion() {
2226
+ return this.client?.getNegotiatedProtocolVersion?.();
2227
+ }
2228
+ /** Call a tool on the server. */
2229
+ async callTool(name, args, options) {
2230
+ if (!this.client) {
2231
+ throw new Error("MCP client is not connected");
2232
+ }
2233
+ const enhancedOptions = options ? { ...options } : void 0;
2234
+ if (enhancedOptions?.resetTimeoutOnProgress && !enhancedOptions.onprogress) {
2235
+ enhancedOptions.onprogress = () => {
2236
+ };
2237
+ logger.debug(
2238
+ `[BaseConnector] Added onprogress callback for tool '${name}' to enable progressToken`
2239
+ );
2240
+ }
2241
+ logger.debug(`Calling tool '${name}' with args`, args);
2242
+ const progressHandler = enhancedOptions?.onprogress;
2243
+ if (progressHandler) this.activeProgressHandlers.add(progressHandler);
2244
+ try {
2245
+ const res = await this.client.callTool(
2246
+ { name, arguments: args },
2247
+ enhancedOptions
2248
+ );
2249
+ logger.debug(`Tool '${name}' returned`, res);
2250
+ return res;
2251
+ } finally {
2252
+ if (progressHandler) this.activeProgressHandlers.delete(progressHandler);
2253
+ }
2254
+ }
2255
+ /**
2256
+ * List all available tools from the MCP server.
2257
+ * This method fetches fresh tools from the server, unlike the `tools` getter which returns cached tools.
2258
+ *
2259
+ * @param options - Optional request options
2260
+ * @returns Array of available tools
2261
+ */
2262
+ async listTools(options) {
2263
+ if (!this.client) {
2264
+ throw new Error("MCP client is not connected");
2265
+ }
2266
+ logger.debug("[listTools] Fetching fresh tools from server...");
2267
+ const result = await this.client.listTools(void 0, options);
2268
+ const tools = result.tools ? [...result.tools] : [];
2269
+ logger.debug(
2270
+ `[listTools] Returned ${tools.length} tools:`,
2271
+ tools.map((t) => t.name)
2272
+ );
2273
+ return tools;
2274
+ }
2275
+ /**
2276
+ * List resources from the server with optional pagination
2277
+ *
2278
+ * @param cursor - Optional cursor for pagination
2279
+ * @param options - Request options
2280
+ * @returns Resource list with optional nextCursor for pagination
2281
+ */
2282
+ async listResources(cursor, options) {
2283
+ if (!this.client) {
2284
+ throw new Error("MCP client is not connected");
2285
+ }
2286
+ logger.debug("Listing resources", cursor ? `with cursor: ${cursor}` : "");
2287
+ return await this.client.listResources({ cursor }, options);
2288
+ }
2289
+ /**
2290
+ * List all resources from the server, automatically handling pagination
2291
+ *
2292
+ * @param options - Request options
2293
+ * @returns Complete list of all resources
2294
+ */
2295
+ async listAllResources(options) {
2296
+ if (!this.client) {
2297
+ throw new Error("MCP client is not connected");
2298
+ }
2299
+ if (!this.capabilitiesCache?.resources) {
2300
+ logger.debug("Server does not advertise resources capability, skipping");
2301
+ return { resources: [] };
2302
+ }
2303
+ try {
2304
+ logger.debug("Listing all resources (with auto-pagination)");
2305
+ const allResources = [];
2306
+ let cursor = void 0;
2307
+ do {
2308
+ const result = await this.client.listResources({ cursor }, options);
2309
+ allResources.push(...result.resources || []);
2310
+ cursor = result.nextCursor;
2311
+ } while (cursor);
2312
+ return { resources: allResources };
2313
+ } catch (err) {
2314
+ const error = err;
2315
+ if (error.code === -32601) {
2316
+ logger.debug("Server advertised resources but method not found");
2317
+ return { resources: [] };
2318
+ }
2319
+ throw err;
2320
+ }
2321
+ }
2322
+ /**
2323
+ * List resource templates from the server
2324
+ *
2325
+ * @param options - Request options
2326
+ * @returns List of available resource templates
2327
+ */
2328
+ async listResourceTemplates(options) {
2329
+ if (!this.client) {
2330
+ throw new Error("MCP client is not connected");
2331
+ }
2332
+ logger.debug("Listing resource templates");
2333
+ return await this.client.listResourceTemplates(void 0, options);
2334
+ }
2335
+ /**
2336
+ * Request completion suggestions for a prompt or resource template argument
2337
+ *
2338
+ * @param params - Completion request parameters
2339
+ * @param options - Request options
2340
+ * @returns Completion suggestions from the server
2341
+ */
2342
+ async complete(params, options) {
2343
+ if (!this.client) {
2344
+ throw new Error("MCP client is not connected");
2345
+ }
2346
+ logger.debug("[complete] Requesting completions for:", params.ref);
2347
+ const result = await this.client.complete(params, options);
2348
+ logger.debug(
2349
+ `[complete] Received ${result.completion.values.length} suggestions`
2350
+ );
2351
+ return result;
2352
+ }
2353
+ /** Read a resource by URI. */
2354
+ async readResource(uri, options) {
2355
+ if (!this.client) {
2356
+ throw new Error("MCP client is not connected");
2357
+ }
2358
+ logger.debug(`Reading resource ${uri}`);
2359
+ const res = await this.client.readResource({ uri }, options);
2360
+ return res;
2361
+ }
2362
+ /**
2363
+ * Subscribe to resource updates
2364
+ *
2365
+ * @param uri - URI of the resource to subscribe to
2366
+ * @param options - Request options
2367
+ */
2368
+ async subscribeToResource(uri, options) {
2369
+ if (!this.client) {
2370
+ throw new Error("MCP client is not connected");
2371
+ }
2372
+ logger.debug(`Subscribing to resource: ${uri}`);
2373
+ return await this.client.subscribeResource({ uri }, options);
2374
+ }
2375
+ /**
2376
+ * Unsubscribe from resource updates
2377
+ *
2378
+ * @param uri - URI of the resource to unsubscribe from
2379
+ * @param options - Request options
2380
+ */
2381
+ async unsubscribeFromResource(uri, options) {
2382
+ if (!this.client) {
2383
+ throw new Error("MCP client is not connected");
2384
+ }
2385
+ logger.debug(`Unsubscribing from resource: ${uri}`);
2386
+ return await this.client.unsubscribeResource({ uri }, options);
2387
+ }
2388
+ async listPrompts() {
2389
+ if (!this.client) {
2390
+ throw new Error("MCP client is not connected");
2391
+ }
2392
+ if (!this.capabilitiesCache?.prompts) {
2393
+ logger.debug("Server does not advertise prompts capability, skipping");
2394
+ return { prompts: [] };
2395
+ }
2396
+ try {
2397
+ logger.debug("Listing prompts");
2398
+ return await this.client.listPrompts();
2399
+ } catch (err) {
2400
+ const error = err;
2401
+ if (error.code === -32601) {
2402
+ logger.debug("Server advertised prompts but method not found");
2403
+ return { prompts: [] };
2404
+ }
2405
+ throw err;
2406
+ }
2407
+ }
2408
+ async getPrompt(name, args) {
2409
+ if (!this.client) {
2410
+ throw new Error("MCP client is not connected");
2411
+ }
2412
+ logger.debug(`Getting prompt ${name}`);
2413
+ return await this.client.getPrompt({ name, arguments: args });
2414
+ }
2415
+ /** Send a raw request through the client. */
2416
+ async request(method, params = null, options) {
2417
+ if (!this.client) {
2418
+ throw new Error("MCP client is not connected");
2419
+ }
2420
+ logger.debug(`Sending raw request '${method}' with params`, params);
2421
+ return await this.client.request(
2422
+ { method, params: params ?? {} },
2423
+ passthroughResultSchema,
2424
+ options
2425
+ );
2426
+ }
2427
+ /**
2428
+ * Helper to tear down the client & connection manager safely.
2429
+ */
2430
+ async cleanupResources() {
2431
+ const issues = [];
2432
+ if (this.client) {
2433
+ try {
2434
+ if (typeof this.client.close === "function") {
2435
+ await this.client.close();
2436
+ }
2437
+ } catch (e) {
2438
+ const msg = `Error closing client: ${e}`;
2439
+ logger.warn(msg);
2440
+ issues.push(msg);
2441
+ } finally {
2442
+ this.client = null;
2443
+ }
2444
+ }
2445
+ if (this.connectionManager) {
2446
+ try {
2447
+ await this.connectionManager.stop();
2448
+ } catch (e) {
2449
+ const msg = `Error stopping connection manager: ${e}`;
2450
+ logger.warn(msg);
2451
+ issues.push(msg);
2452
+ } finally {
2453
+ this.connectionManager = null;
2454
+ }
2455
+ }
2456
+ this.toolsCache = null;
2457
+ if (issues.length) {
2458
+ logger.warn(`Resource cleanup finished with ${issues.length} issue(s)`);
2459
+ }
2460
+ }
2461
+ };
2462
+
2463
+ // src/transport/http.ts
2464
+ function detectUnauthorized(err, depth = 0) {
2465
+ if (!err || depth > 5) return false;
2466
+ if (err instanceof UnauthorizedError2) return true;
2467
+ if (err instanceof SdkHttpError && err.status === 401) return true;
2468
+ if (err instanceof Error) {
2469
+ if (err.cause) {
2470
+ if (detectUnauthorized(err.cause, depth + 1)) return true;
2471
+ }
2472
+ const data = err instanceof SdkError ? err.data : void 0;
2473
+ if (data?.cause && detectUnauthorized(data.cause, depth + 1)) return true;
2474
+ }
2475
+ return false;
2476
+ }
2477
+ function createMcpProxyFetch(logicalServerUrl, proxyUrl, baseFetch, serverId) {
2478
+ const logical = new URL(logicalServerUrl);
2479
+ const proxy = proxyUrl.replace(/\/$/, "");
2480
+ return async (input, init) => {
2481
+ const request = new Request(input, init);
2482
+ const requestUrl = new URL(request.url);
2483
+ const isMcpTransportRequest = requestUrl.origin === logical.origin && requestUrl.pathname === logical.pathname;
2484
+ if (!isMcpTransportRequest) {
2485
+ return baseFetch(request);
2486
+ }
2487
+ const headers = new Headers(request.headers);
2488
+ headers.set("X-Target-URL", request.url);
2489
+ if (serverId) headers.set("X-Server-Id", serverId);
2490
+ const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.clone().arrayBuffer();
2491
+ return baseFetch(
2492
+ new Request(proxy, {
2493
+ method: request.method,
2494
+ headers,
2495
+ body,
2496
+ signal: request.signal,
2497
+ redirect: "manual"
2498
+ })
2499
+ );
2500
+ };
2501
+ }
2502
+ var HttpConnector = class extends BaseConnector {
2503
+ baseUrl;
2504
+ headers;
2505
+ timeout;
2506
+ customFetch;
2507
+ clientInfo;
2508
+ protocolNegotiation;
2509
+ gatewayUrl;
2510
+ serverId;
2511
+ reconnectionOptions;
2512
+ transportType = null;
2513
+ streamableTransport = null;
2514
+ constructor(baseUrl, opts = {}) {
2515
+ super(opts);
2516
+ const originalUrl = baseUrl.replace(/\/$/, "");
2517
+ this.baseUrl = originalUrl;
2518
+ this.headers = { ...opts.headers ?? {} };
2519
+ this.gatewayUrl = opts.gatewayUrl;
2520
+ this.serverId = opts.serverId;
2521
+ if (opts.authToken) {
2522
+ this.headers.Authorization = `Bearer ${opts.authToken}`;
2523
+ }
2524
+ this.timeout = opts.timeout ?? 1e4;
2525
+ const baseFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
2526
+ this.customFetch = this.gatewayUrl ? createMcpProxyFetch(
2527
+ originalUrl,
2528
+ this.gatewayUrl,
2529
+ baseFetch,
2530
+ this.serverId
2531
+ ) : opts.fetch;
2532
+ this.clientInfo = opts.clientInfo ?? {
2533
+ name: "http-connector",
2534
+ version: "1.0.0"
2535
+ };
2536
+ this.protocolNegotiation = opts.protocolNegotiation ?? "auto";
2537
+ this.reconnectionOptions = opts.reconnectionOptions;
2538
+ }
2539
+ buildClientOptions() {
2540
+ return {
2541
+ ...this.opts.clientOptions || {},
2542
+ jsonSchemaValidator: this.opts.clientOptions?.jsonSchemaValidator ?? new DialectJsonSchemaValidator(),
2543
+ versionNegotiation: {
2544
+ // Allow a caller-supplied versionNegotiation in clientOptions to win.
2545
+ mode: this.protocolNegotiation,
2546
+ ...this.opts.clientOptions?.versionNegotiation ?? {}
2547
+ },
2548
+ listChanged: {
2549
+ tools: {
2550
+ autoRefresh: true,
2551
+ onChanged: (error, tools) => void this.handleListChanged(
2552
+ "notifications/tools/list_changed",
2553
+ error,
2554
+ tools
2555
+ )
2556
+ },
2557
+ resources: {
2558
+ autoRefresh: false,
2559
+ onChanged: (error) => void this.handleListChanged(
2560
+ "notifications/resources/list_changed",
2561
+ error
2562
+ )
2563
+ },
2564
+ prompts: {
2565
+ autoRefresh: false,
2566
+ onChanged: (error) => void this.handleListChanged(
2567
+ "notifications/prompts/list_changed",
2568
+ error
2569
+ )
2570
+ },
2571
+ ...this.opts.clientOptions?.listChanged ?? {}
2572
+ },
2573
+ capabilities: {
2574
+ ...this.opts.clientOptions?.capabilities || {},
2575
+ roots: { listChanged: true },
2576
+ ...this.opts.onSampling ? { sampling: {} } : {},
2577
+ ...this.opts.onElicitation ? { elicitation: { form: {}, url: {} } } : {}
2578
+ }
2579
+ };
2580
+ }
2581
+ // In v2 HTTP transport errors are thrown as SdkHttpError (subclass of
2582
+ // SdkError) with a numeric `.status` accessor, replacing v1's
2583
+ // StreamableHTTPError (which carried the status on `.code`).
2584
+ unwrapStreamableError(err) {
2585
+ if (err instanceof SdkHttpError) {
2586
+ return err;
2587
+ }
2588
+ if (err instanceof Error && err.cause instanceof SdkHttpError) {
2589
+ return err.cause;
2590
+ }
2591
+ return null;
2592
+ }
2593
+ classifyStreamableHttpFailure(err) {
2594
+ let fallbackReason = "Unknown error";
2595
+ let is401Error = false;
2596
+ let httpStatusCode;
2597
+ const streamableErr = this.unwrapStreamableError(err);
2598
+ if (streamableErr) {
2599
+ const status = streamableErr.status;
2600
+ is401Error = status === 401;
2601
+ httpStatusCode = status;
2602
+ if (status === 400 && streamableErr.message.includes("Missing session ID")) {
2603
+ fallbackReason = "Server requires session ID (FastMCP compatibility)";
2604
+ logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
2605
+ } else if (status === 404 || status === 405) {
2606
+ fallbackReason = `Server returned ${status} - server likely doesn't support streamable HTTP`;
2607
+ logger.debug(fallbackReason);
2608
+ } else {
2609
+ fallbackReason = `Server returned ${status}: ${streamableErr.message}`;
2610
+ logger.debug(fallbackReason);
2611
+ }
2612
+ return { fallbackReason, is401Error, httpStatusCode };
2613
+ }
2614
+ if (err instanceof Error) {
2615
+ const errorStr = err.toString();
2616
+ const errorMsg = err.message || "";
2617
+ is401Error = detectUnauthorized(err) || errorStr.includes("401") || errorMsg.includes("Unauthorized");
2618
+ if (errorStr.includes("Missing session ID") || errorStr.includes("Bad Request: Missing session ID") || errorMsg.includes("FastMCP session ID error")) {
2619
+ fallbackReason = "Server requires session ID (FastMCP compatibility)";
2620
+ logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
2621
+ } else if (errorStr.includes("405 Method Not Allowed") || errorStr.includes("404 Not Found")) {
2622
+ fallbackReason = "Server doesn't support streamable HTTP (405/404)";
2623
+ logger.debug(fallbackReason);
2624
+ } else {
2625
+ fallbackReason = `Streamable HTTP failed: ${err.message}`;
2626
+ logger.debug(fallbackReason);
2627
+ }
2628
+ }
2629
+ return { fallbackReason, is401Error, httpStatusCode };
2630
+ }
2631
+ /** Establish connection to the MCP implementation via streamable HTTP. */
2632
+ async connect() {
2633
+ if (this.connected) {
2634
+ logger.debug("Already connected to MCP implementation");
2635
+ return;
2636
+ }
2637
+ const baseUrl = this.baseUrl;
2638
+ logger.debug(`Connecting to MCP implementation via HTTP: ${baseUrl}`);
2639
+ try {
2640
+ await this.connectWithStreamableHttp(baseUrl);
2641
+ logger.debug("\u2705 Successfully connected via streamable HTTP");
2642
+ } catch (err) {
2643
+ logger.debug("Streamable HTTP connect failed", err);
2644
+ const { fallbackReason, is401Error, httpStatusCode } = this.classifyStreamableHttpFailure(err);
2645
+ await this.cleanupResources();
2646
+ if (is401Error) {
2647
+ logger.info("Authentication required");
2648
+ const authError = new Error("Authentication required");
2649
+ authError.code = 401;
2650
+ throw authError;
2651
+ }
2652
+ const finalError = new Error(
2653
+ `Could not connect via streamable HTTP: ${fallbackReason}`
2654
+ );
2655
+ if (httpStatusCode !== void 0) {
2656
+ Object.defineProperty(finalError, "code", {
2657
+ value: httpStatusCode,
2658
+ writable: false,
2659
+ enumerable: true,
2660
+ configurable: true
2661
+ });
2662
+ }
2663
+ throw finalError;
2664
+ }
2665
+ }
2666
+ /**
2667
+ * Tee an SSE response so v2 MRTR progress can be correlated even when the
2668
+ * upstream SDK does not carry the original callback to retry request IDs.
2669
+ */
2670
+ observeSseProgress(response) {
2671
+ if (!response.body || !response.headers.get("content-type")?.includes("text/event-stream")) {
2672
+ return response;
2673
+ }
2674
+ const [body, observed] = response.body.tee();
2675
+ void (async () => {
2676
+ const reader = observed.getReader();
2677
+ const decoder = new TextDecoder();
2678
+ let buffer = "";
2679
+ try {
2680
+ while (true) {
2681
+ const { done, value } = await reader.read();
2682
+ if (done) break;
2683
+ buffer += decoder.decode(value, { stream: true });
2684
+ const events = buffer.split(/\r?\n\r?\n/);
2685
+ buffer = events.pop() ?? "";
2686
+ for (const event of events) {
2687
+ for (const line of event.split(/\r?\n/)) {
2688
+ if (!line.startsWith("data:")) continue;
2689
+ try {
2690
+ const message = JSON.parse(line.slice(5).trim());
2691
+ if (message.method === "notifications/progress") {
2692
+ this.forwardRoundProgress(message.params);
2693
+ }
2694
+ } catch {
2695
+ }
2696
+ }
2697
+ }
2698
+ }
2699
+ } catch (error) {
2700
+ if (!(error instanceof DOMException && error.name === "AbortError")) {
2701
+ logger.debug("Progress observer stream ended:", error);
2702
+ }
2703
+ } finally {
2704
+ reader.releaseLock();
2705
+ }
2706
+ })();
2707
+ return new Response(body, {
2708
+ status: response.status,
2709
+ statusText: response.statusText,
2710
+ headers: response.headers
2711
+ });
2712
+ }
2713
+ async connectWithStreamableHttp(baseUrl) {
2714
+ try {
2715
+ logger.debug("[HttpConnector] Connecting with Streamable HTTP", {
2716
+ baseUrl,
2717
+ originalUrl: this.baseUrl,
2718
+ gatewayUrl: this.gatewayUrl || "none",
2719
+ authProviderUrl: this.opts.authProvider && "serverUrl" in this.opts.authProvider && typeof this.opts.authProvider.serverUrl === "string" ? this.opts.authProvider.serverUrl : "none",
2720
+ headers: this.headers
2721
+ });
2722
+ let markPushStreamReady;
2723
+ const pushStreamReady = new Promise((resolve) => {
2724
+ markPushStreamReady = resolve;
2725
+ });
2726
+ const baseFetch = this.customFetch ?? globalThis.fetch.bind(globalThis);
2727
+ const observedFetch = async (input, init) => {
2728
+ const response = await baseFetch(input, init);
2729
+ const method = init?.method ?? (input instanceof Request ? input.method : "GET");
2730
+ const requestHeaders = new Headers(
2731
+ input instanceof Request ? input.headers : void 0
2732
+ );
2733
+ new Headers(init?.headers).forEach((value, key) => {
2734
+ requestHeaders.set(key, value);
2735
+ });
2736
+ if (method.toUpperCase() === "GET" && response.ok && response.headers.get("content-type")?.includes("text/event-stream")) {
2737
+ markPushStreamReady?.();
2738
+ }
2739
+ return requestHeaders.get("mcp-method") === "subscriptions/listen" ? response : this.observeSseProgress(response);
2740
+ };
2741
+ const streamableTransport = new StreamableHTTPClientTransport2(
2742
+ new URL(baseUrl),
2743
+ {
2744
+ authProvider: this.opts.authProvider,
2745
+ // ← Pass OAuth provider to SDK
2746
+ fetch: observedFetch,
2747
+ requestInit: {
2748
+ headers: this.headers
2749
+ },
2750
+ reconnectionOptions: {
2751
+ maxReconnectionDelay: 3e4,
2752
+ initialReconnectionDelay: 1e3,
2753
+ reconnectionDelayGrowFactor: 1.5,
2754
+ maxRetries: 2,
2755
+ ...this.reconnectionOptions
2756
+ }
2757
+ // Don't pass sessionId - let the SDK generate it automatically during connect()
2758
+ }
2759
+ );
2760
+ let transport = streamableTransport;
2761
+ if (this.opts.wrapTransport) {
2762
+ const serverId = this.baseUrl;
2763
+ transport = this.opts.wrapTransport(
2764
+ transport,
2765
+ serverId
2766
+ );
2767
+ }
2768
+ const clientOptions = this.buildClientOptions();
2769
+ logger.debug(
2770
+ `Creating Client with capabilities:`,
2771
+ JSON.stringify(clientOptions.capabilities, null, 2)
2772
+ );
2773
+ this.client = new Client(this.clientInfo, clientOptions);
2774
+ this.setupRootsHandler();
2775
+ this.setupSamplingHandler();
2776
+ this.setupElicitationHandler();
2777
+ logger.debug(
2778
+ "Roots/sampling/elicitation handlers registered before connect"
2779
+ );
2780
+ try {
2781
+ let connectTimeout;
2782
+ await Promise.race([
2783
+ this.client.connect(transport),
2784
+ new Promise((_, reject) => {
2785
+ connectTimeout = setTimeout(
2786
+ () => reject(
2787
+ new Error(`MCP connection timed out after ${this.timeout}ms`)
2788
+ ),
2789
+ this.timeout
2790
+ );
2791
+ })
2792
+ ]).finally(() => {
2793
+ if (connectTimeout !== void 0) clearTimeout(connectTimeout);
2794
+ });
2795
+ if ((this.client.getProtocolEra?.() ?? "legacy") === "legacy" && streamableTransport.sessionId) {
2796
+ let readinessTimeout;
2797
+ const attached = await Promise.race([
2798
+ pushStreamReady.then(() => true),
2799
+ new Promise(
2800
+ (resolve) => readinessTimeout = setTimeout(
2801
+ () => resolve(false),
2802
+ Math.min(this.timeout, 5e3)
2803
+ )
2804
+ )
2805
+ ]);
2806
+ if (readinessTimeout) clearTimeout(readinessTimeout);
2807
+ if (!attached) {
2808
+ logger.warn(
2809
+ "Legacy server push stream did not attach before connect completed"
2810
+ );
2811
+ }
2812
+ }
2813
+ const sessionId2 = streamableTransport.sessionId;
2814
+ if (sessionId2) {
2815
+ logger.debug(`Session ID obtained: ${sessionId2}`);
2816
+ }
2817
+ } catch (connectErr) {
2818
+ if (connectErr instanceof Error) {
2819
+ const errMsg = connectErr.message || connectErr.toString();
2820
+ if (errMsg.includes("Missing session ID") || errMsg.includes("Bad Request: Missing session ID") || errMsg.includes("Mcp-Session-Id header is required")) {
2821
+ const wrappedError = new Error(
2822
+ `Session ID error: ${errMsg}. The SDK should automatically extract session ID from initialize response.`
2823
+ );
2824
+ wrappedError.cause = connectErr;
2825
+ throw wrappedError;
2826
+ }
2827
+ }
2828
+ throw connectErr;
2829
+ }
2830
+ this.streamableTransport = streamableTransport;
2831
+ this.connectionManager = {
2832
+ stop: async () => {
2833
+ if (this.streamableTransport) {
2834
+ try {
2835
+ await this.streamableTransport.close();
2836
+ } catch (e) {
2837
+ logger.warn(`Error closing Streamable HTTP transport: ${e}`);
2838
+ } finally {
2839
+ this.streamableTransport = null;
2840
+ }
2841
+ }
2842
+ }
2843
+ };
2844
+ this.connected = true;
2845
+ this.transportType = "streamable-http";
2846
+ this.setupNotificationHandler();
2847
+ logger.debug(
2848
+ `Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`
2849
+ );
2850
+ this.trackConnectorInit({
2851
+ serverUrl: this.baseUrl,
2852
+ publicIdentifier: `${this.baseUrl} (streamable-http)`
2853
+ });
2854
+ } catch (err) {
2855
+ await this.cleanupResources();
2856
+ throw err;
2857
+ }
2858
+ }
2859
+ get publicIdentifier() {
2860
+ return {
2861
+ type: "http",
2862
+ url: this.baseUrl,
2863
+ transport: this.transportType || "unknown",
2864
+ protocolEra: this.protocolEra ?? "unknown"
2865
+ };
2866
+ }
2867
+ /** Get the active transport type (`streamable-http` once connected). */
2868
+ getTransportType() {
2869
+ return this.transportType;
2870
+ }
2871
+ // Send the streamable-HTTP DELETE *before* super.cleanupResources() invokes
2872
+ // client.close(). The SDK's transport.close() aborts the shared abort
2873
+ // controller, and terminateSession()'s DELETE fetch reuses that signal —
2874
+ // running it after close() rejects immediately with AbortError.
2875
+ async cleanupResources() {
2876
+ if (this.streamableTransport && this.protocolEra !== "modern") {
2877
+ let terminationTimeout;
2878
+ try {
2879
+ const terminated = await Promise.race([
2880
+ this.streamableTransport.terminateSession().then(() => true),
2881
+ new Promise(
2882
+ (resolve) => terminationTimeout = setTimeout(
2883
+ () => resolve(false),
2884
+ Math.min(this.timeout, 5e3)
2885
+ )
2886
+ )
2887
+ ]);
2888
+ if (!terminated) {
2889
+ logger.debug(
2890
+ "Timed out terminating legacy HTTP session; closing transport"
2891
+ );
2892
+ }
2893
+ } catch (e) {
2894
+ logger.debug(`Error terminating Streamable HTTP session: ${e}`);
2895
+ } finally {
2896
+ if (terminationTimeout) clearTimeout(terminationTimeout);
2897
+ }
2898
+ }
2899
+ await super.cleanupResources();
2900
+ }
2901
+ };
2902
+
2903
+ // src/core/config.ts
2904
+ function resolveCallbacks(perServer, globalDefaults) {
2905
+ const pickSampling = perServer?.onSampling ?? globalDefaults?.onSampling;
2906
+ const pickElicitation = perServer?.onElicitation ?? globalDefaults?.onElicitation;
2907
+ const pickNotification = perServer?.onNotification ?? globalDefaults?.onNotification;
2908
+ return {
2909
+ onSampling: pickSampling,
2910
+ onElicitation: pickElicitation,
2911
+ onNotification: pickNotification
2912
+ };
2913
+ }
2914
+ function shouldAutoProvisionOAuth(serverConfig) {
2915
+ if (!("url" in serverConfig) || typeof serverConfig.url !== "string") {
2916
+ return false;
2917
+ }
2918
+ if (serverConfig.authProvider) return false;
2919
+ if (serverConfig.authToken) return false;
2920
+ if (serverConfig.oauth === false) return false;
2921
+ const headers = serverConfig.headers;
2922
+ if (headers) {
2923
+ for (const key of Object.keys(headers)) {
2924
+ if (key.toLowerCase() === "authorization") return false;
2925
+ }
2926
+ }
2927
+ return true;
2928
+ }
2929
+ function getDefaultClientInfo() {
2930
+ return {
2931
+ name: "mcp-use",
2932
+ title: "mcp-use",
2933
+ version: getPackageVersion(),
2934
+ description: "mcp-use is a complete TypeScript framework for building and using MCP",
2935
+ icons: [
2936
+ {
2937
+ src: "https://mcp-use.com/logo.png"
2938
+ }
2939
+ ],
2940
+ websiteUrl: "https://mcp-use.com"
2941
+ };
2942
+ }
2943
+ function normalizeClientInfo(input) {
2944
+ const fallback = getDefaultClientInfo();
2945
+ if (!input || typeof input !== "object") return fallback;
2946
+ const ci = input;
2947
+ if (!ci.name || !ci.version) return fallback;
2948
+ return { ...fallback, ...ci };
2949
+ }
2950
+ function resolveClientOptions(clientOptions) {
2951
+ const capabilities = clientOptions?.capabilities;
2952
+ if (!capabilities || capabilities.views !== true) return clientOptions;
2953
+ const { views: _views, ...capsWithoutViews } = capabilities;
2954
+ const extensions = capsWithoutViews.extensions && typeof capsWithoutViews.extensions === "object" && !Array.isArray(capsWithoutViews.extensions) ? { ...capsWithoutViews.extensions } : {};
2955
+ return {
2956
+ ...clientOptions,
2957
+ capabilities: {
2958
+ ...capsWithoutViews,
2959
+ extensions: {
2960
+ ...extensions,
2961
+ "io.modelcontextprotocol/ui": {
2962
+ mimeTypes: ["text/html;profile=mcp-app"]
2963
+ }
2964
+ }
2965
+ }
2966
+ };
2967
+ }
2968
+ function createConnectorFromConfig(serverConfig, connectorOptions) {
2969
+ const clientInfo = normalizeClientInfo(serverConfig.clientInfo);
2970
+ if ("command" in serverConfig && "args" in serverConfig) {
2971
+ throw new Error(
2972
+ "Stdio connector is not supported in this environment. Stdio connections require Node.js and are only available in the Node.js MCPClient."
2973
+ );
2974
+ }
2975
+ if ("url" in serverConfig) {
2976
+ return new HttpConnector(serverConfig.url, {
2977
+ headers: serverConfig.headers,
2978
+ fetch: serverConfig.fetch,
2979
+ authToken: serverConfig.authToken,
2980
+ authProvider: serverConfig.authProvider,
2981
+ protocolNegotiation: serverConfig.protocolNegotiation,
2982
+ timeout: serverConfig.timeout,
2983
+ roots: serverConfig.roots,
2984
+ clientOptions: resolveClientOptions(serverConfig.clientOptions),
2985
+ defaultRequestOptions: serverConfig.defaultRequestOptions,
2986
+ clientInfo,
2987
+ ...connectorOptions
2988
+ });
2989
+ }
2990
+ throw new Error("Cannot determine connector type from config");
2991
+ }
2992
+
2993
+ // src/core/session.ts
2994
+ var MCPConnection = class {
2995
+ /**
2996
+ * The underlying connector managing the transport layer.
2997
+ * This is the Stdio, HTTP, or WebSocket connector handling actual communication.
2998
+ */
2999
+ connector;
3000
+ /**
3001
+ * Whether to automatically connect when initializing.
3002
+ * @internal
3003
+ */
3004
+ autoConnect;
3005
+ /**
3006
+ * Creates a new MCP session.
3007
+ *
3008
+ * @param connector - The connector to use for communication (Stdio, HTTP, WebSocket)
3009
+ * @param autoConnect - Whether to automatically connect during initialization (default: true)
3010
+ *
3011
+ * @example
3012
+ * ```typescript
3013
+ * const connector = new HttpConnector({ url: 'http://localhost:3000/mcp' });
3014
+ * const session = new MCPSession(connector);
3015
+ * await session.initialize(); // Auto-connects and initializes
3016
+ * ```
3017
+ *
3018
+ * @example
3019
+ * ```typescript
3020
+ * // Manual connection control
3021
+ * const session = new MCPSession(connector, false);
3022
+ * await session.connect();
3023
+ * await session.initialize();
3024
+ * ```
3025
+ */
3026
+ constructor(connector, autoConnect = true) {
3027
+ this.connector = connector;
3028
+ this.autoConnect = autoConnect;
3029
+ }
3030
+ /**
3031
+ * Establishes the connection to the MCP server.
3032
+ *
3033
+ * This method starts the underlying transport (spawns process for Stdio,
3034
+ * opens WebSocket, etc.) but does not perform the MCP initialization
3035
+ * handshake. Call {@link initialize} after connecting.
3036
+ *
3037
+ * @returns Promise that resolves when connected
3038
+ *
3039
+ * @example
3040
+ * ```typescript
3041
+ * await session.connect();
3042
+ * await session.initialize();
3043
+ * ```
3044
+ *
3045
+ * @see {@link initialize} for performing the MCP handshake
3046
+ * @see {@link disconnect} for closing the connection
3047
+ */
3048
+ async connect() {
3049
+ await this.connector.connect();
3050
+ }
3051
+ /**
3052
+ * Closes the connection to the MCP server.
3053
+ *
3054
+ * This method gracefully shuts down the transport and cleans up resources.
3055
+ * After disconnecting, the session cannot be used until reconnected.
3056
+ *
3057
+ * @returns Promise that resolves when disconnected
3058
+ *
3059
+ * @example
3060
+ * ```typescript
3061
+ * await session.disconnect();
3062
+ * console.log('Session closed');
3063
+ * ```
3064
+ *
3065
+ * @see {@link connect} for establishing connections
3066
+ */
3067
+ async disconnect() {
3068
+ await this.connector.disconnect();
3069
+ }
3070
+ /**
3071
+ * Initializes the MCP session with the server.
3072
+ *
3073
+ * This method performs the MCP initialization handshake, exchanging
3074
+ * capabilities and metadata with the server. If `autoConnect` is true
3075
+ * and the session is not yet connected, it will connect first.
3076
+ *
3077
+ * After initialization, you can list and call tools, read resources, etc.
3078
+ *
3079
+ * @returns Promise that resolves when initialized
3080
+ *
3081
+ * @example
3082
+ * ```typescript
3083
+ * const session = await client.createSession('my-server', false);
3084
+ * await session.connect();
3085
+ * await session.initialize();
3086
+ * // Now ready to use
3087
+ * const tools = await session.listTools();
3088
+ * ```
3089
+ *
3090
+ * @see {@link connect} for establishing the connection first
3091
+ */
3092
+ async initialize() {
3093
+ if (!this.isConnected && this.autoConnect) {
3094
+ await this.connect();
3095
+ }
3096
+ await this.connector.initialize();
3097
+ }
3098
+ /**
3099
+ * Checks if the session is currently connected to the server.
3100
+ *
3101
+ * @returns True if connected, false otherwise
3102
+ *
3103
+ * @example
3104
+ * ```typescript
3105
+ * if (session.isConnected) {
3106
+ * const tools = await session.listTools();
3107
+ * }
3108
+ * ```
3109
+ */
3110
+ get isConnected() {
3111
+ return this.connector && this.connector.isClientConnected;
3112
+ }
3113
+ /**
3114
+ * Register an event handler for session events
3115
+ *
3116
+ * @param event - The event type to listen for
3117
+ * @param handler - The handler function to call when the event occurs
3118
+ *
3119
+ * @example
3120
+ * ```typescript
3121
+ * session.on("notification", async (notification) => {
3122
+ * console.log(`Received: ${notification.method}`, notification.params);
3123
+ *
3124
+ * if (notification.method === "notifications/tools/list_changed") {
3125
+ * // Refresh tools list
3126
+ * }
3127
+ * });
3128
+ * ```
3129
+ */
3130
+ on(event, handler) {
3131
+ if (event === "notification") {
3132
+ this.connector.onNotification(handler);
3133
+ }
3134
+ }
3135
+ /**
3136
+ * Set roots and notify the server.
3137
+ * Roots represent directories or files that the client has access to.
3138
+ *
3139
+ * @param roots - Array of Root objects with `uri` (must start with "file://") and optional `name`
3140
+ *
3141
+ * @deprecated Roots are a v1 compatibility feature and are not part of the
3142
+ * sessionless v2 protocol.
3143
+ *
3144
+ * @example
3145
+ * ```typescript
3146
+ * await session.setRoots([
3147
+ * { uri: "file:///home/user/project", name: "My Project" },
3148
+ * { uri: "file:///home/user/data" }
3149
+ * ]);
3150
+ * ```
3151
+ */
3152
+ async setRoots(roots) {
3153
+ return this.connector.setRoots(roots);
3154
+ }
3155
+ /**
3156
+ * Gets the current roots advertised to the server.
3157
+ *
3158
+ * Roots represent directories or files that the client has provided access to.
3159
+ * The server may use this information to scope its operations.
3160
+ *
3161
+ * @returns Array of Root objects
3162
+ *
3163
+ * @example
3164
+ * ```typescript
3165
+ * const roots = session.getRoots();
3166
+ * console.log(`Current roots: ${roots.map(r => r.uri).join(', ')}`);
3167
+ * ```
3168
+ *
3169
+ * @see {@link setRoots} for updating roots
3170
+ */
3171
+ getRoots() {
3172
+ return this.connector.getRoots();
3173
+ }
3174
+ /**
3175
+ * Get the cached list of tools from the server.
3176
+ *
3177
+ * @returns Array of available tools
3178
+ *
3179
+ * @example
3180
+ * ```typescript
3181
+ * const tools = session.tools;
3182
+ * console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
3183
+ * ```
3184
+ */
3185
+ get tools() {
3186
+ return this.connector.tools;
3187
+ }
3188
+ /**
3189
+ * List all available tools from the MCP server.
3190
+ * This method fetches fresh tools from the server, unlike the `tools` getter which returns cached tools.
3191
+ *
3192
+ * @param options - Optional request options
3193
+ * @returns Array of available tools
3194
+ *
3195
+ * @example
3196
+ * ```typescript
3197
+ * const tools = await session.listTools();
3198
+ * console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
3199
+ * ```
3200
+ */
3201
+ async listTools(options) {
3202
+ return this.connector.listTools(options);
3203
+ }
3204
+ /**
3205
+ * Get the server capabilities advertised during initialization.
3206
+ *
3207
+ * @returns Server capabilities object
3208
+ */
3209
+ get serverCapabilities() {
3210
+ return this.connector.serverCapabilities;
3211
+ }
3212
+ /**
3213
+ * Get the server information (name and version).
3214
+ *
3215
+ * @returns Server info object or null if not available
3216
+ */
3217
+ get serverInfo() {
3218
+ return this.connector.serverInfo;
3219
+ }
3220
+ /**
3221
+ * The negotiated protocol era for this session's connection:
3222
+ * `"legacy"` (2025-era) or `"modern"` (2026-07-28-era).
3223
+ * `undefined` before the connection has negotiated.
3224
+ */
3225
+ get protocolEra() {
3226
+ return this.connector.protocolEra;
3227
+ }
3228
+ /** The negotiated protocol version string for this session's connection. */
3229
+ get negotiatedProtocolVersion() {
3230
+ return this.connector.negotiatedProtocolVersion;
3231
+ }
3232
+ /**
3233
+ * Normalized server metadata for this ready connection.
3234
+ *
3235
+ * @throws {Error} When called before protocol negotiation completes.
3236
+ */
3237
+ get info() {
3238
+ const protocolEra = this.protocolEra;
3239
+ const protocolVersion = this.negotiatedProtocolVersion;
3240
+ const server = this.serverInfo;
3241
+ if (!protocolEra || !protocolVersion || !server) {
3242
+ throw new Error("MCP connection is not initialized");
3243
+ }
3244
+ const capabilities = this.serverCapabilities;
3245
+ const extensions = capabilities.extensions && typeof capabilities.extensions === "object" && !Array.isArray(capabilities.extensions) ? capabilities.extensions : {};
3246
+ return {
3247
+ protocolEra,
3248
+ protocolVersion,
3249
+ server,
3250
+ capabilities,
3251
+ instructions: this.connector.instructions,
3252
+ extensions
3253
+ };
3254
+ }
3255
+ /**
3256
+ * Whether the server advertised a named MCP capability.
3257
+ *
3258
+ * @param capability - A top-level capability name such as `"tools"` or
3259
+ * `"resources"`.
3260
+ */
3261
+ supports(capability) {
3262
+ return capability in this.serverCapabilities;
3263
+ }
3264
+ /**
3265
+ * Call a tool on the server.
3266
+ *
3267
+ * @param name - Name of the tool to call
3268
+ * @param args - Arguments to pass to the tool (defaults to empty object)
3269
+ * @param options - Optional request options (timeout, progress handlers, etc.)
3270
+ * @returns Result from the tool execution
3271
+ *
3272
+ * @example
3273
+ * ```typescript
3274
+ * const result = await session.callTool("add", { a: 5, b: 3 });
3275
+ * console.log(`Result: ${result.content[0].text}`);
3276
+ * ```
3277
+ */
3278
+ async callTool(name, args = {}, options) {
3279
+ return this.connector.callTool(name, args, options);
3280
+ }
3281
+ /**
3282
+ * List resources from the server with optional pagination.
3283
+ *
3284
+ * @param cursor - Optional cursor for pagination
3285
+ * @param options - Request options
3286
+ * @returns Resource list with optional nextCursor for pagination
3287
+ *
3288
+ * @example
3289
+ * ```typescript
3290
+ * const result = await session.listResources();
3291
+ * console.log(`Found ${result.resources.length} resources`);
3292
+ * ```
3293
+ */
3294
+ async listResources(cursor, options) {
3295
+ return this.connector.listResources(cursor, options);
3296
+ }
3297
+ /**
3298
+ * List all resources from the server, automatically handling pagination.
3299
+ *
3300
+ * @param options - Request options
3301
+ * @returns Complete list of all resources
3302
+ *
3303
+ * @example
3304
+ * ```typescript
3305
+ * const result = await session.listAllResources();
3306
+ * console.log(`Total resources: ${result.resources.length}`);
3307
+ * ```
3308
+ */
3309
+ async listAllResources(options) {
3310
+ return this.connector.listAllResources(options);
3311
+ }
3312
+ /**
3313
+ * List resource templates from the server.
3314
+ *
3315
+ * @param options - Request options
3316
+ * @returns List of available resource templates
3317
+ *
3318
+ * @example
3319
+ * ```typescript
3320
+ * const result = await session.listResourceTemplates();
3321
+ * console.log(`Available templates: ${result.resourceTemplates.length}`);
3322
+ * ```
3323
+ */
3324
+ async listResourceTemplates(options) {
3325
+ return this.connector.listResourceTemplates(options);
3326
+ }
3327
+ /**
3328
+ * Request completion suggestions for a prompt or resource template argument.
3329
+ *
3330
+ * @param params - Completion request parameters
3331
+ * @param options - Request options
3332
+ * @returns Completion suggestions from the server
3333
+ *
3334
+ * @example
3335
+ * ```typescript
3336
+ * // Complete a prompt argument
3337
+ * const result = await session.complete({
3338
+ * ref: { type: "ref/prompt", name: "my-prompt" },
3339
+ * argument: { name: "language", value: "py" }
3340
+ * });
3341
+ * console.log(result.completion.values); // ["python"]
3342
+ * ```
3343
+ */
3344
+ async complete(params, options) {
3345
+ return this.connector.complete(params, options);
3346
+ }
3347
+ /**
3348
+ * Read a resource by URI.
3349
+ *
3350
+ * @param uri - URI of the resource to read
3351
+ * @param options - Request options
3352
+ * @returns Resource content
3353
+ *
3354
+ * @example
3355
+ * ```typescript
3356
+ * const resource = await session.readResource("file:///path/to/file.txt");
3357
+ * console.log(resource.contents);
3358
+ * ```
3359
+ */
3360
+ async readResource(uri, options) {
3361
+ return this.connector.readResource(uri, options);
3362
+ }
3363
+ /**
3364
+ * Subscribe to resource updates.
3365
+ *
3366
+ * @param uri - URI of the resource to subscribe to
3367
+ * @param options - Request options
3368
+ *
3369
+ * @example
3370
+ * ```typescript
3371
+ * await session.subscribeToResource("file:///path/to/file.txt");
3372
+ * // Now you'll receive notifications when this resource changes
3373
+ * ```
3374
+ */
3375
+ async subscribeToResource(uri, options) {
3376
+ return this.connector.subscribeToResource(uri, options);
3377
+ }
3378
+ /**
3379
+ * Unsubscribe from resource updates.
3380
+ *
3381
+ * @param uri - URI of the resource to unsubscribe from
3382
+ * @param options - Request options
3383
+ *
3384
+ * @example
3385
+ * ```typescript
3386
+ * await session.unsubscribeFromResource("file:///path/to/file.txt");
3387
+ * ```
3388
+ */
3389
+ async unsubscribeFromResource(uri, options) {
3390
+ return this.connector.unsubscribeFromResource(uri, options);
3391
+ }
3392
+ /**
3393
+ * List available prompts from the server.
3394
+ *
3395
+ * @returns List of available prompts
3396
+ *
3397
+ * @example
3398
+ * ```typescript
3399
+ * const result = await session.listPrompts();
3400
+ * console.log(`Available prompts: ${result.prompts.length}`);
3401
+ * ```
3402
+ */
3403
+ async listPrompts() {
3404
+ return this.connector.listPrompts();
3405
+ }
3406
+ /**
3407
+ * Get a specific prompt with arguments.
3408
+ *
3409
+ * @param name - Name of the prompt to get
3410
+ * @param args - Arguments for the prompt
3411
+ * @returns Prompt result
3412
+ *
3413
+ * @example
3414
+ * ```typescript
3415
+ * const prompt = await session.getPrompt("greeting", { name: "Alice" });
3416
+ * console.log(prompt.messages);
3417
+ * ```
3418
+ */
3419
+ async getPrompt(name, args) {
3420
+ return this.connector.getPrompt(name, args);
3421
+ }
3422
+ /**
3423
+ * Send a raw request through the client.
3424
+ *
3425
+ * @param method - MCP method name
3426
+ * @param params - Request parameters
3427
+ * @param options - Request options
3428
+ * @returns Response from the server
3429
+ *
3430
+ * @example
3431
+ * ```typescript
3432
+ * const result = await session.request("custom/method", { key: "value" });
3433
+ * ```
3434
+ */
3435
+ async request(method, params = null, options) {
3436
+ return this.connector.request(method, params, options);
3437
+ }
3438
+ };
3439
+
3440
+ // src/core/base.ts
3441
+ function isOAuthClientProvider(provider) {
3442
+ return !!provider && typeof provider === "object" && "redirectUrl" in provider && "clientMetadata" in provider;
3443
+ }
3444
+ var BaseMCPClient = class {
3445
+ /**
3446
+ * Internal configuration object containing MCP server definitions.
3447
+ * @protected
3448
+ */
3449
+ config = {};
3450
+ /**
3451
+ * Map of server names to their active sessions.
3452
+ * @protected
3453
+ */
3454
+ sessions = {};
3455
+ /**
3456
+ * List of server names that have active sessions.
3457
+ * This array is kept in sync with the sessions map and can be used
3458
+ * to iterate over active connections.
3459
+ *
3460
+ * @example
3461
+ * ```typescript
3462
+ * console.log(`Active servers: ${client.activeSessions.join(', ')}`);
3463
+ * ```
3464
+ */
3465
+ activeSessions = [];
3466
+ /**
3467
+ * Creates a new BaseMCPClient instance.
3468
+ *
3469
+ * @param config - Optional configuration object with MCP server definitions
3470
+ *
3471
+ * @example
3472
+ * ```typescript
3473
+ * const client = new MCPClient({
3474
+ * mcpServers: {
3475
+ * 'example': {
3476
+ * command: 'node',
3477
+ * args: ['server.js']
3478
+ * }
3479
+ * }
3480
+ * });
3481
+ * ```
3482
+ */
3483
+ constructor(config) {
3484
+ if (config) {
3485
+ this.config = config;
3486
+ }
3487
+ }
3488
+ /**
3489
+ * Creates a client instance from a configuration dictionary.
3490
+ *
3491
+ * This static factory method must be implemented by concrete subclasses
3492
+ * to provide proper type information and platform-specific initialization.
3493
+ *
3494
+ * @param _cfg - Configuration dictionary
3495
+ * @returns Client instance
3496
+ * @throws {Error} If called on the base class instead of a concrete implementation
3497
+ *
3498
+ * @example
3499
+ * ```typescript
3500
+ * const client = MCPClient.fromDict({
3501
+ * mcpServers: {
3502
+ * 'my-server': { command: 'node', args: ['server.js'] }
3503
+ * }
3504
+ * });
3505
+ * ```
3506
+ */
3507
+ static fromDict(_cfg) {
3508
+ throw new Error("fromDict must be implemented by concrete class");
3509
+ }
3510
+ /**
3511
+ * Adds a new MCP server configuration to the client.
3512
+ *
3513
+ * This method adds or updates a server configuration dynamically without
3514
+ * needing to restart the client. The server can then be used to create
3515
+ * new sessions.
3516
+ *
3517
+ * @param name - Unique name for the server
3518
+ * @param serverConfig - Server configuration object (connector type, command, args, etc.)
3519
+ *
3520
+ * @example
3521
+ * ```typescript
3522
+ * client.addServer('new-server', {
3523
+ * command: 'python',
3524
+ * args: ['server.py']
3525
+ * });
3526
+ *
3527
+ * // Now you can create a session
3528
+ * const session = await client.createSession('new-server');
3529
+ * ```
3530
+ *
3531
+ * @see {@link removeServer} for removing servers
3532
+ * @see {@link getServerConfig} for retrieving configurations
3533
+ */
3534
+ addServer(name, serverConfig) {
3535
+ this.config.mcpServers = this.config.mcpServers || {};
3536
+ this.config.mcpServers[name] = serverConfig;
3537
+ trackClientAddServer(name, serverConfig);
3538
+ }
3539
+ /**
3540
+ * Removes an MCP server configuration from the client.
3541
+ *
3542
+ * This method removes a server configuration and cleans up any active
3543
+ * sessions associated with that server. If there's an active session,
3544
+ * it will be removed from the active sessions list.
3545
+ *
3546
+ * @param name - Name of the server to remove
3547
+ *
3548
+ * @example
3549
+ * ```typescript
3550
+ * // Remove a server configuration
3551
+ * await client.removeServer('old-server');
3552
+ *
3553
+ * // The server name will no longer appear in getServerNames()
3554
+ * console.log(client.getServerNames()); // 'old-server' is gone
3555
+ * ```
3556
+ *
3557
+ * @see {@link addServer} for adding servers
3558
+ * @see {@link closeSession} for properly closing sessions before removal
3559
+ */
3560
+ async removeServer(name) {
3561
+ if (!this.config.mcpServers?.[name]) return;
3562
+ await this.closeSession(name);
3563
+ delete this.config.mcpServers[name];
3564
+ trackClientRemoveServer(name);
3565
+ }
3566
+ /**
3567
+ * Gets the names of all configured MCP servers.
3568
+ *
3569
+ * @returns Array of server names defined in the configuration
3570
+ *
3571
+ * @example
3572
+ * ```typescript
3573
+ * const serverNames = client.getServerNames();
3574
+ * console.log(`Configured servers: ${serverNames.join(', ')}`);
3575
+ *
3576
+ * // Create sessions for all servers
3577
+ * for (const name of serverNames) {
3578
+ * await client.createSession(name);
3579
+ * }
3580
+ * ```
3581
+ *
3582
+ * @see {@link activeSessions} for servers with active sessions
3583
+ */
3584
+ getServerNames() {
3585
+ return Object.keys(this.config.mcpServers ?? {});
3586
+ }
3587
+ /**
3588
+ * Gets the configuration for a specific MCP server.
3589
+ *
3590
+ * @param name - Name of the server
3591
+ * @returns Server configuration object, or undefined if not found
3592
+ *
3593
+ * @example
3594
+ * ```typescript
3595
+ * const config = client.getServerConfig('my-server');
3596
+ * if (config) {
3597
+ * console.log(`Command: ${config.command}`);
3598
+ * console.log(`Args: ${config.args.join(' ')}`);
3599
+ * }
3600
+ * ```
3601
+ *
3602
+ * @see {@link getConfig} for retrieving the entire configuration
3603
+ */
3604
+ getServerConfig(name) {
3605
+ return this.config.mcpServers?.[name];
3606
+ }
3607
+ /**
3608
+ * Gets the complete client configuration.
3609
+ *
3610
+ * @returns Complete configuration object including all server definitions
3611
+ *
3612
+ * @example
3613
+ * ```typescript
3614
+ * const config = client.getConfig();
3615
+ * console.log(`Total servers: ${Object.keys(config.mcpServers).length}`);
3616
+ * ```
3617
+ *
3618
+ * @see {@link getServerConfig} for retrieving individual server configurations
3619
+ */
3620
+ getConfig() {
3621
+ return this.config ?? {};
3622
+ }
3623
+ /**
3624
+ * Creates a new session for connecting to an MCP server.
3625
+ *
3626
+ * @deprecated Use {@link connect}; modern MCP servers are sessionless.
3627
+ *
3628
+ * This method initializes a connection to the specified server using the
3629
+ * configuration provided during client construction. Sessions manage the
3630
+ * lifecycle of connections and provide methods for calling tools, listing
3631
+ * resources, and more.
3632
+ *
3633
+ * If a session already exists for the server, it will be replaced with a new one.
3634
+ *
3635
+ * @param serverName - The name of the server as defined in the client configuration
3636
+ * @param autoInitialize - Whether to automatically initialize the session (default: true)
3637
+ * @returns A promise that resolves to the created MCPSession instance
3638
+ * @throws {Error} If the server is not found in the configuration
3639
+ *
3640
+ * @example
3641
+ * ```typescript
3642
+ * // Create and initialize a session
3643
+ * const session = await client.createSession('my-server');
3644
+ * const tools = await session.listTools();
3645
+ *
3646
+ * // Create without auto-initialization
3647
+ * const session = await client.createSession('my-server', false);
3648
+ * await session.connect();
3649
+ * await session.initialize();
3650
+ * ```
3651
+ *
3652
+ * @see {@link MCPSession} for session management methods
3653
+ * @see {@link closeSession} for closing sessions
3654
+ * @see {@link getSession} for retrieving existing sessions
3655
+ */
3656
+ async createSession(serverName, autoInitialize = true) {
3657
+ const servers = this.config.mcpServers ?? {};
3658
+ if (Object.keys(servers).length === 0) {
3659
+ logger.warn("No MCP servers defined in config");
3660
+ }
3661
+ if (!servers[serverName]) {
3662
+ throw new Error(`Server '${serverName}' not found in config`);
3663
+ }
3664
+ let serverConfig = { ...servers[serverName] };
3665
+ let oauthProvider;
3666
+ if (shouldAutoProvisionOAuth(serverConfig)) {
3667
+ const oauthOptions = serverConfig.oauth === false ? void 0 : serverConfig.oauth ?? {};
3668
+ oauthProvider = await this.createDefaultOAuthProvider(
3669
+ serverConfig.url,
3670
+ oauthOptions
3671
+ );
3672
+ serverConfig = {
3673
+ ...serverConfig,
3674
+ authProvider: oauthProvider
3675
+ };
3676
+ } else if ("authProvider" in serverConfig && serverConfig.authProvider && isOAuthClientProvider(serverConfig.authProvider)) {
3677
+ oauthProvider = serverConfig.authProvider;
3678
+ }
3679
+ const openSession = async () => {
3680
+ const connector = await Promise.resolve(
3681
+ this.createConnectorFromConfig(serverConfig)
3682
+ );
3683
+ const session2 = new MCPConnection(connector);
3684
+ if (autoInitialize) {
3685
+ await session2.initialize();
3686
+ }
3687
+ return session2;
3688
+ };
3689
+ let session;
3690
+ try {
3691
+ session = await openSession();
3692
+ } catch (err) {
3693
+ const httpConfig = serverConfig;
3694
+ if (!autoInitialize || !oauthProvider || !("url" in httpConfig) || !isUnauthorized(err)) {
3695
+ throw err;
3696
+ }
3697
+ if (oauthProvider.preventAutoAuth) {
3698
+ throw err;
3699
+ }
3700
+ logger.info(
3701
+ `[MCPClient] Unauthorized connecting to '${serverName}'; completing OAuth\u2026`
3702
+ );
3703
+ await completeOAuthFlow(oauthProvider, httpConfig.url);
3704
+ session = await openSession();
3705
+ }
3706
+ this.sessions[serverName] = session;
3707
+ if (!this.activeSessions.includes(serverName)) {
3708
+ this.activeSessions.push(serverName);
3709
+ }
3710
+ return session;
3711
+ }
3712
+ /**
3713
+ * Connect to a configured MCP server and return a ready, protocol-neutral
3714
+ * connection.
3715
+ *
3716
+ * The returned connection represents either a legacy sessionful server or a
3717
+ * modern sessionless server uniformly. Inspect {@link MCPConnection.info} for
3718
+ * the negotiated protocol version and normalized server metadata.
3719
+ *
3720
+ * @param serverName - The configured server name.
3721
+ */
3722
+ async connect(serverName) {
3723
+ return this.createSession(serverName);
3724
+ }
3725
+ /**
3726
+ * Creates sessions for all configured MCP servers.
3727
+ *
3728
+ * This is a convenience method that iterates through all servers in the
3729
+ * configuration and creates a session for each one. Sessions are created
3730
+ * sequentially to avoid overwhelming the system.
3731
+ *
3732
+ * @param autoInitialize - Whether to automatically initialize each session (default: true)
3733
+ * @returns A promise that resolves to a map of server names to sessions
3734
+ *
3735
+ * @example
3736
+ * ```typescript
3737
+ * // Create sessions for all configured servers
3738
+ * const sessions = await client.createAllSessions();
3739
+ * console.log(`Created ${Object.keys(sessions).length} sessions`);
3740
+ *
3741
+ * // List tools from all servers
3742
+ * for (const [name, session] of Object.entries(sessions)) {
3743
+ * const tools = await session.listTools();
3744
+ * console.log(`${name}: ${tools.length} tools`);
3745
+ * }
3746
+ * ```
3747
+ *
3748
+ * @see {@link createSession} for creating individual sessions
3749
+ * @see {@link closeAllSessions} for closing all sessions
3750
+ */
3751
+ async createAllSessions(autoInitialize = true) {
3752
+ const servers = this.config.mcpServers ?? {};
3753
+ if (Object.keys(servers).length === 0) {
3754
+ logger.warn("No MCP servers defined in config");
3755
+ }
3756
+ for (const name of Object.keys(servers)) {
3757
+ await this.createSession(name, autoInitialize);
3758
+ }
3759
+ return this.sessions;
3760
+ }
3761
+ /**
3762
+ * Connect to every configured server sequentially.
3763
+ *
3764
+ * Each result uses the same {@link MCPConnection} API regardless of whether
3765
+ * the negotiated protocol is legacy/sessionful or modern/sessionless.
3766
+ */
3767
+ async connectAll() {
3768
+ return this.createAllSessions();
3769
+ }
3770
+ /**
3771
+ * Retrieves an existing session by server name.
3772
+ *
3773
+ * This method returns null if no session exists, making it safe for
3774
+ * checking session existence without throwing errors.
3775
+ *
3776
+ * @param serverName - Name of the server
3777
+ * @returns The session instance or null if not found
3778
+ *
3779
+ * @example
3780
+ * ```typescript
3781
+ * const session = client.getSession('my-server');
3782
+ * if (session) {
3783
+ * const tools = await session.listTools();
3784
+ * } else {
3785
+ * console.log('Session not found, creating...');
3786
+ * await client.createSession('my-server');
3787
+ * }
3788
+ * ```
3789
+ *
3790
+ * @see {@link requireSession} for getting a session that throws if not found
3791
+ * @see {@link createSession} for creating sessions
3792
+ */
3793
+ getSession(serverName) {
3794
+ const session = this.sessions[serverName];
3795
+ if (!session) {
3796
+ return null;
3797
+ }
3798
+ return session;
3799
+ }
3800
+ /**
3801
+ * Retrieves an existing session by server name, throwing if not found.
3802
+ *
3803
+ * This method is useful when you need to ensure a session exists before
3804
+ * proceeding. It throws a descriptive error if the session is not found.
3805
+ *
3806
+ * @param serverName - Name of the server
3807
+ * @returns The session instance
3808
+ * @throws {Error} If the session is not found
3809
+ *
3810
+ * @example
3811
+ * ```typescript
3812
+ * try {
3813
+ * const session = client.requireSession('my-server');
3814
+ * const tools = await session.listTools();
3815
+ * } catch (error) {
3816
+ * console.error('Session not found:', error.message);
3817
+ * }
3818
+ * ```
3819
+ *
3820
+ * @see {@link getSession} for a null-returning alternative
3821
+ * @see {@link createSession} for creating sessions
3822
+ */
3823
+ requireSession(serverName) {
3824
+ const session = this.sessions[serverName];
3825
+ if (!session) {
3826
+ throw new Error(
3827
+ `Session '${serverName}' not found. Available sessions: ${this.activeSessions.join(", ") || "none"}`
3828
+ );
3829
+ }
3830
+ return session;
3831
+ }
3832
+ /**
3833
+ * Gets all active sessions as a map of server names to sessions.
3834
+ *
3835
+ * @returns Map of server names to their active sessions
3836
+ *
3837
+ * @example
3838
+ * ```typescript
3839
+ * const sessions = client.getAllActiveSessions();
3840
+ *
3841
+ * // Iterate over all active sessions
3842
+ * for (const [name, session] of Object.entries(sessions)) {
3843
+ * console.log(`Server: ${name}`);
3844
+ * const tools = await session.listTools();
3845
+ * console.log(` Tools: ${tools.length}`);
3846
+ * }
3847
+ * ```
3848
+ *
3849
+ * @see {@link activeSessions} for just the list of server names
3850
+ * @see {@link getSession} for retrieving individual sessions
3851
+ */
3852
+ getAllActiveSessions() {
3853
+ return Object.fromEntries(
3854
+ this.activeSessions.map((n) => [n, this.sessions[n]])
3855
+ );
3856
+ }
3857
+ /**
3858
+ * Closes a session and cleans up its resources.
3859
+ *
3860
+ * This method gracefully disconnects from the server and removes the
3861
+ * session from the active sessions list. It's safe to call even if
3862
+ * the session doesn't exist.
3863
+ *
3864
+ * @param serverName - Name of the server whose session should be closed
3865
+ *
3866
+ * @example
3867
+ * ```typescript
3868
+ * // Close a specific session
3869
+ * await client.closeSession('my-server');
3870
+ *
3871
+ * // Verify it's closed
3872
+ * console.log(client.activeSessions.includes('my-server')); // false
3873
+ * ```
3874
+ *
3875
+ * @see {@link closeAllSessions} for closing all sessions at once
3876
+ * @see {@link createSession} for creating new sessions
3877
+ */
3878
+ async closeSession(serverName) {
3879
+ const session = this.sessions[serverName];
3880
+ if (!session) {
3881
+ logger.warn(
3882
+ `No session exists for server ${serverName}, nothing to close`
3883
+ );
3884
+ return;
3885
+ }
3886
+ try {
3887
+ logger.debug(`Closing session for server ${serverName}`);
3888
+ await session.disconnect();
3889
+ } catch (e) {
3890
+ logger.error(`Error closing session for server '${serverName}': ${e}`);
3891
+ } finally {
3892
+ if (this.sessions[serverName] === session) {
3893
+ delete this.sessions[serverName];
3894
+ this.activeSessions = this.activeSessions.filter(
3895
+ (n) => n !== serverName
3896
+ );
3897
+ }
3898
+ }
3899
+ }
3900
+ /**
3901
+ * Closes all active sessions and cleans up their resources.
3902
+ *
3903
+ * This method iterates through all sessions and attempts to close each one
3904
+ * gracefully. If any session fails to close, the error is logged but the
3905
+ * method continues to close remaining sessions.
3906
+ *
3907
+ * This is particularly useful for cleanup on application shutdown.
3908
+ *
3909
+ * @example
3910
+ * ```typescript
3911
+ * // Clean shutdown
3912
+ * try {
3913
+ * await client.closeAllSessions();
3914
+ * console.log('All sessions closed successfully');
3915
+ * } catch (error) {
3916
+ * console.error('Error during cleanup:', error);
3917
+ * }
3918
+ * ```
3919
+ *
3920
+ * @example
3921
+ * ```typescript
3922
+ * // Use in application shutdown handler
3923
+ * process.on('SIGINT', async () => {
3924
+ * console.log('Shutting down...');
3925
+ * await client.closeAllSessions();
3926
+ * process.exit(0);
3927
+ * });
3928
+ * ```
3929
+ *
3930
+ * @see {@link closeSession} for closing individual sessions
3931
+ * @see {@link createAllSessions} for creating sessions
3932
+ */
3933
+ async closeAllSessions() {
3934
+ const serverNames = Object.keys(this.sessions);
3935
+ const errors = [];
3936
+ for (const serverName of serverNames) {
3937
+ try {
3938
+ logger.debug(`Closing session for server ${serverName}`);
3939
+ await this.closeSession(serverName);
3940
+ } catch (e) {
3941
+ const errorMsg = `Failed to close session for server '${serverName}': ${e}`;
3942
+ logger.error(errorMsg);
3943
+ errors.push(errorMsg);
3944
+ }
3945
+ }
3946
+ if (errors.length) {
3947
+ logger.error(
3948
+ `Encountered ${errors.length} errors while closing sessions`
3949
+ );
3950
+ } else {
3951
+ logger.debug("All sessions closed successfully");
3952
+ }
3953
+ }
3954
+ /** Close every active MCP connection. */
3955
+ async close() {
3956
+ await this.closeAllSessions();
3957
+ }
3958
+ };
3959
+
3960
+ // src/core/browser.ts
3961
+ function trackBrowserClientInit(config) {
3962
+ const servers = Object.keys(config.mcpServers ?? {});
3963
+ Tel.getInstance().trackMCPClientInit({
3964
+ codeMode: false,
3965
+ sandbox: false,
3966
+ allCallbacks: false,
3967
+ verify: false,
3968
+ servers,
3969
+ numServers: servers.length,
3970
+ isBrowser: true
3971
+ }).catch(
3972
+ (e) => logger.debug(`Failed to track BrowserMCPClient init: ${e}`)
3973
+ );
3974
+ }
3975
+ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
3976
+ /**
3977
+ * Get the mcp-use package version.
3978
+ * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
3979
+ */
3980
+ static getPackageVersion() {
3981
+ return getPackageVersion();
3982
+ }
3983
+ constructor(config) {
3984
+ super(config);
3985
+ trackBrowserClientInit(this.config);
3986
+ }
3987
+ static fromDict(cfg) {
3988
+ return new _BrowserMCPClient(cfg);
3989
+ }
3990
+ async createDefaultOAuthProvider(serverUrl, options = {}) {
3991
+ return createOAuthProvider(serverUrl, options);
3992
+ }
3993
+ /**
3994
+ * Create a connector from server configuration (Browser version)
3995
+ * Supports HTTP connector only
3996
+ */
3997
+ createConnectorFromConfig(serverConfig) {
3998
+ const {
3999
+ url,
4000
+ headers,
4001
+ fetch: configuredFetch,
4002
+ authToken,
4003
+ authProvider,
4004
+ wrapTransport,
4005
+ clientOptions,
4006
+ protocolNegotiation,
4007
+ timeout,
4008
+ gatewayUrl,
4009
+ serverId,
4010
+ reconnectionOptions
4011
+ } = serverConfig;
4012
+ if (!url) {
4013
+ throw new Error("Server URL is required");
4014
+ }
4015
+ const globalDefaults = this.config;
4016
+ const resolved = resolveCallbacks(
4017
+ serverConfig,
4018
+ globalDefaults
4019
+ );
4020
+ const clientInfo = normalizeClientInfo(
4021
+ serverConfig.clientInfo ?? this.config.clientInfo
4022
+ );
4023
+ const connectorOptions = {
4024
+ headers,
4025
+ fetch: configuredFetch ?? globalThis.fetch.bind(globalThis),
4026
+ authToken,
4027
+ authProvider,
4028
+ wrapTransport,
4029
+ clientOptions,
4030
+ onSampling: resolved.onSampling,
4031
+ onElicitation: resolved.onElicitation,
4032
+ onNotification: resolved.onNotification,
4033
+ protocolNegotiation,
4034
+ timeout,
4035
+ clientInfo,
4036
+ gatewayUrl,
4037
+ serverId,
4038
+ reconnectionOptions
4039
+ };
4040
+ logger.debug(
4041
+ `[BrowserMCPClient] Connector options prepared (clientOptions: ${clientOptions ? "provided" : "none"})`
4042
+ );
4043
+ return new HttpConnector(url, connectorOptions);
4044
+ }
4045
+ };
4046
+
4047
+ // src/utils/favicon.ts
4048
+ var FAVICON_API = "https://favicon.tools.mcp-use.com";
4049
+ var IPV4_RE = /^\d{1,3}(\.\d{1,3}){3}$/;
4050
+ function parseHostname(serverUrl) {
4051
+ try {
4052
+ const raw = serverUrl.includes("://") ? serverUrl : `https://${serverUrl}`;
4053
+ return new URL(raw).hostname;
4054
+ } catch {
4055
+ return null;
4056
+ }
4057
+ }
4058
+ function isLocalHost(hostname) {
4059
+ const h = hostname.toLowerCase();
4060
+ if (h === "localhost" || h.endsWith(".localhost")) return true;
4061
+ if (h === "host.docker.internal" || h === "0.0.0.0") return true;
4062
+ if (!IPV4_RE.test(h)) return false;
4063
+ if (h === "127.0.0.1" || h.startsWith("127.")) return true;
4064
+ if (h.startsWith("10.")) return true;
4065
+ if (h.startsWith("192.168.")) return true;
4066
+ const m = /^172\.(\d+)\./.exec(h);
4067
+ if (m) {
4068
+ const second = Number.parseInt(m[1], 10);
4069
+ if (second >= 16 && second <= 31) return true;
4070
+ }
4071
+ return false;
4072
+ }
4073
+ function subdomainLevels(hostname) {
4074
+ const parts = hostname.split(".");
4075
+ return Array.from(
4076
+ { length: parts.length - 1 },
4077
+ (_, i) => parts.slice(i).join(".")
4078
+ );
4079
+ }
4080
+ function blobToDataUrl(blob) {
4081
+ return new Promise((resolve, reject) => {
4082
+ const reader = new FileReader();
4083
+ reader.onloadend = () => resolve(reader.result);
4084
+ reader.onerror = reject;
4085
+ reader.readAsDataURL(blob);
4086
+ });
4087
+ }
4088
+ async function detectFavicon(serverUrl) {
4089
+ try {
4090
+ const hostname = parseHostname(serverUrl);
4091
+ if (!hostname || isLocalHost(hostname)) return null;
4092
+ for (const domain of subdomainLevels(hostname)) {
4093
+ try {
4094
+ const res = await fetch(`${FAVICON_API}/${domain}?response=json`, {
4095
+ signal: AbortSignal.timeout(2e3)
4096
+ });
4097
+ if (!res.ok) continue;
4098
+ const data = await res.json();
4099
+ if (data.source === "default") continue;
4100
+ const imageUrl = data.url.replace(/^http:\/\//, "https://");
4101
+ const img = await fetch(imageUrl, {
4102
+ signal: AbortSignal.timeout(2e3)
4103
+ });
4104
+ if (!img.ok) continue;
4105
+ return await blobToDataUrl(await img.blob());
4106
+ } catch {
4107
+ continue;
4108
+ }
4109
+ }
4110
+ return null;
4111
+ } catch (error) {
4112
+ console.warn("[favicon] Error detecting favicon:", error);
4113
+ return null;
4114
+ }
4115
+ }
4116
+ export {
4117
+ BaseConnector,
4118
+ BrowserOAuthClientProvider,
4119
+ DialectJsonSchemaValidator,
4120
+ HttpConnector,
4121
+ BrowserMCPClient as MCPClient,
4122
+ MCPConnection,
4123
+ MCPConnection as MCPSession,
4124
+ POSTHOG_API_KEY,
4125
+ POSTHOG_HOST,
4126
+ SCARF_GATEWAY_URL,
4127
+ Tel,
4128
+ Telemetry,
4129
+ UnauthorizedError3 as UnauthorizedError,
4130
+ VERSION,
4131
+ auth2 as auth,
4132
+ capturePostHog,
4133
+ captureScarf,
4134
+ completeOAuthFlow,
4135
+ createConnectorFromConfig,
4136
+ createOAuthProvider,
4137
+ detectFavicon,
4138
+ getPackageVersion,
4139
+ isUnauthorized,
4140
+ logger,
4141
+ normalizeClientInfo,
4142
+ onMcpAuthorization,
4143
+ resolveCallbacks,
4144
+ resolveClientOptions,
4145
+ setProductVersion,
4146
+ setTelemetrySource,
4147
+ shouldAutoProvisionOAuth,
4148
+ telFetch
4149
+ };
4150
+ //# sourceMappingURL=index-browser.js.map