mcp-use 1.10.0-canary.8 → 1.10.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 (39) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/{chunk-CAIRNNL6.js → chunk-BLIJYL2F.js} +1 -1
  3. package/dist/{chunk-BBOYAKT6.js → chunk-D3GIGCHA.js} +1 -1
  4. package/dist/{chunk-X5QAXENQ.js → chunk-EKIKWKIM.js} +1 -1
  5. package/dist/{chunk-QBKQ6JN2.js → chunk-J76TXLP2.js} +24 -2
  6. package/dist/{chunk-6W6MURTQ.js → chunk-TWQ72HSN.js} +51 -2
  7. package/dist/{chunk-MSA3YBQE.js → chunk-UZJK3IKC.js} +1 -1
  8. package/dist/{chunk-ITRC7CNB.js → chunk-X5EWD2UY.js} +344 -157
  9. package/dist/index.cjs +424 -166
  10. package/dist/index.js +24 -18
  11. package/dist/src/agents/index.cjs +337 -151
  12. package/dist/src/agents/index.js +4 -4
  13. package/dist/src/browser.cjs +371 -151
  14. package/dist/src/browser.d.ts +3 -0
  15. package/dist/src/browser.d.ts.map +1 -1
  16. package/dist/src/browser.js +13 -5
  17. package/dist/src/client/base.d.ts.map +1 -1
  18. package/dist/src/client/browser.d.ts +1 -0
  19. package/dist/src/client/browser.d.ts.map +1 -1
  20. package/dist/src/client/prompts.cjs +3 -9
  21. package/dist/src/client/prompts.js +3 -3
  22. package/dist/src/client.d.ts.map +1 -1
  23. package/dist/src/react/index.cjs +414 -151
  24. package/dist/src/react/index.d.ts +3 -0
  25. package/dist/src/react/index.d.ts.map +1 -1
  26. package/dist/src/react/index.js +13 -4
  27. package/dist/src/react/useMcp.d.ts.map +1 -1
  28. package/dist/src/server/index.cjs +756 -569
  29. package/dist/src/server/index.js +5 -5
  30. package/dist/src/telemetry/events.d.ts +28 -0
  31. package/dist/src/telemetry/events.d.ts.map +1 -1
  32. package/dist/src/telemetry/index.d.ts +4 -4
  33. package/dist/src/telemetry/index.d.ts.map +1 -1
  34. package/dist/src/telemetry/telemetry.d.ts +74 -11
  35. package/dist/src/telemetry/telemetry.d.ts.map +1 -1
  36. package/dist/src/version.d.ts +1 -1
  37. package/dist/src/version.d.ts.map +1 -1
  38. package/dist/{tool-execution-helpers-BMGQQKS2.js → tool-execution-helpers-IMWBWRMK.js} +2 -2
  39. package/package.json +4 -3
@@ -31,374 +31,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
31
31
  ));
32
32
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
33
 
