mcp-use 1.11.0-canary.8 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/{chunk-5RTMAOZ6.js → chunk-A4QJRN7Z.js} +5 -1041
  3. package/dist/{chunk-4LZSXUFM.js → chunk-B7AGEK7F.js} +1 -1
  4. package/dist/{chunk-TAEHPLGV.js → chunk-GN5HOAV3.js} +664 -136
  5. package/dist/chunk-QPIDKGV4.js +1246 -0
  6. package/dist/chunk-UWWLWLS2.js +62 -0
  7. package/dist/{chunk-ZFZPZ4GE.js → chunk-V77WS6CS.js} +9 -0
  8. package/dist/{chunk-EBSNALCB.js → chunk-VRHAF2WT.js} +10 -4
  9. package/dist/{chunk-X7JKFBPN.js → chunk-Y2HHHJQB.js} +159 -8
  10. package/dist/{chunk-JPKFN73V.js → chunk-ZLZOOXMJ.js} +96 -43
  11. package/dist/index.cjs +316 -53
  12. package/dist/index.js +22 -24
  13. package/dist/notifications-FLGIFS56.js +9 -0
  14. package/dist/src/agents/index.cjs +153 -47
  15. package/dist/src/agents/index.d.ts +1 -1
  16. package/dist/src/agents/index.d.ts.map +1 -1
  17. package/dist/src/agents/index.js +7 -10
  18. package/dist/src/agents/mcp_agent.d.ts.map +1 -1
  19. package/dist/src/{client/prompts.d.ts → agents/prompts/index.d.ts} +3 -3
  20. package/dist/src/agents/prompts/index.d.ts.map +1 -0
  21. package/dist/src/browser.cjs +160 -48
  22. package/dist/src/browser.js +10 -12
  23. package/dist/src/client/browser.d.ts.map +1 -1
  24. package/dist/src/client.cjs +3852 -0
  25. package/dist/src/client.d.ts +2 -0
  26. package/dist/src/client.d.ts.map +1 -1
  27. package/dist/src/client.js +21 -0
  28. package/dist/src/config.d.ts.map +1 -1
  29. package/dist/src/connectors/http.d.ts +2 -0
  30. package/dist/src/connectors/http.d.ts.map +1 -1
  31. package/dist/src/react/index.cjs +313 -52
  32. package/dist/src/react/index.js +7 -8
  33. package/dist/src/react/types.d.ts +41 -1
  34. package/dist/src/react/types.d.ts.map +1 -1
  35. package/dist/src/react/useMcp.d.ts.map +1 -1
  36. package/dist/src/server/endpoints/mount-mcp.d.ts.map +1 -1
  37. package/dist/src/server/index.cjs +1339 -256
  38. package/dist/src/server/index.d.ts +2 -0
  39. package/dist/src/server/index.d.ts.map +1 -1
  40. package/dist/src/server/index.js +1119 -156
  41. package/dist/src/server/mcp-server.d.ts +4 -1
  42. package/dist/src/server/mcp-server.d.ts.map +1 -1
  43. package/dist/src/server/notifications/index.d.ts +1 -1
  44. package/dist/src/server/notifications/index.d.ts.map +1 -1
  45. package/dist/src/server/notifications/notification-registration.d.ts +51 -0
  46. package/dist/src/server/notifications/notification-registration.d.ts.map +1 -1
  47. package/dist/src/server/sessions/index.d.ts +3 -1
  48. package/dist/src/server/sessions/index.d.ts.map +1 -1
  49. package/dist/src/server/sessions/session-manager.d.ts +30 -16
  50. package/dist/src/server/sessions/session-manager.d.ts.map +1 -1
  51. package/dist/src/server/sessions/stores/filesystem.d.ts +121 -0
  52. package/dist/src/server/sessions/stores/filesystem.d.ts.map +1 -0
  53. package/dist/src/server/sessions/stores/index.d.ts +94 -0
  54. package/dist/src/server/sessions/stores/index.d.ts.map +1 -0
  55. package/dist/src/server/sessions/stores/memory.d.ts +82 -0
  56. package/dist/src/server/sessions/stores/memory.d.ts.map +1 -0
  57. package/dist/src/server/sessions/stores/redis.d.ts +164 -0
  58. package/dist/src/server/sessions/stores/redis.d.ts.map +1 -0
  59. package/dist/src/server/sessions/streams/index.d.ts +77 -0
  60. package/dist/src/server/sessions/streams/index.d.ts.map +1 -0
  61. package/dist/src/server/sessions/streams/memory.d.ts +76 -0
  62. package/dist/src/server/sessions/streams/memory.d.ts.map +1 -0
  63. package/dist/src/server/sessions/streams/redis.d.ts +146 -0
  64. package/dist/src/server/sessions/streams/redis.d.ts.map +1 -0
  65. package/dist/src/server/types/common.d.ts +82 -28
  66. package/dist/src/server/types/common.d.ts.map +1 -1
  67. package/dist/src/server/types/widget.d.ts +2 -2
  68. package/dist/src/server/types/widget.d.ts.map +1 -1
  69. package/dist/src/server/utils/response-helpers.d.ts +4 -2
  70. package/dist/src/server/utils/response-helpers.d.ts.map +1 -1
  71. package/dist/src/server/widgets/mount-widgets-dev.d.ts.map +1 -1
  72. package/dist/src/server/widgets/ui-resource-registration.d.ts.map +1 -1
  73. package/dist/src/task_managers/index.d.ts +10 -0
  74. package/dist/src/task_managers/index.d.ts.map +1 -1
  75. package/dist/src/task_managers/sse.d.ts +34 -1
  76. package/dist/src/task_managers/sse.d.ts.map +1 -1
  77. package/dist/src/task_managers/streamable_http.d.ts +8 -2
  78. package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
  79. package/dist/src/telemetry/telemetry.d.ts +1 -0
  80. package/dist/src/telemetry/telemetry.d.ts.map +1 -1
  81. package/dist/src/version.d.ts +1 -1
  82. package/dist/src/version.d.ts.map +1 -1
  83. package/dist/{tool-execution-helpers-EYAIJERC.js → tool-execution-helpers-ZUA5D5IO.js} +2 -2
  84. package/dist/tsup.config.d.ts.map +1 -1
  85. package/package.json +62 -52
  86. package/dist/chunk-GVU7C2ZD.js +0 -12
  87. package/dist/chunk-JZNXOM7C.js +0 -204
  88. package/dist/chunk-XKTBHYNM.js +0 -491
  89. package/dist/src/client/prompts.cjs +0 -407
  90. package/dist/src/client/prompts.d.ts.map +0 -1
  91. package/dist/src/client/prompts.js +0 -11
@@ -0,0 +1,62 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-3GQAWCBQ.js";
4
+
5
+ // src/server/utils/jsonrpc-helpers.ts
6
+ function createNotification(method, params) {
7
+ return {
8
+ jsonrpc: "2.0",
9
+ method,
10
+ ...params && { params }
11
+ };
12
+ }
13
+ __name(createNotification, "createNotification");
14
+ function createRequest(id, method, params) {
15
+ return {
16
+ jsonrpc: "2.0",
17
+ id,
18
+ method,
19
+ ...params && { params }
20
+ };
21
+ }
22
+ __name(createRequest, "createRequest");
23
+
24
+ // src/server/sessions/notifications.ts
25
+ async function sendNotificationToAll(sessions, method, params) {
26
+ const notification = createNotification(method, params);
27
+ for (const [sessionId, session] of sessions.entries()) {
28
+ try {
29
+ await session.transport.send(notification);
30
+ } catch (error) {
31
+ console.warn(
32
+ `[MCP] Failed to send notification to session ${sessionId}:`,
33
+ error
34
+ );
35
+ }
36
+ }
37
+ }
38
+ __name(sendNotificationToAll, "sendNotificationToAll");
39
+ async function sendNotificationToSession(sessions, sessionId, method, params) {
40
+ const session = sessions.get(sessionId);
41
+ if (!session) {
42
+ return false;
43
+ }
44
+ const notification = createNotification(method, params);
45
+ try {
46
+ await session.transport.send(notification);
47
+ return true;
48
+ } catch (error) {
49
+ console.warn(
50
+ `[MCP] Failed to send notification to session ${sessionId}:`,
51
+ error
52
+ );
53
+ return false;
54
+ }
55
+ }
56
+ __name(sendNotificationToSession, "sendNotificationToSession");
57
+
58
+ export {
59
+ createRequest,
60
+ sendNotificationToAll,
61
+ sendNotificationToSession
62
+ };
@@ -1,7 +1,15 @@
1
+ import {
2
+ CODE_MODE_AGENT_PROMPT
3
+ } from "./chunk-QPIDKGV4.js";
1
4
  import {
2
5
  __name
3
6
  } from "./chunk-3GQAWCBQ.js";