34
- // src/server/utils/runtime.ts
35
- function getEnv(key) {
36
- if (isDeno) {
37
- return globalThis.Deno.env.get(key);
38
- }
39
- return process.env[key];
40
- }
41
- function getCwd() {
42
- if (isDeno) {
43
- return globalThis.Deno.cwd();
44
- }
45
- return process.cwd();
46
- }
47
- function generateUUID() {
48
- return globalThis.crypto.randomUUID();
49
- }
50
- var isDeno, fsHelpers, pathHelpers;
51
- var init_runtime = __esm({
52
- "src/server/utils/runtime.ts"() {
53
- "use strict";
54
- isDeno = typeof globalThis.Deno !== "undefined";
55
- __name(getEnv, "getEnv");
56
- __name(getCwd, "getCwd");
57
- fsHelpers = {
58
- async readFileSync(path2, encoding = "utf8") {
59
- if (isDeno) {
60
- return await globalThis.Deno.readTextFile(path2);
61
- }
62
- const { readFileSync: readFileSync2 } = await import("fs");
63
- const result = readFileSync2(path2, encoding);
64
- return typeof result === "string" ? result : result.toString(encoding);
65
- },
66
- async readFile(path2) {
67
- if (isDeno) {
68
- const data = await globalThis.Deno.readFile(path2);
69
- return data.buffer;
70
- }
71
- const { readFileSync: readFileSync2 } = await import("fs");
72
- const buffer = readFileSync2(path2);
73
- return buffer.buffer.slice(
74
- buffer.byteOffset,
75
- buffer.byteOffset + buffer.byteLength
76
- );
77
- },
78
- async existsSync(path2) {
79
- if (isDeno) {
80
- try {
81
- await globalThis.Deno.stat(path2);
82
- return true;
83
- } catch {
84
- return false;
85
- }
86
- }
87
- const { existsSync: existsSync2 } = await import("fs");
88
- return existsSync2(path2);
89
- },
90
- async readdirSync(path2) {
91
- if (isDeno) {
92
- const entries = [];
93
- for await (const entry of globalThis.Deno.readDir(path2)) {
94
- entries.push(entry.name);
95
- }
96
- return entries;
97
- }
98
- const { readdirSync } = await import("fs");
99
- return readdirSync(path2);
100
- }
101
- };
102
- pathHelpers = {
103
- join(...paths) {
104
- if (isDeno) {
105
- return paths.join("/").replace(/\/+/g, "/");
106
- }
107
- return paths.join("/").replace(/\/+/g, "/");
108
- },
109
- relative(from, to) {
110
- const fromParts = from.split("/").filter((p) => p);
111
- const toParts = to.split("/").filter((p) => p);
112
- let i = 0;
113
- while (i < fromParts.length && i < toParts.length && fromParts[i] === toParts[i]) {
114
- i++;
115
- }
116
- const upCount = fromParts.length - i;
117
- const relativeParts = [...Array(upCount).fill(".."), ...toParts.slice(i)];
118
- return relativeParts.join("/");
119
- }
120
- };
121
- __name(generateUUID, "generateUUID");
122
- }
123
- });
124
-
125
- // src/logging.ts
126
- async function getNodeModules() {
127
- if (typeof process !== "undefined" && process.platform) {
128
- try {
129
- const fs2 = await import("fs");
130
- const path2 = await import("path");
131
- return { fs: fs2.default, path: path2.default };
132
- } catch {
133
- return { fs: null, path: null };
134
- }
135
- }
136
- return { fs: null, path: null };
137
- }
138
- function loadWinstonSync() {
139
- if (typeof require !== "undefined") {
140
- try {
141
- winston = require("winston");
142
- } catch {
143
- }
144
- }
145
- }
146
- async function getWinston() {
147
- if (!winston) {
148
- winston = await import("winston");
149
- }
150
- return winston;
151
- }
152
- function isNodeJSEnvironment() {
153
- try {
154
- if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
155
- return false;
156
- }
157
- if (typeof globalThis.EdgeRuntime !== "undefined" || typeof globalThis.Deno !== "undefined") {
158
- return false;
159
- }
160
- const hasNodeGlobals = typeof process !== "undefined" && typeof process.platform !== "undefined" && typeof __dirname !== "undefined";
161
- return hasNodeGlobals;
162
- } catch {
163
- return false;
164
- }
165
- }
166
- function resolveLevel(env) {
167
- const envValue = typeof process !== "undefined" && process.env ? env : void 0;
168
- switch (envValue?.trim()) {
169
- case "2":
170
- return "debug";
171
- case "1":
172
- return "info";
173
- default:
174
- return "info";
175
- }
176
- }
177
- var winston, DEFAULT_LOGGER_NAME, SimpleConsoleLogger, Logger, logger;
178
- var init_logging = __esm({
179
- "src/logging.ts"() {
180
- "use strict";
181
- __name(getNodeModules, "getNodeModules");
182
- winston = null;
183
- __name(loadWinstonSync, "loadWinstonSync");
184
- __name(getWinston, "getWinston");
185
- DEFAULT_LOGGER_NAME = "mcp-use";
186
- __name(isNodeJSEnvironment, "isNodeJSEnvironment");
187
- SimpleConsoleLogger = class {
188
- static {
189
- __name(this, "SimpleConsoleLogger");
190
- }
191
- _level;
192
- name;
193
- constructor(name = DEFAULT_LOGGER_NAME, level = "info") {
194
- this.name = name;
195
- this._level = level;
196
- }
197
- shouldLog(level) {
198
- const levels = [
199
- "error",
200
- "warn",
201
- "info",
202
- "http",
203
- "verbose",
204
- "debug",
205
- "silly"
206
- ];
207
- const currentIndex = levels.indexOf(this._level);
208
- const messageIndex = levels.indexOf(level);
209
- return messageIndex <= currentIndex;
210
- }
211
- formatMessage(level, message) {
212
- const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
213
- return `${timestamp} [${this.name}] ${level}: ${message}`;
214
- }
215
- error(message) {
216
- if (this.shouldLog("error")) {
217
- console.error(this.formatMessage("error", message));
218
- }
219
- }
220
- warn(message) {
221
- if (this.shouldLog("warn")) {
222
- console.warn(this.formatMessage("warn", message));
223
- }
224
- }
225
- info(message) {
226
- if (this.shouldLog("info")) {
227
- console.info(this.formatMessage("info", message));
228
- }
229
- }
230
- debug(message) {
231
- if (this.shouldLog("debug")) {
232
- console.debug(this.formatMessage("debug", message));
233
- }
234
- }
235
- http(message) {
236
- if (this.shouldLog("http")) {
237
- console.log(this.formatMessage("http", message));
238
- }
239
- }
240
- verbose(message) {
241
- if (this.shouldLog("verbose")) {
242
- console.log(this.formatMessage("verbose", message));
243
- }
244
- }
245
- silly(message) {
246
- if (this.shouldLog("silly")) {
247
- console.log(this.formatMessage("silly", message));
248
- }
249
- }
250
- // Make it compatible with Winston interface
251
- get level() {
252
- return this._level;
253
- }
254
- set level(newLevel) {
255
- this._level = newLevel;
256
- }
257
- };
258
- __name(resolveLevel, "resolveLevel");
259
- Logger = class {
260
- static {
261
- __name(this, "Logger");
262
- }
263
- static instances = {};
264
- static simpleInstances = {};
265
- static currentFormat = "minimal";
266
- static get(name = DEFAULT_LOGGER_NAME) {
267
- if (!isNodeJSEnvironment()) {
268
- if (!this.simpleInstances[name]) {
269
- const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
270
- this.simpleInstances[name] = new SimpleConsoleLogger(
271
- name,
272
- resolveLevel(debugEnv)
273
- );
274
- }
275
- return this.simpleInstances[name];
276
- }
277
- if (!this.instances[name]) {
278
- if (!winston) {
279
- throw new Error("Winston not loaded - call Logger.configure() first");
280
- }
281
- const { createLogger, format } = winston;
282
- const { combine, timestamp, label, colorize, splat } = format;
283
- this.instances[name] = createLogger({
284
- level: resolveLevel(process.env.DEBUG),
285
- format: combine(
286
- colorize(),
287
- splat(),
288
- label({ label: name }),
289
- timestamp({ format: "HH:mm:ss" }),
290
- this.getFormatter()
291
- ),
292
- transports: []
293
- });
294
- }
295
- return this.instances[name];
296
- }
297
- static getFormatter() {
298
- if (!winston) {
299
- throw new Error("Winston not loaded");
300
- }
301
- const { format } = winston;
302
- const { printf } = format;
303
- const minimalFormatter = printf(({ level, message, label, timestamp }) => {
304
- return `${timestamp} [${label}] ${level}: ${message}`;
305
- });
306
- const detailedFormatter = printf(({ level, message, label, timestamp }) => {
307
- return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
308
- });
309
- const emojiFormatter = printf(({ level, message, label, timestamp }) => {
310
- return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
311
- });
312
- switch (this.currentFormat) {
313
- case "minimal":
314
- return minimalFormatter;
315
- case "detailed":
316
- return detailedFormatter;
317
- case "emoji":
318
- return emojiFormatter;
319
- default:
320
- return minimalFormatter;
321
- }
322
- }
323
- static async configure(options = {}) {
324
- const { level, console: console2 = true, file, format = "minimal" } = options;
325
- const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
326
- const resolvedLevel = level ?? resolveLevel(debugEnv);
327
- this.currentFormat = format;
328
- if (!isNodeJSEnvironment()) {
329
- Object.values(this.simpleInstances).forEach((logger2) => {
330
- logger2.level = resolvedLevel;
331
- });
332
- return;
333
- }
334
- await getWinston();
335
- if (!winston) {
336
- throw new Error("Failed to load winston");
337
- }
338
- const root = this.get();
339
- root.level = resolvedLevel;
340
- const winstonRoot = root;
341
- winstonRoot.clear();
342
- if (console2) {
343
- winstonRoot.add(new winston.transports.Console());
344
- }
345
- if (file) {
346
- const { fs: nodeFs, path: nodePath } = await getNodeModules();
347
- if (nodeFs && nodePath) {
348
- const dir = nodePath.dirname(nodePath.resolve(file));
349
- if (!nodeFs.existsSync(dir)) {
350
- nodeFs.mkdirSync(dir, { recursive: true });
351
- }
352
- winstonRoot.add(new winston.transports.File({ filename: file }));
353
- }
354
- }
355
- const { format: winstonFormat } = winston;
356
- const { combine, timestamp, label, colorize, splat } = winstonFormat;
357
- Object.values(this.instances).forEach((logger2) => {
358
- if (logger2 && "format" in logger2) {
359
- logger2.level = resolvedLevel;
360
- logger2.format = combine(
361
- colorize(),
362
- splat(),
363
- label({ label: DEFAULT_LOGGER_NAME }),
364
- timestamp({ format: "HH:mm:ss" }),
365
- this.getFormatter()
366
- );
367
- }
368
- });
369
- }
370
- static setDebug(enabled) {
371
- let level;
372
- if (enabled === 2 || enabled === true) level = "debug";
373
- else if (enabled === 1) level = "info";
374
- else level = "info";
375
- Object.values(this.simpleInstances).forEach((logger2) => {
376
- logger2.level = level;
377
- });
378
- Object.values(this.instances).forEach((logger2) => {
379
- if (logger2) {
380
- logger2.level = level;
381
- }
382
- });
383
- if (typeof process !== "undefined" && process.env) {
384
- process.env.DEBUG = enabled ? enabled === true ? "2" : String(enabled) : "0";
385
- }
386
- }
387
- static setFormat(format) {
388
- this.currentFormat = format;
389
- this.configure({ format });
390
- }
391
- };
392
- if (isNodeJSEnvironment()) {
393
- loadWinstonSync();
394
- if (winston) {
395
- Logger.configure();
396
- }
397
- }
398
- logger = Logger.get();
399
- }
400
- });
401
-
402
34
  // src/telemetry/events.ts
403
35
  function createServerRunEventData(server, transport) {
404
36
  const toolRegistrations = Array.from(server.registrations.tools.values());
@@ -468,7 +100,7 @@ function createServerRunEventData(server, transport) {
468
100
  mcpAppsResourcesNumber: mcpAppsResources.length
469
101
  };
470
102
  }
471
- var BaseTelemetryEvent, MCPAgentExecutionEvent, ServerRunEvent, ServerInitializeEvent, ServerToolCallEvent, ServerResourceCallEvent, ServerPromptCallEvent, ServerContextEvent, MCPClientInitEvent, ConnectorInitEvent;
103
+ var BaseTelemetryEvent, MCPAgentExecutionEvent, ServerRunEvent, ServerInitializeEvent, ServerToolCallEvent, ServerResourceCallEvent, ServerPromptCallEvent, ServerContextEvent, MCPClientInitEvent, ConnectorInitEvent, ClientAddServerEvent, ClientRemoveServerEvent;
472
104
  var init_events = __esm({
473
105
  "src/telemetry/events.ts"() {
474
106
  "use strict";
@@ -622,87 +254,502 @@ var init_events = __esm({
622
254
  };
623
255
  }
624
256
  };
625
- ServerPromptCallEvent = class extends BaseTelemetryEvent {
257
+ ServerPromptCallEvent = class extends BaseTelemetryEvent {
258
+ constructor(data) {
259
+ super();
260
+ this.data = data;
261
+ }
262
+ static {
263
+ __name(this, "ServerPromptCallEvent");
264
+ }
265
+ get name() {
266
+ return "server_prompt_call";
267
+ }
268
+ get properties() {
269
+ return {
270
+ name: this.data.name,
271
+ description: this.data.description,
272
+ success: this.data.success,
273
+ error_type: this.data.errorType ?? null
274
+ };
275
+ }
276
+ };
277
+ ServerContextEvent = class extends BaseTelemetryEvent {
278
+ constructor(data) {
279
+ super();
280
+ this.data = data;
281
+ }
282
+ static {
283
+ __name(this, "ServerContextEvent");
284
+ }
285
+ get name() {
286
+ return `server_context_${this.data.contextType}`;
287
+ }
288
+ get properties() {
289
+ return {
290
+ context_type: this.data.contextType,
291
+ notification_type: this.data.notificationType ?? null
292
+ };
293
+ }
294
+ };
295
+ MCPClientInitEvent = class extends BaseTelemetryEvent {
296
+ constructor(data) {
297
+ super();
298
+ this.data = data;
299
+ }
300
+ static {
301
+ __name(this, "MCPClientInitEvent");
302
+ }
303
+ get name() {
304
+ return "mcpclient_init";
305
+ }
306
+ get properties() {
307
+ return {
308
+ code_mode: this.data.codeMode,
309
+ sandbox: this.data.sandbox,
310
+ all_callbacks: this.data.allCallbacks,
311
+ verify: this.data.verify,
312
+ servers: this.data.servers,
313
+ num_servers: this.data.numServers,
314
+ is_browser: this.data.isBrowser
315
+ };
316
+ }
317
+ };
318
+ ConnectorInitEvent = class extends BaseTelemetryEvent {
319
+ constructor(data) {
320
+ super();
321
+ this.data = data;
322
+ }
323
+ static {
324
+ __name(this, "ConnectorInitEvent");
325
+ }
326
+ get name() {
327
+ return "connector_init";
328
+ }
329
+ get properties() {
330
+ return {
331
+ connector_type: this.data.connectorType,
332
+ server_command: this.data.serverCommand ?? null,
333
+ server_args: this.data.serverArgs ?? null,
334
+ server_url: this.data.serverUrl ?? null,
335
+ public_identifier: this.data.publicIdentifier ?? null
336
+ };
337
+ }
338
+ };
339
+ ClientAddServerEvent = class extends BaseTelemetryEvent {
626
340
  constructor(data) {
627
341
  super();
628
342
  this.data = data;
629
343
  }
630
344
  static {
631
- __name(this, "ServerPromptCallEvent");
345
+ __name(this, "ClientAddServerEvent");
632
346
  }
633
347
  get name() {
634
- return "server_prompt_call";
348
+ return "client_add_server";
635
349
  }
636
350
  get properties() {
351
+ const { serverName, serverConfig } = this.data;
352
+ const url = serverConfig.url;
637
353
  return {
638
- name: this.data.name,
639
- description: this.data.description,
640
- success: this.data.success,
641
- error_type: this.data.errorType ?? null
354
+ server_name: serverName,
355
+ server_url_domain: url ? this._extractHostname(url) : null,
356
+ transport: serverConfig.transport ?? null,
357
+ has_auth: !!(serverConfig.authToken || serverConfig.authProvider)
642
358
  };
643
359
  }
360
+ _extractHostname(url) {
361
+ try {
362
+ return new URL(url).hostname;
363
+ } catch {
364
+ return null;
365
+ }
366
+ }
644
367
  };
645
- ServerContextEvent = class extends BaseTelemetryEvent {
368
+ ClientRemoveServerEvent = class extends BaseTelemetryEvent {
646
369
  constructor(data) {
647
370
  super();
648
371
  this.data = data;
649
372
  }
650
373
  static {
651
- __name(this, "ServerContextEvent");
374
+ __name(this, "ClientRemoveServerEvent");
652
375
  }
653
376
  get name() {
654
- return `server_context_${this.data.contextType}`;
377
+ return "client_remove_server";
655
378
  }
656
379
  get properties() {
657
380
  return {
658
- context_type: this.data.contextType,
659
- notification_type: this.data.notificationType ?? null
381
+ server_name: this.data.serverName
660
382
  };
661
383
  }
662
- };
663
- MCPClientInitEvent = class extends BaseTelemetryEvent {
664
- constructor(data) {
665
- super();
666
- this.data = data;
384
+ };
385
+ }
386
+ });
387
+
388
+ // src/server/utils/runtime.ts
389
+ function getEnv(key) {
390
+ if (isDeno) {
391
+ return globalThis.Deno.env.get(key);
392
+ }
393
+ return process.env[key];
394
+ }
395
+ function getCwd() {
396
+ if (isDeno) {
397
+ return globalThis.Deno.cwd();
398
+ }
399
+ return process.cwd();
400
+ }
401
+ function generateUUID() {
402
+ return globalThis.crypto.randomUUID();
403
+ }
404
+ var isDeno, fsHelpers, pathHelpers;
405
+ var init_runtime = __esm({
406
+ "src/server/utils/runtime.ts"() {
407
+ "use strict";
408
+ isDeno = typeof globalThis.Deno !== "undefined";
409
+ __name(getEnv, "getEnv");
410
+ __name(getCwd, "getCwd");
411
+ fsHelpers = {
412
+ async readFileSync(path, encoding = "utf8") {
413
+ if (isDeno) {
414
+ return await globalThis.Deno.readTextFile(path);
415
+ }
416
+ const { readFileSync } = await import("fs");
417
+ const result = readFileSync(path, encoding);
418
+ return typeof result === "string" ? result : result.toString(encoding);
419
+ },
420
+ async readFile(path) {
421
+ if (isDeno) {
422
+ const data = await globalThis.Deno.readFile(path);
423
+ return data.buffer;
424
+ }
425
+ const { readFileSync } = await import("fs");
426
+ const buffer = readFileSync(path);
427
+ return buffer.buffer.slice(
428
+ buffer.byteOffset,
429
+ buffer.byteOffset + buffer.byteLength
430
+ );
431
+ },
432
+ async existsSync(path) {
433
+ if (isDeno) {
434
+ try {
435
+ await globalThis.Deno.stat(path);
436
+ return true;
437
+ } catch {
438
+ return false;
439
+ }
440
+ }
441
+ const { existsSync } = await import("fs");
442
+ return existsSync(path);
443
+ },
444
+ async readdirSync(path) {
445
+ if (isDeno) {
446
+ const entries = [];
447
+ for await (const entry of globalThis.Deno.readDir(path)) {
448
+ entries.push(entry.name);
449
+ }
450
+ return entries;
451
+ }
452
+ const { readdirSync } = await import("fs");
453
+ return readdirSync(path);
454
+ }
455
+ };
456
+ pathHelpers = {
457
+ join(...paths) {
458
+ if (isDeno) {
459
+ return paths.join("/").replace(/\/+/g, "/");
460
+ }
461
+ return paths.join("/").replace(/\/+/g, "/");
462
+ },
463
+ relative(from, to) {
464
+ const fromParts = from.split("/").filter((p) => p);
465
+ const toParts = to.split("/").filter((p) => p);
466
+ let i = 0;
467
+ while (i < fromParts.length && i < toParts.length && fromParts[i] === toParts[i]) {
468
+ i++;
469
+ }
470
+ const upCount = fromParts.length - i;
471
+ const relativeParts = [...Array(upCount).fill(".."), ...toParts.slice(i)];
472
+ return relativeParts.join("/");
473
+ }
474
+ };
475
+ __name(generateUUID, "generateUUID");
476
+ }
477
+ });
478
+
479
+ // src/logging.ts
480
+ async function getNodeModules() {
481
+ if (typeof process !== "undefined" && process.platform) {
482
+ try {
483
+ const fs = await import("fs");
484
+ const path = await import("path");
485
+ return { fs: fs.default, path: path.default };
486
+ } catch {
487
+ return { fs: null, path: null };
488
+ }
489
+ }
490
+ return { fs: null, path: null };
491
+ }
492
+ function loadWinstonSync() {
493
+ if (typeof require !== "undefined") {
494
+ try {
495
+ winston = require("winston");
496
+ } catch {
497
+ }
498
+ }
499
+ }
500
+ async function getWinston() {
501
+ if (!winston) {
502
+ winston = await import("winston");
503
+ }
504
+ return winston;
505
+ }
506
+ function isNodeJSEnvironment() {
507
+ try {
508
+ if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
509
+ return false;
510
+ }
511
+ if (typeof globalThis.EdgeRuntime !== "undefined" || typeof globalThis.Deno !== "undefined") {
512
+ return false;
513
+ }
514
+ const hasNodeGlobals = typeof process !== "undefined" && typeof process.platform !== "undefined" && typeof __dirname !== "undefined";
515
+ return hasNodeGlobals;
516
+ } catch {
517
+ return false;
518
+ }
519
+ }
520
+ function resolveLevel(env) {
521
+ const envValue = typeof process !== "undefined" && process.env ? env : void 0;
522
+ switch (envValue?.trim()) {
523
+ case "2":
524
+ return "debug";
525
+ case "1":
526
+ return "info";
527
+ default:
528
+ return "info";
529
+ }
530
+ }
531
+ var winston, DEFAULT_LOGGER_NAME, SimpleConsoleLogger, Logger, logger;
532
+ var init_logging = __esm({
533
+ "src/logging.ts"() {
534
+ "use strict";
535
+ __name(getNodeModules, "getNodeModules");
536
+ winston = null;
537
+ __name(loadWinstonSync, "loadWinstonSync");
538
+ __name(getWinston, "getWinston");
539
+ DEFAULT_LOGGER_NAME = "mcp-use";
540
+ __name(isNodeJSEnvironment, "isNodeJSEnvironment");
541
+ SimpleConsoleLogger = class {
542
+ static {
543
+ __name(this, "SimpleConsoleLogger");
544
+ }
545
+ _level;
546
+ name;
547
+ constructor(name = DEFAULT_LOGGER_NAME, level = "info") {
548
+ this.name = name;
549
+ this._level = level;
550
+ }
551
+ shouldLog(level) {
552
+ const levels = [
553
+ "error",
554
+ "warn",
555
+ "info",
556
+ "http",
557
+ "verbose",
558
+ "debug",
559
+ "silly"
560
+ ];
561
+ const currentIndex = levels.indexOf(this._level);
562
+ const messageIndex = levels.indexOf(level);
563
+ return messageIndex <= currentIndex;
564
+ }
565
+ formatMessage(level, message) {
566
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
567
+ return `${timestamp} [${this.name}] ${level}: ${message}`;
568
+ }
569
+ error(message) {
570
+ if (this.shouldLog("error")) {
571
+ console.error(this.formatMessage("error", message));
572
+ }
573
+ }
574
+ warn(message) {
575
+ if (this.shouldLog("warn")) {
576
+ console.warn(this.formatMessage("warn", message));
577
+ }
578
+ }
579
+ info(message) {
580
+ if (this.shouldLog("info")) {
581
+ console.info(this.formatMessage("info", message));
582
+ }
583
+ }
584
+ debug(message) {
585
+ if (this.shouldLog("debug")) {
586
+ console.debug(this.formatMessage("debug", message));
587
+ }
588
+ }
589
+ http(message) {
590
+ if (this.shouldLog("http")) {
591
+ console.log(this.formatMessage("http", message));
592
+ }
593
+ }
594
+ verbose(message) {
595
+ if (this.shouldLog("verbose")) {
596
+ console.log(this.formatMessage("verbose", message));
597
+ }
598
+ }
599
+ silly(message) {
600
+ if (this.shouldLog("silly")) {
601
+ console.log(this.formatMessage("silly", message));
602
+ }
603
+ }
604
+ // Make it compatible with Winston interface
605
+ get level() {
606
+ return this._level;
607
+ }
608
+ set level(newLevel) {
609
+ this._level = newLevel;
610
+ }
611
+ };
612
+ __name(resolveLevel, "resolveLevel");
613
+ Logger = class {
614
+ static {
615
+ __name(this, "Logger");
616
+ }
617
+ static instances = {};
618
+ static simpleInstances = {};
619
+ static currentFormat = "minimal";
620
+ static get(name = DEFAULT_LOGGER_NAME) {
621
+ if (!isNodeJSEnvironment()) {
622
+ if (!this.simpleInstances[name]) {
623
+ const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
624
+ this.simpleInstances[name] = new SimpleConsoleLogger(
625
+ name,
626
+ resolveLevel(debugEnv)
627
+ );
628
+ }
629
+ return this.simpleInstances[name];
630
+ }
631
+ if (!this.instances[name]) {
632
+ if (!winston) {
633
+ throw new Error("Winston not loaded - call Logger.configure() first");
634
+ }
635
+ const { createLogger, format } = winston;
636
+ const { combine, timestamp, label, colorize, splat } = format;
637
+ this.instances[name] = createLogger({
638
+ level: resolveLevel(process.env.DEBUG),
639
+ format: combine(
640
+ colorize(),
641
+ splat(),
642
+ label({ label: name }),
643
+ timestamp({ format: "HH:mm:ss" }),
644
+ this.getFormatter()
645
+ ),
646
+ transports: []
647
+ });
648
+ }
649
+ return this.instances[name];
650
+ }
651
+ static getFormatter() {
652
+ if (!winston) {
653
+ throw new Error("Winston not loaded");
654
+ }
655
+ const { format } = winston;
656
+ const { printf } = format;
657
+ const minimalFormatter = printf(({ level, message, label, timestamp }) => {
658
+ return `${timestamp} [${label}] ${level}: ${message}`;
659
+ });
660
+ const detailedFormatter = printf(({ level, message, label, timestamp }) => {
661
+ return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
662
+ });
663
+ const emojiFormatter = printf(({ level, message, label, timestamp }) => {
664
+ return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
665
+ });
666
+ switch (this.currentFormat) {
667
+ case "minimal":
668
+ return minimalFormatter;
669
+ case "detailed":
670
+ return detailedFormatter;
671
+ case "emoji":
672
+ return emojiFormatter;
673
+ default:
674
+ return minimalFormatter;
675
+ }
667
676
  }
668
- static {
669
- __name(this, "MCPClientInitEvent");
677
+ static async configure(options = {}) {
678
+ const { level, console: console2 = true, file, format = "minimal" } = options;
679
+ const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
680
+ const resolvedLevel = level ?? resolveLevel(debugEnv);
681
+ this.currentFormat = format;
682
+ if (!isNodeJSEnvironment()) {
683
+ Object.values(this.simpleInstances).forEach((logger2) => {
684
+ logger2.level = resolvedLevel;
685
+ });
686
+ return;
687
+ }
688
+ await getWinston();
689
+ if (!winston) {
690
+ throw new Error("Failed to load winston");
691
+ }
692
+ const root = this.get();
693
+ root.level = resolvedLevel;
694
+ const winstonRoot = root;
695
+ winstonRoot.clear();
696
+ if (console2) {
697
+ winstonRoot.add(new winston.transports.Console());
698
+ }
699
+ if (file) {
700
+ const { fs: nodeFs, path: nodePath } = await getNodeModules();
701
+ if (nodeFs && nodePath) {
702
+ const dir = nodePath.dirname(nodePath.resolve(file));
703
+ if (!nodeFs.existsSync(dir)) {
704
+ nodeFs.mkdirSync(dir, { recursive: true });
705
+ }
706
+ winstonRoot.add(new winston.transports.File({ filename: file }));
707
+ }
708
+ }
709
+ const { format: winstonFormat } = winston;
710
+ const { combine, timestamp, label, colorize, splat } = winstonFormat;
711
+ Object.values(this.instances).forEach((logger2) => {
712
+ if (logger2 && "format" in logger2) {
713
+ logger2.level = resolvedLevel;
714
+ logger2.format = combine(
715
+ colorize(),
716
+ splat(),
717
+ label({ label: DEFAULT_LOGGER_NAME }),
718
+ timestamp({ format: "HH:mm:ss" }),
719
+ this.getFormatter()
720
+ );
721
+ }
722
+ });
670
723
  }
671
- get name() {
672
- return "mcpclient_init";
724
+ static setDebug(enabled) {
725
+ let level;
726
+ if (enabled === 2 || enabled === true) level = "debug";
727
+ else if (enabled === 1) level = "info";
728
+ else level = "info";
729
+ Object.values(this.simpleInstances).forEach((logger2) => {
730
+ logger2.level = level;
731
+ });
732
+ Object.values(this.instances).forEach((logger2) => {
733
+ if (logger2) {
734
+ logger2.level = level;
735
+ }
736
+ });
737
+ if (typeof process !== "undefined" && process.env) {
738
+ process.env.DEBUG = enabled ? enabled === true ? "2" : String(enabled) : "0";
739
+ }
673
740
  }
674
- get properties() {
675
- return {
676
- code_mode: this.data.codeMode,
677
- sandbox: this.data.sandbox,
678
- all_callbacks: this.data.allCallbacks,
679
- verify: this.data.verify,
680
- servers: this.data.servers,
681
- num_servers: this.data.numServers
682
- };
741
+ static setFormat(format) {
742
+ this.currentFormat = format;
743
+ this.configure({ format });
683
744
  }
684
745
  };
685
- ConnectorInitEvent = class extends BaseTelemetryEvent {
686
- constructor(data) {
687
- super();
688
- this.data = data;
689
- }
690
- static {
691
- __name(this, "ConnectorInitEvent");
692
- }
693
- get name() {
694
- return "connector_init";
695
- }
696
- get properties() {
697
- return {
698
- connector_type: this.data.connectorType,
699
- server_command: this.data.serverCommand ?? null,
700
- server_args: this.data.serverArgs ?? null,
701
- server_url: this.data.serverUrl ?? null,
702
- public_identifier: this.data.publicIdentifier ?? null
703
- };
746
+ if (isNodeJSEnvironment()) {
747
+ loadWinstonSync();
748
+ if (winston) {
749
+ Logger.configure();
704
750
  }
705
- };
751
+ }
752
+ logger = Logger.get();
706
753
  }
707
754
  });
708
755
 
@@ -714,7 +761,7 @@ var VERSION;
714
761
  var init_version = __esm({
715
762
  "src/version.ts"() {
716
763
  "use strict";
717
- VERSION = "1.10.0-canary.8";
764
+ VERSION = "1.10.0";
718
765
  __name(getPackageVersion, "getPackageVersion");
719
766
  }
720
767
  });
@@ -742,12 +789,12 @@ function detectRuntimeEnvironment() {
742
789
  if (typeof globalThis.EdgeRuntime !== "undefined") {
743
790
  return "edge";
744
791
  }
745
- if (typeof process !== "undefined" && typeof process.versions?.node !== "undefined" && typeof fs !== "undefined" && typeof fs.existsSync === "function") {
746
- return "node";
747
- }
748
792
  if (typeof window !== "undefined" && typeof document !== "undefined") {
749
793
  return "browser";
750
794
  }
795
+ if (typeof process !== "undefined" && typeof process.versions?.node !== "undefined") {
796
+ return "node";
797
+ }
751
798
  return "unknown";
752
799
  } catch {
753
800
  return "unknown";
@@ -780,40 +827,10 @@ function getRuntimeEnvironment() {
780
827
  }
781
828
  return cachedEnvironment;
782
829
  }
783
- function isNodeJSEnvironment2() {
784
- const env = getRuntimeEnvironment();
785
- return env === "node" || env === "bun";
786
- }
787
- function getCacheHome() {
788
- if (!isNodeJSEnvironment2()) {
789
- return "/tmp/mcp_use_cache";
790
- }
791
- const envVar = process.env.XDG_CACHE_HOME;
792
- if (envVar && path.isAbsolute(envVar)) {
793
- return envVar;
794
- }
795
- const platform = process.platform;
796
- const homeDir = os.homedir();
797
- if (platform === "win32") {
798
- const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;
799
- if (appdata) {
800
- return appdata;
801
- }
802
- return path.join(homeDir, "AppData", "Local");
803
- } else if (platform === "darwin") {
804
- return path.join(homeDir, "Library", "Caches");
805
- } else {
806
- return path.join(homeDir, ".cache");
807
- }
808
- }
809
- var fs, os, path, import_posthog_node, USER_ID_STORAGE_KEY, cachedEnvironment, ScarfEventLogger, Telemetry;
830
+ var USER_ID_STORAGE_KEY, cachedEnvironment, ScarfEventLogger, Telemetry;
810
831
  var init_telemetry = __esm({
811
832
  "src/telemetry/telemetry.ts"() {
812
833
  "use strict";
813
- fs = __toESM(require("fs"), 1);
814
- os = __toESM(require("os"), 1);
815
- path = __toESM(require("path"), 1);
816
- import_posthog_node = require("posthog-node");
817
834
  init_runtime();
818
835
  init_logging();
819
836
  init_events();
@@ -823,7 +840,6 @@ var init_telemetry = __esm({
823
840
  __name(getStorageCapability, "getStorageCapability");
824
841
  cachedEnvironment = null;
825
842
  __name(getRuntimeEnvironment, "getRuntimeEnvironment");
826
- __name(isNodeJSEnvironment2, "isNodeJSEnvironment");
827
843
  ScarfEventLogger = class {
828
844
  static {
829
845
  __name(this, "ScarfEventLogger");
@@ -855,49 +871,40 @@ var init_telemetry = __esm({
855
871
  }
856
872
  }
857
873
  };
858
- __name(getCacheHome, "getCacheHome");
859
874
  Telemetry = class _Telemetry {
860
875
  static {
861
876
  __name(this, "Telemetry");
862
877
  }
863
878
  static instance = null;
864
- USER_ID_PATH = path.join(
865
- getCacheHome(),
866
- "mcp_use_3",
867
- "telemetry_user_id"
868
- );
869
- VERSION_DOWNLOAD_PATH = path.join(
870
- getCacheHome(),
871
- "mcp_use",
872
- "download_version"
873
- );
874
879
  PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
875
880
  HOST = "https://eu.i.posthog.com";
876
881
  SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
877
882
  UNKNOWN_USER_ID = "UNKNOWN_USER_ID";
878
883
  _currUserId = null;
879
- _posthogClient = null;
884
+ _posthogNodeClient = null;
885
+ _posthogBrowserClient = null;
886
+ _posthogLoading = null;
880
887
  _scarfClient = null;
881
888
  _runtimeEnvironment;
882
889
  _storageCapability;
883
890
  _source;
891
+ // Node.js specific paths (lazily computed)
892
+ _userIdPath = null;
893
+ _versionDownloadPath = null;
884
894
  constructor() {
885
895
  this._runtimeEnvironment = getRuntimeEnvironment();
886
896
  this._storageCapability = getStorageCapability(this._runtimeEnvironment);
887
897
  this._source = typeof process !== "undefined" && process.env?.MCP_USE_TELEMETRY_SOURCE || this._runtimeEnvironment;
888
- const telemetryDisabled = typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false" || false;
898
+ const telemetryDisabled = this._checkTelemetryDisabled();
889
899
  const canSupportTelemetry = this._runtimeEnvironment !== "unknown";
890
- const isServerlessEnvironment = [
891
- "cloudflare-workers",
892
- "edge",
893
- "deno"
894
- ].includes(this._runtimeEnvironment);
895
900
  if (telemetryDisabled) {
896
- this._posthogClient = null;
901
+ this._posthogNodeClient = null;
902
+ this._posthogBrowserClient = null;
897
903
  this._scarfClient = null;
898
- logger.debug("Telemetry disabled via environment variable");
904
+ logger.debug("Telemetry disabled via environment/localStorage");
899
905
  } else if (!canSupportTelemetry) {
900
- this._posthogClient = null;
906
+ this._posthogNodeClient = null;
907
+ this._posthogBrowserClient = null;
901
908
  this._scarfClient = null;
902
909
  logger.debug(
903
910
  `Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`
@@ -906,27 +913,7 @@ var init_telemetry = __esm({
906
913
  logger.info(
907
914
  "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
908
915
  );
909
- if (this._runtimeEnvironment !== "browser") {
910
- try {
911
- const posthogOptions = {
912
- host: this.HOST,
913
- disableGeoip: false
914
- };
915
- if (isServerlessEnvironment) {
916
- posthogOptions.flushAt = 1;
917
- posthogOptions.flushInterval = 0;
918
- }
919
- this._posthogClient = new import_posthog_node.PostHog(
920
- this.PROJECT_API_KEY,
921
- posthogOptions
922
- );
923
- } catch (e) {
924
- logger.warn(`Failed to initialize PostHog telemetry: ${e}`);
925
- this._posthogClient = null;
926
- }
927
- } else {
928
- this._posthogClient = null;
929
- }
916
+ this._posthogLoading = this._initPostHog();
930
917
  try {
931
918
  this._scarfClient = new ScarfEventLogger(this.SCARF_GATEWAY_URL, 3e3);
932
919
  } catch (e) {
@@ -935,6 +922,75 @@ var init_telemetry = __esm({
935
922
  }
936
923
  }
937
924
  }
925
+ _checkTelemetryDisabled() {
926
+ if (typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false") {
927
+ return true;
928
+ }
929
+ if (typeof localStorage !== "undefined" && localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY") === "false") {
930
+ return true;
931
+ }
932
+ return false;
933
+ }
934
+ async _initPostHog() {
935
+ const isBrowser = this._runtimeEnvironment === "browser";
936
+ if (isBrowser) {
937
+ await this._initPostHogBrowser();
938
+ } else {
939
+ await this._initPostHogNode();
940
+ }
941
+ }
942
+ async _initPostHogBrowser() {
943
+ try {
944
+ const posthogModule = await import("posthog-js");
945
+ const posthog = posthogModule.default || posthogModule.posthog;
946
+ if (!posthog || typeof posthog.init !== "function") {
947
+ throw new Error("posthog-js module did not export expected interface");
948
+ }
949
+ posthog.init(this.PROJECT_API_KEY, {
950
+ api_host: this.HOST,
951
+ persistence: "localStorage",
952
+ autocapture: false,
953
+ // We only want explicit captures
954
+ capture_pageview: false,
955
+ // We don't want automatic pageview tracking
956
+ disable_session_recording: true,
957
+ // No session recording
958
+ loaded: /* @__PURE__ */ __name(() => {
959
+ logger.debug("PostHog browser client initialized");
960
+ }, "loaded")
961
+ });
962
+ this._posthogBrowserClient = posthog;
963
+ } catch (e) {
964
+ logger.warn(`Failed to initialize PostHog browser telemetry: ${e}`);
965
+ this._posthogBrowserClient = null;
966
+ }
967
+ }
968
+ async _initPostHogNode() {
969
+ try {
970
+ const { PostHog } = await import("posthog-node");
971
+ const isServerlessEnvironment = [
972
+ "cloudflare-workers",
973
+ "edge",
974
+ "deno"
975
+ ].includes(this._runtimeEnvironment);
976
+ const posthogOptions = {
977
+ host: this.HOST,
978
+ disableGeoip: false
979
+ };
980
+ if (isServerlessEnvironment) {
981
+ posthogOptions.flushAt = 1;
982
+ posthogOptions.flushInterval = 0;
983
+ }
984
+ this._posthogNodeClient = new PostHog(
985
+ this.PROJECT_API_KEY,
986
+ posthogOptions
987
+ );
988
+ logger.debug("PostHog Node.js client initialized");
989
+ } catch (e) {
990
+ logger.warn(`Failed to initialize PostHog Node.js telemetry: ${e}`);
991
+ this._posthogNodeClient = null;
992
+ }
993
+ }
938
994
  /**
939
995
  * Get the detected runtime environment
940
996
  */
@@ -970,10 +1026,9 @@ var init_telemetry = __esm({
970
1026
  }
971
1027
  /**
972
1028
  * Check if telemetry is enabled.
973
- * Returns false if telemetry was disabled via environment variable or if not in Node.js environment.
974
1029
  */
975
1030
  get isEnabled() {
976
- return this._posthogClient !== null || this._scarfClient !== null;
1031
+ return this._posthogNodeClient !== null || this._posthogBrowserClient !== null || this._scarfClient !== null;
977
1032
  }
978
1033
  get userId() {
979
1034
  if (this._currUserId) {
@@ -982,10 +1037,10 @@ var init_telemetry = __esm({
982
1037
  try {
983
1038
  switch (this._storageCapability) {
984
1039
  case "filesystem":
985
- this._currUserId = this.getUserIdFromFilesystem();
1040
+ this._currUserId = this._getUserIdFromFilesystem();
986
1041
  break;
987
1042
  case "localStorage":
988
- this._currUserId = this.getUserIdFromLocalStorage();
1043
+ this._currUserId = this._getUserIdFromLocalStorage();
989
1044
  break;
990
1045
  case "session-only":
991
1046
  default:
@@ -996,7 +1051,7 @@ var init_telemetry = __esm({
996
1051
  break;
997
1052
  }
998
1053
  if (this._storageCapability === "filesystem" && this._currUserId) {
999
- this.trackPackageDownloadInternal(this._currUserId, {
1054
+ this._trackPackageDownloadInternal(this._currUserId, {
1000
1055
  triggered_by: "user_id_property"
1001
1056
  }).catch((e) => logger.debug(`Failed to track package download: ${e}`));
1002
1057
  }
@@ -1009,22 +1064,32 @@ var init_telemetry = __esm({
1009
1064
  /**
1010
1065
  * Get or create user ID from filesystem (Node.js/Bun)
1011
1066
  */
1012
- getUserIdFromFilesystem() {
1013
- const isFirstTime = !fs.existsSync(this.USER_ID_PATH);
1067
+ _getUserIdFromFilesystem() {
1068
+ const fs = require("fs");
1069
+ const os = require("os");
1070
+ const path = require("path");
1071
+ if (!this._userIdPath) {
1072
+ this._userIdPath = path.join(
1073
+ this._getCacheHome(os, path),
1074
+ "mcp_use_3",
1075
+ "telemetry_user_id"
1076
+ );
1077
+ }
1078
+ const isFirstTime = !fs.existsSync(this._userIdPath);
1014
1079
  if (isFirstTime) {
1015
- logger.debug(`Creating user ID path: ${this.USER_ID_PATH}`);
1016
- fs.mkdirSync(path.dirname(this.USER_ID_PATH), { recursive: true });
1080
+ logger.debug(`Creating user ID path: ${this._userIdPath}`);
1081
+ fs.mkdirSync(path.dirname(this._userIdPath), { recursive: true });
1017
1082
  const newUserId = generateUUID();
1018
- fs.writeFileSync(this.USER_ID_PATH, newUserId);
1019
- logger.debug(`User ID path created: ${this.USER_ID_PATH}`);
1083
+ fs.writeFileSync(this._userIdPath, newUserId);
1084
+ logger.debug(`User ID path created: ${this._userIdPath}`);
1020
1085
  return newUserId;
1021
1086
  }
1022
- return fs.readFileSync(this.USER_ID_PATH, "utf-8").trim();
1087
+ return fs.readFileSync(this._userIdPath, "utf-8").trim();
1023
1088
  }
1024
1089
  /**
1025
1090
  * Get or create user ID from localStorage (Browser)
1026
1091
  */
1027
- getUserIdFromLocalStorage() {
1092
+ _getUserIdFromLocalStorage() {
1028
1093
  try {
1029
1094
  let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
1030
1095
  if (!userId) {
@@ -1038,60 +1103,89 @@ var init_telemetry = __esm({
1038
1103
  return `session-${generateUUID()}`;
1039
1104
  }
1040
1105
  }
1106
+ _getCacheHome(os, path) {
1107
+ const envVar = process.env.XDG_CACHE_HOME;
1108
+ if (envVar && path.isAbsolute(envVar)) {
1109
+ return envVar;
1110
+ }
1111
+ const platform = process.platform;
1112
+ const homeDir = os.homedir();
1113
+ if (platform === "win32") {
1114
+ const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;
1115
+ if (appdata) {
1116
+ return appdata;
1117
+ }
1118
+ return path.join(homeDir, "AppData", "Local");
1119
+ } else if (platform === "darwin") {
1120
+ return path.join(homeDir, "Library", "Caches");
1121
+ } else {
1122
+ return path.join(homeDir, ".cache");
1123
+ }
1124
+ }
1041
1125
  async capture(event) {
1042
- logger.debug(
1043
- `CAPTURE: posthog: ${this._posthogClient !== null}, scarf: ${this._scarfClient !== null}`
1044
- );
1045
- if (!this._posthogClient && !this._scarfClient) {
1126
+ if (this._posthogLoading) {
1127
+ await this._posthogLoading;
1128
+ }
1129
+ if (!this._posthogNodeClient && !this._posthogBrowserClient && !this._scarfClient) {
1046
1130
  return;
1047
1131
  }
1048
- if (this._posthogClient) {
1132
+ const properties = { ...event.properties };
1133
+ properties.mcp_use_version = getPackageVersion();
1134
+ properties.language = "typescript";
1135
+ properties.source = this._source;
1136
+ properties.runtime = this._runtimeEnvironment;
1137
+ if (this._posthogNodeClient) {
1049
1138
  try {
1050
- const properties = { ...event.properties };
1051
- properties.mcp_use_version = getPackageVersion();
1052
- properties.language = "typescript";
1053
- properties.source = this._source;
1054
- properties.runtime = this._runtimeEnvironment;
1055
- logger.debug(`CAPTURE: PostHog Event ${event.name}`);
1056
- logger.debug(
1057
- `CAPTURE: PostHog Properties ${JSON.stringify(properties)}`
1058
- );
1059
- this._posthogClient.capture({
1139
+ logger.debug(`CAPTURE: PostHog Node Event ${event.name}`);
1140
+ this._posthogNodeClient.capture({
1060
1141
  distinctId: this.userId,
1061
1142
  event: event.name,
1062
1143
  properties
1063
1144
  });
1064
1145
  } catch (e) {
1065
- logger.debug(`Failed to track PostHog event ${event.name}: ${e}`);
1146
+ logger.debug(`Failed to track PostHog Node event ${event.name}: ${e}`);
1147
+ }
1148
+ }
1149
+ if (this._posthogBrowserClient) {
1150
+ try {
1151
+ logger.debug(`CAPTURE: PostHog Browser Event ${event.name}`);
1152
+ this._posthogBrowserClient.capture(event.name, {
1153
+ ...properties,
1154
+ distinct_id: this.userId
1155
+ });
1156
+ } catch (e) {
1157
+ logger.debug(
1158
+ `Failed to track PostHog Browser event ${event.name}: ${e}`
1159
+ );
1066
1160
  }
1067
1161
  }
1068
1162
  if (this._scarfClient) {
1069
1163
  try {
1070
- const properties = {};
1071
- properties.mcp_use_version = getPackageVersion();
1072
- properties.user_id = this.userId;
1073
- properties.event = event.name;
1074
- properties.language = "typescript";
1075
- properties.source = this._source;
1076
- properties.runtime = this._runtimeEnvironment;
1077
- await this._scarfClient.logEvent(properties);
1164
+ const scarfProperties = {
1165
+ ...properties,
1166
+ user_id: this.userId,
1167
+ event: event.name
1168
+ };
1169
+ await this._scarfClient.logEvent(scarfProperties);
1078
1170
  } catch (e) {
1079
1171
  logger.debug(`Failed to track Scarf event ${event.name}: ${e}`);
1080
1172
  }
1081
1173
  }
1082
1174
  }
1175
+ // ============================================================================
1176
+ // Package Download Tracking (Node.js only)
1177
+ // ============================================================================
1083
1178
  /**
1084
1179
  * Track package download event.
1085
1180
  * This is a public wrapper that safely accesses userId.
1086
1181
  */
1087
1182
  async trackPackageDownload(properties) {
1088
- return this.trackPackageDownloadInternal(this.userId, properties);
1183
+ return this._trackPackageDownloadInternal(this.userId, properties);
1089
1184
  }
1090
1185
  /**
1091
1186
  * Internal method to track package download with explicit userId.
1092
- * This avoids circular dependency when called from the userId getter.
1093
1187
  */
1094
- async trackPackageDownloadInternal(userId, properties) {
1188
+ async _trackPackageDownloadInternal(userId, properties) {
1095
1189
  if (!this._scarfClient) {
1096
1190
  return;
1097
1191
  }
@@ -1099,22 +1193,32 @@ var init_telemetry = __esm({
1099
1193
  return;
1100
1194
  }
1101
1195
  try {
1196
+ const fs = require("fs");
1197
+ const path = require("path");
1198
+ const os = require("os");
1199
+ if (!this._versionDownloadPath) {
1200
+ this._versionDownloadPath = path.join(
1201
+ this._getCacheHome(os, path),
1202
+ "mcp_use",
1203
+ "download_version"
1204
+ );
1205
+ }
1102
1206
  const currentVersion = getPackageVersion();
1103
1207
  let shouldTrack = false;
1104
1208
  let firstDownload = false;
1105
- if (!fs.existsSync(this.VERSION_DOWNLOAD_PATH)) {
1209
+ if (!fs.existsSync(this._versionDownloadPath)) {
1106
1210
  shouldTrack = true;
1107
1211
  firstDownload = true;
1108
- fs.mkdirSync(path.dirname(this.VERSION_DOWNLOAD_PATH), {
1212
+ fs.mkdirSync(path.dirname(this._versionDownloadPath), {
1109
1213
  recursive: true
1110
1214
  });
1111
- fs.writeFileSync(this.VERSION_DOWNLOAD_PATH, currentVersion);
1215
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
1112
1216
  } else {
1113
- const savedVersion = fs.readFileSync(this.VERSION_DOWNLOAD_PATH, "utf-8").trim();
1217
+ const savedVersion = fs.readFileSync(this._versionDownloadPath, "utf-8").trim();
1114
1218
  if (currentVersion > savedVersion) {
1115
1219
  shouldTrack = true;
1116
1220
  firstDownload = false;
1117
- fs.writeFileSync(this.VERSION_DOWNLOAD_PATH, currentVersion);
1221
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
1118
1222
  }
1119
1223
  }
1120
1224
  if (shouldTrack) {
@@ -1148,9 +1252,6 @@ var init_telemetry = __esm({
1148
1252
  // ============================================================================
1149
1253
  /**
1150
1254
  * Track server run event directly from an MCPServer instance.
1151
- * This extracts the necessary data from the server and creates the event.
1152
- * @param server - The MCPServer instance (or any object conforming to MCPServerTelemetryInfo)
1153
- * @param transport - The transport type (e.g., "http", "stdio", "supabase")
1154
1255
  */
1155
1256
  async trackServerRunFromServer(server, transport) {
1156
1257
  if (!this.isEnabled) return;
@@ -1196,31 +1297,118 @@ var init_telemetry = __esm({
1196
1297
  const event = new ConnectorInitEvent(data);
1197
1298
  await this.capture(event);
1198
1299
  }
1300
+ async trackClientAddServer(serverName, serverConfig) {
1301
+ if (!this.isEnabled) return;
1302
+ const event = new ClientAddServerEvent({ serverName, serverConfig });
1303
+ await this.capture(event);
1304
+ }
1305
+ async trackClientRemoveServer(serverName) {
1306
+ if (!this.isEnabled) return;
1307
+ const event = new ClientRemoveServerEvent({ serverName });
1308
+ await this.capture(event);
1309
+ }
1310
+ // ============================================================================
1311
+ // React Hook / Browser specific events
1312
+ // ============================================================================
1313
+ async trackUseMcpConnection(data) {
1314
+ if (!this.isEnabled) return;
1315
+ await this.capture({
1316
+ name: "usemcp_connection",
1317
+ properties: {
1318
+ url_domain: new URL(data.url).hostname,
1319
+ // Only domain for privacy
1320
+ transport_type: data.transportType,
1321
+ success: data.success,
1322
+ error_type: data.errorType ?? null,
1323
+ connection_time_ms: data.connectionTimeMs ?? null,
1324
+ has_oauth: data.hasOAuth,
1325
+ has_sampling: data.hasSampling,
1326
+ has_elicitation: data.hasElicitation
1327
+ }
1328
+ });
1329
+ }
1330
+ async trackUseMcpToolCall(data) {
1331
+ if (!this.isEnabled) return;
1332
+ await this.capture({
1333
+ name: "usemcp_tool_call",
1334
+ properties: {
1335
+ tool_name: data.toolName,
1336
+ success: data.success,
1337
+ error_type: data.errorType ?? null,
1338
+ execution_time_ms: data.executionTimeMs ?? null
1339
+ }
1340
+ });
1341
+ }
1342
+ async trackUseMcpResourceRead(data) {
1343
+ if (!this.isEnabled) return;
1344
+ await this.capture({
1345
+ name: "usemcp_resource_read",
1346
+ properties: {
1347
+ resource_uri_scheme: data.resourceUri.split(":")[0],
1348
+ // Only scheme for privacy
1349
+ success: data.success,
1350
+ error_type: data.errorType ?? null
1351
+ }
1352
+ });
1353
+ }
1354
+ // ============================================================================
1355
+ // Browser-specific Methods
1356
+ // ============================================================================
1357
+ /**
1358
+ * Identify the current user (useful for linking sessions)
1359
+ * Browser only - no-op in Node.js
1360
+ */
1361
+ identify(userId, properties) {
1362
+ if (this._posthogBrowserClient) {
1363
+ try {
1364
+ this._posthogBrowserClient.identify(userId, properties);
1365
+ } catch (e) {
1366
+ logger.debug(`Failed to identify user: ${e}`);
1367
+ }
1368
+ }
1369
+ }
1370
+ /**
1371
+ * Reset the user identity (useful for logout)
1372
+ * Browser only - no-op in Node.js
1373
+ */
1374
+ reset() {
1375
+ if (this._posthogBrowserClient) {
1376
+ try {
1377
+ this._posthogBrowserClient.reset();
1378
+ } catch (e) {
1379
+ logger.debug(`Failed to reset user: ${e}`);
1380
+ }
1381
+ }
1382
+ this._currUserId = null;
1383
+ }
1384
+ // ============================================================================
1385
+ // Node.js-specific Methods
1386
+ // ============================================================================
1387
+ /**
1388
+ * Flush the telemetry queue (Node.js only)
1389
+ */
1199
1390
  flush() {
1200
- if (this._posthogClient) {
1391
+ if (this._posthogNodeClient) {
1201
1392
  try {
1202
- this._posthogClient.flush();
1393
+ this._posthogNodeClient.flush();
1203
1394
  logger.debug("PostHog client telemetry queue flushed");
1204
1395
  } catch (e) {
1205
1396
  logger.debug(`Failed to flush PostHog client: ${e}`);
1206
1397
  }
1207
1398
  }
1208
- if (this._scarfClient) {
1209
- logger.debug("Scarf telemetry events sent immediately (no flush needed)");
1210
- }
1211
1399
  }
1400
+ /**
1401
+ * Shutdown the telemetry client (Node.js only)
1402
+ */
1212
1403
  shutdown() {
1213
- if (this._posthogClient) {
1404
+ if (this._posthogNodeClient) {
1214
1405
  try {
1215
- this._posthogClient.shutdown();
1406
+ this._posthogNodeClient.shutdown();
1216
1407
  logger.debug("PostHog client shutdown successfully");
1217
1408
  } catch (e) {
1218
1409
  logger.debug(`Error shutting down PostHog client: ${e}`);
1219
1410
  }
1220
1411
  }
1221
- if (this._scarfClient) {
1222
- logger.debug("Scarf telemetry client shutdown (no action needed)");
1223
- }
1224
1412
  }
1225
1413
  };
1226
1414
  }
@@ -1230,7 +1418,6 @@ var init_telemetry = __esm({
1230
1418
  var init_telemetry2 = __esm({
1231
1419
  "src/telemetry/index.ts"() {
1232
1420
  "use strict";
1233
- init_telemetry();
1234
1421
  init_events();
1235
1422
  init_telemetry();
1236
1423
  init_utils();
@@ -2629,11 +2816,11 @@ function createHonoProxy(target, app) {
2629
2816
  if (prop === "use") {
2630
2817
  return async (...args) => {
2631
2818
  const hasPath = typeof args[0] === "string";
2632
- const path2 = hasPath ? args[0] : "*";
2819
+ const path = hasPath ? args[0] : "*";
2633
2820
  const handlers = hasPath ? args.slice(1) : args;
2634
2821
  const adaptedHandlers = handlers.map((handler) => {
2635
2822
  if (isExpressMiddleware(handler)) {
2636
- return { __isExpressMiddleware: true, handler, path: path2 };
2823
+ return { __isExpressMiddleware: true, handler, path };
2637
2824
  }
2638
2825
  return handler;
2639
2826
  });
@@ -2649,13 +2836,13 @@ function createHonoProxy(target, app) {
2649
2836
  h.path
2650
2837
  );
2651
2838
  if (hasPath) {
2652
- app.use(path2, adapted);
2839
+ app.use(path, adapted);
2653
2840
  } else {
2654
2841
  app.use(adapted);
2655
2842
  }
2656
2843
  } else {
2657
2844
  if (hasPath) {
2658
- app.use(path2, h);
2845
+ app.use(path, h);
2659
2846
  } else {
2660
2847
  app.use(h);
2661
2848
  }
@@ -3066,12 +3253,12 @@ __name(setupPublicRoutes, "setupPublicRoutes");
3066
3253
  // src/server/widgets/mount-widgets-dev.ts
3067
3254
  var TMP_MCP_USE_DIR = ".mcp-use";
3068
3255
  async function mountWidgetsDev(app, serverConfig, registerWidget, options) {
3069
- const { promises: fs2 } = await import("fs");
3256
+ const { promises: fs } = await import("fs");
3070
3257
  const baseRoute = options?.baseRoute || "/mcp-use/widgets";
3071
3258
  const resourcesDir = options?.resourcesDir || "resources";
3072
3259
  const srcDir = pathHelpers.join(getCwd(), resourcesDir);
3073
3260
  try {
3074
- await fs2.access(srcDir);
3261
+ await fs.access(srcDir);
3075
3262
  } catch (error2) {
3076
3263
  console.log(
3077
3264
  `[WIDGETS] No ${resourcesDir}/ directory found - skipping widget serving`
@@ -3080,7 +3267,7 @@ async function mountWidgetsDev(app, serverConfig, registerWidget, options) {
3080
3267
  }
3081
3268
  const entries = [];
3082
3269
  try {
3083
- const files = await fs2.readdir(srcDir, { withFileTypes: true });
3270
+ const files = await fs.readdir(srcDir, { withFileTypes: true });
3084
3271
  for (const dirent of files) {
3085
3272
  if (dirent.name.startsWith("._") || dirent.name.startsWith(".DS_Store")) {
3086
3273
  continue;
@@ -3093,7 +3280,7 @@ async function mountWidgetsDev(app, serverConfig, registerWidget, options) {
3093
3280
  } else if (dirent.isDirectory()) {
3094
3281
  const widgetPath = pathHelpers.join(srcDir, dirent.name, "widget.tsx");
3095
3282
  try {
3096
- await fs2.access(widgetPath);
3283
+ await fs.access(widgetPath);
3097
3284
  entries.push({
3098
3285
  name: dirent.name,
3099
3286
  path: widgetPath
@@ -3111,7 +3298,7 @@ async function mountWidgetsDev(app, serverConfig, registerWidget, options) {
3111
3298
  return;
3112
3299
  }
3113
3300
  const tempDir = pathHelpers.join(getCwd(), TMP_MCP_USE_DIR);
3114
- await fs2.mkdir(tempDir, { recursive: true }).catch(() => {
3301
+ await fs.mkdir(tempDir, { recursive: true }).catch(() => {
3115
3302
  });
3116
3303
  let createServer;
3117
3304
  let react;
@@ -3145,7 +3332,7 @@ async function mountWidgetsDev(app, serverConfig, registerWidget, options) {
3145
3332
  });
3146
3333
  for (const widget2 of widgets) {
3147
3334
  const widgetTempDir = pathHelpers.join(tempDir, widget2.name);
3148
- await fs2.mkdir(widgetTempDir, { recursive: true });
3335
+ await fs.mkdir(widgetTempDir, { recursive: true });
3149
3336
  const resourcesPath = pathHelpers.join(getCwd(), resourcesDir);
3150
3337
  const relativeResourcesPath = pathHelpers.relative(widgetTempDir, resourcesPath).replace(/\\/g, "/");
3151
3338
  const cssContent = `@import "tailwindcss";
@@ -3153,7 +3340,7 @@ async function mountWidgetsDev(app, serverConfig, registerWidget, options) {
3153
3340
  /* Configure Tailwind to scan the resources directory */
3154
3341
  @source "${relativeResourcesPath}";
3155
3342
  `;
3156
- await fs2.writeFile(
3343
+ await fs.writeFile(
3157
3344
  pathHelpers.join(widgetTempDir, "styles.css"),
3158
3345
  cssContent,
3159
3346
  "utf8"
@@ -3181,12 +3368,12 @@ if (container && Component) {
3181
3368
  <script type="module" src="${baseRoute}/${widget2.name}/entry.tsx"></script>
3182
3369
  </body>
3183
3370
  </html>`;
3184
- await fs2.writeFile(
3371
+ await fs.writeFile(
3185
3372
  pathHelpers.join(widgetTempDir, "entry.tsx"),
3186
3373
  entryContent,
3187
3374
  "utf8"
3188
3375
  );
3189
- await fs2.writeFile(
3376
+ await fs.writeFile(
3190
3377
  pathHelpers.join(widgetTempDir, "index.html"),
3191
3378
  htmlContent,
3192
3379
  "utf8"