4
7
 
8
+ // src/agents/prompts/index.ts
9
+ var PROMPTS = {
10
+ CODE_MODE: CODE_MODE_AGENT_PROMPT
11
+ };
12
+
5
13
  // src/agents/base.ts
6
14
  var BaseAgent = class {
7
15
  static {
@@ -17,5 +25,6 @@ var BaseAgent = class {
17
25
  };
18
26
 
19
27
  export {
28
+ PROMPTS,
20
29
  BaseAgent
21
30
  };
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  BaseMCPClient,
3
3
  HttpConnector
4
- } from "./chunk-TAEHPLGV.js";
4
+ } from "./chunk-GN5HOAV3.js";
5
5
  import {
6
6
  Tel,
7
7
  getPackageVersion
8
- } from "./chunk-JPKFN73V.js";
8
+ } from "./chunk-ZLZOOXMJ.js";
9
9
  import {
10
10
  logger
11
11
  } from "./chunk-FRUZDWXH.js";
@@ -63,7 +63,9 @@ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
63
63
  wrapTransport,
64
64
  clientOptions,
65
65
  samplingCallback,
66
- elicitationCallback
66
+ elicitationCallback,
67
+ disableSseFallback,
68
+ preferSse
67
69
  } = serverConfig;
68
70
  if (!url) {
69
71
  throw new Error("Server URL is required");
@@ -79,8 +81,12 @@ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
79
81
  // ← Pass client options (capabilities, etc.) to connector
80
82
  samplingCallback,
81
83
  // ← Pass sampling callback to connector
82
- elicitationCallback
84
+ elicitationCallback,
83
85
  // ← Pass elicitation callback to connector
86
+ disableSseFallback,
87
+ // ← Disable automatic SSE fallback
88
+ preferSse
89
+ // ← Use SSE transport directly
84
90
  };
85
91
  if (clientOptions) {
86
92
  console.log(
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  BrowserMCPClient
3
- } from "./chunk-EBSNALCB.js";
3
+ } from "./chunk-VRHAF2WT.js";
4
+ import {
5
+ Tel
6
+ } from "./chunk-ZLZOOXMJ.js";
4
7
  import {
5
8
  BrowserOAuthClientProvider,
6
9
  sanitizeUrl
7
10
  } from "./chunk-J75I2C26.js";
8
- import {
9
- Tel
10
- } from "./chunk-JPKFN73V.js";
11
11
  import {
12
12
  __name
13
13
  } from "./chunk-3GQAWCBQ.js";
@@ -101,6 +101,11 @@ function useMcp(options) {
101
101
  if (clientRef.current) {
102
102
  try {
103
103
  const serverName = "inspector-server";
104
+ const session = clientRef.current.getSession(serverName);
105
+ if (session && session._healthCheckCleanup) {
106
+ session._healthCheckCleanup();
107
+ session._healthCheckCleanup = null;
108
+ }
104
109
  await clientRef.current.closeSession(serverName);
105
110
  } catch (err) {
106
111
  if (!quiet) addLog("warn", "Error closing session:", err);
@@ -202,7 +207,12 @@ function useMcp(options) {
202
207
  const serverName = "inspector-server";
203
208
  const serverConfig = {
204
209
  url,
205
- transport: transportTypeParam === "sse" ? "http" : transportTypeParam
210
+ transport: transportTypeParam === "sse" ? "http" : transportTypeParam,
211
+ // Disable SSE fallback when using explicit HTTP transport (not SSE)
212
+ // This prevents automatic HTTP → SSE fallback at the connector level
213
+ disableSseFallback: transportTypeParam === "http",
214
+ // Use SSE transport when explicitly requested
215
+ preferSse: transportTypeParam === "sse"
206
216
  };
207
217
  if (customHeaders && Object.keys(customHeaders).length > 0) {
208
218
  serverConfig.headers = customHeaders;
@@ -240,9 +250,25 @@ function useMcp(options) {
240
250
  serverName,
241
251
  false
242
252
  );
243
- if (onNotification) {
244
- session.on("notification", onNotification);
245
- }
253
+ session.on("notification", (notification) => {
254
+ onNotification?.(notification);
255
+ if (notification.method === "notifications/tools/list_changed") {
256
+ addLog("info", "Tools list changed, auto-refreshing...");
257
+ refreshTools().catch(
258
+ (err) => addLog("warn", "Auto-refresh tools failed:", err)
259
+ );
260
+ } else if (notification.method === "notifications/resources/list_changed") {
261
+ addLog("info", "Resources list changed, auto-refreshing...");
262
+ refreshResources().catch(
263
+ (err) => addLog("warn", "Auto-refresh resources failed:", err)
264
+ );
265
+ } else if (notification.method === "notifications/prompts/list_changed") {
266
+ addLog("info", "Prompts list changed, auto-refreshing...");
267
+ refreshPrompts().catch(
268
+ (err) => addLog("warn", "Auto-refresh prompts failed:", err)
269
+ );
270
+ }
271
+ });
246
272
  await session.initialize();
247
273
  addLog("info", "\u2705 Successfully connected to MCP server");
248
274
  addLog("info", "Server info:", session.connector.serverInfo);
@@ -258,6 +284,63 @@ function useMcp(options) {
258
284
  );
259
285
  setState("ready");
260
286
  successfulTransportRef.current = transportTypeParam;
287
+ const setupConnectionMonitoring = /* @__PURE__ */ __name(() => {
288
+ let healthCheckInterval = null;
289
+ let lastSuccessfulCheck = Date.now();
290
+ const HEALTH_CHECK_INTERVAL = 1e4;
291
+ const HEALTH_CHECK_TIMEOUT = 3e4;
292
+ const checkConnectionHealth = /* @__PURE__ */ __name(async () => {
293
+ if (!isMountedRef.current || stateRef.current !== "ready") {
294
+ if (healthCheckInterval) {
295
+ clearInterval(healthCheckInterval);
296
+ healthCheckInterval = null;
297
+ }
298
+ return;
299
+ }
300
+ try {
301
+ await session.connector.listTools();
302
+ lastSuccessfulCheck = Date.now();
303
+ } catch (err) {
304
+ const timeSinceLastSuccess = Date.now() - lastSuccessfulCheck;
305
+ if (timeSinceLastSuccess > HEALTH_CHECK_TIMEOUT) {
306
+ addLog(
307
+ "warn",
308
+ `Connection appears to be broken (no response for ${Math.round(timeSinceLastSuccess / 1e3)}s), attempting to reconnect...`
309
+ );
310
+ if (healthCheckInterval) {
311
+ clearInterval(healthCheckInterval);
312
+ healthCheckInterval = null;
313
+ }
314
+ if (autoReconnectRef.current && isMountedRef.current) {
315
+ setState("discovering");
316
+ addLog("info", "Auto-reconnecting to MCP server...");
317
+ setTimeout(
318
+ () => {
319
+ if (isMountedRef.current && stateRef.current === "discovering") {
320
+ connect();
321
+ }
322
+ },
323
+ typeof autoReconnectRef.current === "number" ? autoReconnectRef.current : DEFAULT_RECONNECT_DELAY
324
+ );
325
+ }
326
+ }
327
+ }
328
+ }, "checkConnectionHealth");
329
+ healthCheckInterval = setInterval(
330
+ checkConnectionHealth,
331
+ HEALTH_CHECK_INTERVAL
332
+ );
333
+ return () => {
334
+ if (healthCheckInterval) {
335
+ clearInterval(healthCheckInterval);
336
+ healthCheckInterval = null;
337
+ }
338
+ };
339
+ }, "setupConnectionMonitoring");
340
+ if (autoReconnect) {
341
+ const cleanup = setupConnectionMonitoring();
342
+ session._healthCheckCleanup = cleanup;
343
+ }
261
344
  Tel.getInstance().trackUseMcpConnection({
262
345
  url,
263
346
  transportType: transportTypeParam,
@@ -609,6 +692,70 @@ function useMcp(options) {
609
692
  throw err;
610
693
  }
611
694
  }, [state]);
695
+ const refreshTools = useCallback(async () => {
696
+ if (stateRef.current !== "ready" || !clientRef.current) {
697
+ addLog("debug", "Cannot refresh tools - client not ready");
698
+ return;
699
+ }
700
+ addLog("debug", "Refreshing tools list");
701
+ try {
702
+ const serverName = "inspector-server";
703
+ const session = clientRef.current.getSession(serverName);
704
+ if (!session) {
705
+ addLog("warn", "No active session found for tools refresh");
706
+ return;
707
+ }
708
+ const toolsResult = await session.connector.listTools();
709
+ setTools(toolsResult || []);
710
+ addLog("info", "Tools list refreshed successfully");
711
+ } catch (err) {
712
+ addLog("warn", "Failed to refresh tools:", err);
713
+ }
714
+ }, [addLog]);
715
+ const refreshResources = useCallback(async () => {
716
+ if (stateRef.current !== "ready" || !clientRef.current) {
717
+ addLog("debug", "Cannot refresh resources - client not ready");
718
+ return;
719
+ }
720
+ addLog("debug", "Refreshing resources list");
721
+ try {
722
+ const serverName = "inspector-server";
723
+ const session = clientRef.current.getSession(serverName);
724
+ if (!session) {
725
+ addLog("warn", "No active session found for resources refresh");
726
+ return;
727
+ }
728
+ const resourcesResult = await session.connector.listAllResources();
729
+ setResources(resourcesResult.resources || []);
730
+ addLog("info", "Resources list refreshed successfully");
731
+ } catch (err) {
732
+ addLog("warn", "Failed to refresh resources:", err);
733
+ }
734
+ }, [addLog]);
735
+ const refreshPrompts = useCallback(async () => {
736
+ if (stateRef.current !== "ready" || !clientRef.current) {
737
+ addLog("debug", "Cannot refresh prompts - client not ready");
738
+ return;
739
+ }
740
+ addLog("debug", "Refreshing prompts list");
741
+ try {
742
+ const serverName = "inspector-server";
743
+ const session = clientRef.current.getSession(serverName);
744
+ if (!session) {
745
+ addLog("warn", "No active session found for prompts refresh");
746
+ return;
747
+ }
748
+ const promptsResult = await session.connector.listPrompts();
749
+ setPrompts(promptsResult.prompts || []);
750
+ addLog("info", "Prompts list refreshed successfully");
751
+ } catch (err) {
752
+ addLog("warn", "Failed to refresh prompts:", err);
753
+ }
754
+ }, [addLog]);
755
+ const refreshAll = useCallback(async () => {
756
+ addLog("info", "Refreshing all lists (tools, resources, prompts)");
757
+ await Promise.all([refreshTools(), refreshResources(), refreshPrompts()]);
758
+ }, [refreshTools, refreshResources, refreshPrompts, addLog]);
612
759
  const getPrompt = useCallback(
613
760
  async (name, args) => {
614
761
  if (stateRef.current !== "ready" || !clientRef.current) {
@@ -760,6 +907,10 @@ function useMcp(options) {
760
907
  listResources,
761
908
  listPrompts,
762
909
  getPrompt,
910
+ refreshTools,
911
+ refreshResources,
912
+ refreshPrompts,
913
+ refreshAll,
763
914
  retry,
764
915
  disconnect,
765
916
  authenticate,
@@ -92,7 +92,7 @@ function generateUUID() {
92
92
  __name(generateUUID, "generateUUID");
93
93
 
94
94
  // src/version.ts
95
- var VERSION = "1.11.0-canary.8";
95
+ var VERSION = "1.11.0";
96
96
  function getPackageVersion() {
97
97
  return VERSION;
98
98
  }
@@ -479,6 +479,20 @@ function extractModelInfo(llm) {
479
479
  __name(extractModelInfo, "extractModelInfo");
480
480
 
481
481
  // src/telemetry/telemetry.ts
482
+ function secureRandomString() {
483
+ if (typeof window !== "undefined" && window.crypto && typeof window.crypto.getRandomValues === "function") {
484
+ const array = new Uint8Array(8);
485
+ window.crypto.getRandomValues(array);
486
+ return Array.from(array, (v) => v.toString(16).padStart(2, "0")).join("");
487
+ }
488
+ try {
489
+ const crypto = __require("crypto");
490
+ return crypto.randomBytes(8).toString("hex");
491
+ } catch (e) {
492
+ return Math.random().toString(36).substring(2, 15);
493
+ }
494
+ }
495
+ __name(secureRandomString, "secureRandomString");
482
496
  var USER_ID_STORAGE_KEY = "mcp_use_user_id";
483
497
  function detectRuntimeEnvironment() {
484
498
  try {
@@ -610,12 +624,26 @@ var Telemetry = class _Telemetry {
610
624
  "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
611
625
  );
612
626
  this._posthogLoading = this._initPostHog();
613
- try {
614
- this._scarfClient = new ScarfEventLogger(this.SCARF_GATEWAY_URL, 3e3);
615
- } catch (e) {
616
- logger.warn(`Failed to initialize Scarf telemetry: ${e}`);
627
+ if (this._runtimeEnvironment !== "browser") {
628
+ try {
629
+ this._scarfClient = new ScarfEventLogger(
630
+ this.SCARF_GATEWAY_URL,
631
+ 3e3
632
+ );
633
+ } catch (e) {
634
+ logger.warn(`Failed to initialize Scarf telemetry: ${e}`);
635
+ this._scarfClient = null;
636
+ }
637
+ } else {
617
638
  this._scarfClient = null;
618
639
  }
640
+ if (this._storageCapability === "filesystem" && this._scarfClient) {
641
+ setTimeout(() => {
642
+ this.trackPackageDownload({ triggered_by: "initialization" }).catch(
643
+ (e) => logger.debug(`Failed to track package download: ${e}`)
644
+ );
645
+ }, 0);
646
+ }
619
647
  }
620
648
  }
621
649
  _checkTelemetryDisabled() {
@@ -740,47 +768,65 @@ var Telemetry = class _Telemetry {
740
768
  break;
741
769
  case "session-only":
742
770
  default:
743
- this._currUserId = `session-${generateUUID()}`;
744
- logger.debug(
745
- `Using session-based user ID (${this._runtimeEnvironment} environment)`
746
- );
771
+ try {
772
+ this._currUserId = `session-${generateUUID()}`;
773
+ } catch (uuidError) {
774
+ this._currUserId = `session-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
775
+ }
747
776
  break;
748
777
  }
749
- if (this._storageCapability === "filesystem" && this._currUserId) {
750
- this._trackPackageDownloadInternal(this._currUserId, {
751
- triggered_by: "user_id_property"
752
- }).catch((e) => logger.debug(`Failed to track package download: ${e}`));
753
- }
754
778
  } catch (e) {
755
- logger.debug(`Failed to get/create user ID: ${e}`);
756
779
  this._currUserId = this.UNKNOWN_USER_ID;
757
780
  }
758
781
  return this._currUserId;
759
782
  }
760
783
  /**
761
784
  * Get or create user ID from filesystem (Node.js/Bun)
785
+ * Falls back to session ID if filesystem operations fail
762
786
  */
763
787
  _getUserIdFromFilesystem() {
764
- const fs = __require("fs");
765
- const os = __require("os");
766
- const path = __require("path");
767
- if (!this._userIdPath) {
768
- this._userIdPath = path.join(
769
- this._getCacheHome(os, path),
770
- "mcp_use_3",
771
- "telemetry_user_id"
772
- );
773
- }
774
- const isFirstTime = !fs.existsSync(this._userIdPath);
775
- if (isFirstTime) {
776
- logger.debug(`Creating user ID path: ${this._userIdPath}`);
777
- fs.mkdirSync(path.dirname(this._userIdPath), { recursive: true });
778
- const newUserId = generateUUID();
779
- fs.writeFileSync(this._userIdPath, newUserId);
780
- logger.debug(`User ID path created: ${this._userIdPath}`);
781
- return newUserId;
788
+ try {
789
+ let fs, os, path;
790
+ try {
791
+ fs = __require("fs");
792
+ os = __require("os");
793
+ path = __require("path");
794
+ } catch (requireError) {
795
+ try {
796
+ const sessionId = `session-${generateUUID()}`;
797
+ return sessionId;
798
+ } catch (uuidError) {
799
+ return `session-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
800
+ }
801
+ }
802
+ if (!this._userIdPath) {
803
+ this._userIdPath = path.join(
804
+ this._getCacheHome(os, path),
805
+ "mcp_use_3",
806
+ "telemetry_user_id"
807
+ );
808
+ }
809
+ const isFirstTime = !fs.existsSync(this._userIdPath);
810
+ if (isFirstTime) {
811
+ fs.mkdirSync(path.dirname(this._userIdPath), { recursive: true });
812
+ let newUserId;
813
+ try {
814
+ newUserId = generateUUID();
815
+ } catch (uuidError) {
816
+ newUserId = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
817
+ }
818
+ fs.writeFileSync(this._userIdPath, newUserId);
819
+ return newUserId;
820
+ }
821
+ const userId = fs.readFileSync(this._userIdPath, "utf-8").trim();
822
+ return userId;
823
+ } catch (e) {
824
+ try {
825
+ return `session-${generateUUID()}`;
826
+ } catch (uuidError) {
827
+ return `session-${Date.now()}-${secureRandomString()}`;
828
+ }
782
829
  }
783
- return fs.readFileSync(this._userIdPath, "utf-8").trim();
784
830
  }
785
831
  /**
786
832
  * Get or create user ID from localStorage (Browser)
@@ -789,14 +835,22 @@ var Telemetry = class _Telemetry {
789
835
  try {
790
836
  let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
791
837
  if (!userId) {
792
- userId = generateUUID();
838
+ try {
839
+ userId = generateUUID();
840
+ } catch (uuidError) {
841
+ userId = `${Date.now()}-${secureRandomString()}`;
842
+ }
793
843
  localStorage.setItem(USER_ID_STORAGE_KEY, userId);
794
- logger.debug(`Created new browser user ID`);
795
844
  }
796
845
  return userId;
797
846
  } catch (e) {
798
- logger.debug(`localStorage access failed: ${e}`);
799
- return `session-${generateUUID()}`;
847
+ let sessionId;
848
+ try {
849
+ sessionId = `session-${generateUUID()}`;
850
+ } catch (uuidError) {
851
+ sessionId = `session-${Date.now()}-${secureRandomString()}`;
852
+ }
853
+ return sessionId;
800
854
  }
801
855
  }
802
856
  _getCacheHome(os, path) {
@@ -825,6 +879,7 @@ var Telemetry = class _Telemetry {
825
879
  if (!this._posthogNodeClient && !this._posthogBrowserClient && !this._scarfClient) {
826
880
  return;
827
881
  }
882
+ const currentUserId = this.userId;
828
883
  const properties = { ...event.properties };
829
884
  properties.mcp_use_version = getPackageVersion();
830
885
  properties.language = "typescript";
@@ -832,9 +887,8 @@ var Telemetry = class _Telemetry {
832
887
  properties.runtime = this._runtimeEnvironment;
833
888
  if (this._posthogNodeClient) {
834
889
  try {
835
- logger.debug(`CAPTURE: PostHog Node Event ${event.name}`);
836
890
  this._posthogNodeClient.capture({
837
- distinctId: this.userId,
891
+ distinctId: currentUserId,
838
892
  event: event.name,
839
893
  properties
840
894
  });
@@ -844,10 +898,9 @@ var Telemetry = class _Telemetry {
844
898
  }
845
899
  if (this._posthogBrowserClient) {
846
900
  try {
847
- logger.debug(`CAPTURE: PostHog Browser Event ${event.name}`);
848
901
  this._posthogBrowserClient.capture(event.name, {
849
902
  ...properties,
850
- distinct_id: this.userId
903
+ distinct_id: currentUserId
851
904
  });
852
905
  } catch (e) {
853
906
  logger.debug(
@@ -859,7 +912,7 @@ var Telemetry = class _Telemetry {
859
912
  try {
860
913
  const scarfProperties = {
861
914
  ...properties,
862
- user_id: this.userId,
915
+ user_id: currentUserId,
863
916
  event: event.name
864
917
  };
865
918
  await this._scarfClient.logEvent(scarfProperties);